isl_scheduler.c: compute_schedule_finish_band: split along SCCs before carrying
[isl.git] / isl_scheduler.c
blob68eccae439d3da3da4efefdb03b6b46b4c7a2b5c
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.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.
98 struct isl_sched_node {
99 isl_space *space;
100 int compressed;
101 isl_set *hull;
102 isl_multi_aff *compress;
103 isl_multi_aff *decompress;
104 isl_mat *sched;
105 isl_map *sched_map;
106 int rank;
107 isl_mat *indep;
108 isl_mat *vmap;
109 int start;
110 int nvar;
111 int nparam;
113 int scc;
114 int cluster;
116 int *coincident;
118 isl_multi_val *sizes;
119 isl_vec *max;
122 static int node_has_tuples(const void *entry, const void *val)
124 struct isl_sched_node *node = (struct isl_sched_node *)entry;
125 isl_space *space = (isl_space *) val;
127 return isl_space_has_equal_tuples(node->space, space);
130 static int node_scc_exactly(struct isl_sched_node *node, int scc)
132 return node->scc == scc;
135 static int node_scc_at_most(struct isl_sched_node *node, int scc)
137 return node->scc <= scc;
140 static int node_scc_at_least(struct isl_sched_node *node, int scc)
142 return node->scc >= scc;
145 /* An edge in the dependence graph. An edge may be used to
146 * ensure validity of the generated schedule, to minimize the dependence
147 * distance or both
149 * map is the dependence relation, with i -> j in the map if j depends on i
150 * tagged_condition and tagged_validity contain the union of all tagged
151 * condition or conditional validity dependence relations that
152 * specialize the dependence relation "map"; that is,
153 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
154 * or "tagged_validity", then i -> j is an element of "map".
155 * If these fields are NULL, then they represent the empty relation.
156 * src is the source node
157 * dst is the sink node
159 * types is a bit vector containing the types of this edge.
160 * validity is set if the edge is used to ensure correctness
161 * coincidence is used to enforce zero dependence distances
162 * proximity is set if the edge is used to minimize dependence distances
163 * condition is set if the edge represents a condition
164 * for a conditional validity schedule constraint
165 * local can only be set for condition edges and indicates that
166 * the dependence distance over the edge should be zero
167 * conditional_validity is set if the edge is used to conditionally
168 * ensure correctness
170 * For validity edges, start and end mark the sequence of inequality
171 * constraints in the LP problem that encode the validity constraint
172 * corresponding to this edge.
174 * During clustering, an edge may be marked "no_merge" if it should
175 * not be used to merge clusters.
176 * The weight is also only used during clustering and it is
177 * an indication of how many schedule dimensions on either side
178 * of the schedule constraints can be aligned.
179 * If the weight is negative, then this means that this edge was postponed
180 * by has_bounded_distances or any_no_merge. The original weight can
181 * be retrieved by adding 1 + graph->max_weight, with "graph"
182 * the graph containing this edge.
184 struct isl_sched_edge {
185 isl_map *map;
186 isl_union_map *tagged_condition;
187 isl_union_map *tagged_validity;
189 struct isl_sched_node *src;
190 struct isl_sched_node *dst;
192 unsigned types;
194 int start;
195 int end;
197 int no_merge;
198 int weight;
201 /* Is "edge" marked as being of type "type"?
203 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
205 return ISL_FL_ISSET(edge->types, 1 << type);
208 /* Mark "edge" as being of type "type".
210 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
212 ISL_FL_SET(edge->types, 1 << type);
215 /* No longer mark "edge" as being of type "type"?
217 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
219 ISL_FL_CLR(edge->types, 1 << type);
222 /* Is "edge" marked as a validity edge?
224 static int is_validity(struct isl_sched_edge *edge)
226 return is_type(edge, isl_edge_validity);
229 /* Mark "edge" as a validity edge.
231 static void set_validity(struct isl_sched_edge *edge)
233 set_type(edge, isl_edge_validity);
236 /* Is "edge" marked as a proximity edge?
238 static int is_proximity(struct isl_sched_edge *edge)
240 return is_type(edge, isl_edge_proximity);
243 /* Is "edge" marked as a local edge?
245 static int is_local(struct isl_sched_edge *edge)
247 return is_type(edge, isl_edge_local);
250 /* Mark "edge" as a local edge.
252 static void set_local(struct isl_sched_edge *edge)
254 set_type(edge, isl_edge_local);
257 /* No longer mark "edge" as a local edge.
259 static void clear_local(struct isl_sched_edge *edge)
261 clear_type(edge, isl_edge_local);
264 /* Is "edge" marked as a coincidence edge?
266 static int is_coincidence(struct isl_sched_edge *edge)
268 return is_type(edge, isl_edge_coincidence);
271 /* Is "edge" marked as a condition edge?
273 static int is_condition(struct isl_sched_edge *edge)
275 return is_type(edge, isl_edge_condition);
278 /* Is "edge" marked as a conditional validity edge?
280 static int is_conditional_validity(struct isl_sched_edge *edge)
282 return is_type(edge, isl_edge_conditional_validity);
285 /* Internal information about the dependence graph used during
286 * the construction of the schedule.
288 * intra_hmap is a cache, mapping dependence relations to their dual,
289 * for dependences from a node to itself
290 * inter_hmap is a cache, mapping dependence relations to their dual,
291 * for dependences between distinct nodes
292 * if compression is involved then the key for these maps
293 * is the original, uncompressed dependence relation, while
294 * the value is the dual of the compressed dependence relation.
296 * n is the number of nodes
297 * node is the list of nodes
298 * maxvar is the maximal number of variables over all nodes
299 * max_row is the allocated number of rows in the schedule
300 * n_row is the current (maximal) number of linearly independent
301 * rows in the node schedules
302 * n_total_row is the current number of rows in the node schedules
303 * band_start is the starting row in the node schedules of the current band
304 * root is set if this graph is the original dependence graph,
305 * without any splitting
307 * sorted contains a list of node indices sorted according to the
308 * SCC to which a node belongs
310 * n_edge is the number of edges
311 * edge is the list of edges
312 * max_edge contains the maximal number of edges of each type;
313 * in particular, it contains the number of edges in the inital graph.
314 * edge_table contains pointers into the edge array, hashed on the source
315 * and sink spaces; there is one such table for each type;
316 * a given edge may be referenced from more than one table
317 * if the corresponding relation appears in more than one of the
318 * sets of dependences; however, for each type there is only
319 * a single edge between a given pair of source and sink space
320 * in the entire graph
322 * node_table contains pointers into the node array, hashed on the space tuples
324 * region contains a list of variable sequences that should be non-trivial
326 * lp contains the (I)LP problem used to obtain new schedule rows
328 * src_scc and dst_scc are the source and sink SCCs of an edge with
329 * conflicting constraints
331 * scc represents the number of components
332 * weak is set if the components are weakly connected
334 * max_weight is used during clustering and represents the maximal
335 * weight of the relevant proximity edges.
337 struct isl_sched_graph {
338 isl_map_to_basic_set *intra_hmap;
339 isl_map_to_basic_set *inter_hmap;
341 struct isl_sched_node *node;
342 int n;
343 int maxvar;
344 int max_row;
345 int n_row;
347 int *sorted;
349 int n_total_row;
350 int band_start;
352 int root;
354 struct isl_sched_edge *edge;
355 int n_edge;
356 int max_edge[isl_edge_last + 1];
357 struct isl_hash_table *edge_table[isl_edge_last + 1];
359 struct isl_hash_table *node_table;
360 struct isl_trivial_region *region;
362 isl_basic_set *lp;
364 int src_scc;
365 int dst_scc;
367 int scc;
368 int weak;
370 int max_weight;
373 /* Initialize node_table based on the list of nodes.
375 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
377 int i;
379 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
380 if (!graph->node_table)
381 return -1;
383 for (i = 0; i < graph->n; ++i) {
384 struct isl_hash_table_entry *entry;
385 uint32_t hash;
387 hash = isl_space_get_tuple_hash(graph->node[i].space);
388 entry = isl_hash_table_find(ctx, graph->node_table, hash,
389 &node_has_tuples,
390 graph->node[i].space, 1);
391 if (!entry)
392 return -1;
393 entry->data = &graph->node[i];
396 return 0;
399 /* Return a pointer to the node that lives within the given space,
400 * or NULL if there is no such node.
402 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
403 struct isl_sched_graph *graph, __isl_keep isl_space *space)
405 struct isl_hash_table_entry *entry;
406 uint32_t hash;
408 hash = isl_space_get_tuple_hash(space);
409 entry = isl_hash_table_find(ctx, graph->node_table, hash,
410 &node_has_tuples, space, 0);
412 return entry ? entry->data : NULL;
415 static int edge_has_src_and_dst(const void *entry, const void *val)
417 const struct isl_sched_edge *edge = entry;
418 const struct isl_sched_edge *temp = val;
420 return edge->src == temp->src && edge->dst == temp->dst;
423 /* Add the given edge to graph->edge_table[type].
425 static isl_stat graph_edge_table_add(isl_ctx *ctx,
426 struct isl_sched_graph *graph, enum isl_edge_type type,
427 struct isl_sched_edge *edge)
429 struct isl_hash_table_entry *entry;
430 uint32_t hash;
432 hash = isl_hash_init();
433 hash = isl_hash_builtin(hash, edge->src);
434 hash = isl_hash_builtin(hash, edge->dst);
435 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
436 &edge_has_src_and_dst, edge, 1);
437 if (!entry)
438 return isl_stat_error;
439 entry->data = edge;
441 return isl_stat_ok;
444 /* Allocate the edge_tables based on the maximal number of edges of
445 * each type.
447 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
449 int i;
451 for (i = 0; i <= isl_edge_last; ++i) {
452 graph->edge_table[i] = isl_hash_table_alloc(ctx,
453 graph->max_edge[i]);
454 if (!graph->edge_table[i])
455 return -1;
458 return 0;
461 /* If graph->edge_table[type] contains an edge from the given source
462 * to the given destination, then return the hash table entry of this edge.
463 * Otherwise, return NULL.
465 static struct isl_hash_table_entry *graph_find_edge_entry(
466 struct isl_sched_graph *graph,
467 enum isl_edge_type type,
468 struct isl_sched_node *src, struct isl_sched_node *dst)
470 isl_ctx *ctx = isl_space_get_ctx(src->space);
471 uint32_t hash;
472 struct isl_sched_edge temp = { .src = src, .dst = dst };
474 hash = isl_hash_init();
475 hash = isl_hash_builtin(hash, temp.src);
476 hash = isl_hash_builtin(hash, temp.dst);
477 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
478 &edge_has_src_and_dst, &temp, 0);
482 /* If graph->edge_table[type] contains an edge from the given source
483 * to the given destination, then return this edge.
484 * Otherwise, return NULL.
486 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
487 enum isl_edge_type type,
488 struct isl_sched_node *src, struct isl_sched_node *dst)
490 struct isl_hash_table_entry *entry;
492 entry = graph_find_edge_entry(graph, type, src, dst);
493 if (!entry)
494 return NULL;
496 return entry->data;
499 /* Check whether the dependence graph has an edge of the given type
500 * between the given two nodes.
502 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
503 enum isl_edge_type type,
504 struct isl_sched_node *src, struct isl_sched_node *dst)
506 struct isl_sched_edge *edge;
507 isl_bool empty;
509 edge = graph_find_edge(graph, type, src, dst);
510 if (!edge)
511 return 0;
513 empty = isl_map_plain_is_empty(edge->map);
514 if (empty < 0)
515 return isl_bool_error;
517 return !empty;
520 /* Look for any edge with the same src, dst and map fields as "model".
522 * Return the matching edge if one can be found.
523 * Return "model" if no matching edge is found.
524 * Return NULL on error.
526 static struct isl_sched_edge *graph_find_matching_edge(
527 struct isl_sched_graph *graph, struct isl_sched_edge *model)
529 enum isl_edge_type i;
530 struct isl_sched_edge *edge;
532 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
533 int is_equal;
535 edge = graph_find_edge(graph, i, model->src, model->dst);
536 if (!edge)
537 continue;
538 is_equal = isl_map_plain_is_equal(model->map, edge->map);
539 if (is_equal < 0)
540 return NULL;
541 if (is_equal)
542 return edge;
545 return model;
548 /* Remove the given edge from all the edge_tables that refer to it.
550 static void graph_remove_edge(struct isl_sched_graph *graph,
551 struct isl_sched_edge *edge)
553 isl_ctx *ctx = isl_map_get_ctx(edge->map);
554 enum isl_edge_type i;
556 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
557 struct isl_hash_table_entry *entry;
559 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
560 if (!entry)
561 continue;
562 if (entry->data != edge)
563 continue;
564 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
568 /* Check whether the dependence graph has any edge
569 * between the given two nodes.
571 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
572 struct isl_sched_node *src, struct isl_sched_node *dst)
574 enum isl_edge_type i;
575 isl_bool r;
577 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
578 r = graph_has_edge(graph, i, src, dst);
579 if (r < 0 || r)
580 return r;
583 return r;
586 /* Check whether the dependence graph has a validity edge
587 * between the given two nodes.
589 * Conditional validity edges are essentially validity edges that
590 * can be ignored if the corresponding condition edges are iteration private.
591 * Here, we are only checking for the presence of validity
592 * edges, so we need to consider the conditional validity edges too.
593 * In particular, this function is used during the detection
594 * of strongly connected components and we cannot ignore
595 * conditional validity edges during this detection.
597 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
598 struct isl_sched_node *src, struct isl_sched_node *dst)
600 isl_bool r;
602 r = graph_has_edge(graph, isl_edge_validity, src, dst);
603 if (r < 0 || r)
604 return r;
606 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
609 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
610 int n_node, int n_edge)
612 int i;
614 graph->n = n_node;
615 graph->n_edge = n_edge;
616 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
617 graph->sorted = isl_calloc_array(ctx, int, graph->n);
618 graph->region = isl_alloc_array(ctx,
619 struct isl_trivial_region, graph->n);
620 graph->edge = isl_calloc_array(ctx,
621 struct isl_sched_edge, graph->n_edge);
623 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
624 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
626 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
627 !graph->sorted)
628 return -1;
630 for(i = 0; i < graph->n; ++i)
631 graph->sorted[i] = i;
633 return 0;
636 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
638 int i;
640 isl_map_to_basic_set_free(graph->intra_hmap);
641 isl_map_to_basic_set_free(graph->inter_hmap);
643 if (graph->node)
644 for (i = 0; i < graph->n; ++i) {
645 isl_space_free(graph->node[i].space);
646 isl_set_free(graph->node[i].hull);
647 isl_multi_aff_free(graph->node[i].compress);
648 isl_multi_aff_free(graph->node[i].decompress);
649 isl_mat_free(graph->node[i].sched);
650 isl_map_free(graph->node[i].sched_map);
651 isl_mat_free(graph->node[i].indep);
652 isl_mat_free(graph->node[i].vmap);
653 if (graph->root)
654 free(graph->node[i].coincident);
655 isl_multi_val_free(graph->node[i].sizes);
656 isl_vec_free(graph->node[i].max);
658 free(graph->node);
659 free(graph->sorted);
660 if (graph->edge)
661 for (i = 0; i < graph->n_edge; ++i) {
662 isl_map_free(graph->edge[i].map);
663 isl_union_map_free(graph->edge[i].tagged_condition);
664 isl_union_map_free(graph->edge[i].tagged_validity);
666 free(graph->edge);
667 free(graph->region);
668 for (i = 0; i <= isl_edge_last; ++i)
669 isl_hash_table_free(ctx, graph->edge_table[i]);
670 isl_hash_table_free(ctx, graph->node_table);
671 isl_basic_set_free(graph->lp);
674 /* For each "set" on which this function is called, increment
675 * graph->n by one and update graph->maxvar.
677 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
679 struct isl_sched_graph *graph = user;
680 int nvar = isl_set_dim(set, isl_dim_set);
682 graph->n++;
683 if (nvar > graph->maxvar)
684 graph->maxvar = nvar;
686 isl_set_free(set);
688 return isl_stat_ok;
691 /* Compute the number of rows that should be allocated for the schedule.
692 * In particular, we need one row for each variable or one row
693 * for each basic map in the dependences.
694 * Note that it is practically impossible to exhaust both
695 * the number of dependences and the number of variables.
697 static isl_stat compute_max_row(struct isl_sched_graph *graph,
698 __isl_keep isl_schedule_constraints *sc)
700 int n_edge;
701 isl_stat r;
702 isl_union_set *domain;
704 graph->n = 0;
705 graph->maxvar = 0;
706 domain = isl_schedule_constraints_get_domain(sc);
707 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
708 isl_union_set_free(domain);
709 if (r < 0)
710 return isl_stat_error;
711 n_edge = isl_schedule_constraints_n_basic_map(sc);
712 if (n_edge < 0)
713 return isl_stat_error;
714 graph->max_row = n_edge + graph->maxvar;
716 return isl_stat_ok;
719 /* Does "bset" have any defining equalities for its set variables?
721 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
723 int i, n;
725 if (!bset)
726 return isl_bool_error;
728 n = isl_basic_set_dim(bset, isl_dim_set);
729 for (i = 0; i < n; ++i) {
730 isl_bool has;
732 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
733 NULL);
734 if (has < 0 || has)
735 return has;
738 return isl_bool_false;
741 /* Set the entries of node->max to the value of the schedule_max_coefficient
742 * option, if set.
744 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
746 int max;
748 max = isl_options_get_schedule_max_coefficient(ctx);
749 if (max == -1)
750 return isl_stat_ok;
752 node->max = isl_vec_alloc(ctx, node->nvar);
753 node->max = isl_vec_set_si(node->max, max);
754 if (!node->max)
755 return isl_stat_error;
757 return isl_stat_ok;
760 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
761 * option (if set) and half of the minimum of the sizes in the other
762 * dimensions. If the minimum of the sizes is one, half of the size
763 * is zero and this value is reset to one.
764 * If the global minimum is unbounded (i.e., if both
765 * the schedule_max_coefficient is not set and the sizes in the other
766 * dimensions are unbounded), then store a negative value.
767 * If the schedule coefficient is close to the size of the instance set
768 * in another dimension, then the schedule may represent a loop
769 * coalescing transformation (especially if the coefficient
770 * in that other dimension is one). Forcing the coefficient to be
771 * smaller than or equal to half the minimal size should avoid this
772 * situation.
774 static isl_stat compute_max_coefficient(isl_ctx *ctx,
775 struct isl_sched_node *node)
777 int max;
778 int i, j;
779 isl_vec *v;
781 max = isl_options_get_schedule_max_coefficient(ctx);
782 v = isl_vec_alloc(ctx, node->nvar);
783 if (!v)
784 return isl_stat_error;
786 for (i = 0; i < node->nvar; ++i) {
787 isl_int_set_si(v->el[i], max);
788 isl_int_mul_si(v->el[i], v->el[i], 2);
791 for (i = 0; i < node->nvar; ++i) {
792 isl_val *size;
794 size = isl_multi_val_get_val(node->sizes, i);
795 if (!size)
796 goto error;
797 if (!isl_val_is_int(size)) {
798 isl_val_free(size);
799 continue;
801 for (j = 0; j < node->nvar; ++j) {
802 if (j == i)
803 continue;
804 if (isl_int_is_neg(v->el[j]) ||
805 isl_int_gt(v->el[j], size->n))
806 isl_int_set(v->el[j], size->n);
808 isl_val_free(size);
811 for (i = 0; i < node->nvar; ++i) {
812 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
813 if (isl_int_is_zero(v->el[i]))
814 isl_int_set_si(v->el[i], 1);
817 node->max = v;
818 return isl_stat_ok;
819 error:
820 isl_vec_free(v);
821 return isl_stat_error;
824 /* Compute and return the size of "set" in dimension "dim".
825 * The size is taken to be the difference in values for that variable
826 * for fixed values of the other variables.
827 * In particular, the variable is first isolated from the other variables
828 * in the range of a map
830 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
832 * and then duplicated
834 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
836 * The shared variables are then projected out and the maximal value
837 * of i_dim' - i_dim is computed.
839 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
841 isl_map *map;
842 isl_local_space *ls;
843 isl_aff *obj;
844 isl_val *v;
846 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
847 map = isl_map_project_out(map, isl_dim_in, dim, 1);
848 map = isl_map_range_product(map, isl_map_copy(map));
849 map = isl_set_unwrap(isl_map_range(map));
850 set = isl_map_deltas(map);
851 ls = isl_local_space_from_space(isl_set_get_space(set));
852 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
853 v = isl_set_max_val(set, obj);
854 isl_aff_free(obj);
855 isl_set_free(set);
857 return v;
860 /* Compute the size of the instance set "set" of "node", after compression,
861 * as well as bounds on the corresponding coefficients, if needed.
863 * The sizes are needed when the schedule_treat_coalescing option is set.
864 * The bounds are needed when the schedule_treat_coalescing option or
865 * the schedule_max_coefficient option is set.
867 * If the schedule_treat_coalescing option is not set, then at most
868 * the bounds need to be set and this is done in set_max_coefficient.
869 * Otherwise, compress the domain if needed, compute the size
870 * in each direction and store the results in node->size.
871 * Finally, set the bounds on the coefficients based on the sizes
872 * and the schedule_max_coefficient option in compute_max_coefficient.
874 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
875 __isl_take isl_set *set)
877 int j, n;
878 isl_multi_val *mv;
880 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
881 isl_set_free(set);
882 return set_max_coefficient(ctx, node);
885 if (node->compressed)
886 set = isl_set_preimage_multi_aff(set,
887 isl_multi_aff_copy(node->decompress));
888 mv = isl_multi_val_zero(isl_set_get_space(set));
889 n = isl_set_dim(set, isl_dim_set);
890 for (j = 0; j < n; ++j) {
891 isl_val *v;
893 v = compute_size(isl_set_copy(set), j);
894 mv = isl_multi_val_set_val(mv, j, v);
896 node->sizes = mv;
897 isl_set_free(set);
898 if (!node->sizes)
899 return isl_stat_error;
900 return compute_max_coefficient(ctx, node);
903 /* Add a new node to the graph representing the given instance set.
904 * "nvar" is the (possibly compressed) number of variables and
905 * may be smaller than then number of set variables in "set"
906 * if "compressed" is set.
907 * If "compressed" is set, then "hull" represents the constraints
908 * that were used to derive the compression, while "compress" and
909 * "decompress" map the original space to the compressed space and
910 * vice versa.
911 * If "compressed" is not set, then "hull", "compress" and "decompress"
912 * should be NULL.
914 * Compute the size of the instance set and bounds on the coefficients,
915 * if needed.
917 static isl_stat add_node(struct isl_sched_graph *graph,
918 __isl_take isl_set *set, int nvar, int compressed,
919 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
920 __isl_take isl_multi_aff *decompress)
922 int nparam;
923 isl_ctx *ctx;
924 isl_mat *sched;
925 isl_space *space;
926 int *coincident;
927 struct isl_sched_node *node;
929 if (!set)
930 return isl_stat_error;
932 ctx = isl_set_get_ctx(set);
933 nparam = isl_set_dim(set, isl_dim_param);
934 if (!ctx->opt->schedule_parametric)
935 nparam = 0;
936 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
937 node = &graph->node[graph->n];
938 graph->n++;
939 space = isl_set_get_space(set);
940 node->space = space;
941 node->nvar = nvar;
942 node->nparam = nparam;
943 node->sched = sched;
944 node->sched_map = NULL;
945 coincident = isl_calloc_array(ctx, int, graph->max_row);
946 node->coincident = coincident;
947 node->compressed = compressed;
948 node->hull = hull;
949 node->compress = compress;
950 node->decompress = decompress;
951 if (compute_sizes_and_max(ctx, node, set) < 0)
952 return isl_stat_error;
954 if (!space || !sched || (graph->max_row && !coincident))
955 return isl_stat_error;
956 if (compressed && (!hull || !compress || !decompress))
957 return isl_stat_error;
959 return isl_stat_ok;
962 /* Construct an identifier for node "node", which will represent "set".
963 * The name of the identifier is either "compressed" or
964 * "compressed_<name>", with <name> the name of the space of "set".
965 * The user pointer of the identifier points to "node".
967 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
968 struct isl_sched_node *node)
970 isl_bool has_name;
971 isl_ctx *ctx;
972 isl_id *id;
973 isl_printer *p;
974 const char *name;
975 char *id_name;
977 has_name = isl_set_has_tuple_name(set);
978 if (has_name < 0)
979 return NULL;
981 ctx = isl_set_get_ctx(set);
982 if (!has_name)
983 return isl_id_alloc(ctx, "compressed", node);
985 p = isl_printer_to_str(ctx);
986 name = isl_set_get_tuple_name(set);
987 p = isl_printer_print_str(p, "compressed_");
988 p = isl_printer_print_str(p, name);
989 id_name = isl_printer_get_str(p);
990 isl_printer_free(p);
992 id = isl_id_alloc(ctx, id_name, node);
993 free(id_name);
995 return id;
998 /* Add a new node to the graph representing the given set.
1000 * If any of the set variables is defined by an equality, then
1001 * we perform variable compression such that we can perform
1002 * the scheduling on the compressed domain.
1003 * In this case, an identifier is used that references the new node
1004 * such that each compressed space is unique and
1005 * such that the node can be recovered from the compressed space.
1007 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1009 int nvar;
1010 isl_bool has_equality;
1011 isl_id *id;
1012 isl_basic_set *hull;
1013 isl_set *hull_set;
1014 isl_morph *morph;
1015 isl_multi_aff *compress, *decompress;
1016 struct isl_sched_graph *graph = user;
1018 hull = isl_set_affine_hull(isl_set_copy(set));
1019 hull = isl_basic_set_remove_divs(hull);
1020 nvar = isl_set_dim(set, isl_dim_set);
1021 has_equality = has_any_defining_equality(hull);
1023 if (has_equality < 0)
1024 goto error;
1025 if (!has_equality) {
1026 isl_basic_set_free(hull);
1027 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1030 id = construct_compressed_id(set, &graph->node[graph->n]);
1031 morph = isl_basic_set_variable_compression_with_id(hull,
1032 isl_dim_set, id);
1033 isl_id_free(id);
1034 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1035 compress = isl_morph_get_var_multi_aff(morph);
1036 morph = isl_morph_inverse(morph);
1037 decompress = isl_morph_get_var_multi_aff(morph);
1038 isl_morph_free(morph);
1040 hull_set = isl_set_from_basic_set(hull);
1041 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1042 error:
1043 isl_basic_set_free(hull);
1044 isl_set_free(set);
1045 return isl_stat_error;
1048 struct isl_extract_edge_data {
1049 enum isl_edge_type type;
1050 struct isl_sched_graph *graph;
1053 /* Merge edge2 into edge1, freeing the contents of edge2.
1054 * Return 0 on success and -1 on failure.
1056 * edge1 and edge2 are assumed to have the same value for the map field.
1058 static int merge_edge(struct isl_sched_edge *edge1,
1059 struct isl_sched_edge *edge2)
1061 edge1->types |= edge2->types;
1062 isl_map_free(edge2->map);
1064 if (is_condition(edge2)) {
1065 if (!edge1->tagged_condition)
1066 edge1->tagged_condition = edge2->tagged_condition;
1067 else
1068 edge1->tagged_condition =
1069 isl_union_map_union(edge1->tagged_condition,
1070 edge2->tagged_condition);
1073 if (is_conditional_validity(edge2)) {
1074 if (!edge1->tagged_validity)
1075 edge1->tagged_validity = edge2->tagged_validity;
1076 else
1077 edge1->tagged_validity =
1078 isl_union_map_union(edge1->tagged_validity,
1079 edge2->tagged_validity);
1082 if (is_condition(edge2) && !edge1->tagged_condition)
1083 return -1;
1084 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1085 return -1;
1087 return 0;
1090 /* Insert dummy tags in domain and range of "map".
1092 * In particular, if "map" is of the form
1094 * A -> B
1096 * then return
1098 * [A -> dummy_tag] -> [B -> dummy_tag]
1100 * where the dummy_tags are identical and equal to any dummy tags
1101 * introduced by any other call to this function.
1103 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1105 static char dummy;
1106 isl_ctx *ctx;
1107 isl_id *id;
1108 isl_space *space;
1109 isl_set *domain, *range;
1111 ctx = isl_map_get_ctx(map);
1113 id = isl_id_alloc(ctx, NULL, &dummy);
1114 space = isl_space_params(isl_map_get_space(map));
1115 space = isl_space_set_from_params(space);
1116 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1117 space = isl_space_map_from_set(space);
1119 domain = isl_map_wrap(map);
1120 range = isl_map_wrap(isl_map_universe(space));
1121 map = isl_map_from_domain_and_range(domain, range);
1122 map = isl_map_zip(map);
1124 return map;
1127 /* Given that at least one of "src" or "dst" is compressed, return
1128 * a map between the spaces of these nodes restricted to the affine
1129 * hull that was used in the compression.
1131 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1132 struct isl_sched_node *dst)
1134 isl_set *dom, *ran;
1136 if (src->compressed)
1137 dom = isl_set_copy(src->hull);
1138 else
1139 dom = isl_set_universe(isl_space_copy(src->space));
1140 if (dst->compressed)
1141 ran = isl_set_copy(dst->hull);
1142 else
1143 ran = isl_set_universe(isl_space_copy(dst->space));
1145 return isl_map_from_domain_and_range(dom, ran);
1148 /* Intersect the domains of the nested relations in domain and range
1149 * of "tagged" with "map".
1151 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1152 __isl_keep isl_map *map)
1154 isl_set *set;
1156 tagged = isl_map_zip(tagged);
1157 set = isl_map_wrap(isl_map_copy(map));
1158 tagged = isl_map_intersect_domain(tagged, set);
1159 tagged = isl_map_zip(tagged);
1160 return tagged;
1163 /* Return a pointer to the node that lives in the domain space of "map"
1164 * or NULL if there is no such node.
1166 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1167 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1169 struct isl_sched_node *node;
1170 isl_space *space;
1172 space = isl_space_domain(isl_map_get_space(map));
1173 node = graph_find_node(ctx, graph, space);
1174 isl_space_free(space);
1176 return node;
1179 /* Return a pointer to the node that lives in the range space of "map"
1180 * or NULL if there is no such node.
1182 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1183 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1185 struct isl_sched_node *node;
1186 isl_space *space;
1188 space = isl_space_range(isl_map_get_space(map));
1189 node = graph_find_node(ctx, graph, space);
1190 isl_space_free(space);
1192 return node;
1195 /* Add a new edge to the graph based on the given map
1196 * and add it to data->graph->edge_table[data->type].
1197 * If a dependence relation of a given type happens to be identical
1198 * to one of the dependence relations of a type that was added before,
1199 * then we don't create a new edge, but instead mark the original edge
1200 * as also representing a dependence of the current type.
1202 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1203 * may be specified as "tagged" dependence relations. That is, "map"
1204 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1205 * the dependence on iterations and a and b are tags.
1206 * edge->map is set to the relation containing the elements i -> j,
1207 * while edge->tagged_condition and edge->tagged_validity contain
1208 * the union of all the "map" relations
1209 * for which extract_edge is called that result in the same edge->map.
1211 * If the source or the destination node is compressed, then
1212 * intersect both "map" and "tagged" with the constraints that
1213 * were used to construct the compression.
1214 * This ensures that there are no schedule constraints defined
1215 * outside of these domains, while the scheduler no longer has
1216 * any control over those outside parts.
1218 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1220 isl_ctx *ctx = isl_map_get_ctx(map);
1221 struct isl_extract_edge_data *data = user;
1222 struct isl_sched_graph *graph = data->graph;
1223 struct isl_sched_node *src, *dst;
1224 struct isl_sched_edge *edge;
1225 isl_map *tagged = NULL;
1227 if (data->type == isl_edge_condition ||
1228 data->type == isl_edge_conditional_validity) {
1229 if (isl_map_can_zip(map)) {
1230 tagged = isl_map_copy(map);
1231 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1232 } else {
1233 tagged = insert_dummy_tags(isl_map_copy(map));
1237 src = find_domain_node(ctx, graph, map);
1238 dst = find_range_node(ctx, graph, map);
1240 if (!src || !dst) {
1241 isl_map_free(map);
1242 isl_map_free(tagged);
1243 return isl_stat_ok;
1246 if (src->compressed || dst->compressed) {
1247 isl_map *hull;
1248 hull = extract_hull(src, dst);
1249 if (tagged)
1250 tagged = map_intersect_domains(tagged, hull);
1251 map = isl_map_intersect(map, hull);
1254 graph->edge[graph->n_edge].src = src;
1255 graph->edge[graph->n_edge].dst = dst;
1256 graph->edge[graph->n_edge].map = map;
1257 graph->edge[graph->n_edge].types = 0;
1258 graph->edge[graph->n_edge].tagged_condition = NULL;
1259 graph->edge[graph->n_edge].tagged_validity = NULL;
1260 set_type(&graph->edge[graph->n_edge], data->type);
1261 if (data->type == isl_edge_condition)
1262 graph->edge[graph->n_edge].tagged_condition =
1263 isl_union_map_from_map(tagged);
1264 if (data->type == isl_edge_conditional_validity)
1265 graph->edge[graph->n_edge].tagged_validity =
1266 isl_union_map_from_map(tagged);
1268 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1269 if (!edge) {
1270 graph->n_edge++;
1271 return isl_stat_error;
1273 if (edge == &graph->edge[graph->n_edge])
1274 return graph_edge_table_add(ctx, graph, data->type,
1275 &graph->edge[graph->n_edge++]);
1277 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1278 return -1;
1280 return graph_edge_table_add(ctx, graph, data->type, edge);
1283 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1285 * The context is included in the domain before the nodes of
1286 * the graphs are extracted in order to be able to exploit
1287 * any possible additional equalities.
1288 * Note that this intersection is only performed locally here.
1290 static isl_stat graph_init(struct isl_sched_graph *graph,
1291 __isl_keep isl_schedule_constraints *sc)
1293 isl_ctx *ctx;
1294 isl_union_set *domain;
1295 isl_union_map *c;
1296 struct isl_extract_edge_data data;
1297 enum isl_edge_type i;
1298 isl_stat r;
1300 if (!sc)
1301 return isl_stat_error;
1303 ctx = isl_schedule_constraints_get_ctx(sc);
1305 domain = isl_schedule_constraints_get_domain(sc);
1306 graph->n = isl_union_set_n_set(domain);
1307 isl_union_set_free(domain);
1309 if (graph_alloc(ctx, graph, graph->n,
1310 isl_schedule_constraints_n_map(sc)) < 0)
1311 return isl_stat_error;
1313 if (compute_max_row(graph, sc) < 0)
1314 return isl_stat_error;
1315 graph->root = 1;
1316 graph->n = 0;
1317 domain = isl_schedule_constraints_get_domain(sc);
1318 domain = isl_union_set_intersect_params(domain,
1319 isl_schedule_constraints_get_context(sc));
1320 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1321 isl_union_set_free(domain);
1322 if (r < 0)
1323 return isl_stat_error;
1324 if (graph_init_table(ctx, graph) < 0)
1325 return isl_stat_error;
1326 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1327 c = isl_schedule_constraints_get(sc, i);
1328 graph->max_edge[i] = isl_union_map_n_map(c);
1329 isl_union_map_free(c);
1330 if (!c)
1331 return isl_stat_error;
1333 if (graph_init_edge_tables(ctx, graph) < 0)
1334 return isl_stat_error;
1335 graph->n_edge = 0;
1336 data.graph = graph;
1337 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1338 isl_stat r;
1340 data.type = i;
1341 c = isl_schedule_constraints_get(sc, i);
1342 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1343 isl_union_map_free(c);
1344 if (r < 0)
1345 return isl_stat_error;
1348 return isl_stat_ok;
1351 /* Check whether there is any dependence from node[j] to node[i]
1352 * or from node[i] to node[j].
1354 static isl_bool node_follows_weak(int i, int j, void *user)
1356 isl_bool f;
1357 struct isl_sched_graph *graph = user;
1359 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1360 if (f < 0 || f)
1361 return f;
1362 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1365 /* Check whether there is a (conditional) validity dependence from node[j]
1366 * to node[i], forcing node[i] to follow node[j].
1368 static isl_bool node_follows_strong(int i, int j, void *user)
1370 struct isl_sched_graph *graph = user;
1372 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1375 /* Use Tarjan's algorithm for computing the strongly connected components
1376 * in the dependence graph only considering those edges defined by "follows".
1378 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1379 isl_bool (*follows)(int i, int j, void *user))
1381 int i, n;
1382 struct isl_tarjan_graph *g = NULL;
1384 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1385 if (!g)
1386 return -1;
1388 graph->scc = 0;
1389 i = 0;
1390 n = graph->n;
1391 while (n) {
1392 while (g->order[i] != -1) {
1393 graph->node[g->order[i]].scc = graph->scc;
1394 --n;
1395 ++i;
1397 ++i;
1398 graph->scc++;
1401 isl_tarjan_graph_free(g);
1403 return 0;
1406 /* Apply Tarjan's algorithm to detect the strongly connected components
1407 * in the dependence graph.
1408 * Only consider the (conditional) validity dependences and clear "weak".
1410 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1412 graph->weak = 0;
1413 return detect_ccs(ctx, graph, &node_follows_strong);
1416 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1417 * in the dependence graph.
1418 * Consider all dependences and set "weak".
1420 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1422 graph->weak = 1;
1423 return detect_ccs(ctx, graph, &node_follows_weak);
1426 static int cmp_scc(const void *a, const void *b, void *data)
1428 struct isl_sched_graph *graph = data;
1429 const int *i1 = a;
1430 const int *i2 = b;
1432 return graph->node[*i1].scc - graph->node[*i2].scc;
1435 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1437 static int sort_sccs(struct isl_sched_graph *graph)
1439 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1442 /* Given a dependence relation R from "node" to itself,
1443 * construct the set of coefficients of valid constraints for elements
1444 * in that dependence relation.
1445 * In particular, the result contains tuples of coefficients
1446 * c_0, c_n, c_x such that
1448 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1450 * or, equivalently,
1452 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1454 * We choose here to compute the dual of delta R.
1455 * Alternatively, we could have computed the dual of R, resulting
1456 * in a set of tuples c_0, c_n, c_x, c_y, and then
1457 * plugged in (c_0, c_n, c_x, -c_x).
1459 * If "node" has been compressed, then the dependence relation
1460 * is also compressed before the set of coefficients is computed.
1462 static __isl_give isl_basic_set *intra_coefficients(
1463 struct isl_sched_graph *graph, struct isl_sched_node *node,
1464 __isl_take isl_map *map)
1466 isl_set *delta;
1467 isl_map *key;
1468 isl_basic_set *coef;
1469 isl_maybe_isl_basic_set m;
1471 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1472 if (m.valid < 0 || m.valid) {
1473 isl_map_free(map);
1474 return m.value;
1477 key = isl_map_copy(map);
1478 if (node->compressed) {
1479 map = isl_map_preimage_domain_multi_aff(map,
1480 isl_multi_aff_copy(node->decompress));
1481 map = isl_map_preimage_range_multi_aff(map,
1482 isl_multi_aff_copy(node->decompress));
1484 delta = isl_set_remove_divs(isl_map_deltas(map));
1485 coef = isl_set_coefficients(delta);
1486 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1487 isl_basic_set_copy(coef));
1489 return coef;
1492 /* Given a dependence relation R, construct the set of coefficients
1493 * of valid constraints for elements in that dependence relation.
1494 * In particular, the result contains tuples of coefficients
1495 * c_0, c_n, c_x, c_y such that
1497 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1499 * If the source or destination nodes of "edge" have been compressed,
1500 * then the dependence relation is also compressed before
1501 * the set of coefficients is computed.
1503 static __isl_give isl_basic_set *inter_coefficients(
1504 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1505 __isl_take isl_map *map)
1507 isl_set *set;
1508 isl_map *key;
1509 isl_basic_set *coef;
1510 isl_maybe_isl_basic_set m;
1512 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1513 if (m.valid < 0 || m.valid) {
1514 isl_map_free(map);
1515 return m.value;
1518 key = isl_map_copy(map);
1519 if (edge->src->compressed)
1520 map = isl_map_preimage_domain_multi_aff(map,
1521 isl_multi_aff_copy(edge->src->decompress));
1522 if (edge->dst->compressed)
1523 map = isl_map_preimage_range_multi_aff(map,
1524 isl_multi_aff_copy(edge->dst->decompress));
1525 set = isl_map_wrap(isl_map_remove_divs(map));
1526 coef = isl_set_coefficients(set);
1527 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1528 isl_basic_set_copy(coef));
1530 return coef;
1533 /* Return the position of the coefficients of the variables in
1534 * the coefficients constraints "coef".
1536 * The space of "coef" is of the form
1538 * { coefficients[[cst, params] -> S] }
1540 * Return the position of S.
1542 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1544 int offset;
1545 isl_space *space;
1547 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1548 offset = isl_space_dim(space, isl_dim_in);
1549 isl_space_free(space);
1551 return offset;
1554 /* Return the offset of the coefficient of the constant term of "node"
1555 * within the (I)LP.
1557 * Within each node, the coefficients have the following order:
1558 * - positive and negative parts of c_i_x
1559 * - c_i_n (if parametric)
1560 * - c_i_0
1562 static int node_cst_coef_offset(struct isl_sched_node *node)
1564 return node->start + 2 * node->nvar + node->nparam;
1567 /* Return the offset of the coefficients of the parameters of "node"
1568 * within the (I)LP.
1570 * Within each node, the coefficients have the following order:
1571 * - positive and negative parts of c_i_x
1572 * - c_i_n (if parametric)
1573 * - c_i_0
1575 static int node_par_coef_offset(struct isl_sched_node *node)
1577 return node->start + 2 * node->nvar;
1580 /* Return the offset of the coefficients of the variables of "node"
1581 * within the (I)LP.
1583 * Within each node, the coefficients have the following order:
1584 * - positive and negative parts of c_i_x
1585 * - c_i_n (if parametric)
1586 * - c_i_0
1588 static int node_var_coef_offset(struct isl_sched_node *node)
1590 return node->start;
1593 /* Return the position of the pair of variables encoding
1594 * coefficient "i" of "node".
1596 * The order of these variable pairs is the opposite of
1597 * that of the coefficients, with 2 variables per coefficient.
1599 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1601 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1604 /* Construct an isl_dim_map for mapping constraints on coefficients
1605 * for "node" to the corresponding positions in graph->lp.
1606 * "offset" is the offset of the coefficients for the variables
1607 * in the input constraints.
1608 * "s" is the sign of the mapping.
1610 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1611 * The mapping produced by this function essentially plugs in
1612 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1613 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1614 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1615 * Furthermore, the order of these pairs is the opposite of that
1616 * of the corresponding coefficients.
1618 * The caller can extend the mapping to also map the other coefficients
1619 * (and therefore not plug in 0).
1621 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1622 struct isl_sched_graph *graph, struct isl_sched_node *node,
1623 int offset, int s)
1625 int pos;
1626 unsigned total;
1627 isl_dim_map *dim_map;
1629 if (!node)
1630 return NULL;
1632 total = isl_basic_set_total_dim(graph->lp);
1633 pos = node_var_coef_pos(node, 0);
1634 dim_map = isl_dim_map_alloc(ctx, total);
1635 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1636 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1638 return dim_map;
1641 /* Construct an isl_dim_map for mapping constraints on coefficients
1642 * for "src" (node i) and "dst" (node j) to the corresponding positions
1643 * in graph->lp.
1644 * "offset" is the offset of the coefficients for the variables of "src"
1645 * in the input constraints.
1646 * "s" is the sign of the mapping.
1648 * The input constraints are given in terms of the coefficients
1649 * (c_0, c_n, c_x, c_y).
1650 * The mapping produced by this function essentially plugs in
1651 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1652 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1653 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1654 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1655 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1656 * Furthermore, the order of these pairs is the opposite of that
1657 * of the corresponding coefficients.
1659 * The caller can further extend the mapping.
1661 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1662 struct isl_sched_graph *graph, struct isl_sched_node *src,
1663 struct isl_sched_node *dst, int offset, int s)
1665 int pos;
1666 unsigned total;
1667 isl_dim_map *dim_map;
1669 if (!src || !dst)
1670 return NULL;
1672 total = isl_basic_set_total_dim(graph->lp);
1673 dim_map = isl_dim_map_alloc(ctx, total);
1675 pos = node_cst_coef_offset(dst);
1676 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1677 pos = node_par_coef_offset(dst);
1678 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1679 pos = node_var_coef_pos(dst, 0);
1680 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1681 dst->nvar, -s);
1682 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1683 dst->nvar, s);
1685 pos = node_cst_coef_offset(src);
1686 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1687 pos = node_par_coef_offset(src);
1688 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1689 pos = node_var_coef_pos(src, 0);
1690 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1691 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1693 return dim_map;
1696 /* Add the constraints from "src" to "dst" using "dim_map",
1697 * after making sure there is enough room in "dst" for the extra constraints.
1699 static __isl_give isl_basic_set *add_constraints_dim_map(
1700 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1701 __isl_take isl_dim_map *dim_map)
1703 int n_eq, n_ineq;
1705 n_eq = isl_basic_set_n_equality(src);
1706 n_ineq = isl_basic_set_n_inequality(src);
1707 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1708 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1709 return dst;
1712 /* Add constraints to graph->lp that force validity for the given
1713 * dependence from a node i to itself.
1714 * That is, add constraints that enforce
1716 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1717 * = c_i_x (y - x) >= 0
1719 * for each (x,y) in R.
1720 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1721 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1722 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1723 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1725 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1726 struct isl_sched_edge *edge)
1728 int offset;
1729 isl_map *map = isl_map_copy(edge->map);
1730 isl_ctx *ctx = isl_map_get_ctx(map);
1731 isl_dim_map *dim_map;
1732 isl_basic_set *coef;
1733 struct isl_sched_node *node = edge->src;
1735 coef = intra_coefficients(graph, node, map);
1737 offset = coef_var_offset(coef);
1739 if (!coef)
1740 return isl_stat_error;
1742 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1743 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1745 return isl_stat_ok;
1748 /* Add constraints to graph->lp that force validity for the given
1749 * dependence from node i to node j.
1750 * That is, add constraints that enforce
1752 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1754 * for each (x,y) in R.
1755 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1756 * of valid constraints for R and then plug in
1757 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1758 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1759 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1761 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1762 struct isl_sched_edge *edge)
1764 int offset;
1765 isl_map *map;
1766 isl_ctx *ctx;
1767 isl_dim_map *dim_map;
1768 isl_basic_set *coef;
1769 struct isl_sched_node *src = edge->src;
1770 struct isl_sched_node *dst = edge->dst;
1772 if (!graph->lp)
1773 return isl_stat_error;
1775 map = isl_map_copy(edge->map);
1776 ctx = isl_map_get_ctx(map);
1777 coef = inter_coefficients(graph, edge, map);
1779 offset = coef_var_offset(coef);
1781 if (!coef)
1782 return isl_stat_error;
1784 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1786 edge->start = graph->lp->n_ineq;
1787 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1788 if (!graph->lp)
1789 return isl_stat_error;
1790 edge->end = graph->lp->n_ineq;
1792 return isl_stat_ok;
1795 /* Add constraints to graph->lp that bound the dependence distance for the given
1796 * dependence from a node i to itself.
1797 * If s = 1, we add the constraint
1799 * c_i_x (y - x) <= m_0 + m_n n
1801 * or
1803 * -c_i_x (y - x) + m_0 + m_n n >= 0
1805 * for each (x,y) in R.
1806 * If s = -1, we add the constraint
1808 * -c_i_x (y - x) <= m_0 + m_n n
1810 * or
1812 * c_i_x (y - x) + m_0 + m_n n >= 0
1814 * for each (x,y) in R.
1815 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1816 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1817 * with each coefficient (except m_0) represented as a pair of non-negative
1818 * coefficients.
1821 * If "local" is set, then we add constraints
1823 * c_i_x (y - x) <= 0
1825 * or
1827 * -c_i_x (y - x) <= 0
1829 * instead, forcing the dependence distance to be (less than or) equal to 0.
1830 * That is, we plug in (0, 0, -s * c_i_x),
1831 * Note that dependences marked local are treated as validity constraints
1832 * by add_all_validity_constraints and therefore also have
1833 * their distances bounded by 0 from below.
1835 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1836 struct isl_sched_edge *edge, int s, int local)
1838 int offset;
1839 unsigned nparam;
1840 isl_map *map = isl_map_copy(edge->map);
1841 isl_ctx *ctx = isl_map_get_ctx(map);
1842 isl_dim_map *dim_map;
1843 isl_basic_set *coef;
1844 struct isl_sched_node *node = edge->src;
1846 coef = intra_coefficients(graph, node, map);
1848 offset = coef_var_offset(coef);
1850 if (!coef)
1851 return isl_stat_error;
1853 nparam = isl_space_dim(node->space, isl_dim_param);
1854 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1856 if (!local) {
1857 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1858 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1859 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1861 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1863 return isl_stat_ok;
1866 /* Add constraints to graph->lp that bound the dependence distance for the given
1867 * dependence from node i to node j.
1868 * If s = 1, we add the constraint
1870 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1871 * <= m_0 + m_n n
1873 * or
1875 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1876 * m_0 + m_n n >= 0
1878 * for each (x,y) in R.
1879 * If s = -1, we add the constraint
1881 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1882 * <= m_0 + m_n n
1884 * or
1886 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1887 * m_0 + m_n n >= 0
1889 * for each (x,y) in R.
1890 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1891 * of valid constraints for R and then plug in
1892 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1893 * s*c_i_x, -s*c_j_x)
1894 * with each coefficient (except m_0, c_*_0 and c_*_n)
1895 * represented as a pair of non-negative coefficients.
1898 * If "local" is set (and s = 1), then we add constraints
1900 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1902 * or
1904 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
1906 * instead, forcing the dependence distance to be (less than or) equal to 0.
1907 * That is, we plug in
1908 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
1909 * Note that dependences marked local are treated as validity constraints
1910 * by add_all_validity_constraints and therefore also have
1911 * their distances bounded by 0 from below.
1913 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1914 struct isl_sched_edge *edge, int s, int local)
1916 int offset;
1917 unsigned nparam;
1918 isl_map *map = isl_map_copy(edge->map);
1919 isl_ctx *ctx = isl_map_get_ctx(map);
1920 isl_dim_map *dim_map;
1921 isl_basic_set *coef;
1922 struct isl_sched_node *src = edge->src;
1923 struct isl_sched_node *dst = edge->dst;
1925 coef = inter_coefficients(graph, edge, map);
1927 offset = coef_var_offset(coef);
1929 if (!coef)
1930 return isl_stat_error;
1932 nparam = isl_space_dim(src->space, isl_dim_param);
1933 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1935 if (!local) {
1936 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1937 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1938 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1941 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1943 return isl_stat_ok;
1946 /* Add all validity constraints to graph->lp.
1948 * An edge that is forced to be local needs to have its dependence
1949 * distances equal to zero. We take care of bounding them by 0 from below
1950 * here. add_all_proximity_constraints takes care of bounding them by 0
1951 * from above.
1953 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1954 * Otherwise, we ignore them.
1956 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1957 int use_coincidence)
1959 int i;
1961 for (i = 0; i < graph->n_edge; ++i) {
1962 struct isl_sched_edge *edge = &graph->edge[i];
1963 int local;
1965 local = is_local(edge) ||
1966 (is_coincidence(edge) && use_coincidence);
1967 if (!is_validity(edge) && !local)
1968 continue;
1969 if (edge->src != edge->dst)
1970 continue;
1971 if (add_intra_validity_constraints(graph, edge) < 0)
1972 return -1;
1975 for (i = 0; i < graph->n_edge; ++i) {
1976 struct isl_sched_edge *edge = &graph->edge[i];
1977 int local;
1979 local = is_local(edge) ||
1980 (is_coincidence(edge) && use_coincidence);
1981 if (!is_validity(edge) && !local)
1982 continue;
1983 if (edge->src == edge->dst)
1984 continue;
1985 if (add_inter_validity_constraints(graph, edge) < 0)
1986 return -1;
1989 return 0;
1992 /* Add constraints to graph->lp that bound the dependence distance
1993 * for all dependence relations.
1994 * If a given proximity dependence is identical to a validity
1995 * dependence, then the dependence distance is already bounded
1996 * from below (by zero), so we only need to bound the distance
1997 * from above. (This includes the case of "local" dependences
1998 * which are treated as validity dependence by add_all_validity_constraints.)
1999 * Otherwise, we need to bound the distance both from above and from below.
2001 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2002 * Otherwise, we ignore them.
2004 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2005 int use_coincidence)
2007 int i;
2009 for (i = 0; i < graph->n_edge; ++i) {
2010 struct isl_sched_edge *edge = &graph->edge[i];
2011 int local;
2013 local = is_local(edge) ||
2014 (is_coincidence(edge) && use_coincidence);
2015 if (!is_proximity(edge) && !local)
2016 continue;
2017 if (edge->src == edge->dst &&
2018 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
2019 return -1;
2020 if (edge->src != edge->dst &&
2021 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
2022 return -1;
2023 if (is_validity(edge) || local)
2024 continue;
2025 if (edge->src == edge->dst &&
2026 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2027 return -1;
2028 if (edge->src != edge->dst &&
2029 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2030 return -1;
2033 return 0;
2036 /* Normalize the rows of "indep" such that all rows are lexicographically
2037 * positive and such that each row contains as many final zeros as possible,
2038 * given the choice for the previous rows.
2039 * Do this by performing elementary row operations.
2041 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2043 indep = isl_mat_reverse_gauss(indep);
2044 indep = isl_mat_lexnonneg_rows(indep);
2045 return indep;
2048 /* Compute a basis for the rows in the linear part of the schedule
2049 * and extend this basis to a full basis. The remaining rows
2050 * can then be used to force linear independence from the rows
2051 * in the schedule.
2053 * In particular, given the schedule rows S, we compute
2055 * S = H Q
2056 * S U = H
2058 * with H the Hermite normal form of S. That is, all but the
2059 * first rank columns of H are zero and so each row in S is
2060 * a linear combination of the first rank rows of Q.
2061 * The matrix Q can be used as a variable transformation
2062 * that isolates the directions of S in the first rank rows.
2063 * Transposing S U = H yields
2065 * U^T S^T = H^T
2067 * with all but the first rank rows of H^T zero.
2068 * The last rows of U^T are therefore linear combinations
2069 * of schedule coefficients that are all zero on schedule
2070 * coefficients that are linearly dependent on the rows of S.
2071 * At least one of these combinations is non-zero on
2072 * linearly independent schedule coefficients.
2073 * The rows are normalized to involve as few of the last
2074 * coefficients as possible and to have a positive initial value.
2076 static int node_update_vmap(struct isl_sched_node *node)
2078 isl_mat *H, *U, *Q;
2079 int n_row = isl_mat_rows(node->sched);
2081 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2082 1 + node->nparam, node->nvar);
2084 H = isl_mat_left_hermite(H, 0, &U, &Q);
2085 isl_mat_free(node->indep);
2086 isl_mat_free(node->vmap);
2087 node->vmap = Q;
2088 node->indep = isl_mat_transpose(U);
2089 node->rank = isl_mat_initial_non_zero_cols(H);
2090 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2091 node->indep = normalize_independent(node->indep);
2092 isl_mat_free(H);
2094 if (!node->indep || !node->vmap || node->rank < 0)
2095 return -1;
2096 return 0;
2099 /* Is "edge" marked as a validity or a conditional validity edge?
2101 static int is_any_validity(struct isl_sched_edge *edge)
2103 return is_validity(edge) || is_conditional_validity(edge);
2106 /* How many times should we count the constraints in "edge"?
2108 * We count as follows
2109 * validity -> 1 (>= 0)
2110 * validity+proximity -> 2 (>= 0 and upper bound)
2111 * proximity -> 2 (lower and upper bound)
2112 * local(+any) -> 2 (>= 0 and <= 0)
2114 * If an edge is only marked conditional_validity then it counts
2115 * as zero since it is only checked afterwards.
2117 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2118 * Otherwise, we ignore them.
2120 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2122 if (is_proximity(edge) || is_local(edge))
2123 return 2;
2124 if (use_coincidence && is_coincidence(edge))
2125 return 2;
2126 if (is_validity(edge))
2127 return 1;
2128 return 0;
2131 /* Count the number of equality and inequality constraints
2132 * that will be added for the given map.
2134 * "use_coincidence" is set if we should take into account coincidence edges.
2136 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2137 struct isl_sched_edge *edge, __isl_take isl_map *map,
2138 int *n_eq, int *n_ineq, int use_coincidence)
2140 isl_basic_set *coef;
2141 int f = edge_multiplicity(edge, use_coincidence);
2143 if (f == 0) {
2144 isl_map_free(map);
2145 return isl_stat_ok;
2148 if (edge->src == edge->dst)
2149 coef = intra_coefficients(graph, edge->src, map);
2150 else
2151 coef = inter_coefficients(graph, edge, map);
2152 if (!coef)
2153 return isl_stat_error;
2154 *n_eq += f * isl_basic_set_n_equality(coef);
2155 *n_ineq += f * isl_basic_set_n_inequality(coef);
2156 isl_basic_set_free(coef);
2158 return isl_stat_ok;
2161 /* Count the number of equality and inequality constraints
2162 * that will be added to the main lp problem.
2163 * We count as follows
2164 * validity -> 1 (>= 0)
2165 * validity+proximity -> 2 (>= 0 and upper bound)
2166 * proximity -> 2 (lower and upper bound)
2167 * local(+any) -> 2 (>= 0 and <= 0)
2169 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2170 * Otherwise, we ignore them.
2172 static int count_constraints(struct isl_sched_graph *graph,
2173 int *n_eq, int *n_ineq, int use_coincidence)
2175 int i;
2177 *n_eq = *n_ineq = 0;
2178 for (i = 0; i < graph->n_edge; ++i) {
2179 struct isl_sched_edge *edge = &graph->edge[i];
2180 isl_map *map = isl_map_copy(edge->map);
2182 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2183 use_coincidence) < 0)
2184 return -1;
2187 return 0;
2190 /* Count the number of constraints that will be added by
2191 * add_bound_constant_constraints to bound the values of the constant terms
2192 * and increment *n_eq and *n_ineq accordingly.
2194 * In practice, add_bound_constant_constraints only adds inequalities.
2196 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2197 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2199 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2200 return isl_stat_ok;
2202 *n_ineq += graph->n;
2204 return isl_stat_ok;
2207 /* Add constraints to bound the values of the constant terms in the schedule,
2208 * if requested by the user.
2210 * The maximal value of the constant terms is defined by the option
2211 * "schedule_max_constant_term".
2213 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2214 struct isl_sched_graph *graph)
2216 int i, k;
2217 int max;
2218 int total;
2220 max = isl_options_get_schedule_max_constant_term(ctx);
2221 if (max == -1)
2222 return isl_stat_ok;
2224 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2226 for (i = 0; i < graph->n; ++i) {
2227 struct isl_sched_node *node = &graph->node[i];
2228 int pos;
2230 k = isl_basic_set_alloc_inequality(graph->lp);
2231 if (k < 0)
2232 return isl_stat_error;
2233 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2234 pos = node_cst_coef_offset(node);
2235 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2236 isl_int_set_si(graph->lp->ineq[k][0], max);
2239 return isl_stat_ok;
2242 /* Count the number of constraints that will be added by
2243 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2244 * accordingly.
2246 * In practice, add_bound_coefficient_constraints only adds inequalities.
2248 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2249 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2251 int i;
2253 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2254 !isl_options_get_schedule_treat_coalescing(ctx))
2255 return 0;
2257 for (i = 0; i < graph->n; ++i)
2258 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2260 return 0;
2263 /* Add constraints to graph->lp that bound the values of
2264 * the parameter schedule coefficients of "node" to "max" and
2265 * the variable schedule coefficients to the corresponding entry
2266 * in node->max.
2267 * In either case, a negative value means that no bound needs to be imposed.
2269 * For parameter coefficients, this amounts to adding a constraint
2271 * c_n <= max
2273 * i.e.,
2275 * -c_n + max >= 0
2277 * The variables coefficients are, however, not represented directly.
2278 * Instead, the variable coefficients c_x are written as differences
2279 * c_x = c_x^+ - c_x^-.
2280 * That is,
2282 * -max_i <= c_x_i <= max_i
2284 * is encoded as
2286 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2288 * or
2290 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2291 * c_x_i^+ - c_x_i^- + max_i >= 0
2293 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2294 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2296 int i, j, k;
2297 int total;
2298 isl_vec *ineq;
2300 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2302 for (j = 0; j < node->nparam; ++j) {
2303 int dim;
2305 if (max < 0)
2306 continue;
2308 k = isl_basic_set_alloc_inequality(graph->lp);
2309 if (k < 0)
2310 return isl_stat_error;
2311 dim = 1 + node_par_coef_offset(node) + j;
2312 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2313 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2314 isl_int_set_si(graph->lp->ineq[k][0], max);
2317 ineq = isl_vec_alloc(ctx, 1 + total);
2318 ineq = isl_vec_clr(ineq);
2319 if (!ineq)
2320 return isl_stat_error;
2321 for (i = 0; i < node->nvar; ++i) {
2322 int pos = 1 + node_var_coef_pos(node, i);
2324 if (isl_int_is_neg(node->max->el[i]))
2325 continue;
2327 isl_int_set_si(ineq->el[pos], 1);
2328 isl_int_set_si(ineq->el[pos + 1], -1);
2329 isl_int_set(ineq->el[0], node->max->el[i]);
2331 k = isl_basic_set_alloc_inequality(graph->lp);
2332 if (k < 0)
2333 goto error;
2334 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2336 isl_seq_neg(ineq->el + pos, ineq->el + pos + 2 * i, 2);
2337 k = isl_basic_set_alloc_inequality(graph->lp);
2338 if (k < 0)
2339 goto error;
2340 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2342 isl_vec_free(ineq);
2344 return isl_stat_ok;
2345 error:
2346 isl_vec_free(ineq);
2347 return isl_stat_error;
2350 /* Add constraints that bound the values of the variable and parameter
2351 * coefficients of the schedule.
2353 * The maximal value of the coefficients is defined by the option
2354 * 'schedule_max_coefficient' and the entries in node->max.
2355 * These latter entries are only set if either the schedule_max_coefficient
2356 * option or the schedule_treat_coalescing option is set.
2358 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2359 struct isl_sched_graph *graph)
2361 int i;
2362 int max;
2364 max = isl_options_get_schedule_max_coefficient(ctx);
2366 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2367 return isl_stat_ok;
2369 for (i = 0; i < graph->n; ++i) {
2370 struct isl_sched_node *node = &graph->node[i];
2372 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2373 return isl_stat_error;
2376 return isl_stat_ok;
2379 /* Add a constraint to graph->lp that equates the value at position
2380 * "sum_pos" to the sum of the "n" values starting at "first".
2382 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2383 int sum_pos, int first, int n)
2385 int i, k;
2386 int total;
2388 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2390 k = isl_basic_set_alloc_equality(graph->lp);
2391 if (k < 0)
2392 return isl_stat_error;
2393 isl_seq_clr(graph->lp->eq[k], 1 + total);
2394 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2395 for (i = 0; i < n; ++i)
2396 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2398 return isl_stat_ok;
2401 /* Add a constraint to graph->lp that equates the value at position
2402 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2404 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2405 int sum_pos)
2407 int i, j, k;
2408 int total;
2410 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2412 k = isl_basic_set_alloc_equality(graph->lp);
2413 if (k < 0)
2414 return isl_stat_error;
2415 isl_seq_clr(graph->lp->eq[k], 1 + total);
2416 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2417 for (i = 0; i < graph->n; ++i) {
2418 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2420 for (j = 0; j < graph->node[i].nparam; ++j)
2421 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2424 return isl_stat_ok;
2427 /* Add a constraint to graph->lp that equates the value at position
2428 * "sum_pos" to the sum of the variable coefficients of all nodes.
2430 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2431 int sum_pos)
2433 int i, j, k;
2434 int total;
2436 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2438 k = isl_basic_set_alloc_equality(graph->lp);
2439 if (k < 0)
2440 return isl_stat_error;
2441 isl_seq_clr(graph->lp->eq[k], 1 + total);
2442 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2443 for (i = 0; i < graph->n; ++i) {
2444 struct isl_sched_node *node = &graph->node[i];
2445 int pos = 1 + node_var_coef_offset(node);
2447 for (j = 0; j < 2 * node->nvar; ++j)
2448 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2451 return isl_stat_ok;
2454 /* Construct an ILP problem for finding schedule coefficients
2455 * that result in non-negative, but small dependence distances
2456 * over all dependences.
2457 * In particular, the dependence distances over proximity edges
2458 * are bounded by m_0 + m_n n and we compute schedule coefficients
2459 * with small values (preferably zero) of m_n and m_0.
2461 * All variables of the ILP are non-negative. The actual coefficients
2462 * may be negative, so each coefficient is represented as the difference
2463 * of two non-negative variables. The negative part always appears
2464 * immediately before the positive part.
2465 * Other than that, the variables have the following order
2467 * - sum of positive and negative parts of m_n coefficients
2468 * - m_0
2469 * - sum of all c_n coefficients
2470 * (unconstrained when computing non-parametric schedules)
2471 * - sum of positive and negative parts of all c_x coefficients
2472 * - positive and negative parts of m_n coefficients
2473 * - for each node
2474 * - positive and negative parts of c_i_x, in opposite order
2475 * - c_i_n (if parametric)
2476 * - c_i_0
2478 * The constraints are those from the edges plus two or three equalities
2479 * to express the sums.
2481 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2482 * Otherwise, we ignore them.
2484 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2485 int use_coincidence)
2487 int i;
2488 unsigned nparam;
2489 unsigned total;
2490 isl_space *space;
2491 int parametric;
2492 int param_pos;
2493 int n_eq, n_ineq;
2495 parametric = ctx->opt->schedule_parametric;
2496 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2497 param_pos = 4;
2498 total = param_pos + 2 * nparam;
2499 for (i = 0; i < graph->n; ++i) {
2500 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2501 if (node_update_vmap(node) < 0)
2502 return isl_stat_error;
2503 node->start = total;
2504 total += 1 + node->nparam + 2 * node->nvar;
2507 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2508 return isl_stat_error;
2509 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2510 return isl_stat_error;
2511 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2512 return isl_stat_error;
2514 space = isl_space_set_alloc(ctx, 0, total);
2515 isl_basic_set_free(graph->lp);
2516 n_eq += 2 + parametric;
2518 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2520 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2521 return isl_stat_error;
2522 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2523 return isl_stat_error;
2524 if (add_var_sum_constraint(graph, 3) < 0)
2525 return isl_stat_error;
2526 if (add_bound_constant_constraints(ctx, graph) < 0)
2527 return isl_stat_error;
2528 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2529 return isl_stat_error;
2530 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2531 return isl_stat_error;
2532 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2533 return isl_stat_error;
2535 return isl_stat_ok;
2538 /* Analyze the conflicting constraint found by
2539 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2540 * constraint of one of the edges between distinct nodes, living, moreover
2541 * in distinct SCCs, then record the source and sink SCC as this may
2542 * be a good place to cut between SCCs.
2544 static int check_conflict(int con, void *user)
2546 int i;
2547 struct isl_sched_graph *graph = user;
2549 if (graph->src_scc >= 0)
2550 return 0;
2552 con -= graph->lp->n_eq;
2554 if (con >= graph->lp->n_ineq)
2555 return 0;
2557 for (i = 0; i < graph->n_edge; ++i) {
2558 if (!is_validity(&graph->edge[i]))
2559 continue;
2560 if (graph->edge[i].src == graph->edge[i].dst)
2561 continue;
2562 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2563 continue;
2564 if (graph->edge[i].start > con)
2565 continue;
2566 if (graph->edge[i].end <= con)
2567 continue;
2568 graph->src_scc = graph->edge[i].src->scc;
2569 graph->dst_scc = graph->edge[i].dst->scc;
2572 return 0;
2575 /* Check whether the next schedule row of the given node needs to be
2576 * non-trivial. Lower-dimensional domains may have some trivial rows,
2577 * but as soon as the number of remaining required non-trivial rows
2578 * is as large as the number or remaining rows to be computed,
2579 * all remaining rows need to be non-trivial.
2581 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2583 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2586 /* Construct a non-triviality region with triviality directions
2587 * corresponding to the rows of "indep".
2588 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2589 * while the triviality directions are expressed in terms of
2590 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2591 * before c^+_i. Furthermore,
2592 * the pairs of non-negative variables representing the coefficients
2593 * are stored in the opposite order.
2595 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2597 isl_ctx *ctx;
2598 isl_mat *mat;
2599 int i, j, n, n_var;
2601 if (!indep)
2602 return NULL;
2604 ctx = isl_mat_get_ctx(indep);
2605 n = isl_mat_rows(indep);
2606 n_var = isl_mat_cols(indep);
2607 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2608 if (!mat)
2609 return NULL;
2610 for (i = 0; i < n; ++i) {
2611 for (j = 0; j < n_var; ++j) {
2612 int nj = n_var - 1 - j;
2613 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2614 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2618 return mat;
2621 /* Solve the ILP problem constructed in setup_lp.
2622 * For each node such that all the remaining rows of its schedule
2623 * need to be non-trivial, we construct a non-triviality region.
2624 * This region imposes that the next row is independent of previous rows.
2625 * In particular, the non-triviality region enforces that at least
2626 * one of the linear combinations in the rows of node->indep is non-zero.
2628 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2630 int i;
2631 isl_vec *sol;
2632 isl_basic_set *lp;
2634 for (i = 0; i < graph->n; ++i) {
2635 struct isl_sched_node *node = &graph->node[i];
2636 isl_mat *trivial;
2638 graph->region[i].pos = node_var_coef_offset(node);
2639 if (needs_row(graph, node))
2640 trivial = construct_trivial(node->indep);
2641 else
2642 trivial = isl_mat_zero(ctx, 0, 0);
2643 graph->region[i].trivial = trivial;
2645 lp = isl_basic_set_copy(graph->lp);
2646 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2647 graph->region, &check_conflict, graph);
2648 for (i = 0; i < graph->n; ++i)
2649 isl_mat_free(graph->region[i].trivial);
2650 return sol;
2653 /* Extract the coefficients for the variables of "node" from "sol".
2655 * Each schedule coefficient c_i_x is represented as the difference
2656 * between two non-negative variables c_i_x^+ - c_i_x^-.
2657 * The c_i_x^- appear before their c_i_x^+ counterpart.
2658 * Furthermore, the order of these pairs is the opposite of that
2659 * of the corresponding coefficients.
2661 * Return c_i_x = c_i_x^+ - c_i_x^-
2663 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2664 __isl_keep isl_vec *sol)
2666 int i;
2667 int pos;
2668 isl_vec *csol;
2670 if (!sol)
2671 return NULL;
2672 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2673 if (!csol)
2674 return NULL;
2676 pos = 1 + node_var_coef_offset(node);
2677 for (i = 0; i < node->nvar; ++i)
2678 isl_int_sub(csol->el[node->nvar - 1 - i],
2679 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2681 return csol;
2684 /* Update the schedules of all nodes based on the given solution
2685 * of the LP problem.
2686 * The new row is added to the current band.
2687 * All possibly negative coefficients are encoded as a difference
2688 * of two non-negative variables, so we need to perform the subtraction
2689 * here.
2691 * If coincident is set, then the caller guarantees that the new
2692 * row satisfies the coincidence constraints.
2694 static int update_schedule(struct isl_sched_graph *graph,
2695 __isl_take isl_vec *sol, int coincident)
2697 int i, j;
2698 isl_vec *csol = NULL;
2700 if (!sol)
2701 goto error;
2702 if (sol->size == 0)
2703 isl_die(sol->ctx, isl_error_internal,
2704 "no solution found", goto error);
2705 if (graph->n_total_row >= graph->max_row)
2706 isl_die(sol->ctx, isl_error_internal,
2707 "too many schedule rows", goto error);
2709 for (i = 0; i < graph->n; ++i) {
2710 struct isl_sched_node *node = &graph->node[i];
2711 int pos;
2712 int row = isl_mat_rows(node->sched);
2714 isl_vec_free(csol);
2715 csol = extract_var_coef(node, sol);
2716 if (!csol)
2717 goto error;
2719 isl_map_free(node->sched_map);
2720 node->sched_map = NULL;
2721 node->sched = isl_mat_add_rows(node->sched, 1);
2722 if (!node->sched)
2723 goto error;
2724 pos = node_cst_coef_offset(node);
2725 node->sched = isl_mat_set_element(node->sched,
2726 row, 0, sol->el[1 + pos]);
2727 pos = node_par_coef_offset(node);
2728 for (j = 0; j < node->nparam; ++j)
2729 node->sched = isl_mat_set_element(node->sched,
2730 row, 1 + j, sol->el[1 + pos + j]);
2731 for (j = 0; j < node->nvar; ++j)
2732 node->sched = isl_mat_set_element(node->sched,
2733 row, 1 + node->nparam + j, csol->el[j]);
2734 node->coincident[graph->n_total_row] = coincident;
2736 isl_vec_free(sol);
2737 isl_vec_free(csol);
2739 graph->n_row++;
2740 graph->n_total_row++;
2742 return 0;
2743 error:
2744 isl_vec_free(sol);
2745 isl_vec_free(csol);
2746 return -1;
2749 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2750 * and return this isl_aff.
2752 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2753 struct isl_sched_node *node, int row)
2755 int j;
2756 isl_int v;
2757 isl_aff *aff;
2759 isl_int_init(v);
2761 aff = isl_aff_zero_on_domain(ls);
2762 isl_mat_get_element(node->sched, row, 0, &v);
2763 aff = isl_aff_set_constant(aff, v);
2764 for (j = 0; j < node->nparam; ++j) {
2765 isl_mat_get_element(node->sched, row, 1 + j, &v);
2766 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2768 for (j = 0; j < node->nvar; ++j) {
2769 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2770 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2773 isl_int_clear(v);
2775 return aff;
2778 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2779 * and return this multi_aff.
2781 * The result is defined over the uncompressed node domain.
2783 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2784 struct isl_sched_node *node, int first, int n)
2786 int i;
2787 isl_space *space;
2788 isl_local_space *ls;
2789 isl_aff *aff;
2790 isl_multi_aff *ma;
2791 int nrow;
2793 if (!node)
2794 return NULL;
2795 nrow = isl_mat_rows(node->sched);
2796 if (node->compressed)
2797 space = isl_multi_aff_get_domain_space(node->decompress);
2798 else
2799 space = isl_space_copy(node->space);
2800 ls = isl_local_space_from_space(isl_space_copy(space));
2801 space = isl_space_from_domain(space);
2802 space = isl_space_add_dims(space, isl_dim_out, n);
2803 ma = isl_multi_aff_zero(space);
2805 for (i = first; i < first + n; ++i) {
2806 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2807 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2810 isl_local_space_free(ls);
2812 if (node->compressed)
2813 ma = isl_multi_aff_pullback_multi_aff(ma,
2814 isl_multi_aff_copy(node->compress));
2816 return ma;
2819 /* Convert node->sched into a multi_aff and return this multi_aff.
2821 * The result is defined over the uncompressed node domain.
2823 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2824 struct isl_sched_node *node)
2826 int nrow;
2828 nrow = isl_mat_rows(node->sched);
2829 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2832 /* Convert node->sched into a map and return this map.
2834 * The result is cached in node->sched_map, which needs to be released
2835 * whenever node->sched is updated.
2836 * It is defined over the uncompressed node domain.
2838 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2840 if (!node->sched_map) {
2841 isl_multi_aff *ma;
2843 ma = node_extract_schedule_multi_aff(node);
2844 node->sched_map = isl_map_from_multi_aff(ma);
2847 return isl_map_copy(node->sched_map);
2850 /* Construct a map that can be used to update a dependence relation
2851 * based on the current schedule.
2852 * That is, construct a map expressing that source and sink
2853 * are executed within the same iteration of the current schedule.
2854 * This map can then be intersected with the dependence relation.
2855 * This is not the most efficient way, but this shouldn't be a critical
2856 * operation.
2858 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2859 struct isl_sched_node *dst)
2861 isl_map *src_sched, *dst_sched;
2863 src_sched = node_extract_schedule(src);
2864 dst_sched = node_extract_schedule(dst);
2865 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2868 /* Intersect the domains of the nested relations in domain and range
2869 * of "umap" with "map".
2871 static __isl_give isl_union_map *intersect_domains(
2872 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2874 isl_union_set *uset;
2876 umap = isl_union_map_zip(umap);
2877 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2878 umap = isl_union_map_intersect_domain(umap, uset);
2879 umap = isl_union_map_zip(umap);
2880 return umap;
2883 /* Update the dependence relation of the given edge based
2884 * on the current schedule.
2885 * If the dependence is carried completely by the current schedule, then
2886 * it is removed from the edge_tables. It is kept in the list of edges
2887 * as otherwise all edge_tables would have to be recomputed.
2889 static int update_edge(struct isl_sched_graph *graph,
2890 struct isl_sched_edge *edge)
2892 int empty;
2893 isl_map *id;
2895 id = specializer(edge->src, edge->dst);
2896 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2897 if (!edge->map)
2898 goto error;
2900 if (edge->tagged_condition) {
2901 edge->tagged_condition =
2902 intersect_domains(edge->tagged_condition, id);
2903 if (!edge->tagged_condition)
2904 goto error;
2906 if (edge->tagged_validity) {
2907 edge->tagged_validity =
2908 intersect_domains(edge->tagged_validity, id);
2909 if (!edge->tagged_validity)
2910 goto error;
2913 empty = isl_map_plain_is_empty(edge->map);
2914 if (empty < 0)
2915 goto error;
2916 if (empty)
2917 graph_remove_edge(graph, edge);
2919 isl_map_free(id);
2920 return 0;
2921 error:
2922 isl_map_free(id);
2923 return -1;
2926 /* Does the domain of "umap" intersect "uset"?
2928 static int domain_intersects(__isl_keep isl_union_map *umap,
2929 __isl_keep isl_union_set *uset)
2931 int empty;
2933 umap = isl_union_map_copy(umap);
2934 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2935 empty = isl_union_map_is_empty(umap);
2936 isl_union_map_free(umap);
2938 return empty < 0 ? -1 : !empty;
2941 /* Does the range of "umap" intersect "uset"?
2943 static int range_intersects(__isl_keep isl_union_map *umap,
2944 __isl_keep isl_union_set *uset)
2946 int empty;
2948 umap = isl_union_map_copy(umap);
2949 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2950 empty = isl_union_map_is_empty(umap);
2951 isl_union_map_free(umap);
2953 return empty < 0 ? -1 : !empty;
2956 /* Are the condition dependences of "edge" local with respect to
2957 * the current schedule?
2959 * That is, are domain and range of the condition dependences mapped
2960 * to the same point?
2962 * In other words, is the condition false?
2964 static int is_condition_false(struct isl_sched_edge *edge)
2966 isl_union_map *umap;
2967 isl_map *map, *sched, *test;
2968 int empty, local;
2970 empty = isl_union_map_is_empty(edge->tagged_condition);
2971 if (empty < 0 || empty)
2972 return empty;
2974 umap = isl_union_map_copy(edge->tagged_condition);
2975 umap = isl_union_map_zip(umap);
2976 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2977 map = isl_map_from_union_map(umap);
2979 sched = node_extract_schedule(edge->src);
2980 map = isl_map_apply_domain(map, sched);
2981 sched = node_extract_schedule(edge->dst);
2982 map = isl_map_apply_range(map, sched);
2984 test = isl_map_identity(isl_map_get_space(map));
2985 local = isl_map_is_subset(map, test);
2986 isl_map_free(map);
2987 isl_map_free(test);
2989 return local;
2992 /* For each conditional validity constraint that is adjacent
2993 * to a condition with domain in condition_source or range in condition_sink,
2994 * turn it into an unconditional validity constraint.
2996 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2997 __isl_take isl_union_set *condition_source,
2998 __isl_take isl_union_set *condition_sink)
3000 int i;
3002 condition_source = isl_union_set_coalesce(condition_source);
3003 condition_sink = isl_union_set_coalesce(condition_sink);
3005 for (i = 0; i < graph->n_edge; ++i) {
3006 int adjacent;
3007 isl_union_map *validity;
3009 if (!is_conditional_validity(&graph->edge[i]))
3010 continue;
3011 if (is_validity(&graph->edge[i]))
3012 continue;
3014 validity = graph->edge[i].tagged_validity;
3015 adjacent = domain_intersects(validity, condition_sink);
3016 if (adjacent >= 0 && !adjacent)
3017 adjacent = range_intersects(validity, condition_source);
3018 if (adjacent < 0)
3019 goto error;
3020 if (!adjacent)
3021 continue;
3023 set_validity(&graph->edge[i]);
3026 isl_union_set_free(condition_source);
3027 isl_union_set_free(condition_sink);
3028 return 0;
3029 error:
3030 isl_union_set_free(condition_source);
3031 isl_union_set_free(condition_sink);
3032 return -1;
3035 /* Update the dependence relations of all edges based on the current schedule
3036 * and enforce conditional validity constraints that are adjacent
3037 * to satisfied condition constraints.
3039 * First check if any of the condition constraints are satisfied
3040 * (i.e., not local to the outer schedule) and keep track of
3041 * their domain and range.
3042 * Then update all dependence relations (which removes the non-local
3043 * constraints).
3044 * Finally, if any condition constraints turned out to be satisfied,
3045 * then turn all adjacent conditional validity constraints into
3046 * unconditional validity constraints.
3048 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3050 int i;
3051 int any = 0;
3052 isl_union_set *source, *sink;
3054 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3055 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3056 for (i = 0; i < graph->n_edge; ++i) {
3057 int local;
3058 isl_union_set *uset;
3059 isl_union_map *umap;
3061 if (!is_condition(&graph->edge[i]))
3062 continue;
3063 if (is_local(&graph->edge[i]))
3064 continue;
3065 local = is_condition_false(&graph->edge[i]);
3066 if (local < 0)
3067 goto error;
3068 if (local)
3069 continue;
3071 any = 1;
3073 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3074 uset = isl_union_map_domain(umap);
3075 source = isl_union_set_union(source, uset);
3077 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3078 uset = isl_union_map_range(umap);
3079 sink = isl_union_set_union(sink, uset);
3082 for (i = graph->n_edge - 1; i >= 0; --i) {
3083 if (update_edge(graph, &graph->edge[i]) < 0)
3084 goto error;
3087 if (any)
3088 return unconditionalize_adjacent_validity(graph, source, sink);
3090 isl_union_set_free(source);
3091 isl_union_set_free(sink);
3092 return 0;
3093 error:
3094 isl_union_set_free(source);
3095 isl_union_set_free(sink);
3096 return -1;
3099 static void next_band(struct isl_sched_graph *graph)
3101 graph->band_start = graph->n_total_row;
3104 /* Return the union of the universe domains of the nodes in "graph"
3105 * that satisfy "pred".
3107 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3108 struct isl_sched_graph *graph,
3109 int (*pred)(struct isl_sched_node *node, int data), int data)
3111 int i;
3112 isl_set *set;
3113 isl_union_set *dom;
3115 for (i = 0; i < graph->n; ++i)
3116 if (pred(&graph->node[i], data))
3117 break;
3119 if (i >= graph->n)
3120 isl_die(ctx, isl_error_internal,
3121 "empty component", return NULL);
3123 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3124 dom = isl_union_set_from_set(set);
3126 for (i = i + 1; i < graph->n; ++i) {
3127 if (!pred(&graph->node[i], data))
3128 continue;
3129 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3130 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3133 return dom;
3136 /* Return a list of unions of universe domains, where each element
3137 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3139 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3140 struct isl_sched_graph *graph)
3142 int i;
3143 isl_union_set_list *filters;
3145 filters = isl_union_set_list_alloc(ctx, graph->scc);
3146 for (i = 0; i < graph->scc; ++i) {
3147 isl_union_set *dom;
3149 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3150 filters = isl_union_set_list_add(filters, dom);
3153 return filters;
3156 /* Return a list of two unions of universe domains, one for the SCCs up
3157 * to and including graph->src_scc and another for the other SCCs.
3159 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3160 struct isl_sched_graph *graph)
3162 isl_union_set *dom;
3163 isl_union_set_list *filters;
3165 filters = isl_union_set_list_alloc(ctx, 2);
3166 dom = isl_sched_graph_domain(ctx, graph,
3167 &node_scc_at_most, graph->src_scc);
3168 filters = isl_union_set_list_add(filters, dom);
3169 dom = isl_sched_graph_domain(ctx, graph,
3170 &node_scc_at_least, graph->src_scc + 1);
3171 filters = isl_union_set_list_add(filters, dom);
3173 return filters;
3176 /* Copy nodes that satisfy node_pred from the src dependence graph
3177 * to the dst dependence graph.
3179 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3180 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3182 int i;
3184 dst->n = 0;
3185 for (i = 0; i < src->n; ++i) {
3186 int j;
3188 if (!node_pred(&src->node[i], data))
3189 continue;
3191 j = dst->n;
3192 dst->node[j].space = isl_space_copy(src->node[i].space);
3193 dst->node[j].compressed = src->node[i].compressed;
3194 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3195 dst->node[j].compress =
3196 isl_multi_aff_copy(src->node[i].compress);
3197 dst->node[j].decompress =
3198 isl_multi_aff_copy(src->node[i].decompress);
3199 dst->node[j].nvar = src->node[i].nvar;
3200 dst->node[j].nparam = src->node[i].nparam;
3201 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3202 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3203 dst->node[j].coincident = src->node[i].coincident;
3204 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3205 dst->node[j].max = isl_vec_copy(src->node[i].max);
3206 dst->n++;
3208 if (!dst->node[j].space || !dst->node[j].sched)
3209 return -1;
3210 if (dst->node[j].compressed &&
3211 (!dst->node[j].hull || !dst->node[j].compress ||
3212 !dst->node[j].decompress))
3213 return -1;
3216 return 0;
3219 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3220 * to the dst dependence graph.
3221 * If the source or destination node of the edge is not in the destination
3222 * graph, then it must be a backward proximity edge and it should simply
3223 * be ignored.
3225 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3226 struct isl_sched_graph *src,
3227 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3229 int i;
3230 enum isl_edge_type t;
3232 dst->n_edge = 0;
3233 for (i = 0; i < src->n_edge; ++i) {
3234 struct isl_sched_edge *edge = &src->edge[i];
3235 isl_map *map;
3236 isl_union_map *tagged_condition;
3237 isl_union_map *tagged_validity;
3238 struct isl_sched_node *dst_src, *dst_dst;
3240 if (!edge_pred(edge, data))
3241 continue;
3243 if (isl_map_plain_is_empty(edge->map))
3244 continue;
3246 dst_src = graph_find_node(ctx, dst, edge->src->space);
3247 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3248 if (!dst_src || !dst_dst) {
3249 if (is_validity(edge) || is_conditional_validity(edge))
3250 isl_die(ctx, isl_error_internal,
3251 "backward (conditional) validity edge",
3252 return -1);
3253 continue;
3256 map = isl_map_copy(edge->map);
3257 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3258 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3260 dst->edge[dst->n_edge].src = dst_src;
3261 dst->edge[dst->n_edge].dst = dst_dst;
3262 dst->edge[dst->n_edge].map = map;
3263 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3264 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3265 dst->edge[dst->n_edge].types = edge->types;
3266 dst->n_edge++;
3268 if (edge->tagged_condition && !tagged_condition)
3269 return -1;
3270 if (edge->tagged_validity && !tagged_validity)
3271 return -1;
3273 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3274 if (edge !=
3275 graph_find_edge(src, t, edge->src, edge->dst))
3276 continue;
3277 if (graph_edge_table_add(ctx, dst, t,
3278 &dst->edge[dst->n_edge - 1]) < 0)
3279 return -1;
3283 return 0;
3286 /* Compute the maximal number of variables over all nodes.
3287 * This is the maximal number of linearly independent schedule
3288 * rows that we need to compute.
3289 * Just in case we end up in a part of the dependence graph
3290 * with only lower-dimensional domains, we make sure we will
3291 * compute the required amount of extra linearly independent rows.
3293 static int compute_maxvar(struct isl_sched_graph *graph)
3295 int i;
3297 graph->maxvar = 0;
3298 for (i = 0; i < graph->n; ++i) {
3299 struct isl_sched_node *node = &graph->node[i];
3300 int nvar;
3302 if (node_update_vmap(node) < 0)
3303 return -1;
3304 nvar = node->nvar + graph->n_row - node->rank;
3305 if (nvar > graph->maxvar)
3306 graph->maxvar = nvar;
3309 return 0;
3312 /* Extract the subgraph of "graph" that consists of the node satisfying
3313 * "node_pred" and the edges satisfying "edge_pred" and store
3314 * the result in "sub".
3316 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3317 int (*node_pred)(struct isl_sched_node *node, int data),
3318 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3319 int data, struct isl_sched_graph *sub)
3321 int i, n = 0, n_edge = 0;
3322 int t;
3324 for (i = 0; i < graph->n; ++i)
3325 if (node_pred(&graph->node[i], data))
3326 ++n;
3327 for (i = 0; i < graph->n_edge; ++i)
3328 if (edge_pred(&graph->edge[i], data))
3329 ++n_edge;
3330 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3331 return -1;
3332 if (copy_nodes(sub, graph, node_pred, data) < 0)
3333 return -1;
3334 if (graph_init_table(ctx, sub) < 0)
3335 return -1;
3336 for (t = 0; t <= isl_edge_last; ++t)
3337 sub->max_edge[t] = graph->max_edge[t];
3338 if (graph_init_edge_tables(ctx, sub) < 0)
3339 return -1;
3340 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3341 return -1;
3342 sub->n_row = graph->n_row;
3343 sub->max_row = graph->max_row;
3344 sub->n_total_row = graph->n_total_row;
3345 sub->band_start = graph->band_start;
3347 return 0;
3350 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3351 struct isl_sched_graph *graph);
3352 static __isl_give isl_schedule_node *compute_schedule_wcc(
3353 isl_schedule_node *node, struct isl_sched_graph *graph);
3355 /* Compute a schedule for a subgraph of "graph". In particular, for
3356 * the graph composed of nodes that satisfy node_pred and edges that
3357 * that satisfy edge_pred.
3358 * If the subgraph is known to consist of a single component, then wcc should
3359 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3360 * Otherwise, we call compute_schedule, which will check whether the subgraph
3361 * is connected.
3363 * The schedule is inserted at "node" and the updated schedule node
3364 * is returned.
3366 static __isl_give isl_schedule_node *compute_sub_schedule(
3367 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3368 struct isl_sched_graph *graph,
3369 int (*node_pred)(struct isl_sched_node *node, int data),
3370 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3371 int data, int wcc)
3373 struct isl_sched_graph split = { 0 };
3375 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3376 &split) < 0)
3377 goto error;
3379 if (wcc)
3380 node = compute_schedule_wcc(node, &split);
3381 else
3382 node = compute_schedule(node, &split);
3384 graph_free(ctx, &split);
3385 return node;
3386 error:
3387 graph_free(ctx, &split);
3388 return isl_schedule_node_free(node);
3391 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3393 return edge->src->scc == scc && edge->dst->scc == scc;
3396 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3398 return edge->dst->scc <= scc;
3401 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3403 return edge->src->scc >= scc;
3406 /* Reset the current band by dropping all its schedule rows.
3408 static int reset_band(struct isl_sched_graph *graph)
3410 int i;
3411 int drop;
3413 drop = graph->n_total_row - graph->band_start;
3414 graph->n_total_row -= drop;
3415 graph->n_row -= drop;
3417 for (i = 0; i < graph->n; ++i) {
3418 struct isl_sched_node *node = &graph->node[i];
3420 isl_map_free(node->sched_map);
3421 node->sched_map = NULL;
3423 node->sched = isl_mat_drop_rows(node->sched,
3424 graph->band_start, drop);
3426 if (!node->sched)
3427 return -1;
3430 return 0;
3433 /* Split the current graph into two parts and compute a schedule for each
3434 * part individually. In particular, one part consists of all SCCs up
3435 * to and including graph->src_scc, while the other part contains the other
3436 * SCCs. The split is enforced by a sequence node inserted at position "node"
3437 * in the schedule tree. Return the updated schedule node.
3438 * If either of these two parts consists of a sequence, then it is spliced
3439 * into the sequence containing the two parts.
3441 * The current band is reset. It would be possible to reuse
3442 * the previously computed rows as the first rows in the next
3443 * band, but recomputing them may result in better rows as we are looking
3444 * at a smaller part of the dependence graph.
3446 static __isl_give isl_schedule_node *compute_split_schedule(
3447 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3449 int is_seq;
3450 isl_ctx *ctx;
3451 isl_union_set_list *filters;
3453 if (!node)
3454 return NULL;
3456 if (reset_band(graph) < 0)
3457 return isl_schedule_node_free(node);
3459 next_band(graph);
3461 ctx = isl_schedule_node_get_ctx(node);
3462 filters = extract_split(ctx, graph);
3463 node = isl_schedule_node_insert_sequence(node, filters);
3464 node = isl_schedule_node_child(node, 1);
3465 node = isl_schedule_node_child(node, 0);
3467 node = compute_sub_schedule(node, ctx, graph,
3468 &node_scc_at_least, &edge_src_scc_at_least,
3469 graph->src_scc + 1, 0);
3470 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3471 node = isl_schedule_node_parent(node);
3472 node = isl_schedule_node_parent(node);
3473 if (is_seq)
3474 node = isl_schedule_node_sequence_splice_child(node, 1);
3475 node = isl_schedule_node_child(node, 0);
3476 node = isl_schedule_node_child(node, 0);
3477 node = compute_sub_schedule(node, ctx, graph,
3478 &node_scc_at_most, &edge_dst_scc_at_most,
3479 graph->src_scc, 0);
3480 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3481 node = isl_schedule_node_parent(node);
3482 node = isl_schedule_node_parent(node);
3483 if (is_seq)
3484 node = isl_schedule_node_sequence_splice_child(node, 0);
3486 return node;
3489 /* Insert a band node at position "node" in the schedule tree corresponding
3490 * to the current band in "graph". Mark the band node permutable
3491 * if "permutable" is set.
3492 * The partial schedules and the coincidence property are extracted
3493 * from the graph nodes.
3494 * Return the updated schedule node.
3496 static __isl_give isl_schedule_node *insert_current_band(
3497 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3498 int permutable)
3500 int i;
3501 int start, end, n;
3502 isl_multi_aff *ma;
3503 isl_multi_pw_aff *mpa;
3504 isl_multi_union_pw_aff *mupa;
3506 if (!node)
3507 return NULL;
3509 if (graph->n < 1)
3510 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3511 "graph should have at least one node",
3512 return isl_schedule_node_free(node));
3514 start = graph->band_start;
3515 end = graph->n_total_row;
3516 n = end - start;
3518 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3519 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3520 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3522 for (i = 1; i < graph->n; ++i) {
3523 isl_multi_union_pw_aff *mupa_i;
3525 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3526 start, n);
3527 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3528 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3529 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3531 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3533 for (i = 0; i < n; ++i)
3534 node = isl_schedule_node_band_member_set_coincident(node, i,
3535 graph->node[0].coincident[start + i]);
3536 node = isl_schedule_node_band_set_permutable(node, permutable);
3538 return node;
3541 /* Update the dependence relations based on the current schedule,
3542 * add the current band to "node" and then continue with the computation
3543 * of the next band.
3544 * Return the updated schedule node.
3546 static __isl_give isl_schedule_node *compute_next_band(
3547 __isl_take isl_schedule_node *node,
3548 struct isl_sched_graph *graph, int permutable)
3550 isl_ctx *ctx;
3552 if (!node)
3553 return NULL;
3555 ctx = isl_schedule_node_get_ctx(node);
3556 if (update_edges(ctx, graph) < 0)
3557 return isl_schedule_node_free(node);
3558 node = insert_current_band(node, graph, permutable);
3559 next_band(graph);
3561 node = isl_schedule_node_child(node, 0);
3562 node = compute_schedule(node, graph);
3563 node = isl_schedule_node_parent(node);
3565 return node;
3568 /* Add the constraints "coef" derived from an edge from "node" to itself
3569 * to graph->lp in order to respect the dependences and to try and carry them.
3570 * "pos" is the sequence number of the edge that needs to be carried.
3571 * "coef" represents general constraints on coefficients (c_0, c_n, c_x)
3572 * of valid constraints for (y - x) with x and y instances of the node.
3574 * The constraints added to graph->lp need to enforce
3576 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3577 * = c_j_x (y - x) >= e_i
3579 * for each (x,y) in the dependence relation of the edge.
3580 * That is, (-e_i, 0, c_j_x) needs to be plugged in for (c_0, c_n, c_x),
3581 * taking into account that each coefficient in c_j_x is represented
3582 * as a pair of non-negative coefficients.
3584 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3585 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3587 int offset;
3588 isl_ctx *ctx;
3589 isl_dim_map *dim_map;
3591 if (!coef)
3592 return isl_stat_error;
3594 ctx = isl_basic_set_get_ctx(coef);
3595 offset = coef_var_offset(coef);
3596 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3597 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3598 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3600 return isl_stat_ok;
3603 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3604 * to graph->lp in order to respect the dependences and to try and carry them.
3605 * "pos" is the sequence number of the edge that needs to be carried.
3606 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3607 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3609 * The constraints added to graph->lp need to enforce
3611 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3613 * for each (x,y) in the dependence relation of the edge.
3614 * That is,
3615 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3616 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3617 * taking into account that each coefficient in c_j_x and c_k_x is represented
3618 * as a pair of non-negative coefficients.
3620 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3621 struct isl_sched_node *src, struct isl_sched_node *dst,
3622 __isl_take isl_basic_set *coef, int pos)
3624 int offset;
3625 isl_ctx *ctx;
3626 isl_dim_map *dim_map;
3628 if (!coef)
3629 return isl_stat_error;
3631 ctx = isl_basic_set_get_ctx(coef);
3632 offset = coef_var_offset(coef);
3633 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3634 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3635 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3637 return isl_stat_ok;
3640 /* Data structure collecting information used during the construction
3641 * of an LP for carrying dependences.
3643 * "intra" is a sequence of coefficient constraints for intra-node edges.
3644 * "inter" is a sequence of coefficient constraints for inter-node edges.
3646 struct isl_carry {
3647 isl_basic_set_list *intra;
3648 isl_basic_set_list *inter;
3651 /* Free all the data stored in "carry".
3653 static void isl_carry_clear(struct isl_carry *carry)
3655 isl_basic_set_list_free(carry->intra);
3656 isl_basic_set_list_free(carry->inter);
3659 /* Return a pointer to the node in "graph" that lives in "space".
3660 * If the requested node has been compressed, then "space"
3661 * corresponds to the compressed space.
3663 * First try and see if "space" is the space of an uncompressed node.
3664 * If so, return that node.
3665 * Otherwise, "space" was constructed by construct_compressed_id and
3666 * contains a user pointer pointing to the node in the tuple id.
3668 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3669 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3671 isl_id *id;
3672 struct isl_sched_node *node;
3674 if (!space)
3675 return NULL;
3677 node = graph_find_node(ctx, graph, space);
3678 if (node)
3679 return node;
3681 id = isl_space_get_tuple_id(space, isl_dim_set);
3682 node = isl_id_get_user(id);
3683 isl_id_free(id);
3685 if (!node)
3686 return NULL;
3688 if (!(node >= &graph->node[0] && node < &graph->node[graph->n]))
3689 isl_die(ctx, isl_error_internal,
3690 "space points to invalid node", return NULL);
3692 return node;
3695 /* Internal data structure for add_all_constraints.
3697 * "graph" is the schedule constraint graph for which an LP problem
3698 * is being constructed.
3699 * "pos" is the position of the next edge that needs to be carried.
3701 struct isl_add_all_constraints_data {
3702 isl_ctx *ctx;
3703 struct isl_sched_graph *graph;
3704 int pos;
3707 /* Add the constraints "coef" derived from an edge from a node to itself
3708 * to data->graph->lp in order to respect the dependences and
3709 * to try and carry them.
3711 * The space of "coef" is of the form
3713 * coefficients[[c_cst, c_n] -> S[c_x]]
3715 * with S[c_x] the (compressed) space of the node.
3716 * Extract the node from the space and call add_intra_constraints.
3718 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3720 struct isl_add_all_constraints_data *data = user;
3721 isl_space *space;
3722 struct isl_sched_node *node;
3724 space = isl_basic_set_get_space(coef);
3725 space = isl_space_range(isl_space_unwrap(space));
3726 node = graph_find_compressed_node(data->ctx, data->graph, space);
3727 isl_space_free(space);
3728 return add_intra_constraints(data->graph, node, coef, data->pos++);
3731 /* Add the constraints "coef" derived from an edge from a node j
3732 * to a node k to data->graph->lp in order to respect the dependences and
3733 * to try and carry them.
3735 * The space of "coef" is of the form
3737 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3739 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3740 * Extract the nodes from the space and call add_inter_constraints.
3742 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3744 struct isl_add_all_constraints_data *data = user;
3745 isl_space *space, *dom;
3746 struct isl_sched_node *src, *dst;
3748 space = isl_basic_set_get_space(coef);
3749 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3750 dom = isl_space_domain(isl_space_copy(space));
3751 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3752 isl_space_free(dom);
3753 space = isl_space_range(space);
3754 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3755 isl_space_free(space);
3757 return add_inter_constraints(data->graph, src, dst, coef, data->pos++);
3760 /* Add constraints to graph->lp that force all (conditional) validity
3761 * dependences to be respected and attempt to carry them.
3762 * "intra" is the sequence of coefficient constraints for intra-node edges.
3763 * "inter" is the sequence of coefficient constraints for inter-node edges.
3765 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3766 __isl_keep isl_basic_set_list *intra,
3767 __isl_keep isl_basic_set_list *inter)
3769 struct isl_add_all_constraints_data data = { ctx, graph };
3771 data.pos = 0;
3772 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3773 return isl_stat_error;
3774 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3775 return isl_stat_error;
3776 return isl_stat_ok;
3779 /* Internal data structure for count_all_constraints
3780 * for keeping track of the number of equality and inequality constraints.
3782 struct isl_sched_count {
3783 int n_eq;
3784 int n_ineq;
3787 /* Add the number of equality and inequality constraints of "bset"
3788 * to data->n_eq and data->n_ineq.
3790 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
3792 struct isl_sched_count *data = user;
3794 data->n_eq += isl_basic_set_n_equality(bset);
3795 data->n_ineq += isl_basic_set_n_inequality(bset);
3796 isl_basic_set_free(bset);
3798 return isl_stat_ok;
3801 /* Count the number of equality and inequality constraints
3802 * that will be added to the carry_lp problem.
3803 * We count each edge exactly once.
3804 * "intra" is the sequence of coefficient constraints for intra-node edges.
3805 * "inter" is the sequence of coefficient constraints for inter-node edges.
3807 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
3808 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
3810 struct isl_sched_count data;
3812 data.n_eq = data.n_ineq = 0;
3813 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
3814 return isl_stat_error;
3815 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
3816 return isl_stat_error;
3818 *n_eq = data.n_eq;
3819 *n_ineq = data.n_ineq;
3821 return isl_stat_ok;
3824 /* Construct an LP problem for finding schedule coefficients
3825 * such that the schedule carries as many validity dependences as possible.
3826 * In particular, for each dependence i, we bound the dependence distance
3827 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3828 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3829 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3830 * "intra" is the sequence of coefficient constraints for intra-node edges.
3831 * "inter" is the sequence of coefficient constraints for inter-node edges.
3832 * "n_edge" is the total number of edges.
3834 * All variables of the LP are non-negative. The actual coefficients
3835 * may be negative, so each coefficient is represented as the difference
3836 * of two non-negative variables. The negative part always appears
3837 * immediately before the positive part.
3838 * Other than that, the variables have the following order
3840 * - sum of (1 - e_i) over all edges
3841 * - sum of all c_n coefficients
3842 * (unconstrained when computing non-parametric schedules)
3843 * - sum of positive and negative parts of all c_x coefficients
3844 * - for each edge
3845 * - e_i
3846 * - for each node
3847 * - positive and negative parts of c_i_x, in opposite order
3848 * - c_i_n (if parametric)
3849 * - c_i_0
3851 * The constraints are those from the (validity) edges plus three equalities
3852 * to express the sums and n_edge inequalities to express e_i <= 1.
3854 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
3855 int n_edge, __isl_keep isl_basic_set_list *intra,
3856 __isl_keep isl_basic_set_list *inter)
3858 int i;
3859 int k;
3860 isl_space *dim;
3861 unsigned total;
3862 int n_eq, n_ineq;
3864 total = 3 + n_edge;
3865 for (i = 0; i < graph->n; ++i) {
3866 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3867 node->start = total;
3868 total += 1 + node->nparam + 2 * node->nvar;
3871 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
3872 return isl_stat_error;
3874 dim = isl_space_set_alloc(ctx, 0, total);
3875 isl_basic_set_free(graph->lp);
3876 n_eq += 3;
3877 n_ineq += n_edge;
3878 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3879 graph->lp = isl_basic_set_set_rational(graph->lp);
3881 k = isl_basic_set_alloc_equality(graph->lp);
3882 if (k < 0)
3883 return isl_stat_error;
3884 isl_seq_clr(graph->lp->eq[k], 1 + total);
3885 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3886 isl_int_set_si(graph->lp->eq[k][1], 1);
3887 for (i = 0; i < n_edge; ++i)
3888 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3890 if (add_param_sum_constraint(graph, 1) < 0)
3891 return isl_stat_error;
3892 if (add_var_sum_constraint(graph, 2) < 0)
3893 return isl_stat_error;
3895 for (i = 0; i < n_edge; ++i) {
3896 k = isl_basic_set_alloc_inequality(graph->lp);
3897 if (k < 0)
3898 return isl_stat_error;
3899 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3900 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3901 isl_int_set_si(graph->lp->ineq[k][0], 1);
3904 if (add_all_constraints(ctx, graph, intra, inter) < 0)
3905 return isl_stat_error;
3907 return isl_stat_ok;
3910 static __isl_give isl_schedule_node *compute_component_schedule(
3911 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3912 int wcc);
3914 /* If the schedule_split_scaled option is set and if the linear
3915 * parts of the scheduling rows for all nodes in the graphs have
3916 * a non-trivial common divisor, then remove this
3917 * common divisor from the linear part.
3918 * Otherwise, insert a band node directly and continue with
3919 * the construction of the schedule.
3921 * If a non-trivial common divisor is found, then
3922 * the linear part is reduced and the remainder is ignored.
3923 * The pieces of the graph that are assigned different remainders
3924 * form (groups of) strongly connected components within
3925 * the scaled down band. If needed, they can therefore
3926 * be ordered along this remainder in a sequence node.
3927 * However, this ordering is not enforced here in order to allow
3928 * the scheduler to combine some of the strongly connected components.
3930 static __isl_give isl_schedule_node *split_scaled(
3931 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3933 int i;
3934 int row;
3935 isl_ctx *ctx;
3936 isl_int gcd, gcd_i;
3938 if (!node)
3939 return NULL;
3941 ctx = isl_schedule_node_get_ctx(node);
3942 if (!ctx->opt->schedule_split_scaled)
3943 return compute_next_band(node, graph, 0);
3944 if (graph->n <= 1)
3945 return compute_next_band(node, graph, 0);
3947 isl_int_init(gcd);
3948 isl_int_init(gcd_i);
3950 isl_int_set_si(gcd, 0);
3952 row = isl_mat_rows(graph->node[0].sched) - 1;
3954 for (i = 0; i < graph->n; ++i) {
3955 struct isl_sched_node *node = &graph->node[i];
3956 int cols = isl_mat_cols(node->sched);
3958 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3959 isl_int_gcd(gcd, gcd, gcd_i);
3962 isl_int_clear(gcd_i);
3964 if (isl_int_cmp_si(gcd, 1) <= 0) {
3965 isl_int_clear(gcd);
3966 return compute_next_band(node, graph, 0);
3969 for (i = 0; i < graph->n; ++i) {
3970 struct isl_sched_node *node = &graph->node[i];
3972 isl_int_fdiv_q(node->sched->row[row][0],
3973 node->sched->row[row][0], gcd);
3974 isl_int_mul(node->sched->row[row][0],
3975 node->sched->row[row][0], gcd);
3976 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3977 if (!node->sched)
3978 goto error;
3981 isl_int_clear(gcd);
3983 return compute_next_band(node, graph, 0);
3984 error:
3985 isl_int_clear(gcd);
3986 return isl_schedule_node_free(node);
3989 /* Is the schedule row "sol" trivial on node "node"?
3990 * That is, is the solution zero on the dimensions linearly independent of
3991 * the previously found solutions?
3992 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
3994 * Each coefficient is represented as the difference between
3995 * two non-negative values in "sol".
3996 * We construct the schedule row s and check if it is linearly
3997 * independent of previously computed schedule rows
3998 * by computing T s, with T the linear combinations that are zero
3999 * on linearly dependent schedule rows.
4000 * If the result consists of all zeros, then the solution is trivial.
4002 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4004 int trivial;
4005 isl_vec *node_sol;
4007 if (!sol)
4008 return -1;
4009 if (node->nvar == node->rank)
4010 return 0;
4012 node_sol = extract_var_coef(node, sol);
4013 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4014 if (!node_sol)
4015 return -1;
4017 trivial = isl_seq_first_non_zero(node_sol->el,
4018 node->nvar - node->rank) == -1;
4020 isl_vec_free(node_sol);
4022 return trivial;
4025 /* Is the schedule row "sol" trivial on any node where it should
4026 * not be trivial?
4027 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4029 static int is_any_trivial(struct isl_sched_graph *graph,
4030 __isl_keep isl_vec *sol)
4032 int i;
4034 for (i = 0; i < graph->n; ++i) {
4035 struct isl_sched_node *node = &graph->node[i];
4036 int trivial;
4038 if (!needs_row(graph, node))
4039 continue;
4040 trivial = is_trivial(node, sol);
4041 if (trivial < 0 || trivial)
4042 return trivial;
4045 return 0;
4048 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4049 * If so, return the position of the coalesced dimension.
4050 * Otherwise, return node->nvar or -1 on error.
4052 * In particular, look for pairs of coefficients c_i and c_j such that
4053 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
4054 * If any such pair is found, then return i.
4055 * If size_i is infinity, then no check on c_i needs to be performed.
4057 static int find_node_coalescing(struct isl_sched_node *node,
4058 __isl_keep isl_vec *sol)
4060 int i, j;
4061 isl_int max;
4062 isl_vec *csol;
4064 if (node->nvar <= 1)
4065 return node->nvar;
4067 csol = extract_var_coef(node, sol);
4068 if (!csol)
4069 return -1;
4070 isl_int_init(max);
4071 for (i = 0; i < node->nvar; ++i) {
4072 isl_val *v;
4074 if (isl_int_is_zero(csol->el[i]))
4075 continue;
4076 v = isl_multi_val_get_val(node->sizes, i);
4077 if (!v)
4078 goto error;
4079 if (!isl_val_is_int(v)) {
4080 isl_val_free(v);
4081 continue;
4083 isl_int_mul(max, v->n, csol->el[i]);
4084 isl_val_free(v);
4086 for (j = 0; j < node->nvar; ++j) {
4087 if (j == i)
4088 continue;
4089 if (isl_int_abs_ge(csol->el[j], max))
4090 break;
4092 if (j < node->nvar)
4093 break;
4096 isl_int_clear(max);
4097 isl_vec_free(csol);
4098 return i;
4099 error:
4100 isl_int_clear(max);
4101 isl_vec_free(csol);
4102 return -1;
4105 /* Force the schedule coefficient at position "pos" of "node" to be zero
4106 * in "tl".
4107 * The coefficient is encoded as the difference between two non-negative
4108 * variables. Force these two variables to have the same value.
4110 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4111 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4113 int dim;
4114 isl_ctx *ctx;
4115 isl_vec *eq;
4117 ctx = isl_space_get_ctx(node->space);
4118 dim = isl_tab_lexmin_dim(tl);
4119 if (dim < 0)
4120 return isl_tab_lexmin_free(tl);
4121 eq = isl_vec_alloc(ctx, 1 + dim);
4122 eq = isl_vec_clr(eq);
4123 if (!eq)
4124 return isl_tab_lexmin_free(tl);
4126 pos = 1 + node_var_coef_pos(node, pos);
4127 isl_int_set_si(eq->el[pos], 1);
4128 isl_int_set_si(eq->el[pos + 1], -1);
4129 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4130 isl_vec_free(eq);
4132 return tl;
4135 /* Return the lexicographically smallest rational point in the basic set
4136 * from which "tl" was constructed, double checking that this input set
4137 * was not empty.
4139 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4141 isl_vec *sol;
4143 sol = isl_tab_lexmin_get_solution(tl);
4144 if (!sol)
4145 return NULL;
4146 if (sol->size == 0)
4147 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4148 "error in schedule construction",
4149 return isl_vec_free(sol));
4150 return sol;
4153 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4154 * carry any of the "n_edge" groups of dependences?
4155 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4156 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4157 * by the edge are carried by the solution.
4158 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4159 * one of those is carried.
4161 * Note that despite the fact that the problem is solved using a rational
4162 * solver, the solution is guaranteed to be integral.
4163 * Specifically, the dependence distance lower bounds e_i (and therefore
4164 * also their sum) are integers. See Lemma 5 of [1].
4166 * Any potential denominator of the sum is cleared by this function.
4167 * The denominator is not relevant for any of the other elements
4168 * in the solution.
4170 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4171 * Problem, Part II: Multi-Dimensional Time.
4172 * In Intl. Journal of Parallel Programming, 1992.
4174 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4176 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4177 isl_int_set_si(sol->el[0], 1);
4178 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4181 /* Return the lexicographically smallest rational point in "lp",
4182 * assuming that all variables are non-negative and performing some
4183 * additional sanity checks.
4184 * If "want_integral" is set, then compute the lexicographically smallest
4185 * integer point instead.
4186 * In particular, "lp" should not be empty by construction.
4187 * Double check that this is the case.
4188 * If dependences are not carried for any of the "n_edge" edges,
4189 * then return an empty vector.
4191 * If the schedule_treat_coalescing option is set and
4192 * if the computed schedule performs loop coalescing on a given node,
4193 * i.e., if it is of the form
4195 * c_i i + c_j j + ...
4197 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4198 * to cut out this solution. Repeat this process until no more loop
4199 * coalescing occurs or until no more dependences can be carried.
4200 * In the latter case, revert to the previously computed solution.
4202 * If the caller requests an integral solution and if coalescing should
4203 * be treated, then perform the coalescing treatment first as
4204 * an integral solution computed before coalescing treatment
4205 * would carry the same number of edges and would therefore probably
4206 * also be coalescing.
4208 * To allow the coalescing treatment to be performed first,
4209 * the initial solution is allowed to be rational and it is only
4210 * cut out (if needed) in the next iteration, if no coalescing measures
4211 * were taken.
4213 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4214 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4216 int i, pos, cut;
4217 isl_ctx *ctx;
4218 isl_tab_lexmin *tl;
4219 isl_vec *sol, *prev = NULL;
4220 int treat_coalescing;
4222 if (!lp)
4223 return NULL;
4224 ctx = isl_basic_set_get_ctx(lp);
4225 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4226 tl = isl_tab_lexmin_from_basic_set(lp);
4228 cut = 0;
4229 do {
4230 int integral;
4232 if (cut)
4233 tl = isl_tab_lexmin_cut_to_integer(tl);
4234 sol = non_empty_solution(tl);
4235 if (!sol)
4236 goto error;
4238 integral = isl_int_is_one(sol->el[0]);
4239 if (!carries_dependences(sol, n_edge)) {
4240 if (!prev)
4241 prev = isl_vec_alloc(ctx, 0);
4242 isl_vec_free(sol);
4243 sol = prev;
4244 break;
4246 prev = isl_vec_free(prev);
4247 cut = want_integral && !integral;
4248 if (cut)
4249 prev = sol;
4250 if (!treat_coalescing)
4251 continue;
4252 for (i = 0; i < graph->n; ++i) {
4253 struct isl_sched_node *node = &graph->node[i];
4255 pos = find_node_coalescing(node, sol);
4256 if (pos < 0)
4257 goto error;
4258 if (pos < node->nvar)
4259 break;
4261 if (i < graph->n) {
4262 prev = sol;
4263 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4264 cut = 0;
4266 } while (prev);
4268 isl_tab_lexmin_free(tl);
4270 return sol;
4271 error:
4272 isl_tab_lexmin_free(tl);
4273 isl_vec_free(prev);
4274 isl_vec_free(sol);
4275 return NULL;
4278 /* If "edge" is an edge from a node to itself, then add the corresponding
4279 * dependence relation to "umap".
4280 * If "node" has been compressed, then the dependence relation
4281 * is also compressed first.
4283 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4284 struct isl_sched_edge *edge)
4286 isl_map *map;
4287 struct isl_sched_node *node = edge->src;
4289 if (edge->src != edge->dst)
4290 return umap;
4292 map = isl_map_copy(edge->map);
4293 if (node->compressed) {
4294 map = isl_map_preimage_domain_multi_aff(map,
4295 isl_multi_aff_copy(node->decompress));
4296 map = isl_map_preimage_range_multi_aff(map,
4297 isl_multi_aff_copy(node->decompress));
4299 umap = isl_union_map_add_map(umap, map);
4300 return umap;
4303 /* If "edge" is an edge from a node to another node, then add the corresponding
4304 * dependence relation to "umap".
4305 * If the source or destination nodes of "edge" have been compressed,
4306 * then the dependence relation is also compressed first.
4308 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4309 struct isl_sched_edge *edge)
4311 isl_map *map;
4313 if (edge->src == edge->dst)
4314 return umap;
4316 map = isl_map_copy(edge->map);
4317 if (edge->src->compressed)
4318 map = isl_map_preimage_domain_multi_aff(map,
4319 isl_multi_aff_copy(edge->src->decompress));
4320 if (edge->dst->compressed)
4321 map = isl_map_preimage_range_multi_aff(map,
4322 isl_multi_aff_copy(edge->dst->decompress));
4323 umap = isl_union_map_add_map(umap, map);
4324 return umap;
4327 /* For each (conditional) validity edge in "graph",
4328 * add the corresponding dependence relation using "add"
4329 * to a collection of dependence relations and return the result.
4330 * If "coincidence" is set, then coincidence edges are considered as well.
4332 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4333 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4334 struct isl_sched_edge *edge), int coincidence)
4336 int i;
4337 isl_space *space;
4338 isl_union_map *umap;
4340 space = isl_space_copy(graph->node[0].space);
4341 umap = isl_union_map_empty(space);
4343 for (i = 0; i < graph->n_edge; ++i) {
4344 struct isl_sched_edge *edge = &graph->edge[i];
4346 if (!is_any_validity(edge) &&
4347 (!coincidence || !is_coincidence(edge)))
4348 continue;
4350 umap = add(umap, edge);
4353 return umap;
4356 /* For each dependence relation on a (conditional) validity edge
4357 * from a node to itself,
4358 * construct the set of coefficients of valid constraints for elements
4359 * in that dependence relation and collect the results.
4360 * If "coincidence" is set, then coincidence edges are considered as well.
4362 * In particular, for each dependence relation R, constraints
4363 * on coefficients (c_0, c_n, c_x) are constructed such that
4365 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4367 * This computation is essentially the same as that performed
4368 * by intra_coefficients, except that it operates on multiple
4369 * edges together.
4371 * Note that if a dependence relation is a union of basic maps,
4372 * then each basic map needs to be treated individually as it may only
4373 * be possible to carry the dependences expressed by some of those
4374 * basic maps and not all of them.
4375 * The collected validity constraints are therefore not coalesced and
4376 * it is assumed that they are not coalesced automatically.
4377 * Duplicate basic maps can be removed, however.
4378 * In particular, if the same basic map appears as a disjunct
4379 * in multiple edges, then it only needs to be carried once.
4381 static __isl_give isl_basic_set_list *collect_intra_validity(
4382 struct isl_sched_graph *graph, int coincidence)
4384 isl_union_map *intra;
4385 isl_union_set *delta;
4386 isl_basic_set_list *list;
4388 intra = collect_validity(graph, &add_intra, coincidence);
4389 delta = isl_union_map_deltas(intra);
4390 delta = isl_union_set_remove_divs(delta);
4391 list = isl_union_set_get_basic_set_list(delta);
4392 isl_union_set_free(delta);
4394 return isl_basic_set_list_coefficients(list);
4397 /* For each dependence relation on a (conditional) validity edge
4398 * from a node to some other node,
4399 * construct the set of coefficients of valid constraints for elements
4400 * in that dependence relation and collect the results.
4401 * If "coincidence" is set, then coincidence edges are considered as well.
4403 * In particular, for each dependence relation R, constraints
4404 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4406 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4408 * This computation is essentially the same as that performed
4409 * by inter_coefficients, except that it operates on multiple
4410 * edges together.
4412 * Note that if a dependence relation is a union of basic maps,
4413 * then each basic map needs to be treated individually as it may only
4414 * be possible to carry the dependences expressed by some of those
4415 * basic maps and not all of them.
4416 * The collected validity constraints are therefore not coalesced and
4417 * it is assumed that they are not coalesced automatically.
4418 * Duplicate basic maps can be removed, however.
4419 * In particular, if the same basic map appears as a disjunct
4420 * in multiple edges, then it only needs to be carried once.
4422 static __isl_give isl_basic_set_list *collect_inter_validity(
4423 struct isl_sched_graph *graph, int coincidence)
4425 isl_union_map *inter;
4426 isl_union_set *wrap;
4427 isl_basic_set_list *list;
4429 inter = collect_validity(graph, &add_inter, coincidence);
4430 inter = isl_union_map_remove_divs(inter);
4431 wrap = isl_union_map_wrap(inter);
4432 list = isl_union_set_get_basic_set_list(wrap);
4433 isl_union_set_free(wrap);
4434 return isl_basic_set_list_coefficients(list);
4437 /* Construct an LP problem for finding schedule coefficients
4438 * such that the schedule carries as many of the validity dependences
4439 * as possible and
4440 * return the lexicographically smallest non-trivial solution.
4441 * If "fallback" is set, then the carrying is performed as a fallback
4442 * for the Pluto-like scheduler.
4443 * If "coincidence" is set, then try and carry coincidence edges as well.
4445 * The variable "n_edge" stores the number of groups that should be carried.
4446 * If none of the "n_edge" groups can be carried
4447 * then return an empty vector.
4448 * If, moreover, "n_edge" is zero, then the LP problem does not even
4449 * need to be constructed.
4451 * If a fallback solution is being computed, then compute an integral solution
4452 * for the coefficients rather than using the numerators
4453 * of a rational solution.
4455 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4456 struct isl_sched_graph *graph, int fallback, int coincidence)
4458 int n_intra, n_inter;
4459 int n_edge;
4460 isl_basic_set *lp;
4461 struct isl_carry carry = { 0 };
4463 carry.intra = collect_intra_validity(graph, coincidence);
4464 carry.inter = collect_inter_validity(graph, coincidence);
4465 if (!carry.intra || !carry.inter)
4466 goto error;
4467 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4468 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4469 n_edge = n_intra + n_inter;
4470 if (n_edge == 0) {
4471 isl_carry_clear(&carry);
4472 return isl_vec_alloc(ctx, 0);
4475 if (setup_carry_lp(ctx, graph, n_edge, carry.intra, carry.inter) < 0)
4476 goto error;
4478 isl_carry_clear(&carry);
4479 lp = isl_basic_set_copy(graph->lp);
4480 return non_neg_lexmin(graph, lp, n_edge, fallback);
4481 error:
4482 isl_carry_clear(&carry);
4483 return NULL;
4486 /* Construct a schedule row for each node such that as many validity dependences
4487 * as possible are carried and then continue with the next band.
4488 * If "fallback" is set, then the carrying is performed as a fallback
4489 * for the Pluto-like scheduler.
4490 * If "coincidence" is set, then try and carry coincidence edges as well.
4492 * If there are no validity dependences, then no dependence can be carried and
4493 * the procedure is guaranteed to fail. If there is more than one component,
4494 * then try computing a schedule on each component separately
4495 * to prevent or at least postpone this failure.
4497 * If a schedule row is computed, then check that dependences are carried
4498 * for at least one of the edges.
4500 * If the computed schedule row turns out to be trivial on one or
4501 * more nodes where it should not be trivial, then we throw it away
4502 * and try again on each component separately.
4504 * If there is only one component, then we accept the schedule row anyway,
4505 * but we do not consider it as a complete row and therefore do not
4506 * increment graph->n_row. Note that the ranks of the nodes that
4507 * do get a non-trivial schedule part will get updated regardless and
4508 * graph->maxvar is computed based on these ranks. The test for
4509 * whether more schedule rows are required in compute_schedule_wcc
4510 * is therefore not affected.
4512 * Insert a band corresponding to the schedule row at position "node"
4513 * of the schedule tree and continue with the construction of the schedule.
4514 * This insertion and the continued construction is performed by split_scaled
4515 * after optionally checking for non-trivial common divisors.
4517 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
4518 struct isl_sched_graph *graph, int fallback, int coincidence)
4520 int trivial;
4521 isl_ctx *ctx;
4522 isl_vec *sol;
4524 if (!node)
4525 return NULL;
4527 ctx = isl_schedule_node_get_ctx(node);
4528 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
4529 if (!sol)
4530 return isl_schedule_node_free(node);
4531 if (sol->size == 0) {
4532 isl_vec_free(sol);
4533 if (graph->scc > 1)
4534 return compute_component_schedule(node, graph, 1);
4535 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
4536 return isl_schedule_node_free(node));
4539 trivial = is_any_trivial(graph, sol);
4540 if (trivial < 0) {
4541 sol = isl_vec_free(sol);
4542 } else if (trivial && graph->scc > 1) {
4543 isl_vec_free(sol);
4544 return compute_component_schedule(node, graph, 1);
4547 if (update_schedule(graph, sol, 0) < 0)
4548 return isl_schedule_node_free(node);
4549 if (trivial)
4550 graph->n_row--;
4552 return split_scaled(node, graph);
4555 /* Construct a schedule row for each node such that as many validity dependences
4556 * as possible are carried and then continue with the next band.
4557 * Do so as a fallback for the Pluto-like scheduler.
4558 * If "coincidence" is set, then try and carry coincidence edges as well.
4560 static __isl_give isl_schedule_node *carry_fallback(
4561 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4562 int coincidence)
4564 return carry(node, graph, 1, coincidence);
4567 /* Construct a schedule row for each node such that as many validity dependences
4568 * as possible are carried and then continue with the next band.
4569 * Do so for the case where the Feautrier scheduler was selected
4570 * by the user.
4572 static __isl_give isl_schedule_node *carry_feautrier(
4573 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4575 return carry(node, graph, 0, 0);
4578 /* Construct a schedule row for each node such that as many validity dependences
4579 * as possible are carried and then continue with the next band.
4580 * Do so as a fallback for the Pluto-like scheduler.
4582 static __isl_give isl_schedule_node *carry_dependences(
4583 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4585 return carry_fallback(node, graph, 0);
4588 /* Construct a schedule row for each node such that as many validity or
4589 * coincidence dependences as possible are carried and
4590 * then continue with the next band.
4591 * Do so as a fallback for the Pluto-like scheduler.
4593 static __isl_give isl_schedule_node *carry_coincidence(
4594 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4596 return carry_fallback(node, graph, 1);
4599 /* Topologically sort statements mapped to the same schedule iteration
4600 * and add insert a sequence node in front of "node"
4601 * corresponding to this order.
4602 * If "initialized" is set, then it may be assumed that compute_maxvar
4603 * has been called on the current band. Otherwise, call
4604 * compute_maxvar if and before carry_dependences gets called.
4606 * If it turns out to be impossible to sort the statements apart,
4607 * because different dependences impose different orderings
4608 * on the statements, then we extend the schedule such that
4609 * it carries at least one more dependence.
4611 static __isl_give isl_schedule_node *sort_statements(
4612 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4613 int initialized)
4615 isl_ctx *ctx;
4616 isl_union_set_list *filters;
4618 if (!node)
4619 return NULL;
4621 ctx = isl_schedule_node_get_ctx(node);
4622 if (graph->n < 1)
4623 isl_die(ctx, isl_error_internal,
4624 "graph should have at least one node",
4625 return isl_schedule_node_free(node));
4627 if (graph->n == 1)
4628 return node;
4630 if (update_edges(ctx, graph) < 0)
4631 return isl_schedule_node_free(node);
4633 if (graph->n_edge == 0)
4634 return node;
4636 if (detect_sccs(ctx, graph) < 0)
4637 return isl_schedule_node_free(node);
4639 next_band(graph);
4640 if (graph->scc < graph->n) {
4641 if (!initialized && compute_maxvar(graph) < 0)
4642 return isl_schedule_node_free(node);
4643 return carry_dependences(node, graph);
4646 filters = extract_sccs(ctx, graph);
4647 node = isl_schedule_node_insert_sequence(node, filters);
4649 return node;
4652 /* Are there any (non-empty) (conditional) validity edges in the graph?
4654 static int has_validity_edges(struct isl_sched_graph *graph)
4656 int i;
4658 for (i = 0; i < graph->n_edge; ++i) {
4659 int empty;
4661 empty = isl_map_plain_is_empty(graph->edge[i].map);
4662 if (empty < 0)
4663 return -1;
4664 if (empty)
4665 continue;
4666 if (is_any_validity(&graph->edge[i]))
4667 return 1;
4670 return 0;
4673 /* Should we apply a Feautrier step?
4674 * That is, did the user request the Feautrier algorithm and are
4675 * there any validity dependences (left)?
4677 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4679 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4680 return 0;
4682 return has_validity_edges(graph);
4685 /* Compute a schedule for a connected dependence graph using Feautrier's
4686 * multi-dimensional scheduling algorithm and return the updated schedule node.
4688 * The original algorithm is described in [1].
4689 * The main idea is to minimize the number of scheduling dimensions, by
4690 * trying to satisfy as many dependences as possible per scheduling dimension.
4692 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4693 * Problem, Part II: Multi-Dimensional Time.
4694 * In Intl. Journal of Parallel Programming, 1992.
4696 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4697 isl_schedule_node *node, struct isl_sched_graph *graph)
4699 return carry_feautrier(node, graph);
4702 /* Turn off the "local" bit on all (condition) edges.
4704 static void clear_local_edges(struct isl_sched_graph *graph)
4706 int i;
4708 for (i = 0; i < graph->n_edge; ++i)
4709 if (is_condition(&graph->edge[i]))
4710 clear_local(&graph->edge[i]);
4713 /* Does "graph" have both condition and conditional validity edges?
4715 static int need_condition_check(struct isl_sched_graph *graph)
4717 int i;
4718 int any_condition = 0;
4719 int any_conditional_validity = 0;
4721 for (i = 0; i < graph->n_edge; ++i) {
4722 if (is_condition(&graph->edge[i]))
4723 any_condition = 1;
4724 if (is_conditional_validity(&graph->edge[i]))
4725 any_conditional_validity = 1;
4728 return any_condition && any_conditional_validity;
4731 /* Does "graph" contain any coincidence edge?
4733 static int has_any_coincidence(struct isl_sched_graph *graph)
4735 int i;
4737 for (i = 0; i < graph->n_edge; ++i)
4738 if (is_coincidence(&graph->edge[i]))
4739 return 1;
4741 return 0;
4744 /* Extract the final schedule row as a map with the iteration domain
4745 * of "node" as domain.
4747 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4749 isl_multi_aff *ma;
4750 int row;
4752 row = isl_mat_rows(node->sched) - 1;
4753 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
4754 return isl_map_from_multi_aff(ma);
4757 /* Is the conditional validity dependence in the edge with index "edge_index"
4758 * violated by the latest (i.e., final) row of the schedule?
4759 * That is, is i scheduled after j
4760 * for any conditional validity dependence i -> j?
4762 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4764 isl_map *src_sched, *dst_sched, *map;
4765 struct isl_sched_edge *edge = &graph->edge[edge_index];
4766 int empty;
4768 src_sched = final_row(edge->src);
4769 dst_sched = final_row(edge->dst);
4770 map = isl_map_copy(edge->map);
4771 map = isl_map_apply_domain(map, src_sched);
4772 map = isl_map_apply_range(map, dst_sched);
4773 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4774 empty = isl_map_is_empty(map);
4775 isl_map_free(map);
4777 if (empty < 0)
4778 return -1;
4780 return !empty;
4783 /* Does "graph" have any satisfied condition edges that
4784 * are adjacent to the conditional validity constraint with
4785 * domain "conditional_source" and range "conditional_sink"?
4787 * A satisfied condition is one that is not local.
4788 * If a condition was forced to be local already (i.e., marked as local)
4789 * then there is no need to check if it is in fact local.
4791 * Additionally, mark all adjacent condition edges found as local.
4793 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4794 __isl_keep isl_union_set *conditional_source,
4795 __isl_keep isl_union_set *conditional_sink)
4797 int i;
4798 int any = 0;
4800 for (i = 0; i < graph->n_edge; ++i) {
4801 int adjacent, local;
4802 isl_union_map *condition;
4804 if (!is_condition(&graph->edge[i]))
4805 continue;
4806 if (is_local(&graph->edge[i]))
4807 continue;
4809 condition = graph->edge[i].tagged_condition;
4810 adjacent = domain_intersects(condition, conditional_sink);
4811 if (adjacent >= 0 && !adjacent)
4812 adjacent = range_intersects(condition,
4813 conditional_source);
4814 if (adjacent < 0)
4815 return -1;
4816 if (!adjacent)
4817 continue;
4819 set_local(&graph->edge[i]);
4821 local = is_condition_false(&graph->edge[i]);
4822 if (local < 0)
4823 return -1;
4824 if (!local)
4825 any = 1;
4828 return any;
4831 /* Are there any violated conditional validity dependences with
4832 * adjacent condition dependences that are not local with respect
4833 * to the current schedule?
4834 * That is, is the conditional validity constraint violated?
4836 * Additionally, mark all those adjacent condition dependences as local.
4837 * We also mark those adjacent condition dependences that were not marked
4838 * as local before, but just happened to be local already. This ensures
4839 * that they remain local if the schedule is recomputed.
4841 * We first collect domain and range of all violated conditional validity
4842 * dependences and then check if there are any adjacent non-local
4843 * condition dependences.
4845 static int has_violated_conditional_constraint(isl_ctx *ctx,
4846 struct isl_sched_graph *graph)
4848 int i;
4849 int any = 0;
4850 isl_union_set *source, *sink;
4852 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4853 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4854 for (i = 0; i < graph->n_edge; ++i) {
4855 isl_union_set *uset;
4856 isl_union_map *umap;
4857 int violated;
4859 if (!is_conditional_validity(&graph->edge[i]))
4860 continue;
4862 violated = is_violated(graph, i);
4863 if (violated < 0)
4864 goto error;
4865 if (!violated)
4866 continue;
4868 any = 1;
4870 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4871 uset = isl_union_map_domain(umap);
4872 source = isl_union_set_union(source, uset);
4873 source = isl_union_set_coalesce(source);
4875 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4876 uset = isl_union_map_range(umap);
4877 sink = isl_union_set_union(sink, uset);
4878 sink = isl_union_set_coalesce(sink);
4881 if (any)
4882 any = has_adjacent_true_conditions(graph, source, sink);
4884 isl_union_set_free(source);
4885 isl_union_set_free(sink);
4886 return any;
4887 error:
4888 isl_union_set_free(source);
4889 isl_union_set_free(sink);
4890 return -1;
4893 /* Examine the current band (the rows between graph->band_start and
4894 * graph->n_total_row), deciding whether to drop it or add it to "node"
4895 * and then continue with the computation of the next band, if any.
4896 * If "initialized" is set, then it may be assumed that compute_maxvar
4897 * has been called on the current band. Otherwise, call
4898 * compute_maxvar if and before carry_dependences gets called.
4900 * The caller keeps looking for a new row as long as
4901 * graph->n_row < graph->maxvar. If the latest attempt to find
4902 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4903 * then we either
4904 * - split between SCCs and start over (assuming we found an interesting
4905 * pair of SCCs between which to split)
4906 * - continue with the next band (assuming the current band has at least
4907 * one row)
4908 * - if there is more than one SCC left, then split along all SCCs
4909 * - if outer coincidence needs to be enforced, then try to carry as many
4910 * validity or coincidence dependences as possible and
4911 * continue with the next band
4912 * - try to carry as many validity dependences as possible and
4913 * continue with the next band
4914 * In each case, we first insert a band node in the schedule tree
4915 * if any rows have been computed.
4917 * If the caller managed to complete the schedule, we insert a band node
4918 * (if any schedule rows were computed) and we finish off by topologically
4919 * sorting the statements based on the remaining dependences.
4921 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4922 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4923 int initialized)
4925 int insert;
4927 if (!node)
4928 return NULL;
4930 if (graph->n_row < graph->maxvar) {
4931 isl_ctx *ctx;
4932 int empty = graph->n_total_row == graph->band_start;
4934 ctx = isl_schedule_node_get_ctx(node);
4935 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4936 return compute_next_band(node, graph, 1);
4937 if (graph->src_scc >= 0)
4938 return compute_split_schedule(node, graph);
4939 if (!empty)
4940 return compute_next_band(node, graph, 1);
4941 if (graph->scc > 1)
4942 return compute_component_schedule(node, graph, 1);
4943 if (!initialized && compute_maxvar(graph) < 0)
4944 return isl_schedule_node_free(node);
4945 if (isl_options_get_schedule_outer_coincidence(ctx))
4946 return carry_coincidence(node, graph);
4947 return carry_dependences(node, graph);
4950 insert = graph->n_total_row > graph->band_start;
4951 if (insert) {
4952 node = insert_current_band(node, graph, 1);
4953 node = isl_schedule_node_child(node, 0);
4955 node = sort_statements(node, graph, initialized);
4956 if (insert)
4957 node = isl_schedule_node_parent(node);
4959 return node;
4962 /* Construct a band of schedule rows for a connected dependence graph.
4963 * The caller is responsible for determining the strongly connected
4964 * components and calling compute_maxvar first.
4966 * We try to find a sequence of as many schedule rows as possible that result
4967 * in non-negative dependence distances (independent of the previous rows
4968 * in the sequence, i.e., such that the sequence is tilable), with as
4969 * many of the initial rows as possible satisfying the coincidence constraints.
4970 * The computation stops if we can't find any more rows or if we have found
4971 * all the rows we wanted to find.
4973 * If ctx->opt->schedule_outer_coincidence is set, then we force the
4974 * outermost dimension to satisfy the coincidence constraints. If this
4975 * turns out to be impossible, we fall back on the general scheme above
4976 * and try to carry as many dependences as possible.
4978 * If "graph" contains both condition and conditional validity dependences,
4979 * then we need to check that that the conditional schedule constraint
4980 * is satisfied, i.e., there are no violated conditional validity dependences
4981 * that are adjacent to any non-local condition dependences.
4982 * If there are, then we mark all those adjacent condition dependences
4983 * as local and recompute the current band. Those dependences that
4984 * are marked local will then be forced to be local.
4985 * The initial computation is performed with no dependences marked as local.
4986 * If we are lucky, then there will be no violated conditional validity
4987 * dependences adjacent to any non-local condition dependences.
4988 * Otherwise, we mark some additional condition dependences as local and
4989 * recompute. We continue this process until there are no violations left or
4990 * until we are no longer able to compute a schedule.
4991 * Since there are only a finite number of dependences,
4992 * there will only be a finite number of iterations.
4994 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
4995 struct isl_sched_graph *graph)
4997 int has_coincidence;
4998 int use_coincidence;
4999 int force_coincidence = 0;
5000 int check_conditional;
5002 if (sort_sccs(graph) < 0)
5003 return isl_stat_error;
5005 clear_local_edges(graph);
5006 check_conditional = need_condition_check(graph);
5007 has_coincidence = has_any_coincidence(graph);
5009 if (ctx->opt->schedule_outer_coincidence)
5010 force_coincidence = 1;
5012 use_coincidence = has_coincidence;
5013 while (graph->n_row < graph->maxvar) {
5014 isl_vec *sol;
5015 int violated;
5016 int coincident;
5018 graph->src_scc = -1;
5019 graph->dst_scc = -1;
5021 if (setup_lp(ctx, graph, use_coincidence) < 0)
5022 return isl_stat_error;
5023 sol = solve_lp(ctx, graph);
5024 if (!sol)
5025 return isl_stat_error;
5026 if (sol->size == 0) {
5027 int empty = graph->n_total_row == graph->band_start;
5029 isl_vec_free(sol);
5030 if (use_coincidence && (!force_coincidence || !empty)) {
5031 use_coincidence = 0;
5032 continue;
5034 return isl_stat_ok;
5036 coincident = !has_coincidence || use_coincidence;
5037 if (update_schedule(graph, sol, coincident) < 0)
5038 return isl_stat_error;
5040 if (!check_conditional)
5041 continue;
5042 violated = has_violated_conditional_constraint(ctx, graph);
5043 if (violated < 0)
5044 return isl_stat_error;
5045 if (!violated)
5046 continue;
5047 if (reset_band(graph) < 0)
5048 return isl_stat_error;
5049 use_coincidence = has_coincidence;
5052 return isl_stat_ok;
5055 /* Compute a schedule for a connected dependence graph by considering
5056 * the graph as a whole and return the updated schedule node.
5058 * The actual schedule rows of the current band are computed by
5059 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5060 * care of integrating the band into "node" and continuing
5061 * the computation.
5063 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5064 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5066 isl_ctx *ctx;
5068 if (!node)
5069 return NULL;
5071 ctx = isl_schedule_node_get_ctx(node);
5072 if (compute_schedule_wcc_band(ctx, graph) < 0)
5073 return isl_schedule_node_free(node);
5075 return compute_schedule_finish_band(node, graph, 1);
5078 /* Clustering information used by compute_schedule_wcc_clustering.
5080 * "n" is the number of SCCs in the original dependence graph
5081 * "scc" is an array of "n" elements, each representing an SCC
5082 * of the original dependence graph. All entries in the same cluster
5083 * have the same number of schedule rows.
5084 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5085 * where each cluster is represented by the index of the first SCC
5086 * in the cluster. Initially, each SCC belongs to a cluster containing
5087 * only that SCC.
5089 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5090 * track of which SCCs need to be merged.
5092 * "cluster" contains the merged clusters of SCCs after the clustering
5093 * has completed.
5095 * "scc_node" is a temporary data structure used inside copy_partial.
5096 * For each SCC, it keeps track of the number of nodes in the SCC
5097 * that have already been copied.
5099 struct isl_clustering {
5100 int n;
5101 struct isl_sched_graph *scc;
5102 struct isl_sched_graph *cluster;
5103 int *scc_cluster;
5104 int *scc_node;
5105 int *scc_in_merge;
5108 /* Initialize the clustering data structure "c" from "graph".
5110 * In particular, allocate memory, extract the SCCs from "graph"
5111 * into c->scc, initialize scc_cluster and construct
5112 * a band of schedule rows for each SCC.
5113 * Within each SCC, there is only one SCC by definition.
5114 * Each SCC initially belongs to a cluster containing only that SCC.
5116 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5117 struct isl_sched_graph *graph)
5119 int i;
5121 c->n = graph->scc;
5122 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5123 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5124 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5125 c->scc_node = isl_calloc_array(ctx, int, c->n);
5126 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5127 if (!c->scc || !c->cluster ||
5128 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5129 return isl_stat_error;
5131 for (i = 0; i < c->n; ++i) {
5132 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5133 &edge_scc_exactly, i, &c->scc[i]) < 0)
5134 return isl_stat_error;
5135 c->scc[i].scc = 1;
5136 if (compute_maxvar(&c->scc[i]) < 0)
5137 return isl_stat_error;
5138 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5139 return isl_stat_error;
5140 c->scc_cluster[i] = i;
5143 return isl_stat_ok;
5146 /* Free all memory allocated for "c".
5148 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5150 int i;
5152 if (c->scc)
5153 for (i = 0; i < c->n; ++i)
5154 graph_free(ctx, &c->scc[i]);
5155 free(c->scc);
5156 if (c->cluster)
5157 for (i = 0; i < c->n; ++i)
5158 graph_free(ctx, &c->cluster[i]);
5159 free(c->cluster);
5160 free(c->scc_cluster);
5161 free(c->scc_node);
5162 free(c->scc_in_merge);
5165 /* Should we refrain from merging the cluster in "graph" with
5166 * any other cluster?
5167 * In particular, is its current schedule band empty and incomplete.
5169 static int bad_cluster(struct isl_sched_graph *graph)
5171 return graph->n_row < graph->maxvar &&
5172 graph->n_total_row == graph->band_start;
5175 /* Is "edge" a proximity edge with a non-empty dependence relation?
5177 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5179 if (!is_proximity(edge))
5180 return isl_bool_false;
5181 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5184 /* Return the index of an edge in "graph" that can be used to merge
5185 * two clusters in "c".
5186 * Return graph->n_edge if no such edge can be found.
5187 * Return -1 on error.
5189 * In particular, return a proximity edge between two clusters
5190 * that is not marked "no_merge" and such that neither of the
5191 * two clusters has an incomplete, empty band.
5193 * If there are multiple such edges, then try and find the most
5194 * appropriate edge to use for merging. In particular, pick the edge
5195 * with the greatest weight. If there are multiple of those,
5196 * then pick one with the shortest distance between
5197 * the two cluster representatives.
5199 static int find_proximity(struct isl_sched_graph *graph,
5200 struct isl_clustering *c)
5202 int i, best = graph->n_edge, best_dist, best_weight;
5204 for (i = 0; i < graph->n_edge; ++i) {
5205 struct isl_sched_edge *edge = &graph->edge[i];
5206 int dist, weight;
5207 isl_bool prox;
5209 prox = is_non_empty_proximity(edge);
5210 if (prox < 0)
5211 return -1;
5212 if (!prox)
5213 continue;
5214 if (edge->no_merge)
5215 continue;
5216 if (bad_cluster(&c->scc[edge->src->scc]) ||
5217 bad_cluster(&c->scc[edge->dst->scc]))
5218 continue;
5219 dist = c->scc_cluster[edge->dst->scc] -
5220 c->scc_cluster[edge->src->scc];
5221 if (dist == 0)
5222 continue;
5223 weight = edge->weight;
5224 if (best < graph->n_edge) {
5225 if (best_weight > weight)
5226 continue;
5227 if (best_weight == weight && best_dist <= dist)
5228 continue;
5230 best = i;
5231 best_dist = dist;
5232 best_weight = weight;
5235 return best;
5238 /* Internal data structure used in mark_merge_sccs.
5240 * "graph" is the dependence graph in which a strongly connected
5241 * component is constructed.
5242 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5243 * "src" and "dst" are the indices of the nodes that are being merged.
5245 struct isl_mark_merge_sccs_data {
5246 struct isl_sched_graph *graph;
5247 int *scc_cluster;
5248 int src;
5249 int dst;
5252 /* Check whether the cluster containing node "i" depends on the cluster
5253 * containing node "j". If "i" and "j" belong to the same cluster,
5254 * then they are taken to depend on each other to ensure that
5255 * the resulting strongly connected component consists of complete
5256 * clusters. Furthermore, if "i" and "j" are the two nodes that
5257 * are being merged, then they are taken to depend on each other as well.
5258 * Otherwise, check if there is a (conditional) validity dependence
5259 * from node[j] to node[i], forcing node[i] to follow node[j].
5261 static isl_bool cluster_follows(int i, int j, void *user)
5263 struct isl_mark_merge_sccs_data *data = user;
5264 struct isl_sched_graph *graph = data->graph;
5265 int *scc_cluster = data->scc_cluster;
5267 if (data->src == i && data->dst == j)
5268 return isl_bool_true;
5269 if (data->src == j && data->dst == i)
5270 return isl_bool_true;
5271 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5272 return isl_bool_true;
5274 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5277 /* Mark all SCCs that belong to either of the two clusters in "c"
5278 * connected by the edge in "graph" with index "edge", or to any
5279 * of the intermediate clusters.
5280 * The marking is recorded in c->scc_in_merge.
5282 * The given edge has been selected for merging two clusters,
5283 * meaning that there is at least a proximity edge between the two nodes.
5284 * However, there may also be (indirect) validity dependences
5285 * between the two nodes. When merging the two clusters, all clusters
5286 * containing one or more of the intermediate nodes along the
5287 * indirect validity dependences need to be merged in as well.
5289 * First collect all such nodes by computing the strongly connected
5290 * component (SCC) containing the two nodes connected by the edge, where
5291 * the two nodes are considered to depend on each other to make
5292 * sure they end up in the same SCC. Similarly, each node is considered
5293 * to depend on every other node in the same cluster to ensure
5294 * that the SCC consists of complete clusters.
5296 * Then the original SCCs that contain any of these nodes are marked
5297 * in c->scc_in_merge.
5299 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5300 int edge, struct isl_clustering *c)
5302 struct isl_mark_merge_sccs_data data;
5303 struct isl_tarjan_graph *g;
5304 int i;
5306 for (i = 0; i < c->n; ++i)
5307 c->scc_in_merge[i] = 0;
5309 data.graph = graph;
5310 data.scc_cluster = c->scc_cluster;
5311 data.src = graph->edge[edge].src - graph->node;
5312 data.dst = graph->edge[edge].dst - graph->node;
5314 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5315 &cluster_follows, &data);
5316 if (!g)
5317 goto error;
5319 i = g->op;
5320 if (i < 3)
5321 isl_die(ctx, isl_error_internal,
5322 "expecting at least two nodes in component",
5323 goto error);
5324 if (g->order[--i] != -1)
5325 isl_die(ctx, isl_error_internal,
5326 "expecting end of component marker", goto error);
5328 for (--i; i >= 0 && g->order[i] != -1; --i) {
5329 int scc = graph->node[g->order[i]].scc;
5330 c->scc_in_merge[scc] = 1;
5333 isl_tarjan_graph_free(g);
5334 return isl_stat_ok;
5335 error:
5336 isl_tarjan_graph_free(g);
5337 return isl_stat_error;
5340 /* Construct the identifier "cluster_i".
5342 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5344 char name[40];
5346 snprintf(name, sizeof(name), "cluster_%d", i);
5347 return isl_id_alloc(ctx, name, NULL);
5350 /* Construct the space of the cluster with index "i" containing
5351 * the strongly connected component "scc".
5353 * In particular, construct a space called cluster_i with dimension equal
5354 * to the number of schedule rows in the current band of "scc".
5356 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5358 int nvar;
5359 isl_space *space;
5360 isl_id *id;
5362 nvar = scc->n_total_row - scc->band_start;
5363 space = isl_space_copy(scc->node[0].space);
5364 space = isl_space_params(space);
5365 space = isl_space_set_from_params(space);
5366 space = isl_space_add_dims(space, isl_dim_set, nvar);
5367 id = cluster_id(isl_space_get_ctx(space), i);
5368 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5370 return space;
5373 /* Collect the domain of the graph for merging clusters.
5375 * In particular, for each cluster with first SCC "i", construct
5376 * a set in the space called cluster_i with dimension equal
5377 * to the number of schedule rows in the current band of the cluster.
5379 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5380 struct isl_sched_graph *graph, struct isl_clustering *c)
5382 int i;
5383 isl_space *space;
5384 isl_union_set *domain;
5386 space = isl_space_params_alloc(ctx, 0);
5387 domain = isl_union_set_empty(space);
5389 for (i = 0; i < graph->scc; ++i) {
5390 isl_space *space;
5392 if (!c->scc_in_merge[i])
5393 continue;
5394 if (c->scc_cluster[i] != i)
5395 continue;
5396 space = cluster_space(&c->scc[i], i);
5397 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5400 return domain;
5403 /* Construct a map from the original instances to the corresponding
5404 * cluster instance in the current bands of the clusters in "c".
5406 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5407 struct isl_sched_graph *graph, struct isl_clustering *c)
5409 int i, j;
5410 isl_space *space;
5411 isl_union_map *cluster_map;
5413 space = isl_space_params_alloc(ctx, 0);
5414 cluster_map = isl_union_map_empty(space);
5415 for (i = 0; i < graph->scc; ++i) {
5416 int start, n;
5417 isl_id *id;
5419 if (!c->scc_in_merge[i])
5420 continue;
5422 id = cluster_id(ctx, c->scc_cluster[i]);
5423 start = c->scc[i].band_start;
5424 n = c->scc[i].n_total_row - start;
5425 for (j = 0; j < c->scc[i].n; ++j) {
5426 isl_multi_aff *ma;
5427 isl_map *map;
5428 struct isl_sched_node *node = &c->scc[i].node[j];
5430 ma = node_extract_partial_schedule_multi_aff(node,
5431 start, n);
5432 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5433 isl_id_copy(id));
5434 map = isl_map_from_multi_aff(ma);
5435 cluster_map = isl_union_map_add_map(cluster_map, map);
5437 isl_id_free(id);
5440 return cluster_map;
5443 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5444 * that are not isl_edge_condition or isl_edge_conditional_validity.
5446 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5447 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5448 __isl_take isl_schedule_constraints *sc)
5450 enum isl_edge_type t;
5452 if (!sc)
5453 return NULL;
5455 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5456 if (t == isl_edge_condition ||
5457 t == isl_edge_conditional_validity)
5458 continue;
5459 if (!is_type(edge, t))
5460 continue;
5461 sc = isl_schedule_constraints_add(sc, t,
5462 isl_union_map_copy(umap));
5465 return sc;
5468 /* Add schedule constraints of types isl_edge_condition and
5469 * isl_edge_conditional_validity to "sc" by applying "umap" to
5470 * the domains of the wrapped relations in domain and range
5471 * of the corresponding tagged constraints of "edge".
5473 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5474 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5475 __isl_take isl_schedule_constraints *sc)
5477 enum isl_edge_type t;
5478 isl_union_map *tagged;
5480 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5481 if (!is_type(edge, t))
5482 continue;
5483 if (t == isl_edge_condition)
5484 tagged = isl_union_map_copy(edge->tagged_condition);
5485 else
5486 tagged = isl_union_map_copy(edge->tagged_validity);
5487 tagged = isl_union_map_zip(tagged);
5488 tagged = isl_union_map_apply_domain(tagged,
5489 isl_union_map_copy(umap));
5490 tagged = isl_union_map_zip(tagged);
5491 sc = isl_schedule_constraints_add(sc, t, tagged);
5492 if (!sc)
5493 return NULL;
5496 return sc;
5499 /* Given a mapping "cluster_map" from the original instances to
5500 * the cluster instances, add schedule constraints on the clusters
5501 * to "sc" corresponding to the original constraints represented by "edge".
5503 * For non-tagged dependence constraints, the cluster constraints
5504 * are obtained by applying "cluster_map" to the edge->map.
5506 * For tagged dependence constraints, "cluster_map" needs to be applied
5507 * to the domains of the wrapped relations in domain and range
5508 * of the tagged dependence constraints. Pick out the mappings
5509 * from these domains from "cluster_map" and construct their product.
5510 * This mapping can then be applied to the pair of domains.
5512 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5513 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5514 __isl_take isl_schedule_constraints *sc)
5516 isl_union_map *umap;
5517 isl_space *space;
5518 isl_union_set *uset;
5519 isl_union_map *umap1, *umap2;
5521 if (!sc)
5522 return NULL;
5524 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5525 umap = isl_union_map_apply_domain(umap,
5526 isl_union_map_copy(cluster_map));
5527 umap = isl_union_map_apply_range(umap,
5528 isl_union_map_copy(cluster_map));
5529 sc = add_non_conditional_constraints(edge, umap, sc);
5530 isl_union_map_free(umap);
5532 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5533 return sc;
5535 space = isl_space_domain(isl_map_get_space(edge->map));
5536 uset = isl_union_set_from_set(isl_set_universe(space));
5537 umap1 = isl_union_map_copy(cluster_map);
5538 umap1 = isl_union_map_intersect_domain(umap1, uset);
5539 space = isl_space_range(isl_map_get_space(edge->map));
5540 uset = isl_union_set_from_set(isl_set_universe(space));
5541 umap2 = isl_union_map_copy(cluster_map);
5542 umap2 = isl_union_map_intersect_domain(umap2, uset);
5543 umap = isl_union_map_product(umap1, umap2);
5545 sc = add_conditional_constraints(edge, umap, sc);
5547 isl_union_map_free(umap);
5548 return sc;
5551 /* Given a mapping "cluster_map" from the original instances to
5552 * the cluster instances, add schedule constraints on the clusters
5553 * to "sc" corresponding to all edges in "graph" between nodes that
5554 * belong to SCCs that are marked for merging in "scc_in_merge".
5556 static __isl_give isl_schedule_constraints *collect_constraints(
5557 struct isl_sched_graph *graph, int *scc_in_merge,
5558 __isl_keep isl_union_map *cluster_map,
5559 __isl_take isl_schedule_constraints *sc)
5561 int i;
5563 for (i = 0; i < graph->n_edge; ++i) {
5564 struct isl_sched_edge *edge = &graph->edge[i];
5566 if (!scc_in_merge[edge->src->scc])
5567 continue;
5568 if (!scc_in_merge[edge->dst->scc])
5569 continue;
5570 sc = collect_edge_constraints(edge, cluster_map, sc);
5573 return sc;
5576 /* Construct a dependence graph for scheduling clusters with respect
5577 * to each other and store the result in "merge_graph".
5578 * In particular, the nodes of the graph correspond to the schedule
5579 * dimensions of the current bands of those clusters that have been
5580 * marked for merging in "c".
5582 * First construct an isl_schedule_constraints object for this domain
5583 * by transforming the edges in "graph" to the domain.
5584 * Then initialize a dependence graph for scheduling from these
5585 * constraints.
5587 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5588 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5590 isl_union_set *domain;
5591 isl_union_map *cluster_map;
5592 isl_schedule_constraints *sc;
5593 isl_stat r;
5595 domain = collect_domain(ctx, graph, c);
5596 sc = isl_schedule_constraints_on_domain(domain);
5597 if (!sc)
5598 return isl_stat_error;
5599 cluster_map = collect_cluster_map(ctx, graph, c);
5600 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5601 isl_union_map_free(cluster_map);
5603 r = graph_init(merge_graph, sc);
5605 isl_schedule_constraints_free(sc);
5607 return r;
5610 /* Compute the maximal number of remaining schedule rows that still need
5611 * to be computed for the nodes that belong to clusters with the maximal
5612 * dimension for the current band (i.e., the band that is to be merged).
5613 * Only clusters that are about to be merged are considered.
5614 * "maxvar" is the maximal dimension for the current band.
5615 * "c" contains information about the clusters.
5617 * Return the maximal number of remaining schedule rows or -1 on error.
5619 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5621 int i, j;
5622 int max_slack;
5624 max_slack = 0;
5625 for (i = 0; i < c->n; ++i) {
5626 int nvar;
5627 struct isl_sched_graph *scc;
5629 if (!c->scc_in_merge[i])
5630 continue;
5631 scc = &c->scc[i];
5632 nvar = scc->n_total_row - scc->band_start;
5633 if (nvar != maxvar)
5634 continue;
5635 for (j = 0; j < scc->n; ++j) {
5636 struct isl_sched_node *node = &scc->node[j];
5637 int slack;
5639 if (node_update_vmap(node) < 0)
5640 return -1;
5641 slack = node->nvar - node->rank;
5642 if (slack > max_slack)
5643 max_slack = slack;
5647 return max_slack;
5650 /* If there are any clusters where the dimension of the current band
5651 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5652 * if there are any nodes in such a cluster where the number
5653 * of remaining schedule rows that still need to be computed
5654 * is greater than "max_slack", then return the smallest current band
5655 * dimension of all these clusters. Otherwise return the original value
5656 * of "maxvar". Return -1 in case of any error.
5657 * Only clusters that are about to be merged are considered.
5658 * "c" contains information about the clusters.
5660 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5661 struct isl_clustering *c)
5663 int i, j;
5665 for (i = 0; i < c->n; ++i) {
5666 int nvar;
5667 struct isl_sched_graph *scc;
5669 if (!c->scc_in_merge[i])
5670 continue;
5671 scc = &c->scc[i];
5672 nvar = scc->n_total_row - scc->band_start;
5673 if (nvar >= maxvar)
5674 continue;
5675 for (j = 0; j < scc->n; ++j) {
5676 struct isl_sched_node *node = &scc->node[j];
5677 int slack;
5679 if (node_update_vmap(node) < 0)
5680 return -1;
5681 slack = node->nvar - node->rank;
5682 if (slack > max_slack) {
5683 maxvar = nvar;
5684 break;
5689 return maxvar;
5692 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5693 * that still need to be computed. In particular, if there is a node
5694 * in a cluster where the dimension of the current band is smaller
5695 * than merge_graph->maxvar, but the number of remaining schedule rows
5696 * is greater than that of any node in a cluster with the maximal
5697 * dimension for the current band (i.e., merge_graph->maxvar),
5698 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5699 * of those clusters. Without this adjustment, the total number of
5700 * schedule dimensions would be increased, resulting in a skewed view
5701 * of the number of coincident dimensions.
5702 * "c" contains information about the clusters.
5704 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5705 * then there is no point in attempting any merge since it will be rejected
5706 * anyway. Set merge_graph->maxvar to zero in such cases.
5708 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5709 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5711 int max_slack, maxvar;
5713 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5714 if (max_slack < 0)
5715 return isl_stat_error;
5716 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5717 if (maxvar < 0)
5718 return isl_stat_error;
5720 if (maxvar < merge_graph->maxvar) {
5721 if (isl_options_get_schedule_maximize_band_depth(ctx))
5722 merge_graph->maxvar = 0;
5723 else
5724 merge_graph->maxvar = maxvar;
5727 return isl_stat_ok;
5730 /* Return the number of coincident dimensions in the current band of "graph",
5731 * where the nodes of "graph" are assumed to be scheduled by a single band.
5733 static int get_n_coincident(struct isl_sched_graph *graph)
5735 int i;
5737 for (i = graph->band_start; i < graph->n_total_row; ++i)
5738 if (!graph->node[0].coincident[i])
5739 break;
5741 return i - graph->band_start;
5744 /* Should the clusters be merged based on the cluster schedule
5745 * in the current (and only) band of "merge_graph", given that
5746 * coincidence should be maximized?
5748 * If the number of coincident schedule dimensions in the merged band
5749 * would be less than the maximal number of coincident schedule dimensions
5750 * in any of the merged clusters, then the clusters should not be merged.
5752 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5753 struct isl_sched_graph *merge_graph)
5755 int i;
5756 int n_coincident;
5757 int max_coincident;
5759 max_coincident = 0;
5760 for (i = 0; i < c->n; ++i) {
5761 if (!c->scc_in_merge[i])
5762 continue;
5763 n_coincident = get_n_coincident(&c->scc[i]);
5764 if (n_coincident > max_coincident)
5765 max_coincident = n_coincident;
5768 n_coincident = get_n_coincident(merge_graph);
5770 return n_coincident >= max_coincident;
5773 /* Return the transformation on "node" expressed by the current (and only)
5774 * band of "merge_graph" applied to the clusters in "c".
5776 * First find the representation of "node" in its SCC in "c" and
5777 * extract the transformation expressed by the current band.
5778 * Then extract the transformation applied by "merge_graph"
5779 * to the cluster to which this SCC belongs.
5780 * Combine the two to obtain the complete transformation on the node.
5782 * Note that the range of the first transformation is an anonymous space,
5783 * while the domain of the second is named "cluster_X". The range
5784 * of the former therefore needs to be adjusted before the two
5785 * can be combined.
5787 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5788 struct isl_sched_node *node, struct isl_clustering *c,
5789 struct isl_sched_graph *merge_graph)
5791 struct isl_sched_node *scc_node, *cluster_node;
5792 int start, n;
5793 isl_id *id;
5794 isl_space *space;
5795 isl_multi_aff *ma, *ma2;
5797 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5798 start = c->scc[node->scc].band_start;
5799 n = c->scc[node->scc].n_total_row - start;
5800 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5801 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5802 cluster_node = graph_find_node(ctx, merge_graph, space);
5803 if (space && !cluster_node)
5804 isl_die(ctx, isl_error_internal, "unable to find cluster",
5805 space = isl_space_free(space));
5806 id = isl_space_get_tuple_id(space, isl_dim_set);
5807 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5808 isl_space_free(space);
5809 n = merge_graph->n_total_row;
5810 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5811 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5813 return isl_map_from_multi_aff(ma);
5816 /* Give a set of distances "set", are they bounded by a small constant
5817 * in direction "pos"?
5818 * In practice, check if they are bounded by 2 by checking that there
5819 * are no elements with a value greater than or equal to 3 or
5820 * smaller than or equal to -3.
5822 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5824 isl_bool bounded;
5825 isl_set *test;
5827 if (!set)
5828 return isl_bool_error;
5830 test = isl_set_copy(set);
5831 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5832 bounded = isl_set_is_empty(test);
5833 isl_set_free(test);
5835 if (bounded < 0 || !bounded)
5836 return bounded;
5838 test = isl_set_copy(set);
5839 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5840 bounded = isl_set_is_empty(test);
5841 isl_set_free(test);
5843 return bounded;
5846 /* Does the set "set" have a fixed (but possible parametric) value
5847 * at dimension "pos"?
5849 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5851 int n;
5852 isl_bool single;
5854 if (!set)
5855 return isl_bool_error;
5856 set = isl_set_copy(set);
5857 n = isl_set_dim(set, isl_dim_set);
5858 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5859 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5860 single = isl_set_is_singleton(set);
5861 isl_set_free(set);
5863 return single;
5866 /* Does "map" have a fixed (but possible parametric) value
5867 * at dimension "pos" of either its domain or its range?
5869 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5871 isl_set *set;
5872 isl_bool single;
5874 set = isl_map_domain(isl_map_copy(map));
5875 single = has_single_value(set, pos);
5876 isl_set_free(set);
5878 if (single < 0 || single)
5879 return single;
5881 set = isl_map_range(isl_map_copy(map));
5882 single = has_single_value(set, pos);
5883 isl_set_free(set);
5885 return single;
5888 /* Does the edge "edge" from "graph" have bounded dependence distances
5889 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5891 * Extract the complete transformations of the source and destination
5892 * nodes of the edge, apply them to the edge constraints and
5893 * compute the differences. Finally, check if these differences are bounded
5894 * in each direction.
5896 * If the dimension of the band is greater than the number of
5897 * dimensions that can be expected to be optimized by the edge
5898 * (based on its weight), then also allow the differences to be unbounded
5899 * in the remaining dimensions, but only if either the source or
5900 * the destination has a fixed value in that direction.
5901 * This allows a statement that produces values that are used by
5902 * several instances of another statement to be merged with that
5903 * other statement.
5904 * However, merging such clusters will introduce an inherently
5905 * large proximity distance inside the merged cluster, meaning
5906 * that proximity distances will no longer be optimized in
5907 * subsequent merges. These merges are therefore only allowed
5908 * after all other possible merges have been tried.
5909 * The first time such a merge is encountered, the weight of the edge
5910 * is replaced by a negative weight. The second time (i.e., after
5911 * all merges over edges with a non-negative weight have been tried),
5912 * the merge is allowed.
5914 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5915 struct isl_sched_graph *graph, struct isl_clustering *c,
5916 struct isl_sched_graph *merge_graph)
5918 int i, n, n_slack;
5919 isl_bool bounded;
5920 isl_map *map, *t;
5921 isl_set *dist;
5923 map = isl_map_copy(edge->map);
5924 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5925 map = isl_map_apply_domain(map, t);
5926 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5927 map = isl_map_apply_range(map, t);
5928 dist = isl_map_deltas(isl_map_copy(map));
5930 bounded = isl_bool_true;
5931 n = isl_set_dim(dist, isl_dim_set);
5932 n_slack = n - edge->weight;
5933 if (edge->weight < 0)
5934 n_slack -= graph->max_weight + 1;
5935 for (i = 0; i < n; ++i) {
5936 isl_bool bounded_i, singular_i;
5938 bounded_i = distance_is_bounded(dist, i);
5939 if (bounded_i < 0)
5940 goto error;
5941 if (bounded_i)
5942 continue;
5943 if (edge->weight >= 0)
5944 bounded = isl_bool_false;
5945 n_slack--;
5946 if (n_slack < 0)
5947 break;
5948 singular_i = has_singular_src_or_dst(map, i);
5949 if (singular_i < 0)
5950 goto error;
5951 if (singular_i)
5952 continue;
5953 bounded = isl_bool_false;
5954 break;
5956 if (!bounded && i >= n && edge->weight >= 0)
5957 edge->weight -= graph->max_weight + 1;
5958 isl_map_free(map);
5959 isl_set_free(dist);
5961 return bounded;
5962 error:
5963 isl_map_free(map);
5964 isl_set_free(dist);
5965 return isl_bool_error;
5968 /* Should the clusters be merged based on the cluster schedule
5969 * in the current (and only) band of "merge_graph"?
5970 * "graph" is the original dependence graph, while "c" records
5971 * which SCCs are involved in the latest merge.
5973 * In particular, is there at least one proximity constraint
5974 * that is optimized by the merge?
5976 * A proximity constraint is considered to be optimized
5977 * if the dependence distances are small.
5979 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
5980 struct isl_sched_graph *graph, struct isl_clustering *c,
5981 struct isl_sched_graph *merge_graph)
5983 int i;
5985 for (i = 0; i < graph->n_edge; ++i) {
5986 struct isl_sched_edge *edge = &graph->edge[i];
5987 isl_bool bounded;
5989 if (!is_proximity(edge))
5990 continue;
5991 if (!c->scc_in_merge[edge->src->scc])
5992 continue;
5993 if (!c->scc_in_merge[edge->dst->scc])
5994 continue;
5995 if (c->scc_cluster[edge->dst->scc] ==
5996 c->scc_cluster[edge->src->scc])
5997 continue;
5998 bounded = has_bounded_distances(ctx, edge, graph, c,
5999 merge_graph);
6000 if (bounded < 0 || bounded)
6001 return bounded;
6004 return isl_bool_false;
6007 /* Should the clusters be merged based on the cluster schedule
6008 * in the current (and only) band of "merge_graph"?
6009 * "graph" is the original dependence graph, while "c" records
6010 * which SCCs are involved in the latest merge.
6012 * If the current band is empty, then the clusters should not be merged.
6014 * If the band depth should be maximized and the merge schedule
6015 * is incomplete (meaning that the dimension of some of the schedule
6016 * bands in the original schedule will be reduced), then the clusters
6017 * should not be merged.
6019 * If the schedule_maximize_coincidence option is set, then check that
6020 * the number of coincident schedule dimensions is not reduced.
6022 * Finally, only allow the merge if at least one proximity
6023 * constraint is optimized.
6025 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6026 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6028 if (merge_graph->n_total_row == merge_graph->band_start)
6029 return isl_bool_false;
6031 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6032 merge_graph->n_total_row < merge_graph->maxvar)
6033 return isl_bool_false;
6035 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6036 isl_bool ok;
6038 ok = ok_to_merge_coincident(c, merge_graph);
6039 if (ok < 0 || !ok)
6040 return ok;
6043 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6046 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6047 * of the schedule in "node" and return the result.
6049 * That is, essentially compute
6051 * T * N(first:first+n-1)
6053 * taking into account the constant term and the parameter coefficients
6054 * in "t_node".
6056 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6057 struct isl_sched_node *t_node, struct isl_sched_node *node,
6058 int first, int n)
6060 int i, j;
6061 isl_mat *t;
6062 int n_row, n_col, n_param, n_var;
6064 n_param = node->nparam;
6065 n_var = node->nvar;
6066 n_row = isl_mat_rows(t_node->sched);
6067 n_col = isl_mat_cols(node->sched);
6068 t = isl_mat_alloc(ctx, n_row, n_col);
6069 if (!t)
6070 return NULL;
6071 for (i = 0; i < n_row; ++i) {
6072 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6073 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6074 for (j = 0; j < n; ++j)
6075 isl_seq_addmul(t->row[i],
6076 t_node->sched->row[i][1 + n_param + j],
6077 node->sched->row[first + j],
6078 1 + n_param + n_var);
6080 return t;
6083 /* Apply the cluster schedule in "t_node" to the current band
6084 * schedule of the nodes in "graph".
6086 * In particular, replace the rows starting at band_start
6087 * by the result of applying the cluster schedule in "t_node"
6088 * to the original rows.
6090 * The coincidence of the schedule is determined by the coincidence
6091 * of the cluster schedule.
6093 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6094 struct isl_sched_node *t_node)
6096 int i, j;
6097 int n_new;
6098 int start, n;
6100 start = graph->band_start;
6101 n = graph->n_total_row - start;
6103 n_new = isl_mat_rows(t_node->sched);
6104 for (i = 0; i < graph->n; ++i) {
6105 struct isl_sched_node *node = &graph->node[i];
6106 isl_mat *t;
6108 t = node_transformation(ctx, t_node, node, start, n);
6109 node->sched = isl_mat_drop_rows(node->sched, start, n);
6110 node->sched = isl_mat_concat(node->sched, t);
6111 node->sched_map = isl_map_free(node->sched_map);
6112 if (!node->sched)
6113 return isl_stat_error;
6114 for (j = 0; j < n_new; ++j)
6115 node->coincident[start + j] = t_node->coincident[j];
6117 graph->n_total_row -= n;
6118 graph->n_row -= n;
6119 graph->n_total_row += n_new;
6120 graph->n_row += n_new;
6122 return isl_stat_ok;
6125 /* Merge the clusters marked for merging in "c" into a single
6126 * cluster using the cluster schedule in the current band of "merge_graph".
6127 * The representative SCC for the new cluster is the SCC with
6128 * the smallest index.
6130 * The current band schedule of each SCC in the new cluster is obtained
6131 * by applying the schedule of the corresponding original cluster
6132 * to the original band schedule.
6133 * All SCCs in the new cluster have the same number of schedule rows.
6135 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6136 struct isl_sched_graph *merge_graph)
6138 int i;
6139 int cluster = -1;
6140 isl_space *space;
6142 for (i = 0; i < c->n; ++i) {
6143 struct isl_sched_node *node;
6145 if (!c->scc_in_merge[i])
6146 continue;
6147 if (cluster < 0)
6148 cluster = i;
6149 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6150 if (!space)
6151 return isl_stat_error;
6152 node = graph_find_node(ctx, merge_graph, space);
6153 isl_space_free(space);
6154 if (!node)
6155 isl_die(ctx, isl_error_internal,
6156 "unable to find cluster",
6157 return isl_stat_error);
6158 if (transform(ctx, &c->scc[i], node) < 0)
6159 return isl_stat_error;
6160 c->scc_cluster[i] = cluster;
6163 return isl_stat_ok;
6166 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6167 * by scheduling the current cluster bands with respect to each other.
6169 * Construct a dependence graph with a space for each cluster and
6170 * with the coordinates of each space corresponding to the schedule
6171 * dimensions of the current band of that cluster.
6172 * Construct a cluster schedule in this cluster dependence graph and
6173 * apply it to the current cluster bands if it is applicable
6174 * according to ok_to_merge.
6176 * If the number of remaining schedule dimensions in a cluster
6177 * with a non-maximal current schedule dimension is greater than
6178 * the number of remaining schedule dimensions in clusters
6179 * with a maximal current schedule dimension, then restrict
6180 * the number of rows to be computed in the cluster schedule
6181 * to the minimal such non-maximal current schedule dimension.
6182 * Do this by adjusting merge_graph.maxvar.
6184 * Return isl_bool_true if the clusters have effectively been merged
6185 * into a single cluster.
6187 * Note that since the standard scheduling algorithm minimizes the maximal
6188 * distance over proximity constraints, the proximity constraints between
6189 * the merged clusters may not be optimized any further than what is
6190 * sufficient to bring the distances within the limits of the internal
6191 * proximity constraints inside the individual clusters.
6192 * It may therefore make sense to perform an additional translation step
6193 * to bring the clusters closer to each other, while maintaining
6194 * the linear part of the merging schedule found using the standard
6195 * scheduling algorithm.
6197 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6198 struct isl_clustering *c)
6200 struct isl_sched_graph merge_graph = { 0 };
6201 isl_bool merged;
6203 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6204 goto error;
6206 if (compute_maxvar(&merge_graph) < 0)
6207 goto error;
6208 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6209 goto error;
6210 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6211 goto error;
6212 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6213 if (merged && merge(ctx, c, &merge_graph) < 0)
6214 goto error;
6216 graph_free(ctx, &merge_graph);
6217 return merged;
6218 error:
6219 graph_free(ctx, &merge_graph);
6220 return isl_bool_error;
6223 /* Is there any edge marked "no_merge" between two SCCs that are
6224 * about to be merged (i.e., that are set in "scc_in_merge")?
6225 * "merge_edge" is the proximity edge along which the clusters of SCCs
6226 * are going to be merged.
6228 * If there is any edge between two SCCs with a negative weight,
6229 * while the weight of "merge_edge" is non-negative, then this
6230 * means that the edge was postponed. "merge_edge" should then
6231 * also be postponed since merging along the edge with negative weight should
6232 * be postponed until all edges with non-negative weight have been tried.
6233 * Replace the weight of "merge_edge" by a negative weight as well and
6234 * tell the caller not to attempt a merge.
6236 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6237 struct isl_sched_edge *merge_edge)
6239 int i;
6241 for (i = 0; i < graph->n_edge; ++i) {
6242 struct isl_sched_edge *edge = &graph->edge[i];
6244 if (!scc_in_merge[edge->src->scc])
6245 continue;
6246 if (!scc_in_merge[edge->dst->scc])
6247 continue;
6248 if (edge->no_merge)
6249 return 1;
6250 if (merge_edge->weight >= 0 && edge->weight < 0) {
6251 merge_edge->weight -= graph->max_weight + 1;
6252 return 1;
6256 return 0;
6259 /* Merge the two clusters in "c" connected by the edge in "graph"
6260 * with index "edge" into a single cluster.
6261 * If it turns out to be impossible to merge these two clusters,
6262 * then mark the edge as "no_merge" such that it will not be
6263 * considered again.
6265 * First mark all SCCs that need to be merged. This includes the SCCs
6266 * in the two clusters, but it may also include the SCCs
6267 * of intermediate clusters.
6268 * If there is already a no_merge edge between any pair of such SCCs,
6269 * then simply mark the current edge as no_merge as well.
6270 * Likewise, if any of those edges was postponed by has_bounded_distances,
6271 * then postpone the current edge as well.
6272 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6273 * if the clusters did not end up getting merged, unless the non-merge
6274 * is due to the fact that the edge was postponed. This postponement
6275 * can be recognized by a change in weight (from non-negative to negative).
6277 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6278 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6280 isl_bool merged;
6281 int edge_weight = graph->edge[edge].weight;
6283 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6284 return isl_stat_error;
6286 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6287 merged = isl_bool_false;
6288 else
6289 merged = try_merge(ctx, graph, c);
6290 if (merged < 0)
6291 return isl_stat_error;
6292 if (!merged && edge_weight == graph->edge[edge].weight)
6293 graph->edge[edge].no_merge = 1;
6295 return isl_stat_ok;
6298 /* Does "node" belong to the cluster identified by "cluster"?
6300 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6302 return node->cluster == cluster;
6305 /* Does "edge" connect two nodes belonging to the cluster
6306 * identified by "cluster"?
6308 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6310 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6313 /* Swap the schedule of "node1" and "node2".
6314 * Both nodes have been derived from the same node in a common parent graph.
6315 * Since the "coincident" field is shared with that node
6316 * in the parent graph, there is no need to also swap this field.
6318 static void swap_sched(struct isl_sched_node *node1,
6319 struct isl_sched_node *node2)
6321 isl_mat *sched;
6322 isl_map *sched_map;
6324 sched = node1->sched;
6325 node1->sched = node2->sched;
6326 node2->sched = sched;
6328 sched_map = node1->sched_map;
6329 node1->sched_map = node2->sched_map;
6330 node2->sched_map = sched_map;
6333 /* Copy the current band schedule from the SCCs that form the cluster
6334 * with index "pos" to the actual cluster at position "pos".
6335 * By construction, the index of the first SCC that belongs to the cluster
6336 * is also "pos".
6338 * The order of the nodes inside both the SCCs and the cluster
6339 * is assumed to be same as the order in the original "graph".
6341 * Since the SCC graphs will no longer be used after this function,
6342 * the schedules are actually swapped rather than copied.
6344 static isl_stat copy_partial(struct isl_sched_graph *graph,
6345 struct isl_clustering *c, int pos)
6347 int i, j;
6349 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6350 c->cluster[pos].n_row = c->scc[pos].n_row;
6351 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6352 j = 0;
6353 for (i = 0; i < graph->n; ++i) {
6354 int k;
6355 int s;
6357 if (graph->node[i].cluster != pos)
6358 continue;
6359 s = graph->node[i].scc;
6360 k = c->scc_node[s]++;
6361 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6362 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6363 c->cluster[pos].maxvar = c->scc[s].maxvar;
6364 ++j;
6367 return isl_stat_ok;
6370 /* Is there a (conditional) validity dependence from node[j] to node[i],
6371 * forcing node[i] to follow node[j] or do the nodes belong to the same
6372 * cluster?
6374 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6376 struct isl_sched_graph *graph = user;
6378 if (graph->node[i].cluster == graph->node[j].cluster)
6379 return isl_bool_true;
6380 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6383 /* Extract the merged clusters of SCCs in "graph", sort them, and
6384 * store them in c->clusters. Update c->scc_cluster accordingly.
6386 * First keep track of the cluster containing the SCC to which a node
6387 * belongs in the node itself.
6388 * Then extract the clusters into c->clusters, copying the current
6389 * band schedule from the SCCs that belong to the cluster.
6390 * Do this only once per cluster.
6392 * Finally, topologically sort the clusters and update c->scc_cluster
6393 * to match the new scc numbering. While the SCCs were originally
6394 * sorted already, some SCCs that depend on some other SCCs may
6395 * have been merged with SCCs that appear before these other SCCs.
6396 * A reordering may therefore be required.
6398 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6399 struct isl_clustering *c)
6401 int i;
6403 for (i = 0; i < graph->n; ++i)
6404 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6406 for (i = 0; i < graph->scc; ++i) {
6407 if (c->scc_cluster[i] != i)
6408 continue;
6409 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6410 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6411 return isl_stat_error;
6412 c->cluster[i].src_scc = -1;
6413 c->cluster[i].dst_scc = -1;
6414 if (copy_partial(graph, c, i) < 0)
6415 return isl_stat_error;
6418 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6419 return isl_stat_error;
6420 for (i = 0; i < graph->n; ++i)
6421 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6423 return isl_stat_ok;
6426 /* Compute weights on the proximity edges of "graph" that can
6427 * be used by find_proximity to find the most appropriate
6428 * proximity edge to use to merge two clusters in "c".
6429 * The weights are also used by has_bounded_distances to determine
6430 * whether the merge should be allowed.
6431 * Store the maximum of the computed weights in graph->max_weight.
6433 * The computed weight is a measure for the number of remaining schedule
6434 * dimensions that can still be completely aligned.
6435 * In particular, compute the number of equalities between
6436 * input dimensions and output dimensions in the proximity constraints.
6437 * The directions that are already handled by outer schedule bands
6438 * are projected out prior to determining this number.
6440 * Edges that will never be considered by find_proximity are ignored.
6442 static isl_stat compute_weights(struct isl_sched_graph *graph,
6443 struct isl_clustering *c)
6445 int i;
6447 graph->max_weight = 0;
6449 for (i = 0; i < graph->n_edge; ++i) {
6450 struct isl_sched_edge *edge = &graph->edge[i];
6451 struct isl_sched_node *src = edge->src;
6452 struct isl_sched_node *dst = edge->dst;
6453 isl_basic_map *hull;
6454 isl_bool prox;
6455 int n_in, n_out;
6457 prox = is_non_empty_proximity(edge);
6458 if (prox < 0)
6459 return isl_stat_error;
6460 if (!prox)
6461 continue;
6462 if (bad_cluster(&c->scc[edge->src->scc]) ||
6463 bad_cluster(&c->scc[edge->dst->scc]))
6464 continue;
6465 if (c->scc_cluster[edge->dst->scc] ==
6466 c->scc_cluster[edge->src->scc])
6467 continue;
6469 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6470 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6471 isl_mat_copy(src->vmap));
6472 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6473 isl_mat_copy(dst->vmap));
6474 hull = isl_basic_map_project_out(hull,
6475 isl_dim_in, 0, src->rank);
6476 hull = isl_basic_map_project_out(hull,
6477 isl_dim_out, 0, dst->rank);
6478 hull = isl_basic_map_remove_divs(hull);
6479 n_in = isl_basic_map_dim(hull, isl_dim_in);
6480 n_out = isl_basic_map_dim(hull, isl_dim_out);
6481 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6482 isl_dim_in, 0, n_in);
6483 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6484 isl_dim_out, 0, n_out);
6485 if (!hull)
6486 return isl_stat_error;
6487 edge->weight = isl_basic_map_n_equality(hull);
6488 isl_basic_map_free(hull);
6490 if (edge->weight > graph->max_weight)
6491 graph->max_weight = edge->weight;
6494 return isl_stat_ok;
6497 /* Call compute_schedule_finish_band on each of the clusters in "c"
6498 * in their topological order. This order is determined by the scc
6499 * fields of the nodes in "graph".
6500 * Combine the results in a sequence expressing the topological order.
6502 * If there is only one cluster left, then there is no need to introduce
6503 * a sequence node. Also, in this case, the cluster necessarily contains
6504 * the SCC at position 0 in the original graph and is therefore also
6505 * stored in the first cluster of "c".
6507 static __isl_give isl_schedule_node *finish_bands_clustering(
6508 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6509 struct isl_clustering *c)
6511 int i;
6512 isl_ctx *ctx;
6513 isl_union_set_list *filters;
6515 if (graph->scc == 1)
6516 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6518 ctx = isl_schedule_node_get_ctx(node);
6520 filters = extract_sccs(ctx, graph);
6521 node = isl_schedule_node_insert_sequence(node, filters);
6523 for (i = 0; i < graph->scc; ++i) {
6524 int j = c->scc_cluster[i];
6525 node = isl_schedule_node_child(node, i);
6526 node = isl_schedule_node_child(node, 0);
6527 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6528 node = isl_schedule_node_parent(node);
6529 node = isl_schedule_node_parent(node);
6532 return node;
6535 /* Compute a schedule for a connected dependence graph by first considering
6536 * each strongly connected component (SCC) in the graph separately and then
6537 * incrementally combining them into clusters.
6538 * Return the updated schedule node.
6540 * Initially, each cluster consists of a single SCC, each with its
6541 * own band schedule. The algorithm then tries to merge pairs
6542 * of clusters along a proximity edge until no more suitable
6543 * proximity edges can be found. During this merging, the schedule
6544 * is maintained in the individual SCCs.
6545 * After the merging is completed, the full resulting clusters
6546 * are extracted and in finish_bands_clustering,
6547 * compute_schedule_finish_band is called on each of them to integrate
6548 * the band into "node" and to continue the computation.
6550 * compute_weights initializes the weights that are used by find_proximity.
6552 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6553 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6555 isl_ctx *ctx;
6556 struct isl_clustering c;
6557 int i;
6559 ctx = isl_schedule_node_get_ctx(node);
6561 if (clustering_init(ctx, &c, graph) < 0)
6562 goto error;
6564 if (compute_weights(graph, &c) < 0)
6565 goto error;
6567 for (;;) {
6568 i = find_proximity(graph, &c);
6569 if (i < 0)
6570 goto error;
6571 if (i >= graph->n_edge)
6572 break;
6573 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6574 goto error;
6577 if (extract_clusters(ctx, graph, &c) < 0)
6578 goto error;
6580 node = finish_bands_clustering(node, graph, &c);
6582 clustering_free(ctx, &c);
6583 return node;
6584 error:
6585 clustering_free(ctx, &c);
6586 return isl_schedule_node_free(node);
6589 /* Compute a schedule for a connected dependence graph and return
6590 * the updated schedule node.
6592 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6593 * as many validity dependences as possible. When all validity dependences
6594 * are satisfied we extend the schedule to a full-dimensional schedule.
6596 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6597 * depending on whether the user has selected the option to try and
6598 * compute a schedule for the entire (weakly connected) component first.
6599 * If there is only a single strongly connected component (SCC), then
6600 * there is no point in trying to combine SCCs
6601 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6602 * is called instead.
6604 static __isl_give isl_schedule_node *compute_schedule_wcc(
6605 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6607 isl_ctx *ctx;
6609 if (!node)
6610 return NULL;
6612 ctx = isl_schedule_node_get_ctx(node);
6613 if (detect_sccs(ctx, graph) < 0)
6614 return isl_schedule_node_free(node);
6616 if (compute_maxvar(graph) < 0)
6617 return isl_schedule_node_free(node);
6619 if (need_feautrier_step(ctx, graph))
6620 return compute_schedule_wcc_feautrier(node, graph);
6622 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6623 return compute_schedule_wcc_whole(node, graph);
6624 else
6625 return compute_schedule_wcc_clustering(node, graph);
6628 /* Compute a schedule for each group of nodes identified by node->scc
6629 * separately and then combine them in a sequence node (or as set node
6630 * if graph->weak is set) inserted at position "node" of the schedule tree.
6631 * Return the updated schedule node.
6633 * If "wcc" is set then each of the groups belongs to a single
6634 * weakly connected component in the dependence graph so that
6635 * there is no need for compute_sub_schedule to look for weakly
6636 * connected components.
6638 static __isl_give isl_schedule_node *compute_component_schedule(
6639 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6640 int wcc)
6642 int component;
6643 isl_ctx *ctx;
6644 isl_union_set_list *filters;
6646 if (!node)
6647 return NULL;
6648 ctx = isl_schedule_node_get_ctx(node);
6650 filters = extract_sccs(ctx, graph);
6651 if (graph->weak)
6652 node = isl_schedule_node_insert_set(node, filters);
6653 else
6654 node = isl_schedule_node_insert_sequence(node, filters);
6656 for (component = 0; component < graph->scc; ++component) {
6657 node = isl_schedule_node_child(node, component);
6658 node = isl_schedule_node_child(node, 0);
6659 node = compute_sub_schedule(node, ctx, graph,
6660 &node_scc_exactly,
6661 &edge_scc_exactly, component, wcc);
6662 node = isl_schedule_node_parent(node);
6663 node = isl_schedule_node_parent(node);
6666 return node;
6669 /* Compute a schedule for the given dependence graph and insert it at "node".
6670 * Return the updated schedule node.
6672 * We first check if the graph is connected (through validity and conditional
6673 * validity dependences) and, if not, compute a schedule
6674 * for each component separately.
6675 * If the schedule_serialize_sccs option is set, then we check for strongly
6676 * connected components instead and compute a separate schedule for
6677 * each such strongly connected component.
6679 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6680 struct isl_sched_graph *graph)
6682 isl_ctx *ctx;
6684 if (!node)
6685 return NULL;
6687 ctx = isl_schedule_node_get_ctx(node);
6688 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6689 if (detect_sccs(ctx, graph) < 0)
6690 return isl_schedule_node_free(node);
6691 } else {
6692 if (detect_wccs(ctx, graph) < 0)
6693 return isl_schedule_node_free(node);
6696 if (graph->scc > 1)
6697 return compute_component_schedule(node, graph, 1);
6699 return compute_schedule_wcc(node, graph);
6702 /* Compute a schedule on sc->domain that respects the given schedule
6703 * constraints.
6705 * In particular, the schedule respects all the validity dependences.
6706 * If the default isl scheduling algorithm is used, it tries to minimize
6707 * the dependence distances over the proximity dependences.
6708 * If Feautrier's scheduling algorithm is used, the proximity dependence
6709 * distances are only minimized during the extension to a full-dimensional
6710 * schedule.
6712 * If there are any condition and conditional validity dependences,
6713 * then the conditional validity dependences may be violated inside
6714 * a tilable band, provided they have no adjacent non-local
6715 * condition dependences.
6717 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6718 __isl_take isl_schedule_constraints *sc)
6720 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6721 struct isl_sched_graph graph = { 0 };
6722 isl_schedule *sched;
6723 isl_schedule_node *node;
6724 isl_union_set *domain;
6726 sc = isl_schedule_constraints_align_params(sc);
6728 domain = isl_schedule_constraints_get_domain(sc);
6729 if (isl_union_set_n_set(domain) == 0) {
6730 isl_schedule_constraints_free(sc);
6731 return isl_schedule_from_domain(domain);
6734 if (graph_init(&graph, sc) < 0)
6735 domain = isl_union_set_free(domain);
6737 node = isl_schedule_node_from_domain(domain);
6738 node = isl_schedule_node_child(node, 0);
6739 if (graph.n > 0)
6740 node = compute_schedule(node, &graph);
6741 sched = isl_schedule_node_get_schedule(node);
6742 isl_schedule_node_free(node);
6744 graph_free(ctx, &graph);
6745 isl_schedule_constraints_free(sc);
6747 return sched;
6750 /* Compute a schedule for the given union of domains that respects
6751 * all the validity dependences and minimizes
6752 * the dependence distances over the proximity dependences.
6754 * This function is kept for backward compatibility.
6756 __isl_give isl_schedule *isl_union_set_compute_schedule(
6757 __isl_take isl_union_set *domain,
6758 __isl_take isl_union_map *validity,
6759 __isl_take isl_union_map *proximity)
6761 isl_schedule_constraints *sc;
6763 sc = isl_schedule_constraints_on_domain(domain);
6764 sc = isl_schedule_constraints_set_validity(sc, validity);
6765 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6767 return isl_schedule_constraints_compute_schedule(sc);