]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-loop-distribution.c
re PR tree-optimization/81369 (ICE in generate_code_for_partition)
[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);
818625cf
RB
1415 if (!nb_iter || nb_iter == chrec_dont_know)
1416 return;
d995e887
RB
1417 if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
1418 gimple_bb (DR_STMT (single_store))))
1419 plus_one = true;
818625cf 1420
d0582dc1
RG
1421 if (single_store && !single_load)
1422 {
355fe088 1423 gimple *stmt = DR_STMT (single_store);
d0582dc1 1424 tree rhs = gimple_assign_rhs1 (stmt);
401f3a81
JJ
1425 if (const_with_all_bytes_same (rhs) == -1
1426 && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
1427 || (TYPE_MODE (TREE_TYPE (rhs))
1428 != TYPE_MODE (unsigned_char_type_node))))
d0582dc1
RG
1429 return;
1430 if (TREE_CODE (rhs) == SSA_NAME
1431 && !SSA_NAME_IS_DEFAULT_DEF (rhs)
1432 && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
1433 return;
ca406576
RB
1434 if (!adjacent_dr_p (single_store)
1435 || !dominated_by_p (CDI_DOMINATORS,
1436 loop->latch, gimple_bb (stmt)))
d0582dc1
RG
1437 return;
1438 partition->kind = PKIND_MEMSET;
1439 partition->main_dr = single_store;
818625cf 1440 partition->niter = nb_iter;
d995e887 1441 partition->plus_one = plus_one;
d0582dc1
RG
1442 }
1443 else if (single_store && single_load)
1444 {
355fe088
TS
1445 gimple *store = DR_STMT (single_store);
1446 gimple *load = DR_STMT (single_load);
d0582dc1
RG
1447 /* Direct aggregate copy or via an SSA name temporary. */
1448 if (load != store
1449 && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
1450 return;
1451 if (!adjacent_dr_p (single_store)
1452 || !adjacent_dr_p (single_load)
1453 || !operand_equal_p (DR_STEP (single_store),
ca406576
RB
1454 DR_STEP (single_load), 0)
1455 || !dominated_by_p (CDI_DOMINATORS,
1456 loop->latch, gimple_bb (store)))
d0582dc1 1457 return;
f20132e7
RG
1458 /* Now check that if there is a dependence this dependence is
1459 of a suitable form for memmove. */
17c5cbdf 1460 ddr_p ddr = get_data_dependence (rdg, single_load, single_store);
f20132e7 1461 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
17c5cbdf
BC
1462 return;
1463
f20132e7
RG
1464 if (DDR_ARE_DEPENDENT (ddr) != chrec_known)
1465 {
1466 if (DDR_NUM_DIST_VECTS (ddr) == 0)
17c5cbdf
BC
1467 return;
1468
f20132e7 1469 lambda_vector dist_v;
9771b263 1470 FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
f20132e7
RG
1471 {
1472 int dist = dist_v[index_in_loop_nest (loop->num,
1473 DDR_LOOP_NEST (ddr))];
1474 if (dist > 0 && !DDR_REVERSED_P (ddr))
17c5cbdf 1475 return;
f20132e7 1476 }
510d73a0 1477 partition->kind = PKIND_MEMMOVE;
f20132e7 1478 }
510d73a0
RB
1479 else
1480 partition->kind = PKIND_MEMCPY;
d0582dc1
RG
1481 partition->main_dr = single_store;
1482 partition->secondary_dr = single_load;
818625cf 1483 partition->niter = nb_iter;
d995e887 1484 partition->plus_one = plus_one;
d0582dc1 1485 }
cfee318d
SP
1486}
1487
95f7d11b
BC
1488/* Returns true when PARTITION1 and PARTITION2 access the same memory
1489 object in RDG. */
cfee318d
SP
1490
1491static bool
95f7d11b
BC
1492share_memory_accesses (struct graph *rdg,
1493 partition *partition1, partition *partition2)
cfee318d 1494{
95f7d11b 1495 unsigned i, j;
cfee318d 1496 bitmap_iterator bi, bj;
95f7d11b 1497 data_reference_p dr1, dr2;
1fa0c180
RG
1498
1499 /* First check whether in the intersection of the two partitions are
1500 any loads or stores. Common loads are the situation that happens
1501 most often. */
1502 EXECUTE_IF_AND_IN_BITMAP (partition1->stmts, partition2->stmts, 0, i, bi)
1503 if (RDG_MEM_WRITE_STMT (rdg, i)
1504 || RDG_MEM_READS_STMT (rdg, i))
1505 return true;
cfee318d 1506
95f7d11b
BC
1507 /* Then check whether the two partitions access the same memory object. */
1508 EXECUTE_IF_SET_IN_BITMAP (partition1->datarefs, 0, i, bi)
1509 {
1510 dr1 = datarefs_vec[i];
1511
1512 if (!DR_BASE_ADDRESS (dr1)
1513 || !DR_OFFSET (dr1) || !DR_INIT (dr1) || !DR_STEP (dr1))
1514 continue;
1515
1516 EXECUTE_IF_SET_IN_BITMAP (partition2->datarefs, 0, j, bj)
1517 {
1518 dr2 = datarefs_vec[j];
1519
1520 if (!DR_BASE_ADDRESS (dr2)
1521 || !DR_OFFSET (dr2) || !DR_INIT (dr2) || !DR_STEP (dr2))
1522 continue;
1523
1524 if (operand_equal_p (DR_BASE_ADDRESS (dr1), DR_BASE_ADDRESS (dr2), 0)
1525 && operand_equal_p (DR_OFFSET (dr1), DR_OFFSET (dr2), 0)
1526 && operand_equal_p (DR_INIT (dr1), DR_INIT (dr2), 0)
1527 && operand_equal_p (DR_STEP (dr1), DR_STEP (dr2), 0))
1528 return true;
1529 }
1530 }
cfee318d
SP
1531
1532 return false;
1533}
1534
4a52eb19
BC
1535/* For each seed statement in STARTING_STMTS, this function builds
1536 partition for it by adding depended statements according to RDG.
1537 All partitions are recorded in PARTITIONS. */
dea61d92
SP
1538
1539static void
83a95546 1540rdg_build_partitions (struct graph *rdg,
355fe088 1541 vec<gimple *> starting_stmts,
526ceb68 1542 vec<partition *> *partitions)
dea61d92 1543{
0e3de1d4 1544 auto_bitmap processed;
2fd5894f 1545 int i;
355fe088 1546 gimple *stmt;
dea61d92 1547
2fd5894f 1548 FOR_EACH_VEC_ELT (starting_stmts, i, stmt)
dea61d92 1549 {
2fd5894f
RB
1550 int v = rdg_vertex_for_stmt (rdg, stmt);
1551
1552 if (dump_file && (dump_flags & TDF_DETAILS))
1553 fprintf (dump_file,
1554 "ldist asked to generate code for vertex %d\n", v);
b8698a0f 1555
24f161fd
RB
1556 /* If the vertex is already contained in another partition so
1557 is the partition rooted at it. */
dea61d92
SP
1558 if (bitmap_bit_p (processed, v))
1559 continue;
b8698a0f 1560
526ceb68 1561 partition *partition = build_rdg_partition_for_vertex (rdg, v);
24f161fd 1562 bitmap_ior_into (processed, partition->stmts);
dea61d92 1563
826a536d 1564 if (dump_file && (dump_flags & TDF_DETAILS))
dea61d92 1565 {
f1eb4621
BC
1566 fprintf (dump_file, "ldist creates useful %s partition:\n",
1567 partition->type == PTYPE_PARALLEL ? "parallel" : "sequent");
1568 bitmap_print (dump_file, partition->stmts, " ", "\n");
dea61d92 1569 }
826a536d
RB
1570
1571 partitions->safe_push (partition);
dea61d92
SP
1572 }
1573
83a95546
RB
1574 /* All vertices should have been assigned to at least one partition now,
1575 other than vertices belonging to dead code. */
dea61d92
SP
1576}
1577
1578/* Dump to FILE the PARTITIONS. */
1579
1580static void
526ceb68 1581dump_rdg_partitions (FILE *file, vec<partition *> partitions)
dea61d92
SP
1582{
1583 int i;
526ceb68 1584 partition *partition;
dea61d92 1585
9771b263 1586 FOR_EACH_VEC_ELT (partitions, i, partition)
c61f8985 1587 debug_bitmap_file (file, partition->stmts);
dea61d92
SP
1588}
1589
1590/* Debug PARTITIONS. */
526ceb68 1591extern void debug_rdg_partitions (vec<partition *> );
dea61d92 1592
24e47c76 1593DEBUG_FUNCTION void
526ceb68 1594debug_rdg_partitions (vec<partition *> partitions)
dea61d92
SP
1595{
1596 dump_rdg_partitions (stderr, partitions);
1597}
1598
2b8aee8e
SP
1599/* Returns the number of read and write operations in the RDG. */
1600
1601static int
1602number_of_rw_in_rdg (struct graph *rdg)
1603{
1604 int i, res = 0;
1605
1606 for (i = 0; i < rdg->n_vertices; i++)
1607 {
1608 if (RDG_MEM_WRITE_STMT (rdg, i))
1609 ++res;
1610
1611 if (RDG_MEM_READS_STMT (rdg, i))
1612 ++res;
1613 }
1614
1615 return res;
1616}
1617
1618/* Returns the number of read and write operations in a PARTITION of
1619 the RDG. */
1620
1621static int
526ceb68 1622number_of_rw_in_partition (struct graph *rdg, partition *partition)
2b8aee8e
SP
1623{
1624 int res = 0;
1625 unsigned i;
1626 bitmap_iterator ii;
1627
c61f8985 1628 EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, ii)
2b8aee8e
SP
1629 {
1630 if (RDG_MEM_WRITE_STMT (rdg, i))
1631 ++res;
1632
1633 if (RDG_MEM_READS_STMT (rdg, i))
1634 ++res;
1635 }
1636
1637 return res;
1638}
1639
1640/* Returns true when one of the PARTITIONS contains all the read or
1641 write operations of RDG. */
1642
1643static bool
9771b263 1644partition_contains_all_rw (struct graph *rdg,
526ceb68 1645 vec<partition *> partitions)
2b8aee8e
SP
1646{
1647 int i;
526ceb68 1648 partition *partition;
2b8aee8e
SP
1649 int nrw = number_of_rw_in_rdg (rdg);
1650
9771b263 1651 FOR_EACH_VEC_ELT (partitions, i, partition)
2b8aee8e
SP
1652 if (nrw == number_of_rw_in_partition (rdg, partition))
1653 return true;
1654
1655 return false;
1656}
1657
447f3223 1658/* Compute partition dependence created by the data references in DRS1
a8745cc2
BC
1659 and DRS2, modify and return DIR according to that. IF ALIAS_DDR is
1660 not NULL, we record dependence introduced by possible alias between
1661 two data references in ALIAS_DDRS; otherwise, we simply ignore such
1662 dependence as if it doesn't exist at all. */
447f3223
RB
1663
1664static int
4084ea5f 1665pg_add_dependence_edges (struct graph *rdg, int dir,
a8745cc2 1666 bitmap drs1, bitmap drs2, vec<ddr_p> *alias_ddrs)
447f3223 1667{
a7a44c07
BC
1668 unsigned i, j;
1669 bitmap_iterator bi, bj;
1670 data_reference_p dr1, dr2, saved_dr1;
447f3223
RB
1671
1672 /* dependence direction - 0 is no dependence, -1 is back,
1673 1 is forth, 2 is both (we can stop then, merging will occur). */
a7a44c07
BC
1674 EXECUTE_IF_SET_IN_BITMAP (drs1, 0, i, bi)
1675 {
1676 dr1 = datarefs_vec[i];
1677
1678 EXECUTE_IF_SET_IN_BITMAP (drs2, 0, j, bj)
1679 {
a8745cc2
BC
1680 int res, this_dir = 1;
1681 ddr_p ddr;
1682
a7a44c07
BC
1683 dr2 = datarefs_vec[j];
1684
1685 /* Skip all <read, read> data dependence. */
1686 if (DR_IS_READ (dr1) && DR_IS_READ (dr2))
1687 continue;
1688
1689 saved_dr1 = dr1;
a8745cc2 1690 /* Re-shuffle data-refs to be in topological order. */
a7a44c07
BC
1691 if (rdg_vertex_for_stmt (rdg, DR_STMT (dr1))
1692 > rdg_vertex_for_stmt (rdg, DR_STMT (dr2)))
1693 {
1694 std::swap (dr1, dr2);
1695 this_dir = -this_dir;
1696 }
17c5cbdf 1697 ddr = get_data_dependence (rdg, dr1, dr2);
a7a44c07 1698 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
a8745cc2
BC
1699 {
1700 this_dir = 0;
1701 res = data_ref_compare_tree (DR_BASE_ADDRESS (dr1),
1702 DR_BASE_ADDRESS (dr2));
1703 /* Be conservative. If data references are not well analyzed,
1704 or the two data references have the same base address and
1705 offset, add dependence and consider it alias to each other.
1706 In other words, the dependence can not be resolved by
1707 runtime alias check. */
1708 if (!DR_BASE_ADDRESS (dr1) || !DR_BASE_ADDRESS (dr2)
1709 || !DR_OFFSET (dr1) || !DR_OFFSET (dr2)
1710 || !DR_INIT (dr1) || !DR_INIT (dr2)
1711 || !DR_STEP (dr1) || !tree_fits_uhwi_p (DR_STEP (dr1))
1712 || !DR_STEP (dr2) || !tree_fits_uhwi_p (DR_STEP (dr2))
1713 || res == 0)
1714 this_dir = 2;
1715 /* Data dependence could be resolved by runtime alias check,
1716 record it in ALIAS_DDRS. */
1717 else if (alias_ddrs != NULL)
1718 alias_ddrs->safe_push (ddr);
1719 /* Or simply ignore it. */
1720 }
a7a44c07
BC
1721 else if (DDR_ARE_DEPENDENT (ddr) == NULL_TREE)
1722 {
1723 if (DDR_REVERSED_P (ddr))
a8745cc2
BC
1724 this_dir = -this_dir;
1725
a7a44c07
BC
1726 /* Known dependences can still be unordered througout the
1727 iteration space, see gcc.dg/tree-ssa/ldist-16.c. */
1728 if (DDR_NUM_DIST_VECTS (ddr) != 1)
1729 this_dir = 2;
1730 /* If the overlap is exact preserve stmt order. */
1731 else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
1732 ;
a8745cc2
BC
1733 /* Else as the distance vector is lexicographic positive swap
1734 the dependence direction. */
a7a44c07 1735 else
a8745cc2 1736 this_dir = -this_dir;
a7a44c07
BC
1737 }
1738 else
1739 this_dir = 0;
a7a44c07
BC
1740 if (this_dir == 2)
1741 return 2;
1742 else if (dir == 0)
1743 dir = this_dir;
1744 else if (this_dir != 0 && dir != this_dir)
1745 return 2;
1746 /* Shuffle "back" dr1. */
1747 dr1 = saved_dr1;
1748 }
1749 }
447f3223
RB
1750 return dir;
1751}
1752
1753/* Compare postorder number of the partition graph vertices V1 and V2. */
1754
1755static int
1756pgcmp (const void *v1_, const void *v2_)
1757{
1758 const vertex *v1 = (const vertex *)v1_;
1759 const vertex *v2 = (const vertex *)v2_;
1760 return v2->post - v1->post;
1761}
2fd5894f 1762
a8745cc2
BC
1763/* Data attached to vertices of partition dependence graph. */
1764struct pg_vdata
1765{
1766 /* ID of the corresponding partition. */
1767 int id;
1768 /* The partition. */
1769 struct partition *partition;
1770};
1771
1772/* Data attached to edges of partition dependence graph. */
1773struct pg_edata
1774{
1775 /* If the dependence edge can be resolved by runtime alias check,
1776 this vector contains data dependence relations for runtime alias
1777 check. On the other hand, if the dependence edge is introduced
1778 because of compilation time known data dependence, this vector
1779 contains nothing. */
1780 vec<ddr_p> alias_ddrs;
1781};
1782
1783/* Callback data for traversing edges in graph. */
1784struct pg_edge_callback_data
1785{
1786 /* Bitmap contains strong connected components should be merged. */
1787 bitmap sccs_to_merge;
1788 /* Array constains component information for all vertices. */
1789 int *vertices_component;
1790 /* Vector to record all data dependence relations which are needed
1791 to break strong connected components by runtime alias checks. */
1792 vec<ddr_p> *alias_ddrs;
1793};
1794
1795/* Initialize vertice's data for partition dependence graph PG with
1796 PARTITIONS. */
1797
1798static void
1799init_partition_graph_vertices (struct graph *pg,
1800 vec<struct partition *> *partitions)
1801{
1802 int i;
1803 partition *partition;
1804 struct pg_vdata *data;
1805
1806 for (i = 0; partitions->iterate (i, &partition); ++i)
1807 {
1808 data = new pg_vdata;
1809 pg->vertices[i].data = data;
1810 data->id = i;
1811 data->partition = partition;
1812 }
1813}
1814
1815/* Add edge <I, J> to partition dependence graph PG. Attach vector of data
1816 dependence relations to the EDGE if DDRS isn't NULL. */
1817
1818static void
1819add_partition_graph_edge (struct graph *pg, int i, int j, vec<ddr_p> *ddrs)
1820{
1821 struct graph_edge *e = add_edge (pg, i, j);
1822
1823 /* If the edge is attached with data dependence relations, it means this
1824 dependence edge can be resolved by runtime alias checks. */
1825 if (ddrs != NULL)
1826 {
1827 struct pg_edata *data = new pg_edata;
1828
1829 gcc_assert (ddrs->length () > 0);
1830 e->data = data;
1831 data->alias_ddrs = vNULL;
1832 data->alias_ddrs.safe_splice (*ddrs);
1833 }
1834}
1835
1836/* Callback function for graph travesal algorithm. It returns true
1837 if edge E should skipped when traversing the graph. */
1838
1839static bool
1840pg_skip_alias_edge (struct graph_edge *e)
1841{
1842 struct pg_edata *data = (struct pg_edata *)e->data;
1843 return (data != NULL && data->alias_ddrs.length () > 0);
1844}
1845
1846/* Callback function freeing data attached to edge E of graph. */
1847
1848static void
1849free_partition_graph_edata_cb (struct graph *, struct graph_edge *e, void *)
1850{
1851 if (e->data != NULL)
1852 {
1853 struct pg_edata *data = (struct pg_edata *)e->data;
1854 data->alias_ddrs.release ();
1855 delete data;
1856 }
1857}
1858
1859/* Free data attached to vertice of partition dependence graph PG. */
1860
1861static void
1862free_partition_graph_vdata (struct graph *pg)
1863{
1864 int i;
1865 struct pg_vdata *data;
1866
1867 for (i = 0; i < pg->n_vertices; ++i)
1868 {
1869 data = (struct pg_vdata *)pg->vertices[i].data;
1870 delete data;
1871 }
1872}
1873
1874/* Build and return partition dependence graph for PARTITIONS. RDG is
1875 reduced dependence graph for the loop to be distributed. If IGNORE_ALIAS_P
1876 is true, data dependence caused by possible alias between references
1877 is ignored, as if it doesn't exist at all; otherwise all depdendences
1878 are considered. */
1879
1880static struct graph *
1881build_partition_graph (struct graph *rdg,
1882 vec<struct partition *> *partitions,
1883 bool ignore_alias_p)
1884{
1885 int i, j;
1886 struct partition *partition1, *partition2;
1887 graph *pg = new_graph (partitions->length ());
1888 auto_vec<ddr_p> alias_ddrs, *alias_ddrs_p;
1889
1890 alias_ddrs_p = ignore_alias_p ? NULL : &alias_ddrs;
1891
1892 init_partition_graph_vertices (pg, partitions);
1893
1894 for (i = 0; partitions->iterate (i, &partition1); ++i)
1895 {
1896 for (j = i + 1; partitions->iterate (j, &partition2); ++j)
1897 {
1898 /* dependence direction - 0 is no dependence, -1 is back,
1899 1 is forth, 2 is both (we can stop then, merging will occur). */
1900 int dir = 0;
1901
1902 /* If the first partition has reduction, add back edge; if the
1903 second partition has reduction, add forth edge. This makes
1904 sure that reduction partition will be sorted as the last one. */
1905 if (partition_reduction_p (partition1))
1906 dir = -1;
1907 else if (partition_reduction_p (partition2))
1908 dir = 1;
1909
1910 /* Cleanup the temporary vector. */
1911 alias_ddrs.truncate (0);
1912
1913 dir = pg_add_dependence_edges (rdg, dir, partition1->datarefs,
1914 partition2->datarefs, alias_ddrs_p);
1915
1916 /* Add edge to partition graph if there exists dependence. There
1917 are two types of edges. One type edge is caused by compilation
1918 time known dependence, this type can not be resolved by runtime
1919 alias check. The other type can be resolved by runtime alias
1920 check. */
1921 if (dir == 1 || dir == 2
1922 || alias_ddrs.length () > 0)
1923 {
1924 /* Attach data dependence relations to edge that can be resolved
1925 by runtime alias check. */
1926 bool alias_edge_p = (dir != 1 && dir != 2);
1927 add_partition_graph_edge (pg, i, j,
1928 (alias_edge_p) ? &alias_ddrs : NULL);
1929 }
1930 if (dir == -1 || dir == 2
1931 || alias_ddrs.length () > 0)
1932 {
1933 /* Attach data dependence relations to edge that can be resolved
1934 by runtime alias check. */
1935 bool alias_edge_p = (dir != -1 && dir != 2);
1936 add_partition_graph_edge (pg, j, i,
1937 (alias_edge_p) ? &alias_ddrs : NULL);
1938 }
1939 }
1940 }
1941 return pg;
1942}
1943
1944/* Sort partitions in PG by post order and store them in PARTITIONS. */
1945
1946static void
1947sort_partitions_by_post_order (struct graph *pg,
1948 vec<struct partition *> *partitions)
1949{
1950 int i;
1951 struct pg_vdata *data;
1952
1953 /* Now order the remaining nodes in postorder. */
1954 qsort (pg->vertices, pg->n_vertices, sizeof (vertex), pgcmp);
1955 partitions->truncate (0);
1956 for (i = 0; i < pg->n_vertices; ++i)
1957 {
1958 data = (struct pg_vdata *)pg->vertices[i].data;
1959 if (data->partition)
1960 partitions->safe_push (data->partition);
1961 }
1962}
1963
1964/* Given reduced dependence graph RDG merge strong connected components
1965 of PARTITIONS. If IGNORE_ALIAS_P is true, data dependence caused by
1966 possible alias between references is ignored, as if it doesn't exist
1967 at all; otherwise all depdendences are considered. */
1968
1969static void
1970merge_dep_scc_partitions (struct graph *rdg,
1971 vec<struct partition *> *partitions,
1972 bool ignore_alias_p)
1973{
1974 struct partition *partition1, *partition2;
1975 struct pg_vdata *data;
1976 graph *pg = build_partition_graph (rdg, partitions, ignore_alias_p);
1977 int i, j, num_sccs = graphds_scc (pg, NULL);
1978
1979 /* Strong connected compoenent means dependence cycle, we cannot distribute
1980 them. So fuse them together. */
1981 if ((unsigned) num_sccs < partitions->length ())
1982 {
1983 for (i = 0; i < num_sccs; ++i)
1984 {
1985 for (j = 0; partitions->iterate (j, &partition1); ++j)
1986 if (pg->vertices[j].component == i)
1987 break;
1988 for (j = j + 1; partitions->iterate (j, &partition2); ++j)
1989 if (pg->vertices[j].component == i)
1990 {
1991 partition_merge_into (NULL, partition1,
1992 partition2, FUSE_SAME_SCC);
1993 partition1->type = PTYPE_SEQUENTIAL;
1994 (*partitions)[j] = NULL;
1995 partition_free (partition2);
1996 data = (struct pg_vdata *)pg->vertices[j].data;
1997 data->partition = NULL;
1998 }
1999 }
a8745cc2 2000 }
aa1528b5
BC
2001
2002 sort_partitions_by_post_order (pg, partitions);
a8745cc2
BC
2003 gcc_assert (partitions->length () == (unsigned)num_sccs);
2004 free_partition_graph_vdata (pg);
2005 free_graph (pg);
2006}
2007
2008/* Callback function for traversing edge E in graph G. DATA is private
2009 callback data. */
2010
2011static void
2012pg_collect_alias_ddrs (struct graph *g, struct graph_edge *e, void *data)
2013{
2014 int i, j, component;
2015 struct pg_edge_callback_data *cbdata;
2016 struct pg_edata *edata = (struct pg_edata *) e->data;
2017
2018 /* If the edge doesn't have attached data dependence, it represents
2019 compilation time known dependences. This type dependence cannot
2020 be resolved by runtime alias check. */
2021 if (edata == NULL || edata->alias_ddrs.length () == 0)
2022 return;
2023
2024 cbdata = (struct pg_edge_callback_data *) data;
2025 i = e->src;
2026 j = e->dest;
2027 component = cbdata->vertices_component[i];
2028 /* Vertices are topologically sorted according to compilation time
2029 known dependences, so we can break strong connected components
2030 by removing edges of the opposite direction, i.e, edges pointing
2031 from vertice with smaller post number to vertice with bigger post
2032 number. */
2033 if (g->vertices[i].post < g->vertices[j].post
2034 /* We only need to remove edges connecting vertices in the same
2035 strong connected component to break it. */
2036 && component == cbdata->vertices_component[j]
2037 /* Check if we want to break the strong connected component or not. */
2038 && !bitmap_bit_p (cbdata->sccs_to_merge, component))
2039 cbdata->alias_ddrs->safe_splice (edata->alias_ddrs);
2040}
2041
2042/* This is the main function breaking strong conected components in
2043 PARTITIONS giving reduced depdendence graph RDG. Store data dependence
2044 relations for runtime alias check in ALIAS_DDRS. */
2045
2046static void
2047break_alias_scc_partitions (struct graph *rdg,
2048 vec<struct partition *> *partitions,
2049 vec<ddr_p> *alias_ddrs)
2050{
2051 int i, j, num_sccs, num_sccs_no_alias;
2052 /* Build partition dependence graph. */
2053 graph *pg = build_partition_graph (rdg, partitions, false);
2054
2055 alias_ddrs->truncate (0);
2056 /* Find strong connected components in the graph, with all dependence edges
2057 considered. */
2058 num_sccs = graphds_scc (pg, NULL);
2059 /* All SCCs now can be broken by runtime alias checks because SCCs caused by
2060 compilation time known dependences are merged before this function. */
2061 if ((unsigned) num_sccs < partitions->length ())
2062 {
2063 struct pg_edge_callback_data cbdata;
2064 auto_bitmap sccs_to_merge;
2065 auto_vec<enum partition_type> scc_types;
2066 struct partition *partition, *first;
2067
2068 /* If all paritions in a SCC has the same type, we can simply merge the
2069 SCC. This loop finds out such SCCS and record them in bitmap. */
2070 bitmap_set_range (sccs_to_merge, 0, (unsigned) num_sccs);
2071 for (i = 0; i < num_sccs; ++i)
2072 {
2073 for (j = 0; partitions->iterate (j, &first); ++j)
2074 if (pg->vertices[j].component == i)
2075 break;
2076 for (++j; partitions->iterate (j, &partition); ++j)
2077 {
2078 if (pg->vertices[j].component != i)
2079 continue;
2080
2081 if (first->type != partition->type)
2082 {
2083 bitmap_clear_bit (sccs_to_merge, i);
2084 break;
2085 }
2086 }
2087 }
2088
2089 /* Initialize callback data for traversing. */
2090 cbdata.sccs_to_merge = sccs_to_merge;
2091 cbdata.alias_ddrs = alias_ddrs;
2092 cbdata.vertices_component = XNEWVEC (int, pg->n_vertices);
2093 /* Record the component information which will be corrupted by next
2094 graph scc finding call. */
2095 for (i = 0; i < pg->n_vertices; ++i)
2096 cbdata.vertices_component[i] = pg->vertices[i].component;
2097
2098 /* Collect data dependences for runtime alias checks to break SCCs. */
2099 if (bitmap_count_bits (sccs_to_merge) != (unsigned) num_sccs)
2100 {
2101 /* Run SCC finding algorithm again, with alias dependence edges
2102 skipped. This is to topologically sort paritions according to
2103 compilation time known dependence. Note the topological order
2104 is stored in the form of pg's post order number. */
2105 num_sccs_no_alias = graphds_scc (pg, NULL, pg_skip_alias_edge);
2106 gcc_assert (partitions->length () == (unsigned) num_sccs_no_alias);
2107 /* With topological order, we can construct two subgraphs L and R.
2108 L contains edge <x, y> where x < y in terms of post order, while
2109 R contains edge <x, y> where x > y. Edges for compilation time
2110 known dependence all fall in R, so we break SCCs by removing all
2111 (alias) edges of in subgraph L. */
2112 for_each_edge (pg, pg_collect_alias_ddrs, &cbdata);
2113 }
2114
2115 /* For SCC that doesn't need to be broken, merge it. */
2116 for (i = 0; i < num_sccs; ++i)
2117 {
2118 if (!bitmap_bit_p (sccs_to_merge, i))
2119 continue;
2120
2121 for (j = 0; partitions->iterate (j, &first); ++j)
2122 if (cbdata.vertices_component[j] == i)
2123 break;
2124 for (++j; partitions->iterate (j, &partition); ++j)
2125 {
2126 struct pg_vdata *data;
2127
2128 if (cbdata.vertices_component[j] != i)
2129 continue;
2130
2131 partition_merge_into (NULL, first, partition, FUSE_SAME_SCC);
2132 (*partitions)[j] = NULL;
2133 partition_free (partition);
2134 data = (struct pg_vdata *)pg->vertices[j].data;
2135 gcc_assert (data->id == j);
2136 data->partition = NULL;
2137 }
2138 }
2139 }
2140
2141 sort_partitions_by_post_order (pg, partitions);
2142 free_partition_graph_vdata (pg);
2143 for_each_edge (pg, free_partition_graph_edata_cb, NULL);
2144 free_graph (pg);
2145
2146 if (dump_file && (dump_flags & TDF_DETAILS))
2147 {
2148 fprintf (dump_file, "Possible alias data dependence to break:\n");
2149 dump_data_dependence_relations (dump_file, *alias_ddrs);
2150 }
2151}
2152
2153/* Compute and return an expression whose value is the segment length which
2154 will be accessed by DR in NITERS iterations. */
2155
2156static tree
2157data_ref_segment_size (struct data_reference *dr, tree niters)
2158{
2159 tree segment_length;
2160
2161 if (integer_zerop (DR_STEP (dr)))
2162 segment_length = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
2163 else
2164 segment_length = size_binop (MULT_EXPR,
2165 fold_convert (sizetype, DR_STEP (dr)),
2166 fold_convert (sizetype, niters));
2167
2168 return segment_length;
2169}
2170
2171/* Return true if LOOP's latch is dominated by statement for data reference
2172 DR. */
2173
2174static inline bool
2175latch_dominated_by_data_ref (struct loop *loop, data_reference *dr)
2176{
2177 return dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
2178 gimple_bb (DR_STMT (dr)));
2179}
2180
2181/* Compute alias check pairs and store them in COMP_ALIAS_PAIRS for LOOP's
2182 data dependence relations ALIAS_DDRS. */
2183
2184static void
2185compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
2186 vec<dr_with_seg_len_pair_t> *comp_alias_pairs)
2187{
2188 unsigned int i;
2189 unsigned HOST_WIDE_INT factor = 1;
2190 tree niters_plus_one, niters = number_of_latch_executions (loop);
2191
2192 gcc_assert (niters != NULL_TREE && niters != chrec_dont_know);
2193 niters = fold_convert (sizetype, niters);
2194 niters_plus_one = size_binop (PLUS_EXPR, niters, size_one_node);
2195
2196 if (dump_file && (dump_flags & TDF_DETAILS))
2197 fprintf (dump_file, "Creating alias check pairs:\n");
2198
2199 /* Iterate all data dependence relations and compute alias check pairs. */
2200 for (i = 0; i < alias_ddrs->length (); i++)
2201 {
2202 ddr_p ddr = (*alias_ddrs)[i];
2203 struct data_reference *dr_a = DDR_A (ddr);
2204 struct data_reference *dr_b = DDR_B (ddr);
2205 tree seg_length_a, seg_length_b;
2206 int comp_res = data_ref_compare_tree (DR_BASE_ADDRESS (dr_a),
2207 DR_BASE_ADDRESS (dr_b));
2208
2209 if (comp_res == 0)
2210 comp_res = data_ref_compare_tree (DR_OFFSET (dr_a), DR_OFFSET (dr_b));
2211 gcc_assert (comp_res != 0);
2212
2213 if (latch_dominated_by_data_ref (loop, dr_a))
2214 seg_length_a = data_ref_segment_size (dr_a, niters_plus_one);
2215 else
2216 seg_length_a = data_ref_segment_size (dr_a, niters);
2217
2218 if (latch_dominated_by_data_ref (loop, dr_b))
2219 seg_length_b = data_ref_segment_size (dr_b, niters_plus_one);
2220 else
2221 seg_length_b = data_ref_segment_size (dr_b, niters);
2222
2223 dr_with_seg_len_pair_t dr_with_seg_len_pair
2224 (dr_with_seg_len (dr_a, seg_length_a),
2225 dr_with_seg_len (dr_b, seg_length_b));
2226
2227 /* Canonicalize pairs by sorting the two DR members. */
2228 if (comp_res > 0)
2229 std::swap (dr_with_seg_len_pair.first, dr_with_seg_len_pair.second);
2230
2231 comp_alias_pairs->safe_push (dr_with_seg_len_pair);
2232 }
2233
2234 if (tree_fits_uhwi_p (niters))
2235 factor = tree_to_uhwi (niters);
2236
2237 /* Prune alias check pairs. */
2238 prune_runtime_alias_test_list (comp_alias_pairs, factor);
2239 if (dump_file && (dump_flags & TDF_DETAILS))
2240 fprintf (dump_file,
2241 "Improved number of alias checks from %d to %d\n",
2242 alias_ddrs->length (), comp_alias_pairs->length ());
2243}
2244
2245/* Given data dependence relations in ALIAS_DDRS, generate runtime alias
2246 checks and version LOOP under condition of these runtime alias checks. */
2247
2248static void
2249version_loop_by_alias_check (struct loop *loop, vec<ddr_p> *alias_ddrs)
2250{
2251 profile_probability prob;
2252 basic_block cond_bb;
2253 struct loop *nloop;
2254 tree lhs, arg0, cond_expr = NULL_TREE;
2255 gimple_seq cond_stmts = NULL;
2256 gimple *call_stmt = NULL;
2257 auto_vec<dr_with_seg_len_pair_t> comp_alias_pairs;
2258
2259 /* Generate code for runtime alias checks if necessary. */
2260 gcc_assert (alias_ddrs->length () > 0);
2261
2262 if (dump_file && (dump_flags & TDF_DETAILS))
2263 fprintf (dump_file,
2264 "Version loop <%d> with runtime alias check\n", loop->num);
2265
2266 compute_alias_check_pairs (loop, alias_ddrs, &comp_alias_pairs);
2267 create_runtime_alias_checks (loop, &comp_alias_pairs, &cond_expr);
2268 cond_expr = force_gimple_operand_1 (cond_expr, &cond_stmts,
2269 is_gimple_condexpr, NULL_TREE);
2270
2271 /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS. */
2272 if (flag_tree_loop_vectorize)
2273 {
2274 /* Generate internal function call for loop distribution alias check. */
2275 call_stmt = gimple_build_call_internal (IFN_LOOP_DIST_ALIAS,
2276 2, NULL_TREE, cond_expr);
2277 lhs = make_ssa_name (boolean_type_node);
2278 gimple_call_set_lhs (call_stmt, lhs);
2279 }
2280 else
2281 lhs = cond_expr;
2282
2283 prob = profile_probability::guessed_always ().apply_scale (9, 10);
2284 initialize_original_copy_tables ();
2285 nloop = loop_version (loop, lhs, &cond_bb, prob, prob.invert (),
2286 prob, prob.invert (), true);
2287 free_original_copy_tables ();
2288 /* Record the original loop number in newly generated loops. In case of
2289 distribution, the original loop will be distributed and the new loop
2290 is kept. */
2291 loop->orig_loop_num = nloop->num;
2292 nloop->orig_loop_num = nloop->num;
2293 nloop->dont_vectorize = true;
2294 nloop->force_vectorize = false;
2295
2296 if (call_stmt)
2297 {
2298 /* Record new loop's num in IFN_LOOP_DIST_ALIAS because the original
2299 loop could be destroyed. */
2300 arg0 = build_int_cst (integer_type_node, loop->orig_loop_num);
2301 gimple_call_set_arg (call_stmt, 0, arg0);
2302 gimple_seq_add_stmt_without_update (&cond_stmts, call_stmt);
2303 }
2304
2305 if (cond_stmts)
2306 {
2307 gimple_stmt_iterator cond_gsi = gsi_last_bb (cond_bb);
2308 gsi_insert_seq_before (&cond_gsi, cond_stmts, GSI_SAME_STMT);
2309 }
2310 update_ssa (TODO_update_ssa);
2311}
2312
2313/* Return true if loop versioning is needed to distrubute PARTITIONS.
2314 ALIAS_DDRS are data dependence relations for runtime alias check. */
2315
2316static inline bool
2317version_for_distribution_p (vec<struct partition *> *partitions,
2318 vec<ddr_p> *alias_ddrs)
2319{
2320 /* No need to version loop if we have only one partition. */
2321 if (partitions->length () == 1)
2322 return false;
2323
2324 /* Need to version loop if runtime alias check is necessary. */
2325 return (alias_ddrs->length () > 0);
2326}
2327
2328/* Fuse all partitions if necessary before finalizing distribution. */
2329
2330static void
2331finalize_partitions (vec<struct partition *> *partitions,
2332 vec<ddr_p> *alias_ddrs)
2333{
2334 unsigned i;
2335 struct partition *a, *partition;
2336
2337 if (partitions->length () == 1
2338 || alias_ddrs->length () > 0)
2339 return;
2340
2341 a = (*partitions)[0];
2342 if (a->kind != PKIND_NORMAL)
2343 return;
2344
2345 for (i = 1; partitions->iterate (i, &partition); ++i)
2346 {
2347 /* Don't fuse if partition has different type or it is a builtin. */
2348 if (partition->type != a->type
2349 || partition->kind != PKIND_NORMAL)
2350 return;
2351 }
2352
2353 /* Fuse all partitions. */
2354 for (i = 1; partitions->iterate (i, &partition); ++i)
2355 {
2356 partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
2357 partition_free (partition);
2358 }
2359 partitions->truncate (1);
2360}
2361
2362/* Distributes the code from LOOP in such a way that producer statements
2363 are placed before consumer statements. Tries to separate only the
2364 statements from STMTS into separate loops. Returns the number of
2365 distributed loops. Set NB_CALLS to number of generated builtin calls.
2366 Set *DESTROY_P to whether LOOP needs to be destroyed. */
dea61d92
SP
2367
2368static int
355fe088 2369distribute_loop (struct loop *loop, vec<gimple *> stmts,
b71b7a8e 2370 control_dependences *cd, int *nb_calls, bool *destroy_p)
dea61d92 2371{
2fd5894f 2372 struct graph *rdg;
526ceb68 2373 partition *partition;
be6b029b 2374 bool any_builtin;
2fd5894f 2375 int i, nbp;
dea61d92 2376
c9326aef 2377 *destroy_p = false;
826a536d 2378 *nb_calls = 0;
4084ea5f 2379 loop_nest.create (0);
2fd5894f 2380 if (!find_loop_nest (loop, &loop_nest))
4084ea5f
BC
2381 {
2382 loop_nest.release ();
2383 return 0;
2384 }
2fd5894f 2385
9fafb14a 2386 datarefs_vec.create (20);
4084ea5f 2387 rdg = build_rdg (loop, cd);
2fd5894f
RB
2388 if (!rdg)
2389 {
2390 if (dump_file && (dump_flags & TDF_DETAILS))
2391 fprintf (dump_file,
2392 "Loop %d not distributed: failed to build the RDG.\n",
2393 loop->num);
2394
4084ea5f 2395 loop_nest.release ();
9fafb14a
BC
2396 free_data_refs (datarefs_vec);
2397 return 0;
2398 }
2399
2400 if (datarefs_vec.length () > MAX_DATAREFS_NUM)
2401 {
2402 if (dump_file && (dump_flags & TDF_DETAILS))
2403 fprintf (dump_file,
2404 "Loop %d not distributed: too many memory references.\n",
2405 loop->num);
2406
2407 free_rdg (rdg);
2408 loop_nest.release ();
2409 free_data_refs (datarefs_vec);
2fd5894f
RB
2410 return 0;
2411 }
2412
9fafb14a
BC
2413 data_reference_p dref;
2414 for (i = 0; datarefs_vec.iterate (i, &dref); ++i)
2415 dref->aux = (void *) (uintptr_t) i;
2416
2fd5894f
RB
2417 if (dump_file && (dump_flags & TDF_DETAILS))
2418 dump_rdg (dump_file, rdg);
2419
526ceb68 2420 auto_vec<struct partition *, 3> partitions;
2fd5894f 2421 rdg_build_partitions (rdg, stmts, &partitions);
dea61d92 2422
a8745cc2
BC
2423 /* Can't do runtime alias check if loop niter is unknown. */
2424 tree niters = number_of_latch_executions (loop);
2425 bool rt_alias_check_p = (niters != NULL_TREE && niters != chrec_dont_know);
2426 auto_vec<ddr_p> alias_ddrs;
2427
4a52eb19
BC
2428 auto_bitmap stmt_in_all_partitions;
2429 bitmap_copy (stmt_in_all_partitions, partitions[0]->stmts);
2430 for (i = 1; partitions.iterate (i, &partition); ++i)
2431 bitmap_and_into (stmt_in_all_partitions, partitions[i]->stmts);
2432
be6b029b 2433 any_builtin = false;
9771b263 2434 FOR_EACH_VEC_ELT (partitions, i, partition)
be6b029b 2435 {
4a52eb19 2436 classify_partition (loop, rdg, partition, stmt_in_all_partitions);
be6b029b
RG
2437 any_builtin |= partition_builtin_p (partition);
2438 }
30d55936 2439
447f3223
RB
2440 /* If we are only distributing patterns but did not detect any,
2441 simply bail out. */
9fed7f3a
RB
2442 if (!flag_tree_loop_distribution
2443 && !any_builtin)
2444 {
2445 nbp = 0;
2446 goto ldist_done;
2447 }
2448
447f3223
RB
2449 /* If we are only distributing patterns fuse all partitions that
2450 were not classified as builtins. This also avoids chopping
2451 a loop into pieces, separated by builtin calls. That is, we
2452 only want no or a single loop body remaining. */
526ceb68 2453 struct partition *into;
447f3223
RB
2454 if (!flag_tree_loop_distribution)
2455 {
2456 for (i = 0; partitions.iterate (i, &into); ++i)
2457 if (!partition_builtin_p (into))
2458 break;
2459 for (++i; partitions.iterate (i, &partition); ++i)
2460 if (!partition_builtin_p (partition))
2461 {
f1eb4621 2462 partition_merge_into (NULL, into, partition, FUSE_NON_BUILTIN);
447f3223
RB
2463 partitions.unordered_remove (i);
2464 partition_free (partition);
2465 i--;
2466 }
2467 }
2468
2469 /* Due to limitations in the transform phase we have to fuse all
2470 reduction partitions into the last partition so the existing
2471 loop will contain all loop-closed PHI nodes. */
2472 for (i = 0; partitions.iterate (i, &into); ++i)
2473 if (partition_reduction_p (into))
2474 break;
2475 for (i = i + 1; partitions.iterate (i, &partition); ++i)
2476 if (partition_reduction_p (partition))
2477 {
f1eb4621 2478 partition_merge_into (rdg, into, partition, FUSE_REDUCTION);
447f3223
RB
2479 partitions.unordered_remove (i);
2480 partition_free (partition);
2481 i--;
2482 }
2483
9fed7f3a
RB
2484 /* Apply our simple cost model - fuse partitions with similar
2485 memory accesses. */
9fed7f3a
RB
2486 for (i = 0; partitions.iterate (i, &into); ++i)
2487 {
16eba420 2488 bool changed = false;
9fed7f3a
RB
2489 if (partition_builtin_p (into))
2490 continue;
2491 for (int j = i + 1;
2492 partitions.iterate (j, &partition); ++j)
2493 {
95f7d11b 2494 if (share_memory_accesses (rdg, into, partition))
9fed7f3a 2495 {
f1eb4621 2496 partition_merge_into (rdg, into, partition, FUSE_SHARE_REF);
447f3223 2497 partitions.unordered_remove (j);
9fed7f3a
RB
2498 partition_free (partition);
2499 j--;
16eba420 2500 changed = true;
9fed7f3a
RB
2501 }
2502 }
16eba420
RB
2503 /* If we fused 0 1 2 in step 1 to 0,2 1 as 0 and 2 have similar
2504 accesses when 1 and 2 have similar accesses but not 0 and 1
2505 then in the next iteration we will fail to consider merging
2506 1 into 0,2. So try again if we did any merging into 0. */
2507 if (changed)
2508 i--;
9fed7f3a
RB
2509 }
2510
447f3223
RB
2511 /* Build the partition dependency graph. */
2512 if (partitions.length () > 1)
c014f6f5 2513 {
a8745cc2
BC
2514 merge_dep_scc_partitions (rdg, &partitions, rt_alias_check_p);
2515 alias_ddrs.truncate (0);
2516 if (rt_alias_check_p && partitions.length () > 1)
2517 break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
b9fc0497
RB
2518 }
2519
a8745cc2
BC
2520 finalize_partitions (&partitions, &alias_ddrs);
2521
9771b263 2522 nbp = partitions.length ();
a4293fa6 2523 if (nbp == 0
9771b263
DN
2524 || (nbp == 1 && !partition_builtin_p (partitions[0]))
2525 || (nbp > 1 && partition_contains_all_rw (rdg, partitions)))
c014f6f5
RG
2526 {
2527 nbp = 0;
2528 goto ldist_done;
2529 }
dea61d92 2530
a8745cc2
BC
2531 if (version_for_distribution_p (&partitions, &alias_ddrs))
2532 version_loop_by_alias_check (loop, &alias_ddrs);
2533
dea61d92 2534 if (dump_file && (dump_flags & TDF_DETAILS))
a8745cc2
BC
2535 {
2536 fprintf (dump_file,
2537 "distribute loop <%d> into partitions:\n", loop->num);
2538 dump_rdg_partitions (dump_file, partitions);
2539 }
dea61d92 2540
9771b263 2541 FOR_EACH_VEC_ELT (partitions, i, partition)
826a536d
RB
2542 {
2543 if (partition_builtin_p (partition))
2544 (*nb_calls)++;
b71b7a8e 2545 *destroy_p |= generate_code_for_partition (loop, partition, i < nbp - 1);
826a536d 2546 }
dea61d92 2547
dea61d92 2548 ldist_done:
4084ea5f 2549 loop_nest.release ();
9fafb14a 2550 free_data_refs (datarefs_vec);
17c5cbdf
BC
2551 for (hash_table<ddr_hasher>::iterator iter = ddrs_table.begin ();
2552 iter != ddrs_table.end (); ++iter)
2553 {
2554 free_dependence_relation (*iter);
2555 *iter = NULL;
2556 }
2557 ddrs_table.empty ();
dea61d92 2558
9771b263 2559 FOR_EACH_VEC_ELT (partitions, i, partition)
c61f8985 2560 partition_free (partition);
dea61d92 2561
dea61d92 2562 free_rdg (rdg);
826a536d 2563 return nbp - *nb_calls;
dea61d92
SP
2564}
2565
2566/* Distribute all loops in the current function. */
2567
be55bfe6
TS
2568namespace {
2569
2570const pass_data pass_data_loop_distribution =
2571{
2572 GIMPLE_PASS, /* type */
2573 "ldist", /* name */
2574 OPTGROUP_LOOP, /* optinfo_flags */
be55bfe6
TS
2575 TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
2576 ( PROP_cfg | PROP_ssa ), /* properties_required */
2577 0, /* properties_provided */
2578 0, /* properties_destroyed */
2579 0, /* todo_flags_start */
3bea341f 2580 0, /* todo_flags_finish */
be55bfe6
TS
2581};
2582
2583class pass_loop_distribution : public gimple_opt_pass
2584{
2585public:
2586 pass_loop_distribution (gcc::context *ctxt)
2587 : gimple_opt_pass (pass_data_loop_distribution, ctxt)
2588 {}
2589
2590 /* opt_pass methods: */
2591 virtual bool gate (function *)
2592 {
2593 return flag_tree_loop_distribution
2594 || flag_tree_loop_distribute_patterns;
2595 }
2596
2597 virtual unsigned int execute (function *);
2598
2599}; // class pass_loop_distribution
2600
2601unsigned int
2602pass_loop_distribution::execute (function *fun)
dea61d92
SP
2603{
2604 struct loop *loop;
c014f6f5 2605 bool changed = false;
1fa0c180 2606 basic_block bb;
36875e8f 2607 control_dependences *cd = NULL;
b71b7a8e 2608 auto_vec<loop_p> loops_to_be_destroyed;
1fa0c180 2609
773d9217
BC
2610 if (number_of_loops (fun) <= 1)
2611 return 0;
2612
3be57c56
BC
2613 /* Compute topological order for basic blocks. Topological order is
2614 needed because data dependence is computed for data references in
2615 lexicographical order. */
2616 if (bb_top_order_index == NULL)
2617 {
3fb82452 2618 int rpo_num;
3be57c56
BC
2619 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
2620
2621 bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
3fb82452
BC
2622 bb_top_order_index_size = last_basic_block_for_fn (cfun);
2623 rpo_num = pre_and_rev_post_order_compute_fn (cfun, NULL, rpo, true);
2624 for (int i = 0; i < rpo_num; i++)
3be57c56
BC
2625 bb_top_order_index[rpo[i]] = i;
2626
2627 free (rpo);
2628 }
2629
be55bfe6 2630 FOR_ALL_BB_FN (bb, fun)
1fa0c180
RG
2631 {
2632 gimple_stmt_iterator gsi;
2633 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2634 gimple_set_uid (gsi_stmt (gsi), -1);
2635 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2636 gimple_set_uid (gsi_stmt (gsi), -1);
2637 }
dea61d92 2638
c014f6f5
RG
2639 /* We can at the moment only distribute non-nested loops, thus restrict
2640 walking to innermost loops. */
f0bd40b1 2641 FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
dea61d92 2642 {
355fe088 2643 auto_vec<gimple *> work_list;
be6b029b 2644 basic_block *bbs;
0e20c89f 2645 int num = loop->num;
be6b029b 2646 unsigned int i;
a3357f7d
RG
2647
2648 /* If the loop doesn't have a single exit we will fail anyway,
2649 so do that early. */
2650 if (!single_exit (loop))
2651 continue;
dea61d92 2652
f56f2d33
JH
2653 /* Only optimize hot loops. */
2654 if (!optimize_loop_for_speed_p (loop))
2655 continue;
2656
be6b029b
RG
2657 /* Initialize the worklist with stmts we seed the partitions with. */
2658 bbs = get_loop_body_in_dom_order (loop);
2659 for (i = 0; i < loop->num_nodes; ++i)
2660 {
538dd0b7
DM
2661 for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
2662 !gsi_end_p (gsi);
2663 gsi_next (&gsi))
deb6c11a 2664 {
538dd0b7 2665 gphi *phi = gsi.phi ();
deb6c11a
RB
2666 if (virtual_operand_p (gimple_phi_result (phi)))
2667 continue;
2668 /* Distribute stmts which have defs that are used outside of
be55bfe6 2669 the loop. */
deb6c11a
RB
2670 if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
2671 continue;
2672 work_list.safe_push (phi);
2673 }
538dd0b7
DM
2674 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
2675 !gsi_end_p (gsi);
2676 gsi_next (&gsi))
be6b029b 2677 {
355fe088 2678 gimple *stmt = gsi_stmt (gsi);
83a95546
RB
2679
2680 /* If there is a stmt with side-effects bail out - we
be55bfe6 2681 cannot and should not distribute this loop. */
83a95546
RB
2682 if (gimple_has_side_effects (stmt))
2683 {
2684 work_list.truncate (0);
2685 goto out;
2686 }
2687
b9fc0497 2688 /* Distribute stmts which have defs that are used outside of
be55bfe6 2689 the loop. */
b9fc0497
RB
2690 if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
2691 ;
2692 /* Otherwise only distribute stores for now. */
e179190c 2693 else if (!gimple_vdef (stmt))
be6b029b
RG
2694 continue;
2695
9771b263 2696 work_list.safe_push (stmt);
be6b029b
RG
2697 }
2698 }
83a95546 2699out:
be6b029b 2700 free (bbs);
c014f6f5 2701
826a536d
RB
2702 int nb_generated_loops = 0;
2703 int nb_generated_calls = 0;
2704 location_t loc = find_loop_location (loop);
9771b263 2705 if (work_list.length () > 0)
36875e8f
RB
2706 {
2707 if (!cd)
2708 {
ca406576 2709 calculate_dominance_info (CDI_DOMINATORS);
36875e8f 2710 calculate_dominance_info (CDI_POST_DOMINATORS);
30fd2977 2711 cd = new control_dependences ();
36875e8f
RB
2712 free_dominance_info (CDI_POST_DOMINATORS);
2713 }
b71b7a8e 2714 bool destroy_p;
826a536d 2715 nb_generated_loops = distribute_loop (loop, work_list, cd,
b71b7a8e
RB
2716 &nb_generated_calls,
2717 &destroy_p);
2718 if (destroy_p)
2719 loops_to_be_destroyed.safe_push (loop);
36875e8f 2720 }
c014f6f5 2721
826a536d 2722 if (nb_generated_loops + nb_generated_calls > 0)
dea61d92 2723 {
826a536d
RB
2724 changed = true;
2725 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
2726 loc, "Loop %d distributed: split to %d loops "
2727 "and %d library calls.\n",
2728 num, nb_generated_loops, nb_generated_calls);
dea61d92 2729 }
826a536d
RB
2730 else if (dump_file && (dump_flags & TDF_DETAILS))
2731 fprintf (dump_file, "Loop %d is the same.\n", num);
dea61d92
SP
2732 }
2733
36875e8f
RB
2734 if (cd)
2735 delete cd;
2736
3be57c56
BC
2737 if (bb_top_order_index != NULL)
2738 {
2739 free (bb_top_order_index);
2740 bb_top_order_index = NULL;
2741 bb_top_order_index_size = 0;
2742 }
2743
c014f6f5
RG
2744 if (changed)
2745 {
30fd2977
RB
2746 /* Destroy loop bodies that could not be reused. Do this late as we
2747 otherwise can end up refering to stale data in control dependences. */
2748 unsigned i;
2749 FOR_EACH_VEC_ELT (loops_to_be_destroyed, i, loop)
3be57c56 2750 destroy_loop (loop);
30fd2977 2751
d0ed943c
RB
2752 /* Cached scalar evolutions now may refer to wrong or non-existing
2753 loops. */
2754 scev_reset_htab ();
be55bfe6 2755 mark_virtual_operands_for_renaming (fun);
c014f6f5
RG
2756 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
2757 }
2758
b2b29377 2759 checking_verify_loop_structure ();
c014f6f5 2760
5006671f 2761 return 0;
dea61d92
SP
2762}
2763
27a4cd48
DM
2764} // anon namespace
2765
2766gimple_opt_pass *
2767make_pass_loop_distribution (gcc::context *ctxt)
2768{
2769 return new pass_loop_distribution (ctxt);
2770}