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