]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-loop-distribution.c
altivec.md (UNSPEC_VMRGOW_DIRECT): New constant.
[thirdparty/gcc.git] / gcc / tree-loop-distribution.c
CommitLineData
dea61d92 1/* Loop distribution.
cbe34bb5 2 Copyright (C) 2006-2017 Free Software Foundation, Inc.
dea61d92
SP
3 Contributed by Georges-Andre Silber <Georges-Andre.Silber@ensmp.fr>
4 and Sebastian Pop <sebastian.pop@amd.com>.
5
6This file is part of GCC.
b8698a0f 7
dea61d92
SP
8GCC is free software; you can redistribute it and/or modify it
9under the terms of the GNU General Public License as published by the
10Free Software Foundation; either version 3, or (at your option) any
11later version.
b8698a0f 12
dea61d92
SP
13GCC is distributed in the hope that it will be useful, but WITHOUT
14ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16for more details.
b8698a0f 17
dea61d92
SP
18You should have received a copy of the GNU General Public License
19along with GCC; see the file COPYING3. If not see
20<http://www.gnu.org/licenses/>. */
21
22/* This pass performs loop distribution: for example, the loop
23
24 |DO I = 2, N
25 | A(I) = B(I) + C
26 | D(I) = A(I-1)*E
27 |ENDDO
28
b8698a0f 29 is transformed to
dea61d92
SP
30
31 |DOALL I = 2, N
32 | A(I) = B(I) + C
33 |ENDDO
34 |
35 |DOALL I = 2, N
36 | D(I) = A(I-1)*E
37 |ENDDO
38
a8745cc2
BC
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:
44
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.
84
85 TODO:
86 1) We only distribute innermost loops now. This pass should handle loop
87 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. */
dea61d92
SP
91
92#include "config.h"
93#include "system.h"
94#include "coretypes.h"
c7131fb2 95#include "backend.h"
40e23961 96#include "tree.h"
c7131fb2 97#include "gimple.h"
957060b5
AM
98#include "cfghooks.h"
99#include "tree-pass.h"
c7131fb2 100#include "ssa.h"
957060b5 101#include "gimple-pretty-print.h"
c7131fb2 102#include "fold-const.h"
60393bbc 103#include "cfganal.h"
5be5c238 104#include "gimple-iterator.h"
18f429e2 105#include "gimplify-me.h"
d8a2d370 106#include "stor-layout.h"
442b4905 107#include "tree-cfg.h"
e28030cf 108#include "tree-ssa-loop-manip.h"
442b4905
AM
109#include "tree-ssa-loop.h"
110#include "tree-into-ssa.h"
7a300452 111#include "tree-ssa.h"
dea61d92 112#include "cfgloop.h"
dea61d92 113#include "tree-scalar-evolution.h"
9fafb14a 114#include "params.h"
826a536d 115#include "tree-vectorizer.h"
80ab0b19
RB
116
117
9fafb14a
BC
118#define MAX_DATAREFS_NUM \
119 ((unsigned) PARAM_VALUE (PARAM_LOOP_MAX_DATAREFS_FOR_DATADEPS))
120
17c5cbdf
BC
121/* Hashtable helpers. */
122
123struct ddr_hasher : nofree_ptr_hash <struct data_dependence_relation>
124{
125 static inline hashval_t hash (const data_dependence_relation *);
126 static inline bool equal (const data_dependence_relation *,
127 const data_dependence_relation *);
128};
129
130/* Hash function for data dependence. */
131
132inline hashval_t
133ddr_hasher::hash (const data_dependence_relation *ddr)
134{
135 inchash::hash h;
136 h.add_ptr (DDR_A (ddr));
137 h.add_ptr (DDR_B (ddr));
138 return h.end ();
139}
140
141/* Hash table equality function for data dependence. */
142
143inline bool
144ddr_hasher::equal (const data_dependence_relation *ddr1,
145 const data_dependence_relation *ddr2)
146{
147 return (DDR_A (ddr1) == DDR_A (ddr2) && DDR_B (ddr1) == DDR_B (ddr2));
148}
149
4084ea5f
BC
150/* The loop (nest) to be distributed. */
151static vec<loop_p> loop_nest;
152
9fafb14a
BC
153/* Vector of data references in the loop to be distributed. */
154static vec<data_reference_p> datarefs_vec;
155
156/* Store index of data reference in aux field. */
157#define DR_INDEX(dr) ((uintptr_t) (dr)->aux)
158
17c5cbdf
BC
159/* Hash table for data dependence relation in the loop to be distributed. */
160static hash_table<ddr_hasher> ddrs_table (389);
161
162
80ab0b19 163/* A Reduced Dependence Graph (RDG) vertex representing a statement. */
526ceb68 164struct rdg_vertex
80ab0b19
RB
165{
166 /* The statement represented by this vertex. */
355fe088 167 gimple *stmt;
80ab0b19
RB
168
169 /* Vector of data-references in this statement. */
170 vec<data_reference_p> datarefs;
171
172 /* True when the statement contains a write to memory. */
173 bool has_mem_write;
174
175 /* True when the statement contains a read from memory. */
176 bool has_mem_reads;
526ceb68 177};
80ab0b19
RB
178
179#define RDGV_STMT(V) ((struct rdg_vertex *) ((V)->data))->stmt
180#define RDGV_DATAREFS(V) ((struct rdg_vertex *) ((V)->data))->datarefs
181#define RDGV_HAS_MEM_WRITE(V) ((struct rdg_vertex *) ((V)->data))->has_mem_write
182#define RDGV_HAS_MEM_READS(V) ((struct rdg_vertex *) ((V)->data))->has_mem_reads
183#define RDG_STMT(RDG, I) RDGV_STMT (&(RDG->vertices[I]))
184#define RDG_DATAREFS(RDG, I) RDGV_DATAREFS (&(RDG->vertices[I]))
185#define RDG_MEM_WRITE_STMT(RDG, I) RDGV_HAS_MEM_WRITE (&(RDG->vertices[I]))
186#define RDG_MEM_READS_STMT(RDG, I) RDGV_HAS_MEM_READS (&(RDG->vertices[I]))
187
188/* Data dependence type. */
189
190enum rdg_dep_type
191{
192 /* Read After Write (RAW). */
193 flow_dd = 'f',
194
36875e8f
RB
195 /* Control dependence (execute conditional on). */
196 control_dd = 'c'
80ab0b19
RB
197};
198
199/* Dependence information attached to an edge of the RDG. */
200
526ceb68 201struct rdg_edge
80ab0b19
RB
202{
203 /* Type of the dependence. */
204 enum rdg_dep_type type;
526ceb68 205};
80ab0b19
RB
206
207#define RDGE_TYPE(E) ((struct rdg_edge *) ((E)->data))->type
80ab0b19 208
80ab0b19
RB
209/* Dump vertex I in RDG to FILE. */
210
211static void
212dump_rdg_vertex (FILE *file, struct graph *rdg, int i)
213{
214 struct vertex *v = &(rdg->vertices[i]);
215 struct graph_edge *e;
216
217 fprintf (file, "(vertex %d: (%s%s) (in:", i,
218 RDG_MEM_WRITE_STMT (rdg, i) ? "w" : "",
219 RDG_MEM_READS_STMT (rdg, i) ? "r" : "");
220
221 if (v->pred)
222 for (e = v->pred; e; e = e->pred_next)
223 fprintf (file, " %d", e->src);
224
225 fprintf (file, ") (out:");
226
227 if (v->succ)
228 for (e = v->succ; e; e = e->succ_next)
229 fprintf (file, " %d", e->dest);
230
231 fprintf (file, ")\n");
232 print_gimple_stmt (file, RDGV_STMT (v), 0, TDF_VOPS|TDF_MEMSYMS);
233 fprintf (file, ")\n");
234}
235
236/* Call dump_rdg_vertex on stderr. */
237
238DEBUG_FUNCTION void
239debug_rdg_vertex (struct graph *rdg, int i)
240{
241 dump_rdg_vertex (stderr, rdg, i);
242}
243
80ab0b19
RB
244/* Dump the reduced dependence graph RDG to FILE. */
245
246static void
247dump_rdg (FILE *file, struct graph *rdg)
248{
80ab0b19 249 fprintf (file, "(rdg\n");
2fd5894f
RB
250 for (int i = 0; i < rdg->n_vertices; i++)
251 dump_rdg_vertex (file, rdg, i);
80ab0b19 252 fprintf (file, ")\n");
80ab0b19
RB
253}
254
255/* Call dump_rdg on stderr. */
256
257DEBUG_FUNCTION void
258debug_rdg (struct graph *rdg)
259{
260 dump_rdg (stderr, rdg);
261}
262
263static void
264dot_rdg_1 (FILE *file, struct graph *rdg)
265{
266 int i;
174ec470
RB
267 pretty_printer buffer;
268 pp_needs_newline (&buffer) = false;
269 buffer.buffer->stream = file;
80ab0b19
RB
270
271 fprintf (file, "digraph RDG {\n");
272
273 for (i = 0; i < rdg->n_vertices; i++)
274 {
275 struct vertex *v = &(rdg->vertices[i]);
276 struct graph_edge *e;
277
174ec470
RB
278 fprintf (file, "%d [label=\"[%d] ", i, i);
279 pp_gimple_stmt_1 (&buffer, RDGV_STMT (v), 0, TDF_SLIM);
280 pp_flush (&buffer);
281 fprintf (file, "\"]\n");
282
80ab0b19
RB
283 /* Highlight reads from memory. */
284 if (RDG_MEM_READS_STMT (rdg, i))
285 fprintf (file, "%d [style=filled, fillcolor=green]\n", i);
286
287 /* Highlight stores to memory. */
288 if (RDG_MEM_WRITE_STMT (rdg, i))
289 fprintf (file, "%d [style=filled, fillcolor=red]\n", i);
290
291 if (v->succ)
292 for (e = v->succ; e; e = e->succ_next)
293 switch (RDGE_TYPE (e))
294 {
80ab0b19
RB
295 case flow_dd:
296 /* These are the most common dependences: don't print these. */
297 fprintf (file, "%d -> %d \n", i, e->dest);
298 break;
299
36875e8f
RB
300 case control_dd:
301 fprintf (file, "%d -> %d [label=control] \n", i, e->dest);
302 break;
303
80ab0b19
RB
304 default:
305 gcc_unreachable ();
306 }
307 }
308
309 fprintf (file, "}\n\n");
310}
311
312/* Display the Reduced Dependence Graph using dotty. */
313
314DEBUG_FUNCTION void
315dot_rdg (struct graph *rdg)
316{
174ec470 317 /* When debugging, you may want to enable the following code. */
b6d94045 318#ifdef HAVE_POPEN
c3284718 319 FILE *file = popen ("dot -Tx11", "w");
174ec470
RB
320 if (!file)
321 return;
80ab0b19 322 dot_rdg_1 (file, rdg);
174ec470
RB
323 fflush (file);
324 close (fileno (file));
325 pclose (file);
80ab0b19
RB
326#else
327 dot_rdg_1 (stderr, rdg);
328#endif
329}
330
331/* Returns the index of STMT in RDG. */
332
333static int
355fe088 334rdg_vertex_for_stmt (struct graph *rdg ATTRIBUTE_UNUSED, gimple *stmt)
80ab0b19
RB
335{
336 int index = gimple_uid (stmt);
337 gcc_checking_assert (index == -1 || RDG_STMT (rdg, index) == stmt);
338 return index;
339}
340
80ab0b19
RB
341/* Creates dependence edges in RDG for all the uses of DEF. IDEF is
342 the index of DEF in RDG. */
343
344static void
345create_rdg_edges_for_scalar (struct graph *rdg, tree def, int idef)
346{
347 use_operand_p imm_use_p;
348 imm_use_iterator iterator;
349
350 FOR_EACH_IMM_USE_FAST (imm_use_p, iterator, def)
351 {
352 struct graph_edge *e;
353 int use = rdg_vertex_for_stmt (rdg, USE_STMT (imm_use_p));
354
355 if (use < 0)
356 continue;
357
358 e = add_edge (rdg, idef, use);
359 e->data = XNEW (struct rdg_edge);
360 RDGE_TYPE (e) = flow_dd;
80ab0b19
RB
361 }
362}
363
36875e8f
RB
364/* Creates an edge for the control dependences of BB to the vertex V. */
365
366static void
367create_edge_for_control_dependence (struct graph *rdg, basic_block bb,
368 int v, control_dependences *cd)
369{
370 bitmap_iterator bi;
371 unsigned edge_n;
372 EXECUTE_IF_SET_IN_BITMAP (cd->get_edges_dependent_on (bb->index),
373 0, edge_n, bi)
374 {
30fd2977 375 basic_block cond_bb = cd->get_edge_src (edge_n);
355fe088 376 gimple *stmt = last_stmt (cond_bb);
36875e8f
RB
377 if (stmt && is_ctrl_stmt (stmt))
378 {
379 struct graph_edge *e;
380 int c = rdg_vertex_for_stmt (rdg, stmt);
381 if (c < 0)
382 continue;
383
384 e = add_edge (rdg, c, v);
385 e->data = XNEW (struct rdg_edge);
386 RDGE_TYPE (e) = control_dd;
36875e8f
RB
387 }
388 }
389}
390
80ab0b19
RB
391/* Creates the edges of the reduced dependence graph RDG. */
392
393static void
447f3223 394create_rdg_flow_edges (struct graph *rdg)
80ab0b19
RB
395{
396 int i;
80ab0b19
RB
397 def_operand_p def_p;
398 ssa_op_iter iter;
399
80ab0b19
RB
400 for (i = 0; i < rdg->n_vertices; i++)
401 FOR_EACH_PHI_OR_STMT_DEF (def_p, RDG_STMT (rdg, i),
402 iter, SSA_OP_DEF)
403 create_rdg_edges_for_scalar (rdg, DEF_FROM_PTR (def_p), i);
447f3223 404}
36875e8f 405
447f3223
RB
406/* Creates the edges of the reduced dependence graph RDG. */
407
408static void
b71b7a8e 409create_rdg_cd_edges (struct graph *rdg, control_dependences *cd, loop_p loop)
447f3223
RB
410{
411 int i;
412
413 for (i = 0; i < rdg->n_vertices; i++)
414 {
355fe088 415 gimple *stmt = RDG_STMT (rdg, i);
447f3223
RB
416 if (gimple_code (stmt) == GIMPLE_PHI)
417 {
418 edge_iterator ei;
419 edge e;
420 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->preds)
b71b7a8e 421 if (flow_bb_inside_loop_p (loop, e->src))
36875e8f 422 create_edge_for_control_dependence (rdg, e->src, i, cd);
447f3223
RB
423 }
424 else
425 create_edge_for_control_dependence (rdg, gimple_bb (stmt), i, cd);
426 }
80ab0b19
RB
427}
428
429/* Build the vertices of the reduced dependence graph RDG. Return false
430 if that failed. */
431
432static bool
9fafb14a 433create_rdg_vertices (struct graph *rdg, vec<gimple *> stmts, loop_p loop)
80ab0b19
RB
434{
435 int i;
355fe088 436 gimple *stmt;
80ab0b19
RB
437
438 FOR_EACH_VEC_ELT (stmts, i, stmt)
439 {
440 struct vertex *v = &(rdg->vertices[i]);
441
442 /* Record statement to vertex mapping. */
443 gimple_set_uid (stmt, i);
444
445 v->data = XNEW (struct rdg_vertex);
446 RDGV_STMT (v) = stmt;
447 RDGV_DATAREFS (v).create (0);
448 RDGV_HAS_MEM_WRITE (v) = false;
449 RDGV_HAS_MEM_READS (v) = false;
450 if (gimple_code (stmt) == GIMPLE_PHI)
451 continue;
452
9fafb14a
BC
453 unsigned drp = datarefs_vec.length ();
454 if (!find_data_references_in_stmt (loop, stmt, &datarefs_vec))
80ab0b19 455 return false;
9fafb14a 456 for (unsigned j = drp; j < datarefs_vec.length (); ++j)
80ab0b19 457 {
9fafb14a 458 data_reference_p dr = datarefs_vec[j];
80ab0b19
RB
459 if (DR_IS_READ (dr))
460 RDGV_HAS_MEM_READS (v) = true;
461 else
462 RDGV_HAS_MEM_WRITE (v) = true;
463 RDGV_DATAREFS (v).safe_push (dr);
464 }
465 }
466 return true;
467}
468
3be57c56
BC
469/* Array mapping basic block's index to its topological order. */
470static int *bb_top_order_index;
471/* And size of the array. */
472static int bb_top_order_index_size;
473
474/* If X has a smaller topological sort number than Y, returns -1;
475 if greater, returns 1. */
476
477static int
478bb_top_order_cmp (const void *x, const void *y)
479{
480 basic_block bb1 = *(const basic_block *) x;
481 basic_block bb2 = *(const basic_block *) y;
482
483 gcc_assert (bb1->index < bb_top_order_index_size
484 && bb2->index < bb_top_order_index_size);
485 gcc_assert (bb1 == bb2
486 || bb_top_order_index[bb1->index]
487 != bb_top_order_index[bb2->index]);
488
489 return (bb_top_order_index[bb1->index] - bb_top_order_index[bb2->index]);
490}
491
492/* Initialize STMTS with all the statements of LOOP. We use topological
493 order to discover all statements. The order is important because
494 generate_loops_for_partition is using the same traversal for identifying
495 statements in loop copies. */
80ab0b19
RB
496
497static void
355fe088 498stmts_from_loop (struct loop *loop, vec<gimple *> *stmts)
80ab0b19
RB
499{
500 unsigned int i;
3be57c56 501 basic_block *bbs = get_loop_body_in_custom_order (loop, bb_top_order_cmp);
80ab0b19
RB
502
503 for (i = 0; i < loop->num_nodes; i++)
504 {
505 basic_block bb = bbs[i];
80ab0b19 506
538dd0b7
DM
507 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
508 gsi_next (&bsi))
509 if (!virtual_operand_p (gimple_phi_result (bsi.phi ())))
510 stmts->safe_push (bsi.phi ());
80ab0b19 511
538dd0b7
DM
512 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);
513 gsi_next (&bsi))
80ab0b19 514 {
355fe088 515 gimple *stmt = gsi_stmt (bsi);
80ab0b19
RB
516 if (gimple_code (stmt) != GIMPLE_LABEL && !is_gimple_debug (stmt))
517 stmts->safe_push (stmt);
518 }
519 }
520
521 free (bbs);
522}
523
80ab0b19
RB
524/* Free the reduced dependence graph RDG. */
525
526static void
527free_rdg (struct graph *rdg)
528{
529 int i;
530
531 for (i = 0; i < rdg->n_vertices; i++)
532 {
533 struct vertex *v = &(rdg->vertices[i]);
534 struct graph_edge *e;
535
536 for (e = v->succ; e; e = e->succ_next)
447f3223 537 free (e->data);
80ab0b19
RB
538
539 if (v->data)
540 {
541 gimple_set_uid (RDGV_STMT (v), -1);
9fafb14a 542 (RDGV_DATAREFS (v)).release ();
80ab0b19
RB
543 free (v->data);
544 }
545 }
546
547 free_graph (rdg);
548}
549
4084ea5f
BC
550/* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
551 LOOP, and one edge per flow dependence or control dependence from control
9fafb14a
BC
552 dependence CD. During visiting each statement, data references are also
553 collected and recorded in global data DATAREFS_VEC. */
80ab0b19
RB
554
555static struct graph *
4084ea5f 556build_rdg (struct loop *loop, control_dependences *cd)
80ab0b19
RB
557{
558 struct graph *rdg;
80ab0b19 559
97463b2b 560 /* Create the RDG vertices from the stmts of the loop nest. */
355fe088 561 auto_vec<gimple *, 10> stmts;
4084ea5f 562 stmts_from_loop (loop, &stmts);
24f161fd 563 rdg = new_graph (stmts.length ());
9fafb14a 564 if (!create_rdg_vertices (rdg, stmts, loop))
80ab0b19 565 {
80ab0b19
RB
566 free_rdg (rdg);
567 return NULL;
568 }
569 stmts.release ();
97463b2b 570
447f3223
RB
571 create_rdg_flow_edges (rdg);
572 if (cd)
4084ea5f 573 create_rdg_cd_edges (rdg, cd, loop);
447f3223 574
80ab0b19
RB
575 return rdg;
576}
577
80ab0b19 578
f1eb4621 579/* Kind of distributed loop. */
b9fc0497 580enum partition_kind {
510d73a0 581 PKIND_NORMAL, PKIND_MEMSET, PKIND_MEMCPY, PKIND_MEMMOVE
b9fc0497 582};
30d55936 583
f1eb4621
BC
584/* Type of distributed loop. */
585enum partition_type {
586 /* The distributed loop can be executed parallelly. */
587 PTYPE_PARALLEL = 0,
588 /* The distributed loop has to be executed sequentially. */
589 PTYPE_SEQUENTIAL
590};
591
a7a44c07 592/* Partition for loop distribution. */
526ceb68 593struct partition
c61f8985 594{
a7a44c07 595 /* Statements of the partition. */
c61f8985 596 bitmap stmts;
a7a44c07 597 /* Loops of the partition. */
80ab0b19 598 bitmap loops;
a7a44c07 599 /* True if the partition defines variable which is used outside of loop. */
826a536d 600 bool reduction_p;
a7a44c07
BC
601 /* For builtin partition, true if it executes one iteration more than
602 number of loop (latch) iterations. */
34e82342 603 bool plus_one;
30d55936 604 enum partition_kind kind;
f1eb4621 605 enum partition_type type;
d0582dc1
RG
606 /* data-references a kind != PKIND_NORMAL partition is about. */
607 data_reference_p main_dr;
608 data_reference_p secondary_dr;
a7a44c07 609 /* Number of loop (latch) iterations. */
818625cf 610 tree niter;
a7a44c07
BC
611 /* Data references in the partition. */
612 bitmap datarefs;
526ceb68 613};
c61f8985 614
c61f8985
RG
615
616/* Allocate and initialize a partition from BITMAP. */
617
526ceb68 618static partition *
a7a44c07 619partition_alloc (void)
c61f8985 620{
526ceb68 621 partition *partition = XCNEW (struct partition);
a7a44c07
BC
622 partition->stmts = BITMAP_ALLOC (NULL);
623 partition->loops = BITMAP_ALLOC (NULL);
826a536d 624 partition->reduction_p = false;
30d55936 625 partition->kind = PKIND_NORMAL;
a7a44c07 626 partition->datarefs = BITMAP_ALLOC (NULL);
c61f8985
RG
627 return partition;
628}
629
630/* Free PARTITION. */
631
632static void
526ceb68 633partition_free (partition *partition)
c61f8985
RG
634{
635 BITMAP_FREE (partition->stmts);
80ab0b19 636 BITMAP_FREE (partition->loops);
a7a44c07 637 BITMAP_FREE (partition->datarefs);
c61f8985
RG
638 free (partition);
639}
640
30d55936
RG
641/* Returns true if the partition can be generated as a builtin. */
642
643static bool
526ceb68 644partition_builtin_p (partition *partition)
30d55936 645{
826a536d 646 return partition->kind != PKIND_NORMAL;
30d55936 647}
c61f8985 648
826a536d 649/* Returns true if the partition contains a reduction. */
7ad672e4
RG
650
651static bool
526ceb68 652partition_reduction_p (partition *partition)
7ad672e4 653{
826a536d 654 return partition->reduction_p;
7ad672e4
RG
655}
656
821dbeef
BC
657/* Partitions are fused because of different reasons. */
658enum fuse_type
659{
660 FUSE_NON_BUILTIN = 0,
661 FUSE_REDUCTION = 1,
662 FUSE_SHARE_REF = 2,
663 FUSE_SAME_SCC = 3,
664 FUSE_FINALIZE = 4
665};
666
667/* Description on different fusing reason. */
668static const char *fuse_message[] = {
669 "they are non-builtins",
670 "they have reductions",
671 "they have shared memory refs",
672 "they are in the same dependence scc",
673 "there is no point to distribute loop"};
674
826a536d 675static void
f1eb4621 676update_type_for_merge (struct graph *, partition *, partition *);
821dbeef 677
f1eb4621
BC
678/* Merge PARTITION into the partition DEST. RDG is the reduced dependence
679 graph and we update type for result partition if it is non-NULL. */
a7a44c07 680
f1eb4621
BC
681static void
682partition_merge_into (struct graph *rdg, partition *dest,
683 partition *partition, enum fuse_type ft)
684{
821dbeef
BC
685 if (dump_file && (dump_flags & TDF_DETAILS))
686 {
687 fprintf (dump_file, "Fuse partitions because %s:\n", fuse_message[ft]);
688 fprintf (dump_file, " Part 1: ");
689 dump_bitmap (dump_file, dest->stmts);
690 fprintf (dump_file, " Part 2: ");
691 dump_bitmap (dump_file, partition->stmts);
692 }
f1eb4621
BC
693
694 dest->kind = PKIND_NORMAL;
695 if (dest->type == PTYPE_PARALLEL)
696 dest->type = partition->type;
697
698 bitmap_ior_into (dest->stmts, partition->stmts);
699 if (partition_reduction_p (partition))
700 dest->reduction_p = true;
701
702 /* Further check if any data dependence prevents us from executing the
703 new partition parallelly. */
704 if (dest->type == PTYPE_PARALLEL && rdg != NULL)
705 update_type_for_merge (rdg, dest, partition);
706
707 bitmap_ior_into (dest->datarefs, partition->datarefs);
826a536d
RB
708}
709
710
c07a8cb3
RG
711/* Returns true when DEF is an SSA_NAME defined in LOOP and used after
712 the LOOP. */
713
714static bool
715ssa_name_has_uses_outside_loop_p (tree def, loop_p loop)
716{
717 imm_use_iterator imm_iter;
718 use_operand_p use_p;
719
720 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
e665269a 721 {
355fe088 722 gimple *use_stmt = USE_STMT (use_p);
e665269a
RG
723 if (!is_gimple_debug (use_stmt)
724 && loop != loop_containing_stmt (use_stmt))
725 return true;
726 }
c07a8cb3
RG
727
728 return false;
729}
730
731/* Returns true when STMT defines a scalar variable used after the
88af7c1a 732 loop LOOP. */
c07a8cb3
RG
733
734static bool
355fe088 735stmt_has_scalar_dependences_outside_loop (loop_p loop, gimple *stmt)
c07a8cb3 736{
88af7c1a
RG
737 def_operand_p def_p;
738 ssa_op_iter op_iter;
c07a8cb3 739
9ca86fc3
RG
740 if (gimple_code (stmt) == GIMPLE_PHI)
741 return ssa_name_has_uses_outside_loop_p (gimple_phi_result (stmt), loop);
742
88af7c1a
RG
743 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, op_iter, SSA_OP_DEF)
744 if (ssa_name_has_uses_outside_loop_p (DEF_FROM_PTR (def_p), loop))
745 return true;
c07a8cb3 746
88af7c1a 747 return false;
c07a8cb3
RG
748}
749
dea61d92
SP
750/* Return a copy of LOOP placed before LOOP. */
751
752static struct loop *
753copy_loop_before (struct loop *loop)
754{
755 struct loop *res;
756 edge preheader = loop_preheader_edge (loop);
757
dea61d92 758 initialize_original_copy_tables ();
5ce9450f 759 res = slpeel_tree_duplicate_loop_to_edge_cfg (loop, NULL, preheader);
30d55936 760 gcc_assert (res != NULL);
dea61d92 761 free_original_copy_tables ();
2cfc56b9 762 delete_update_ssa ();
dea61d92
SP
763
764 return res;
765}
766
767/* Creates an empty basic block after LOOP. */
768
769static void
770create_bb_after_loop (struct loop *loop)
771{
772 edge exit = single_exit (loop);
773
774 if (!exit)
775 return;
776
777 split_edge (exit);
778}
779
780/* Generate code for PARTITION from the code in LOOP. The loop is
781 copied when COPY_P is true. All the statements not flagged in the
782 PARTITION bitmap are removed from the loop or from its copy. The
783 statements are indexed in sequence inside a basic block, and the
30d55936 784 basic blocks of a loop are taken in dom order. */
dea61d92 785
30d55936 786static void
526ceb68 787generate_loops_for_partition (struct loop *loop, partition *partition,
c61f8985 788 bool copy_p)
dea61d92 789{
2fd5894f 790 unsigned i;
dea61d92
SP
791 basic_block *bbs;
792
793 if (copy_p)
794 {
a8745cc2 795 int orig_loop_num = loop->orig_loop_num;
dea61d92 796 loop = copy_loop_before (loop);
30d55936 797 gcc_assert (loop != NULL);
a8745cc2 798 loop->orig_loop_num = orig_loop_num;
dea61d92
SP
799 create_preheader (loop, CP_SIMPLE_PREHEADERS);
800 create_bb_after_loop (loop);
801 }
a8745cc2
BC
802 else
803 {
804 /* Origin number is set to the new versioned loop's num. */
805 gcc_assert (loop->orig_loop_num != loop->num);
806 }
dea61d92 807
2fd5894f 808 /* Remove stmts not in the PARTITION bitmap. */
dea61d92
SP
809 bbs = get_loop_body_in_dom_order (loop);
810
b03c3082 811 if (MAY_HAVE_DEBUG_STMTS)
2fd5894f 812 for (i = 0; i < loop->num_nodes; i++)
b03c3082
JJ
813 {
814 basic_block bb = bbs[i];
815
538dd0b7
DM
816 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);
817 gsi_next (&bsi))
2fd5894f 818 {
538dd0b7 819 gphi *phi = bsi.phi ();
2fd5894f
RB
820 if (!virtual_operand_p (gimple_phi_result (phi))
821 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
822 reset_debug_uses (phi);
823 }
b03c3082 824
538dd0b7 825 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
b03c3082 826 {
355fe088 827 gimple *stmt = gsi_stmt (bsi);
b03c3082
JJ
828 if (gimple_code (stmt) != GIMPLE_LABEL
829 && !is_gimple_debug (stmt)
2fd5894f 830 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
b03c3082
JJ
831 reset_debug_uses (stmt);
832 }
833 }
834
2fd5894f 835 for (i = 0; i < loop->num_nodes; i++)
dea61d92
SP
836 {
837 basic_block bb = bbs[i];
dea61d92 838
538dd0b7 839 for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);)
2fd5894f 840 {
538dd0b7 841 gphi *phi = bsi.phi ();
2fd5894f
RB
842 if (!virtual_operand_p (gimple_phi_result (phi))
843 && !bitmap_bit_p (partition->stmts, gimple_uid (phi)))
2706a615 844 remove_phi_node (&bsi, true);
2fd5894f
RB
845 else
846 gsi_next (&bsi);
847 }
dea61d92 848
538dd0b7 849 for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi);)
2706a615 850 {
355fe088 851 gimple *stmt = gsi_stmt (bsi);
b03c3082
JJ
852 if (gimple_code (stmt) != GIMPLE_LABEL
853 && !is_gimple_debug (stmt)
2fd5894f 854 && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
2706a615 855 {
36875e8f
RB
856 /* Choose an arbitrary path through the empty CFG part
857 that this unnecessary control stmt controls. */
538dd0b7 858 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
36875e8f 859 {
538dd0b7 860 gimple_cond_make_false (cond_stmt);
36875e8f
RB
861 update_stmt (stmt);
862 }
863 else if (gimple_code (stmt) == GIMPLE_SWITCH)
864 {
538dd0b7 865 gswitch *switch_stmt = as_a <gswitch *> (stmt);
36875e8f 866 gimple_switch_set_index
538dd0b7 867 (switch_stmt, CASE_LOW (gimple_switch_label (switch_stmt, 1)));
36875e8f
RB
868 update_stmt (stmt);
869 }
870 else
871 {
872 unlink_stmt_vdef (stmt);
873 gsi_remove (&bsi, true);
874 release_defs (stmt);
875 continue;
876 }
2706a615 877 }
36875e8f 878 gsi_next (&bsi);
2706a615 879 }
dea61d92
SP
880 }
881
882 free (bbs);
dea61d92
SP
883}
884
d0582dc1 885/* Build the size argument for a memory operation call. */
3661e899 886
d0582dc1 887static tree
d995e887
RB
888build_size_arg_loc (location_t loc, data_reference_p dr, tree nb_iter,
889 bool plus_one)
3661e899 890{
d995e887
RB
891 tree size = fold_convert_loc (loc, sizetype, nb_iter);
892 if (plus_one)
893 size = size_binop (PLUS_EXPR, size, size_one_node);
894 size = fold_build2_loc (loc, MULT_EXPR, sizetype, size,
d0582dc1 895 TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr))));
d995e887
RB
896 size = fold_convert_loc (loc, size_type_node, size);
897 return size;
d0582dc1
RG
898}
899
900/* Build an address argument for a memory operation call. */
901
902static tree
903build_addr_arg_loc (location_t loc, data_reference_p dr, tree nb_bytes)
904{
905 tree addr_base;
906
907 addr_base = size_binop_loc (loc, PLUS_EXPR, DR_OFFSET (dr), DR_INIT (dr));
908 addr_base = fold_convert_loc (loc, sizetype, addr_base);
909
910 /* Test for a negative stride, iterating over every element. */
911 if (tree_int_cst_sgn (DR_STEP (dr)) == -1)
912 {
913 addr_base = size_binop_loc (loc, MINUS_EXPR, addr_base,
914 fold_convert_loc (loc, sizetype, nb_bytes));
915 addr_base = size_binop_loc (loc, PLUS_EXPR, addr_base,
916 TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr))));
917 }
918
919 return fold_build_pointer_plus_loc (loc, DR_BASE_ADDRESS (dr), addr_base);
3661e899
TB
920}
921
401f3a81
JJ
922/* If VAL memory representation contains the same value in all bytes,
923 return that value, otherwise return -1.
924 E.g. for 0x24242424 return 0x24, for IEEE double
925 747708026454360457216.0 return 0x44, etc. */
926
927static int
928const_with_all_bytes_same (tree val)
929{
930 unsigned char buf[64];
931 int i, len;
932
933 if (integer_zerop (val)
401f3a81
JJ
934 || (TREE_CODE (val) == CONSTRUCTOR
935 && !TREE_CLOBBER_P (val)
936 && CONSTRUCTOR_NELTS (val) == 0))
937 return 0;
938
9e207d6f
JJ
939 if (real_zerop (val))
940 {
941 /* Only return 0 for +0.0, not for -0.0, which doesn't have
942 an all bytes same memory representation. Don't transform
943 -0.0 stores into +0.0 even for !HONOR_SIGNED_ZEROS. */
944 switch (TREE_CODE (val))
945 {
946 case REAL_CST:
947 if (!real_isneg (TREE_REAL_CST_PTR (val)))
948 return 0;
949 break;
950 case COMPLEX_CST:
951 if (!const_with_all_bytes_same (TREE_REALPART (val))
952 && !const_with_all_bytes_same (TREE_IMAGPART (val)))
953 return 0;
954 break;
955 case VECTOR_CST:
956 unsigned int j;
957 for (j = 0; j < VECTOR_CST_NELTS (val); ++j)
66088065 958 if (const_with_all_bytes_same (VECTOR_CST_ELT (val, j)))
9e207d6f
JJ
959 break;
960 if (j == VECTOR_CST_NELTS (val))
961 return 0;
962 break;
963 default:
964 break;
965 }
966 }
967
401f3a81
JJ
968 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
969 return -1;
970
971 len = native_encode_expr (val, buf, sizeof (buf));
972 if (len == 0)
973 return -1;
974 for (i = 1; i < len; i++)
975 if (buf[i] != buf[0])
976 return -1;
977 return buf[0];
978}
979
30d55936 980/* Generate a call to memset for PARTITION in LOOP. */
dea61d92 981
cfee318d 982static void
526ceb68 983generate_memset_builtin (struct loop *loop, partition *partition)
dea61d92 984{
30d55936 985 gimple_stmt_iterator gsi;
355fe088 986 gimple *stmt, *fn_call;
818625cf 987 tree mem, fn, nb_bytes;
30d55936 988 location_t loc;
b6dd5261 989 tree val;
30d55936 990
d0582dc1 991 stmt = DR_STMT (partition->main_dr);
30d55936 992 loc = gimple_location (stmt);
30d55936
RG
993
994 /* The new statements will be placed before LOOP. */
995 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
dea61d92 996
d995e887
RB
997 nb_bytes = build_size_arg_loc (loc, partition->main_dr, partition->niter,
998 partition->plus_one);
d0582dc1
RG
999 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
1000 false, GSI_CONTINUE_LINKING);
1001 mem = build_addr_arg_loc (loc, partition->main_dr, nb_bytes);
1002 mem = force_gimple_operand_gsi (&gsi, mem, true, NULL_TREE,
1003 false, GSI_CONTINUE_LINKING);
dea61d92 1004
b6dd5261
RG
1005 /* This exactly matches the pattern recognition in classify_partition. */
1006 val = gimple_assign_rhs1 (stmt);
401f3a81
JJ
1007 /* Handle constants like 0x15151515 and similarly
1008 floating point constants etc. where all bytes are the same. */
1009 int bytev = const_with_all_bytes_same (val);
1010 if (bytev != -1)
1011 val = build_int_cst (integer_type_node, bytev);
1012 else if (TREE_CODE (val) == INTEGER_CST)
1013 val = fold_convert (integer_type_node, val);
1014 else if (!useless_type_conversion_p (integer_type_node, TREE_TYPE (val)))
b6dd5261 1015 {
b731b390 1016 tree tem = make_ssa_name (integer_type_node);
355fe088 1017 gimple *cstmt = gimple_build_assign (tem, NOP_EXPR, val);
401f3a81
JJ
1018 gsi_insert_after (&gsi, cstmt, GSI_CONTINUE_LINKING);
1019 val = tem;
b6dd5261
RG
1020 }
1021
e79983f4 1022 fn = build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_MEMSET));
b6dd5261 1023 fn_call = gimple_build_call (fn, 3, mem, val, nb_bytes);
d0582dc1 1024 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
dea61d92
SP
1025
1026 if (dump_file && (dump_flags & TDF_DETAILS))
b6dd5261
RG
1027 {
1028 fprintf (dump_file, "generated memset");
401f3a81 1029 if (bytev == 0)
b6dd5261 1030 fprintf (dump_file, " zero\n");
b6dd5261
RG
1031 else
1032 fprintf (dump_file, "\n");
1033 }
dea61d92
SP
1034}
1035
d0582dc1
RG
1036/* Generate a call to memcpy for PARTITION in LOOP. */
1037
1038static void
526ceb68 1039generate_memcpy_builtin (struct loop *loop, partition *partition)
d0582dc1
RG
1040{
1041 gimple_stmt_iterator gsi;
355fe088 1042 gimple *stmt, *fn_call;
818625cf 1043 tree dest, src, fn, nb_bytes;
d0582dc1
RG
1044 location_t loc;
1045 enum built_in_function kind;
1046
1047 stmt = DR_STMT (partition->main_dr);
1048 loc = gimple_location (stmt);
d0582dc1
RG
1049
1050 /* The new statements will be placed before LOOP. */
1051 gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
1052
d995e887
RB
1053 nb_bytes = build_size_arg_loc (loc, partition->main_dr, partition->niter,
1054 partition->plus_one);
d0582dc1
RG
1055 nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
1056 false, GSI_CONTINUE_LINKING);
1057 dest = build_addr_arg_loc (loc, partition->main_dr, nb_bytes);
1058 src = build_addr_arg_loc (loc, partition->secondary_dr, nb_bytes);
510d73a0
RB
1059 if (partition->kind == PKIND_MEMCPY
1060 || ! ptr_derefs_may_alias_p (dest, src))
d0582dc1 1061 kind = BUILT_IN_MEMCPY;
510d73a0
RB
1062 else
1063 kind = BUILT_IN_MEMMOVE;
d0582dc1
RG
1064
1065 dest = force_gimple_operand_gsi (&gsi, dest, true, NULL_TREE,
1066 false, GSI_CONTINUE_LINKING);
1067 src = force_gimple_operand_gsi (&gsi, src, true, NULL_TREE,
1068 false, GSI_CONTINUE_LINKING);
1069 fn = build_fold_addr_expr (builtin_decl_implicit (kind));
1070 fn_call = gimple_build_call (fn, 3, dest, src, nb_bytes);
1071 gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
1072
1073 if (dump_file && (dump_flags & TDF_DETAILS))
1074 {
1075 if (kind == BUILT_IN_MEMCPY)
1076 fprintf (dump_file, "generated memcpy\n");
1077 else
1078 fprintf (dump_file, "generated memmove\n");
1079 }
1080}
1081
30d55936 1082/* Remove and destroy the loop LOOP. */
dea61d92 1083
30d55936
RG
1084static void
1085destroy_loop (struct loop *loop)
dea61d92 1086{
30d55936
RG
1087 unsigned nbbs = loop->num_nodes;
1088 edge exit = single_exit (loop);
1089 basic_block src = loop_preheader_edge (loop)->src, dest = exit->dest;
dea61d92 1090 basic_block *bbs;
30d55936 1091 unsigned i;
dea61d92
SP
1092
1093 bbs = get_loop_body_in_dom_order (loop);
1094
30d55936
RG
1095 redirect_edge_pred (exit, src);
1096 exit->flags &= ~(EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
1097 exit->flags |= EDGE_FALLTHRU;
1098 cancel_loop_tree (loop);
1099 rescan_loop_exit (exit, false, true);
dea61d92 1100
b9aba0a0
RB
1101 i = nbbs;
1102 do
c014f6f5
RG
1103 {
1104 /* We have made sure to not leave any dangling uses of SSA
1105 names defined in the loop. With the exception of virtuals.
1106 Make sure we replace all uses of virtual defs that will remain
1107 outside of the loop with the bare symbol as delete_basic_block
1108 will release them. */
b9aba0a0 1109 --i;
538dd0b7
DM
1110 for (gphi_iterator gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi);
1111 gsi_next (&gsi))
c014f6f5 1112 {
538dd0b7 1113 gphi *phi = gsi.phi ();
ea057359 1114 if (virtual_operand_p (gimple_phi_result (phi)))
c014f6f5
RG
1115 mark_virtual_phi_result_for_renaming (phi);
1116 }
538dd0b7
DM
1117 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);
1118 gsi_next (&gsi))
c014f6f5 1119 {
355fe088 1120 gimple *stmt = gsi_stmt (gsi);
c014f6f5
RG
1121 tree vdef = gimple_vdef (stmt);
1122 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1123 mark_virtual_operand_for_renaming (vdef);
1124 }
1125 delete_basic_block (bbs[i]);
1126 }
b9aba0a0
RB
1127 while (i != 0);
1128
dea61d92 1129 free (bbs);
30d55936
RG
1130
1131 set_immediate_dominator (CDI_DOMINATORS, dest,
1132 recompute_dominator (CDI_DOMINATORS, dest));
dea61d92
SP
1133}
1134
b71b7a8e 1135/* Generates code for PARTITION. Return whether LOOP needs to be destroyed. */
dea61d92 1136
b71b7a8e 1137static bool
d0582dc1 1138generate_code_for_partition (struct loop *loop,
526ceb68 1139 partition *partition, bool copy_p)
dea61d92 1140{
30d55936
RG
1141 switch (partition->kind)
1142 {
826a536d
RB
1143 case PKIND_NORMAL:
1144 /* Reductions all have to be in the last partition. */
1145 gcc_assert (!partition_reduction_p (partition)
1146 || !copy_p);
1147 generate_loops_for_partition (loop, partition, copy_p);
b71b7a8e 1148 return false;
826a536d 1149
30d55936 1150 case PKIND_MEMSET:
d0582dc1 1151 generate_memset_builtin (loop, partition);
d0582dc1
RG
1152 break;
1153
1154 case PKIND_MEMCPY:
510d73a0 1155 case PKIND_MEMMOVE:
d0582dc1 1156 generate_memcpy_builtin (loop, partition);
30d55936
RG
1157 break;
1158
1159 default:
1160 gcc_unreachable ();
1161 }
dea61d92 1162
826a536d
RB
1163 /* Common tail for partitions we turn into a call. If this was the last
1164 partition for which we generate code, we have to destroy the loop. */
1165 if (!copy_p)
b71b7a8e
RB
1166 return true;
1167 return false;
dea61d92
SP
1168}
1169
17c5cbdf
BC
1170/* Return data dependence relation for data references A and B. The two
1171 data references must be in lexicographic order wrto reduced dependence
1172 graph RDG. We firstly try to find ddr from global ddr hash table. If
1173 it doesn't exist, compute the ddr and cache it. */
1174
1175static data_dependence_relation *
1176get_data_dependence (struct graph *rdg, data_reference_p a, data_reference_p b)
1177{
1178 struct data_dependence_relation ent, **slot;
1179 struct data_dependence_relation *ddr;
1180
1181 gcc_assert (DR_IS_WRITE (a) || DR_IS_WRITE (b));
1182 gcc_assert (rdg_vertex_for_stmt (rdg, DR_STMT (a))
1183 <= rdg_vertex_for_stmt (rdg, DR_STMT (b)));
1184 ent.a = a;
1185 ent.b = b;
1186 slot = ddrs_table.find_slot (&ent, INSERT);
1187 if (*slot == NULL)
1188 {
1189 ddr = initialize_data_dependence_relation (a, b, loop_nest);
1190 compute_affine_dependence (ddr, loop_nest[0]);
1191 *slot = ddr;
1192 }
1193
1194 return *slot;
1195}
dea61d92 1196
f1eb4621
BC
1197/* In reduced dependence graph RDG for loop distribution, return true if
1198 dependence between references DR1 and DR2 leads to a dependence cycle
1199 and such dependence cycle can't be resolved by runtime alias check. */
1200
1201static bool
1202data_dep_in_cycle_p (struct graph *rdg,
1203 data_reference_p dr1, data_reference_p dr2)
1204{
1205 struct data_dependence_relation *ddr;
1206
1207 /* Re-shuffle data-refs to be in topological order. */
1208 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1209 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1210 std::swap (dr1, dr2);
1211
1212 ddr = get_data_dependence (rdg, dr1, dr2);
1213
1214 /* In case of no data dependence. */
1215 if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
1216 return false;
1217 /* For unknown data dependence or known data dependence which can't be
1218 expressed in classic distance vector, we check if it can be resolved
1219 by runtime alias check. If yes, we still consider data dependence
1220 as won't introduce data dependence cycle. */
1221 else if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
1222 || DDR_NUM_DIST_VECTS (ddr) == 0)
1223 return !runtime_alias_check_p (ddr, NULL, true);
1224 else if (DDR_NUM_DIST_VECTS (ddr) > 1)
1225 return true;
1226 else if (DDR_REVERSED_P (ddr)
1227 || lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1228 return false;
1229
1230 return true;
1231}
1232
1233/* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
1234 PARTITION1's type after merging PARTITION2 into PARTITION1. */
1235
1236static void
1237update_type_for_merge (struct graph *rdg,
1238 partition *partition1, partition *partition2)
1239{
1240 unsigned i, j;
1241 bitmap_iterator bi, bj;
1242 data_reference_p dr1, dr2;
1243
1244 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1245 {
1246 unsigned start = (partition1 == partition2) ? i + 1 : 0;
1247
1248 dr1 = datarefs_vec[i];
1249 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, start, j, bj)
1250 {
1251 dr2 = datarefs_vec[j];
1252 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1253 continue;
1254
1255 /* Partition can only be executed sequentially if there is any
1256 data dependence cycle. */
1257 if (data_dep_in_cycle_p (rdg, dr1, dr2))
1258 {
1259 partition1->type = PTYPE_SEQUENTIAL;
1260 return;
1261 }
1262 }
1263 }
1264}
1265
24f161fd
RB
1266/* Returns a partition with all the statements needed for computing
1267 the vertex V of the RDG, also including the loop exit conditions. */
dea61d92 1268
526ceb68 1269static partition *
24f161fd 1270build_rdg_partition_for_vertex (struct graph *rdg, int v)
dea61d92 1271{
a7a44c07 1272 partition *partition = partition_alloc ();
00f96dc9 1273 auto_vec<int, 3> nodes;
a7a44c07 1274 unsigned i, j;
dea61d92 1275 int x;
a7a44c07 1276 data_reference_p dr;
dea61d92 1277
174ec470 1278 graphds_dfs (rdg, &v, 1, &nodes, false, NULL);
dea61d92 1279
9771b263 1280 FOR_EACH_VEC_ELT (nodes, i, x)
24f161fd
RB
1281 {
1282 bitmap_set_bit (partition->stmts, x);
1283 bitmap_set_bit (partition->loops,
1284 loop_containing_stmt (RDG_STMT (rdg, x))->num);
a7a44c07
BC
1285
1286 for (j = 0; RDG_DATAREFS (rdg, x).iterate (j, &dr); ++j)
1287 {
1288 unsigned idx = (unsigned) DR_INDEX (dr);
1289 gcc_assert (idx < datarefs_vec.length ());
1290
f1eb4621
BC
1291 /* Partition can only be executed sequentially if there is any
1292 unknown data reference. */
1293 if (!DR_BASE_ADDRESS (dr) || !DR_OFFSET (dr)
1294 || !DR_INIT (dr) || !DR_STEP (dr))
1295 partition->type = PTYPE_SEQUENTIAL;
1296
a7a44c07
BC
1297 bitmap_set_bit (partition->datarefs, idx);
1298 }
24f161fd 1299 }
dea61d92 1300
f1eb4621
BC
1301 if (partition->type == PTYPE_SEQUENTIAL)
1302 return partition;
1303
1304 /* Further check if any data dependence prevents us from executing the
1305 partition parallelly. */
1306 update_type_for_merge (rdg, partition, partition);
1307
dea61d92
SP
1308 return partition;
1309}
1310
30d55936 1311/* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
4a52eb19
BC
1312 For the moment we detect memset, memcpy and memmove patterns. Bitmap
1313 STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions. */
cfee318d 1314
30d55936 1315static void
4a52eb19
BC
1316classify_partition (loop_p loop, struct graph *rdg, partition *partition,
1317 bitmap stmt_in_all_partitions)
cfee318d 1318{
cfee318d 1319 bitmap_iterator bi;
30d55936
RG
1320 unsigned i;
1321 tree nb_iter;
d0582dc1 1322 data_reference_p single_load, single_store;
4a52eb19 1323 bool volatiles_p = false, plus_one = false, has_reduction = false;
30d55936
RG
1324
1325 partition->kind = PKIND_NORMAL;
d0582dc1
RG
1326 partition->main_dr = NULL;
1327 partition->secondary_dr = NULL;
818625cf 1328 partition->niter = NULL_TREE;
d995e887 1329 partition->plus_one = false;
30d55936 1330
c61f8985 1331 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
30d55936 1332 {
355fe088 1333 gimple *stmt = RDG_STMT (rdg, i);
30d55936
RG
1334
1335 if (gimple_has_volatile_ops (stmt))
b9fc0497 1336 volatiles_p = true;
cfee318d 1337
4a52eb19
BC
1338 /* If the stmt is not included by all partitions and there is uses
1339 outside of the loop, then mark the partition as reduction. */
9ca86fc3 1340 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
30d55936 1341 {
4a52eb19
BC
1342 /* Due to limitation in the transform phase we have to fuse all
1343 reduction partitions. As a result, this could cancel valid
1344 loop distribution especially for loop that induction variable
1345 is used outside of loop. To workaround this issue, we skip
1346 marking partition as reudction if the reduction stmt belongs
1347 to all partitions. In such case, reduction will be computed
1348 correctly no matter how partitions are fused/distributed. */
1349 if (!bitmap_bit_p (stmt_in_all_partitions, i))
1350 {
1351 partition->reduction_p = true;
1352 return;
1353 }
1354 has_reduction = true;
30d55936
RG
1355 }
1356 }
1357
b9fc0497
RB
1358 /* Perform general partition disqualification for builtins. */
1359 if (volatiles_p
4a52eb19
BC
1360 /* Simple workaround to prevent classifying the partition as builtin
1361 if it contains any use outside of loop. */
1362 || has_reduction
b9fc0497
RB
1363 || !flag_tree_loop_distribute_patterns)
1364 return;
1365
d0582dc1
RG
1366 /* Detect memset and memcpy. */
1367 single_load = NULL;
1368 single_store = NULL;
30d55936
RG
1369 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
1370 {
355fe088 1371 gimple *stmt = RDG_STMT (rdg, i);
d0582dc1
RG
1372 data_reference_p dr;
1373 unsigned j;
30d55936
RG
1374
1375 if (gimple_code (stmt) == GIMPLE_PHI)
1376 continue;
1377
1378 /* Any scalar stmts are ok. */
1379 if (!gimple_vuse (stmt))
1380 continue;
1381
d0582dc1
RG
1382 /* Otherwise just regular loads/stores. */
1383 if (!gimple_assign_single_p (stmt))
1384 return;
1385
1386 /* But exactly one store and/or load. */
9771b263 1387 for (j = 0; RDG_DATAREFS (rdg, i).iterate (j, &dr); ++j)
30d55936 1388 {
d002d099
JJ
1389 tree type = TREE_TYPE (DR_REF (dr));
1390
1391 /* The memset, memcpy and memmove library calls are only
1392 able to deal with generic address space. */
1393 if (!ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type)))
1394 return;
1395
d0582dc1
RG
1396 if (DR_IS_READ (dr))
1397 {
1398 if (single_load != NULL)
1399 return;
1400 single_load = dr;
1401 }
1402 else
1403 {
1404 if (single_store != NULL)
1405 return;
1406 single_store = dr;
1407 }
30d55936 1408 }
30d55936
RG
1409 }
1410
818625cf
RB
1411 if (!single_store)
1412 return;
1413
d995e887 1414 nb_iter = number_of_latch_executions (loop);
6ff37519 1415 gcc_assert (nb_iter && nb_iter != chrec_dont_know);
d995e887
RB
1416 if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
1417 gimple_bb (DR_STMT (single_store))))
1418 plus_one = true;
818625cf 1419
d0582dc1
RG
1420 if (single_store && !single_load)
1421 {
355fe088 1422 gimple *stmt = DR_STMT (single_store);
d0582dc1 1423 tree rhs = gimple_assign_rhs1 (stmt);
401f3a81
JJ
1424 if (const_with_all_bytes_same (rhs) == -1
1425 && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
1426 || (TYPE_MODE (TREE_TYPE (rhs))
1427 != TYPE_MODE (unsigned_char_type_node))))
d0582dc1
RG
1428 return;
1429 if (TREE_CODE (rhs) == SSA_NAME
1430 && !SSA_NAME_IS_DEFAULT_DEF (rhs)
1431 && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
1432 return;
ca406576
RB
1433 if (!adjacent_dr_p (single_store)
1434 || !dominated_by_p (CDI_DOMINATORS,
1435 loop->latch, gimple_bb (stmt)))
d0582dc1
RG
1436 return;
1437 partition->kind = PKIND_MEMSET;
1438 partition->main_dr = single_store;
818625cf 1439 partition->niter = nb_iter;
d995e887 1440 partition->plus_one = plus_one;
d0582dc1
RG
1441 }
1442 else if (single_store && single_load)
1443 {
355fe088
TS
1444 gimple *store = DR_STMT (single_store);
1445 gimple *load = DR_STMT (single_load);
d0582dc1
RG
1446 /* Direct aggregate copy or via an SSA name temporary. */
1447 if (load != store
1448 && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
1449 return;
1450 if (!adjacent_dr_p (single_store)
1451 || !adjacent_dr_p (single_load)
1452 || !operand_equal_p (DR_STEP (single_store),
ca406576
RB
1453 DR_STEP (single_load), 0)
1454 || !dominated_by_p (CDI_DOMINATORS,
1455 loop->latch, gimple_bb (store)))
d0582dc1 1456 return;
f20132e7
RG
1457 /* Now check that if there is a dependence this dependence is
1458 of a suitable form for memmove. */
17c5cbdf 1459 ddr_p ddr = get_data_dependence (rdg, single_load, single_store);
f20132e7 1460 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
17c5cbdf
BC
1461 return;
1462
f20132e7
RG
1463 if (DDR_ARE_DEPENDENT (ddr) != chrec_known)
1464 {
1465 if (DDR_NUM_DIST_VECTS (ddr) == 0)
17c5cbdf
BC
1466 return;
1467
f20132e7 1468 lambda_vector dist_v;
9771b263 1469 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
f20132e7
RG
1470 {
1471 int dist = dist_v[index_in_loop_nest (loop->num,
1472 DDR_LOOP_NEST (ddr))];
1473 if (dist > 0 && !DDR_REVERSED_P (ddr))
17c5cbdf 1474 return;
f20132e7 1475 }
510d73a0 1476 partition->kind = PKIND_MEMMOVE;
f20132e7 1477 }
510d73a0
RB
1478 else
1479 partition->kind = PKIND_MEMCPY;
d0582dc1
RG
1480 partition->main_dr = single_store;
1481 partition->secondary_dr = single_load;
818625cf 1482 partition->niter = nb_iter;
d995e887 1483 partition->plus_one = plus_one;
d0582dc1 1484 }
cfee318d
SP
1485}
1486
95f7d11b
BC
1487/* Returns true when PARTITION1 and PARTITION2 access the same memory
1488 object in RDG. */
cfee318d
SP
1489
1490static bool
95f7d11b
BC
1491share_memory_accesses (struct graph *rdg,
1492 partition *partition1, partition *partition2)
cfee318d 1493{
95f7d11b 1494 unsigned i, j;
cfee318d 1495 bitmap_iterator bi, bj;
95f7d11b 1496 data_reference_p dr1, dr2;
1fa0c180
RG
1497
1498 /* First check whether in the intersection of the two partitions are
1499 any loads or stores. Common loads are the situation that happens
1500 most often. */
1501 EXECUTE_IF_AND_IN_BITMAP (partition1->stmts, partition2->stmts, 0, i, bi)
1502 if (RDG_MEM_WRITE_STMT (rdg, i)
1503 || RDG_MEM_READS_STMT (rdg, i))
1504 return true;
cfee318d 1505
95f7d11b
BC
1506 /* Then check whether the two partitions access the same memory object. */
1507 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1508 {
1509 dr1 = datarefs_vec[i];
1510
1511 if (!DR_BASE_ADDRESS (dr1)
1512 || !DR_OFFSET (dr1) || !DR_INIT (dr1) || !DR_STEP (dr1))
1513 continue;
1514
1515 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, 0, j, bj)
1516 {
1517 dr2 = datarefs_vec[j];
1518
1519 if (!DR_BASE_ADDRESS (dr2)
1520 || !DR_OFFSET (dr2) || !DR_INIT (dr2) || !DR_STEP (dr2))
1521 continue;
1522
1523 if (operand_equal_p (DR_BASE_ADDRESS (dr1), DR_BASE_ADDRESS (dr2), 0)
1524 && operand_equal_p (DR_OFFSET (dr1), DR_OFFSET (dr2), 0)
1525 && operand_equal_p (DR_INIT (dr1), DR_INIT (dr2), 0)
1526 && operand_equal_p (DR_STEP (dr1), DR_STEP (dr2), 0))
1527 return true;
1528 }
1529 }
cfee318d
SP
1530
1531 return false;
1532}
1533
4a52eb19
BC
1534/* For each seed statement in STARTING_STMTS, this function builds
1535 partition for it by adding depended statements according to RDG.
1536 All partitions are recorded in PARTITIONS. */
dea61d92
SP
1537
1538static void
83a95546 1539rdg_build_partitions (struct graph *rdg,
355fe088 1540 vec<gimple *> starting_stmts,
526ceb68 1541 vec<partition *> *partitions)
dea61d92 1542{
0e3de1d4 1543 auto_bitmap processed;
2fd5894f 1544 int i;
355fe088 1545 gimple *stmt;
dea61d92 1546
2fd5894f 1547 FOR_EACH_VEC_ELT (starting_stmts, i, stmt)
dea61d92 1548 {
2fd5894f
RB
1549 int v = rdg_vertex_for_stmt (rdg, stmt);
1550
1551 if (dump_file && (dump_flags & TDF_DETAILS))
1552 fprintf (dump_file,
1553 "ldist asked to generate code for vertex %d\n", v);
b8698a0f 1554
24f161fd
RB
1555 /* If the vertex is already contained in another partition so
1556 is the partition rooted at it. */
dea61d92
SP
1557 if (bitmap_bit_p (processed, v))
1558 continue;
b8698a0f 1559
526ceb68 1560 partition *partition = build_rdg_partition_for_vertex (rdg, v);
24f161fd 1561 bitmap_ior_into (processed, partition->stmts);
dea61d92 1562
826a536d 1563 if (dump_file && (dump_flags & TDF_DETAILS))
dea61d92 1564 {
f1eb4621
BC
1565 fprintf (dump_file, "ldist creates useful %s partition:\n",
1566 partition->type == PTYPE_PARALLEL ? "parallel" : "sequent");
1567 bitmap_print (dump_file, partition->stmts, " ", "\n");
dea61d92 1568 }
826a536d
RB
1569
1570 partitions->safe_push (partition);
dea61d92
SP
1571 }
1572
83a95546
RB
1573 /* All vertices should have been assigned to at least one partition now,
1574 other than vertices belonging to dead code. */
dea61d92
SP
1575}
1576
1577/* Dump to FILE the PARTITIONS. */
1578
1579static void
526ceb68 1580dump_rdg_partitions (FILE *file, vec<partition *> partitions)
dea61d92
SP
1581{
1582 int i;
526ceb68 1583 partition *partition;
dea61d92 1584
9771b263 1585 FOR_EACH_VEC_ELT (partitions, i, partition)
c61f8985 1586 debug_bitmap_file (file, partition->stmts);
dea61d92
SP
1587}
1588
1589/* Debug PARTITIONS. */
526ceb68 1590extern void debug_rdg_partitions (vec<partition *> );
dea61d92 1591
24e47c76 1592DEBUG_FUNCTION void
526ceb68 1593debug_rdg_partitions (vec<partition *> partitions)
dea61d92
SP
1594{
1595 dump_rdg_partitions (stderr, partitions);
1596}
1597
2b8aee8e
SP
1598/* Returns the number of read and write operations in the RDG. */
1599
1600static int
1601number_of_rw_in_rdg (struct graph *rdg)
1602{
1603 int i, res = 0;
1604
1605 for (i = 0; i < rdg->n_vertices; i++)
1606 {
1607 if (RDG_MEM_WRITE_STMT (rdg, i))
1608 ++res;
1609
1610 if (RDG_MEM_READS_STMT (rdg, i))
1611 ++res;
1612 }
1613
1614 return res;
1615}
1616
1617/* Returns the number of read and write operations in a PARTITION of
1618 the RDG. */
1619
1620static int
526ceb68 1621number_of_rw_in_partition (struct graph *rdg, partition *partition)
2b8aee8e
SP
1622{
1623 int res = 0;
1624 unsigned i;
1625 bitmap_iterator ii;
1626
c61f8985 1627 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, ii)
2b8aee8e
SP
1628 {
1629 if (RDG_MEM_WRITE_STMT (rdg, i))
1630 ++res;
1631
1632 if (RDG_MEM_READS_STMT (rdg, i))
1633 ++res;
1634 }
1635
1636 return res;
1637}
1638
1639/* Returns true when one of the PARTITIONS contains all the read or
1640 write operations of RDG. */
1641
1642static bool
9771b263 1643partition_contains_all_rw (struct graph *rdg,
526ceb68 1644 vec<partition *> partitions)
2b8aee8e
SP
1645{
1646 int i;
526ceb68 1647 partition *partition;
2b8aee8e
SP
1648 int nrw = number_of_rw_in_rdg (rdg);
1649
9771b263 1650 FOR_EACH_VEC_ELT (partitions, i, partition)
2b8aee8e
SP
1651 if (nrw == number_of_rw_in_partition (rdg, partition))
1652 return true;
1653
1654 return false;
1655}
1656
447f3223 1657/* Compute partition dependence created by the data references in DRS1
a8745cc2
BC
1658 and DRS2, modify and return DIR according to that. IF ALIAS_DDR is
1659 not NULL, we record dependence introduced by possible alias between
1660 two data references in ALIAS_DDRS; otherwise, we simply ignore such
1661 dependence as if it doesn't exist at all. */
447f3223
RB
1662
1663static int
4084ea5f 1664pg_add_dependence_edges (struct graph *rdg, int dir,
a8745cc2 1665 bitmap drs1, bitmap drs2, vec<ddr_p> *alias_ddrs)
447f3223 1666{
a7a44c07
BC
1667 unsigned i, j;
1668 bitmap_iterator bi, bj;
1669 data_reference_p dr1, dr2, saved_dr1;
447f3223
RB
1670
1671 /* dependence direction - 0 is no dependence, -1 is back,
1672 1 is forth, 2 is both (we can stop then, merging will occur). */
a7a44c07
BC
1673 EXECUTE_IF_SET_IN_BITMAP (drs1, 0, i, bi)
1674 {
1675 dr1 = datarefs_vec[i];
1676
1677 EXECUTE_IF_SET_IN_BITMAP (drs2, 0, j, bj)
1678 {
a8745cc2
BC
1679 int res, this_dir = 1;
1680 ddr_p ddr;
1681
a7a44c07
BC
1682 dr2 = datarefs_vec[j];
1683
1684 /* Skip all <read, read> data dependence. */
1685 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1686 continue;
1687
1688 saved_dr1 = dr1;
a8745cc2 1689 /* Re-shuffle data-refs to be in topological order. */
a7a44c07
BC
1690 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1691 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1692 {
1693 std::swap (dr1, dr2);
1694 this_dir = -this_dir;
1695 }
17c5cbdf 1696 ddr = get_data_dependence (rdg, dr1, dr2);
a7a44c07 1697 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
a8745cc2
BC
1698 {
1699 this_dir = 0;
1700 res = data_ref_compare_tree (DR_BASE_ADDRESS (dr1),
1701 DR_BASE_ADDRESS (dr2));
1702 /* Be conservative. If data references are not well analyzed,
1703 or the two data references have the same base address and
1704 offset, add dependence and consider it alias to each other.
1705 In other words, the dependence can not be resolved by
1706 runtime alias check. */
1707 if (!DR_BASE_ADDRESS (dr1) || !DR_BASE_ADDRESS (dr2)
1708 || !DR_OFFSET (dr1) || !DR_OFFSET (dr2)
1709 || !DR_INIT (dr1) || !DR_INIT (dr2)
1710 || !DR_STEP (dr1) || !tree_fits_uhwi_p (DR_STEP (dr1))
1711 || !DR_STEP (dr2) || !tree_fits_uhwi_p (DR_STEP (dr2))
1712 || res == 0)
1713 this_dir = 2;
1714 /* Data dependence could be resolved by runtime alias check,
1715 record it in ALIAS_DDRS. */
1716 else if (alias_ddrs != NULL)
1717 alias_ddrs->safe_push (ddr);
1718 /* Or simply ignore it. */
1719 }
a7a44c07
BC
1720 else if (DDR_ARE_DEPENDENT (ddr) == NULL_TREE)
1721 {
1722 if (DDR_REVERSED_P (ddr))
a8745cc2
BC
1723 this_dir = -this_dir;
1724
a7a44c07
BC
1725 /* Known dependences can still be unordered througout the
1726 iteration space, see gcc.dg/tree-ssa/ldist-16.c. */
1727 if (DDR_NUM_DIST_VECTS (ddr) != 1)
1728 this_dir = 2;
1729 /* If the overlap is exact preserve stmt order. */
1730 else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1731 ;
a8745cc2
BC
1732 /* Else as the distance vector is lexicographic positive swap
1733 the dependence direction. */
a7a44c07 1734 else
a8745cc2 1735 this_dir = -this_dir;
a7a44c07
BC
1736 }
1737 else
1738 this_dir = 0;
a7a44c07
BC
1739 if (this_dir == 2)
1740 return 2;
1741 else if (dir == 0)
1742 dir = this_dir;
1743 else if (this_dir != 0 && dir != this_dir)
1744 return 2;
1745 /* Shuffle "back" dr1. */
1746 dr1 = saved_dr1;
1747 }
1748 }
447f3223
RB
1749 return dir;
1750}
1751
1752/* Compare postorder number of the partition graph vertices V1 and V2. */
1753
1754static int
1755pgcmp (const void *v1_, const void *v2_)
1756{
1757 const vertex *v1 = (const vertex *)v1_;
1758 const vertex *v2 = (const vertex *)v2_;
1759 return v2->post - v1->post;
1760}
2fd5894f 1761
a8745cc2
BC
1762/* Data attached to vertices of partition dependence graph. */
1763struct pg_vdata
1764{
1765 /* ID of the corresponding partition. */
1766 int id;
1767 /* The partition. */
1768 struct partition *partition;
1769};
1770
1771/* Data attached to edges of partition dependence graph. */
1772struct pg_edata
1773{
1774 /* If the dependence edge can be resolved by runtime alias check,
1775 this vector contains data dependence relations for runtime alias
1776 check. On the other hand, if the dependence edge is introduced
1777 because of compilation time known data dependence, this vector
1778 contains nothing. */
1779 vec<ddr_p> alias_ddrs;
1780};
1781
1782/* Callback data for traversing edges in graph. */
1783struct pg_edge_callback_data
1784{
1785 /* Bitmap contains strong connected components should be merged. */
1786 bitmap sccs_to_merge;
1787 /* Array constains component information for all vertices. */
1788 int *vertices_component;
1789 /* Vector to record all data dependence relations which are needed
1790 to break strong connected components by runtime alias checks. */
1791 vec<ddr_p> *alias_ddrs;
1792};
1793
1794/* Initialize vertice's data for partition dependence graph PG with
1795 PARTITIONS. */
1796
1797static void
1798init_partition_graph_vertices (struct graph *pg,
1799 vec<struct partition *> *partitions)
1800{
1801 int i;
1802 partition *partition;
1803 struct pg_vdata *data;
1804
1805 for (i = 0; partitions->iterate (i, &partition); ++i)
1806 {
1807 data = new pg_vdata;
1808 pg->vertices[i].data = data;
1809 data->id = i;
1810 data->partition = partition;
1811 }
1812}
1813
1814/* Add edge <I, J> to partition dependence graph PG. Attach vector of data
1815 dependence relations to the EDGE if DDRS isn't NULL. */
1816
1817static void
1818add_partition_graph_edge (struct graph *pg, int i, int j, vec<ddr_p> *ddrs)
1819{
1820 struct graph_edge *e = add_edge (pg, i, j);
1821
1822 /* If the edge is attached with data dependence relations, it means this
1823 dependence edge can be resolved by runtime alias checks. */
1824 if (ddrs != NULL)
1825 {
1826 struct pg_edata *data = new pg_edata;
1827
1828 gcc_assert (ddrs->length () > 0);
1829 e->data = data;
1830 data->alias_ddrs = vNULL;
1831 data->alias_ddrs.safe_splice (*ddrs);
1832 }
1833}
1834
1835/* Callback function for graph travesal algorithm. It returns true
1836 if edge E should skipped when traversing the graph. */
1837
1838static bool
1839pg_skip_alias_edge (struct graph_edge *e)
1840{
1841 struct pg_edata *data = (struct pg_edata *)e->data;
1842 return (data != NULL && data->alias_ddrs.length () > 0);
1843}
1844
1845/* Callback function freeing data attached to edge E of graph. */
1846
1847static void
1848free_partition_graph_edata_cb (struct graph *, struct graph_edge *e, void *)
1849{
1850 if (e->data != NULL)
1851 {
1852 struct pg_edata *data = (struct pg_edata *)e->data;
1853 data->alias_ddrs.release ();
1854 delete data;
1855 }
1856}
1857
1858/* Free data attached to vertice of partition dependence graph PG. */
1859
1860static void
1861free_partition_graph_vdata (struct graph *pg)
1862{
1863 int i;
1864 struct pg_vdata *data;
1865
1866 for (i = 0; i < pg->n_vertices; ++i)
1867 {
1868 data = (struct pg_vdata *)pg->vertices[i].data;
1869 delete data;
1870 }
1871}
1872
1873/* Build and return partition dependence graph for PARTITIONS. RDG is
1874 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
1875 is true, data dependence caused by possible alias between references
1876 is ignored, as if it doesn't exist at all; otherwise all depdendences
1877 are considered. */
1878
1879static struct graph *
1880build_partition_graph (struct graph *rdg,
1881 vec<struct partition *> *partitions,
1882 bool ignore_alias_p)
1883{
1884 int i, j;
1885 struct partition *partition1, *partition2;
1886 graph *pg = new_graph (partitions->length ());
1887 auto_vec<ddr_p> alias_ddrs, *alias_ddrs_p;
1888
1889 alias_ddrs_p = ignore_alias_p ? NULL : &alias_ddrs;
1890
1891 init_partition_graph_vertices (pg, partitions);
1892
1893 for (i = 0; partitions->iterate (i, &partition1); ++i)
1894 {
1895 for (j = i + 1; partitions->iterate (j, &partition2); ++j)
1896 {
1897 /* dependence direction - 0 is no dependence, -1 is back,
1898 1 is forth, 2 is both (we can stop then, merging will occur). */
1899 int dir = 0;
1900
1901 /* If the first partition has reduction, add back edge; if the
1902 second partition has reduction, add forth edge. This makes
1903 sure that reduction partition will be sorted as the last one. */
1904 if (partition_reduction_p (partition1))
1905 dir = -1;
1906 else if (partition_reduction_p (partition2))
1907 dir = 1;
1908
1909 /* Cleanup the temporary vector. */
1910 alias_ddrs.truncate (0);
1911
1912 dir = pg_add_dependence_edges (rdg, dir, partition1->datarefs,
1913 partition2->datarefs, alias_ddrs_p);
1914
1915 /* Add edge to partition graph if there exists dependence. There
1916 are two types of edges. One type edge is caused by compilation
1917 time known dependence, this type can not be resolved by runtime
1918 alias check. The other type can be resolved by runtime alias
1919 check. */
1920 if (dir == 1 || dir == 2
1921 || alias_ddrs.length () > 0)
1922 {
1923 /* Attach data dependence relations to edge that can be resolved
1924 by runtime alias check. */
1925 bool alias_edge_p = (dir != 1 && dir != 2);
1926 add_partition_graph_edge (pg, i, j,
1927 (alias_edge_p) ? &alias_ddrs : NULL);
1928 }
1929 if (dir == -1 || dir == 2
1930 || alias_ddrs.length () > 0)
1931 {
1932 /* Attach data dependence relations to edge that can be resolved
1933 by runtime alias check. */
1934 bool alias_edge_p = (dir != -1 && dir != 2);
1935 add_partition_graph_edge (pg, j, i,
1936 (alias_edge_p) ? &alias_ddrs : NULL);
1937 }
1938 }
1939 }
1940 return pg;
1941}
1942
1943/* Sort partitions in PG by post order and store them in PARTITIONS. */
1944
1945static void
1946sort_partitions_by_post_order (struct graph *pg,
1947 vec<struct partition *> *partitions)
1948{
1949 int i;
1950 struct pg_vdata *data;
1951
1952 /* Now order the remaining nodes in postorder. */
1953 qsort (pg->vertices, pg->n_vertices, sizeof (vertex), pgcmp);
1954 partitions->truncate (0);
1955 for (i = 0; i < pg->n_vertices; ++i)
1956 {
1957 data = (struct pg_vdata *)pg->vertices[i].data;
1958 if (data->partition)
1959 partitions->safe_push (data->partition);
1960 }
1961}
1962
1963/* Given reduced dependence graph RDG merge strong connected components
6ff37519
BC
1964 of PARTITIONS. In this function, data dependence caused by possible
1965 alias between references is ignored, as if it doesn't exist at all. */
a8745cc2
BC
1966
1967static void
1968merge_dep_scc_partitions (struct graph *rdg,
6ff37519 1969 vec<struct partition *> *partitions)
a8745cc2
BC
1970{
1971 struct partition *partition1, *partition2;
1972 struct pg_vdata *data;
6ff37519 1973 graph *pg = build_partition_graph (rdg, partitions, true);
a8745cc2
BC
1974 int i, j, num_sccs = graphds_scc (pg, NULL);
1975
1976 /* Strong connected compoenent means dependence cycle, we cannot distribute
1977 them. So fuse them together. */
1978 if ((unsigned) num_sccs < partitions->length ())
1979 {
1980 for (i = 0; i < num_sccs; ++i)
1981 {
1982 for (j = 0; partitions->iterate (j, &partition1); ++j)
1983 if (pg->vertices[j].component == i)
1984 break;
1985 for (j = j + 1; partitions->iterate (j, &partition2); ++j)
1986 if (pg->vertices[j].component == i)
1987 {
1988 partition_merge_into (NULL, partition1,
1989 partition2, FUSE_SAME_SCC);
1990 partition1->type = PTYPE_SEQUENTIAL;
1991 (*partitions)[j] = NULL;
1992 partition_free (partition2);
1993 data = (struct pg_vdata *)pg->vertices[j].data;
1994 data->partition = NULL;
1995 }
1996 }
a8745cc2 1997 }
aa1528b5
BC
1998
1999 sort_partitions_by_post_order (pg, partitions);
a8745cc2
BC
2000 gcc_assert (partitions->length () == (unsigned)num_sccs);
2001 free_partition_graph_vdata (pg);
2002 free_graph (pg);
2003}
2004
2005/* Callback function for traversing edge E in graph G. DATA is private
2006 callback data. */
2007
2008static void
2009pg_collect_alias_ddrs (struct graph *g, struct graph_edge *e, void *data)
2010{
2011 int i, j, component;
2012 struct pg_edge_callback_data *cbdata;
2013 struct pg_edata *edata = (struct pg_edata *) e->data;
2014
2015 /* If the edge doesn't have attached data dependence, it represents
2016 compilation time known dependences. This type dependence cannot
2017 be resolved by runtime alias check. */
2018 if (edata == NULL || edata->alias_ddrs.length () == 0)
2019 return;
2020
2021 cbdata = (struct pg_edge_callback_data *) data;
2022 i = e->src;
2023 j = e->dest;
2024 component = cbdata->vertices_component[i];
2025 /* Vertices are topologically sorted according to compilation time
2026 known dependences, so we can break strong connected components
2027 by removing edges of the opposite direction, i.e, edges pointing
2028 from vertice with smaller post number to vertice with bigger post
2029 number. */
2030 if (g->vertices[i].post < g->vertices[j].post
2031 /* We only need to remove edges connecting vertices in the same
2032 strong connected component to break it. */
2033 && component == cbdata->vertices_component[j]
2034 /* Check if we want to break the strong connected component or not. */
2035 && !bitmap_bit_p (cbdata->sccs_to_merge, component))
2036 cbdata->alias_ddrs->safe_splice (edata->alias_ddrs);
2037}
2038
2039/* This is the main function breaking strong conected components in
2040 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
2041 relations for runtime alias check in ALIAS_DDRS. */
2042
2043static void
2044break_alias_scc_partitions (struct graph *rdg,
2045 vec<struct partition *> *partitions,
2046 vec<ddr_p> *alias_ddrs)
2047{
2048 int i, j, num_sccs, num_sccs_no_alias;
2049 /* Build partition dependence graph. */
2050 graph *pg = build_partition_graph (rdg, partitions, false);
2051
2052 alias_ddrs->truncate (0);
2053 /* Find strong connected components in the graph, with all dependence edges
2054 considered. */
2055 num_sccs = graphds_scc (pg, NULL);
2056 /* All SCCs now can be broken by runtime alias checks because SCCs caused by
2057 compilation time known dependences are merged before this function. */
2058 if ((unsigned) num_sccs < partitions->length ())
2059 {
2060 struct pg_edge_callback_data cbdata;
2061 auto_bitmap sccs_to_merge;
2062 auto_vec<enum partition_type> scc_types;
2063 struct partition *partition, *first;
2064
2065 /* If all paritions in a SCC has the same type, we can simply merge the
2066 SCC. This loop finds out such SCCS and record them in bitmap. */
2067 bitmap_set_range (sccs_to_merge, 0, (unsigned) num_sccs);
2068 for (i = 0; i < num_sccs; ++i)
2069 {
2070 for (j = 0; partitions->iterate (j, &first); ++j)
2071 if (pg->vertices[j].component == i)
2072 break;
2073 for (++j; partitions->iterate (j, &partition); ++j)
2074 {
2075 if (pg->vertices[j].component != i)
2076 continue;
2077
2078 if (first->type != partition->type)
2079 {
2080 bitmap_clear_bit (sccs_to_merge, i);
2081 break;
2082 }
2083 }
2084 }
2085
2086 /* Initialize callback data for traversing. */
2087 cbdata.sccs_to_merge = sccs_to_merge;
2088 cbdata.alias_ddrs = alias_ddrs;
2089 cbdata.vertices_component = XNEWVEC (int, pg->n_vertices);
2090 /* Record the component information which will be corrupted by next
2091 graph scc finding call. */
2092 for (i = 0; i < pg->n_vertices; ++i)
2093 cbdata.vertices_component[i] = pg->vertices[i].component;
2094
2095 /* Collect data dependences for runtime alias checks to break SCCs. */
2096 if (bitmap_count_bits (sccs_to_merge) != (unsigned) num_sccs)
2097 {
2098 /* Run SCC finding algorithm again, with alias dependence edges
2099 skipped. This is to topologically sort paritions according to
2100 compilation time known dependence. Note the topological order
2101 is stored in the form of pg's post order number. */
2102 num_sccs_no_alias = graphds_scc (pg, NULL, pg_skip_alias_edge);
2103 gcc_assert (partitions->length () == (unsigned) num_sccs_no_alias);
2104 /* With topological order, we can construct two subgraphs L and R.
2105 L contains edge <x, y> where x < y in terms of post order, while
2106 R contains edge <x, y> where x > y. Edges for compilation time
2107 known dependence all fall in R, so we break SCCs by removing all
2108 (alias) edges of in subgraph L. */
2109 for_each_edge (pg, pg_collect_alias_ddrs, &cbdata);
2110 }
2111
2112 /* For SCC that doesn't need to be broken, merge it. */
2113 for (i = 0; i < num_sccs; ++i)
2114 {
2115 if (!bitmap_bit_p (sccs_to_merge, i))
2116 continue;
2117
2118 for (j = 0; partitions->iterate (j, &first); ++j)
2119 if (cbdata.vertices_component[j] == i)
2120 break;
2121 for (++j; partitions->iterate (j, &partition); ++j)
2122 {
2123 struct pg_vdata *data;
2124
2125 if (cbdata.vertices_component[j] != i)
2126 continue;
2127
2128 partition_merge_into (NULL, first, partition, FUSE_SAME_SCC);
2129 (*partitions)[j] = NULL;
2130 partition_free (partition);
2131 data = (struct pg_vdata *)pg->vertices[j].data;
2132 gcc_assert (data->id == j);
2133 data->partition = NULL;
2134 }
2135 }
2136 }
2137
2138 sort_partitions_by_post_order (pg, partitions);
2139 free_partition_graph_vdata (pg);
2140 for_each_edge (pg, free_partition_graph_edata_cb, NULL);
2141 free_graph (pg);
2142
2143 if (dump_file && (dump_flags & TDF_DETAILS))
2144 {
2145 fprintf (dump_file, "Possible alias data dependence to break:\n");
2146 dump_data_dependence_relations (dump_file, *alias_ddrs);
2147 }
2148}
2149
2150/* Compute and return an expression whose value is the segment length which
2151 will be accessed by DR in NITERS iterations. */
2152
2153static tree
2154data_ref_segment_size (struct data_reference *dr, tree niters)
2155{
2156 tree segment_length;
2157
2158 if (integer_zerop (DR_STEP (dr)))
2159 segment_length = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
2160 else
2161 segment_length = size_binop (MULT_EXPR,
2162 fold_convert (sizetype, DR_STEP (dr)),
2163 fold_convert (sizetype, niters));
2164
2165 return segment_length;
2166}
2167
2168/* Return true if LOOP's latch is dominated by statement for data reference
2169 DR. */
2170
2171static inline bool
2172latch_dominated_by_data_ref (struct loop *loop, data_reference *dr)
2173{
2174 return dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
2175 gimple_bb (DR_STMT (dr)));
2176}
2177
2178/* Compute alias check pairs and store them in COMP_ALIAS_PAIRS for LOOP's
2179 data dependence relations ALIAS_DDRS. */
2180
2181static void
2182compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
2183 vec<dr_with_seg_len_pair_t> *comp_alias_pairs)
2184{
2185 unsigned int i;
2186 unsigned HOST_WIDE_INT factor = 1;
2187 tree niters_plus_one, niters = number_of_latch_executions (loop);
2188
2189 gcc_assert (niters != NULL_TREE && niters != chrec_dont_know);
2190 niters = fold_convert (sizetype, niters);
2191 niters_plus_one = size_binop (PLUS_EXPR, niters, size_one_node);
2192
2193 if (dump_file && (dump_flags & TDF_DETAILS))
2194 fprintf (dump_file, "Creating alias check pairs:\n");
2195
2196 /* Iterate all data dependence relations and compute alias check pairs. */
2197 for (i = 0; i < alias_ddrs->length (); i++)
2198 {
2199 ddr_p ddr = (*alias_ddrs)[i];
2200 struct data_reference *dr_a = DDR_A (ddr);
2201 struct data_reference *dr_b = DDR_B (ddr);
2202 tree seg_length_a, seg_length_b;
2203 int comp_res = data_ref_compare_tree (DR_BASE_ADDRESS (dr_a),
2204 DR_BASE_ADDRESS (dr_b));
2205
2206 if (comp_res == 0)
2207 comp_res = data_ref_compare_tree (DR_OFFSET (dr_a), DR_OFFSET (dr_b));
2208 gcc_assert (comp_res != 0);
2209
2210 if (latch_dominated_by_data_ref (loop, dr_a))
2211 seg_length_a = data_ref_segment_size (dr_a, niters_plus_one);
2212 else
2213 seg_length_a = data_ref_segment_size (dr_a, niters);
2214
2215 if (latch_dominated_by_data_ref (loop, dr_b))
2216 seg_length_b = data_ref_segment_size (dr_b, niters_plus_one);
2217 else
2218 seg_length_b = data_ref_segment_size (dr_b, niters);
2219
2220 dr_with_seg_len_pair_t dr_with_seg_len_pair
2221 (dr_with_seg_len (dr_a, seg_length_a),
2222 dr_with_seg_len (dr_b, seg_length_b));
2223
2224 /* Canonicalize pairs by sorting the two DR members. */
2225 if (comp_res > 0)
2226 std::swap (dr_with_seg_len_pair.first, dr_with_seg_len_pair.second);
2227
2228 comp_alias_pairs->safe_push (dr_with_seg_len_pair);
2229 }
2230
2231 if (tree_fits_uhwi_p (niters))
2232 factor = tree_to_uhwi (niters);
2233
2234 /* Prune alias check pairs. */
2235 prune_runtime_alias_test_list (comp_alias_pairs, factor);
2236 if (dump_file && (dump_flags & TDF_DETAILS))
2237 fprintf (dump_file,
2238 "Improved number of alias checks from %d to %d\n",
2239 alias_ddrs->length (), comp_alias_pairs->length ());
2240}
2241
2242/* Given data dependence relations in ALIAS_DDRS, generate runtime alias
2243 checks and version LOOP under condition of these runtime alias checks. */
2244
2245static void
2246version_loop_by_alias_check (struct loop *loop, vec<ddr_p> *alias_ddrs)
2247{
2248 profile_probability prob;
2249 basic_block cond_bb;
2250 struct loop *nloop;
2251 tree lhs, arg0, cond_expr = NULL_TREE;
2252 gimple_seq cond_stmts = NULL;
2253 gimple *call_stmt = NULL;
2254 auto_vec<dr_with_seg_len_pair_t> comp_alias_pairs;
2255
2256 /* Generate code for runtime alias checks if necessary. */
2257 gcc_assert (alias_ddrs->length () > 0);
2258
2259 if (dump_file && (dump_flags & TDF_DETAILS))
2260 fprintf (dump_file,
2261 "Version loop <%d> with runtime alias check\n", loop->num);
2262
2263 compute_alias_check_pairs (loop, alias_ddrs, &comp_alias_pairs);
2264 create_runtime_alias_checks (loop, &comp_alias_pairs, &cond_expr);
2265 cond_expr = force_gimple_operand_1 (cond_expr, &cond_stmts,
8d2d0de9 2266 is_gimple_val, NULL_TREE);
a8745cc2
BC
2267
2268 /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS. */
2269 if (flag_tree_loop_vectorize)
2270 {
2271 /* Generate internal function call for loop distribution alias check. */
2272 call_stmt = gimple_build_call_internal (IFN_LOOP_DIST_ALIAS,
2273 2, NULL_TREE, cond_expr);
2274 lhs = make_ssa_name (boolean_type_node);
2275 gimple_call_set_lhs (call_stmt, lhs);
2276 }
2277 else
2278 lhs = cond_expr;
2279
2280 prob = profile_probability::guessed_always ().apply_scale (9, 10);
2281 initialize_original_copy_tables ();
2282 nloop = loop_version (loop, lhs, &cond_bb, prob, prob.invert (),
2283 prob, prob.invert (), true);
2284 free_original_copy_tables ();
2285 /* Record the original loop number in newly generated loops. In case of
2286 distribution, the original loop will be distributed and the new loop
2287 is kept. */
2288 loop->orig_loop_num = nloop->num;
2289 nloop->orig_loop_num = nloop->num;
2290 nloop->dont_vectorize = true;
2291 nloop->force_vectorize = false;
2292
2293 if (call_stmt)
2294 {
2295 /* Record new loop's num in IFN_LOOP_DIST_ALIAS because the original
2296 loop could be destroyed. */
2297 arg0 = build_int_cst (integer_type_node, loop->orig_loop_num);
2298 gimple_call_set_arg (call_stmt, 0, arg0);
2299 gimple_seq_add_stmt_without_update (&cond_stmts, call_stmt);
2300 }
2301
2302 if (cond_stmts)
2303 {
2304 gimple_stmt_iterator cond_gsi = gsi_last_bb (cond_bb);
2305 gsi_insert_seq_before (&cond_gsi, cond_stmts, GSI_SAME_STMT);
2306 }
2307 update_ssa (TODO_update_ssa);
2308}
2309
2310/* Return true if loop versioning is needed to distrubute PARTITIONS.
2311 ALIAS_DDRS are data dependence relations for runtime alias check. */
2312
2313static inline bool
2314version_for_distribution_p (vec<struct partition *> *partitions,
2315 vec<ddr_p> *alias_ddrs)
2316{
2317 /* No need to version loop if we have only one partition. */
2318 if (partitions->length () == 1)
2319 return false;
2320
2321 /* Need to version loop if runtime alias check is necessary. */
2322 return (alias_ddrs->length () > 0);
2323}
2324
2325/* Fuse all partitions if necessary before finalizing distribution. */
2326
2327static void
2328finalize_partitions (vec<struct partition *> *partitions,
2329 vec<ddr_p> *alias_ddrs)
2330{
2331 unsigned i;
2332 struct partition *a, *partition;
2333
2334 if (partitions->length () == 1
2335 || alias_ddrs->length () > 0)
2336 return;
2337
2338 a = (*partitions)[0];
2339 if (a->kind != PKIND_NORMAL)
2340 return;
2341
2342 for (i = 1; partitions->iterate (i, &partition); ++i)
2343 {
2344 /* Don't fuse if partition has different type or it is a builtin. */
2345 if (partition->type != a->type
2346 || partition->kind != PKIND_NORMAL)
2347 return;
2348 }
2349
2350 /* Fuse all partitions. */
2351 for (i = 1; partitions->iterate (i, &partition); ++i)
2352 {
2353 partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
2354 partition_free (partition);
2355 }
2356 partitions->truncate (1);
2357}
2358
2359/* Distributes the code from LOOP in such a way that producer statements
2360 are placed before consumer statements. Tries to separate only the
2361 statements from STMTS into separate loops. Returns the number of
2362 distributed loops. Set NB_CALLS to number of generated builtin calls.
2363 Set *DESTROY_P to whether LOOP needs to be destroyed. */
dea61d92
SP
2364
2365static int
355fe088 2366distribute_loop (struct loop *loop, vec<gimple *> stmts,
b71b7a8e 2367 control_dependences *cd, int *nb_calls, bool *destroy_p)
dea61d92 2368{
2fd5894f 2369 struct graph *rdg;
526ceb68 2370 partition *partition;
be6b029b 2371 bool any_builtin;
2fd5894f 2372 int i, nbp;
dea61d92 2373
c9326aef 2374 *destroy_p = false;
826a536d 2375 *nb_calls = 0;
4084ea5f 2376 loop_nest.create (0);
2fd5894f 2377 if (!find_loop_nest (loop, &loop_nest))
4084ea5f
BC
2378 {
2379 loop_nest.release ();
2380 return 0;
2381 }
2fd5894f 2382
9fafb14a 2383 datarefs_vec.create (20);
4084ea5f 2384 rdg = build_rdg (loop, cd);
2fd5894f
RB
2385 if (!rdg)
2386 {
2387 if (dump_file && (dump_flags & TDF_DETAILS))
2388 fprintf (dump_file,
2389 "Loop %d not distributed: failed to build the RDG.\n",
2390 loop->num);
2391
4084ea5f 2392 loop_nest.release ();
9fafb14a
BC
2393 free_data_refs (datarefs_vec);
2394 return 0;
2395 }
2396
2397 if (datarefs_vec.length () > MAX_DATAREFS_NUM)
2398 {
2399 if (dump_file && (dump_flags & TDF_DETAILS))
2400 fprintf (dump_file,
2401 "Loop %d not distributed: too many memory references.\n",
2402 loop->num);
2403
2404 free_rdg (rdg);
2405 loop_nest.release ();
2406 free_data_refs (datarefs_vec);
2fd5894f
RB
2407 return 0;
2408 }
2409
9fafb14a
BC
2410 data_reference_p dref;
2411 for (i = 0; datarefs_vec.iterate (i, &dref); ++i)
2412 dref->aux = (void *) (uintptr_t) i;
2413
2fd5894f
RB
2414 if (dump_file && (dump_flags & TDF_DETAILS))
2415 dump_rdg (dump_file, rdg);
2416
526ceb68 2417 auto_vec<struct partition *, 3> partitions;
2fd5894f 2418 rdg_build_partitions (rdg, stmts, &partitions);
dea61d92 2419
a8745cc2
BC
2420 auto_vec<ddr_p> alias_ddrs;
2421
4a52eb19
BC
2422 auto_bitmap stmt_in_all_partitions;
2423 bitmap_copy (stmt_in_all_partitions, partitions[0]->stmts);
2424 for (i = 1; partitions.iterate (i, &partition); ++i)
2425 bitmap_and_into (stmt_in_all_partitions, partitions[i]->stmts);
2426
be6b029b 2427 any_builtin = false;
9771b263 2428 FOR_EACH_VEC_ELT (partitions, i, partition)
be6b029b 2429 {
4a52eb19 2430 classify_partition (loop, rdg, partition, stmt_in_all_partitions);
be6b029b
RG
2431 any_builtin |= partition_builtin_p (partition);
2432 }
30d55936 2433
447f3223
RB
2434 /* If we are only distributing patterns but did not detect any,
2435 simply bail out. */
9fed7f3a
RB
2436 if (!flag_tree_loop_distribution
2437 && !any_builtin)
2438 {
2439 nbp = 0;
2440 goto ldist_done;
2441 }
2442
447f3223
RB
2443 /* If we are only distributing patterns fuse all partitions that
2444 were not classified as builtins. This also avoids chopping
2445 a loop into pieces, separated by builtin calls. That is, we
2446 only want no or a single loop body remaining. */
526ceb68 2447 struct partition *into;
447f3223
RB
2448 if (!flag_tree_loop_distribution)
2449 {
2450 for (i = 0; partitions.iterate (i, &into); ++i)
2451 if (!partition_builtin_p (into))
2452 break;
2453 for (++i; partitions.iterate (i, &partition); ++i)
2454 if (!partition_builtin_p (partition))
2455 {
f1eb4621 2456 partition_merge_into (NULL, into, partition, FUSE_NON_BUILTIN);
447f3223
RB
2457 partitions.unordered_remove (i);
2458 partition_free (partition);
2459 i--;
2460 }
2461 }
2462
2463 /* Due to limitations in the transform phase we have to fuse all
2464 reduction partitions into the last partition so the existing
2465 loop will contain all loop-closed PHI nodes. */
2466 for (i = 0; partitions.iterate (i, &into); ++i)
2467 if (partition_reduction_p (into))
2468 break;
2469 for (i = i + 1; partitions.iterate (i, &partition); ++i)
2470 if (partition_reduction_p (partition))
2471 {
f1eb4621 2472 partition_merge_into (rdg, into, partition, FUSE_REDUCTION);
447f3223
RB
2473 partitions.unordered_remove (i);
2474 partition_free (partition);
2475 i--;
2476 }
2477
9fed7f3a
RB
2478 /* Apply our simple cost model - fuse partitions with similar
2479 memory accesses. */
9fed7f3a
RB
2480 for (i = 0; partitions.iterate (i, &into); ++i)
2481 {
16eba420 2482 bool changed = false;
9fed7f3a
RB
2483 if (partition_builtin_p (into))
2484 continue;
2485 for (int j = i + 1;
2486 partitions.iterate (j, &partition); ++j)
2487 {
95f7d11b 2488 if (share_memory_accesses (rdg, into, partition))
9fed7f3a 2489 {
f1eb4621 2490 partition_merge_into (rdg, into, partition, FUSE_SHARE_REF);
447f3223 2491 partitions.unordered_remove (j);
9fed7f3a
RB
2492 partition_free (partition);
2493 j--;
16eba420 2494 changed = true;
9fed7f3a
RB
2495 }
2496 }
16eba420
RB
2497 /* If we fused 0 1 2 in step 1 to 0,2 1 as 0 and 2 have similar
2498 accesses when 1 and 2 have similar accesses but not 0 and 1
2499 then in the next iteration we will fail to consider merging
2500 1 into 0,2. So try again if we did any merging into 0. */
2501 if (changed)
2502 i--;
9fed7f3a
RB
2503 }
2504
447f3223
RB
2505 /* Build the partition dependency graph. */
2506 if (partitions.length () > 1)
c014f6f5 2507 {
6ff37519 2508 merge_dep_scc_partitions (rdg, &partitions);
a8745cc2 2509 alias_ddrs.truncate (0);
6ff37519 2510 if (partitions.length () > 1)
a8745cc2 2511 break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
b9fc0497
RB
2512 }
2513
a8745cc2
BC
2514 finalize_partitions (&partitions, &alias_ddrs);
2515
9771b263 2516 nbp = partitions.length ();
a4293fa6 2517 if (nbp == 0
9771b263
DN
2518 || (nbp == 1 && !partition_builtin_p (partitions[0]))
2519 || (nbp > 1 && partition_contains_all_rw (rdg, partitions)))
c014f6f5
RG
2520 {
2521 nbp = 0;
2522 goto ldist_done;
2523 }
dea61d92 2524
a8745cc2
BC
2525 if (version_for_distribution_p (&partitions, &alias_ddrs))
2526 version_loop_by_alias_check (loop, &alias_ddrs);
2527
dea61d92 2528 if (dump_file && (dump_flags & TDF_DETAILS))
a8745cc2
BC
2529 {
2530 fprintf (dump_file,
2531 "distribute loop <%d> into partitions:\n", loop->num);
2532 dump_rdg_partitions (dump_file, partitions);
2533 }
dea61d92 2534
9771b263 2535 FOR_EACH_VEC_ELT (partitions, i, partition)
826a536d
RB
2536 {
2537 if (partition_builtin_p (partition))
2538 (*nb_calls)++;
b71b7a8e 2539 *destroy_p |= generate_code_for_partition (loop, partition, i < nbp - 1);
826a536d 2540 }
dea61d92 2541
dea61d92 2542 ldist_done:
4084ea5f 2543 loop_nest.release ();
9fafb14a 2544 free_data_refs (datarefs_vec);
17c5cbdf
BC
2545 for (hash_table<ddr_hasher>::iterator iter = ddrs_table.begin ();
2546 iter != ddrs_table.end (); ++iter)
2547 {
2548 free_dependence_relation (*iter);
2549 *iter = NULL;
2550 }
2551 ddrs_table.empty ();
dea61d92 2552
9771b263 2553 FOR_EACH_VEC_ELT (partitions, i, partition)
c61f8985 2554 partition_free (partition);
dea61d92 2555
dea61d92 2556 free_rdg (rdg);
826a536d 2557 return nbp - *nb_calls;
dea61d92
SP
2558}
2559
2560/* Distribute all loops in the current function. */
2561
be55bfe6
TS
2562namespace {
2563
2564const pass_data pass_data_loop_distribution =
2565{
2566 GIMPLE_PASS, /* type */
2567 "ldist", /* name */
2568 OPTGROUP_LOOP, /* optinfo_flags */
be55bfe6
TS
2569 TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
2570 ( PROP_cfg | PROP_ssa ), /* properties_required */
2571 0, /* properties_provided */
2572 0, /* properties_destroyed */
2573 0, /* todo_flags_start */
3bea341f 2574 0, /* todo_flags_finish */
be55bfe6
TS
2575};
2576
2577class pass_loop_distribution : public gimple_opt_pass
2578{
2579public:
2580 pass_loop_distribution (gcc::context *ctxt)
2581 : gimple_opt_pass (pass_data_loop_distribution, ctxt)
2582 {}
2583
2584 /* opt_pass methods: */
2585 virtual bool gate (function *)
2586 {
2587 return flag_tree_loop_distribution
2588 || flag_tree_loop_distribute_patterns;
2589 }
2590
2591 virtual unsigned int execute (function *);
2592
2593}; // class pass_loop_distribution
2594
2595unsigned int
2596pass_loop_distribution::execute (function *fun)
dea61d92
SP
2597{
2598 struct loop *loop;
c014f6f5 2599 bool changed = false;
1fa0c180 2600 basic_block bb;
36875e8f 2601 control_dependences *cd = NULL;
b71b7a8e 2602 auto_vec<loop_p> loops_to_be_destroyed;
1fa0c180 2603
773d9217
BC
2604 if (number_of_loops (fun) <= 1)
2605 return 0;
2606
3be57c56
BC
2607 /* Compute topological order for basic blocks. Topological order is
2608 needed because data dependence is computed for data references in
2609 lexicographical order. */
2610 if (bb_top_order_index == NULL)
2611 {
3fb82452 2612 int rpo_num;
3be57c56
BC
2613 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
2614
2615 bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
3fb82452
BC
2616 bb_top_order_index_size = last_basic_block_for_fn (cfun);
2617 rpo_num = pre_and_rev_post_order_compute_fn (cfun, NULL, rpo, true);
2618 for (int i = 0; i < rpo_num; i++)
3be57c56
BC
2619 bb_top_order_index[rpo[i]] = i;
2620
2621 free (rpo);
2622 }
2623
be55bfe6 2624 FOR_ALL_BB_FN (bb, fun)
1fa0c180
RG
2625 {
2626 gimple_stmt_iterator gsi;
2627 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2628 gimple_set_uid (gsi_stmt (gsi), -1);
2629 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2630 gimple_set_uid (gsi_stmt (gsi), -1);
2631 }
dea61d92 2632
c014f6f5
RG
2633 /* We can at the moment only distribute non-nested loops, thus restrict
2634 walking to innermost loops. */
f0bd40b1 2635 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
dea61d92 2636 {
355fe088 2637 auto_vec<gimple *> work_list;
be6b029b 2638 basic_block *bbs;
0e20c89f 2639 int num = loop->num;
be6b029b 2640 unsigned int i;
a3357f7d
RG
2641
2642 /* If the loop doesn't have a single exit we will fail anyway,
2643 so do that early. */
2644 if (!single_exit (loop))
2645 continue;
dea61d92 2646
f56f2d33
JH
2647 /* Only optimize hot loops. */
2648 if (!optimize_loop_for_speed_p (loop))
2649 continue;
2650
6ff37519
BC
2651 /* Don't distribute loop if niters is unknown. */
2652 tree niters = number_of_latch_executions (loop);
2653 if (niters == NULL_TREE || niters == chrec_dont_know)
2654 continue;
2655
be6b029b
RG
2656 /* Initialize the worklist with stmts we seed the partitions with. */
2657 bbs = get_loop_body_in_dom_order (loop);
2658 for (i = 0; i < loop->num_nodes; ++i)
2659 {
538dd0b7
DM
2660 for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
2661 !gsi_end_p (gsi);
2662 gsi_next (&gsi))
deb6c11a 2663 {
538dd0b7 2664 gphi *phi = gsi.phi ();
deb6c11a
RB
2665 if (virtual_operand_p (gimple_phi_result (phi)))
2666 continue;
2667 /* Distribute stmts which have defs that are used outside of
be55bfe6 2668 the loop. */
deb6c11a
RB
2669 if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
2670 continue;
2671 work_list.safe_push (phi);
2672 }
538dd0b7
DM
2673 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
2674 !gsi_end_p (gsi);
2675 gsi_next (&gsi))
be6b029b 2676 {
355fe088 2677 gimple *stmt = gsi_stmt (gsi);
83a95546
RB
2678
2679 /* If there is a stmt with side-effects bail out - we
be55bfe6 2680 cannot and should not distribute this loop. */
83a95546
RB
2681 if (gimple_has_side_effects (stmt))
2682 {
2683 work_list.truncate (0);
2684 goto out;
2685 }
2686
b9fc0497 2687 /* Distribute stmts which have defs that are used outside of
be55bfe6 2688 the loop. */
b9fc0497
RB
2689 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
2690 ;
2691 /* Otherwise only distribute stores for now. */
e179190c 2692 else if (!gimple_vdef (stmt))
be6b029b
RG
2693 continue;
2694
9771b263 2695 work_list.safe_push (stmt);
be6b029b
RG
2696 }
2697 }
83a95546 2698out:
be6b029b 2699 free (bbs);
c014f6f5 2700
826a536d
RB
2701 int nb_generated_loops = 0;
2702 int nb_generated_calls = 0;
2703 location_t loc = find_loop_location (loop);
9771b263 2704 if (work_list.length () > 0)
36875e8f
RB
2705 {
2706 if (!cd)
2707 {
ca406576 2708 calculate_dominance_info (CDI_DOMINATORS);
36875e8f 2709 calculate_dominance_info (CDI_POST_DOMINATORS);
30fd2977 2710 cd = new control_dependences ();
36875e8f
RB
2711 free_dominance_info (CDI_POST_DOMINATORS);
2712 }
b71b7a8e 2713 bool destroy_p;
826a536d 2714 nb_generated_loops = distribute_loop (loop, work_list, cd,
b71b7a8e
RB
2715 &nb_generated_calls,
2716 &destroy_p);
2717 if (destroy_p)
2718 loops_to_be_destroyed.safe_push (loop);
36875e8f 2719 }
c014f6f5 2720
826a536d 2721 if (nb_generated_loops + nb_generated_calls > 0)
dea61d92 2722 {
826a536d
RB
2723 changed = true;
2724 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
2725 loc, "Loop %d distributed: split to %d loops "
2726 "and %d library calls.\n",
2727 num, nb_generated_loops, nb_generated_calls);
dea61d92 2728 }
826a536d
RB
2729 else if (dump_file && (dump_flags & TDF_DETAILS))
2730 fprintf (dump_file, "Loop %d is the same.\n", num);
dea61d92
SP
2731 }
2732
36875e8f
RB
2733 if (cd)
2734 delete cd;
2735
3be57c56
BC
2736 if (bb_top_order_index != NULL)
2737 {
2738 free (bb_top_order_index);
2739 bb_top_order_index = NULL;
2740 bb_top_order_index_size = 0;
2741 }
2742
c014f6f5
RG
2743 if (changed)
2744 {
30fd2977
RB
2745 /* Destroy loop bodies that could not be reused. Do this late as we
2746 otherwise can end up refering to stale data in control dependences. */
2747 unsigned i;
2748 FOR_EACH_VEC_ELT (loops_to_be_destroyed, i, loop)
3be57c56 2749 destroy_loop (loop);
30fd2977 2750
d0ed943c
RB
2751 /* Cached scalar evolutions now may refer to wrong or non-existing
2752 loops. */
2753 scev_reset_htab ();
be55bfe6 2754 mark_virtual_operands_for_renaming (fun);
c014f6f5
RG
2755 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
2756 }
2757
b2b29377 2758 checking_verify_loop_structure ();
c014f6f5 2759
5006671f 2760 return 0;
dea61d92
SP
2761}
2762
27a4cd48
DM
2763} // anon namespace
2764
2765gimple_opt_pass *
2766make_pass_loop_distribution (gcc::context *ctxt)
2767{
2768 return new pass_loop_distribution (ctxt);
2769}