isl_set_universe: rename "dim" argument to "space"
[isl.git] / isl_scheduler.c
blob9a93c30711caa65e5712d996a53776e509c4067a
1 /*
2 * Copyright 2011 INRIA Saclay
3 * Copyright 2012-2014 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
5 * Copyright 2016 INRIA Paris
6 * Copyright 2017 Sven Verdoolaege
8 * Use of this software is governed by the MIT license
10 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
11 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
12 * 91893 Orsay, France
13 * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
14 * and Centre de Recherche Inria de Paris, 2 rue Simone Iff - Voie DQ12,
15 * CS 42112, 75589 Paris Cedex 12, France
18 #include <isl_ctx_private.h>
19 #include <isl_map_private.h>
20 #include <isl_space_private.h>
21 #include <isl_aff_private.h>
22 #include <isl/hash.h>
23 #include <isl/constraint.h>
24 #include <isl/schedule.h>
25 #include <isl_schedule_constraints.h>
26 #include <isl/schedule_node.h>
27 #include <isl_mat_private.h>
28 #include <isl_vec_private.h>
29 #include <isl/set.h>
30 #include <isl_union_set_private.h>
31 #include <isl_seq.h>
32 #include <isl_tab.h>
33 #include <isl_dim_map.h>
34 #include <isl/map_to_basic_set.h>
35 #include <isl_sort.h>
36 #include <isl_options_private.h>
37 #include <isl_tarjan.h>
38 #include <isl_morph.h>
39 #include <isl/ilp.h>
40 #include <isl_val_private.h>
43 * The scheduling algorithm implemented in this file was inspired by
44 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
45 * Parallelization and Locality Optimization in the Polyhedral Model".
49 /* Internal information about a node that is used during the construction
50 * of a schedule.
51 * space represents the original space in which the domain lives;
52 * that is, the space is not affected by compression
53 * sched is a matrix representation of the schedule being constructed
54 * for this node; if compressed is set, then this schedule is
55 * defined over the compressed domain space
56 * sched_map is an isl_map representation of the same (partial) schedule
57 * sched_map may be NULL; if compressed is set, then this map
58 * is defined over the uncompressed domain space
59 * rank is the number of linearly independent rows in the linear part
60 * of sched
61 * the rows of "vmap" represent a change of basis for the node
62 * variables; the first rank rows span the linear part of
63 * the schedule rows; the remaining rows are linearly independent
64 * the rows of "indep" represent linear combinations of the schedule
65 * coefficients that are non-zero when the schedule coefficients are
66 * linearly independent of previously computed schedule rows.
67 * start is the first variable in the LP problem in the sequences that
68 * represents the schedule coefficients of this node
69 * nvar is the dimension of the domain
70 * nparam is the number of parameters or 0 if we are not constructing
71 * a parametric schedule
73 * If compressed is set, then hull represents the constraints
74 * that were used to derive the compression, while compress and
75 * decompress map the original space to the compressed space and
76 * vice versa.
78 * scc is the index of SCC (or WCC) this node belongs to
80 * "cluster" is only used inside extract_clusters and identifies
81 * the cluster of SCCs that the node belongs to.
83 * coincident contains a boolean for each of the rows of the schedule,
84 * indicating whether the corresponding scheduling dimension satisfies
85 * the coincidence constraints in the sense that the corresponding
86 * dependence distances are zero.
88 * If the schedule_treat_coalescing option is set, then
89 * "sizes" contains the sizes of the (compressed) instance set
90 * in each direction. If there is no fixed size in a given direction,
91 * then the corresponding size value is set to infinity.
92 * If the schedule_treat_coalescing option or the schedule_max_coefficient
93 * option is set, then "max" contains the maximal values for
94 * schedule coefficients of the (compressed) variables. If no bound
95 * needs to be imposed on a particular variable, then the corresponding
96 * value is negative.
97 * If not NULL, then "bounds" contains a non-parametric set
98 * in the compressed space that is bounded by the size in each direction.
100 struct isl_sched_node {
101 isl_space *space;
102 int compressed;
103 isl_set *hull;
104 isl_multi_aff *compress;
105 isl_multi_aff *decompress;
106 isl_mat *sched;
107 isl_map *sched_map;
108 int rank;
109 isl_mat *indep;
110 isl_mat *vmap;
111 int start;
112 int nvar;
113 int nparam;
115 int scc;
116 int cluster;
118 int *coincident;
120 isl_multi_val *sizes;
121 isl_basic_set *bounds;
122 isl_vec *max;
125 static int node_has_tuples(const void *entry, const void *val)
127 struct isl_sched_node *node = (struct isl_sched_node *)entry;
128 isl_space *space = (isl_space *) val;
130 return isl_space_has_equal_tuples(node->space, space);
133 static int node_scc_exactly(struct isl_sched_node *node, int scc)
135 return node->scc == scc;
138 static int node_scc_at_most(struct isl_sched_node *node, int scc)
140 return node->scc <= scc;
143 static int node_scc_at_least(struct isl_sched_node *node, int scc)
145 return node->scc >= scc;
148 /* An edge in the dependence graph. An edge may be used to
149 * ensure validity of the generated schedule, to minimize the dependence
150 * distance or both
152 * map is the dependence relation, with i -> j in the map if j depends on i
153 * tagged_condition and tagged_validity contain the union of all tagged
154 * condition or conditional validity dependence relations that
155 * specialize the dependence relation "map"; that is,
156 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
157 * or "tagged_validity", then i -> j is an element of "map".
158 * If these fields are NULL, then they represent the empty relation.
159 * src is the source node
160 * dst is the sink node
162 * types is a bit vector containing the types of this edge.
163 * validity is set if the edge is used to ensure correctness
164 * coincidence is used to enforce zero dependence distances
165 * proximity is set if the edge is used to minimize dependence distances
166 * condition is set if the edge represents a condition
167 * for a conditional validity schedule constraint
168 * local can only be set for condition edges and indicates that
169 * the dependence distance over the edge should be zero
170 * conditional_validity is set if the edge is used to conditionally
171 * ensure correctness
173 * For validity edges, start and end mark the sequence of inequality
174 * constraints in the LP problem that encode the validity constraint
175 * corresponding to this edge.
177 * During clustering, an edge may be marked "no_merge" if it should
178 * not be used to merge clusters.
179 * The weight is also only used during clustering and it is
180 * an indication of how many schedule dimensions on either side
181 * of the schedule constraints can be aligned.
182 * If the weight is negative, then this means that this edge was postponed
183 * by has_bounded_distances or any_no_merge. The original weight can
184 * be retrieved by adding 1 + graph->max_weight, with "graph"
185 * the graph containing this edge.
187 struct isl_sched_edge {
188 isl_map *map;
189 isl_union_map *tagged_condition;
190 isl_union_map *tagged_validity;
192 struct isl_sched_node *src;
193 struct isl_sched_node *dst;
195 unsigned types;
197 int start;
198 int end;
200 int no_merge;
201 int weight;
204 /* Is "edge" marked as being of type "type"?
206 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
208 return ISL_FL_ISSET(edge->types, 1 << type);
211 /* Mark "edge" as being of type "type".
213 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
215 ISL_FL_SET(edge->types, 1 << type);
218 /* No longer mark "edge" as being of type "type"?
220 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
222 ISL_FL_CLR(edge->types, 1 << type);
225 /* Is "edge" marked as a validity edge?
227 static int is_validity(struct isl_sched_edge *edge)
229 return is_type(edge, isl_edge_validity);
232 /* Mark "edge" as a validity edge.
234 static void set_validity(struct isl_sched_edge *edge)
236 set_type(edge, isl_edge_validity);
239 /* Is "edge" marked as a proximity edge?
241 static int is_proximity(struct isl_sched_edge *edge)
243 return is_type(edge, isl_edge_proximity);
246 /* Is "edge" marked as a local edge?
248 static int is_local(struct isl_sched_edge *edge)
250 return is_type(edge, isl_edge_local);
253 /* Mark "edge" as a local edge.
255 static void set_local(struct isl_sched_edge *edge)
257 set_type(edge, isl_edge_local);
260 /* No longer mark "edge" as a local edge.
262 static void clear_local(struct isl_sched_edge *edge)
264 clear_type(edge, isl_edge_local);
267 /* Is "edge" marked as a coincidence edge?
269 static int is_coincidence(struct isl_sched_edge *edge)
271 return is_type(edge, isl_edge_coincidence);
274 /* Is "edge" marked as a condition edge?
276 static int is_condition(struct isl_sched_edge *edge)
278 return is_type(edge, isl_edge_condition);
281 /* Is "edge" marked as a conditional validity edge?
283 static int is_conditional_validity(struct isl_sched_edge *edge)
285 return is_type(edge, isl_edge_conditional_validity);
288 /* Internal information about the dependence graph used during
289 * the construction of the schedule.
291 * intra_hmap is a cache, mapping dependence relations to their dual,
292 * for dependences from a node to itself, possibly without
293 * coefficients for the parameters
294 * intra_hmap_param is a cache, mapping dependence relations to their dual,
295 * for dependences from a node to itself, including coefficients
296 * for the parameters
297 * inter_hmap is a cache, mapping dependence relations to their dual,
298 * for dependences between distinct nodes
299 * if compression is involved then the key for these maps
300 * is the original, uncompressed dependence relation, while
301 * the value is the dual of the compressed dependence relation.
303 * n is the number of nodes
304 * node is the list of nodes
305 * maxvar is the maximal number of variables over all nodes
306 * max_row is the allocated number of rows in the schedule
307 * n_row is the current (maximal) number of linearly independent
308 * rows in the node schedules
309 * n_total_row is the current number of rows in the node schedules
310 * band_start is the starting row in the node schedules of the current band
311 * root is set to the the original dependence graph from which this graph
312 * is derived through splitting. If this graph is not the result of
313 * splitting, then the root field points to the graph itself.
315 * sorted contains a list of node indices sorted according to the
316 * SCC to which a node belongs
318 * n_edge is the number of edges
319 * edge is the list of edges
320 * max_edge contains the maximal number of edges of each type;
321 * in particular, it contains the number of edges in the inital graph.
322 * edge_table contains pointers into the edge array, hashed on the source
323 * and sink spaces; there is one such table for each type;
324 * a given edge may be referenced from more than one table
325 * if the corresponding relation appears in more than one of the
326 * sets of dependences; however, for each type there is only
327 * a single edge between a given pair of source and sink space
328 * in the entire graph
330 * node_table contains pointers into the node array, hashed on the space tuples
332 * region contains a list of variable sequences that should be non-trivial
334 * lp contains the (I)LP problem used to obtain new schedule rows
336 * src_scc and dst_scc are the source and sink SCCs of an edge with
337 * conflicting constraints
339 * scc represents the number of components
340 * weak is set if the components are weakly connected
342 * max_weight is used during clustering and represents the maximal
343 * weight of the relevant proximity edges.
345 struct isl_sched_graph {
346 isl_map_to_basic_set *intra_hmap;
347 isl_map_to_basic_set *intra_hmap_param;
348 isl_map_to_basic_set *inter_hmap;
350 struct isl_sched_node *node;
351 int n;
352 int maxvar;
353 int max_row;
354 int n_row;
356 int *sorted;
358 int n_total_row;
359 int band_start;
361 struct isl_sched_graph *root;
363 struct isl_sched_edge *edge;
364 int n_edge;
365 int max_edge[isl_edge_last + 1];
366 struct isl_hash_table *edge_table[isl_edge_last + 1];
368 struct isl_hash_table *node_table;
369 struct isl_trivial_region *region;
371 isl_basic_set *lp;
373 int src_scc;
374 int dst_scc;
376 int scc;
377 int weak;
379 int max_weight;
382 /* Initialize node_table based on the list of nodes.
384 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
386 int i;
388 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
389 if (!graph->node_table)
390 return -1;
392 for (i = 0; i < graph->n; ++i) {
393 struct isl_hash_table_entry *entry;
394 uint32_t hash;
396 hash = isl_space_get_tuple_hash(graph->node[i].space);
397 entry = isl_hash_table_find(ctx, graph->node_table, hash,
398 &node_has_tuples,
399 graph->node[i].space, 1);
400 if (!entry)
401 return -1;
402 entry->data = &graph->node[i];
405 return 0;
408 /* Return a pointer to the node that lives within the given space,
409 * or NULL if there is no such node.
411 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
412 struct isl_sched_graph *graph, __isl_keep isl_space *space)
414 struct isl_hash_table_entry *entry;
415 uint32_t hash;
417 hash = isl_space_get_tuple_hash(space);
418 entry = isl_hash_table_find(ctx, graph->node_table, hash,
419 &node_has_tuples, space, 0);
421 return entry ? entry->data : NULL;
424 /* Is "node" a node in "graph"?
426 static int is_node(struct isl_sched_graph *graph,
427 struct isl_sched_node *node)
429 return node && node >= &graph->node[0] && node < &graph->node[graph->n];
432 static int edge_has_src_and_dst(const void *entry, const void *val)
434 const struct isl_sched_edge *edge = entry;
435 const struct isl_sched_edge *temp = val;
437 return edge->src == temp->src && edge->dst == temp->dst;
440 /* Add the given edge to graph->edge_table[type].
442 static isl_stat graph_edge_table_add(isl_ctx *ctx,
443 struct isl_sched_graph *graph, enum isl_edge_type type,
444 struct isl_sched_edge *edge)
446 struct isl_hash_table_entry *entry;
447 uint32_t hash;
449 hash = isl_hash_init();
450 hash = isl_hash_builtin(hash, edge->src);
451 hash = isl_hash_builtin(hash, edge->dst);
452 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
453 &edge_has_src_and_dst, edge, 1);
454 if (!entry)
455 return isl_stat_error;
456 entry->data = edge;
458 return isl_stat_ok;
461 /* Allocate the edge_tables based on the maximal number of edges of
462 * each type.
464 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
466 int i;
468 for (i = 0; i <= isl_edge_last; ++i) {
469 graph->edge_table[i] = isl_hash_table_alloc(ctx,
470 graph->max_edge[i]);
471 if (!graph->edge_table[i])
472 return -1;
475 return 0;
478 /* If graph->edge_table[type] contains an edge from the given source
479 * to the given destination, then return the hash table entry of this edge.
480 * Otherwise, return NULL.
482 static struct isl_hash_table_entry *graph_find_edge_entry(
483 struct isl_sched_graph *graph,
484 enum isl_edge_type type,
485 struct isl_sched_node *src, struct isl_sched_node *dst)
487 isl_ctx *ctx = isl_space_get_ctx(src->space);
488 uint32_t hash;
489 struct isl_sched_edge temp = { .src = src, .dst = dst };
491 hash = isl_hash_init();
492 hash = isl_hash_builtin(hash, temp.src);
493 hash = isl_hash_builtin(hash, temp.dst);
494 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
495 &edge_has_src_and_dst, &temp, 0);
499 /* If graph->edge_table[type] contains an edge from the given source
500 * to the given destination, then return this edge.
501 * Otherwise, return NULL.
503 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
504 enum isl_edge_type type,
505 struct isl_sched_node *src, struct isl_sched_node *dst)
507 struct isl_hash_table_entry *entry;
509 entry = graph_find_edge_entry(graph, type, src, dst);
510 if (!entry)
511 return NULL;
513 return entry->data;
516 /* Check whether the dependence graph has an edge of the given type
517 * between the given two nodes.
519 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
520 enum isl_edge_type type,
521 struct isl_sched_node *src, struct isl_sched_node *dst)
523 struct isl_sched_edge *edge;
524 isl_bool empty;
526 edge = graph_find_edge(graph, type, src, dst);
527 if (!edge)
528 return 0;
530 empty = isl_map_plain_is_empty(edge->map);
531 if (empty < 0)
532 return isl_bool_error;
534 return !empty;
537 /* Look for any edge with the same src, dst and map fields as "model".
539 * Return the matching edge if one can be found.
540 * Return "model" if no matching edge is found.
541 * Return NULL on error.
543 static struct isl_sched_edge *graph_find_matching_edge(
544 struct isl_sched_graph *graph, struct isl_sched_edge *model)
546 enum isl_edge_type i;
547 struct isl_sched_edge *edge;
549 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
550 int is_equal;
552 edge = graph_find_edge(graph, i, model->src, model->dst);
553 if (!edge)
554 continue;
555 is_equal = isl_map_plain_is_equal(model->map, edge->map);
556 if (is_equal < 0)
557 return NULL;
558 if (is_equal)
559 return edge;
562 return model;
565 /* Remove the given edge from all the edge_tables that refer to it.
567 static void graph_remove_edge(struct isl_sched_graph *graph,
568 struct isl_sched_edge *edge)
570 isl_ctx *ctx = isl_map_get_ctx(edge->map);
571 enum isl_edge_type i;
573 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
574 struct isl_hash_table_entry *entry;
576 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
577 if (!entry)
578 continue;
579 if (entry->data != edge)
580 continue;
581 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
585 /* Check whether the dependence graph has any edge
586 * between the given two nodes.
588 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
589 struct isl_sched_node *src, struct isl_sched_node *dst)
591 enum isl_edge_type i;
592 isl_bool r;
594 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
595 r = graph_has_edge(graph, i, src, dst);
596 if (r < 0 || r)
597 return r;
600 return r;
603 /* Check whether the dependence graph has a validity edge
604 * between the given two nodes.
606 * Conditional validity edges are essentially validity edges that
607 * can be ignored if the corresponding condition edges are iteration private.
608 * Here, we are only checking for the presence of validity
609 * edges, so we need to consider the conditional validity edges too.
610 * In particular, this function is used during the detection
611 * of strongly connected components and we cannot ignore
612 * conditional validity edges during this detection.
614 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
615 struct isl_sched_node *src, struct isl_sched_node *dst)
617 isl_bool r;
619 r = graph_has_edge(graph, isl_edge_validity, src, dst);
620 if (r < 0 || r)
621 return r;
623 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
626 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
627 int n_node, int n_edge)
629 int i;
631 graph->n = n_node;
632 graph->n_edge = n_edge;
633 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
634 graph->sorted = isl_calloc_array(ctx, int, graph->n);
635 graph->region = isl_alloc_array(ctx,
636 struct isl_trivial_region, graph->n);
637 graph->edge = isl_calloc_array(ctx,
638 struct isl_sched_edge, graph->n_edge);
640 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
641 graph->intra_hmap_param = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
642 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
644 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
645 !graph->sorted)
646 return -1;
648 for(i = 0; i < graph->n; ++i)
649 graph->sorted[i] = i;
651 return 0;
654 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
656 int i;
658 isl_map_to_basic_set_free(graph->intra_hmap);
659 isl_map_to_basic_set_free(graph->intra_hmap_param);
660 isl_map_to_basic_set_free(graph->inter_hmap);
662 if (graph->node)
663 for (i = 0; i < graph->n; ++i) {
664 isl_space_free(graph->node[i].space);
665 isl_set_free(graph->node[i].hull);
666 isl_multi_aff_free(graph->node[i].compress);
667 isl_multi_aff_free(graph->node[i].decompress);
668 isl_mat_free(graph->node[i].sched);
669 isl_map_free(graph->node[i].sched_map);
670 isl_mat_free(graph->node[i].indep);
671 isl_mat_free(graph->node[i].vmap);
672 if (graph->root == graph)
673 free(graph->node[i].coincident);
674 isl_multi_val_free(graph->node[i].sizes);
675 isl_basic_set_free(graph->node[i].bounds);
676 isl_vec_free(graph->node[i].max);
678 free(graph->node);
679 free(graph->sorted);
680 if (graph->edge)
681 for (i = 0; i < graph->n_edge; ++i) {
682 isl_map_free(graph->edge[i].map);
683 isl_union_map_free(graph->edge[i].tagged_condition);
684 isl_union_map_free(graph->edge[i].tagged_validity);
686 free(graph->edge);
687 free(graph->region);
688 for (i = 0; i <= isl_edge_last; ++i)
689 isl_hash_table_free(ctx, graph->edge_table[i]);
690 isl_hash_table_free(ctx, graph->node_table);
691 isl_basic_set_free(graph->lp);
694 /* For each "set" on which this function is called, increment
695 * graph->n by one and update graph->maxvar.
697 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
699 struct isl_sched_graph *graph = user;
700 int nvar = isl_set_dim(set, isl_dim_set);
702 graph->n++;
703 if (nvar > graph->maxvar)
704 graph->maxvar = nvar;
706 isl_set_free(set);
708 return isl_stat_ok;
711 /* Compute the number of rows that should be allocated for the schedule.
712 * In particular, we need one row for each variable or one row
713 * for each basic map in the dependences.
714 * Note that it is practically impossible to exhaust both
715 * the number of dependences and the number of variables.
717 static isl_stat compute_max_row(struct isl_sched_graph *graph,
718 __isl_keep isl_schedule_constraints *sc)
720 int n_edge;
721 isl_stat r;
722 isl_union_set *domain;
724 graph->n = 0;
725 graph->maxvar = 0;
726 domain = isl_schedule_constraints_get_domain(sc);
727 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
728 isl_union_set_free(domain);
729 if (r < 0)
730 return isl_stat_error;
731 n_edge = isl_schedule_constraints_n_basic_map(sc);
732 if (n_edge < 0)
733 return isl_stat_error;
734 graph->max_row = n_edge + graph->maxvar;
736 return isl_stat_ok;
739 /* Does "bset" have any defining equalities for its set variables?
741 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
743 int i, n;
745 if (!bset)
746 return isl_bool_error;
748 n = isl_basic_set_dim(bset, isl_dim_set);
749 for (i = 0; i < n; ++i) {
750 isl_bool has;
752 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
753 NULL);
754 if (has < 0 || has)
755 return has;
758 return isl_bool_false;
761 /* Set the entries of node->max to the value of the schedule_max_coefficient
762 * option, if set.
764 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
766 int max;
768 max = isl_options_get_schedule_max_coefficient(ctx);
769 if (max == -1)
770 return isl_stat_ok;
772 node->max = isl_vec_alloc(ctx, node->nvar);
773 node->max = isl_vec_set_si(node->max, max);
774 if (!node->max)
775 return isl_stat_error;
777 return isl_stat_ok;
780 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
781 * option (if set) and half of the minimum of the sizes in the other
782 * dimensions. Round up when computing the half such that
783 * if the minimum of the sizes is one, half of the size is taken to be one
784 * rather than zero.
785 * If the global minimum is unbounded (i.e., if both
786 * the schedule_max_coefficient is not set and the sizes in the other
787 * dimensions are unbounded), then store a negative value.
788 * If the schedule coefficient is close to the size of the instance set
789 * in another dimension, then the schedule may represent a loop
790 * coalescing transformation (especially if the coefficient
791 * in that other dimension is one). Forcing the coefficient to be
792 * smaller than or equal to half the minimal size should avoid this
793 * situation.
795 static isl_stat compute_max_coefficient(isl_ctx *ctx,
796 struct isl_sched_node *node)
798 int max;
799 int i, j;
800 isl_vec *v;
802 max = isl_options_get_schedule_max_coefficient(ctx);
803 v = isl_vec_alloc(ctx, node->nvar);
804 if (!v)
805 return isl_stat_error;
807 for (i = 0; i < node->nvar; ++i) {
808 isl_int_set_si(v->el[i], max);
809 isl_int_mul_si(v->el[i], v->el[i], 2);
812 for (i = 0; i < node->nvar; ++i) {
813 isl_val *size;
815 size = isl_multi_val_get_val(node->sizes, i);
816 if (!size)
817 goto error;
818 if (!isl_val_is_int(size)) {
819 isl_val_free(size);
820 continue;
822 for (j = 0; j < node->nvar; ++j) {
823 if (j == i)
824 continue;
825 if (isl_int_is_neg(v->el[j]) ||
826 isl_int_gt(v->el[j], size->n))
827 isl_int_set(v->el[j], size->n);
829 isl_val_free(size);
832 for (i = 0; i < node->nvar; ++i)
833 isl_int_cdiv_q_ui(v->el[i], v->el[i], 2);
835 node->max = v;
836 return isl_stat_ok;
837 error:
838 isl_vec_free(v);
839 return isl_stat_error;
842 /* Compute and return the size of "set" in dimension "dim".
843 * The size is taken to be the difference in values for that variable
844 * for fixed values of the other variables.
845 * In particular, the variable is first isolated from the other variables
846 * in the range of a map
848 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
850 * and then duplicated
852 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
854 * The shared variables are then projected out and the maximal value
855 * of i_dim' - i_dim is computed.
857 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
859 isl_map *map;
860 isl_local_space *ls;
861 isl_aff *obj;
862 isl_val *v;
864 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
865 map = isl_map_project_out(map, isl_dim_in, dim, 1);
866 map = isl_map_range_product(map, isl_map_copy(map));
867 map = isl_set_unwrap(isl_map_range(map));
868 set = isl_map_deltas(map);
869 ls = isl_local_space_from_space(isl_set_get_space(set));
870 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
871 v = isl_set_max_val(set, obj);
872 isl_aff_free(obj);
873 isl_set_free(set);
875 return v;
878 /* Compute the size of the instance set "set" of "node", after compression,
879 * as well as bounds on the corresponding coefficients, if needed.
881 * The sizes are needed when the schedule_treat_coalescing option is set.
882 * The bounds are needed when the schedule_treat_coalescing option or
883 * the schedule_max_coefficient option is set.
885 * If the schedule_treat_coalescing option is not set, then at most
886 * the bounds need to be set and this is done in set_max_coefficient.
887 * Otherwise, compress the domain if needed, compute the size
888 * in each direction and store the results in node->size.
889 * Finally, set the bounds on the coefficients based on the sizes
890 * and the schedule_max_coefficient option in compute_max_coefficient.
892 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
893 __isl_take isl_set *set)
895 int j, n;
896 isl_multi_val *mv;
898 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
899 isl_set_free(set);
900 return set_max_coefficient(ctx, node);
903 if (node->compressed)
904 set = isl_set_preimage_multi_aff(set,
905 isl_multi_aff_copy(node->decompress));
906 mv = isl_multi_val_zero(isl_set_get_space(set));
907 n = isl_set_dim(set, isl_dim_set);
908 for (j = 0; j < n; ++j) {
909 isl_val *v;
911 v = compute_size(isl_set_copy(set), j);
912 mv = isl_multi_val_set_val(mv, j, v);
914 node->sizes = mv;
915 isl_set_free(set);
916 if (!node->sizes)
917 return isl_stat_error;
918 return compute_max_coefficient(ctx, node);
921 /* Add a new node to the graph representing the given instance set.
922 * "nvar" is the (possibly compressed) number of variables and
923 * may be smaller than then number of set variables in "set"
924 * if "compressed" is set.
925 * If "compressed" is set, then "hull" represents the constraints
926 * that were used to derive the compression, while "compress" and
927 * "decompress" map the original space to the compressed space and
928 * vice versa.
929 * If "compressed" is not set, then "hull", "compress" and "decompress"
930 * should be NULL.
932 * Compute the size of the instance set and bounds on the coefficients,
933 * if needed.
935 static isl_stat add_node(struct isl_sched_graph *graph,
936 __isl_take isl_set *set, int nvar, int compressed,
937 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
938 __isl_take isl_multi_aff *decompress)
940 int nparam;
941 isl_ctx *ctx;
942 isl_mat *sched;
943 isl_space *space;
944 int *coincident;
945 struct isl_sched_node *node;
947 if (!set)
948 return isl_stat_error;
950 ctx = isl_set_get_ctx(set);
951 nparam = isl_set_dim(set, isl_dim_param);
952 if (!ctx->opt->schedule_parametric)
953 nparam = 0;
954 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
955 node = &graph->node[graph->n];
956 graph->n++;
957 space = isl_set_get_space(set);
958 node->space = space;
959 node->nvar = nvar;
960 node->nparam = nparam;
961 node->sched = sched;
962 node->sched_map = NULL;
963 coincident = isl_calloc_array(ctx, int, graph->max_row);
964 node->coincident = coincident;
965 node->compressed = compressed;
966 node->hull = hull;
967 node->compress = compress;
968 node->decompress = decompress;
969 if (compute_sizes_and_max(ctx, node, set) < 0)
970 return isl_stat_error;
972 if (!space || !sched || (graph->max_row && !coincident))
973 return isl_stat_error;
974 if (compressed && (!hull || !compress || !decompress))
975 return isl_stat_error;
977 return isl_stat_ok;
980 /* Construct an identifier for node "node", which will represent "set".
981 * The name of the identifier is either "compressed" or
982 * "compressed_<name>", with <name> the name of the space of "set".
983 * The user pointer of the identifier points to "node".
985 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
986 struct isl_sched_node *node)
988 isl_bool has_name;
989 isl_ctx *ctx;
990 isl_id *id;
991 isl_printer *p;
992 const char *name;
993 char *id_name;
995 has_name = isl_set_has_tuple_name(set);
996 if (has_name < 0)
997 return NULL;
999 ctx = isl_set_get_ctx(set);
1000 if (!has_name)
1001 return isl_id_alloc(ctx, "compressed", node);
1003 p = isl_printer_to_str(ctx);
1004 name = isl_set_get_tuple_name(set);
1005 p = isl_printer_print_str(p, "compressed_");
1006 p = isl_printer_print_str(p, name);
1007 id_name = isl_printer_get_str(p);
1008 isl_printer_free(p);
1010 id = isl_id_alloc(ctx, id_name, node);
1011 free(id_name);
1013 return id;
1016 /* Add a new node to the graph representing the given set.
1018 * If any of the set variables is defined by an equality, then
1019 * we perform variable compression such that we can perform
1020 * the scheduling on the compressed domain.
1021 * In this case, an identifier is used that references the new node
1022 * such that each compressed space is unique and
1023 * such that the node can be recovered from the compressed space.
1025 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1027 int nvar;
1028 isl_bool has_equality;
1029 isl_id *id;
1030 isl_basic_set *hull;
1031 isl_set *hull_set;
1032 isl_morph *morph;
1033 isl_multi_aff *compress, *decompress;
1034 struct isl_sched_graph *graph = user;
1036 hull = isl_set_affine_hull(isl_set_copy(set));
1037 hull = isl_basic_set_remove_divs(hull);
1038 nvar = isl_set_dim(set, isl_dim_set);
1039 has_equality = has_any_defining_equality(hull);
1041 if (has_equality < 0)
1042 goto error;
1043 if (!has_equality) {
1044 isl_basic_set_free(hull);
1045 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1048 id = construct_compressed_id(set, &graph->node[graph->n]);
1049 morph = isl_basic_set_variable_compression_with_id(hull,
1050 isl_dim_set, id);
1051 isl_id_free(id);
1052 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1053 compress = isl_morph_get_var_multi_aff(morph);
1054 morph = isl_morph_inverse(morph);
1055 decompress = isl_morph_get_var_multi_aff(morph);
1056 isl_morph_free(morph);
1058 hull_set = isl_set_from_basic_set(hull);
1059 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1060 error:
1061 isl_basic_set_free(hull);
1062 isl_set_free(set);
1063 return isl_stat_error;
1066 struct isl_extract_edge_data {
1067 enum isl_edge_type type;
1068 struct isl_sched_graph *graph;
1071 /* Merge edge2 into edge1, freeing the contents of edge2.
1072 * Return 0 on success and -1 on failure.
1074 * edge1 and edge2 are assumed to have the same value for the map field.
1076 static int merge_edge(struct isl_sched_edge *edge1,
1077 struct isl_sched_edge *edge2)
1079 edge1->types |= edge2->types;
1080 isl_map_free(edge2->map);
1082 if (is_condition(edge2)) {
1083 if (!edge1->tagged_condition)
1084 edge1->tagged_condition = edge2->tagged_condition;
1085 else
1086 edge1->tagged_condition =
1087 isl_union_map_union(edge1->tagged_condition,
1088 edge2->tagged_condition);
1091 if (is_conditional_validity(edge2)) {
1092 if (!edge1->tagged_validity)
1093 edge1->tagged_validity = edge2->tagged_validity;
1094 else
1095 edge1->tagged_validity =
1096 isl_union_map_union(edge1->tagged_validity,
1097 edge2->tagged_validity);
1100 if (is_condition(edge2) && !edge1->tagged_condition)
1101 return -1;
1102 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1103 return -1;
1105 return 0;
1108 /* Insert dummy tags in domain and range of "map".
1110 * In particular, if "map" is of the form
1112 * A -> B
1114 * then return
1116 * [A -> dummy_tag] -> [B -> dummy_tag]
1118 * where the dummy_tags are identical and equal to any dummy tags
1119 * introduced by any other call to this function.
1121 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1123 static char dummy;
1124 isl_ctx *ctx;
1125 isl_id *id;
1126 isl_space *space;
1127 isl_set *domain, *range;
1129 ctx = isl_map_get_ctx(map);
1131 id = isl_id_alloc(ctx, NULL, &dummy);
1132 space = isl_space_params(isl_map_get_space(map));
1133 space = isl_space_set_from_params(space);
1134 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1135 space = isl_space_map_from_set(space);
1137 domain = isl_map_wrap(map);
1138 range = isl_map_wrap(isl_map_universe(space));
1139 map = isl_map_from_domain_and_range(domain, range);
1140 map = isl_map_zip(map);
1142 return map;
1145 /* Given that at least one of "src" or "dst" is compressed, return
1146 * a map between the spaces of these nodes restricted to the affine
1147 * hull that was used in the compression.
1149 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1150 struct isl_sched_node *dst)
1152 isl_set *dom, *ran;
1154 if (src->compressed)
1155 dom = isl_set_copy(src->hull);
1156 else
1157 dom = isl_set_universe(isl_space_copy(src->space));
1158 if (dst->compressed)
1159 ran = isl_set_copy(dst->hull);
1160 else
1161 ran = isl_set_universe(isl_space_copy(dst->space));
1163 return isl_map_from_domain_and_range(dom, ran);
1166 /* Intersect the domains of the nested relations in domain and range
1167 * of "tagged" with "map".
1169 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1170 __isl_keep isl_map *map)
1172 isl_set *set;
1174 tagged = isl_map_zip(tagged);
1175 set = isl_map_wrap(isl_map_copy(map));
1176 tagged = isl_map_intersect_domain(tagged, set);
1177 tagged = isl_map_zip(tagged);
1178 return tagged;
1181 /* Return a pointer to the node that lives in the domain space of "map"
1182 * or NULL if there is no such node.
1184 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1185 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1187 struct isl_sched_node *node;
1188 isl_space *space;
1190 space = isl_space_domain(isl_map_get_space(map));
1191 node = graph_find_node(ctx, graph, space);
1192 isl_space_free(space);
1194 return node;
1197 /* Return a pointer to the node that lives in the range space of "map"
1198 * or NULL if there is no such node.
1200 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1201 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1203 struct isl_sched_node *node;
1204 isl_space *space;
1206 space = isl_space_range(isl_map_get_space(map));
1207 node = graph_find_node(ctx, graph, space);
1208 isl_space_free(space);
1210 return node;
1213 /* Add a new edge to the graph based on the given map
1214 * and add it to data->graph->edge_table[data->type].
1215 * If a dependence relation of a given type happens to be identical
1216 * to one of the dependence relations of a type that was added before,
1217 * then we don't create a new edge, but instead mark the original edge
1218 * as also representing a dependence of the current type.
1220 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1221 * may be specified as "tagged" dependence relations. That is, "map"
1222 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1223 * the dependence on iterations and a and b are tags.
1224 * edge->map is set to the relation containing the elements i -> j,
1225 * while edge->tagged_condition and edge->tagged_validity contain
1226 * the union of all the "map" relations
1227 * for which extract_edge is called that result in the same edge->map.
1229 * If the source or the destination node is compressed, then
1230 * intersect both "map" and "tagged" with the constraints that
1231 * were used to construct the compression.
1232 * This ensures that there are no schedule constraints defined
1233 * outside of these domains, while the scheduler no longer has
1234 * any control over those outside parts.
1236 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1238 isl_ctx *ctx = isl_map_get_ctx(map);
1239 struct isl_extract_edge_data *data = user;
1240 struct isl_sched_graph *graph = data->graph;
1241 struct isl_sched_node *src, *dst;
1242 struct isl_sched_edge *edge;
1243 isl_map *tagged = NULL;
1245 if (data->type == isl_edge_condition ||
1246 data->type == isl_edge_conditional_validity) {
1247 if (isl_map_can_zip(map)) {
1248 tagged = isl_map_copy(map);
1249 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1250 } else {
1251 tagged = insert_dummy_tags(isl_map_copy(map));
1255 src = find_domain_node(ctx, graph, map);
1256 dst = find_range_node(ctx, graph, map);
1258 if (!src || !dst) {
1259 isl_map_free(map);
1260 isl_map_free(tagged);
1261 return isl_stat_ok;
1264 if (src->compressed || dst->compressed) {
1265 isl_map *hull;
1266 hull = extract_hull(src, dst);
1267 if (tagged)
1268 tagged = map_intersect_domains(tagged, hull);
1269 map = isl_map_intersect(map, hull);
1272 graph->edge[graph->n_edge].src = src;
1273 graph->edge[graph->n_edge].dst = dst;
1274 graph->edge[graph->n_edge].map = map;
1275 graph->edge[graph->n_edge].types = 0;
1276 graph->edge[graph->n_edge].tagged_condition = NULL;
1277 graph->edge[graph->n_edge].tagged_validity = NULL;
1278 set_type(&graph->edge[graph->n_edge], data->type);
1279 if (data->type == isl_edge_condition)
1280 graph->edge[graph->n_edge].tagged_condition =
1281 isl_union_map_from_map(tagged);
1282 if (data->type == isl_edge_conditional_validity)
1283 graph->edge[graph->n_edge].tagged_validity =
1284 isl_union_map_from_map(tagged);
1286 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1287 if (!edge) {
1288 graph->n_edge++;
1289 return isl_stat_error;
1291 if (edge == &graph->edge[graph->n_edge])
1292 return graph_edge_table_add(ctx, graph, data->type,
1293 &graph->edge[graph->n_edge++]);
1295 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1296 return -1;
1298 return graph_edge_table_add(ctx, graph, data->type, edge);
1301 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1303 * The context is included in the domain before the nodes of
1304 * the graphs are extracted in order to be able to exploit
1305 * any possible additional equalities.
1306 * Note that this intersection is only performed locally here.
1308 static isl_stat graph_init(struct isl_sched_graph *graph,
1309 __isl_keep isl_schedule_constraints *sc)
1311 isl_ctx *ctx;
1312 isl_union_set *domain;
1313 isl_union_map *c;
1314 struct isl_extract_edge_data data;
1315 enum isl_edge_type i;
1316 isl_stat r;
1318 if (!sc)
1319 return isl_stat_error;
1321 ctx = isl_schedule_constraints_get_ctx(sc);
1323 domain = isl_schedule_constraints_get_domain(sc);
1324 graph->n = isl_union_set_n_set(domain);
1325 isl_union_set_free(domain);
1327 if (graph_alloc(ctx, graph, graph->n,
1328 isl_schedule_constraints_n_map(sc)) < 0)
1329 return isl_stat_error;
1331 if (compute_max_row(graph, sc) < 0)
1332 return isl_stat_error;
1333 graph->root = graph;
1334 graph->n = 0;
1335 domain = isl_schedule_constraints_get_domain(sc);
1336 domain = isl_union_set_intersect_params(domain,
1337 isl_schedule_constraints_get_context(sc));
1338 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1339 isl_union_set_free(domain);
1340 if (r < 0)
1341 return isl_stat_error;
1342 if (graph_init_table(ctx, graph) < 0)
1343 return isl_stat_error;
1344 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1345 c = isl_schedule_constraints_get(sc, i);
1346 graph->max_edge[i] = isl_union_map_n_map(c);
1347 isl_union_map_free(c);
1348 if (!c)
1349 return isl_stat_error;
1351 if (graph_init_edge_tables(ctx, graph) < 0)
1352 return isl_stat_error;
1353 graph->n_edge = 0;
1354 data.graph = graph;
1355 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1356 isl_stat r;
1358 data.type = i;
1359 c = isl_schedule_constraints_get(sc, i);
1360 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1361 isl_union_map_free(c);
1362 if (r < 0)
1363 return isl_stat_error;
1366 return isl_stat_ok;
1369 /* Check whether there is any dependence from node[j] to node[i]
1370 * or from node[i] to node[j].
1372 static isl_bool node_follows_weak(int i, int j, void *user)
1374 isl_bool f;
1375 struct isl_sched_graph *graph = user;
1377 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1378 if (f < 0 || f)
1379 return f;
1380 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1383 /* Check whether there is a (conditional) validity dependence from node[j]
1384 * to node[i], forcing node[i] to follow node[j].
1386 static isl_bool node_follows_strong(int i, int j, void *user)
1388 struct isl_sched_graph *graph = user;
1390 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1393 /* Use Tarjan's algorithm for computing the strongly connected components
1394 * in the dependence graph only considering those edges defined by "follows".
1396 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1397 isl_bool (*follows)(int i, int j, void *user))
1399 int i, n;
1400 struct isl_tarjan_graph *g = NULL;
1402 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1403 if (!g)
1404 return -1;
1406 graph->scc = 0;
1407 i = 0;
1408 n = graph->n;
1409 while (n) {
1410 while (g->order[i] != -1) {
1411 graph->node[g->order[i]].scc = graph->scc;
1412 --n;
1413 ++i;
1415 ++i;
1416 graph->scc++;
1419 isl_tarjan_graph_free(g);
1421 return 0;
1424 /* Apply Tarjan's algorithm to detect the strongly connected components
1425 * in the dependence graph.
1426 * Only consider the (conditional) validity dependences and clear "weak".
1428 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1430 graph->weak = 0;
1431 return detect_ccs(ctx, graph, &node_follows_strong);
1434 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1435 * in the dependence graph.
1436 * Consider all dependences and set "weak".
1438 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1440 graph->weak = 1;
1441 return detect_ccs(ctx, graph, &node_follows_weak);
1444 static int cmp_scc(const void *a, const void *b, void *data)
1446 struct isl_sched_graph *graph = data;
1447 const int *i1 = a;
1448 const int *i2 = b;
1450 return graph->node[*i1].scc - graph->node[*i2].scc;
1453 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1455 static int sort_sccs(struct isl_sched_graph *graph)
1457 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1460 /* Return a non-parametric set in the compressed space of "node" that is
1461 * bounded by the size in each direction
1463 * { [x] : -S_i <= x_i <= S_i }
1465 * If S_i is infinity in direction i, then there are no constraints
1466 * in that direction.
1468 * Cache the result in node->bounds.
1470 static __isl_give isl_basic_set *get_size_bounds(struct isl_sched_node *node)
1472 isl_space *space;
1473 isl_basic_set *bounds;
1474 int i;
1475 unsigned nparam;
1477 if (node->bounds)
1478 return isl_basic_set_copy(node->bounds);
1480 if (node->compressed)
1481 space = isl_multi_aff_get_domain_space(node->decompress);
1482 else
1483 space = isl_space_copy(node->space);
1484 nparam = isl_space_dim(space, isl_dim_param);
1485 space = isl_space_drop_dims(space, isl_dim_param, 0, nparam);
1486 bounds = isl_basic_set_universe(space);
1488 for (i = 0; i < node->nvar; ++i) {
1489 isl_val *size;
1491 size = isl_multi_val_get_val(node->sizes, i);
1492 if (!size)
1493 return isl_basic_set_free(bounds);
1494 if (!isl_val_is_int(size)) {
1495 isl_val_free(size);
1496 continue;
1498 bounds = isl_basic_set_upper_bound_val(bounds, isl_dim_set, i,
1499 isl_val_copy(size));
1500 bounds = isl_basic_set_lower_bound_val(bounds, isl_dim_set, i,
1501 isl_val_neg(size));
1504 node->bounds = isl_basic_set_copy(bounds);
1505 return bounds;
1508 /* Drop some constraints from "delta" that could be exploited
1509 * to construct loop coalescing schedules.
1510 * In particular, drop those constraint that bound the difference
1511 * to the size of the domain.
1512 * First project out the parameters to improve the effectiveness.
1514 static __isl_give isl_set *drop_coalescing_constraints(
1515 __isl_take isl_set *delta, struct isl_sched_node *node)
1517 unsigned nparam;
1518 isl_basic_set *bounds;
1520 bounds = get_size_bounds(node);
1522 nparam = isl_set_dim(delta, isl_dim_param);
1523 delta = isl_set_project_out(delta, isl_dim_param, 0, nparam);
1524 delta = isl_set_remove_divs(delta);
1525 delta = isl_set_plain_gist_basic_set(delta, bounds);
1526 return delta;
1529 /* Given a dependence relation R from "node" to itself,
1530 * construct the set of coefficients of valid constraints for elements
1531 * in that dependence relation.
1532 * In particular, the result contains tuples of coefficients
1533 * c_0, c_n, c_x such that
1535 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1537 * or, equivalently,
1539 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1541 * We choose here to compute the dual of delta R.
1542 * Alternatively, we could have computed the dual of R, resulting
1543 * in a set of tuples c_0, c_n, c_x, c_y, and then
1544 * plugged in (c_0, c_n, c_x, -c_x).
1546 * If "need_param" is set, then the resulting coefficients effectively
1547 * include coefficients for the parameters c_n. Otherwise, they may
1548 * have been projected out already.
1549 * Since the constraints may be different for these two cases,
1550 * they are stored in separate caches.
1551 * In particular, if no parameter coefficients are required and
1552 * the schedule_treat_coalescing option is set, then the parameters
1553 * are projected out and some constraints that could be exploited
1554 * to construct coalescing schedules are removed before the dual
1555 * is computed.
1557 * If "node" has been compressed, then the dependence relation
1558 * is also compressed before the set of coefficients is computed.
1560 static __isl_give isl_basic_set *intra_coefficients(
1561 struct isl_sched_graph *graph, struct isl_sched_node *node,
1562 __isl_take isl_map *map, int need_param)
1564 isl_ctx *ctx;
1565 isl_set *delta;
1566 isl_map *key;
1567 isl_basic_set *coef;
1568 isl_maybe_isl_basic_set m;
1569 isl_map_to_basic_set **hmap = &graph->intra_hmap;
1570 int treat;
1572 if (!map)
1573 return NULL;
1575 ctx = isl_map_get_ctx(map);
1576 treat = !need_param && isl_options_get_schedule_treat_coalescing(ctx);
1577 if (!treat)
1578 hmap = &graph->intra_hmap_param;
1579 m = isl_map_to_basic_set_try_get(*hmap, map);
1580 if (m.valid < 0 || m.valid) {
1581 isl_map_free(map);
1582 return m.value;
1585 key = isl_map_copy(map);
1586 if (node->compressed) {
1587 map = isl_map_preimage_domain_multi_aff(map,
1588 isl_multi_aff_copy(node->decompress));
1589 map = isl_map_preimage_range_multi_aff(map,
1590 isl_multi_aff_copy(node->decompress));
1592 delta = isl_map_deltas(map);
1593 if (treat)
1594 delta = drop_coalescing_constraints(delta, node);
1595 delta = isl_set_remove_divs(delta);
1596 coef = isl_set_coefficients(delta);
1597 *hmap = isl_map_to_basic_set_set(*hmap, key, isl_basic_set_copy(coef));
1599 return coef;
1602 /* Given a dependence relation R, construct the set of coefficients
1603 * of valid constraints for elements in that dependence relation.
1604 * In particular, the result contains tuples of coefficients
1605 * c_0, c_n, c_x, c_y such that
1607 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1609 * If the source or destination nodes of "edge" have been compressed,
1610 * then the dependence relation is also compressed before
1611 * the set of coefficients is computed.
1613 static __isl_give isl_basic_set *inter_coefficients(
1614 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1615 __isl_take isl_map *map)
1617 isl_set *set;
1618 isl_map *key;
1619 isl_basic_set *coef;
1620 isl_maybe_isl_basic_set m;
1622 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1623 if (m.valid < 0 || m.valid) {
1624 isl_map_free(map);
1625 return m.value;
1628 key = isl_map_copy(map);
1629 if (edge->src->compressed)
1630 map = isl_map_preimage_domain_multi_aff(map,
1631 isl_multi_aff_copy(edge->src->decompress));
1632 if (edge->dst->compressed)
1633 map = isl_map_preimage_range_multi_aff(map,
1634 isl_multi_aff_copy(edge->dst->decompress));
1635 set = isl_map_wrap(isl_map_remove_divs(map));
1636 coef = isl_set_coefficients(set);
1637 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1638 isl_basic_set_copy(coef));
1640 return coef;
1643 /* Return the position of the coefficients of the variables in
1644 * the coefficients constraints "coef".
1646 * The space of "coef" is of the form
1648 * { coefficients[[cst, params] -> S] }
1650 * Return the position of S.
1652 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1654 int offset;
1655 isl_space *space;
1657 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1658 offset = isl_space_dim(space, isl_dim_in);
1659 isl_space_free(space);
1661 return offset;
1664 /* Return the offset of the coefficient of the constant term of "node"
1665 * within the (I)LP.
1667 * Within each node, the coefficients have the following order:
1668 * - positive and negative parts of c_i_x
1669 * - c_i_n (if parametric)
1670 * - c_i_0
1672 static int node_cst_coef_offset(struct isl_sched_node *node)
1674 return node->start + 2 * node->nvar + node->nparam;
1677 /* Return the offset of the coefficients of the parameters of "node"
1678 * within the (I)LP.
1680 * Within each node, the coefficients have the following order:
1681 * - positive and negative parts of c_i_x
1682 * - c_i_n (if parametric)
1683 * - c_i_0
1685 static int node_par_coef_offset(struct isl_sched_node *node)
1687 return node->start + 2 * node->nvar;
1690 /* Return the offset of the coefficients of the variables of "node"
1691 * within the (I)LP.
1693 * Within each node, the coefficients have the following order:
1694 * - positive and negative parts of c_i_x
1695 * - c_i_n (if parametric)
1696 * - c_i_0
1698 static int node_var_coef_offset(struct isl_sched_node *node)
1700 return node->start;
1703 /* Return the position of the pair of variables encoding
1704 * coefficient "i" of "node".
1706 * The order of these variable pairs is the opposite of
1707 * that of the coefficients, with 2 variables per coefficient.
1709 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1711 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1714 /* Construct an isl_dim_map for mapping constraints on coefficients
1715 * for "node" to the corresponding positions in graph->lp.
1716 * "offset" is the offset of the coefficients for the variables
1717 * in the input constraints.
1718 * "s" is the sign of the mapping.
1720 * The input constraints are given in terms of the coefficients
1721 * (c_0, c_x) or (c_0, c_n, c_x).
1722 * The mapping produced by this function essentially plugs in
1723 * (0, c_i_x^+ - c_i_x^-) if s = 1 and
1724 * (0, -c_i_x^+ + c_i_x^-) if s = -1 or
1725 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1726 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1727 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1728 * Furthermore, the order of these pairs is the opposite of that
1729 * of the corresponding coefficients.
1731 * The caller can extend the mapping to also map the other coefficients
1732 * (and therefore not plug in 0).
1734 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1735 struct isl_sched_graph *graph, struct isl_sched_node *node,
1736 int offset, int s)
1738 int pos;
1739 unsigned total;
1740 isl_dim_map *dim_map;
1742 if (!node)
1743 return NULL;
1745 total = isl_basic_set_total_dim(graph->lp);
1746 pos = node_var_coef_pos(node, 0);
1747 dim_map = isl_dim_map_alloc(ctx, total);
1748 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1749 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1751 return dim_map;
1754 /* Construct an isl_dim_map for mapping constraints on coefficients
1755 * for "src" (node i) and "dst" (node j) to the corresponding positions
1756 * in graph->lp.
1757 * "offset" is the offset of the coefficients for the variables of "src"
1758 * in the input constraints.
1759 * "s" is the sign of the mapping.
1761 * The input constraints are given in terms of the coefficients
1762 * (c_0, c_n, c_x, c_y).
1763 * The mapping produced by this function essentially plugs in
1764 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1765 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1766 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1767 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1768 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1769 * Furthermore, the order of these pairs is the opposite of that
1770 * of the corresponding coefficients.
1772 * The caller can further extend the mapping.
1774 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1775 struct isl_sched_graph *graph, struct isl_sched_node *src,
1776 struct isl_sched_node *dst, int offset, int s)
1778 int pos;
1779 unsigned total;
1780 isl_dim_map *dim_map;
1782 if (!src || !dst)
1783 return NULL;
1785 total = isl_basic_set_total_dim(graph->lp);
1786 dim_map = isl_dim_map_alloc(ctx, total);
1788 pos = node_cst_coef_offset(dst);
1789 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1790 pos = node_par_coef_offset(dst);
1791 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1792 pos = node_var_coef_pos(dst, 0);
1793 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1794 dst->nvar, -s);
1795 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1796 dst->nvar, s);
1798 pos = node_cst_coef_offset(src);
1799 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1800 pos = node_par_coef_offset(src);
1801 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1802 pos = node_var_coef_pos(src, 0);
1803 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1804 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1806 return dim_map;
1809 /* Add the constraints from "src" to "dst" using "dim_map",
1810 * after making sure there is enough room in "dst" for the extra constraints.
1812 static __isl_give isl_basic_set *add_constraints_dim_map(
1813 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1814 __isl_take isl_dim_map *dim_map)
1816 int n_eq, n_ineq;
1818 n_eq = isl_basic_set_n_equality(src);
1819 n_ineq = isl_basic_set_n_inequality(src);
1820 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1821 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1822 return dst;
1825 /* Add constraints to graph->lp that force validity for the given
1826 * dependence from a node i to itself.
1827 * That is, add constraints that enforce
1829 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1830 * = c_i_x (y - x) >= 0
1832 * for each (x,y) in R.
1833 * We obtain general constraints on coefficients (c_0, c_x)
1834 * of valid constraints for (y - x) and then plug in (0, c_i_x^+ - c_i_x^-),
1835 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1836 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1837 * Note that the result of intra_coefficients may also contain
1838 * parameter coefficients c_n, in which case 0 is plugged in for them as well.
1840 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1841 struct isl_sched_edge *edge)
1843 int offset;
1844 isl_map *map = isl_map_copy(edge->map);
1845 isl_ctx *ctx = isl_map_get_ctx(map);
1846 isl_dim_map *dim_map;
1847 isl_basic_set *coef;
1848 struct isl_sched_node *node = edge->src;
1850 coef = intra_coefficients(graph, node, map, 0);
1852 offset = coef_var_offset(coef);
1854 if (!coef)
1855 return isl_stat_error;
1857 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1858 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1860 return isl_stat_ok;
1863 /* Add constraints to graph->lp that force validity for the given
1864 * dependence from node i to node j.
1865 * That is, add constraints that enforce
1867 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1869 * for each (x,y) in R.
1870 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1871 * of valid constraints for R and then plug in
1872 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1873 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1874 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1876 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1877 struct isl_sched_edge *edge)
1879 int offset;
1880 isl_map *map;
1881 isl_ctx *ctx;
1882 isl_dim_map *dim_map;
1883 isl_basic_set *coef;
1884 struct isl_sched_node *src = edge->src;
1885 struct isl_sched_node *dst = edge->dst;
1887 if (!graph->lp)
1888 return isl_stat_error;
1890 map = isl_map_copy(edge->map);
1891 ctx = isl_map_get_ctx(map);
1892 coef = inter_coefficients(graph, edge, map);
1894 offset = coef_var_offset(coef);
1896 if (!coef)
1897 return isl_stat_error;
1899 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1901 edge->start = graph->lp->n_ineq;
1902 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1903 if (!graph->lp)
1904 return isl_stat_error;
1905 edge->end = graph->lp->n_ineq;
1907 return isl_stat_ok;
1910 /* Add constraints to graph->lp that bound the dependence distance for the given
1911 * dependence from a node i to itself.
1912 * If s = 1, we add the constraint
1914 * c_i_x (y - x) <= m_0 + m_n n
1916 * or
1918 * -c_i_x (y - x) + m_0 + m_n n >= 0
1920 * for each (x,y) in R.
1921 * If s = -1, we add the constraint
1923 * -c_i_x (y - x) <= m_0 + m_n n
1925 * or
1927 * c_i_x (y - x) + m_0 + m_n n >= 0
1929 * for each (x,y) in R.
1930 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1931 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1932 * with each coefficient (except m_0) represented as a pair of non-negative
1933 * coefficients.
1936 * If "local" is set, then we add constraints
1938 * c_i_x (y - x) <= 0
1940 * or
1942 * -c_i_x (y - x) <= 0
1944 * instead, forcing the dependence distance to be (less than or) equal to 0.
1945 * That is, we plug in (0, 0, -s * c_i_x),
1946 * intra_coefficients is not required to have c_n in its result when
1947 * "local" is set. If they are missing, then (0, -s * c_i_x) is plugged in.
1948 * Note that dependences marked local are treated as validity constraints
1949 * by add_all_validity_constraints and therefore also have
1950 * their distances bounded by 0 from below.
1952 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1953 struct isl_sched_edge *edge, int s, int local)
1955 int offset;
1956 unsigned nparam;
1957 isl_map *map = isl_map_copy(edge->map);
1958 isl_ctx *ctx = isl_map_get_ctx(map);
1959 isl_dim_map *dim_map;
1960 isl_basic_set *coef;
1961 struct isl_sched_node *node = edge->src;
1963 coef = intra_coefficients(graph, node, map, !local);
1965 offset = coef_var_offset(coef);
1967 if (!coef)
1968 return isl_stat_error;
1970 nparam = isl_space_dim(node->space, isl_dim_param);
1971 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1973 if (!local) {
1974 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1975 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1976 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1978 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1980 return isl_stat_ok;
1983 /* Add constraints to graph->lp that bound the dependence distance for the given
1984 * dependence from node i to node j.
1985 * If s = 1, we add the constraint
1987 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1988 * <= m_0 + m_n n
1990 * or
1992 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1993 * m_0 + m_n n >= 0
1995 * for each (x,y) in R.
1996 * If s = -1, we add the constraint
1998 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1999 * <= m_0 + m_n n
2001 * or
2003 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
2004 * m_0 + m_n n >= 0
2006 * for each (x,y) in R.
2007 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
2008 * of valid constraints for R and then plug in
2009 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
2010 * s*c_i_x, -s*c_j_x)
2011 * with each coefficient (except m_0, c_*_0 and c_*_n)
2012 * represented as a pair of non-negative coefficients.
2015 * If "local" is set (and s = 1), then we add constraints
2017 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
2019 * or
2021 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
2023 * instead, forcing the dependence distance to be (less than or) equal to 0.
2024 * That is, we plug in
2025 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
2026 * Note that dependences marked local are treated as validity constraints
2027 * by add_all_validity_constraints and therefore also have
2028 * their distances bounded by 0 from below.
2030 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
2031 struct isl_sched_edge *edge, int s, int local)
2033 int offset;
2034 unsigned nparam;
2035 isl_map *map = isl_map_copy(edge->map);
2036 isl_ctx *ctx = isl_map_get_ctx(map);
2037 isl_dim_map *dim_map;
2038 isl_basic_set *coef;
2039 struct isl_sched_node *src = edge->src;
2040 struct isl_sched_node *dst = edge->dst;
2042 coef = inter_coefficients(graph, edge, map);
2044 offset = coef_var_offset(coef);
2046 if (!coef)
2047 return isl_stat_error;
2049 nparam = isl_space_dim(src->space, isl_dim_param);
2050 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
2052 if (!local) {
2053 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2054 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2055 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2058 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2060 return isl_stat_ok;
2063 /* Should the distance over "edge" be forced to zero?
2064 * That is, is it marked as a local edge?
2065 * If "use_coincidence" is set, then coincidence edges are treated
2066 * as local edges.
2068 static int force_zero(struct isl_sched_edge *edge, int use_coincidence)
2070 return is_local(edge) || (use_coincidence && is_coincidence(edge));
2073 /* Add all validity constraints to graph->lp.
2075 * An edge that is forced to be local needs to have its dependence
2076 * distances equal to zero. We take care of bounding them by 0 from below
2077 * here. add_all_proximity_constraints takes care of bounding them by 0
2078 * from above.
2080 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2081 * Otherwise, we ignore them.
2083 static int add_all_validity_constraints(struct isl_sched_graph *graph,
2084 int use_coincidence)
2086 int i;
2088 for (i = 0; i < graph->n_edge; ++i) {
2089 struct isl_sched_edge *edge = &graph->edge[i];
2090 int zero;
2092 zero = force_zero(edge, use_coincidence);
2093 if (!is_validity(edge) && !zero)
2094 continue;
2095 if (edge->src != edge->dst)
2096 continue;
2097 if (add_intra_validity_constraints(graph, edge) < 0)
2098 return -1;
2101 for (i = 0; i < graph->n_edge; ++i) {
2102 struct isl_sched_edge *edge = &graph->edge[i];
2103 int zero;
2105 zero = force_zero(edge, use_coincidence);
2106 if (!is_validity(edge) && !zero)
2107 continue;
2108 if (edge->src == edge->dst)
2109 continue;
2110 if (add_inter_validity_constraints(graph, edge) < 0)
2111 return -1;
2114 return 0;
2117 /* Add constraints to graph->lp that bound the dependence distance
2118 * for all dependence relations.
2119 * If a given proximity dependence is identical to a validity
2120 * dependence, then the dependence distance is already bounded
2121 * from below (by zero), so we only need to bound the distance
2122 * from above. (This includes the case of "local" dependences
2123 * which are treated as validity dependence by add_all_validity_constraints.)
2124 * Otherwise, we need to bound the distance both from above and from below.
2126 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2127 * Otherwise, we ignore them.
2129 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2130 int use_coincidence)
2132 int i;
2134 for (i = 0; i < graph->n_edge; ++i) {
2135 struct isl_sched_edge *edge = &graph->edge[i];
2136 int zero;
2138 zero = force_zero(edge, use_coincidence);
2139 if (!is_proximity(edge) && !zero)
2140 continue;
2141 if (edge->src == edge->dst &&
2142 add_intra_proximity_constraints(graph, edge, 1, zero) < 0)
2143 return -1;
2144 if (edge->src != edge->dst &&
2145 add_inter_proximity_constraints(graph, edge, 1, zero) < 0)
2146 return -1;
2147 if (is_validity(edge) || zero)
2148 continue;
2149 if (edge->src == edge->dst &&
2150 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2151 return -1;
2152 if (edge->src != edge->dst &&
2153 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2154 return -1;
2157 return 0;
2160 /* Normalize the rows of "indep" such that all rows are lexicographically
2161 * positive and such that each row contains as many final zeros as possible,
2162 * given the choice for the previous rows.
2163 * Do this by performing elementary row operations.
2165 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2167 indep = isl_mat_reverse_gauss(indep);
2168 indep = isl_mat_lexnonneg_rows(indep);
2169 return indep;
2172 /* Compute a basis for the rows in the linear part of the schedule
2173 * and extend this basis to a full basis. The remaining rows
2174 * can then be used to force linear independence from the rows
2175 * in the schedule.
2177 * In particular, given the schedule rows S, we compute
2179 * S = H Q
2180 * S U = H
2182 * with H the Hermite normal form of S. That is, all but the
2183 * first rank columns of H are zero and so each row in S is
2184 * a linear combination of the first rank rows of Q.
2185 * The matrix Q can be used as a variable transformation
2186 * that isolates the directions of S in the first rank rows.
2187 * Transposing S U = H yields
2189 * U^T S^T = H^T
2191 * with all but the first rank rows of H^T zero.
2192 * The last rows of U^T are therefore linear combinations
2193 * of schedule coefficients that are all zero on schedule
2194 * coefficients that are linearly dependent on the rows of S.
2195 * At least one of these combinations is non-zero on
2196 * linearly independent schedule coefficients.
2197 * The rows are normalized to involve as few of the last
2198 * coefficients as possible and to have a positive initial value.
2200 static int node_update_vmap(struct isl_sched_node *node)
2202 isl_mat *H, *U, *Q;
2203 int n_row = isl_mat_rows(node->sched);
2205 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2206 1 + node->nparam, node->nvar);
2208 H = isl_mat_left_hermite(H, 0, &U, &Q);
2209 isl_mat_free(node->indep);
2210 isl_mat_free(node->vmap);
2211 node->vmap = Q;
2212 node->indep = isl_mat_transpose(U);
2213 node->rank = isl_mat_initial_non_zero_cols(H);
2214 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2215 node->indep = normalize_independent(node->indep);
2216 isl_mat_free(H);
2218 if (!node->indep || !node->vmap || node->rank < 0)
2219 return -1;
2220 return 0;
2223 /* Is "edge" marked as a validity or a conditional validity edge?
2225 static int is_any_validity(struct isl_sched_edge *edge)
2227 return is_validity(edge) || is_conditional_validity(edge);
2230 /* How many times should we count the constraints in "edge"?
2232 * We count as follows
2233 * validity -> 1 (>= 0)
2234 * validity+proximity -> 2 (>= 0 and upper bound)
2235 * proximity -> 2 (lower and upper bound)
2236 * local(+any) -> 2 (>= 0 and <= 0)
2238 * If an edge is only marked conditional_validity then it counts
2239 * as zero since it is only checked afterwards.
2241 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2242 * Otherwise, we ignore them.
2244 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2246 if (is_proximity(edge) || force_zero(edge, use_coincidence))
2247 return 2;
2248 if (is_validity(edge))
2249 return 1;
2250 return 0;
2253 /* How many times should the constraints in "edge" be counted
2254 * as a parametric intra-node constraint?
2256 * Only proximity edges that are not forced zero need
2257 * coefficient constraints that include coefficients for parameters.
2258 * If the edge is also a validity edge, then only
2259 * an upper bound is introduced. Otherwise, both lower and upper bounds
2260 * are introduced.
2262 static int parametric_intra_edge_multiplicity(struct isl_sched_edge *edge,
2263 int use_coincidence)
2265 if (edge->src != edge->dst)
2266 return 0;
2267 if (!is_proximity(edge))
2268 return 0;
2269 if (force_zero(edge, use_coincidence))
2270 return 0;
2271 if (is_validity(edge))
2272 return 1;
2273 else
2274 return 2;
2277 /* Add "f" times the number of equality and inequality constraints of "bset"
2278 * to "n_eq" and "n_ineq" and free "bset".
2280 static isl_stat update_count(__isl_take isl_basic_set *bset,
2281 int f, int *n_eq, int *n_ineq)
2283 if (!bset)
2284 return isl_stat_error;
2286 *n_eq += isl_basic_set_n_equality(bset);
2287 *n_ineq += isl_basic_set_n_inequality(bset);
2288 isl_basic_set_free(bset);
2290 return isl_stat_ok;
2293 /* Count the number of equality and inequality constraints
2294 * that will be added for the given map.
2296 * The edges that require parameter coefficients are counted separately.
2298 * "use_coincidence" is set if we should take into account coincidence edges.
2300 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2301 struct isl_sched_edge *edge, __isl_take isl_map *map,
2302 int *n_eq, int *n_ineq, int use_coincidence)
2304 isl_map *copy;
2305 isl_basic_set *coef;
2306 int f = edge_multiplicity(edge, use_coincidence);
2307 int fp = parametric_intra_edge_multiplicity(edge, use_coincidence);
2309 if (f == 0) {
2310 isl_map_free(map);
2311 return isl_stat_ok;
2314 if (edge->src != edge->dst) {
2315 coef = inter_coefficients(graph, edge, map);
2316 return update_count(coef, f, n_eq, n_ineq);
2319 if (fp > 0) {
2320 copy = isl_map_copy(map);
2321 coef = intra_coefficients(graph, edge->src, copy, 1);
2322 if (update_count(coef, fp, n_eq, n_ineq) < 0)
2323 goto error;
2326 if (f > fp) {
2327 copy = isl_map_copy(map);
2328 coef = intra_coefficients(graph, edge->src, copy, 0);
2329 if (update_count(coef, f - fp, n_eq, n_ineq) < 0)
2330 goto error;
2333 isl_map_free(map);
2334 return isl_stat_ok;
2335 error:
2336 isl_map_free(map);
2337 return isl_stat_error;
2340 /* Count the number of equality and inequality constraints
2341 * that will be added to the main lp problem.
2342 * We count as follows
2343 * validity -> 1 (>= 0)
2344 * validity+proximity -> 2 (>= 0 and upper bound)
2345 * proximity -> 2 (lower and upper bound)
2346 * local(+any) -> 2 (>= 0 and <= 0)
2348 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2349 * Otherwise, we ignore them.
2351 static int count_constraints(struct isl_sched_graph *graph,
2352 int *n_eq, int *n_ineq, int use_coincidence)
2354 int i;
2356 *n_eq = *n_ineq = 0;
2357 for (i = 0; i < graph->n_edge; ++i) {
2358 struct isl_sched_edge *edge = &graph->edge[i];
2359 isl_map *map = isl_map_copy(edge->map);
2361 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2362 use_coincidence) < 0)
2363 return -1;
2366 return 0;
2369 /* Count the number of constraints that will be added by
2370 * add_bound_constant_constraints to bound the values of the constant terms
2371 * and increment *n_eq and *n_ineq accordingly.
2373 * In practice, add_bound_constant_constraints only adds inequalities.
2375 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2376 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2378 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2379 return isl_stat_ok;
2381 *n_ineq += graph->n;
2383 return isl_stat_ok;
2386 /* Add constraints to bound the values of the constant terms in the schedule,
2387 * if requested by the user.
2389 * The maximal value of the constant terms is defined by the option
2390 * "schedule_max_constant_term".
2392 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2393 struct isl_sched_graph *graph)
2395 int i, k;
2396 int max;
2397 int total;
2399 max = isl_options_get_schedule_max_constant_term(ctx);
2400 if (max == -1)
2401 return isl_stat_ok;
2403 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2405 for (i = 0; i < graph->n; ++i) {
2406 struct isl_sched_node *node = &graph->node[i];
2407 int pos;
2409 k = isl_basic_set_alloc_inequality(graph->lp);
2410 if (k < 0)
2411 return isl_stat_error;
2412 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2413 pos = node_cst_coef_offset(node);
2414 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2415 isl_int_set_si(graph->lp->ineq[k][0], max);
2418 return isl_stat_ok;
2421 /* Count the number of constraints that will be added by
2422 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2423 * accordingly.
2425 * In practice, add_bound_coefficient_constraints only adds inequalities.
2427 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2428 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2430 int i;
2432 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2433 !isl_options_get_schedule_treat_coalescing(ctx))
2434 return 0;
2436 for (i = 0; i < graph->n; ++i)
2437 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2439 return 0;
2442 /* Add constraints to graph->lp that bound the values of
2443 * the parameter schedule coefficients of "node" to "max" and
2444 * the variable schedule coefficients to the corresponding entry
2445 * in node->max.
2446 * In either case, a negative value means that no bound needs to be imposed.
2448 * For parameter coefficients, this amounts to adding a constraint
2450 * c_n <= max
2452 * i.e.,
2454 * -c_n + max >= 0
2456 * The variables coefficients are, however, not represented directly.
2457 * Instead, the variable coefficients c_x are written as differences
2458 * c_x = c_x^+ - c_x^-.
2459 * That is,
2461 * -max_i <= c_x_i <= max_i
2463 * is encoded as
2465 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2467 * or
2469 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2470 * c_x_i^+ - c_x_i^- + max_i >= 0
2472 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2473 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2475 int i, j, k;
2476 int total;
2477 isl_vec *ineq;
2479 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2481 for (j = 0; j < node->nparam; ++j) {
2482 int dim;
2484 if (max < 0)
2485 continue;
2487 k = isl_basic_set_alloc_inequality(graph->lp);
2488 if (k < 0)
2489 return isl_stat_error;
2490 dim = 1 + node_par_coef_offset(node) + j;
2491 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2492 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2493 isl_int_set_si(graph->lp->ineq[k][0], max);
2496 ineq = isl_vec_alloc(ctx, 1 + total);
2497 ineq = isl_vec_clr(ineq);
2498 if (!ineq)
2499 return isl_stat_error;
2500 for (i = 0; i < node->nvar; ++i) {
2501 int pos = 1 + node_var_coef_pos(node, i);
2503 if (isl_int_is_neg(node->max->el[i]))
2504 continue;
2506 isl_int_set_si(ineq->el[pos], 1);
2507 isl_int_set_si(ineq->el[pos + 1], -1);
2508 isl_int_set(ineq->el[0], node->max->el[i]);
2510 k = isl_basic_set_alloc_inequality(graph->lp);
2511 if (k < 0)
2512 goto error;
2513 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2515 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2);
2516 k = isl_basic_set_alloc_inequality(graph->lp);
2517 if (k < 0)
2518 goto error;
2519 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2521 isl_seq_clr(ineq->el + pos, 2);
2523 isl_vec_free(ineq);
2525 return isl_stat_ok;
2526 error:
2527 isl_vec_free(ineq);
2528 return isl_stat_error;
2531 /* Add constraints that bound the values of the variable and parameter
2532 * coefficients of the schedule.
2534 * The maximal value of the coefficients is defined by the option
2535 * 'schedule_max_coefficient' and the entries in node->max.
2536 * These latter entries are only set if either the schedule_max_coefficient
2537 * option or the schedule_treat_coalescing option is set.
2539 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2540 struct isl_sched_graph *graph)
2542 int i;
2543 int max;
2545 max = isl_options_get_schedule_max_coefficient(ctx);
2547 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2548 return isl_stat_ok;
2550 for (i = 0; i < graph->n; ++i) {
2551 struct isl_sched_node *node = &graph->node[i];
2553 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2554 return isl_stat_error;
2557 return isl_stat_ok;
2560 /* Add a constraint to graph->lp that equates the value at position
2561 * "sum_pos" to the sum of the "n" values starting at "first".
2563 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2564 int sum_pos, int first, int n)
2566 int i, k;
2567 int total;
2569 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2571 k = isl_basic_set_alloc_equality(graph->lp);
2572 if (k < 0)
2573 return isl_stat_error;
2574 isl_seq_clr(graph->lp->eq[k], 1 + total);
2575 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2576 for (i = 0; i < n; ++i)
2577 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2579 return isl_stat_ok;
2582 /* Add a constraint to graph->lp that equates the value at position
2583 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2585 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2586 int sum_pos)
2588 int i, j, k;
2589 int total;
2591 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2593 k = isl_basic_set_alloc_equality(graph->lp);
2594 if (k < 0)
2595 return isl_stat_error;
2596 isl_seq_clr(graph->lp->eq[k], 1 + total);
2597 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2598 for (i = 0; i < graph->n; ++i) {
2599 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2601 for (j = 0; j < graph->node[i].nparam; ++j)
2602 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2605 return isl_stat_ok;
2608 /* Add a constraint to graph->lp that equates the value at position
2609 * "sum_pos" to the sum of the variable coefficients of all nodes.
2611 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2612 int sum_pos)
2614 int i, j, k;
2615 int total;
2617 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2619 k = isl_basic_set_alloc_equality(graph->lp);
2620 if (k < 0)
2621 return isl_stat_error;
2622 isl_seq_clr(graph->lp->eq[k], 1 + total);
2623 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2624 for (i = 0; i < graph->n; ++i) {
2625 struct isl_sched_node *node = &graph->node[i];
2626 int pos = 1 + node_var_coef_offset(node);
2628 for (j = 0; j < 2 * node->nvar; ++j)
2629 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2632 return isl_stat_ok;
2635 /* Construct an ILP problem for finding schedule coefficients
2636 * that result in non-negative, but small dependence distances
2637 * over all dependences.
2638 * In particular, the dependence distances over proximity edges
2639 * are bounded by m_0 + m_n n and we compute schedule coefficients
2640 * with small values (preferably zero) of m_n and m_0.
2642 * All variables of the ILP are non-negative. The actual coefficients
2643 * may be negative, so each coefficient is represented as the difference
2644 * of two non-negative variables. The negative part always appears
2645 * immediately before the positive part.
2646 * Other than that, the variables have the following order
2648 * - sum of positive and negative parts of m_n coefficients
2649 * - m_0
2650 * - sum of all c_n coefficients
2651 * (unconstrained when computing non-parametric schedules)
2652 * - sum of positive and negative parts of all c_x coefficients
2653 * - positive and negative parts of m_n coefficients
2654 * - for each node
2655 * - positive and negative parts of c_i_x, in opposite order
2656 * - c_i_n (if parametric)
2657 * - c_i_0
2659 * The constraints are those from the edges plus two or three equalities
2660 * to express the sums.
2662 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2663 * Otherwise, we ignore them.
2665 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2666 int use_coincidence)
2668 int i;
2669 unsigned nparam;
2670 unsigned total;
2671 isl_space *space;
2672 int parametric;
2673 int param_pos;
2674 int n_eq, n_ineq;
2676 parametric = ctx->opt->schedule_parametric;
2677 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2678 param_pos = 4;
2679 total = param_pos + 2 * nparam;
2680 for (i = 0; i < graph->n; ++i) {
2681 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2682 if (node_update_vmap(node) < 0)
2683 return isl_stat_error;
2684 node->start = total;
2685 total += 1 + node->nparam + 2 * node->nvar;
2688 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2689 return isl_stat_error;
2690 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2691 return isl_stat_error;
2692 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2693 return isl_stat_error;
2695 space = isl_space_set_alloc(ctx, 0, total);
2696 isl_basic_set_free(graph->lp);
2697 n_eq += 2 + parametric;
2699 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2701 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2702 return isl_stat_error;
2703 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2704 return isl_stat_error;
2705 if (add_var_sum_constraint(graph, 3) < 0)
2706 return isl_stat_error;
2707 if (add_bound_constant_constraints(ctx, graph) < 0)
2708 return isl_stat_error;
2709 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2710 return isl_stat_error;
2711 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2712 return isl_stat_error;
2713 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2714 return isl_stat_error;
2716 return isl_stat_ok;
2719 /* Analyze the conflicting constraint found by
2720 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2721 * constraint of one of the edges between distinct nodes, living, moreover
2722 * in distinct SCCs, then record the source and sink SCC as this may
2723 * be a good place to cut between SCCs.
2725 static int check_conflict(int con, void *user)
2727 int i;
2728 struct isl_sched_graph *graph = user;
2730 if (graph->src_scc >= 0)
2731 return 0;
2733 con -= graph->lp->n_eq;
2735 if (con >= graph->lp->n_ineq)
2736 return 0;
2738 for (i = 0; i < graph->n_edge; ++i) {
2739 if (!is_validity(&graph->edge[i]))
2740 continue;
2741 if (graph->edge[i].src == graph->edge[i].dst)
2742 continue;
2743 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2744 continue;
2745 if (graph->edge[i].start > con)
2746 continue;
2747 if (graph->edge[i].end <= con)
2748 continue;
2749 graph->src_scc = graph->edge[i].src->scc;
2750 graph->dst_scc = graph->edge[i].dst->scc;
2753 return 0;
2756 /* Check whether the next schedule row of the given node needs to be
2757 * non-trivial. Lower-dimensional domains may have some trivial rows,
2758 * but as soon as the number of remaining required non-trivial rows
2759 * is as large as the number or remaining rows to be computed,
2760 * all remaining rows need to be non-trivial.
2762 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2764 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2767 /* Construct a non-triviality region with triviality directions
2768 * corresponding to the rows of "indep".
2769 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2770 * while the triviality directions are expressed in terms of
2771 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2772 * before c^+_i. Furthermore,
2773 * the pairs of non-negative variables representing the coefficients
2774 * are stored in the opposite order.
2776 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2778 isl_ctx *ctx;
2779 isl_mat *mat;
2780 int i, j, n, n_var;
2782 if (!indep)
2783 return NULL;
2785 ctx = isl_mat_get_ctx(indep);
2786 n = isl_mat_rows(indep);
2787 n_var = isl_mat_cols(indep);
2788 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2789 if (!mat)
2790 return NULL;
2791 for (i = 0; i < n; ++i) {
2792 for (j = 0; j < n_var; ++j) {
2793 int nj = n_var - 1 - j;
2794 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2795 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2799 return mat;
2802 /* Solve the ILP problem constructed in setup_lp.
2803 * For each node such that all the remaining rows of its schedule
2804 * need to be non-trivial, we construct a non-triviality region.
2805 * This region imposes that the next row is independent of previous rows.
2806 * In particular, the non-triviality region enforces that at least
2807 * one of the linear combinations in the rows of node->indep is non-zero.
2809 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2811 int i;
2812 isl_vec *sol;
2813 isl_basic_set *lp;
2815 for (i = 0; i < graph->n; ++i) {
2816 struct isl_sched_node *node = &graph->node[i];
2817 isl_mat *trivial;
2819 graph->region[i].pos = node_var_coef_offset(node);
2820 if (needs_row(graph, node))
2821 trivial = construct_trivial(node->indep);
2822 else
2823 trivial = isl_mat_zero(ctx, 0, 0);
2824 graph->region[i].trivial = trivial;
2826 lp = isl_basic_set_copy(graph->lp);
2827 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2828 graph->region, &check_conflict, graph);
2829 for (i = 0; i < graph->n; ++i)
2830 isl_mat_free(graph->region[i].trivial);
2831 return sol;
2834 /* Extract the coefficients for the variables of "node" from "sol".
2836 * Each schedule coefficient c_i_x is represented as the difference
2837 * between two non-negative variables c_i_x^+ - c_i_x^-.
2838 * The c_i_x^- appear before their c_i_x^+ counterpart.
2839 * Furthermore, the order of these pairs is the opposite of that
2840 * of the corresponding coefficients.
2842 * Return c_i_x = c_i_x^+ - c_i_x^-
2844 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2845 __isl_keep isl_vec *sol)
2847 int i;
2848 int pos;
2849 isl_vec *csol;
2851 if (!sol)
2852 return NULL;
2853 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2854 if (!csol)
2855 return NULL;
2857 pos = 1 + node_var_coef_offset(node);
2858 for (i = 0; i < node->nvar; ++i)
2859 isl_int_sub(csol->el[node->nvar - 1 - i],
2860 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2862 return csol;
2865 /* Update the schedules of all nodes based on the given solution
2866 * of the LP problem.
2867 * The new row is added to the current band.
2868 * All possibly negative coefficients are encoded as a difference
2869 * of two non-negative variables, so we need to perform the subtraction
2870 * here.
2872 * If coincident is set, then the caller guarantees that the new
2873 * row satisfies the coincidence constraints.
2875 static int update_schedule(struct isl_sched_graph *graph,
2876 __isl_take isl_vec *sol, int coincident)
2878 int i, j;
2879 isl_vec *csol = NULL;
2881 if (!sol)
2882 goto error;
2883 if (sol->size == 0)
2884 isl_die(sol->ctx, isl_error_internal,
2885 "no solution found", goto error);
2886 if (graph->n_total_row >= graph->max_row)
2887 isl_die(sol->ctx, isl_error_internal,
2888 "too many schedule rows", goto error);
2890 for (i = 0; i < graph->n; ++i) {
2891 struct isl_sched_node *node = &graph->node[i];
2892 int pos;
2893 int row = isl_mat_rows(node->sched);
2895 isl_vec_free(csol);
2896 csol = extract_var_coef(node, sol);
2897 if (!csol)
2898 goto error;
2900 isl_map_free(node->sched_map);
2901 node->sched_map = NULL;
2902 node->sched = isl_mat_add_rows(node->sched, 1);
2903 if (!node->sched)
2904 goto error;
2905 pos = node_cst_coef_offset(node);
2906 node->sched = isl_mat_set_element(node->sched,
2907 row, 0, sol->el[1 + pos]);
2908 pos = node_par_coef_offset(node);
2909 for (j = 0; j < node->nparam; ++j)
2910 node->sched = isl_mat_set_element(node->sched,
2911 row, 1 + j, sol->el[1 + pos + j]);
2912 for (j = 0; j < node->nvar; ++j)
2913 node->sched = isl_mat_set_element(node->sched,
2914 row, 1 + node->nparam + j, csol->el[j]);
2915 node->coincident[graph->n_total_row] = coincident;
2917 isl_vec_free(sol);
2918 isl_vec_free(csol);
2920 graph->n_row++;
2921 graph->n_total_row++;
2923 return 0;
2924 error:
2925 isl_vec_free(sol);
2926 isl_vec_free(csol);
2927 return -1;
2930 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2931 * and return this isl_aff.
2933 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2934 struct isl_sched_node *node, int row)
2936 int j;
2937 isl_int v;
2938 isl_aff *aff;
2940 isl_int_init(v);
2942 aff = isl_aff_zero_on_domain(ls);
2943 isl_mat_get_element(node->sched, row, 0, &v);
2944 aff = isl_aff_set_constant(aff, v);
2945 for (j = 0; j < node->nparam; ++j) {
2946 isl_mat_get_element(node->sched, row, 1 + j, &v);
2947 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2949 for (j = 0; j < node->nvar; ++j) {
2950 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2951 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2954 isl_int_clear(v);
2956 return aff;
2959 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2960 * and return this multi_aff.
2962 * The result is defined over the uncompressed node domain.
2964 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2965 struct isl_sched_node *node, int first, int n)
2967 int i;
2968 isl_space *space;
2969 isl_local_space *ls;
2970 isl_aff *aff;
2971 isl_multi_aff *ma;
2972 int nrow;
2974 if (!node)
2975 return NULL;
2976 nrow = isl_mat_rows(node->sched);
2977 if (node->compressed)
2978 space = isl_multi_aff_get_domain_space(node->decompress);
2979 else
2980 space = isl_space_copy(node->space);
2981 ls = isl_local_space_from_space(isl_space_copy(space));
2982 space = isl_space_from_domain(space);
2983 space = isl_space_add_dims(space, isl_dim_out, n);
2984 ma = isl_multi_aff_zero(space);
2986 for (i = first; i < first + n; ++i) {
2987 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2988 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2991 isl_local_space_free(ls);
2993 if (node->compressed)
2994 ma = isl_multi_aff_pullback_multi_aff(ma,
2995 isl_multi_aff_copy(node->compress));
2997 return ma;
3000 /* Convert node->sched into a multi_aff and return this multi_aff.
3002 * The result is defined over the uncompressed node domain.
3004 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
3005 struct isl_sched_node *node)
3007 int nrow;
3009 nrow = isl_mat_rows(node->sched);
3010 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
3013 /* Convert node->sched into a map and return this map.
3015 * The result is cached in node->sched_map, which needs to be released
3016 * whenever node->sched is updated.
3017 * It is defined over the uncompressed node domain.
3019 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
3021 if (!node->sched_map) {
3022 isl_multi_aff *ma;
3024 ma = node_extract_schedule_multi_aff(node);
3025 node->sched_map = isl_map_from_multi_aff(ma);
3028 return isl_map_copy(node->sched_map);
3031 /* Construct a map that can be used to update a dependence relation
3032 * based on the current schedule.
3033 * That is, construct a map expressing that source and sink
3034 * are executed within the same iteration of the current schedule.
3035 * This map can then be intersected with the dependence relation.
3036 * This is not the most efficient way, but this shouldn't be a critical
3037 * operation.
3039 static __isl_give isl_map *specializer(struct isl_sched_node *src,
3040 struct isl_sched_node *dst)
3042 isl_map *src_sched, *dst_sched;
3044 src_sched = node_extract_schedule(src);
3045 dst_sched = node_extract_schedule(dst);
3046 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
3049 /* Intersect the domains of the nested relations in domain and range
3050 * of "umap" with "map".
3052 static __isl_give isl_union_map *intersect_domains(
3053 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
3055 isl_union_set *uset;
3057 umap = isl_union_map_zip(umap);
3058 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
3059 umap = isl_union_map_intersect_domain(umap, uset);
3060 umap = isl_union_map_zip(umap);
3061 return umap;
3064 /* Update the dependence relation of the given edge based
3065 * on the current schedule.
3066 * If the dependence is carried completely by the current schedule, then
3067 * it is removed from the edge_tables. It is kept in the list of edges
3068 * as otherwise all edge_tables would have to be recomputed.
3070 static int update_edge(struct isl_sched_graph *graph,
3071 struct isl_sched_edge *edge)
3073 int empty;
3074 isl_map *id;
3076 id = specializer(edge->src, edge->dst);
3077 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
3078 if (!edge->map)
3079 goto error;
3081 if (edge->tagged_condition) {
3082 edge->tagged_condition =
3083 intersect_domains(edge->tagged_condition, id);
3084 if (!edge->tagged_condition)
3085 goto error;
3087 if (edge->tagged_validity) {
3088 edge->tagged_validity =
3089 intersect_domains(edge->tagged_validity, id);
3090 if (!edge->tagged_validity)
3091 goto error;
3094 empty = isl_map_plain_is_empty(edge->map);
3095 if (empty < 0)
3096 goto error;
3097 if (empty)
3098 graph_remove_edge(graph, edge);
3100 isl_map_free(id);
3101 return 0;
3102 error:
3103 isl_map_free(id);
3104 return -1;
3107 /* Does the domain of "umap" intersect "uset"?
3109 static int domain_intersects(__isl_keep isl_union_map *umap,
3110 __isl_keep isl_union_set *uset)
3112 int empty;
3114 umap = isl_union_map_copy(umap);
3115 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
3116 empty = isl_union_map_is_empty(umap);
3117 isl_union_map_free(umap);
3119 return empty < 0 ? -1 : !empty;
3122 /* Does the range of "umap" intersect "uset"?
3124 static int range_intersects(__isl_keep isl_union_map *umap,
3125 __isl_keep isl_union_set *uset)
3127 int empty;
3129 umap = isl_union_map_copy(umap);
3130 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
3131 empty = isl_union_map_is_empty(umap);
3132 isl_union_map_free(umap);
3134 return empty < 0 ? -1 : !empty;
3137 /* Are the condition dependences of "edge" local with respect to
3138 * the current schedule?
3140 * That is, are domain and range of the condition dependences mapped
3141 * to the same point?
3143 * In other words, is the condition false?
3145 static int is_condition_false(struct isl_sched_edge *edge)
3147 isl_union_map *umap;
3148 isl_map *map, *sched, *test;
3149 int empty, local;
3151 empty = isl_union_map_is_empty(edge->tagged_condition);
3152 if (empty < 0 || empty)
3153 return empty;
3155 umap = isl_union_map_copy(edge->tagged_condition);
3156 umap = isl_union_map_zip(umap);
3157 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3158 map = isl_map_from_union_map(umap);
3160 sched = node_extract_schedule(edge->src);
3161 map = isl_map_apply_domain(map, sched);
3162 sched = node_extract_schedule(edge->dst);
3163 map = isl_map_apply_range(map, sched);
3165 test = isl_map_identity(isl_map_get_space(map));
3166 local = isl_map_is_subset(map, test);
3167 isl_map_free(map);
3168 isl_map_free(test);
3170 return local;
3173 /* For each conditional validity constraint that is adjacent
3174 * to a condition with domain in condition_source or range in condition_sink,
3175 * turn it into an unconditional validity constraint.
3177 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3178 __isl_take isl_union_set *condition_source,
3179 __isl_take isl_union_set *condition_sink)
3181 int i;
3183 condition_source = isl_union_set_coalesce(condition_source);
3184 condition_sink = isl_union_set_coalesce(condition_sink);
3186 for (i = 0; i < graph->n_edge; ++i) {
3187 int adjacent;
3188 isl_union_map *validity;
3190 if (!is_conditional_validity(&graph->edge[i]))
3191 continue;
3192 if (is_validity(&graph->edge[i]))
3193 continue;
3195 validity = graph->edge[i].tagged_validity;
3196 adjacent = domain_intersects(validity, condition_sink);
3197 if (adjacent >= 0 && !adjacent)
3198 adjacent = range_intersects(validity, condition_source);
3199 if (adjacent < 0)
3200 goto error;
3201 if (!adjacent)
3202 continue;
3204 set_validity(&graph->edge[i]);
3207 isl_union_set_free(condition_source);
3208 isl_union_set_free(condition_sink);
3209 return 0;
3210 error:
3211 isl_union_set_free(condition_source);
3212 isl_union_set_free(condition_sink);
3213 return -1;
3216 /* Update the dependence relations of all edges based on the current schedule
3217 * and enforce conditional validity constraints that are adjacent
3218 * to satisfied condition constraints.
3220 * First check if any of the condition constraints are satisfied
3221 * (i.e., not local to the outer schedule) and keep track of
3222 * their domain and range.
3223 * Then update all dependence relations (which removes the non-local
3224 * constraints).
3225 * Finally, if any condition constraints turned out to be satisfied,
3226 * then turn all adjacent conditional validity constraints into
3227 * unconditional validity constraints.
3229 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3231 int i;
3232 int any = 0;
3233 isl_union_set *source, *sink;
3235 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3236 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3237 for (i = 0; i < graph->n_edge; ++i) {
3238 int local;
3239 isl_union_set *uset;
3240 isl_union_map *umap;
3242 if (!is_condition(&graph->edge[i]))
3243 continue;
3244 if (is_local(&graph->edge[i]))
3245 continue;
3246 local = is_condition_false(&graph->edge[i]);
3247 if (local < 0)
3248 goto error;
3249 if (local)
3250 continue;
3252 any = 1;
3254 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3255 uset = isl_union_map_domain(umap);
3256 source = isl_union_set_union(source, uset);
3258 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3259 uset = isl_union_map_range(umap);
3260 sink = isl_union_set_union(sink, uset);
3263 for (i = graph->n_edge - 1; i >= 0; --i) {
3264 if (update_edge(graph, &graph->edge[i]) < 0)
3265 goto error;
3268 if (any)
3269 return unconditionalize_adjacent_validity(graph, source, sink);
3271 isl_union_set_free(source);
3272 isl_union_set_free(sink);
3273 return 0;
3274 error:
3275 isl_union_set_free(source);
3276 isl_union_set_free(sink);
3277 return -1;
3280 static void next_band(struct isl_sched_graph *graph)
3282 graph->band_start = graph->n_total_row;
3285 /* Return the union of the universe domains of the nodes in "graph"
3286 * that satisfy "pred".
3288 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3289 struct isl_sched_graph *graph,
3290 int (*pred)(struct isl_sched_node *node, int data), int data)
3292 int i;
3293 isl_set *set;
3294 isl_union_set *dom;
3296 for (i = 0; i < graph->n; ++i)
3297 if (pred(&graph->node[i], data))
3298 break;
3300 if (i >= graph->n)
3301 isl_die(ctx, isl_error_internal,
3302 "empty component", return NULL);
3304 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3305 dom = isl_union_set_from_set(set);
3307 for (i = i + 1; i < graph->n; ++i) {
3308 if (!pred(&graph->node[i], data))
3309 continue;
3310 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3311 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3314 return dom;
3317 /* Return a list of unions of universe domains, where each element
3318 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3320 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3321 struct isl_sched_graph *graph)
3323 int i;
3324 isl_union_set_list *filters;
3326 filters = isl_union_set_list_alloc(ctx, graph->scc);
3327 for (i = 0; i < graph->scc; ++i) {
3328 isl_union_set *dom;
3330 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3331 filters = isl_union_set_list_add(filters, dom);
3334 return filters;
3337 /* Return a list of two unions of universe domains, one for the SCCs up
3338 * to and including graph->src_scc and another for the other SCCs.
3340 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3341 struct isl_sched_graph *graph)
3343 isl_union_set *dom;
3344 isl_union_set_list *filters;
3346 filters = isl_union_set_list_alloc(ctx, 2);
3347 dom = isl_sched_graph_domain(ctx, graph,
3348 &node_scc_at_most, graph->src_scc);
3349 filters = isl_union_set_list_add(filters, dom);
3350 dom = isl_sched_graph_domain(ctx, graph,
3351 &node_scc_at_least, graph->src_scc + 1);
3352 filters = isl_union_set_list_add(filters, dom);
3354 return filters;
3357 /* Copy nodes that satisfy node_pred from the src dependence graph
3358 * to the dst dependence graph.
3360 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3361 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3363 int i;
3365 dst->n = 0;
3366 for (i = 0; i < src->n; ++i) {
3367 int j;
3369 if (!node_pred(&src->node[i], data))
3370 continue;
3372 j = dst->n;
3373 dst->node[j].space = isl_space_copy(src->node[i].space);
3374 dst->node[j].compressed = src->node[i].compressed;
3375 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3376 dst->node[j].compress =
3377 isl_multi_aff_copy(src->node[i].compress);
3378 dst->node[j].decompress =
3379 isl_multi_aff_copy(src->node[i].decompress);
3380 dst->node[j].nvar = src->node[i].nvar;
3381 dst->node[j].nparam = src->node[i].nparam;
3382 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3383 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3384 dst->node[j].coincident = src->node[i].coincident;
3385 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3386 dst->node[j].bounds = isl_basic_set_copy(src->node[i].bounds);
3387 dst->node[j].max = isl_vec_copy(src->node[i].max);
3388 dst->n++;
3390 if (!dst->node[j].space || !dst->node[j].sched)
3391 return -1;
3392 if (dst->node[j].compressed &&
3393 (!dst->node[j].hull || !dst->node[j].compress ||
3394 !dst->node[j].decompress))
3395 return -1;
3398 return 0;
3401 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3402 * to the dst dependence graph.
3403 * If the source or destination node of the edge is not in the destination
3404 * graph, then it must be a backward proximity edge and it should simply
3405 * be ignored.
3407 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3408 struct isl_sched_graph *src,
3409 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3411 int i;
3412 enum isl_edge_type t;
3414 dst->n_edge = 0;
3415 for (i = 0; i < src->n_edge; ++i) {
3416 struct isl_sched_edge *edge = &src->edge[i];
3417 isl_map *map;
3418 isl_union_map *tagged_condition;
3419 isl_union_map *tagged_validity;
3420 struct isl_sched_node *dst_src, *dst_dst;
3422 if (!edge_pred(edge, data))
3423 continue;
3425 if (isl_map_plain_is_empty(edge->map))
3426 continue;
3428 dst_src = graph_find_node(ctx, dst, edge->src->space);
3429 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3430 if (!dst_src || !dst_dst) {
3431 if (is_validity(edge) || is_conditional_validity(edge))
3432 isl_die(ctx, isl_error_internal,
3433 "backward (conditional) validity edge",
3434 return -1);
3435 continue;
3438 map = isl_map_copy(edge->map);
3439 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3440 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3442 dst->edge[dst->n_edge].src = dst_src;
3443 dst->edge[dst->n_edge].dst = dst_dst;
3444 dst->edge[dst->n_edge].map = map;
3445 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3446 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3447 dst->edge[dst->n_edge].types = edge->types;
3448 dst->n_edge++;
3450 if (edge->tagged_condition && !tagged_condition)
3451 return -1;
3452 if (edge->tagged_validity && !tagged_validity)
3453 return -1;
3455 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3456 if (edge !=
3457 graph_find_edge(src, t, edge->src, edge->dst))
3458 continue;
3459 if (graph_edge_table_add(ctx, dst, t,
3460 &dst->edge[dst->n_edge - 1]) < 0)
3461 return -1;
3465 return 0;
3468 /* Compute the maximal number of variables over all nodes.
3469 * This is the maximal number of linearly independent schedule
3470 * rows that we need to compute.
3471 * Just in case we end up in a part of the dependence graph
3472 * with only lower-dimensional domains, we make sure we will
3473 * compute the required amount of extra linearly independent rows.
3475 static int compute_maxvar(struct isl_sched_graph *graph)
3477 int i;
3479 graph->maxvar = 0;
3480 for (i = 0; i < graph->n; ++i) {
3481 struct isl_sched_node *node = &graph->node[i];
3482 int nvar;
3484 if (node_update_vmap(node) < 0)
3485 return -1;
3486 nvar = node->nvar + graph->n_row - node->rank;
3487 if (nvar > graph->maxvar)
3488 graph->maxvar = nvar;
3491 return 0;
3494 /* Extract the subgraph of "graph" that consists of the node satisfying
3495 * "node_pred" and the edges satisfying "edge_pred" and store
3496 * the result in "sub".
3498 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3499 int (*node_pred)(struct isl_sched_node *node, int data),
3500 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3501 int data, struct isl_sched_graph *sub)
3503 int i, n = 0, n_edge = 0;
3504 int t;
3506 for (i = 0; i < graph->n; ++i)
3507 if (node_pred(&graph->node[i], data))
3508 ++n;
3509 for (i = 0; i < graph->n_edge; ++i)
3510 if (edge_pred(&graph->edge[i], data))
3511 ++n_edge;
3512 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3513 return -1;
3514 sub->root = graph->root;
3515 if (copy_nodes(sub, graph, node_pred, data) < 0)
3516 return -1;
3517 if (graph_init_table(ctx, sub) < 0)
3518 return -1;
3519 for (t = 0; t <= isl_edge_last; ++t)
3520 sub->max_edge[t] = graph->max_edge[t];
3521 if (graph_init_edge_tables(ctx, sub) < 0)
3522 return -1;
3523 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3524 return -1;
3525 sub->n_row = graph->n_row;
3526 sub->max_row = graph->max_row;
3527 sub->n_total_row = graph->n_total_row;
3528 sub->band_start = graph->band_start;
3530 return 0;
3533 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3534 struct isl_sched_graph *graph);
3535 static __isl_give isl_schedule_node *compute_schedule_wcc(
3536 isl_schedule_node *node, struct isl_sched_graph *graph);
3538 /* Compute a schedule for a subgraph of "graph". In particular, for
3539 * the graph composed of nodes that satisfy node_pred and edges that
3540 * that satisfy edge_pred.
3541 * If the subgraph is known to consist of a single component, then wcc should
3542 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3543 * Otherwise, we call compute_schedule, which will check whether the subgraph
3544 * is connected.
3546 * The schedule is inserted at "node" and the updated schedule node
3547 * is returned.
3549 static __isl_give isl_schedule_node *compute_sub_schedule(
3550 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3551 struct isl_sched_graph *graph,
3552 int (*node_pred)(struct isl_sched_node *node, int data),
3553 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3554 int data, int wcc)
3556 struct isl_sched_graph split = { 0 };
3558 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3559 &split) < 0)
3560 goto error;
3562 if (wcc)
3563 node = compute_schedule_wcc(node, &split);
3564 else
3565 node = compute_schedule(node, &split);
3567 graph_free(ctx, &split);
3568 return node;
3569 error:
3570 graph_free(ctx, &split);
3571 return isl_schedule_node_free(node);
3574 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3576 return edge->src->scc == scc && edge->dst->scc == scc;
3579 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3581 return edge->dst->scc <= scc;
3584 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3586 return edge->src->scc >= scc;
3589 /* Reset the current band by dropping all its schedule rows.
3591 static int reset_band(struct isl_sched_graph *graph)
3593 int i;
3594 int drop;
3596 drop = graph->n_total_row - graph->band_start;
3597 graph->n_total_row -= drop;
3598 graph->n_row -= drop;
3600 for (i = 0; i < graph->n; ++i) {
3601 struct isl_sched_node *node = &graph->node[i];
3603 isl_map_free(node->sched_map);
3604 node->sched_map = NULL;
3606 node->sched = isl_mat_drop_rows(node->sched,
3607 graph->band_start, drop);
3609 if (!node->sched)
3610 return -1;
3613 return 0;
3616 /* Split the current graph into two parts and compute a schedule for each
3617 * part individually. In particular, one part consists of all SCCs up
3618 * to and including graph->src_scc, while the other part contains the other
3619 * SCCs. The split is enforced by a sequence node inserted at position "node"
3620 * in the schedule tree. Return the updated schedule node.
3621 * If either of these two parts consists of a sequence, then it is spliced
3622 * into the sequence containing the two parts.
3624 * The current band is reset. It would be possible to reuse
3625 * the previously computed rows as the first rows in the next
3626 * band, but recomputing them may result in better rows as we are looking
3627 * at a smaller part of the dependence graph.
3629 static __isl_give isl_schedule_node *compute_split_schedule(
3630 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3632 int is_seq;
3633 isl_ctx *ctx;
3634 isl_union_set_list *filters;
3636 if (!node)
3637 return NULL;
3639 if (reset_band(graph) < 0)
3640 return isl_schedule_node_free(node);
3642 next_band(graph);
3644 ctx = isl_schedule_node_get_ctx(node);
3645 filters = extract_split(ctx, graph);
3646 node = isl_schedule_node_insert_sequence(node, filters);
3647 node = isl_schedule_node_child(node, 1);
3648 node = isl_schedule_node_child(node, 0);
3650 node = compute_sub_schedule(node, ctx, graph,
3651 &node_scc_at_least, &edge_src_scc_at_least,
3652 graph->src_scc + 1, 0);
3653 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3654 node = isl_schedule_node_parent(node);
3655 node = isl_schedule_node_parent(node);
3656 if (is_seq)
3657 node = isl_schedule_node_sequence_splice_child(node, 1);
3658 node = isl_schedule_node_child(node, 0);
3659 node = isl_schedule_node_child(node, 0);
3660 node = compute_sub_schedule(node, ctx, graph,
3661 &node_scc_at_most, &edge_dst_scc_at_most,
3662 graph->src_scc, 0);
3663 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3664 node = isl_schedule_node_parent(node);
3665 node = isl_schedule_node_parent(node);
3666 if (is_seq)
3667 node = isl_schedule_node_sequence_splice_child(node, 0);
3669 return node;
3672 /* Insert a band node at position "node" in the schedule tree corresponding
3673 * to the current band in "graph". Mark the band node permutable
3674 * if "permutable" is set.
3675 * The partial schedules and the coincidence property are extracted
3676 * from the graph nodes.
3677 * Return the updated schedule node.
3679 static __isl_give isl_schedule_node *insert_current_band(
3680 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3681 int permutable)
3683 int i;
3684 int start, end, n;
3685 isl_multi_aff *ma;
3686 isl_multi_pw_aff *mpa;
3687 isl_multi_union_pw_aff *mupa;
3689 if (!node)
3690 return NULL;
3692 if (graph->n < 1)
3693 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3694 "graph should have at least one node",
3695 return isl_schedule_node_free(node));
3697 start = graph->band_start;
3698 end = graph->n_total_row;
3699 n = end - start;
3701 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3702 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3703 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3705 for (i = 1; i < graph->n; ++i) {
3706 isl_multi_union_pw_aff *mupa_i;
3708 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3709 start, n);
3710 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3711 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3712 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3714 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3716 for (i = 0; i < n; ++i)
3717 node = isl_schedule_node_band_member_set_coincident(node, i,
3718 graph->node[0].coincident[start + i]);
3719 node = isl_schedule_node_band_set_permutable(node, permutable);
3721 return node;
3724 /* Update the dependence relations based on the current schedule,
3725 * add the current band to "node" and then continue with the computation
3726 * of the next band.
3727 * Return the updated schedule node.
3729 static __isl_give isl_schedule_node *compute_next_band(
3730 __isl_take isl_schedule_node *node,
3731 struct isl_sched_graph *graph, int permutable)
3733 isl_ctx *ctx;
3735 if (!node)
3736 return NULL;
3738 ctx = isl_schedule_node_get_ctx(node);
3739 if (update_edges(ctx, graph) < 0)
3740 return isl_schedule_node_free(node);
3741 node = insert_current_band(node, graph, permutable);
3742 next_band(graph);
3744 node = isl_schedule_node_child(node, 0);
3745 node = compute_schedule(node, graph);
3746 node = isl_schedule_node_parent(node);
3748 return node;
3751 /* Add the constraints "coef" derived from an edge from "node" to itself
3752 * to graph->lp in order to respect the dependences and to try and carry them.
3753 * "pos" is the sequence number of the edge that needs to be carried.
3754 * "coef" represents general constraints on coefficients (c_0, c_x)
3755 * of valid constraints for (y - x) with x and y instances of the node.
3757 * The constraints added to graph->lp need to enforce
3759 * (c_j_0 + c_j_x y) - (c_j_0 + c_j_x x)
3760 * = c_j_x (y - x) >= e_i
3762 * for each (x,y) in the dependence relation of the edge.
3763 * That is, (-e_i, c_j_x) needs to be plugged in for (c_0, c_x),
3764 * taking into account that each coefficient in c_j_x is represented
3765 * as a pair of non-negative coefficients.
3767 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3768 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3770 int offset;
3771 isl_ctx *ctx;
3772 isl_dim_map *dim_map;
3774 if (!coef)
3775 return isl_stat_error;
3777 ctx = isl_basic_set_get_ctx(coef);
3778 offset = coef_var_offset(coef);
3779 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3780 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3781 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3783 return isl_stat_ok;
3786 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3787 * to graph->lp in order to respect the dependences and to try and carry them.
3788 * "pos" is the sequence number of the edge that needs to be carried or
3789 * -1 if no attempt should be made to carry the dependences.
3790 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3791 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3793 * The constraints added to graph->lp need to enforce
3795 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3797 * for each (x,y) in the dependence relation of the edge or
3799 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= 0
3801 * if pos is -1.
3802 * That is,
3803 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3804 * or
3805 * (c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3806 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3807 * taking into account that each coefficient in c_j_x and c_k_x is represented
3808 * as a pair of non-negative coefficients.
3810 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3811 struct isl_sched_node *src, struct isl_sched_node *dst,
3812 __isl_take isl_basic_set *coef, int pos)
3814 int offset;
3815 isl_ctx *ctx;
3816 isl_dim_map *dim_map;
3818 if (!coef)
3819 return isl_stat_error;
3821 ctx = isl_basic_set_get_ctx(coef);
3822 offset = coef_var_offset(coef);
3823 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3824 if (pos >= 0)
3825 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3826 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3828 return isl_stat_ok;
3831 /* Data structure for keeping track of the data needed
3832 * to exploit non-trivial lineality spaces.
3834 * "any_non_trivial" is true if there are any non-trivial lineality spaces.
3835 * If "any_non_trivial" is not true, then "equivalent" and "mask" may be NULL.
3836 * "equivalent" connects instances to other instances on the same line(s).
3837 * "mask" contains the domain spaces of "equivalent".
3838 * Any instance set not in "mask" does not have a non-trivial lineality space.
3840 struct isl_exploit_lineality_data {
3841 isl_bool any_non_trivial;
3842 isl_union_map *equivalent;
3843 isl_union_set *mask;
3846 /* Data structure collecting information used during the construction
3847 * of an LP for carrying dependences.
3849 * "intra" is a sequence of coefficient constraints for intra-node edges.
3850 * "inter" is a sequence of coefficient constraints for inter-node edges.
3851 * "lineality" contains data used to exploit non-trivial lineality spaces.
3853 struct isl_carry {
3854 isl_basic_set_list *intra;
3855 isl_basic_set_list *inter;
3856 struct isl_exploit_lineality_data lineality;
3859 /* Free all the data stored in "carry".
3861 static void isl_carry_clear(struct isl_carry *carry)
3863 isl_basic_set_list_free(carry->intra);
3864 isl_basic_set_list_free(carry->inter);
3865 isl_union_map_free(carry->lineality.equivalent);
3866 isl_union_set_free(carry->lineality.mask);
3869 /* Return a pointer to the node in "graph" that lives in "space".
3870 * If the requested node has been compressed, then "space"
3871 * corresponds to the compressed space.
3873 * First try and see if "space" is the space of an uncompressed node.
3874 * If so, return that node.
3875 * Otherwise, "space" was constructed by construct_compressed_id and
3876 * contains a user pointer pointing to the node in the tuple id.
3877 * However, this node belongs to the original dependence graph.
3878 * If "graph" is a subgraph of this original dependence graph,
3879 * then the node with the same space still needs to be looked up
3880 * in the current graph.
3882 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3883 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3885 isl_id *id;
3886 struct isl_sched_node *node;
3888 if (!space)
3889 return NULL;
3891 node = graph_find_node(ctx, graph, space);
3892 if (node)
3893 return node;
3895 id = isl_space_get_tuple_id(space, isl_dim_set);
3896 node = isl_id_get_user(id);
3897 isl_id_free(id);
3899 if (!node)
3900 return NULL;
3902 if (!is_node(graph->root, node))
3903 isl_die(ctx, isl_error_internal,
3904 "space points to invalid node", return NULL);
3905 if (graph != graph->root)
3906 node = graph_find_node(ctx, graph, node->space);
3908 return node;
3911 /* Internal data structure for add_all_constraints.
3913 * "graph" is the schedule constraint graph for which an LP problem
3914 * is being constructed.
3915 * "carry_inter" indicates whether inter-node edges should be carried.
3916 * "pos" is the position of the next edge that needs to be carried.
3918 struct isl_add_all_constraints_data {
3919 isl_ctx *ctx;
3920 struct isl_sched_graph *graph;
3921 int carry_inter;
3922 int pos;
3925 /* Add the constraints "coef" derived from an edge from a node to itself
3926 * to data->graph->lp in order to respect the dependences and
3927 * to try and carry them.
3929 * The space of "coef" is of the form
3931 * coefficients[[c_cst] -> S[c_x]]
3933 * with S[c_x] the (compressed) space of the node.
3934 * Extract the node from the space and call add_intra_constraints.
3936 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3938 struct isl_add_all_constraints_data *data = user;
3939 isl_space *space;
3940 struct isl_sched_node *node;
3942 space = isl_basic_set_get_space(coef);
3943 space = isl_space_range(isl_space_unwrap(space));
3944 node = graph_find_compressed_node(data->ctx, data->graph, space);
3945 isl_space_free(space);
3946 return add_intra_constraints(data->graph, node, coef, data->pos++);
3949 /* Add the constraints "coef" derived from an edge from a node j
3950 * to a node k to data->graph->lp in order to respect the dependences and
3951 * to try and carry them (provided data->carry_inter is set).
3953 * The space of "coef" is of the form
3955 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3957 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3958 * Extract the nodes from the space and call add_inter_constraints.
3960 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3962 struct isl_add_all_constraints_data *data = user;
3963 isl_space *space, *dom;
3964 struct isl_sched_node *src, *dst;
3965 int pos;
3967 space = isl_basic_set_get_space(coef);
3968 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3969 dom = isl_space_domain(isl_space_copy(space));
3970 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3971 isl_space_free(dom);
3972 space = isl_space_range(space);
3973 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3974 isl_space_free(space);
3976 pos = data->carry_inter ? data->pos++ : -1;
3977 return add_inter_constraints(data->graph, src, dst, coef, pos);
3980 /* Add constraints to graph->lp that force all (conditional) validity
3981 * dependences to be respected and attempt to carry them.
3982 * "intra" is the sequence of coefficient constraints for intra-node edges.
3983 * "inter" is the sequence of coefficient constraints for inter-node edges.
3984 * "carry_inter" indicates whether inter-node edges should be carried or
3985 * only respected.
3987 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3988 __isl_keep isl_basic_set_list *intra,
3989 __isl_keep isl_basic_set_list *inter, int carry_inter)
3991 struct isl_add_all_constraints_data data = { ctx, graph, carry_inter };
3993 data.pos = 0;
3994 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3995 return isl_stat_error;
3996 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3997 return isl_stat_error;
3998 return isl_stat_ok;
4001 /* Internal data structure for count_all_constraints
4002 * for keeping track of the number of equality and inequality constraints.
4004 struct isl_sched_count {
4005 int n_eq;
4006 int n_ineq;
4009 /* Add the number of equality and inequality constraints of "bset"
4010 * to data->n_eq and data->n_ineq.
4012 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
4014 struct isl_sched_count *data = user;
4016 return update_count(bset, 1, &data->n_eq, &data->n_ineq);
4019 /* Count the number of equality and inequality constraints
4020 * that will be added to the carry_lp problem.
4021 * We count each edge exactly once.
4022 * "intra" is the sequence of coefficient constraints for intra-node edges.
4023 * "inter" is the sequence of coefficient constraints for inter-node edges.
4025 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
4026 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
4028 struct isl_sched_count data;
4030 data.n_eq = data.n_ineq = 0;
4031 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
4032 return isl_stat_error;
4033 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
4034 return isl_stat_error;
4036 *n_eq = data.n_eq;
4037 *n_ineq = data.n_ineq;
4039 return isl_stat_ok;
4042 /* Construct an LP problem for finding schedule coefficients
4043 * such that the schedule carries as many validity dependences as possible.
4044 * In particular, for each dependence i, we bound the dependence distance
4045 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
4046 * of all e_i's. Dependences with e_i = 0 in the solution are simply
4047 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
4048 * "intra" is the sequence of coefficient constraints for intra-node edges.
4049 * "inter" is the sequence of coefficient constraints for inter-node edges.
4050 * "n_edge" is the total number of edges.
4051 * "carry_inter" indicates whether inter-node edges should be carried or
4052 * only respected. That is, if "carry_inter" is not set, then
4053 * no e_i variables are introduced for the inter-node edges.
4055 * All variables of the LP are non-negative. The actual coefficients
4056 * may be negative, so each coefficient is represented as the difference
4057 * of two non-negative variables. The negative part always appears
4058 * immediately before the positive part.
4059 * Other than that, the variables have the following order
4061 * - sum of (1 - e_i) over all edges
4062 * - sum of all c_n coefficients
4063 * (unconstrained when computing non-parametric schedules)
4064 * - sum of positive and negative parts of all c_x coefficients
4065 * - for each edge
4066 * - e_i
4067 * - for each node
4068 * - positive and negative parts of c_i_x, in opposite order
4069 * - c_i_n (if parametric)
4070 * - c_i_0
4072 * The constraints are those from the (validity) edges plus three equalities
4073 * to express the sums and n_edge inequalities to express e_i <= 1.
4075 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
4076 int n_edge, __isl_keep isl_basic_set_list *intra,
4077 __isl_keep isl_basic_set_list *inter, int carry_inter)
4079 int i;
4080 int k;
4081 isl_space *dim;
4082 unsigned total;
4083 int n_eq, n_ineq;
4085 total = 3 + n_edge;
4086 for (i = 0; i < graph->n; ++i) {
4087 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
4088 node->start = total;
4089 total += 1 + node->nparam + 2 * node->nvar;
4092 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
4093 return isl_stat_error;
4095 dim = isl_space_set_alloc(ctx, 0, total);
4096 isl_basic_set_free(graph->lp);
4097 n_eq += 3;
4098 n_ineq += n_edge;
4099 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
4100 graph->lp = isl_basic_set_set_rational(graph->lp);
4102 k = isl_basic_set_alloc_equality(graph->lp);
4103 if (k < 0)
4104 return isl_stat_error;
4105 isl_seq_clr(graph->lp->eq[k], 1 + total);
4106 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
4107 isl_int_set_si(graph->lp->eq[k][1], 1);
4108 for (i = 0; i < n_edge; ++i)
4109 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
4111 if (add_param_sum_constraint(graph, 1) < 0)
4112 return isl_stat_error;
4113 if (add_var_sum_constraint(graph, 2) < 0)
4114 return isl_stat_error;
4116 for (i = 0; i < n_edge; ++i) {
4117 k = isl_basic_set_alloc_inequality(graph->lp);
4118 if (k < 0)
4119 return isl_stat_error;
4120 isl_seq_clr(graph->lp->ineq[k], 1 + total);
4121 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
4122 isl_int_set_si(graph->lp->ineq[k][0], 1);
4125 if (add_all_constraints(ctx, graph, intra, inter, carry_inter) < 0)
4126 return isl_stat_error;
4128 return isl_stat_ok;
4131 static __isl_give isl_schedule_node *compute_component_schedule(
4132 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4133 int wcc);
4135 /* If the schedule_split_scaled option is set and if the linear
4136 * parts of the scheduling rows for all nodes in the graphs have
4137 * a non-trivial common divisor, then remove this
4138 * common divisor from the linear part.
4139 * Otherwise, insert a band node directly and continue with
4140 * the construction of the schedule.
4142 * If a non-trivial common divisor is found, then
4143 * the linear part is reduced and the remainder is ignored.
4144 * The pieces of the graph that are assigned different remainders
4145 * form (groups of) strongly connected components within
4146 * the scaled down band. If needed, they can therefore
4147 * be ordered along this remainder in a sequence node.
4148 * However, this ordering is not enforced here in order to allow
4149 * the scheduler to combine some of the strongly connected components.
4151 static __isl_give isl_schedule_node *split_scaled(
4152 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4154 int i;
4155 int row;
4156 isl_ctx *ctx;
4157 isl_int gcd, gcd_i;
4159 if (!node)
4160 return NULL;
4162 ctx = isl_schedule_node_get_ctx(node);
4163 if (!ctx->opt->schedule_split_scaled)
4164 return compute_next_band(node, graph, 0);
4165 if (graph->n <= 1)
4166 return compute_next_band(node, graph, 0);
4168 isl_int_init(gcd);
4169 isl_int_init(gcd_i);
4171 isl_int_set_si(gcd, 0);
4173 row = isl_mat_rows(graph->node[0].sched) - 1;
4175 for (i = 0; i < graph->n; ++i) {
4176 struct isl_sched_node *node = &graph->node[i];
4177 int cols = isl_mat_cols(node->sched);
4179 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4180 isl_int_gcd(gcd, gcd, gcd_i);
4183 isl_int_clear(gcd_i);
4185 if (isl_int_cmp_si(gcd, 1) <= 0) {
4186 isl_int_clear(gcd);
4187 return compute_next_band(node, graph, 0);
4190 for (i = 0; i < graph->n; ++i) {
4191 struct isl_sched_node *node = &graph->node[i];
4193 isl_int_fdiv_q(node->sched->row[row][0],
4194 node->sched->row[row][0], gcd);
4195 isl_int_mul(node->sched->row[row][0],
4196 node->sched->row[row][0], gcd);
4197 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4198 if (!node->sched)
4199 goto error;
4202 isl_int_clear(gcd);
4204 return compute_next_band(node, graph, 0);
4205 error:
4206 isl_int_clear(gcd);
4207 return isl_schedule_node_free(node);
4210 /* Is the schedule row "sol" trivial on node "node"?
4211 * That is, is the solution zero on the dimensions linearly independent of
4212 * the previously found solutions?
4213 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4215 * Each coefficient is represented as the difference between
4216 * two non-negative values in "sol".
4217 * We construct the schedule row s and check if it is linearly
4218 * independent of previously computed schedule rows
4219 * by computing T s, with T the linear combinations that are zero
4220 * on linearly dependent schedule rows.
4221 * If the result consists of all zeros, then the solution is trivial.
4223 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4225 int trivial;
4226 isl_vec *node_sol;
4228 if (!sol)
4229 return -1;
4230 if (node->nvar == node->rank)
4231 return 0;
4233 node_sol = extract_var_coef(node, sol);
4234 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4235 if (!node_sol)
4236 return -1;
4238 trivial = isl_seq_first_non_zero(node_sol->el,
4239 node->nvar - node->rank) == -1;
4241 isl_vec_free(node_sol);
4243 return trivial;
4246 /* Is the schedule row "sol" trivial on any node where it should
4247 * not be trivial?
4248 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4250 static int is_any_trivial(struct isl_sched_graph *graph,
4251 __isl_keep isl_vec *sol)
4253 int i;
4255 for (i = 0; i < graph->n; ++i) {
4256 struct isl_sched_node *node = &graph->node[i];
4257 int trivial;
4259 if (!needs_row(graph, node))
4260 continue;
4261 trivial = is_trivial(node, sol);
4262 if (trivial < 0 || trivial)
4263 return trivial;
4266 return 0;
4269 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4270 * If so, return the position of the coalesced dimension.
4271 * Otherwise, return node->nvar or -1 on error.
4273 * In particular, look for pairs of coefficients c_i and c_j such that
4274 * |c_j/c_i| > ceil(size_i/2), i.e., |c_j| > |c_i * ceil(size_i/2)|.
4275 * If any such pair is found, then return i.
4276 * If size_i is infinity, then no check on c_i needs to be performed.
4278 static int find_node_coalescing(struct isl_sched_node *node,
4279 __isl_keep isl_vec *sol)
4281 int i, j;
4282 isl_int max;
4283 isl_vec *csol;
4285 if (node->nvar <= 1)
4286 return node->nvar;
4288 csol = extract_var_coef(node, sol);
4289 if (!csol)
4290 return -1;
4291 isl_int_init(max);
4292 for (i = 0; i < node->nvar; ++i) {
4293 isl_val *v;
4295 if (isl_int_is_zero(csol->el[i]))
4296 continue;
4297 v = isl_multi_val_get_val(node->sizes, i);
4298 if (!v)
4299 goto error;
4300 if (!isl_val_is_int(v)) {
4301 isl_val_free(v);
4302 continue;
4304 v = isl_val_div_ui(v, 2);
4305 v = isl_val_ceil(v);
4306 if (!v)
4307 goto error;
4308 isl_int_mul(max, v->n, csol->el[i]);
4309 isl_val_free(v);
4311 for (j = 0; j < node->nvar; ++j) {
4312 if (j == i)
4313 continue;
4314 if (isl_int_abs_gt(csol->el[j], max))
4315 break;
4317 if (j < node->nvar)
4318 break;
4321 isl_int_clear(max);
4322 isl_vec_free(csol);
4323 return i;
4324 error:
4325 isl_int_clear(max);
4326 isl_vec_free(csol);
4327 return -1;
4330 /* Force the schedule coefficient at position "pos" of "node" to be zero
4331 * in "tl".
4332 * The coefficient is encoded as the difference between two non-negative
4333 * variables. Force these two variables to have the same value.
4335 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4336 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4338 int dim;
4339 isl_ctx *ctx;
4340 isl_vec *eq;
4342 ctx = isl_space_get_ctx(node->space);
4343 dim = isl_tab_lexmin_dim(tl);
4344 if (dim < 0)
4345 return isl_tab_lexmin_free(tl);
4346 eq = isl_vec_alloc(ctx, 1 + dim);
4347 eq = isl_vec_clr(eq);
4348 if (!eq)
4349 return isl_tab_lexmin_free(tl);
4351 pos = 1 + node_var_coef_pos(node, pos);
4352 isl_int_set_si(eq->el[pos], 1);
4353 isl_int_set_si(eq->el[pos + 1], -1);
4354 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4355 isl_vec_free(eq);
4357 return tl;
4360 /* Return the lexicographically smallest rational point in the basic set
4361 * from which "tl" was constructed, double checking that this input set
4362 * was not empty.
4364 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4366 isl_vec *sol;
4368 sol = isl_tab_lexmin_get_solution(tl);
4369 if (!sol)
4370 return NULL;
4371 if (sol->size == 0)
4372 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4373 "error in schedule construction",
4374 return isl_vec_free(sol));
4375 return sol;
4378 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4379 * carry any of the "n_edge" groups of dependences?
4380 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4381 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4382 * by the edge are carried by the solution.
4383 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4384 * one of those is carried.
4386 * Note that despite the fact that the problem is solved using a rational
4387 * solver, the solution is guaranteed to be integral.
4388 * Specifically, the dependence distance lower bounds e_i (and therefore
4389 * also their sum) are integers. See Lemma 5 of [1].
4391 * Any potential denominator of the sum is cleared by this function.
4392 * The denominator is not relevant for any of the other elements
4393 * in the solution.
4395 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4396 * Problem, Part II: Multi-Dimensional Time.
4397 * In Intl. Journal of Parallel Programming, 1992.
4399 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4401 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4402 isl_int_set_si(sol->el[0], 1);
4403 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4406 /* Return the lexicographically smallest rational point in "lp",
4407 * assuming that all variables are non-negative and performing some
4408 * additional sanity checks.
4409 * If "want_integral" is set, then compute the lexicographically smallest
4410 * integer point instead.
4411 * In particular, "lp" should not be empty by construction.
4412 * Double check that this is the case.
4413 * If dependences are not carried for any of the "n_edge" edges,
4414 * then return an empty vector.
4416 * If the schedule_treat_coalescing option is set and
4417 * if the computed schedule performs loop coalescing on a given node,
4418 * i.e., if it is of the form
4420 * c_i i + c_j j + ...
4422 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4423 * to cut out this solution. Repeat this process until no more loop
4424 * coalescing occurs or until no more dependences can be carried.
4425 * In the latter case, revert to the previously computed solution.
4427 * If the caller requests an integral solution and if coalescing should
4428 * be treated, then perform the coalescing treatment first as
4429 * an integral solution computed before coalescing treatment
4430 * would carry the same number of edges and would therefore probably
4431 * also be coalescing.
4433 * To allow the coalescing treatment to be performed first,
4434 * the initial solution is allowed to be rational and it is only
4435 * cut out (if needed) in the next iteration, if no coalescing measures
4436 * were taken.
4438 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4439 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4441 int i, pos, cut;
4442 isl_ctx *ctx;
4443 isl_tab_lexmin *tl;
4444 isl_vec *sol, *prev = NULL;
4445 int treat_coalescing;
4447 if (!lp)
4448 return NULL;
4449 ctx = isl_basic_set_get_ctx(lp);
4450 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4451 tl = isl_tab_lexmin_from_basic_set(lp);
4453 cut = 0;
4454 do {
4455 int integral;
4457 if (cut)
4458 tl = isl_tab_lexmin_cut_to_integer(tl);
4459 sol = non_empty_solution(tl);
4460 if (!sol)
4461 goto error;
4463 integral = isl_int_is_one(sol->el[0]);
4464 if (!carries_dependences(sol, n_edge)) {
4465 if (!prev)
4466 prev = isl_vec_alloc(ctx, 0);
4467 isl_vec_free(sol);
4468 sol = prev;
4469 break;
4471 prev = isl_vec_free(prev);
4472 cut = want_integral && !integral;
4473 if (cut)
4474 prev = sol;
4475 if (!treat_coalescing)
4476 continue;
4477 for (i = 0; i < graph->n; ++i) {
4478 struct isl_sched_node *node = &graph->node[i];
4480 pos = find_node_coalescing(node, sol);
4481 if (pos < 0)
4482 goto error;
4483 if (pos < node->nvar)
4484 break;
4486 if (i < graph->n) {
4487 prev = sol;
4488 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4489 cut = 0;
4491 } while (prev);
4493 isl_tab_lexmin_free(tl);
4495 return sol;
4496 error:
4497 isl_tab_lexmin_free(tl);
4498 isl_vec_free(prev);
4499 isl_vec_free(sol);
4500 return NULL;
4503 /* If "edge" is an edge from a node to itself, then add the corresponding
4504 * dependence relation to "umap".
4505 * If "node" has been compressed, then the dependence relation
4506 * is also compressed first.
4508 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4509 struct isl_sched_edge *edge)
4511 isl_map *map;
4512 struct isl_sched_node *node = edge->src;
4514 if (edge->src != edge->dst)
4515 return umap;
4517 map = isl_map_copy(edge->map);
4518 if (node->compressed) {
4519 map = isl_map_preimage_domain_multi_aff(map,
4520 isl_multi_aff_copy(node->decompress));
4521 map = isl_map_preimage_range_multi_aff(map,
4522 isl_multi_aff_copy(node->decompress));
4524 umap = isl_union_map_add_map(umap, map);
4525 return umap;
4528 /* If "edge" is an edge from a node to another node, then add the corresponding
4529 * dependence relation to "umap".
4530 * If the source or destination nodes of "edge" have been compressed,
4531 * then the dependence relation is also compressed first.
4533 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4534 struct isl_sched_edge *edge)
4536 isl_map *map;
4538 if (edge->src == edge->dst)
4539 return umap;
4541 map = isl_map_copy(edge->map);
4542 if (edge->src->compressed)
4543 map = isl_map_preimage_domain_multi_aff(map,
4544 isl_multi_aff_copy(edge->src->decompress));
4545 if (edge->dst->compressed)
4546 map = isl_map_preimage_range_multi_aff(map,
4547 isl_multi_aff_copy(edge->dst->decompress));
4548 umap = isl_union_map_add_map(umap, map);
4549 return umap;
4552 /* Internal data structure used by union_drop_coalescing_constraints
4553 * to collect bounds on all relevant statements.
4555 * "graph" is the schedule constraint graph for which an LP problem
4556 * is being constructed.
4557 * "bounds" collects the bounds.
4559 struct isl_collect_bounds_data {
4560 isl_ctx *ctx;
4561 struct isl_sched_graph *graph;
4562 isl_union_set *bounds;
4565 /* Add the size bounds for the node with instance deltas in "set"
4566 * to data->bounds.
4568 static isl_stat collect_bounds(__isl_take isl_set *set, void *user)
4570 struct isl_collect_bounds_data *data = user;
4571 struct isl_sched_node *node;
4572 isl_space *space;
4573 isl_set *bounds;
4575 space = isl_set_get_space(set);
4576 isl_set_free(set);
4578 node = graph_find_compressed_node(data->ctx, data->graph, space);
4579 isl_space_free(space);
4581 bounds = isl_set_from_basic_set(get_size_bounds(node));
4582 data->bounds = isl_union_set_add_set(data->bounds, bounds);
4584 return isl_stat_ok;
4587 /* Drop some constraints from "delta" that could be exploited
4588 * to construct loop coalescing schedules.
4589 * In particular, drop those constraint that bound the difference
4590 * to the size of the domain.
4591 * Do this for each set/node in "delta" separately.
4592 * The parameters are assumed to have been projected out by the caller.
4594 static __isl_give isl_union_set *union_drop_coalescing_constraints(isl_ctx *ctx,
4595 struct isl_sched_graph *graph, __isl_take isl_union_set *delta)
4597 struct isl_collect_bounds_data data = { ctx, graph };
4599 data.bounds = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4600 if (isl_union_set_foreach_set(delta, &collect_bounds, &data) < 0)
4601 data.bounds = isl_union_set_free(data.bounds);
4602 delta = isl_union_set_plain_gist(delta, data.bounds);
4604 return delta;
4607 /* Given a non-trivial lineality space "lineality", add the corresponding
4608 * universe set to data->mask and add a map from elements to
4609 * other elements along the lines in "lineality" to data->equivalent.
4610 * If this is the first time this function gets called
4611 * (data->any_non_trivial is still false), then set data->any_non_trivial and
4612 * initialize data->mask and data->equivalent.
4614 * In particular, if the lineality space is defined by equality constraints
4616 * E x = 0
4618 * then construct an affine mapping
4620 * f : x -> E x
4622 * and compute the equivalence relation of having the same image under f:
4624 * { x -> x' : E x = E x' }
4626 static isl_stat add_non_trivial_lineality(__isl_take isl_basic_set *lineality,
4627 struct isl_exploit_lineality_data *data)
4629 isl_mat *eq;
4630 isl_space *space;
4631 isl_set *univ;
4632 isl_multi_aff *ma;
4633 isl_multi_pw_aff *mpa;
4634 isl_map *map;
4635 int n;
4637 if (!lineality)
4638 return isl_stat_error;
4639 if (isl_basic_set_dim(lineality, isl_dim_div) != 0)
4640 isl_die(isl_basic_set_get_ctx(lineality), isl_error_internal,
4641 "local variables not allowed", goto error);
4643 space = isl_basic_set_get_space(lineality);
4644 if (!data->any_non_trivial) {
4645 data->equivalent = isl_union_map_empty(isl_space_copy(space));
4646 data->mask = isl_union_set_empty(isl_space_copy(space));
4648 data->any_non_trivial = isl_bool_true;
4650 univ = isl_set_universe(isl_space_copy(space));
4651 data->mask = isl_union_set_add_set(data->mask, univ);
4653 eq = isl_basic_set_extract_equalities(lineality);
4654 n = isl_mat_rows(eq);
4655 eq = isl_mat_insert_zero_rows(eq, 0, 1);
4656 eq = isl_mat_set_element_si(eq, 0, 0, 1);
4657 space = isl_space_from_domain(space);
4658 space = isl_space_add_dims(space, isl_dim_out, n);
4659 ma = isl_multi_aff_from_aff_mat(space, eq);
4660 mpa = isl_multi_pw_aff_from_multi_aff(ma);
4661 map = isl_multi_pw_aff_eq_map(mpa, isl_multi_pw_aff_copy(mpa));
4662 data->equivalent = isl_union_map_add_map(data->equivalent, map);
4664 isl_basic_set_free(lineality);
4665 return isl_stat_ok;
4666 error:
4667 isl_basic_set_free(lineality);
4668 return isl_stat_error;
4671 /* Check if the lineality space "set" is non-trivial (i.e., is not just
4672 * the origin or, in other words, satisfies a number of equality constraints
4673 * that is smaller than the dimension of the set).
4674 * If so, extend data->mask and data->equivalent accordingly.
4676 * The input should not have any local variables already, but
4677 * isl_set_remove_divs is called to make sure it does not.
4679 static isl_stat add_lineality(__isl_take isl_set *set, void *user)
4681 struct isl_exploit_lineality_data *data = user;
4682 isl_basic_set *hull;
4683 int dim, n_eq;
4685 set = isl_set_remove_divs(set);
4686 hull = isl_set_unshifted_simple_hull(set);
4687 dim = isl_basic_set_dim(hull, isl_dim_set);
4688 n_eq = isl_basic_set_n_equality(hull);
4689 if (!hull)
4690 return isl_stat_error;
4691 if (dim != n_eq)
4692 return add_non_trivial_lineality(hull, data);
4693 isl_basic_set_free(hull);
4694 return isl_stat_ok;
4697 /* Check if the difference set on intra-node schedule constraints "intra"
4698 * has any non-trivial lineality space.
4699 * If so, then extend the difference set to a difference set
4700 * on equivalent elements. That is, if "intra" is
4702 * { y - x : (x,y) \in V }
4704 * and elements are equivalent if they have the same image under f,
4705 * then return
4707 * { y' - x' : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4709 * or, since f is linear,
4711 * { y' - x' : (x,y) \in V and f(y - x) = f(y' - x') }
4713 * The results of the search for non-trivial lineality spaces is stored
4714 * in "data".
4716 static __isl_give isl_union_set *exploit_intra_lineality(
4717 __isl_take isl_union_set *intra,
4718 struct isl_exploit_lineality_data *data)
4720 isl_union_set *lineality;
4721 isl_union_set *uset;
4723 data->any_non_trivial = isl_bool_false;
4724 lineality = isl_union_set_copy(intra);
4725 lineality = isl_union_set_combined_lineality_space(lineality);
4726 if (isl_union_set_foreach_set(lineality, &add_lineality, data) < 0)
4727 data->any_non_trivial = isl_bool_error;
4728 isl_union_set_free(lineality);
4730 if (data->any_non_trivial < 0)
4731 return isl_union_set_free(intra);
4732 if (!data->any_non_trivial)
4733 return intra;
4735 uset = isl_union_set_copy(intra);
4736 intra = isl_union_set_subtract(intra, isl_union_set_copy(data->mask));
4737 uset = isl_union_set_apply(uset, isl_union_map_copy(data->equivalent));
4738 intra = isl_union_set_union(intra, uset);
4740 intra = isl_union_set_remove_divs(intra);
4742 return intra;
4745 /* If the difference set on intra-node schedule constraints was found to have
4746 * any non-trivial lineality space by exploit_intra_lineality,
4747 * as recorded in "data", then extend the inter-node
4748 * schedule constraints "inter" to schedule constraints on equivalent elements.
4749 * That is, if "inter" is V and
4750 * elements are equivalent if they have the same image under f, then return
4752 * { (x', y') : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4754 static __isl_give isl_union_map *exploit_inter_lineality(
4755 __isl_take isl_union_map *inter,
4756 struct isl_exploit_lineality_data *data)
4758 isl_union_map *umap;
4760 if (data->any_non_trivial < 0)
4761 return isl_union_map_free(inter);
4762 if (!data->any_non_trivial)
4763 return inter;
4765 umap = isl_union_map_copy(inter);
4766 inter = isl_union_map_subtract_range(inter,
4767 isl_union_set_copy(data->mask));
4768 umap = isl_union_map_apply_range(umap,
4769 isl_union_map_copy(data->equivalent));
4770 inter = isl_union_map_union(inter, umap);
4771 umap = isl_union_map_copy(inter);
4772 inter = isl_union_map_subtract_domain(inter,
4773 isl_union_set_copy(data->mask));
4774 umap = isl_union_map_apply_range(isl_union_map_copy(data->equivalent),
4775 umap);
4776 inter = isl_union_map_union(inter, umap);
4778 inter = isl_union_map_remove_divs(inter);
4780 return inter;
4783 /* For each (conditional) validity edge in "graph",
4784 * add the corresponding dependence relation using "add"
4785 * to a collection of dependence relations and return the result.
4786 * If "coincidence" is set, then coincidence edges are considered as well.
4788 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4789 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4790 struct isl_sched_edge *edge), int coincidence)
4792 int i;
4793 isl_space *space;
4794 isl_union_map *umap;
4796 space = isl_space_copy(graph->node[0].space);
4797 umap = isl_union_map_empty(space);
4799 for (i = 0; i < graph->n_edge; ++i) {
4800 struct isl_sched_edge *edge = &graph->edge[i];
4802 if (!is_any_validity(edge) &&
4803 (!coincidence || !is_coincidence(edge)))
4804 continue;
4806 umap = add(umap, edge);
4809 return umap;
4812 /* Project out all parameters from "uset" and return the result.
4814 static __isl_give isl_union_set *union_set_drop_parameters(
4815 __isl_take isl_union_set *uset)
4817 unsigned nparam;
4819 nparam = isl_union_set_dim(uset, isl_dim_param);
4820 return isl_union_set_project_out(uset, isl_dim_param, 0, nparam);
4823 /* For each dependence relation on a (conditional) validity edge
4824 * from a node to itself,
4825 * construct the set of coefficients of valid constraints for elements
4826 * in that dependence relation and collect the results.
4827 * If "coincidence" is set, then coincidence edges are considered as well.
4829 * In particular, for each dependence relation R, constraints
4830 * on coefficients (c_0, c_x) are constructed such that
4832 * c_0 + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4834 * If the schedule_treat_coalescing option is set, then some constraints
4835 * that could be exploited to construct coalescing schedules
4836 * are removed before the dual is computed, but after the parameters
4837 * have been projected out.
4838 * The entire computation is essentially the same as that performed
4839 * by intra_coefficients, except that it operates on multiple
4840 * edges together and that the parameters are always projected out.
4842 * Additionally, exploit any non-trivial lineality space
4843 * in the difference set after removing coalescing constraints and
4844 * store the results of the non-trivial lineality space detection in "data".
4845 * The procedure is currently run unconditionally, but it is unlikely
4846 * to find any non-trivial lineality spaces if no coalescing constraints
4847 * have been removed.
4849 * Note that if a dependence relation is a union of basic maps,
4850 * then each basic map needs to be treated individually as it may only
4851 * be possible to carry the dependences expressed by some of those
4852 * basic maps and not all of them.
4853 * The collected validity constraints are therefore not coalesced and
4854 * it is assumed that they are not coalesced automatically.
4855 * Duplicate basic maps can be removed, however.
4856 * In particular, if the same basic map appears as a disjunct
4857 * in multiple edges, then it only needs to be carried once.
4859 static __isl_give isl_basic_set_list *collect_intra_validity(isl_ctx *ctx,
4860 struct isl_sched_graph *graph, int coincidence,
4861 struct isl_exploit_lineality_data *data)
4863 isl_union_map *intra;
4864 isl_union_set *delta;
4865 isl_basic_set_list *list;
4867 intra = collect_validity(graph, &add_intra, coincidence);
4868 delta = isl_union_map_deltas(intra);
4869 delta = union_set_drop_parameters(delta);
4870 delta = isl_union_set_remove_divs(delta);
4871 if (isl_options_get_schedule_treat_coalescing(ctx))
4872 delta = union_drop_coalescing_constraints(ctx, graph, delta);
4873 delta = exploit_intra_lineality(delta, data);
4874 list = isl_union_set_get_basic_set_list(delta);
4875 isl_union_set_free(delta);
4877 return isl_basic_set_list_coefficients(list);
4880 /* For each dependence relation on a (conditional) validity edge
4881 * from a node to some other node,
4882 * construct the set of coefficients of valid constraints for elements
4883 * in that dependence relation and collect the results.
4884 * If "coincidence" is set, then coincidence edges are considered as well.
4886 * In particular, for each dependence relation R, constraints
4887 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4889 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4891 * This computation is essentially the same as that performed
4892 * by inter_coefficients, except that it operates on multiple
4893 * edges together.
4895 * Additionally, exploit any non-trivial lineality space
4896 * that may have been discovered by collect_intra_validity
4897 * (as stored in "data").
4899 * Note that if a dependence relation is a union of basic maps,
4900 * then each basic map needs to be treated individually as it may only
4901 * be possible to carry the dependences expressed by some of those
4902 * basic maps and not all of them.
4903 * The collected validity constraints are therefore not coalesced and
4904 * it is assumed that they are not coalesced automatically.
4905 * Duplicate basic maps can be removed, however.
4906 * In particular, if the same basic map appears as a disjunct
4907 * in multiple edges, then it only needs to be carried once.
4909 static __isl_give isl_basic_set_list *collect_inter_validity(
4910 struct isl_sched_graph *graph, int coincidence,
4911 struct isl_exploit_lineality_data *data)
4913 isl_union_map *inter;
4914 isl_union_set *wrap;
4915 isl_basic_set_list *list;
4917 inter = collect_validity(graph, &add_inter, coincidence);
4918 inter = exploit_inter_lineality(inter, data);
4919 inter = isl_union_map_remove_divs(inter);
4920 wrap = isl_union_map_wrap(inter);
4921 list = isl_union_set_get_basic_set_list(wrap);
4922 isl_union_set_free(wrap);
4923 return isl_basic_set_list_coefficients(list);
4926 /* Construct an LP problem for finding schedule coefficients
4927 * such that the schedule carries as many of the "n_edge" groups of
4928 * dependences as possible based on the corresponding coefficient
4929 * constraints and return the lexicographically smallest non-trivial solution.
4930 * "intra" is the sequence of coefficient constraints for intra-node edges.
4931 * "inter" is the sequence of coefficient constraints for inter-node edges.
4932 * If "want_integral" is set, then compute an integral solution
4933 * for the coefficients rather than using the numerators
4934 * of a rational solution.
4935 * "carry_inter" indicates whether inter-node edges should be carried or
4936 * only respected.
4938 * If none of the "n_edge" groups can be carried
4939 * then return an empty vector.
4941 static __isl_give isl_vec *compute_carrying_sol_coef(isl_ctx *ctx,
4942 struct isl_sched_graph *graph, int n_edge,
4943 __isl_keep isl_basic_set_list *intra,
4944 __isl_keep isl_basic_set_list *inter, int want_integral,
4945 int carry_inter)
4947 isl_basic_set *lp;
4949 if (setup_carry_lp(ctx, graph, n_edge, intra, inter, carry_inter) < 0)
4950 return NULL;
4952 lp = isl_basic_set_copy(graph->lp);
4953 return non_neg_lexmin(graph, lp, n_edge, want_integral);
4956 /* Construct an LP problem for finding schedule coefficients
4957 * such that the schedule carries as many of the validity dependences
4958 * as possible and
4959 * return the lexicographically smallest non-trivial solution.
4960 * If "fallback" is set, then the carrying is performed as a fallback
4961 * for the Pluto-like scheduler.
4962 * If "coincidence" is set, then try and carry coincidence edges as well.
4964 * The variable "n_edge" stores the number of groups that should be carried.
4965 * If none of the "n_edge" groups can be carried
4966 * then return an empty vector.
4967 * If, moreover, "n_edge" is zero, then the LP problem does not even
4968 * need to be constructed.
4970 * If a fallback solution is being computed, then compute an integral solution
4971 * for the coefficients rather than using the numerators
4972 * of a rational solution.
4974 * If a fallback solution is being computed, if there are any intra-node
4975 * dependences, and if requested by the user, then first try
4976 * to only carry those intra-node dependences.
4977 * If this fails to carry any dependences, then try again
4978 * with the inter-node dependences included.
4980 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4981 struct isl_sched_graph *graph, int fallback, int coincidence)
4983 int n_intra, n_inter;
4984 int n_edge;
4985 struct isl_carry carry = { 0 };
4986 isl_vec *sol;
4988 carry.intra = collect_intra_validity(ctx, graph, coincidence,
4989 &carry.lineality);
4990 carry.inter = collect_inter_validity(graph, coincidence,
4991 &carry.lineality);
4992 if (!carry.intra || !carry.inter)
4993 goto error;
4994 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4995 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4997 if (fallback && n_intra > 0 &&
4998 isl_options_get_schedule_carry_self_first(ctx)) {
4999 sol = compute_carrying_sol_coef(ctx, graph, n_intra,
5000 carry.intra, carry.inter, fallback, 0);
5001 if (!sol || sol->size != 0 || n_inter == 0) {
5002 isl_carry_clear(&carry);
5003 return sol;
5005 isl_vec_free(sol);
5008 n_edge = n_intra + n_inter;
5009 if (n_edge == 0) {
5010 isl_carry_clear(&carry);
5011 return isl_vec_alloc(ctx, 0);
5014 sol = compute_carrying_sol_coef(ctx, graph, n_edge,
5015 carry.intra, carry.inter, fallback, 1);
5016 isl_carry_clear(&carry);
5017 return sol;
5018 error:
5019 isl_carry_clear(&carry);
5020 return NULL;
5023 /* Construct a schedule row for each node such that as many validity dependences
5024 * as possible are carried and then continue with the next band.
5025 * If "fallback" is set, then the carrying is performed as a fallback
5026 * for the Pluto-like scheduler.
5027 * If "coincidence" is set, then try and carry coincidence edges as well.
5029 * If there are no validity dependences, then no dependence can be carried and
5030 * the procedure is guaranteed to fail. If there is more than one component,
5031 * then try computing a schedule on each component separately
5032 * to prevent or at least postpone this failure.
5034 * If a schedule row is computed, then check that dependences are carried
5035 * for at least one of the edges.
5037 * If the computed schedule row turns out to be trivial on one or
5038 * more nodes where it should not be trivial, then we throw it away
5039 * and try again on each component separately.
5041 * If there is only one component, then we accept the schedule row anyway,
5042 * but we do not consider it as a complete row and therefore do not
5043 * increment graph->n_row. Note that the ranks of the nodes that
5044 * do get a non-trivial schedule part will get updated regardless and
5045 * graph->maxvar is computed based on these ranks. The test for
5046 * whether more schedule rows are required in compute_schedule_wcc
5047 * is therefore not affected.
5049 * Insert a band corresponding to the schedule row at position "node"
5050 * of the schedule tree and continue with the construction of the schedule.
5051 * This insertion and the continued construction is performed by split_scaled
5052 * after optionally checking for non-trivial common divisors.
5054 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
5055 struct isl_sched_graph *graph, int fallback, int coincidence)
5057 int trivial;
5058 isl_ctx *ctx;
5059 isl_vec *sol;
5061 if (!node)
5062 return NULL;
5064 ctx = isl_schedule_node_get_ctx(node);
5065 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
5066 if (!sol)
5067 return isl_schedule_node_free(node);
5068 if (sol->size == 0) {
5069 isl_vec_free(sol);
5070 if (graph->scc > 1)
5071 return compute_component_schedule(node, graph, 1);
5072 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
5073 return isl_schedule_node_free(node));
5076 trivial = is_any_trivial(graph, sol);
5077 if (trivial < 0) {
5078 sol = isl_vec_free(sol);
5079 } else if (trivial && graph->scc > 1) {
5080 isl_vec_free(sol);
5081 return compute_component_schedule(node, graph, 1);
5084 if (update_schedule(graph, sol, 0) < 0)
5085 return isl_schedule_node_free(node);
5086 if (trivial)
5087 graph->n_row--;
5089 return split_scaled(node, graph);
5092 /* Construct a schedule row for each node such that as many validity dependences
5093 * as possible are carried and then continue with the next band.
5094 * Do so as a fallback for the Pluto-like scheduler.
5095 * If "coincidence" is set, then try and carry coincidence edges as well.
5097 static __isl_give isl_schedule_node *carry_fallback(
5098 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5099 int coincidence)
5101 return carry(node, graph, 1, coincidence);
5104 /* Construct a schedule row for each node such that as many validity dependences
5105 * as possible are carried and then continue with the next band.
5106 * Do so for the case where the Feautrier scheduler was selected
5107 * by the user.
5109 static __isl_give isl_schedule_node *carry_feautrier(
5110 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5112 return carry(node, graph, 0, 0);
5115 /* Construct a schedule row for each node such that as many validity dependences
5116 * as possible are carried and then continue with the next band.
5117 * Do so as a fallback for the Pluto-like scheduler.
5119 static __isl_give isl_schedule_node *carry_dependences(
5120 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5122 return carry_fallback(node, graph, 0);
5125 /* Construct a schedule row for each node such that as many validity or
5126 * coincidence dependences as possible are carried and
5127 * then continue with the next band.
5128 * Do so as a fallback for the Pluto-like scheduler.
5130 static __isl_give isl_schedule_node *carry_coincidence(
5131 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5133 return carry_fallback(node, graph, 1);
5136 /* Topologically sort statements mapped to the same schedule iteration
5137 * and add insert a sequence node in front of "node"
5138 * corresponding to this order.
5139 * If "initialized" is set, then it may be assumed that compute_maxvar
5140 * has been called on the current band. Otherwise, call
5141 * compute_maxvar if and before carry_dependences gets called.
5143 * If it turns out to be impossible to sort the statements apart,
5144 * because different dependences impose different orderings
5145 * on the statements, then we extend the schedule such that
5146 * it carries at least one more dependence.
5148 static __isl_give isl_schedule_node *sort_statements(
5149 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5150 int initialized)
5152 isl_ctx *ctx;
5153 isl_union_set_list *filters;
5155 if (!node)
5156 return NULL;
5158 ctx = isl_schedule_node_get_ctx(node);
5159 if (graph->n < 1)
5160 isl_die(ctx, isl_error_internal,
5161 "graph should have at least one node",
5162 return isl_schedule_node_free(node));
5164 if (graph->n == 1)
5165 return node;
5167 if (update_edges(ctx, graph) < 0)
5168 return isl_schedule_node_free(node);
5170 if (graph->n_edge == 0)
5171 return node;
5173 if (detect_sccs(ctx, graph) < 0)
5174 return isl_schedule_node_free(node);
5176 next_band(graph);
5177 if (graph->scc < graph->n) {
5178 if (!initialized && compute_maxvar(graph) < 0)
5179 return isl_schedule_node_free(node);
5180 return carry_dependences(node, graph);
5183 filters = extract_sccs(ctx, graph);
5184 node = isl_schedule_node_insert_sequence(node, filters);
5186 return node;
5189 /* Are there any (non-empty) (conditional) validity edges in the graph?
5191 static int has_validity_edges(struct isl_sched_graph *graph)
5193 int i;
5195 for (i = 0; i < graph->n_edge; ++i) {
5196 int empty;
5198 empty = isl_map_plain_is_empty(graph->edge[i].map);
5199 if (empty < 0)
5200 return -1;
5201 if (empty)
5202 continue;
5203 if (is_any_validity(&graph->edge[i]))
5204 return 1;
5207 return 0;
5210 /* Should we apply a Feautrier step?
5211 * That is, did the user request the Feautrier algorithm and are
5212 * there any validity dependences (left)?
5214 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
5216 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
5217 return 0;
5219 return has_validity_edges(graph);
5222 /* Compute a schedule for a connected dependence graph using Feautrier's
5223 * multi-dimensional scheduling algorithm and return the updated schedule node.
5225 * The original algorithm is described in [1].
5226 * The main idea is to minimize the number of scheduling dimensions, by
5227 * trying to satisfy as many dependences as possible per scheduling dimension.
5229 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
5230 * Problem, Part II: Multi-Dimensional Time.
5231 * In Intl. Journal of Parallel Programming, 1992.
5233 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
5234 isl_schedule_node *node, struct isl_sched_graph *graph)
5236 return carry_feautrier(node, graph);
5239 /* Turn off the "local" bit on all (condition) edges.
5241 static void clear_local_edges(struct isl_sched_graph *graph)
5243 int i;
5245 for (i = 0; i < graph->n_edge; ++i)
5246 if (is_condition(&graph->edge[i]))
5247 clear_local(&graph->edge[i]);
5250 /* Does "graph" have both condition and conditional validity edges?
5252 static int need_condition_check(struct isl_sched_graph *graph)
5254 int i;
5255 int any_condition = 0;
5256 int any_conditional_validity = 0;
5258 for (i = 0; i < graph->n_edge; ++i) {
5259 if (is_condition(&graph->edge[i]))
5260 any_condition = 1;
5261 if (is_conditional_validity(&graph->edge[i]))
5262 any_conditional_validity = 1;
5265 return any_condition && any_conditional_validity;
5268 /* Does "graph" contain any coincidence edge?
5270 static int has_any_coincidence(struct isl_sched_graph *graph)
5272 int i;
5274 for (i = 0; i < graph->n_edge; ++i)
5275 if (is_coincidence(&graph->edge[i]))
5276 return 1;
5278 return 0;
5281 /* Extract the final schedule row as a map with the iteration domain
5282 * of "node" as domain.
5284 static __isl_give isl_map *final_row(struct isl_sched_node *node)
5286 isl_multi_aff *ma;
5287 int row;
5289 row = isl_mat_rows(node->sched) - 1;
5290 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
5291 return isl_map_from_multi_aff(ma);
5294 /* Is the conditional validity dependence in the edge with index "edge_index"
5295 * violated by the latest (i.e., final) row of the schedule?
5296 * That is, is i scheduled after j
5297 * for any conditional validity dependence i -> j?
5299 static int is_violated(struct isl_sched_graph *graph, int edge_index)
5301 isl_map *src_sched, *dst_sched, *map;
5302 struct isl_sched_edge *edge = &graph->edge[edge_index];
5303 int empty;
5305 src_sched = final_row(edge->src);
5306 dst_sched = final_row(edge->dst);
5307 map = isl_map_copy(edge->map);
5308 map = isl_map_apply_domain(map, src_sched);
5309 map = isl_map_apply_range(map, dst_sched);
5310 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
5311 empty = isl_map_is_empty(map);
5312 isl_map_free(map);
5314 if (empty < 0)
5315 return -1;
5317 return !empty;
5320 /* Does "graph" have any satisfied condition edges that
5321 * are adjacent to the conditional validity constraint with
5322 * domain "conditional_source" and range "conditional_sink"?
5324 * A satisfied condition is one that is not local.
5325 * If a condition was forced to be local already (i.e., marked as local)
5326 * then there is no need to check if it is in fact local.
5328 * Additionally, mark all adjacent condition edges found as local.
5330 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
5331 __isl_keep isl_union_set *conditional_source,
5332 __isl_keep isl_union_set *conditional_sink)
5334 int i;
5335 int any = 0;
5337 for (i = 0; i < graph->n_edge; ++i) {
5338 int adjacent, local;
5339 isl_union_map *condition;
5341 if (!is_condition(&graph->edge[i]))
5342 continue;
5343 if (is_local(&graph->edge[i]))
5344 continue;
5346 condition = graph->edge[i].tagged_condition;
5347 adjacent = domain_intersects(condition, conditional_sink);
5348 if (adjacent >= 0 && !adjacent)
5349 adjacent = range_intersects(condition,
5350 conditional_source);
5351 if (adjacent < 0)
5352 return -1;
5353 if (!adjacent)
5354 continue;
5356 set_local(&graph->edge[i]);
5358 local = is_condition_false(&graph->edge[i]);
5359 if (local < 0)
5360 return -1;
5361 if (!local)
5362 any = 1;
5365 return any;
5368 /* Are there any violated conditional validity dependences with
5369 * adjacent condition dependences that are not local with respect
5370 * to the current schedule?
5371 * That is, is the conditional validity constraint violated?
5373 * Additionally, mark all those adjacent condition dependences as local.
5374 * We also mark those adjacent condition dependences that were not marked
5375 * as local before, but just happened to be local already. This ensures
5376 * that they remain local if the schedule is recomputed.
5378 * We first collect domain and range of all violated conditional validity
5379 * dependences and then check if there are any adjacent non-local
5380 * condition dependences.
5382 static int has_violated_conditional_constraint(isl_ctx *ctx,
5383 struct isl_sched_graph *graph)
5385 int i;
5386 int any = 0;
5387 isl_union_set *source, *sink;
5389 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5390 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5391 for (i = 0; i < graph->n_edge; ++i) {
5392 isl_union_set *uset;
5393 isl_union_map *umap;
5394 int violated;
5396 if (!is_conditional_validity(&graph->edge[i]))
5397 continue;
5399 violated = is_violated(graph, i);
5400 if (violated < 0)
5401 goto error;
5402 if (!violated)
5403 continue;
5405 any = 1;
5407 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5408 uset = isl_union_map_domain(umap);
5409 source = isl_union_set_union(source, uset);
5410 source = isl_union_set_coalesce(source);
5412 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5413 uset = isl_union_map_range(umap);
5414 sink = isl_union_set_union(sink, uset);
5415 sink = isl_union_set_coalesce(sink);
5418 if (any)
5419 any = has_adjacent_true_conditions(graph, source, sink);
5421 isl_union_set_free(source);
5422 isl_union_set_free(sink);
5423 return any;
5424 error:
5425 isl_union_set_free(source);
5426 isl_union_set_free(sink);
5427 return -1;
5430 /* Examine the current band (the rows between graph->band_start and
5431 * graph->n_total_row), deciding whether to drop it or add it to "node"
5432 * and then continue with the computation of the next band, if any.
5433 * If "initialized" is set, then it may be assumed that compute_maxvar
5434 * has been called on the current band. Otherwise, call
5435 * compute_maxvar if and before carry_dependences gets called.
5437 * The caller keeps looking for a new row as long as
5438 * graph->n_row < graph->maxvar. If the latest attempt to find
5439 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
5440 * then we either
5441 * - split between SCCs and start over (assuming we found an interesting
5442 * pair of SCCs between which to split)
5443 * - continue with the next band (assuming the current band has at least
5444 * one row)
5445 * - if there is more than one SCC left, then split along all SCCs
5446 * - if outer coincidence needs to be enforced, then try to carry as many
5447 * validity or coincidence dependences as possible and
5448 * continue with the next band
5449 * - try to carry as many validity dependences as possible and
5450 * continue with the next band
5451 * In each case, we first insert a band node in the schedule tree
5452 * if any rows have been computed.
5454 * If the caller managed to complete the schedule, we insert a band node
5455 * (if any schedule rows were computed) and we finish off by topologically
5456 * sorting the statements based on the remaining dependences.
5458 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5459 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5460 int initialized)
5462 int insert;
5464 if (!node)
5465 return NULL;
5467 if (graph->n_row < graph->maxvar) {
5468 isl_ctx *ctx;
5469 int empty = graph->n_total_row == graph->band_start;
5471 ctx = isl_schedule_node_get_ctx(node);
5472 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5473 return compute_next_band(node, graph, 1);
5474 if (graph->src_scc >= 0)
5475 return compute_split_schedule(node, graph);
5476 if (!empty)
5477 return compute_next_band(node, graph, 1);
5478 if (graph->scc > 1)
5479 return compute_component_schedule(node, graph, 1);
5480 if (!initialized && compute_maxvar(graph) < 0)
5481 return isl_schedule_node_free(node);
5482 if (isl_options_get_schedule_outer_coincidence(ctx))
5483 return carry_coincidence(node, graph);
5484 return carry_dependences(node, graph);
5487 insert = graph->n_total_row > graph->band_start;
5488 if (insert) {
5489 node = insert_current_band(node, graph, 1);
5490 node = isl_schedule_node_child(node, 0);
5492 node = sort_statements(node, graph, initialized);
5493 if (insert)
5494 node = isl_schedule_node_parent(node);
5496 return node;
5499 /* Construct a band of schedule rows for a connected dependence graph.
5500 * The caller is responsible for determining the strongly connected
5501 * components and calling compute_maxvar first.
5503 * We try to find a sequence of as many schedule rows as possible that result
5504 * in non-negative dependence distances (independent of the previous rows
5505 * in the sequence, i.e., such that the sequence is tilable), with as
5506 * many of the initial rows as possible satisfying the coincidence constraints.
5507 * The computation stops if we can't find any more rows or if we have found
5508 * all the rows we wanted to find.
5510 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5511 * outermost dimension to satisfy the coincidence constraints. If this
5512 * turns out to be impossible, we fall back on the general scheme above
5513 * and try to carry as many dependences as possible.
5515 * If "graph" contains both condition and conditional validity dependences,
5516 * then we need to check that that the conditional schedule constraint
5517 * is satisfied, i.e., there are no violated conditional validity dependences
5518 * that are adjacent to any non-local condition dependences.
5519 * If there are, then we mark all those adjacent condition dependences
5520 * as local and recompute the current band. Those dependences that
5521 * are marked local will then be forced to be local.
5522 * The initial computation is performed with no dependences marked as local.
5523 * If we are lucky, then there will be no violated conditional validity
5524 * dependences adjacent to any non-local condition dependences.
5525 * Otherwise, we mark some additional condition dependences as local and
5526 * recompute. We continue this process until there are no violations left or
5527 * until we are no longer able to compute a schedule.
5528 * Since there are only a finite number of dependences,
5529 * there will only be a finite number of iterations.
5531 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5532 struct isl_sched_graph *graph)
5534 int has_coincidence;
5535 int use_coincidence;
5536 int force_coincidence = 0;
5537 int check_conditional;
5539 if (sort_sccs(graph) < 0)
5540 return isl_stat_error;
5542 clear_local_edges(graph);
5543 check_conditional = need_condition_check(graph);
5544 has_coincidence = has_any_coincidence(graph);
5546 if (ctx->opt->schedule_outer_coincidence)
5547 force_coincidence = 1;
5549 use_coincidence = has_coincidence;
5550 while (graph->n_row < graph->maxvar) {
5551 isl_vec *sol;
5552 int violated;
5553 int coincident;
5555 graph->src_scc = -1;
5556 graph->dst_scc = -1;
5558 if (setup_lp(ctx, graph, use_coincidence) < 0)
5559 return isl_stat_error;
5560 sol = solve_lp(ctx, graph);
5561 if (!sol)
5562 return isl_stat_error;
5563 if (sol->size == 0) {
5564 int empty = graph->n_total_row == graph->band_start;
5566 isl_vec_free(sol);
5567 if (use_coincidence && (!force_coincidence || !empty)) {
5568 use_coincidence = 0;
5569 continue;
5571 return isl_stat_ok;
5573 coincident = !has_coincidence || use_coincidence;
5574 if (update_schedule(graph, sol, coincident) < 0)
5575 return isl_stat_error;
5577 if (!check_conditional)
5578 continue;
5579 violated = has_violated_conditional_constraint(ctx, graph);
5580 if (violated < 0)
5581 return isl_stat_error;
5582 if (!violated)
5583 continue;
5584 if (reset_band(graph) < 0)
5585 return isl_stat_error;
5586 use_coincidence = has_coincidence;
5589 return isl_stat_ok;
5592 /* Compute a schedule for a connected dependence graph by considering
5593 * the graph as a whole and return the updated schedule node.
5595 * The actual schedule rows of the current band are computed by
5596 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5597 * care of integrating the band into "node" and continuing
5598 * the computation.
5600 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5601 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5603 isl_ctx *ctx;
5605 if (!node)
5606 return NULL;
5608 ctx = isl_schedule_node_get_ctx(node);
5609 if (compute_schedule_wcc_band(ctx, graph) < 0)
5610 return isl_schedule_node_free(node);
5612 return compute_schedule_finish_band(node, graph, 1);
5615 /* Clustering information used by compute_schedule_wcc_clustering.
5617 * "n" is the number of SCCs in the original dependence graph
5618 * "scc" is an array of "n" elements, each representing an SCC
5619 * of the original dependence graph. All entries in the same cluster
5620 * have the same number of schedule rows.
5621 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5622 * where each cluster is represented by the index of the first SCC
5623 * in the cluster. Initially, each SCC belongs to a cluster containing
5624 * only that SCC.
5626 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5627 * track of which SCCs need to be merged.
5629 * "cluster" contains the merged clusters of SCCs after the clustering
5630 * has completed.
5632 * "scc_node" is a temporary data structure used inside copy_partial.
5633 * For each SCC, it keeps track of the number of nodes in the SCC
5634 * that have already been copied.
5636 struct isl_clustering {
5637 int n;
5638 struct isl_sched_graph *scc;
5639 struct isl_sched_graph *cluster;
5640 int *scc_cluster;
5641 int *scc_node;
5642 int *scc_in_merge;
5645 /* Initialize the clustering data structure "c" from "graph".
5647 * In particular, allocate memory, extract the SCCs from "graph"
5648 * into c->scc, initialize scc_cluster and construct
5649 * a band of schedule rows for each SCC.
5650 * Within each SCC, there is only one SCC by definition.
5651 * Each SCC initially belongs to a cluster containing only that SCC.
5653 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5654 struct isl_sched_graph *graph)
5656 int i;
5658 c->n = graph->scc;
5659 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5660 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5661 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5662 c->scc_node = isl_calloc_array(ctx, int, c->n);
5663 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5664 if (!c->scc || !c->cluster ||
5665 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5666 return isl_stat_error;
5668 for (i = 0; i < c->n; ++i) {
5669 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5670 &edge_scc_exactly, i, &c->scc[i]) < 0)
5671 return isl_stat_error;
5672 c->scc[i].scc = 1;
5673 if (compute_maxvar(&c->scc[i]) < 0)
5674 return isl_stat_error;
5675 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5676 return isl_stat_error;
5677 c->scc_cluster[i] = i;
5680 return isl_stat_ok;
5683 /* Free all memory allocated for "c".
5685 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5687 int i;
5689 if (c->scc)
5690 for (i = 0; i < c->n; ++i)
5691 graph_free(ctx, &c->scc[i]);
5692 free(c->scc);
5693 if (c->cluster)
5694 for (i = 0; i < c->n; ++i)
5695 graph_free(ctx, &c->cluster[i]);
5696 free(c->cluster);
5697 free(c->scc_cluster);
5698 free(c->scc_node);
5699 free(c->scc_in_merge);
5702 /* Should we refrain from merging the cluster in "graph" with
5703 * any other cluster?
5704 * In particular, is its current schedule band empty and incomplete.
5706 static int bad_cluster(struct isl_sched_graph *graph)
5708 return graph->n_row < graph->maxvar &&
5709 graph->n_total_row == graph->band_start;
5712 /* Is "edge" a proximity edge with a non-empty dependence relation?
5714 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5716 if (!is_proximity(edge))
5717 return isl_bool_false;
5718 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5721 /* Return the index of an edge in "graph" that can be used to merge
5722 * two clusters in "c".
5723 * Return graph->n_edge if no such edge can be found.
5724 * Return -1 on error.
5726 * In particular, return a proximity edge between two clusters
5727 * that is not marked "no_merge" and such that neither of the
5728 * two clusters has an incomplete, empty band.
5730 * If there are multiple such edges, then try and find the most
5731 * appropriate edge to use for merging. In particular, pick the edge
5732 * with the greatest weight. If there are multiple of those,
5733 * then pick one with the shortest distance between
5734 * the two cluster representatives.
5736 static int find_proximity(struct isl_sched_graph *graph,
5737 struct isl_clustering *c)
5739 int i, best = graph->n_edge, best_dist, best_weight;
5741 for (i = 0; i < graph->n_edge; ++i) {
5742 struct isl_sched_edge *edge = &graph->edge[i];
5743 int dist, weight;
5744 isl_bool prox;
5746 prox = is_non_empty_proximity(edge);
5747 if (prox < 0)
5748 return -1;
5749 if (!prox)
5750 continue;
5751 if (edge->no_merge)
5752 continue;
5753 if (bad_cluster(&c->scc[edge->src->scc]) ||
5754 bad_cluster(&c->scc[edge->dst->scc]))
5755 continue;
5756 dist = c->scc_cluster[edge->dst->scc] -
5757 c->scc_cluster[edge->src->scc];
5758 if (dist == 0)
5759 continue;
5760 weight = edge->weight;
5761 if (best < graph->n_edge) {
5762 if (best_weight > weight)
5763 continue;
5764 if (best_weight == weight && best_dist <= dist)
5765 continue;
5767 best = i;
5768 best_dist = dist;
5769 best_weight = weight;
5772 return best;
5775 /* Internal data structure used in mark_merge_sccs.
5777 * "graph" is the dependence graph in which a strongly connected
5778 * component is constructed.
5779 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5780 * "src" and "dst" are the indices of the nodes that are being merged.
5782 struct isl_mark_merge_sccs_data {
5783 struct isl_sched_graph *graph;
5784 int *scc_cluster;
5785 int src;
5786 int dst;
5789 /* Check whether the cluster containing node "i" depends on the cluster
5790 * containing node "j". If "i" and "j" belong to the same cluster,
5791 * then they are taken to depend on each other to ensure that
5792 * the resulting strongly connected component consists of complete
5793 * clusters. Furthermore, if "i" and "j" are the two nodes that
5794 * are being merged, then they are taken to depend on each other as well.
5795 * Otherwise, check if there is a (conditional) validity dependence
5796 * from node[j] to node[i], forcing node[i] to follow node[j].
5798 static isl_bool cluster_follows(int i, int j, void *user)
5800 struct isl_mark_merge_sccs_data *data = user;
5801 struct isl_sched_graph *graph = data->graph;
5802 int *scc_cluster = data->scc_cluster;
5804 if (data->src == i && data->dst == j)
5805 return isl_bool_true;
5806 if (data->src == j && data->dst == i)
5807 return isl_bool_true;
5808 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5809 return isl_bool_true;
5811 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5814 /* Mark all SCCs that belong to either of the two clusters in "c"
5815 * connected by the edge in "graph" with index "edge", or to any
5816 * of the intermediate clusters.
5817 * The marking is recorded in c->scc_in_merge.
5819 * The given edge has been selected for merging two clusters,
5820 * meaning that there is at least a proximity edge between the two nodes.
5821 * However, there may also be (indirect) validity dependences
5822 * between the two nodes. When merging the two clusters, all clusters
5823 * containing one or more of the intermediate nodes along the
5824 * indirect validity dependences need to be merged in as well.
5826 * First collect all such nodes by computing the strongly connected
5827 * component (SCC) containing the two nodes connected by the edge, where
5828 * the two nodes are considered to depend on each other to make
5829 * sure they end up in the same SCC. Similarly, each node is considered
5830 * to depend on every other node in the same cluster to ensure
5831 * that the SCC consists of complete clusters.
5833 * Then the original SCCs that contain any of these nodes are marked
5834 * in c->scc_in_merge.
5836 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5837 int edge, struct isl_clustering *c)
5839 struct isl_mark_merge_sccs_data data;
5840 struct isl_tarjan_graph *g;
5841 int i;
5843 for (i = 0; i < c->n; ++i)
5844 c->scc_in_merge[i] = 0;
5846 data.graph = graph;
5847 data.scc_cluster = c->scc_cluster;
5848 data.src = graph->edge[edge].src - graph->node;
5849 data.dst = graph->edge[edge].dst - graph->node;
5851 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5852 &cluster_follows, &data);
5853 if (!g)
5854 goto error;
5856 i = g->op;
5857 if (i < 3)
5858 isl_die(ctx, isl_error_internal,
5859 "expecting at least two nodes in component",
5860 goto error);
5861 if (g->order[--i] != -1)
5862 isl_die(ctx, isl_error_internal,
5863 "expecting end of component marker", goto error);
5865 for (--i; i >= 0 && g->order[i] != -1; --i) {
5866 int scc = graph->node[g->order[i]].scc;
5867 c->scc_in_merge[scc] = 1;
5870 isl_tarjan_graph_free(g);
5871 return isl_stat_ok;
5872 error:
5873 isl_tarjan_graph_free(g);
5874 return isl_stat_error;
5877 /* Construct the identifier "cluster_i".
5879 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5881 char name[40];
5883 snprintf(name, sizeof(name), "cluster_%d", i);
5884 return isl_id_alloc(ctx, name, NULL);
5887 /* Construct the space of the cluster with index "i" containing
5888 * the strongly connected component "scc".
5890 * In particular, construct a space called cluster_i with dimension equal
5891 * to the number of schedule rows in the current band of "scc".
5893 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5895 int nvar;
5896 isl_space *space;
5897 isl_id *id;
5899 nvar = scc->n_total_row - scc->band_start;
5900 space = isl_space_copy(scc->node[0].space);
5901 space = isl_space_params(space);
5902 space = isl_space_set_from_params(space);
5903 space = isl_space_add_dims(space, isl_dim_set, nvar);
5904 id = cluster_id(isl_space_get_ctx(space), i);
5905 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5907 return space;
5910 /* Collect the domain of the graph for merging clusters.
5912 * In particular, for each cluster with first SCC "i", construct
5913 * a set in the space called cluster_i with dimension equal
5914 * to the number of schedule rows in the current band of the cluster.
5916 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5917 struct isl_sched_graph *graph, struct isl_clustering *c)
5919 int i;
5920 isl_space *space;
5921 isl_union_set *domain;
5923 space = isl_space_params_alloc(ctx, 0);
5924 domain = isl_union_set_empty(space);
5926 for (i = 0; i < graph->scc; ++i) {
5927 isl_space *space;
5929 if (!c->scc_in_merge[i])
5930 continue;
5931 if (c->scc_cluster[i] != i)
5932 continue;
5933 space = cluster_space(&c->scc[i], i);
5934 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5937 return domain;
5940 /* Construct a map from the original instances to the corresponding
5941 * cluster instance in the current bands of the clusters in "c".
5943 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5944 struct isl_sched_graph *graph, struct isl_clustering *c)
5946 int i, j;
5947 isl_space *space;
5948 isl_union_map *cluster_map;
5950 space = isl_space_params_alloc(ctx, 0);
5951 cluster_map = isl_union_map_empty(space);
5952 for (i = 0; i < graph->scc; ++i) {
5953 int start, n;
5954 isl_id *id;
5956 if (!c->scc_in_merge[i])
5957 continue;
5959 id = cluster_id(ctx, c->scc_cluster[i]);
5960 start = c->scc[i].band_start;
5961 n = c->scc[i].n_total_row - start;
5962 for (j = 0; j < c->scc[i].n; ++j) {
5963 isl_multi_aff *ma;
5964 isl_map *map;
5965 struct isl_sched_node *node = &c->scc[i].node[j];
5967 ma = node_extract_partial_schedule_multi_aff(node,
5968 start, n);
5969 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5970 isl_id_copy(id));
5971 map = isl_map_from_multi_aff(ma);
5972 cluster_map = isl_union_map_add_map(cluster_map, map);
5974 isl_id_free(id);
5977 return cluster_map;
5980 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5981 * that are not isl_edge_condition or isl_edge_conditional_validity.
5983 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5984 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5985 __isl_take isl_schedule_constraints *sc)
5987 enum isl_edge_type t;
5989 if (!sc)
5990 return NULL;
5992 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5993 if (t == isl_edge_condition ||
5994 t == isl_edge_conditional_validity)
5995 continue;
5996 if (!is_type(edge, t))
5997 continue;
5998 sc = isl_schedule_constraints_add(sc, t,
5999 isl_union_map_copy(umap));
6002 return sc;
6005 /* Add schedule constraints of types isl_edge_condition and
6006 * isl_edge_conditional_validity to "sc" by applying "umap" to
6007 * the domains of the wrapped relations in domain and range
6008 * of the corresponding tagged constraints of "edge".
6010 static __isl_give isl_schedule_constraints *add_conditional_constraints(
6011 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6012 __isl_take isl_schedule_constraints *sc)
6014 enum isl_edge_type t;
6015 isl_union_map *tagged;
6017 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
6018 if (!is_type(edge, t))
6019 continue;
6020 if (t == isl_edge_condition)
6021 tagged = isl_union_map_copy(edge->tagged_condition);
6022 else
6023 tagged = isl_union_map_copy(edge->tagged_validity);
6024 tagged = isl_union_map_zip(tagged);
6025 tagged = isl_union_map_apply_domain(tagged,
6026 isl_union_map_copy(umap));
6027 tagged = isl_union_map_zip(tagged);
6028 sc = isl_schedule_constraints_add(sc, t, tagged);
6029 if (!sc)
6030 return NULL;
6033 return sc;
6036 /* Given a mapping "cluster_map" from the original instances to
6037 * the cluster instances, add schedule constraints on the clusters
6038 * to "sc" corresponding to the original constraints represented by "edge".
6040 * For non-tagged dependence constraints, the cluster constraints
6041 * are obtained by applying "cluster_map" to the edge->map.
6043 * For tagged dependence constraints, "cluster_map" needs to be applied
6044 * to the domains of the wrapped relations in domain and range
6045 * of the tagged dependence constraints. Pick out the mappings
6046 * from these domains from "cluster_map" and construct their product.
6047 * This mapping can then be applied to the pair of domains.
6049 static __isl_give isl_schedule_constraints *collect_edge_constraints(
6050 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
6051 __isl_take isl_schedule_constraints *sc)
6053 isl_union_map *umap;
6054 isl_space *space;
6055 isl_union_set *uset;
6056 isl_union_map *umap1, *umap2;
6058 if (!sc)
6059 return NULL;
6061 umap = isl_union_map_from_map(isl_map_copy(edge->map));
6062 umap = isl_union_map_apply_domain(umap,
6063 isl_union_map_copy(cluster_map));
6064 umap = isl_union_map_apply_range(umap,
6065 isl_union_map_copy(cluster_map));
6066 sc = add_non_conditional_constraints(edge, umap, sc);
6067 isl_union_map_free(umap);
6069 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
6070 return sc;
6072 space = isl_space_domain(isl_map_get_space(edge->map));
6073 uset = isl_union_set_from_set(isl_set_universe(space));
6074 umap1 = isl_union_map_copy(cluster_map);
6075 umap1 = isl_union_map_intersect_domain(umap1, uset);
6076 space = isl_space_range(isl_map_get_space(edge->map));
6077 uset = isl_union_set_from_set(isl_set_universe(space));
6078 umap2 = isl_union_map_copy(cluster_map);
6079 umap2 = isl_union_map_intersect_domain(umap2, uset);
6080 umap = isl_union_map_product(umap1, umap2);
6082 sc = add_conditional_constraints(edge, umap, sc);
6084 isl_union_map_free(umap);
6085 return sc;
6088 /* Given a mapping "cluster_map" from the original instances to
6089 * the cluster instances, add schedule constraints on the clusters
6090 * to "sc" corresponding to all edges in "graph" between nodes that
6091 * belong to SCCs that are marked for merging in "scc_in_merge".
6093 static __isl_give isl_schedule_constraints *collect_constraints(
6094 struct isl_sched_graph *graph, int *scc_in_merge,
6095 __isl_keep isl_union_map *cluster_map,
6096 __isl_take isl_schedule_constraints *sc)
6098 int i;
6100 for (i = 0; i < graph->n_edge; ++i) {
6101 struct isl_sched_edge *edge = &graph->edge[i];
6103 if (!scc_in_merge[edge->src->scc])
6104 continue;
6105 if (!scc_in_merge[edge->dst->scc])
6106 continue;
6107 sc = collect_edge_constraints(edge, cluster_map, sc);
6110 return sc;
6113 /* Construct a dependence graph for scheduling clusters with respect
6114 * to each other and store the result in "merge_graph".
6115 * In particular, the nodes of the graph correspond to the schedule
6116 * dimensions of the current bands of those clusters that have been
6117 * marked for merging in "c".
6119 * First construct an isl_schedule_constraints object for this domain
6120 * by transforming the edges in "graph" to the domain.
6121 * Then initialize a dependence graph for scheduling from these
6122 * constraints.
6124 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
6125 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6127 isl_union_set *domain;
6128 isl_union_map *cluster_map;
6129 isl_schedule_constraints *sc;
6130 isl_stat r;
6132 domain = collect_domain(ctx, graph, c);
6133 sc = isl_schedule_constraints_on_domain(domain);
6134 if (!sc)
6135 return isl_stat_error;
6136 cluster_map = collect_cluster_map(ctx, graph, c);
6137 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
6138 isl_union_map_free(cluster_map);
6140 r = graph_init(merge_graph, sc);
6142 isl_schedule_constraints_free(sc);
6144 return r;
6147 /* Compute the maximal number of remaining schedule rows that still need
6148 * to be computed for the nodes that belong to clusters with the maximal
6149 * dimension for the current band (i.e., the band that is to be merged).
6150 * Only clusters that are about to be merged are considered.
6151 * "maxvar" is the maximal dimension for the current band.
6152 * "c" contains information about the clusters.
6154 * Return the maximal number of remaining schedule rows or -1 on error.
6156 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
6158 int i, j;
6159 int max_slack;
6161 max_slack = 0;
6162 for (i = 0; i < c->n; ++i) {
6163 int nvar;
6164 struct isl_sched_graph *scc;
6166 if (!c->scc_in_merge[i])
6167 continue;
6168 scc = &c->scc[i];
6169 nvar = scc->n_total_row - scc->band_start;
6170 if (nvar != maxvar)
6171 continue;
6172 for (j = 0; j < scc->n; ++j) {
6173 struct isl_sched_node *node = &scc->node[j];
6174 int slack;
6176 if (node_update_vmap(node) < 0)
6177 return -1;
6178 slack = node->nvar - node->rank;
6179 if (slack > max_slack)
6180 max_slack = slack;
6184 return max_slack;
6187 /* If there are any clusters where the dimension of the current band
6188 * (i.e., the band that is to be merged) is smaller than "maxvar" and
6189 * if there are any nodes in such a cluster where the number
6190 * of remaining schedule rows that still need to be computed
6191 * is greater than "max_slack", then return the smallest current band
6192 * dimension of all these clusters. Otherwise return the original value
6193 * of "maxvar". Return -1 in case of any error.
6194 * Only clusters that are about to be merged are considered.
6195 * "c" contains information about the clusters.
6197 static int limit_maxvar_to_slack(int maxvar, int max_slack,
6198 struct isl_clustering *c)
6200 int i, j;
6202 for (i = 0; i < c->n; ++i) {
6203 int nvar;
6204 struct isl_sched_graph *scc;
6206 if (!c->scc_in_merge[i])
6207 continue;
6208 scc = &c->scc[i];
6209 nvar = scc->n_total_row - scc->band_start;
6210 if (nvar >= maxvar)
6211 continue;
6212 for (j = 0; j < scc->n; ++j) {
6213 struct isl_sched_node *node = &scc->node[j];
6214 int slack;
6216 if (node_update_vmap(node) < 0)
6217 return -1;
6218 slack = node->nvar - node->rank;
6219 if (slack > max_slack) {
6220 maxvar = nvar;
6221 break;
6226 return maxvar;
6229 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
6230 * that still need to be computed. In particular, if there is a node
6231 * in a cluster where the dimension of the current band is smaller
6232 * than merge_graph->maxvar, but the number of remaining schedule rows
6233 * is greater than that of any node in a cluster with the maximal
6234 * dimension for the current band (i.e., merge_graph->maxvar),
6235 * then adjust merge_graph->maxvar to the (smallest) current band dimension
6236 * of those clusters. Without this adjustment, the total number of
6237 * schedule dimensions would be increased, resulting in a skewed view
6238 * of the number of coincident dimensions.
6239 * "c" contains information about the clusters.
6241 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
6242 * then there is no point in attempting any merge since it will be rejected
6243 * anyway. Set merge_graph->maxvar to zero in such cases.
6245 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
6246 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
6248 int max_slack, maxvar;
6250 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
6251 if (max_slack < 0)
6252 return isl_stat_error;
6253 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
6254 if (maxvar < 0)
6255 return isl_stat_error;
6257 if (maxvar < merge_graph->maxvar) {
6258 if (isl_options_get_schedule_maximize_band_depth(ctx))
6259 merge_graph->maxvar = 0;
6260 else
6261 merge_graph->maxvar = maxvar;
6264 return isl_stat_ok;
6267 /* Return the number of coincident dimensions in the current band of "graph",
6268 * where the nodes of "graph" are assumed to be scheduled by a single band.
6270 static int get_n_coincident(struct isl_sched_graph *graph)
6272 int i;
6274 for (i = graph->band_start; i < graph->n_total_row; ++i)
6275 if (!graph->node[0].coincident[i])
6276 break;
6278 return i - graph->band_start;
6281 /* Should the clusters be merged based on the cluster schedule
6282 * in the current (and only) band of "merge_graph", given that
6283 * coincidence should be maximized?
6285 * If the number of coincident schedule dimensions in the merged band
6286 * would be less than the maximal number of coincident schedule dimensions
6287 * in any of the merged clusters, then the clusters should not be merged.
6289 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
6290 struct isl_sched_graph *merge_graph)
6292 int i;
6293 int n_coincident;
6294 int max_coincident;
6296 max_coincident = 0;
6297 for (i = 0; i < c->n; ++i) {
6298 if (!c->scc_in_merge[i])
6299 continue;
6300 n_coincident = get_n_coincident(&c->scc[i]);
6301 if (n_coincident > max_coincident)
6302 max_coincident = n_coincident;
6305 n_coincident = get_n_coincident(merge_graph);
6307 return n_coincident >= max_coincident;
6310 /* Return the transformation on "node" expressed by the current (and only)
6311 * band of "merge_graph" applied to the clusters in "c".
6313 * First find the representation of "node" in its SCC in "c" and
6314 * extract the transformation expressed by the current band.
6315 * Then extract the transformation applied by "merge_graph"
6316 * to the cluster to which this SCC belongs.
6317 * Combine the two to obtain the complete transformation on the node.
6319 * Note that the range of the first transformation is an anonymous space,
6320 * while the domain of the second is named "cluster_X". The range
6321 * of the former therefore needs to be adjusted before the two
6322 * can be combined.
6324 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
6325 struct isl_sched_node *node, struct isl_clustering *c,
6326 struct isl_sched_graph *merge_graph)
6328 struct isl_sched_node *scc_node, *cluster_node;
6329 int start, n;
6330 isl_id *id;
6331 isl_space *space;
6332 isl_multi_aff *ma, *ma2;
6334 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
6335 start = c->scc[node->scc].band_start;
6336 n = c->scc[node->scc].n_total_row - start;
6337 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
6338 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
6339 cluster_node = graph_find_node(ctx, merge_graph, space);
6340 if (space && !cluster_node)
6341 isl_die(ctx, isl_error_internal, "unable to find cluster",
6342 space = isl_space_free(space));
6343 id = isl_space_get_tuple_id(space, isl_dim_set);
6344 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
6345 isl_space_free(space);
6346 n = merge_graph->n_total_row;
6347 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
6348 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
6350 return isl_map_from_multi_aff(ma);
6353 /* Give a set of distances "set", are they bounded by a small constant
6354 * in direction "pos"?
6355 * In practice, check if they are bounded by 2 by checking that there
6356 * are no elements with a value greater than or equal to 3 or
6357 * smaller than or equal to -3.
6359 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
6361 isl_bool bounded;
6362 isl_set *test;
6364 if (!set)
6365 return isl_bool_error;
6367 test = isl_set_copy(set);
6368 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
6369 bounded = isl_set_is_empty(test);
6370 isl_set_free(test);
6372 if (bounded < 0 || !bounded)
6373 return bounded;
6375 test = isl_set_copy(set);
6376 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
6377 bounded = isl_set_is_empty(test);
6378 isl_set_free(test);
6380 return bounded;
6383 /* Does the set "set" have a fixed (but possible parametric) value
6384 * at dimension "pos"?
6386 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
6388 int n;
6389 isl_bool single;
6391 if (!set)
6392 return isl_bool_error;
6393 set = isl_set_copy(set);
6394 n = isl_set_dim(set, isl_dim_set);
6395 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
6396 set = isl_set_project_out(set, isl_dim_set, 0, pos);
6397 single = isl_set_is_singleton(set);
6398 isl_set_free(set);
6400 return single;
6403 /* Does "map" have a fixed (but possible parametric) value
6404 * at dimension "pos" of either its domain or its range?
6406 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
6408 isl_set *set;
6409 isl_bool single;
6411 set = isl_map_domain(isl_map_copy(map));
6412 single = has_single_value(set, pos);
6413 isl_set_free(set);
6415 if (single < 0 || single)
6416 return single;
6418 set = isl_map_range(isl_map_copy(map));
6419 single = has_single_value(set, pos);
6420 isl_set_free(set);
6422 return single;
6425 /* Does the edge "edge" from "graph" have bounded dependence distances
6426 * in the merged graph "merge_graph" of a selection of clusters in "c"?
6428 * Extract the complete transformations of the source and destination
6429 * nodes of the edge, apply them to the edge constraints and
6430 * compute the differences. Finally, check if these differences are bounded
6431 * in each direction.
6433 * If the dimension of the band is greater than the number of
6434 * dimensions that can be expected to be optimized by the edge
6435 * (based on its weight), then also allow the differences to be unbounded
6436 * in the remaining dimensions, but only if either the source or
6437 * the destination has a fixed value in that direction.
6438 * This allows a statement that produces values that are used by
6439 * several instances of another statement to be merged with that
6440 * other statement.
6441 * However, merging such clusters will introduce an inherently
6442 * large proximity distance inside the merged cluster, meaning
6443 * that proximity distances will no longer be optimized in
6444 * subsequent merges. These merges are therefore only allowed
6445 * after all other possible merges have been tried.
6446 * The first time such a merge is encountered, the weight of the edge
6447 * is replaced by a negative weight. The second time (i.e., after
6448 * all merges over edges with a non-negative weight have been tried),
6449 * the merge is allowed.
6451 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
6452 struct isl_sched_graph *graph, struct isl_clustering *c,
6453 struct isl_sched_graph *merge_graph)
6455 int i, n, n_slack;
6456 isl_bool bounded;
6457 isl_map *map, *t;
6458 isl_set *dist;
6460 map = isl_map_copy(edge->map);
6461 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6462 map = isl_map_apply_domain(map, t);
6463 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6464 map = isl_map_apply_range(map, t);
6465 dist = isl_map_deltas(isl_map_copy(map));
6467 bounded = isl_bool_true;
6468 n = isl_set_dim(dist, isl_dim_set);
6469 n_slack = n - edge->weight;
6470 if (edge->weight < 0)
6471 n_slack -= graph->max_weight + 1;
6472 for (i = 0; i < n; ++i) {
6473 isl_bool bounded_i, singular_i;
6475 bounded_i = distance_is_bounded(dist, i);
6476 if (bounded_i < 0)
6477 goto error;
6478 if (bounded_i)
6479 continue;
6480 if (edge->weight >= 0)
6481 bounded = isl_bool_false;
6482 n_slack--;
6483 if (n_slack < 0)
6484 break;
6485 singular_i = has_singular_src_or_dst(map, i);
6486 if (singular_i < 0)
6487 goto error;
6488 if (singular_i)
6489 continue;
6490 bounded = isl_bool_false;
6491 break;
6493 if (!bounded && i >= n && edge->weight >= 0)
6494 edge->weight -= graph->max_weight + 1;
6495 isl_map_free(map);
6496 isl_set_free(dist);
6498 return bounded;
6499 error:
6500 isl_map_free(map);
6501 isl_set_free(dist);
6502 return isl_bool_error;
6505 /* Should the clusters be merged based on the cluster schedule
6506 * in the current (and only) band of "merge_graph"?
6507 * "graph" is the original dependence graph, while "c" records
6508 * which SCCs are involved in the latest merge.
6510 * In particular, is there at least one proximity constraint
6511 * that is optimized by the merge?
6513 * A proximity constraint is considered to be optimized
6514 * if the dependence distances are small.
6516 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6517 struct isl_sched_graph *graph, struct isl_clustering *c,
6518 struct isl_sched_graph *merge_graph)
6520 int i;
6522 for (i = 0; i < graph->n_edge; ++i) {
6523 struct isl_sched_edge *edge = &graph->edge[i];
6524 isl_bool bounded;
6526 if (!is_proximity(edge))
6527 continue;
6528 if (!c->scc_in_merge[edge->src->scc])
6529 continue;
6530 if (!c->scc_in_merge[edge->dst->scc])
6531 continue;
6532 if (c->scc_cluster[edge->dst->scc] ==
6533 c->scc_cluster[edge->src->scc])
6534 continue;
6535 bounded = has_bounded_distances(ctx, edge, graph, c,
6536 merge_graph);
6537 if (bounded < 0 || bounded)
6538 return bounded;
6541 return isl_bool_false;
6544 /* Should the clusters be merged based on the cluster schedule
6545 * in the current (and only) band of "merge_graph"?
6546 * "graph" is the original dependence graph, while "c" records
6547 * which SCCs are involved in the latest merge.
6549 * If the current band is empty, then the clusters should not be merged.
6551 * If the band depth should be maximized and the merge schedule
6552 * is incomplete (meaning that the dimension of some of the schedule
6553 * bands in the original schedule will be reduced), then the clusters
6554 * should not be merged.
6556 * If the schedule_maximize_coincidence option is set, then check that
6557 * the number of coincident schedule dimensions is not reduced.
6559 * Finally, only allow the merge if at least one proximity
6560 * constraint is optimized.
6562 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6563 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6565 if (merge_graph->n_total_row == merge_graph->band_start)
6566 return isl_bool_false;
6568 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6569 merge_graph->n_total_row < merge_graph->maxvar)
6570 return isl_bool_false;
6572 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6573 isl_bool ok;
6575 ok = ok_to_merge_coincident(c, merge_graph);
6576 if (ok < 0 || !ok)
6577 return ok;
6580 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6583 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6584 * of the schedule in "node" and return the result.
6586 * That is, essentially compute
6588 * T * N(first:first+n-1)
6590 * taking into account the constant term and the parameter coefficients
6591 * in "t_node".
6593 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6594 struct isl_sched_node *t_node, struct isl_sched_node *node,
6595 int first, int n)
6597 int i, j;
6598 isl_mat *t;
6599 int n_row, n_col, n_param, n_var;
6601 n_param = node->nparam;
6602 n_var = node->nvar;
6603 n_row = isl_mat_rows(t_node->sched);
6604 n_col = isl_mat_cols(node->sched);
6605 t = isl_mat_alloc(ctx, n_row, n_col);
6606 if (!t)
6607 return NULL;
6608 for (i = 0; i < n_row; ++i) {
6609 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6610 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6611 for (j = 0; j < n; ++j)
6612 isl_seq_addmul(t->row[i],
6613 t_node->sched->row[i][1 + n_param + j],
6614 node->sched->row[first + j],
6615 1 + n_param + n_var);
6617 return t;
6620 /* Apply the cluster schedule in "t_node" to the current band
6621 * schedule of the nodes in "graph".
6623 * In particular, replace the rows starting at band_start
6624 * by the result of applying the cluster schedule in "t_node"
6625 * to the original rows.
6627 * The coincidence of the schedule is determined by the coincidence
6628 * of the cluster schedule.
6630 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6631 struct isl_sched_node *t_node)
6633 int i, j;
6634 int n_new;
6635 int start, n;
6637 start = graph->band_start;
6638 n = graph->n_total_row - start;
6640 n_new = isl_mat_rows(t_node->sched);
6641 for (i = 0; i < graph->n; ++i) {
6642 struct isl_sched_node *node = &graph->node[i];
6643 isl_mat *t;
6645 t = node_transformation(ctx, t_node, node, start, n);
6646 node->sched = isl_mat_drop_rows(node->sched, start, n);
6647 node->sched = isl_mat_concat(node->sched, t);
6648 node->sched_map = isl_map_free(node->sched_map);
6649 if (!node->sched)
6650 return isl_stat_error;
6651 for (j = 0; j < n_new; ++j)
6652 node->coincident[start + j] = t_node->coincident[j];
6654 graph->n_total_row -= n;
6655 graph->n_row -= n;
6656 graph->n_total_row += n_new;
6657 graph->n_row += n_new;
6659 return isl_stat_ok;
6662 /* Merge the clusters marked for merging in "c" into a single
6663 * cluster using the cluster schedule in the current band of "merge_graph".
6664 * The representative SCC for the new cluster is the SCC with
6665 * the smallest index.
6667 * The current band schedule of each SCC in the new cluster is obtained
6668 * by applying the schedule of the corresponding original cluster
6669 * to the original band schedule.
6670 * All SCCs in the new cluster have the same number of schedule rows.
6672 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6673 struct isl_sched_graph *merge_graph)
6675 int i;
6676 int cluster = -1;
6677 isl_space *space;
6679 for (i = 0; i < c->n; ++i) {
6680 struct isl_sched_node *node;
6682 if (!c->scc_in_merge[i])
6683 continue;
6684 if (cluster < 0)
6685 cluster = i;
6686 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6687 if (!space)
6688 return isl_stat_error;
6689 node = graph_find_node(ctx, merge_graph, space);
6690 isl_space_free(space);
6691 if (!node)
6692 isl_die(ctx, isl_error_internal,
6693 "unable to find cluster",
6694 return isl_stat_error);
6695 if (transform(ctx, &c->scc[i], node) < 0)
6696 return isl_stat_error;
6697 c->scc_cluster[i] = cluster;
6700 return isl_stat_ok;
6703 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6704 * by scheduling the current cluster bands with respect to each other.
6706 * Construct a dependence graph with a space for each cluster and
6707 * with the coordinates of each space corresponding to the schedule
6708 * dimensions of the current band of that cluster.
6709 * Construct a cluster schedule in this cluster dependence graph and
6710 * apply it to the current cluster bands if it is applicable
6711 * according to ok_to_merge.
6713 * If the number of remaining schedule dimensions in a cluster
6714 * with a non-maximal current schedule dimension is greater than
6715 * the number of remaining schedule dimensions in clusters
6716 * with a maximal current schedule dimension, then restrict
6717 * the number of rows to be computed in the cluster schedule
6718 * to the minimal such non-maximal current schedule dimension.
6719 * Do this by adjusting merge_graph.maxvar.
6721 * Return isl_bool_true if the clusters have effectively been merged
6722 * into a single cluster.
6724 * Note that since the standard scheduling algorithm minimizes the maximal
6725 * distance over proximity constraints, the proximity constraints between
6726 * the merged clusters may not be optimized any further than what is
6727 * sufficient to bring the distances within the limits of the internal
6728 * proximity constraints inside the individual clusters.
6729 * It may therefore make sense to perform an additional translation step
6730 * to bring the clusters closer to each other, while maintaining
6731 * the linear part of the merging schedule found using the standard
6732 * scheduling algorithm.
6734 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6735 struct isl_clustering *c)
6737 struct isl_sched_graph merge_graph = { 0 };
6738 isl_bool merged;
6740 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6741 goto error;
6743 if (compute_maxvar(&merge_graph) < 0)
6744 goto error;
6745 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6746 goto error;
6747 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6748 goto error;
6749 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6750 if (merged && merge(ctx, c, &merge_graph) < 0)
6751 goto error;
6753 graph_free(ctx, &merge_graph);
6754 return merged;
6755 error:
6756 graph_free(ctx, &merge_graph);
6757 return isl_bool_error;
6760 /* Is there any edge marked "no_merge" between two SCCs that are
6761 * about to be merged (i.e., that are set in "scc_in_merge")?
6762 * "merge_edge" is the proximity edge along which the clusters of SCCs
6763 * are going to be merged.
6765 * If there is any edge between two SCCs with a negative weight,
6766 * while the weight of "merge_edge" is non-negative, then this
6767 * means that the edge was postponed. "merge_edge" should then
6768 * also be postponed since merging along the edge with negative weight should
6769 * be postponed until all edges with non-negative weight have been tried.
6770 * Replace the weight of "merge_edge" by a negative weight as well and
6771 * tell the caller not to attempt a merge.
6773 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6774 struct isl_sched_edge *merge_edge)
6776 int i;
6778 for (i = 0; i < graph->n_edge; ++i) {
6779 struct isl_sched_edge *edge = &graph->edge[i];
6781 if (!scc_in_merge[edge->src->scc])
6782 continue;
6783 if (!scc_in_merge[edge->dst->scc])
6784 continue;
6785 if (edge->no_merge)
6786 return 1;
6787 if (merge_edge->weight >= 0 && edge->weight < 0) {
6788 merge_edge->weight -= graph->max_weight + 1;
6789 return 1;
6793 return 0;
6796 /* Merge the two clusters in "c" connected by the edge in "graph"
6797 * with index "edge" into a single cluster.
6798 * If it turns out to be impossible to merge these two clusters,
6799 * then mark the edge as "no_merge" such that it will not be
6800 * considered again.
6802 * First mark all SCCs that need to be merged. This includes the SCCs
6803 * in the two clusters, but it may also include the SCCs
6804 * of intermediate clusters.
6805 * If there is already a no_merge edge between any pair of such SCCs,
6806 * then simply mark the current edge as no_merge as well.
6807 * Likewise, if any of those edges was postponed by has_bounded_distances,
6808 * then postpone the current edge as well.
6809 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6810 * if the clusters did not end up getting merged, unless the non-merge
6811 * is due to the fact that the edge was postponed. This postponement
6812 * can be recognized by a change in weight (from non-negative to negative).
6814 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6815 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6817 isl_bool merged;
6818 int edge_weight = graph->edge[edge].weight;
6820 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6821 return isl_stat_error;
6823 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6824 merged = isl_bool_false;
6825 else
6826 merged = try_merge(ctx, graph, c);
6827 if (merged < 0)
6828 return isl_stat_error;
6829 if (!merged && edge_weight == graph->edge[edge].weight)
6830 graph->edge[edge].no_merge = 1;
6832 return isl_stat_ok;
6835 /* Does "node" belong to the cluster identified by "cluster"?
6837 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6839 return node->cluster == cluster;
6842 /* Does "edge" connect two nodes belonging to the cluster
6843 * identified by "cluster"?
6845 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6847 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6850 /* Swap the schedule of "node1" and "node2".
6851 * Both nodes have been derived from the same node in a common parent graph.
6852 * Since the "coincident" field is shared with that node
6853 * in the parent graph, there is no need to also swap this field.
6855 static void swap_sched(struct isl_sched_node *node1,
6856 struct isl_sched_node *node2)
6858 isl_mat *sched;
6859 isl_map *sched_map;
6861 sched = node1->sched;
6862 node1->sched = node2->sched;
6863 node2->sched = sched;
6865 sched_map = node1->sched_map;
6866 node1->sched_map = node2->sched_map;
6867 node2->sched_map = sched_map;
6870 /* Copy the current band schedule from the SCCs that form the cluster
6871 * with index "pos" to the actual cluster at position "pos".
6872 * By construction, the index of the first SCC that belongs to the cluster
6873 * is also "pos".
6875 * The order of the nodes inside both the SCCs and the cluster
6876 * is assumed to be same as the order in the original "graph".
6878 * Since the SCC graphs will no longer be used after this function,
6879 * the schedules are actually swapped rather than copied.
6881 static isl_stat copy_partial(struct isl_sched_graph *graph,
6882 struct isl_clustering *c, int pos)
6884 int i, j;
6886 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6887 c->cluster[pos].n_row = c->scc[pos].n_row;
6888 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6889 j = 0;
6890 for (i = 0; i < graph->n; ++i) {
6891 int k;
6892 int s;
6894 if (graph->node[i].cluster != pos)
6895 continue;
6896 s = graph->node[i].scc;
6897 k = c->scc_node[s]++;
6898 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6899 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6900 c->cluster[pos].maxvar = c->scc[s].maxvar;
6901 ++j;
6904 return isl_stat_ok;
6907 /* Is there a (conditional) validity dependence from node[j] to node[i],
6908 * forcing node[i] to follow node[j] or do the nodes belong to the same
6909 * cluster?
6911 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6913 struct isl_sched_graph *graph = user;
6915 if (graph->node[i].cluster == graph->node[j].cluster)
6916 return isl_bool_true;
6917 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6920 /* Extract the merged clusters of SCCs in "graph", sort them, and
6921 * store them in c->clusters. Update c->scc_cluster accordingly.
6923 * First keep track of the cluster containing the SCC to which a node
6924 * belongs in the node itself.
6925 * Then extract the clusters into c->clusters, copying the current
6926 * band schedule from the SCCs that belong to the cluster.
6927 * Do this only once per cluster.
6929 * Finally, topologically sort the clusters and update c->scc_cluster
6930 * to match the new scc numbering. While the SCCs were originally
6931 * sorted already, some SCCs that depend on some other SCCs may
6932 * have been merged with SCCs that appear before these other SCCs.
6933 * A reordering may therefore be required.
6935 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6936 struct isl_clustering *c)
6938 int i;
6940 for (i = 0; i < graph->n; ++i)
6941 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6943 for (i = 0; i < graph->scc; ++i) {
6944 if (c->scc_cluster[i] != i)
6945 continue;
6946 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6947 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6948 return isl_stat_error;
6949 c->cluster[i].src_scc = -1;
6950 c->cluster[i].dst_scc = -1;
6951 if (copy_partial(graph, c, i) < 0)
6952 return isl_stat_error;
6955 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6956 return isl_stat_error;
6957 for (i = 0; i < graph->n; ++i)
6958 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6960 return isl_stat_ok;
6963 /* Compute weights on the proximity edges of "graph" that can
6964 * be used by find_proximity to find the most appropriate
6965 * proximity edge to use to merge two clusters in "c".
6966 * The weights are also used by has_bounded_distances to determine
6967 * whether the merge should be allowed.
6968 * Store the maximum of the computed weights in graph->max_weight.
6970 * The computed weight is a measure for the number of remaining schedule
6971 * dimensions that can still be completely aligned.
6972 * In particular, compute the number of equalities between
6973 * input dimensions and output dimensions in the proximity constraints.
6974 * The directions that are already handled by outer schedule bands
6975 * are projected out prior to determining this number.
6977 * Edges that will never be considered by find_proximity are ignored.
6979 static isl_stat compute_weights(struct isl_sched_graph *graph,
6980 struct isl_clustering *c)
6982 int i;
6984 graph->max_weight = 0;
6986 for (i = 0; i < graph->n_edge; ++i) {
6987 struct isl_sched_edge *edge = &graph->edge[i];
6988 struct isl_sched_node *src = edge->src;
6989 struct isl_sched_node *dst = edge->dst;
6990 isl_basic_map *hull;
6991 isl_bool prox;
6992 int n_in, n_out;
6994 prox = is_non_empty_proximity(edge);
6995 if (prox < 0)
6996 return isl_stat_error;
6997 if (!prox)
6998 continue;
6999 if (bad_cluster(&c->scc[edge->src->scc]) ||
7000 bad_cluster(&c->scc[edge->dst->scc]))
7001 continue;
7002 if (c->scc_cluster[edge->dst->scc] ==
7003 c->scc_cluster[edge->src->scc])
7004 continue;
7006 hull = isl_map_affine_hull(isl_map_copy(edge->map));
7007 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
7008 isl_mat_copy(src->vmap));
7009 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
7010 isl_mat_copy(dst->vmap));
7011 hull = isl_basic_map_project_out(hull,
7012 isl_dim_in, 0, src->rank);
7013 hull = isl_basic_map_project_out(hull,
7014 isl_dim_out, 0, dst->rank);
7015 hull = isl_basic_map_remove_divs(hull);
7016 n_in = isl_basic_map_dim(hull, isl_dim_in);
7017 n_out = isl_basic_map_dim(hull, isl_dim_out);
7018 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7019 isl_dim_in, 0, n_in);
7020 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7021 isl_dim_out, 0, n_out);
7022 if (!hull)
7023 return isl_stat_error;
7024 edge->weight = isl_basic_map_n_equality(hull);
7025 isl_basic_map_free(hull);
7027 if (edge->weight > graph->max_weight)
7028 graph->max_weight = edge->weight;
7031 return isl_stat_ok;
7034 /* Call compute_schedule_finish_band on each of the clusters in "c"
7035 * in their topological order. This order is determined by the scc
7036 * fields of the nodes in "graph".
7037 * Combine the results in a sequence expressing the topological order.
7039 * If there is only one cluster left, then there is no need to introduce
7040 * a sequence node. Also, in this case, the cluster necessarily contains
7041 * the SCC at position 0 in the original graph and is therefore also
7042 * stored in the first cluster of "c".
7044 static __isl_give isl_schedule_node *finish_bands_clustering(
7045 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7046 struct isl_clustering *c)
7048 int i;
7049 isl_ctx *ctx;
7050 isl_union_set_list *filters;
7052 if (graph->scc == 1)
7053 return compute_schedule_finish_band(node, &c->cluster[0], 0);
7055 ctx = isl_schedule_node_get_ctx(node);
7057 filters = extract_sccs(ctx, graph);
7058 node = isl_schedule_node_insert_sequence(node, filters);
7060 for (i = 0; i < graph->scc; ++i) {
7061 int j = c->scc_cluster[i];
7062 node = isl_schedule_node_child(node, i);
7063 node = isl_schedule_node_child(node, 0);
7064 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
7065 node = isl_schedule_node_parent(node);
7066 node = isl_schedule_node_parent(node);
7069 return node;
7072 /* Compute a schedule for a connected dependence graph by first considering
7073 * each strongly connected component (SCC) in the graph separately and then
7074 * incrementally combining them into clusters.
7075 * Return the updated schedule node.
7077 * Initially, each cluster consists of a single SCC, each with its
7078 * own band schedule. The algorithm then tries to merge pairs
7079 * of clusters along a proximity edge until no more suitable
7080 * proximity edges can be found. During this merging, the schedule
7081 * is maintained in the individual SCCs.
7082 * After the merging is completed, the full resulting clusters
7083 * are extracted and in finish_bands_clustering,
7084 * compute_schedule_finish_band is called on each of them to integrate
7085 * the band into "node" and to continue the computation.
7087 * compute_weights initializes the weights that are used by find_proximity.
7089 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
7090 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7092 isl_ctx *ctx;
7093 struct isl_clustering c;
7094 int i;
7096 ctx = isl_schedule_node_get_ctx(node);
7098 if (clustering_init(ctx, &c, graph) < 0)
7099 goto error;
7101 if (compute_weights(graph, &c) < 0)
7102 goto error;
7104 for (;;) {
7105 i = find_proximity(graph, &c);
7106 if (i < 0)
7107 goto error;
7108 if (i >= graph->n_edge)
7109 break;
7110 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
7111 goto error;
7114 if (extract_clusters(ctx, graph, &c) < 0)
7115 goto error;
7117 node = finish_bands_clustering(node, graph, &c);
7119 clustering_free(ctx, &c);
7120 return node;
7121 error:
7122 clustering_free(ctx, &c);
7123 return isl_schedule_node_free(node);
7126 /* Compute a schedule for a connected dependence graph and return
7127 * the updated schedule node.
7129 * If Feautrier's algorithm is selected, we first recursively try to satisfy
7130 * as many validity dependences as possible. When all validity dependences
7131 * are satisfied we extend the schedule to a full-dimensional schedule.
7133 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
7134 * depending on whether the user has selected the option to try and
7135 * compute a schedule for the entire (weakly connected) component first.
7136 * If there is only a single strongly connected component (SCC), then
7137 * there is no point in trying to combine SCCs
7138 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
7139 * is called instead.
7141 static __isl_give isl_schedule_node *compute_schedule_wcc(
7142 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7144 isl_ctx *ctx;
7146 if (!node)
7147 return NULL;
7149 ctx = isl_schedule_node_get_ctx(node);
7150 if (detect_sccs(ctx, graph) < 0)
7151 return isl_schedule_node_free(node);
7153 if (compute_maxvar(graph) < 0)
7154 return isl_schedule_node_free(node);
7156 if (need_feautrier_step(ctx, graph))
7157 return compute_schedule_wcc_feautrier(node, graph);
7159 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
7160 return compute_schedule_wcc_whole(node, graph);
7161 else
7162 return compute_schedule_wcc_clustering(node, graph);
7165 /* Compute a schedule for each group of nodes identified by node->scc
7166 * separately and then combine them in a sequence node (or as set node
7167 * if graph->weak is set) inserted at position "node" of the schedule tree.
7168 * Return the updated schedule node.
7170 * If "wcc" is set then each of the groups belongs to a single
7171 * weakly connected component in the dependence graph so that
7172 * there is no need for compute_sub_schedule to look for weakly
7173 * connected components.
7175 static __isl_give isl_schedule_node *compute_component_schedule(
7176 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7177 int wcc)
7179 int component;
7180 isl_ctx *ctx;
7181 isl_union_set_list *filters;
7183 if (!node)
7184 return NULL;
7185 ctx = isl_schedule_node_get_ctx(node);
7187 filters = extract_sccs(ctx, graph);
7188 if (graph->weak)
7189 node = isl_schedule_node_insert_set(node, filters);
7190 else
7191 node = isl_schedule_node_insert_sequence(node, filters);
7193 for (component = 0; component < graph->scc; ++component) {
7194 node = isl_schedule_node_child(node, component);
7195 node = isl_schedule_node_child(node, 0);
7196 node = compute_sub_schedule(node, ctx, graph,
7197 &node_scc_exactly,
7198 &edge_scc_exactly, component, wcc);
7199 node = isl_schedule_node_parent(node);
7200 node = isl_schedule_node_parent(node);
7203 return node;
7206 /* Compute a schedule for the given dependence graph and insert it at "node".
7207 * Return the updated schedule node.
7209 * We first check if the graph is connected (through validity and conditional
7210 * validity dependences) and, if not, compute a schedule
7211 * for each component separately.
7212 * If the schedule_serialize_sccs option is set, then we check for strongly
7213 * connected components instead and compute a separate schedule for
7214 * each such strongly connected component.
7216 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
7217 struct isl_sched_graph *graph)
7219 isl_ctx *ctx;
7221 if (!node)
7222 return NULL;
7224 ctx = isl_schedule_node_get_ctx(node);
7225 if (isl_options_get_schedule_serialize_sccs(ctx)) {
7226 if (detect_sccs(ctx, graph) < 0)
7227 return isl_schedule_node_free(node);
7228 } else {
7229 if (detect_wccs(ctx, graph) < 0)
7230 return isl_schedule_node_free(node);
7233 if (graph->scc > 1)
7234 return compute_component_schedule(node, graph, 1);
7236 return compute_schedule_wcc(node, graph);
7239 /* Compute a schedule on sc->domain that respects the given schedule
7240 * constraints.
7242 * In particular, the schedule respects all the validity dependences.
7243 * If the default isl scheduling algorithm is used, it tries to minimize
7244 * the dependence distances over the proximity dependences.
7245 * If Feautrier's scheduling algorithm is used, the proximity dependence
7246 * distances are only minimized during the extension to a full-dimensional
7247 * schedule.
7249 * If there are any condition and conditional validity dependences,
7250 * then the conditional validity dependences may be violated inside
7251 * a tilable band, provided they have no adjacent non-local
7252 * condition dependences.
7254 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
7255 __isl_take isl_schedule_constraints *sc)
7257 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
7258 struct isl_sched_graph graph = { 0 };
7259 isl_schedule *sched;
7260 isl_schedule_node *node;
7261 isl_union_set *domain;
7263 sc = isl_schedule_constraints_align_params(sc);
7265 domain = isl_schedule_constraints_get_domain(sc);
7266 if (isl_union_set_n_set(domain) == 0) {
7267 isl_schedule_constraints_free(sc);
7268 return isl_schedule_from_domain(domain);
7271 if (graph_init(&graph, sc) < 0)
7272 domain = isl_union_set_free(domain);
7274 node = isl_schedule_node_from_domain(domain);
7275 node = isl_schedule_node_child(node, 0);
7276 if (graph.n > 0)
7277 node = compute_schedule(node, &graph);
7278 sched = isl_schedule_node_get_schedule(node);
7279 isl_schedule_node_free(node);
7281 graph_free(ctx, &graph);
7282 isl_schedule_constraints_free(sc);
7284 return sched;
7287 /* Compute a schedule for the given union of domains that respects
7288 * all the validity dependences and minimizes
7289 * the dependence distances over the proximity dependences.
7291 * This function is kept for backward compatibility.
7293 __isl_give isl_schedule *isl_union_set_compute_schedule(
7294 __isl_take isl_union_set *domain,
7295 __isl_take isl_union_map *validity,
7296 __isl_take isl_union_map *proximity)
7298 isl_schedule_constraints *sc;
7300 sc = isl_schedule_constraints_on_domain(domain);
7301 sc = isl_schedule_constraints_set_validity(sc, validity);
7302 sc = isl_schedule_constraints_set_proximity(sc, proximity);
7304 return isl_schedule_constraints_compute_schedule(sc);