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