isl_scheduler.c: update_schedule: drop support for transformed coefficients
[isl.git] / isl_scheduler.c
blob61fb684379b53c2e5d532c9a8b379688a81d2630
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 columns of cmap represent a change of basis for the schedule
62 * coefficients; the first rank columns span the linear part of
63 * the schedule rows
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 * ctrans is the transpose of cmap.
68 * start is the first variable in the LP problem in the sequences that
69 * represents the schedule coefficients of this node
70 * nvar is the dimension of the domain
71 * nparam is the number of parameters or 0 if we are not constructing
72 * a parametric schedule
74 * If compressed is set, then hull represents the constraints
75 * that were used to derive the compression, while compress and
76 * decompress map the original space to the compressed space and
77 * vice versa.
79 * scc is the index of SCC (or WCC) this node belongs to
81 * "cluster" is only used inside extract_clusters and identifies
82 * the cluster of SCCs that the node belongs to.
84 * coincident contains a boolean for each of the rows of the schedule,
85 * indicating whether the corresponding scheduling dimension satisfies
86 * the coincidence constraints in the sense that the corresponding
87 * dependence distances are zero.
89 * If the schedule_treat_coalescing option is set, then
90 * "sizes" contains the sizes of the (compressed) instance set
91 * in each direction. If there is no fixed size in a given direction,
92 * then the corresponding size value is set to infinity.
93 * If the schedule_treat_coalescing option or the schedule_max_coefficient
94 * option is set, then "max" contains the maximal values for
95 * schedule coefficients of the (compressed) variables. If no bound
96 * needs to be imposed on a particular variable, then the corresponding
97 * value is negative.
99 struct isl_sched_node {
100 isl_space *space;
101 int compressed;
102 isl_set *hull;
103 isl_multi_aff *compress;
104 isl_multi_aff *decompress;
105 isl_mat *sched;
106 isl_map *sched_map;
107 int rank;
108 isl_mat *cmap;
109 isl_mat *indep;
110 isl_mat *ctrans;
111 int start;
112 int nvar;
113 int nparam;
115 int scc;
116 int cluster;
118 int *coincident;
120 isl_multi_val *sizes;
121 isl_vec *max;
124 static int node_has_tuples(const void *entry, const void *val)
126 struct isl_sched_node *node = (struct isl_sched_node *)entry;
127 isl_space *space = (isl_space *) val;
129 return isl_space_has_equal_tuples(node->space, space);
132 static int node_scc_exactly(struct isl_sched_node *node, int scc)
134 return node->scc == scc;
137 static int node_scc_at_most(struct isl_sched_node *node, int scc)
139 return node->scc <= scc;
142 static int node_scc_at_least(struct isl_sched_node *node, int scc)
144 return node->scc >= scc;
147 /* An edge in the dependence graph. An edge may be used to
148 * ensure validity of the generated schedule, to minimize the dependence
149 * distance or both
151 * map is the dependence relation, with i -> j in the map if j depends on i
152 * tagged_condition and tagged_validity contain the union of all tagged
153 * condition or conditional validity dependence relations that
154 * specialize the dependence relation "map"; that is,
155 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
156 * or "tagged_validity", then i -> j is an element of "map".
157 * If these fields are NULL, then they represent the empty relation.
158 * src is the source node
159 * dst is the sink node
161 * types is a bit vector containing the types of this edge.
162 * validity is set if the edge is used to ensure correctness
163 * coincidence is used to enforce zero dependence distances
164 * proximity is set if the edge is used to minimize dependence distances
165 * condition is set if the edge represents a condition
166 * for a conditional validity schedule constraint
167 * local can only be set for condition edges and indicates that
168 * the dependence distance over the edge should be zero
169 * conditional_validity is set if the edge is used to conditionally
170 * ensure correctness
172 * For validity edges, start and end mark the sequence of inequality
173 * constraints in the LP problem that encode the validity constraint
174 * corresponding to this edge.
176 * During clustering, an edge may be marked "no_merge" if it should
177 * not be used to merge clusters.
178 * The weight is also only used during clustering and it is
179 * an indication of how many schedule dimensions on either side
180 * of the schedule constraints can be aligned.
181 * If the weight is negative, then this means that this edge was postponed
182 * by has_bounded_distances or any_no_merge. The original weight can
183 * be retrieved by adding 1 + graph->max_weight, with "graph"
184 * the graph containing this edge.
186 struct isl_sched_edge {
187 isl_map *map;
188 isl_union_map *tagged_condition;
189 isl_union_map *tagged_validity;
191 struct isl_sched_node *src;
192 struct isl_sched_node *dst;
194 unsigned types;
196 int start;
197 int end;
199 int no_merge;
200 int weight;
203 /* Is "edge" marked as being of type "type"?
205 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
207 return ISL_FL_ISSET(edge->types, 1 << type);
210 /* Mark "edge" as being of type "type".
212 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
214 ISL_FL_SET(edge->types, 1 << type);
217 /* No longer mark "edge" as being of type "type"?
219 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
221 ISL_FL_CLR(edge->types, 1 << type);
224 /* Is "edge" marked as a validity edge?
226 static int is_validity(struct isl_sched_edge *edge)
228 return is_type(edge, isl_edge_validity);
231 /* Mark "edge" as a validity edge.
233 static void set_validity(struct isl_sched_edge *edge)
235 set_type(edge, isl_edge_validity);
238 /* Is "edge" marked as a proximity edge?
240 static int is_proximity(struct isl_sched_edge *edge)
242 return is_type(edge, isl_edge_proximity);
245 /* Is "edge" marked as a local edge?
247 static int is_local(struct isl_sched_edge *edge)
249 return is_type(edge, isl_edge_local);
252 /* Mark "edge" as a local edge.
254 static void set_local(struct isl_sched_edge *edge)
256 set_type(edge, isl_edge_local);
259 /* No longer mark "edge" as a local edge.
261 static void clear_local(struct isl_sched_edge *edge)
263 clear_type(edge, isl_edge_local);
266 /* Is "edge" marked as a coincidence edge?
268 static int is_coincidence(struct isl_sched_edge *edge)
270 return is_type(edge, isl_edge_coincidence);
273 /* Is "edge" marked as a condition edge?
275 static int is_condition(struct isl_sched_edge *edge)
277 return is_type(edge, isl_edge_condition);
280 /* Is "edge" marked as a conditional validity edge?
282 static int is_conditional_validity(struct isl_sched_edge *edge)
284 return is_type(edge, isl_edge_conditional_validity);
287 /* Internal information about the dependence graph used during
288 * the construction of the schedule.
290 * intra_hmap is a cache, mapping dependence relations to their dual,
291 * for dependences from a node to itself
292 * inter_hmap is a cache, mapping dependence relations to their dual,
293 * for dependences between distinct nodes
294 * if compression is involved then the key for these maps
295 * is the original, uncompressed dependence relation, while
296 * the value is the dual of the compressed dependence relation.
298 * n is the number of nodes
299 * node is the list of nodes
300 * maxvar is the maximal number of variables over all nodes
301 * max_row is the allocated number of rows in the schedule
302 * n_row is the current (maximal) number of linearly independent
303 * rows in the node schedules
304 * n_total_row is the current number of rows in the node schedules
305 * band_start is the starting row in the node schedules of the current band
306 * root is set if this graph is the original dependence graph,
307 * without any splitting
309 * sorted contains a list of node indices sorted according to the
310 * SCC to which a node belongs
312 * n_edge is the number of edges
313 * edge is the list of edges
314 * max_edge contains the maximal number of edges of each type;
315 * in particular, it contains the number of edges in the inital graph.
316 * edge_table contains pointers into the edge array, hashed on the source
317 * and sink spaces; there is one such table for each type;
318 * a given edge may be referenced from more than one table
319 * if the corresponding relation appears in more than one of the
320 * sets of dependences; however, for each type there is only
321 * a single edge between a given pair of source and sink space
322 * in the entire graph
324 * node_table contains pointers into the node array, hashed on the space tuples
326 * region contains a list of variable sequences that should be non-trivial
328 * lp contains the (I)LP problem used to obtain new schedule rows
330 * src_scc and dst_scc are the source and sink SCCs of an edge with
331 * conflicting constraints
333 * scc represents the number of components
334 * weak is set if the components are weakly connected
336 * max_weight is used during clustering and represents the maximal
337 * weight of the relevant proximity edges.
339 struct isl_sched_graph {
340 isl_map_to_basic_set *intra_hmap;
341 isl_map_to_basic_set *inter_hmap;
343 struct isl_sched_node *node;
344 int n;
345 int maxvar;
346 int max_row;
347 int n_row;
349 int *sorted;
351 int n_total_row;
352 int band_start;
354 int root;
356 struct isl_sched_edge *edge;
357 int n_edge;
358 int max_edge[isl_edge_last + 1];
359 struct isl_hash_table *edge_table[isl_edge_last + 1];
361 struct isl_hash_table *node_table;
362 struct isl_trivial_region *region;
364 isl_basic_set *lp;
366 int src_scc;
367 int dst_scc;
369 int scc;
370 int weak;
372 int max_weight;
375 /* Initialize node_table based on the list of nodes.
377 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
379 int i;
381 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
382 if (!graph->node_table)
383 return -1;
385 for (i = 0; i < graph->n; ++i) {
386 struct isl_hash_table_entry *entry;
387 uint32_t hash;
389 hash = isl_space_get_tuple_hash(graph->node[i].space);
390 entry = isl_hash_table_find(ctx, graph->node_table, hash,
391 &node_has_tuples,
392 graph->node[i].space, 1);
393 if (!entry)
394 return -1;
395 entry->data = &graph->node[i];
398 return 0;
401 /* Return a pointer to the node that lives within the given space,
402 * or NULL if there is no such node.
404 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
405 struct isl_sched_graph *graph, __isl_keep isl_space *space)
407 struct isl_hash_table_entry *entry;
408 uint32_t hash;
410 hash = isl_space_get_tuple_hash(space);
411 entry = isl_hash_table_find(ctx, graph->node_table, hash,
412 &node_has_tuples, space, 0);
414 return entry ? entry->data : NULL;
417 static int edge_has_src_and_dst(const void *entry, const void *val)
419 const struct isl_sched_edge *edge = entry;
420 const struct isl_sched_edge *temp = val;
422 return edge->src == temp->src && edge->dst == temp->dst;
425 /* Add the given edge to graph->edge_table[type].
427 static isl_stat graph_edge_table_add(isl_ctx *ctx,
428 struct isl_sched_graph *graph, enum isl_edge_type type,
429 struct isl_sched_edge *edge)
431 struct isl_hash_table_entry *entry;
432 uint32_t hash;
434 hash = isl_hash_init();
435 hash = isl_hash_builtin(hash, edge->src);
436 hash = isl_hash_builtin(hash, edge->dst);
437 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
438 &edge_has_src_and_dst, edge, 1);
439 if (!entry)
440 return isl_stat_error;
441 entry->data = edge;
443 return isl_stat_ok;
446 /* Allocate the edge_tables based on the maximal number of edges of
447 * each type.
449 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
451 int i;
453 for (i = 0; i <= isl_edge_last; ++i) {
454 graph->edge_table[i] = isl_hash_table_alloc(ctx,
455 graph->max_edge[i]);
456 if (!graph->edge_table[i])
457 return -1;
460 return 0;
463 /* If graph->edge_table[type] contains an edge from the given source
464 * to the given destination, then return the hash table entry of this edge.
465 * Otherwise, return NULL.
467 static struct isl_hash_table_entry *graph_find_edge_entry(
468 struct isl_sched_graph *graph,
469 enum isl_edge_type type,
470 struct isl_sched_node *src, struct isl_sched_node *dst)
472 isl_ctx *ctx = isl_space_get_ctx(src->space);
473 uint32_t hash;
474 struct isl_sched_edge temp = { .src = src, .dst = dst };
476 hash = isl_hash_init();
477 hash = isl_hash_builtin(hash, temp.src);
478 hash = isl_hash_builtin(hash, temp.dst);
479 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
480 &edge_has_src_and_dst, &temp, 0);
484 /* If graph->edge_table[type] contains an edge from the given source
485 * to the given destination, then return this edge.
486 * Otherwise, return NULL.
488 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
489 enum isl_edge_type type,
490 struct isl_sched_node *src, struct isl_sched_node *dst)
492 struct isl_hash_table_entry *entry;
494 entry = graph_find_edge_entry(graph, type, src, dst);
495 if (!entry)
496 return NULL;
498 return entry->data;
501 /* Check whether the dependence graph has an edge of the given type
502 * between the given two nodes.
504 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
505 enum isl_edge_type type,
506 struct isl_sched_node *src, struct isl_sched_node *dst)
508 struct isl_sched_edge *edge;
509 isl_bool empty;
511 edge = graph_find_edge(graph, type, src, dst);
512 if (!edge)
513 return 0;
515 empty = isl_map_plain_is_empty(edge->map);
516 if (empty < 0)
517 return isl_bool_error;
519 return !empty;
522 /* Look for any edge with the same src, dst and map fields as "model".
524 * Return the matching edge if one can be found.
525 * Return "model" if no matching edge is found.
526 * Return NULL on error.
528 static struct isl_sched_edge *graph_find_matching_edge(
529 struct isl_sched_graph *graph, struct isl_sched_edge *model)
531 enum isl_edge_type i;
532 struct isl_sched_edge *edge;
534 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
535 int is_equal;
537 edge = graph_find_edge(graph, i, model->src, model->dst);
538 if (!edge)
539 continue;
540 is_equal = isl_map_plain_is_equal(model->map, edge->map);
541 if (is_equal < 0)
542 return NULL;
543 if (is_equal)
544 return edge;
547 return model;
550 /* Remove the given edge from all the edge_tables that refer to it.
552 static void graph_remove_edge(struct isl_sched_graph *graph,
553 struct isl_sched_edge *edge)
555 isl_ctx *ctx = isl_map_get_ctx(edge->map);
556 enum isl_edge_type i;
558 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
559 struct isl_hash_table_entry *entry;
561 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
562 if (!entry)
563 continue;
564 if (entry->data != edge)
565 continue;
566 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
570 /* Check whether the dependence graph has any edge
571 * between the given two nodes.
573 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
574 struct isl_sched_node *src, struct isl_sched_node *dst)
576 enum isl_edge_type i;
577 isl_bool r;
579 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
580 r = graph_has_edge(graph, i, src, dst);
581 if (r < 0 || r)
582 return r;
585 return r;
588 /* Check whether the dependence graph has a validity edge
589 * between the given two nodes.
591 * Conditional validity edges are essentially validity edges that
592 * can be ignored if the corresponding condition edges are iteration private.
593 * Here, we are only checking for the presence of validity
594 * edges, so we need to consider the conditional validity edges too.
595 * In particular, this function is used during the detection
596 * of strongly connected components and we cannot ignore
597 * conditional validity edges during this detection.
599 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
600 struct isl_sched_node *src, struct isl_sched_node *dst)
602 isl_bool r;
604 r = graph_has_edge(graph, isl_edge_validity, src, dst);
605 if (r < 0 || r)
606 return r;
608 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
611 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
612 int n_node, int n_edge)
614 int i;
616 graph->n = n_node;
617 graph->n_edge = n_edge;
618 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
619 graph->sorted = isl_calloc_array(ctx, int, graph->n);
620 graph->region = isl_alloc_array(ctx,
621 struct isl_trivial_region, graph->n);
622 graph->edge = isl_calloc_array(ctx,
623 struct isl_sched_edge, graph->n_edge);
625 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
626 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
628 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
629 !graph->sorted)
630 return -1;
632 for(i = 0; i < graph->n; ++i)
633 graph->sorted[i] = i;
635 return 0;
638 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
640 int i;
642 isl_map_to_basic_set_free(graph->intra_hmap);
643 isl_map_to_basic_set_free(graph->inter_hmap);
645 if (graph->node)
646 for (i = 0; i < graph->n; ++i) {
647 isl_space_free(graph->node[i].space);
648 isl_set_free(graph->node[i].hull);
649 isl_multi_aff_free(graph->node[i].compress);
650 isl_multi_aff_free(graph->node[i].decompress);
651 isl_mat_free(graph->node[i].sched);
652 isl_map_free(graph->node[i].sched_map);
653 isl_mat_free(graph->node[i].cmap);
654 isl_mat_free(graph->node[i].indep);
655 isl_mat_free(graph->node[i].ctrans);
656 if (graph->root)
657 free(graph->node[i].coincident);
658 isl_multi_val_free(graph->node[i].sizes);
659 isl_vec_free(graph->node[i].max);
661 free(graph->node);
662 free(graph->sorted);
663 if (graph->edge)
664 for (i = 0; i < graph->n_edge; ++i) {
665 isl_map_free(graph->edge[i].map);
666 isl_union_map_free(graph->edge[i].tagged_condition);
667 isl_union_map_free(graph->edge[i].tagged_validity);
669 free(graph->edge);
670 free(graph->region);
671 for (i = 0; i <= isl_edge_last; ++i)
672 isl_hash_table_free(ctx, graph->edge_table[i]);
673 isl_hash_table_free(ctx, graph->node_table);
674 isl_basic_set_free(graph->lp);
677 /* For each "set" on which this function is called, increment
678 * graph->n by one and update graph->maxvar.
680 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
682 struct isl_sched_graph *graph = user;
683 int nvar = isl_set_dim(set, isl_dim_set);
685 graph->n++;
686 if (nvar > graph->maxvar)
687 graph->maxvar = nvar;
689 isl_set_free(set);
691 return isl_stat_ok;
694 /* Compute the number of rows that should be allocated for the schedule.
695 * In particular, we need one row for each variable or one row
696 * for each basic map in the dependences.
697 * Note that it is practically impossible to exhaust both
698 * the number of dependences and the number of variables.
700 static isl_stat compute_max_row(struct isl_sched_graph *graph,
701 __isl_keep isl_schedule_constraints *sc)
703 int n_edge;
704 isl_stat r;
705 isl_union_set *domain;
707 graph->n = 0;
708 graph->maxvar = 0;
709 domain = isl_schedule_constraints_get_domain(sc);
710 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
711 isl_union_set_free(domain);
712 if (r < 0)
713 return isl_stat_error;
714 n_edge = isl_schedule_constraints_n_basic_map(sc);
715 if (n_edge < 0)
716 return isl_stat_error;
717 graph->max_row = n_edge + graph->maxvar;
719 return isl_stat_ok;
722 /* Does "bset" have any defining equalities for its set variables?
724 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
726 int i, n;
728 if (!bset)
729 return isl_bool_error;
731 n = isl_basic_set_dim(bset, isl_dim_set);
732 for (i = 0; i < n; ++i) {
733 isl_bool has;
735 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
736 NULL);
737 if (has < 0 || has)
738 return has;
741 return isl_bool_false;
744 /* Set the entries of node->max to the value of the schedule_max_coefficient
745 * option, if set.
747 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
749 int max;
751 max = isl_options_get_schedule_max_coefficient(ctx);
752 if (max == -1)
753 return isl_stat_ok;
755 node->max = isl_vec_alloc(ctx, node->nvar);
756 node->max = isl_vec_set_si(node->max, max);
757 if (!node->max)
758 return isl_stat_error;
760 return isl_stat_ok;
763 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
764 * option (if set) and half of the minimum of the sizes in the other
765 * dimensions. If the minimum of the sizes is one, half of the size
766 * is zero and this value is reset to one.
767 * If the global minimum is unbounded (i.e., if both
768 * the schedule_max_coefficient is not set and the sizes in the other
769 * dimensions are unbounded), then store a negative value.
770 * If the schedule coefficient is close to the size of the instance set
771 * in another dimension, then the schedule may represent a loop
772 * coalescing transformation (especially if the coefficient
773 * in that other dimension is one). Forcing the coefficient to be
774 * smaller than or equal to half the minimal size should avoid this
775 * situation.
777 static isl_stat compute_max_coefficient(isl_ctx *ctx,
778 struct isl_sched_node *node)
780 int max;
781 int i, j;
782 isl_vec *v;
784 max = isl_options_get_schedule_max_coefficient(ctx);
785 v = isl_vec_alloc(ctx, node->nvar);
786 if (!v)
787 return isl_stat_error;
789 for (i = 0; i < node->nvar; ++i) {
790 isl_int_set_si(v->el[i], max);
791 isl_int_mul_si(v->el[i], v->el[i], 2);
794 for (i = 0; i < node->nvar; ++i) {
795 isl_val *size;
797 size = isl_multi_val_get_val(node->sizes, i);
798 if (!size)
799 goto error;
800 if (!isl_val_is_int(size)) {
801 isl_val_free(size);
802 continue;
804 for (j = 0; j < node->nvar; ++j) {
805 if (j == i)
806 continue;
807 if (isl_int_is_neg(v->el[j]) ||
808 isl_int_gt(v->el[j], size->n))
809 isl_int_set(v->el[j], size->n);
811 isl_val_free(size);
814 for (i = 0; i < node->nvar; ++i) {
815 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
816 if (isl_int_is_zero(v->el[i]))
817 isl_int_set_si(v->el[i], 1);
820 node->max = v;
821 return isl_stat_ok;
822 error:
823 isl_vec_free(v);
824 return isl_stat_error;
827 /* Compute and return the size of "set" in dimension "dim".
828 * The size is taken to be the difference in values for that variable
829 * for fixed values of the other variables.
830 * In particular, the variable is first isolated from the other variables
831 * in the range of a map
833 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
835 * and then duplicated
837 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
839 * The shared variables are then projected out and the maximal value
840 * of i_dim' - i_dim is computed.
842 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
844 isl_map *map;
845 isl_local_space *ls;
846 isl_aff *obj;
847 isl_val *v;
849 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
850 map = isl_map_project_out(map, isl_dim_in, dim, 1);
851 map = isl_map_range_product(map, isl_map_copy(map));
852 map = isl_set_unwrap(isl_map_range(map));
853 set = isl_map_deltas(map);
854 ls = isl_local_space_from_space(isl_set_get_space(set));
855 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
856 v = isl_set_max_val(set, obj);
857 isl_aff_free(obj);
858 isl_set_free(set);
860 return v;
863 /* Compute the size of the instance set "set" of "node", after compression,
864 * as well as bounds on the corresponding coefficients, if needed.
866 * The sizes are needed when the schedule_treat_coalescing option is set.
867 * The bounds are needed when the schedule_treat_coalescing option or
868 * the schedule_max_coefficient option is set.
870 * If the schedule_treat_coalescing option is not set, then at most
871 * the bounds need to be set and this is done in set_max_coefficient.
872 * Otherwise, compress the domain if needed, compute the size
873 * in each direction and store the results in node->size.
874 * Finally, set the bounds on the coefficients based on the sizes
875 * and the schedule_max_coefficient option in compute_max_coefficient.
877 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
878 __isl_take isl_set *set)
880 int j, n;
881 isl_multi_val *mv;
883 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
884 isl_set_free(set);
885 return set_max_coefficient(ctx, node);
888 if (node->compressed)
889 set = isl_set_preimage_multi_aff(set,
890 isl_multi_aff_copy(node->decompress));
891 mv = isl_multi_val_zero(isl_set_get_space(set));
892 n = isl_set_dim(set, isl_dim_set);
893 for (j = 0; j < n; ++j) {
894 isl_val *v;
896 v = compute_size(isl_set_copy(set), j);
897 mv = isl_multi_val_set_val(mv, j, v);
899 node->sizes = mv;
900 isl_set_free(set);
901 if (!node->sizes)
902 return isl_stat_error;
903 return compute_max_coefficient(ctx, node);
906 /* Add a new node to the graph representing the given instance set.
907 * "nvar" is the (possibly compressed) number of variables and
908 * may be smaller than then number of set variables in "set"
909 * if "compressed" is set.
910 * If "compressed" is set, then "hull" represents the constraints
911 * that were used to derive the compression, while "compress" and
912 * "decompress" map the original space to the compressed space and
913 * vice versa.
914 * If "compressed" is not set, then "hull", "compress" and "decompress"
915 * should be NULL.
917 * Compute the size of the instance set and bounds on the coefficients,
918 * if needed.
920 static isl_stat add_node(struct isl_sched_graph *graph,
921 __isl_take isl_set *set, int nvar, int compressed,
922 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
923 __isl_take isl_multi_aff *decompress)
925 int nparam;
926 isl_ctx *ctx;
927 isl_mat *sched;
928 isl_space *space;
929 int *coincident;
930 struct isl_sched_node *node;
932 if (!set)
933 return isl_stat_error;
935 ctx = isl_set_get_ctx(set);
936 nparam = isl_set_dim(set, isl_dim_param);
937 if (!ctx->opt->schedule_parametric)
938 nparam = 0;
939 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
940 node = &graph->node[graph->n];
941 graph->n++;
942 space = isl_set_get_space(set);
943 node->space = space;
944 node->nvar = nvar;
945 node->nparam = nparam;
946 node->sched = sched;
947 node->sched_map = NULL;
948 coincident = isl_calloc_array(ctx, int, graph->max_row);
949 node->coincident = coincident;
950 node->compressed = compressed;
951 node->hull = hull;
952 node->compress = compress;
953 node->decompress = decompress;
954 if (compute_sizes_and_max(ctx, node, set) < 0)
955 return isl_stat_error;
957 if (!space || !sched || (graph->max_row && !coincident))
958 return isl_stat_error;
959 if (compressed && (!hull || !compress || !decompress))
960 return isl_stat_error;
962 return isl_stat_ok;
965 /* Construct an identifier for node "node", which will represent "set".
966 * The name of the identifier is either "compressed" or
967 * "compressed_<name>", with <name> the name of the space of "set".
968 * The user pointer of the identifier points to "node".
970 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
971 struct isl_sched_node *node)
973 isl_bool has_name;
974 isl_ctx *ctx;
975 isl_id *id;
976 isl_printer *p;
977 const char *name;
978 char *id_name;
980 has_name = isl_set_has_tuple_name(set);
981 if (has_name < 0)
982 return NULL;
984 ctx = isl_set_get_ctx(set);
985 if (!has_name)
986 return isl_id_alloc(ctx, "compressed", node);
988 p = isl_printer_to_str(ctx);
989 name = isl_set_get_tuple_name(set);
990 p = isl_printer_print_str(p, "compressed_");
991 p = isl_printer_print_str(p, name);
992 id_name = isl_printer_get_str(p);
993 isl_printer_free(p);
995 id = isl_id_alloc(ctx, id_name, node);
996 free(id_name);
998 return id;
1001 /* Add a new node to the graph representing the given set.
1003 * If any of the set variables is defined by an equality, then
1004 * we perform variable compression such that we can perform
1005 * the scheduling on the compressed domain.
1006 * In this case, an identifier is used that references the new node
1007 * such that each compressed space is unique and
1008 * such that the node can be recovered from the compressed space.
1010 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1012 int nvar;
1013 isl_bool has_equality;
1014 isl_id *id;
1015 isl_basic_set *hull;
1016 isl_set *hull_set;
1017 isl_morph *morph;
1018 isl_multi_aff *compress, *decompress;
1019 struct isl_sched_graph *graph = user;
1021 hull = isl_set_affine_hull(isl_set_copy(set));
1022 hull = isl_basic_set_remove_divs(hull);
1023 nvar = isl_set_dim(set, isl_dim_set);
1024 has_equality = has_any_defining_equality(hull);
1026 if (has_equality < 0)
1027 goto error;
1028 if (!has_equality) {
1029 isl_basic_set_free(hull);
1030 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1033 id = construct_compressed_id(set, &graph->node[graph->n]);
1034 morph = isl_basic_set_variable_compression_with_id(hull,
1035 isl_dim_set, id);
1036 isl_id_free(id);
1037 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1038 compress = isl_morph_get_var_multi_aff(morph);
1039 morph = isl_morph_inverse(morph);
1040 decompress = isl_morph_get_var_multi_aff(morph);
1041 isl_morph_free(morph);
1043 hull_set = isl_set_from_basic_set(hull);
1044 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1045 error:
1046 isl_basic_set_free(hull);
1047 isl_set_free(set);
1048 return isl_stat_error;
1051 struct isl_extract_edge_data {
1052 enum isl_edge_type type;
1053 struct isl_sched_graph *graph;
1056 /* Merge edge2 into edge1, freeing the contents of edge2.
1057 * Return 0 on success and -1 on failure.
1059 * edge1 and edge2 are assumed to have the same value for the map field.
1061 static int merge_edge(struct isl_sched_edge *edge1,
1062 struct isl_sched_edge *edge2)
1064 edge1->types |= edge2->types;
1065 isl_map_free(edge2->map);
1067 if (is_condition(edge2)) {
1068 if (!edge1->tagged_condition)
1069 edge1->tagged_condition = edge2->tagged_condition;
1070 else
1071 edge1->tagged_condition =
1072 isl_union_map_union(edge1->tagged_condition,
1073 edge2->tagged_condition);
1076 if (is_conditional_validity(edge2)) {
1077 if (!edge1->tagged_validity)
1078 edge1->tagged_validity = edge2->tagged_validity;
1079 else
1080 edge1->tagged_validity =
1081 isl_union_map_union(edge1->tagged_validity,
1082 edge2->tagged_validity);
1085 if (is_condition(edge2) && !edge1->tagged_condition)
1086 return -1;
1087 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1088 return -1;
1090 return 0;
1093 /* Insert dummy tags in domain and range of "map".
1095 * In particular, if "map" is of the form
1097 * A -> B
1099 * then return
1101 * [A -> dummy_tag] -> [B -> dummy_tag]
1103 * where the dummy_tags are identical and equal to any dummy tags
1104 * introduced by any other call to this function.
1106 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1108 static char dummy;
1109 isl_ctx *ctx;
1110 isl_id *id;
1111 isl_space *space;
1112 isl_set *domain, *range;
1114 ctx = isl_map_get_ctx(map);
1116 id = isl_id_alloc(ctx, NULL, &dummy);
1117 space = isl_space_params(isl_map_get_space(map));
1118 space = isl_space_set_from_params(space);
1119 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1120 space = isl_space_map_from_set(space);
1122 domain = isl_map_wrap(map);
1123 range = isl_map_wrap(isl_map_universe(space));
1124 map = isl_map_from_domain_and_range(domain, range);
1125 map = isl_map_zip(map);
1127 return map;
1130 /* Given that at least one of "src" or "dst" is compressed, return
1131 * a map between the spaces of these nodes restricted to the affine
1132 * hull that was used in the compression.
1134 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1135 struct isl_sched_node *dst)
1137 isl_set *dom, *ran;
1139 if (src->compressed)
1140 dom = isl_set_copy(src->hull);
1141 else
1142 dom = isl_set_universe(isl_space_copy(src->space));
1143 if (dst->compressed)
1144 ran = isl_set_copy(dst->hull);
1145 else
1146 ran = isl_set_universe(isl_space_copy(dst->space));
1148 return isl_map_from_domain_and_range(dom, ran);
1151 /* Intersect the domains of the nested relations in domain and range
1152 * of "tagged" with "map".
1154 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1155 __isl_keep isl_map *map)
1157 isl_set *set;
1159 tagged = isl_map_zip(tagged);
1160 set = isl_map_wrap(isl_map_copy(map));
1161 tagged = isl_map_intersect_domain(tagged, set);
1162 tagged = isl_map_zip(tagged);
1163 return tagged;
1166 /* Return a pointer to the node that lives in the domain space of "map"
1167 * or NULL if there is no such node.
1169 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1170 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1172 struct isl_sched_node *node;
1173 isl_space *space;
1175 space = isl_space_domain(isl_map_get_space(map));
1176 node = graph_find_node(ctx, graph, space);
1177 isl_space_free(space);
1179 return node;
1182 /* Return a pointer to the node that lives in the range space of "map"
1183 * or NULL if there is no such node.
1185 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1186 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1188 struct isl_sched_node *node;
1189 isl_space *space;
1191 space = isl_space_range(isl_map_get_space(map));
1192 node = graph_find_node(ctx, graph, space);
1193 isl_space_free(space);
1195 return node;
1198 /* Add a new edge to the graph based on the given map
1199 * and add it to data->graph->edge_table[data->type].
1200 * If a dependence relation of a given type happens to be identical
1201 * to one of the dependence relations of a type that was added before,
1202 * then we don't create a new edge, but instead mark the original edge
1203 * as also representing a dependence of the current type.
1205 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1206 * may be specified as "tagged" dependence relations. That is, "map"
1207 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1208 * the dependence on iterations and a and b are tags.
1209 * edge->map is set to the relation containing the elements i -> j,
1210 * while edge->tagged_condition and edge->tagged_validity contain
1211 * the union of all the "map" relations
1212 * for which extract_edge is called that result in the same edge->map.
1214 * If the source or the destination node is compressed, then
1215 * intersect both "map" and "tagged" with the constraints that
1216 * were used to construct the compression.
1217 * This ensures that there are no schedule constraints defined
1218 * outside of these domains, while the scheduler no longer has
1219 * any control over those outside parts.
1221 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1223 isl_ctx *ctx = isl_map_get_ctx(map);
1224 struct isl_extract_edge_data *data = user;
1225 struct isl_sched_graph *graph = data->graph;
1226 struct isl_sched_node *src, *dst;
1227 struct isl_sched_edge *edge;
1228 isl_map *tagged = NULL;
1230 if (data->type == isl_edge_condition ||
1231 data->type == isl_edge_conditional_validity) {
1232 if (isl_map_can_zip(map)) {
1233 tagged = isl_map_copy(map);
1234 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1235 } else {
1236 tagged = insert_dummy_tags(isl_map_copy(map));
1240 src = find_domain_node(ctx, graph, map);
1241 dst = find_range_node(ctx, graph, map);
1243 if (!src || !dst) {
1244 isl_map_free(map);
1245 isl_map_free(tagged);
1246 return isl_stat_ok;
1249 if (src->compressed || dst->compressed) {
1250 isl_map *hull;
1251 hull = extract_hull(src, dst);
1252 if (tagged)
1253 tagged = map_intersect_domains(tagged, hull);
1254 map = isl_map_intersect(map, hull);
1257 graph->edge[graph->n_edge].src = src;
1258 graph->edge[graph->n_edge].dst = dst;
1259 graph->edge[graph->n_edge].map = map;
1260 graph->edge[graph->n_edge].types = 0;
1261 graph->edge[graph->n_edge].tagged_condition = NULL;
1262 graph->edge[graph->n_edge].tagged_validity = NULL;
1263 set_type(&graph->edge[graph->n_edge], data->type);
1264 if (data->type == isl_edge_condition)
1265 graph->edge[graph->n_edge].tagged_condition =
1266 isl_union_map_from_map(tagged);
1267 if (data->type == isl_edge_conditional_validity)
1268 graph->edge[graph->n_edge].tagged_validity =
1269 isl_union_map_from_map(tagged);
1271 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1272 if (!edge) {
1273 graph->n_edge++;
1274 return isl_stat_error;
1276 if (edge == &graph->edge[graph->n_edge])
1277 return graph_edge_table_add(ctx, graph, data->type,
1278 &graph->edge[graph->n_edge++]);
1280 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1281 return -1;
1283 return graph_edge_table_add(ctx, graph, data->type, edge);
1286 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1288 * The context is included in the domain before the nodes of
1289 * the graphs are extracted in order to be able to exploit
1290 * any possible additional equalities.
1291 * Note that this intersection is only performed locally here.
1293 static isl_stat graph_init(struct isl_sched_graph *graph,
1294 __isl_keep isl_schedule_constraints *sc)
1296 isl_ctx *ctx;
1297 isl_union_set *domain;
1298 isl_union_map *c;
1299 struct isl_extract_edge_data data;
1300 enum isl_edge_type i;
1301 isl_stat r;
1303 if (!sc)
1304 return isl_stat_error;
1306 ctx = isl_schedule_constraints_get_ctx(sc);
1308 domain = isl_schedule_constraints_get_domain(sc);
1309 graph->n = isl_union_set_n_set(domain);
1310 isl_union_set_free(domain);
1312 if (graph_alloc(ctx, graph, graph->n,
1313 isl_schedule_constraints_n_map(sc)) < 0)
1314 return isl_stat_error;
1316 if (compute_max_row(graph, sc) < 0)
1317 return isl_stat_error;
1318 graph->root = 1;
1319 graph->n = 0;
1320 domain = isl_schedule_constraints_get_domain(sc);
1321 domain = isl_union_set_intersect_params(domain,
1322 isl_schedule_constraints_get_context(sc));
1323 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1324 isl_union_set_free(domain);
1325 if (r < 0)
1326 return isl_stat_error;
1327 if (graph_init_table(ctx, graph) < 0)
1328 return isl_stat_error;
1329 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1330 c = isl_schedule_constraints_get(sc, i);
1331 graph->max_edge[i] = isl_union_map_n_map(c);
1332 isl_union_map_free(c);
1333 if (!c)
1334 return isl_stat_error;
1336 if (graph_init_edge_tables(ctx, graph) < 0)
1337 return isl_stat_error;
1338 graph->n_edge = 0;
1339 data.graph = graph;
1340 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1341 isl_stat r;
1343 data.type = i;
1344 c = isl_schedule_constraints_get(sc, i);
1345 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1346 isl_union_map_free(c);
1347 if (r < 0)
1348 return isl_stat_error;
1351 return isl_stat_ok;
1354 /* Check whether there is any dependence from node[j] to node[i]
1355 * or from node[i] to node[j].
1357 static isl_bool node_follows_weak(int i, int j, void *user)
1359 isl_bool f;
1360 struct isl_sched_graph *graph = user;
1362 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1363 if (f < 0 || f)
1364 return f;
1365 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1368 /* Check whether there is a (conditional) validity dependence from node[j]
1369 * to node[i], forcing node[i] to follow node[j].
1371 static isl_bool node_follows_strong(int i, int j, void *user)
1373 struct isl_sched_graph *graph = user;
1375 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1378 /* Use Tarjan's algorithm for computing the strongly connected components
1379 * in the dependence graph only considering those edges defined by "follows".
1381 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1382 isl_bool (*follows)(int i, int j, void *user))
1384 int i, n;
1385 struct isl_tarjan_graph *g = NULL;
1387 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1388 if (!g)
1389 return -1;
1391 graph->scc = 0;
1392 i = 0;
1393 n = graph->n;
1394 while (n) {
1395 while (g->order[i] != -1) {
1396 graph->node[g->order[i]].scc = graph->scc;
1397 --n;
1398 ++i;
1400 ++i;
1401 graph->scc++;
1404 isl_tarjan_graph_free(g);
1406 return 0;
1409 /* Apply Tarjan's algorithm to detect the strongly connected components
1410 * in the dependence graph.
1411 * Only consider the (conditional) validity dependences and clear "weak".
1413 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1415 graph->weak = 0;
1416 return detect_ccs(ctx, graph, &node_follows_strong);
1419 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1420 * in the dependence graph.
1421 * Consider all dependences and set "weak".
1423 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1425 graph->weak = 1;
1426 return detect_ccs(ctx, graph, &node_follows_weak);
1429 static int cmp_scc(const void *a, const void *b, void *data)
1431 struct isl_sched_graph *graph = data;
1432 const int *i1 = a;
1433 const int *i2 = b;
1435 return graph->node[*i1].scc - graph->node[*i2].scc;
1438 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1440 static int sort_sccs(struct isl_sched_graph *graph)
1442 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1445 /* Given a dependence relation R from "node" to itself,
1446 * construct the set of coefficients of valid constraints for elements
1447 * in that dependence relation.
1448 * In particular, the result contains tuples of coefficients
1449 * c_0, c_n, c_x such that
1451 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1453 * or, equivalently,
1455 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1457 * We choose here to compute the dual of delta R.
1458 * Alternatively, we could have computed the dual of R, resulting
1459 * in a set of tuples c_0, c_n, c_x, c_y, and then
1460 * plugged in (c_0, c_n, c_x, -c_x).
1462 * If "node" has been compressed, then the dependence relation
1463 * is also compressed before the set of coefficients is computed.
1465 static __isl_give isl_basic_set *intra_coefficients(
1466 struct isl_sched_graph *graph, struct isl_sched_node *node,
1467 __isl_take isl_map *map)
1469 isl_set *delta;
1470 isl_map *key;
1471 isl_basic_set *coef;
1472 isl_maybe_isl_basic_set m;
1474 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1475 if (m.valid < 0 || m.valid) {
1476 isl_map_free(map);
1477 return m.value;
1480 key = isl_map_copy(map);
1481 if (node->compressed) {
1482 map = isl_map_preimage_domain_multi_aff(map,
1483 isl_multi_aff_copy(node->decompress));
1484 map = isl_map_preimage_range_multi_aff(map,
1485 isl_multi_aff_copy(node->decompress));
1487 delta = isl_set_remove_divs(isl_map_deltas(map));
1488 coef = isl_set_coefficients(delta);
1489 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1490 isl_basic_set_copy(coef));
1492 return coef;
1495 /* Given a dependence relation R, construct the set of coefficients
1496 * of valid constraints for elements in that dependence relation.
1497 * In particular, the result contains tuples of coefficients
1498 * c_0, c_n, c_x, c_y such that
1500 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1502 * If the source or destination nodes of "edge" have been compressed,
1503 * then the dependence relation is also compressed before
1504 * the set of coefficients is computed.
1506 static __isl_give isl_basic_set *inter_coefficients(
1507 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1508 __isl_take isl_map *map)
1510 isl_set *set;
1511 isl_map *key;
1512 isl_basic_set *coef;
1513 isl_maybe_isl_basic_set m;
1515 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1516 if (m.valid < 0 || m.valid) {
1517 isl_map_free(map);
1518 return m.value;
1521 key = isl_map_copy(map);
1522 if (edge->src->compressed)
1523 map = isl_map_preimage_domain_multi_aff(map,
1524 isl_multi_aff_copy(edge->src->decompress));
1525 if (edge->dst->compressed)
1526 map = isl_map_preimage_range_multi_aff(map,
1527 isl_multi_aff_copy(edge->dst->decompress));
1528 set = isl_map_wrap(isl_map_remove_divs(map));
1529 coef = isl_set_coefficients(set);
1530 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1531 isl_basic_set_copy(coef));
1533 return coef;
1536 /* Return the position of the coefficients of the variables in
1537 * the coefficients constraints "coef".
1539 * The space of "coef" is of the form
1541 * { coefficients[[cst, params] -> S] }
1543 * Return the position of S.
1545 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1547 int offset;
1548 isl_space *space;
1550 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1551 offset = isl_space_dim(space, isl_dim_in);
1552 isl_space_free(space);
1554 return offset;
1557 /* Return the offset of the coefficients of the variables of "node"
1558 * within the (I)LP.
1560 * Within each node, the coefficients have the following order:
1561 * - c_i_0
1562 * - c_i_n (if parametric)
1563 * - positive and negative parts of c_i_x
1565 static int node_var_coef_offset(struct isl_sched_node *node)
1567 return node->start + 1 + node->nparam;
1570 /* Return the position of the pair of variables encoding
1571 * coefficient "i" of "node".
1573 * The order of these variable pairs is the opposite of
1574 * that of the coefficients, with 2 variables per coefficient.
1576 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1578 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1581 /* Construct an isl_dim_map for mapping constraints on coefficients
1582 * for "node" to the corresponding positions in graph->lp.
1583 * "offset" is the offset of the coefficients for the variables
1584 * in the input constraints.
1585 * "s" is the sign of the mapping.
1587 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1588 * The mapping produced by this function essentially plugs in
1589 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1590 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1591 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1592 * Furthermore, the order of these pairs is the opposite of that
1593 * of the corresponding coefficients.
1595 * The caller can extend the mapping to also map the other coefficients
1596 * (and therefore not plug in 0).
1598 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1599 struct isl_sched_graph *graph, struct isl_sched_node *node,
1600 int offset, int s)
1602 int pos;
1603 unsigned total;
1604 isl_dim_map *dim_map;
1606 if (!node)
1607 return NULL;
1609 total = isl_basic_set_total_dim(graph->lp);
1610 pos = node_var_coef_pos(node, 0);
1611 dim_map = isl_dim_map_alloc(ctx, total);
1612 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1613 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1615 return dim_map;
1618 /* Construct an isl_dim_map for mapping constraints on coefficients
1619 * for "src" (node i) and "dst" (node j) to the corresponding positions
1620 * in graph->lp.
1621 * "offset" is the offset of the coefficients for the variables of "src"
1622 * in the input constraints.
1623 * "s" is the sign of the mapping.
1625 * The input constraints are given in terms of the coefficients
1626 * (c_0, c_n, c_x, c_y).
1627 * The mapping produced by this function essentially plugs in
1628 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1629 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1630 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1631 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1632 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1633 * Furthermore, the order of these pairs is the opposite of that
1634 * of the corresponding coefficients.
1636 * The caller can further extend the mapping.
1638 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1639 struct isl_sched_graph *graph, struct isl_sched_node *src,
1640 struct isl_sched_node *dst, int offset, int s)
1642 int pos;
1643 unsigned total;
1644 isl_dim_map *dim_map;
1646 if (!src || !dst)
1647 return NULL;
1649 total = isl_basic_set_total_dim(graph->lp);
1650 dim_map = isl_dim_map_alloc(ctx, total);
1652 isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, s);
1653 isl_dim_map_range(dim_map, dst->start + 1, 1, 1, 1, dst->nparam, s);
1654 pos = node_var_coef_pos(dst, 0);
1655 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1656 dst->nvar, -s);
1657 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1658 dst->nvar, s);
1660 isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -s);
1661 isl_dim_map_range(dim_map, src->start + 1, 1, 1, 1, src->nparam, -s);
1662 pos = node_var_coef_pos(src, 0);
1663 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1664 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1666 return dim_map;
1669 /* Add the constraints from "src" to "dst" using "dim_map",
1670 * after making sure there is enough room in "dst" for the extra constraints.
1672 static __isl_give isl_basic_set *add_constraints_dim_map(
1673 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1674 __isl_take isl_dim_map *dim_map)
1676 int n_eq, n_ineq;
1678 n_eq = isl_basic_set_n_equality(src);
1679 n_ineq = isl_basic_set_n_inequality(src);
1680 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1681 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1682 return dst;
1685 /* Add constraints to graph->lp that force validity for the given
1686 * dependence from a node i to itself.
1687 * That is, add constraints that enforce
1689 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1690 * = c_i_x (y - x) >= 0
1692 * for each (x,y) in R.
1693 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1694 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1695 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1696 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1698 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1699 struct isl_sched_edge *edge)
1701 int offset;
1702 isl_map *map = isl_map_copy(edge->map);
1703 isl_ctx *ctx = isl_map_get_ctx(map);
1704 isl_dim_map *dim_map;
1705 isl_basic_set *coef;
1706 struct isl_sched_node *node = edge->src;
1708 coef = intra_coefficients(graph, node, map);
1710 offset = coef_var_offset(coef);
1712 if (!coef)
1713 return isl_stat_error;
1715 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1716 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1718 return isl_stat_ok;
1721 /* Add constraints to graph->lp that force validity for the given
1722 * dependence from node i to node j.
1723 * That is, add constraints that enforce
1725 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1727 * for each (x,y) in R.
1728 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1729 * of valid constraints for R and then plug in
1730 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1731 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1732 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1734 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1735 struct isl_sched_edge *edge)
1737 int offset;
1738 isl_map *map;
1739 isl_ctx *ctx;
1740 isl_dim_map *dim_map;
1741 isl_basic_set *coef;
1742 struct isl_sched_node *src = edge->src;
1743 struct isl_sched_node *dst = edge->dst;
1745 if (!graph->lp)
1746 return isl_stat_error;
1748 map = isl_map_copy(edge->map);
1749 ctx = isl_map_get_ctx(map);
1750 coef = inter_coefficients(graph, edge, map);
1752 offset = coef_var_offset(coef);
1754 if (!coef)
1755 return isl_stat_error;
1757 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1759 edge->start = graph->lp->n_ineq;
1760 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1761 if (!graph->lp)
1762 return isl_stat_error;
1763 edge->end = graph->lp->n_ineq;
1765 return isl_stat_ok;
1768 /* Add constraints to graph->lp that bound the dependence distance for the given
1769 * dependence from a node i to itself.
1770 * If s = 1, we add the constraint
1772 * c_i_x (y - x) <= m_0 + m_n n
1774 * or
1776 * -c_i_x (y - x) + m_0 + m_n n >= 0
1778 * for each (x,y) in R.
1779 * If s = -1, we add the constraint
1781 * -c_i_x (y - x) <= m_0 + m_n n
1783 * or
1785 * c_i_x (y - x) + m_0 + m_n n >= 0
1787 * for each (x,y) in R.
1788 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1789 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1790 * with each coefficient (except m_0) represented as a pair of non-negative
1791 * coefficients.
1794 * If "local" is set, then we add constraints
1796 * c_i_x (y - x) <= 0
1798 * or
1800 * -c_i_x (y - x) <= 0
1802 * instead, forcing the dependence distance to be (less than or) equal to 0.
1803 * That is, we plug in (0, 0, -s * c_i_x),
1804 * Note that dependences marked local are treated as validity constraints
1805 * by add_all_validity_constraints and therefore also have
1806 * their distances bounded by 0 from below.
1808 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1809 struct isl_sched_edge *edge, int s, int local)
1811 int offset;
1812 unsigned nparam;
1813 isl_map *map = isl_map_copy(edge->map);
1814 isl_ctx *ctx = isl_map_get_ctx(map);
1815 isl_dim_map *dim_map;
1816 isl_basic_set *coef;
1817 struct isl_sched_node *node = edge->src;
1819 coef = intra_coefficients(graph, node, map);
1821 offset = coef_var_offset(coef);
1823 if (!coef)
1824 return isl_stat_error;
1826 nparam = isl_space_dim(node->space, isl_dim_param);
1827 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1829 if (!local) {
1830 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1831 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1832 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1834 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1836 return isl_stat_ok;
1839 /* Add constraints to graph->lp that bound the dependence distance for the given
1840 * dependence from node i to node j.
1841 * If s = 1, we add the constraint
1843 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1844 * <= m_0 + m_n n
1846 * or
1848 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1849 * m_0 + m_n n >= 0
1851 * for each (x,y) in R.
1852 * If s = -1, we add the constraint
1854 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1855 * <= m_0 + m_n n
1857 * or
1859 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1860 * m_0 + m_n n >= 0
1862 * for each (x,y) in R.
1863 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1864 * of valid constraints for R and then plug in
1865 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1866 * s*c_i_x, -s*c_j_x)
1867 * with each coefficient (except m_0, c_*_0 and c_*_n)
1868 * represented as a pair of non-negative coefficients.
1871 * If "local" is set (and s = 1), then we add constraints
1873 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1875 * or
1877 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
1879 * instead, forcing the dependence distance to be (less than or) equal to 0.
1880 * That is, we plug in
1881 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
1882 * Note that dependences marked local are treated as validity constraints
1883 * by add_all_validity_constraints and therefore also have
1884 * their distances bounded by 0 from below.
1886 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1887 struct isl_sched_edge *edge, int s, int local)
1889 int offset;
1890 unsigned nparam;
1891 isl_map *map = isl_map_copy(edge->map);
1892 isl_ctx *ctx = isl_map_get_ctx(map);
1893 isl_dim_map *dim_map;
1894 isl_basic_set *coef;
1895 struct isl_sched_node *src = edge->src;
1896 struct isl_sched_node *dst = edge->dst;
1898 coef = inter_coefficients(graph, edge, map);
1900 offset = coef_var_offset(coef);
1902 if (!coef)
1903 return isl_stat_error;
1905 nparam = isl_space_dim(src->space, isl_dim_param);
1906 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1908 if (!local) {
1909 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1910 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1911 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1914 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1916 return isl_stat_ok;
1919 /* Add all validity constraints to graph->lp.
1921 * An edge that is forced to be local needs to have its dependence
1922 * distances equal to zero. We take care of bounding them by 0 from below
1923 * here. add_all_proximity_constraints takes care of bounding them by 0
1924 * from above.
1926 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1927 * Otherwise, we ignore them.
1929 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1930 int use_coincidence)
1932 int i;
1934 for (i = 0; i < graph->n_edge; ++i) {
1935 struct isl_sched_edge *edge = &graph->edge[i];
1936 int local;
1938 local = is_local(edge) ||
1939 (is_coincidence(edge) && use_coincidence);
1940 if (!is_validity(edge) && !local)
1941 continue;
1942 if (edge->src != edge->dst)
1943 continue;
1944 if (add_intra_validity_constraints(graph, edge) < 0)
1945 return -1;
1948 for (i = 0; i < graph->n_edge; ++i) {
1949 struct isl_sched_edge *edge = &graph->edge[i];
1950 int local;
1952 local = is_local(edge) ||
1953 (is_coincidence(edge) && use_coincidence);
1954 if (!is_validity(edge) && !local)
1955 continue;
1956 if (edge->src == edge->dst)
1957 continue;
1958 if (add_inter_validity_constraints(graph, edge) < 0)
1959 return -1;
1962 return 0;
1965 /* Add constraints to graph->lp that bound the dependence distance
1966 * for all dependence relations.
1967 * If a given proximity dependence is identical to a validity
1968 * dependence, then the dependence distance is already bounded
1969 * from below (by zero), so we only need to bound the distance
1970 * from above. (This includes the case of "local" dependences
1971 * which are treated as validity dependence by add_all_validity_constraints.)
1972 * Otherwise, we need to bound the distance both from above and from below.
1974 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1975 * Otherwise, we ignore them.
1977 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
1978 int use_coincidence)
1980 int i;
1982 for (i = 0; i < graph->n_edge; ++i) {
1983 struct isl_sched_edge *edge = &graph->edge[i];
1984 int local;
1986 local = is_local(edge) ||
1987 (is_coincidence(edge) && use_coincidence);
1988 if (!is_proximity(edge) && !local)
1989 continue;
1990 if (edge->src == edge->dst &&
1991 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
1992 return -1;
1993 if (edge->src != edge->dst &&
1994 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
1995 return -1;
1996 if (is_validity(edge) || local)
1997 continue;
1998 if (edge->src == edge->dst &&
1999 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2000 return -1;
2001 if (edge->src != edge->dst &&
2002 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2003 return -1;
2006 return 0;
2009 /* Normalize the rows of "indep" such that all rows are lexicographically
2010 * positive and such that each row contains as many final zeros as possible,
2011 * given the choice for the previous rows.
2012 * Do this by performing elementary row operations.
2014 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2016 indep = isl_mat_reverse_gauss(indep);
2017 indep = isl_mat_lexnonneg_rows(indep);
2018 return indep;
2021 /* Compute a basis for the rows in the linear part of the schedule
2022 * and extend this basis to a full basis. The remaining rows
2023 * can then be used to force linear independence from the rows
2024 * in the schedule.
2026 * In particular, given the schedule rows S, we compute
2028 * S = H Q
2029 * S U = H
2031 * with H the Hermite normal form of S. That is, all but the
2032 * first rank columns of H are zero and so each row in S is
2033 * a linear combination of the first rank rows of Q.
2034 * The matrix Q is then transposed because we will write the
2035 * coefficients of the next schedule row as a column vector s
2036 * and express this s as a linear combination s = Q c of the
2037 * computed basis.
2038 * Transposing S U = H yields
2040 * U^T S^T = H^T
2042 * with all but the first rank rows of H^T zero.
2043 * The last rows of U^T are therefore linear combinations
2044 * of schedule coefficients that are all zero on schedule
2045 * coefficients that are linearly dependent on the rows of S.
2046 * At least one of these combinations is non-zero on
2047 * linearly independent schedule coefficients.
2048 * The rows are normalized to involve as few of the last
2049 * coefficients as possible and to have a positive initial value.
2051 static int node_update_cmap(struct isl_sched_node *node)
2053 isl_mat *H, *U, *Q;
2054 int n_row = isl_mat_rows(node->sched);
2056 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2057 1 + node->nparam, node->nvar);
2059 H = isl_mat_left_hermite(H, 0, &U, &Q);
2060 isl_mat_free(node->cmap);
2061 isl_mat_free(node->indep);
2062 isl_mat_free(node->ctrans);
2063 node->ctrans = isl_mat_copy(Q);
2064 node->cmap = isl_mat_transpose(Q);
2065 node->indep = isl_mat_transpose(U);
2066 node->rank = isl_mat_initial_non_zero_cols(H);
2067 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2068 node->indep = normalize_independent(node->indep);
2069 isl_mat_free(H);
2071 if (!node->cmap || !node->indep || !node->ctrans || node->rank < 0)
2072 return -1;
2073 return 0;
2076 /* Is "edge" marked as a validity or a conditional validity edge?
2078 static int is_any_validity(struct isl_sched_edge *edge)
2080 return is_validity(edge) || is_conditional_validity(edge);
2083 /* How many times should we count the constraints in "edge"?
2085 * We count as follows
2086 * validity -> 1 (>= 0)
2087 * validity+proximity -> 2 (>= 0 and upper bound)
2088 * proximity -> 2 (lower and upper bound)
2089 * local(+any) -> 2 (>= 0 and <= 0)
2091 * If an edge is only marked conditional_validity then it counts
2092 * as zero since it is only checked afterwards.
2094 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2095 * Otherwise, we ignore them.
2097 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2099 if (is_proximity(edge) || is_local(edge))
2100 return 2;
2101 if (use_coincidence && is_coincidence(edge))
2102 return 2;
2103 if (is_validity(edge))
2104 return 1;
2105 return 0;
2108 /* Count the number of equality and inequality constraints
2109 * that will be added for the given map.
2111 * "use_coincidence" is set if we should take into account coincidence edges.
2113 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2114 struct isl_sched_edge *edge, __isl_take isl_map *map,
2115 int *n_eq, int *n_ineq, int use_coincidence)
2117 isl_basic_set *coef;
2118 int f = edge_multiplicity(edge, use_coincidence);
2120 if (f == 0) {
2121 isl_map_free(map);
2122 return isl_stat_ok;
2125 if (edge->src == edge->dst)
2126 coef = intra_coefficients(graph, edge->src, map);
2127 else
2128 coef = inter_coefficients(graph, edge, map);
2129 if (!coef)
2130 return isl_stat_error;
2131 *n_eq += f * isl_basic_set_n_equality(coef);
2132 *n_ineq += f * isl_basic_set_n_inequality(coef);
2133 isl_basic_set_free(coef);
2135 return isl_stat_ok;
2138 /* Count the number of equality and inequality constraints
2139 * that will be added to the main lp problem.
2140 * We count as follows
2141 * validity -> 1 (>= 0)
2142 * validity+proximity -> 2 (>= 0 and upper bound)
2143 * proximity -> 2 (lower and upper bound)
2144 * local(+any) -> 2 (>= 0 and <= 0)
2146 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2147 * Otherwise, we ignore them.
2149 static int count_constraints(struct isl_sched_graph *graph,
2150 int *n_eq, int *n_ineq, int use_coincidence)
2152 int i;
2154 *n_eq = *n_ineq = 0;
2155 for (i = 0; i < graph->n_edge; ++i) {
2156 struct isl_sched_edge *edge = &graph->edge[i];
2157 isl_map *map = isl_map_copy(edge->map);
2159 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2160 use_coincidence) < 0)
2161 return -1;
2164 return 0;
2167 /* Count the number of constraints that will be added by
2168 * add_bound_constant_constraints to bound the values of the constant terms
2169 * and increment *n_eq and *n_ineq accordingly.
2171 * In practice, add_bound_constant_constraints only adds inequalities.
2173 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2174 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2176 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2177 return isl_stat_ok;
2179 *n_ineq += graph->n;
2181 return isl_stat_ok;
2184 /* Add constraints to bound the values of the constant terms in the schedule,
2185 * if requested by the user.
2187 * The maximal value of the constant terms is defined by the option
2188 * "schedule_max_constant_term".
2190 * Within each node, the coefficients have the following order:
2191 * - c_i_0
2192 * - c_i_n (if parametric)
2193 * - positive and negative parts of c_i_x
2195 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2196 struct isl_sched_graph *graph)
2198 int i, k;
2199 int max;
2200 int total;
2202 max = isl_options_get_schedule_max_constant_term(ctx);
2203 if (max == -1)
2204 return isl_stat_ok;
2206 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2208 for (i = 0; i < graph->n; ++i) {
2209 struct isl_sched_node *node = &graph->node[i];
2210 k = isl_basic_set_alloc_inequality(graph->lp);
2211 if (k < 0)
2212 return isl_stat_error;
2213 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2214 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2215 isl_int_set_si(graph->lp->ineq[k][0], max);
2218 return isl_stat_ok;
2221 /* Count the number of constraints that will be added by
2222 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2223 * accordingly.
2225 * In practice, add_bound_coefficient_constraints only adds inequalities.
2227 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2228 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2230 int i;
2232 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2233 !isl_options_get_schedule_treat_coalescing(ctx))
2234 return 0;
2236 for (i = 0; i < graph->n; ++i)
2237 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2239 return 0;
2242 /* Add constraints to graph->lp that bound the values of
2243 * the parameter schedule coefficients of "node" to "max" and
2244 * the variable schedule coefficients to the corresponding entry
2245 * in node->max.
2246 * In either case, a negative value means that no bound needs to be imposed.
2248 * For parameter coefficients, this amounts to adding a constraint
2250 * c_n <= max
2252 * i.e.,
2254 * -c_n + max >= 0
2256 * The variables coefficients are, however, not represented directly.
2257 * Instead, the variable coefficients c_x are written as differences
2258 * c_x = c_x^+ - c_x^-.
2259 * That is,
2261 * -max_i <= c_x_i <= max_i
2263 * is encoded as
2265 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2267 * or
2269 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2270 * c_x_i^+ - c_x_i^- + max_i >= 0
2272 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2273 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2275 int i, j, k;
2276 int total;
2277 isl_vec *ineq;
2279 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2281 for (j = 0; j < node->nparam; ++j) {
2282 int dim;
2284 if (max < 0)
2285 continue;
2287 k = isl_basic_set_alloc_inequality(graph->lp);
2288 if (k < 0)
2289 return isl_stat_error;
2290 dim = 1 + node->start + 1 + j;
2291 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2292 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2293 isl_int_set_si(graph->lp->ineq[k][0], max);
2296 ineq = isl_vec_alloc(ctx, 1 + total);
2297 ineq = isl_vec_clr(ineq);
2298 if (!ineq)
2299 return isl_stat_error;
2300 for (i = 0; i < node->nvar; ++i) {
2301 int pos = 1 + node_var_coef_pos(node, i);
2303 if (isl_int_is_neg(node->max->el[i]))
2304 continue;
2306 isl_int_set_si(ineq->el[pos], 1);
2307 isl_int_set_si(ineq->el[pos + 1], -1);
2308 isl_int_set(ineq->el[0], node->max->el[i]);
2310 k = isl_basic_set_alloc_inequality(graph->lp);
2311 if (k < 0)
2312 goto error;
2313 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2315 isl_seq_neg(ineq->el + pos, ineq->el + pos + 2 * i, 2);
2316 k = isl_basic_set_alloc_inequality(graph->lp);
2317 if (k < 0)
2318 goto error;
2319 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2321 isl_vec_free(ineq);
2323 return isl_stat_ok;
2324 error:
2325 isl_vec_free(ineq);
2326 return isl_stat_error;
2329 /* Add constraints that bound the values of the variable and parameter
2330 * coefficients of the schedule.
2332 * The maximal value of the coefficients is defined by the option
2333 * 'schedule_max_coefficient' and the entries in node->max.
2334 * These latter entries are only set if either the schedule_max_coefficient
2335 * option or the schedule_treat_coalescing option is set.
2337 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2338 struct isl_sched_graph *graph)
2340 int i;
2341 int max;
2343 max = isl_options_get_schedule_max_coefficient(ctx);
2345 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2346 return isl_stat_ok;
2348 for (i = 0; i < graph->n; ++i) {
2349 struct isl_sched_node *node = &graph->node[i];
2351 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2352 return isl_stat_error;
2355 return isl_stat_ok;
2358 /* Add a constraint to graph->lp that equates the value at position
2359 * "sum_pos" to the sum of the "n" values starting at "first".
2361 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2362 int sum_pos, int first, int n)
2364 int i, k;
2365 int total;
2367 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2369 k = isl_basic_set_alloc_equality(graph->lp);
2370 if (k < 0)
2371 return isl_stat_error;
2372 isl_seq_clr(graph->lp->eq[k], 1 + total);
2373 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2374 for (i = 0; i < n; ++i)
2375 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2377 return isl_stat_ok;
2380 /* Add a constraint to graph->lp that equates the value at position
2381 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2383 * Within each node, the coefficients have the following order:
2384 * - c_i_0
2385 * - c_i_n (if parametric)
2386 * - positive and negative parts of c_i_x
2388 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2389 int sum_pos)
2391 int i, j, k;
2392 int total;
2394 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2396 k = isl_basic_set_alloc_equality(graph->lp);
2397 if (k < 0)
2398 return isl_stat_error;
2399 isl_seq_clr(graph->lp->eq[k], 1 + total);
2400 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2401 for (i = 0; i < graph->n; ++i) {
2402 int pos = 1 + graph->node[i].start + 1;
2404 for (j = 0; j < graph->node[i].nparam; ++j)
2405 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2408 return isl_stat_ok;
2411 /* Add a constraint to graph->lp that equates the value at position
2412 * "sum_pos" to the sum of the variable coefficients of all nodes.
2414 * Within each node, the coefficients have the following order:
2415 * - c_i_0
2416 * - c_i_n (if parametric)
2417 * - positive and negative parts of c_i_x
2419 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2420 int sum_pos)
2422 int i, j, k;
2423 int total;
2425 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2427 k = isl_basic_set_alloc_equality(graph->lp);
2428 if (k < 0)
2429 return isl_stat_error;
2430 isl_seq_clr(graph->lp->eq[k], 1 + total);
2431 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2432 for (i = 0; i < graph->n; ++i) {
2433 struct isl_sched_node *node = &graph->node[i];
2434 int pos = 1 + node_var_coef_offset(node);
2436 for (j = 0; j < 2 * node->nvar; ++j)
2437 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2440 return isl_stat_ok;
2443 /* Construct an ILP problem for finding schedule coefficients
2444 * that result in non-negative, but small dependence distances
2445 * over all dependences.
2446 * In particular, the dependence distances over proximity edges
2447 * are bounded by m_0 + m_n n and we compute schedule coefficients
2448 * with small values (preferably zero) of m_n and m_0.
2450 * All variables of the ILP are non-negative. The actual coefficients
2451 * may be negative, so each coefficient is represented as the difference
2452 * of two non-negative variables. The negative part always appears
2453 * immediately before the positive part.
2454 * Other than that, the variables have the following order
2456 * - sum of positive and negative parts of m_n coefficients
2457 * - m_0
2458 * - sum of all c_n coefficients
2459 * (unconstrained when computing non-parametric schedules)
2460 * - sum of positive and negative parts of all c_x coefficients
2461 * - positive and negative parts of m_n coefficients
2462 * - for each node
2463 * - c_i_0
2464 * - c_i_n (if parametric)
2465 * - positive and negative parts of c_i_x, in opposite order
2467 * The constraints are those from the edges plus two or three equalities
2468 * to express the sums.
2470 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2471 * Otherwise, we ignore them.
2473 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2474 int use_coincidence)
2476 int i;
2477 unsigned nparam;
2478 unsigned total;
2479 isl_space *space;
2480 int parametric;
2481 int param_pos;
2482 int n_eq, n_ineq;
2484 parametric = ctx->opt->schedule_parametric;
2485 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2486 param_pos = 4;
2487 total = param_pos + 2 * nparam;
2488 for (i = 0; i < graph->n; ++i) {
2489 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2490 if (node_update_cmap(node) < 0)
2491 return isl_stat_error;
2492 node->start = total;
2493 total += 1 + node->nparam + 2 * node->nvar;
2496 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2497 return isl_stat_error;
2498 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2499 return isl_stat_error;
2500 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2501 return isl_stat_error;
2503 space = isl_space_set_alloc(ctx, 0, total);
2504 isl_basic_set_free(graph->lp);
2505 n_eq += 2 + parametric;
2507 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2509 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2510 return isl_stat_error;
2511 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2512 return isl_stat_error;
2513 if (add_var_sum_constraint(graph, 3) < 0)
2514 return isl_stat_error;
2515 if (add_bound_constant_constraints(ctx, graph) < 0)
2516 return isl_stat_error;
2517 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2518 return isl_stat_error;
2519 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2520 return isl_stat_error;
2521 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2522 return isl_stat_error;
2524 return isl_stat_ok;
2527 /* Analyze the conflicting constraint found by
2528 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2529 * constraint of one of the edges between distinct nodes, living, moreover
2530 * in distinct SCCs, then record the source and sink SCC as this may
2531 * be a good place to cut between SCCs.
2533 static int check_conflict(int con, void *user)
2535 int i;
2536 struct isl_sched_graph *graph = user;
2538 if (graph->src_scc >= 0)
2539 return 0;
2541 con -= graph->lp->n_eq;
2543 if (con >= graph->lp->n_ineq)
2544 return 0;
2546 for (i = 0; i < graph->n_edge; ++i) {
2547 if (!is_validity(&graph->edge[i]))
2548 continue;
2549 if (graph->edge[i].src == graph->edge[i].dst)
2550 continue;
2551 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2552 continue;
2553 if (graph->edge[i].start > con)
2554 continue;
2555 if (graph->edge[i].end <= con)
2556 continue;
2557 graph->src_scc = graph->edge[i].src->scc;
2558 graph->dst_scc = graph->edge[i].dst->scc;
2561 return 0;
2564 /* Check whether the next schedule row of the given node needs to be
2565 * non-trivial. Lower-dimensional domains may have some trivial rows,
2566 * but as soon as the number of remaining required non-trivial rows
2567 * is as large as the number or remaining rows to be computed,
2568 * all remaining rows need to be non-trivial.
2570 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2572 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2575 /* Construct a non-triviality region with triviality directions
2576 * corresponding to the rows of "indep".
2577 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2578 * while the triviality directions are expressed in terms of
2579 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2580 * before c^+_i. Furthermore,
2581 * the pairs of non-negative variables representing the coefficients
2582 * are stored in the opposite order.
2584 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2586 isl_ctx *ctx;
2587 isl_mat *mat;
2588 int i, j, n, n_var;
2590 if (!indep)
2591 return NULL;
2593 ctx = isl_mat_get_ctx(indep);
2594 n = isl_mat_rows(indep);
2595 n_var = isl_mat_cols(indep);
2596 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2597 if (!mat)
2598 return NULL;
2599 for (i = 0; i < n; ++i) {
2600 for (j = 0; j < n_var; ++j) {
2601 int nj = n_var - 1 - j;
2602 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2603 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2607 return mat;
2610 /* Solve the ILP problem constructed in setup_lp.
2611 * For each node such that all the remaining rows of its schedule
2612 * need to be non-trivial, we construct a non-triviality region.
2613 * This region imposes that the next row is independent of previous rows.
2614 * In particular, the non-triviality region enforces that at least
2615 * one of the linear combinations in the rows of node->indep is non-zero.
2617 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2619 int i;
2620 isl_vec *sol;
2621 isl_basic_set *lp;
2623 for (i = 0; i < graph->n; ++i) {
2624 struct isl_sched_node *node = &graph->node[i];
2625 isl_mat *trivial;
2627 graph->region[i].pos = node_var_coef_offset(node);
2628 if (needs_row(graph, node))
2629 trivial = construct_trivial(node->indep);
2630 else
2631 trivial = isl_mat_zero(ctx, 0, 0);
2632 graph->region[i].trivial = trivial;
2634 lp = isl_basic_set_copy(graph->lp);
2635 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2636 graph->region, &check_conflict, graph);
2637 for (i = 0; i < graph->n; ++i)
2638 isl_mat_free(graph->region[i].trivial);
2639 return sol;
2642 /* Extract the coefficients for the variables of "node" from "sol".
2644 * Within each node, the coefficients have the following order:
2645 * - c_i_0
2646 * - c_i_n (if parametric)
2647 * - positive and negative parts of c_i_x
2649 * The c_i_x^- appear before their c_i_x^+ counterpart.
2650 * Furthermore, the order of these pairs is the opposite of that
2651 * of the corresponding coefficients.
2653 * Return c_i_x = c_i_x^+ - c_i_x^-
2655 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2656 __isl_keep isl_vec *sol)
2658 int i;
2659 int pos;
2660 isl_vec *csol;
2662 if (!sol)
2663 return NULL;
2664 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2665 if (!csol)
2666 return NULL;
2668 pos = 1 + node_var_coef_offset(node);
2669 for (i = 0; i < node->nvar; ++i)
2670 isl_int_sub(csol->el[node->nvar - 1 - i],
2671 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2673 return csol;
2676 /* Update the schedules of all nodes based on the given solution
2677 * of the LP problem.
2678 * The new row is added to the current band.
2679 * All possibly negative coefficients are encoded as a difference
2680 * of two non-negative variables, so we need to perform the subtraction
2681 * here.
2683 * If coincident is set, then the caller guarantees that the new
2684 * row satisfies the coincidence constraints.
2686 static int update_schedule(struct isl_sched_graph *graph,
2687 __isl_take isl_vec *sol, int coincident)
2689 int i, j;
2690 isl_vec *csol = NULL;
2692 if (!sol)
2693 goto error;
2694 if (sol->size == 0)
2695 isl_die(sol->ctx, isl_error_internal,
2696 "no solution found", goto error);
2697 if (graph->n_total_row >= graph->max_row)
2698 isl_die(sol->ctx, isl_error_internal,
2699 "too many schedule rows", goto error);
2701 for (i = 0; i < graph->n; ++i) {
2702 struct isl_sched_node *node = &graph->node[i];
2703 int pos = node->start;
2704 int row = isl_mat_rows(node->sched);
2706 isl_vec_free(csol);
2707 csol = extract_var_coef(node, sol);
2708 if (!csol)
2709 goto error;
2711 isl_map_free(node->sched_map);
2712 node->sched_map = NULL;
2713 node->sched = isl_mat_add_rows(node->sched, 1);
2714 if (!node->sched)
2715 goto error;
2716 for (j = 0; j < 1 + node->nparam; ++j)
2717 node->sched = isl_mat_set_element(node->sched,
2718 row, j, sol->el[1 + pos + j]);
2719 for (j = 0; j < node->nvar; ++j)
2720 node->sched = isl_mat_set_element(node->sched,
2721 row, 1 + node->nparam + j, csol->el[j]);
2722 node->coincident[graph->n_total_row] = coincident;
2724 isl_vec_free(sol);
2725 isl_vec_free(csol);
2727 graph->n_row++;
2728 graph->n_total_row++;
2730 return 0;
2731 error:
2732 isl_vec_free(sol);
2733 isl_vec_free(csol);
2734 return -1;
2737 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2738 * and return this isl_aff.
2740 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2741 struct isl_sched_node *node, int row)
2743 int j;
2744 isl_int v;
2745 isl_aff *aff;
2747 isl_int_init(v);
2749 aff = isl_aff_zero_on_domain(ls);
2750 isl_mat_get_element(node->sched, row, 0, &v);
2751 aff = isl_aff_set_constant(aff, v);
2752 for (j = 0; j < node->nparam; ++j) {
2753 isl_mat_get_element(node->sched, row, 1 + j, &v);
2754 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2756 for (j = 0; j < node->nvar; ++j) {
2757 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2758 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2761 isl_int_clear(v);
2763 return aff;
2766 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2767 * and return this multi_aff.
2769 * The result is defined over the uncompressed node domain.
2771 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2772 struct isl_sched_node *node, int first, int n)
2774 int i;
2775 isl_space *space;
2776 isl_local_space *ls;
2777 isl_aff *aff;
2778 isl_multi_aff *ma;
2779 int nrow;
2781 if (!node)
2782 return NULL;
2783 nrow = isl_mat_rows(node->sched);
2784 if (node->compressed)
2785 space = isl_multi_aff_get_domain_space(node->decompress);
2786 else
2787 space = isl_space_copy(node->space);
2788 ls = isl_local_space_from_space(isl_space_copy(space));
2789 space = isl_space_from_domain(space);
2790 space = isl_space_add_dims(space, isl_dim_out, n);
2791 ma = isl_multi_aff_zero(space);
2793 for (i = first; i < first + n; ++i) {
2794 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2795 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2798 isl_local_space_free(ls);
2800 if (node->compressed)
2801 ma = isl_multi_aff_pullback_multi_aff(ma,
2802 isl_multi_aff_copy(node->compress));
2804 return ma;
2807 /* Convert node->sched into a multi_aff and return this multi_aff.
2809 * The result is defined over the uncompressed node domain.
2811 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2812 struct isl_sched_node *node)
2814 int nrow;
2816 nrow = isl_mat_rows(node->sched);
2817 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2820 /* Convert node->sched into a map and return this map.
2822 * The result is cached in node->sched_map, which needs to be released
2823 * whenever node->sched is updated.
2824 * It is defined over the uncompressed node domain.
2826 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2828 if (!node->sched_map) {
2829 isl_multi_aff *ma;
2831 ma = node_extract_schedule_multi_aff(node);
2832 node->sched_map = isl_map_from_multi_aff(ma);
2835 return isl_map_copy(node->sched_map);
2838 /* Construct a map that can be used to update a dependence relation
2839 * based on the current schedule.
2840 * That is, construct a map expressing that source and sink
2841 * are executed within the same iteration of the current schedule.
2842 * This map can then be intersected with the dependence relation.
2843 * This is not the most efficient way, but this shouldn't be a critical
2844 * operation.
2846 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2847 struct isl_sched_node *dst)
2849 isl_map *src_sched, *dst_sched;
2851 src_sched = node_extract_schedule(src);
2852 dst_sched = node_extract_schedule(dst);
2853 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2856 /* Intersect the domains of the nested relations in domain and range
2857 * of "umap" with "map".
2859 static __isl_give isl_union_map *intersect_domains(
2860 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2862 isl_union_set *uset;
2864 umap = isl_union_map_zip(umap);
2865 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2866 umap = isl_union_map_intersect_domain(umap, uset);
2867 umap = isl_union_map_zip(umap);
2868 return umap;
2871 /* Update the dependence relation of the given edge based
2872 * on the current schedule.
2873 * If the dependence is carried completely by the current schedule, then
2874 * it is removed from the edge_tables. It is kept in the list of edges
2875 * as otherwise all edge_tables would have to be recomputed.
2877 static int update_edge(struct isl_sched_graph *graph,
2878 struct isl_sched_edge *edge)
2880 int empty;
2881 isl_map *id;
2883 id = specializer(edge->src, edge->dst);
2884 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2885 if (!edge->map)
2886 goto error;
2888 if (edge->tagged_condition) {
2889 edge->tagged_condition =
2890 intersect_domains(edge->tagged_condition, id);
2891 if (!edge->tagged_condition)
2892 goto error;
2894 if (edge->tagged_validity) {
2895 edge->tagged_validity =
2896 intersect_domains(edge->tagged_validity, id);
2897 if (!edge->tagged_validity)
2898 goto error;
2901 empty = isl_map_plain_is_empty(edge->map);
2902 if (empty < 0)
2903 goto error;
2904 if (empty)
2905 graph_remove_edge(graph, edge);
2907 isl_map_free(id);
2908 return 0;
2909 error:
2910 isl_map_free(id);
2911 return -1;
2914 /* Does the domain of "umap" intersect "uset"?
2916 static int domain_intersects(__isl_keep isl_union_map *umap,
2917 __isl_keep isl_union_set *uset)
2919 int empty;
2921 umap = isl_union_map_copy(umap);
2922 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2923 empty = isl_union_map_is_empty(umap);
2924 isl_union_map_free(umap);
2926 return empty < 0 ? -1 : !empty;
2929 /* Does the range of "umap" intersect "uset"?
2931 static int range_intersects(__isl_keep isl_union_map *umap,
2932 __isl_keep isl_union_set *uset)
2934 int empty;
2936 umap = isl_union_map_copy(umap);
2937 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2938 empty = isl_union_map_is_empty(umap);
2939 isl_union_map_free(umap);
2941 return empty < 0 ? -1 : !empty;
2944 /* Are the condition dependences of "edge" local with respect to
2945 * the current schedule?
2947 * That is, are domain and range of the condition dependences mapped
2948 * to the same point?
2950 * In other words, is the condition false?
2952 static int is_condition_false(struct isl_sched_edge *edge)
2954 isl_union_map *umap;
2955 isl_map *map, *sched, *test;
2956 int empty, local;
2958 empty = isl_union_map_is_empty(edge->tagged_condition);
2959 if (empty < 0 || empty)
2960 return empty;
2962 umap = isl_union_map_copy(edge->tagged_condition);
2963 umap = isl_union_map_zip(umap);
2964 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2965 map = isl_map_from_union_map(umap);
2967 sched = node_extract_schedule(edge->src);
2968 map = isl_map_apply_domain(map, sched);
2969 sched = node_extract_schedule(edge->dst);
2970 map = isl_map_apply_range(map, sched);
2972 test = isl_map_identity(isl_map_get_space(map));
2973 local = isl_map_is_subset(map, test);
2974 isl_map_free(map);
2975 isl_map_free(test);
2977 return local;
2980 /* For each conditional validity constraint that is adjacent
2981 * to a condition with domain in condition_source or range in condition_sink,
2982 * turn it into an unconditional validity constraint.
2984 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2985 __isl_take isl_union_set *condition_source,
2986 __isl_take isl_union_set *condition_sink)
2988 int i;
2990 condition_source = isl_union_set_coalesce(condition_source);
2991 condition_sink = isl_union_set_coalesce(condition_sink);
2993 for (i = 0; i < graph->n_edge; ++i) {
2994 int adjacent;
2995 isl_union_map *validity;
2997 if (!is_conditional_validity(&graph->edge[i]))
2998 continue;
2999 if (is_validity(&graph->edge[i]))
3000 continue;
3002 validity = graph->edge[i].tagged_validity;
3003 adjacent = domain_intersects(validity, condition_sink);
3004 if (adjacent >= 0 && !adjacent)
3005 adjacent = range_intersects(validity, condition_source);
3006 if (adjacent < 0)
3007 goto error;
3008 if (!adjacent)
3009 continue;
3011 set_validity(&graph->edge[i]);
3014 isl_union_set_free(condition_source);
3015 isl_union_set_free(condition_sink);
3016 return 0;
3017 error:
3018 isl_union_set_free(condition_source);
3019 isl_union_set_free(condition_sink);
3020 return -1;
3023 /* Update the dependence relations of all edges based on the current schedule
3024 * and enforce conditional validity constraints that are adjacent
3025 * to satisfied condition constraints.
3027 * First check if any of the condition constraints are satisfied
3028 * (i.e., not local to the outer schedule) and keep track of
3029 * their domain and range.
3030 * Then update all dependence relations (which removes the non-local
3031 * constraints).
3032 * Finally, if any condition constraints turned out to be satisfied,
3033 * then turn all adjacent conditional validity constraints into
3034 * unconditional validity constraints.
3036 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3038 int i;
3039 int any = 0;
3040 isl_union_set *source, *sink;
3042 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3043 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3044 for (i = 0; i < graph->n_edge; ++i) {
3045 int local;
3046 isl_union_set *uset;
3047 isl_union_map *umap;
3049 if (!is_condition(&graph->edge[i]))
3050 continue;
3051 if (is_local(&graph->edge[i]))
3052 continue;
3053 local = is_condition_false(&graph->edge[i]);
3054 if (local < 0)
3055 goto error;
3056 if (local)
3057 continue;
3059 any = 1;
3061 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3062 uset = isl_union_map_domain(umap);
3063 source = isl_union_set_union(source, uset);
3065 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3066 uset = isl_union_map_range(umap);
3067 sink = isl_union_set_union(sink, uset);
3070 for (i = graph->n_edge - 1; i >= 0; --i) {
3071 if (update_edge(graph, &graph->edge[i]) < 0)
3072 goto error;
3075 if (any)
3076 return unconditionalize_adjacent_validity(graph, source, sink);
3078 isl_union_set_free(source);
3079 isl_union_set_free(sink);
3080 return 0;
3081 error:
3082 isl_union_set_free(source);
3083 isl_union_set_free(sink);
3084 return -1;
3087 static void next_band(struct isl_sched_graph *graph)
3089 graph->band_start = graph->n_total_row;
3092 /* Return the union of the universe domains of the nodes in "graph"
3093 * that satisfy "pred".
3095 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3096 struct isl_sched_graph *graph,
3097 int (*pred)(struct isl_sched_node *node, int data), int data)
3099 int i;
3100 isl_set *set;
3101 isl_union_set *dom;
3103 for (i = 0; i < graph->n; ++i)
3104 if (pred(&graph->node[i], data))
3105 break;
3107 if (i >= graph->n)
3108 isl_die(ctx, isl_error_internal,
3109 "empty component", return NULL);
3111 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3112 dom = isl_union_set_from_set(set);
3114 for (i = i + 1; i < graph->n; ++i) {
3115 if (!pred(&graph->node[i], data))
3116 continue;
3117 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3118 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3121 return dom;
3124 /* Return a list of unions of universe domains, where each element
3125 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3127 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3128 struct isl_sched_graph *graph)
3130 int i;
3131 isl_union_set_list *filters;
3133 filters = isl_union_set_list_alloc(ctx, graph->scc);
3134 for (i = 0; i < graph->scc; ++i) {
3135 isl_union_set *dom;
3137 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3138 filters = isl_union_set_list_add(filters, dom);
3141 return filters;
3144 /* Return a list of two unions of universe domains, one for the SCCs up
3145 * to and including graph->src_scc and another for the other SCCs.
3147 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3148 struct isl_sched_graph *graph)
3150 isl_union_set *dom;
3151 isl_union_set_list *filters;
3153 filters = isl_union_set_list_alloc(ctx, 2);
3154 dom = isl_sched_graph_domain(ctx, graph,
3155 &node_scc_at_most, graph->src_scc);
3156 filters = isl_union_set_list_add(filters, dom);
3157 dom = isl_sched_graph_domain(ctx, graph,
3158 &node_scc_at_least, graph->src_scc + 1);
3159 filters = isl_union_set_list_add(filters, dom);
3161 return filters;
3164 /* Copy nodes that satisfy node_pred from the src dependence graph
3165 * to the dst dependence graph.
3167 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3168 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3170 int i;
3172 dst->n = 0;
3173 for (i = 0; i < src->n; ++i) {
3174 int j;
3176 if (!node_pred(&src->node[i], data))
3177 continue;
3179 j = dst->n;
3180 dst->node[j].space = isl_space_copy(src->node[i].space);
3181 dst->node[j].compressed = src->node[i].compressed;
3182 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3183 dst->node[j].compress =
3184 isl_multi_aff_copy(src->node[i].compress);
3185 dst->node[j].decompress =
3186 isl_multi_aff_copy(src->node[i].decompress);
3187 dst->node[j].nvar = src->node[i].nvar;
3188 dst->node[j].nparam = src->node[i].nparam;
3189 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3190 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3191 dst->node[j].coincident = src->node[i].coincident;
3192 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3193 dst->node[j].max = isl_vec_copy(src->node[i].max);
3194 dst->n++;
3196 if (!dst->node[j].space || !dst->node[j].sched)
3197 return -1;
3198 if (dst->node[j].compressed &&
3199 (!dst->node[j].hull || !dst->node[j].compress ||
3200 !dst->node[j].decompress))
3201 return -1;
3204 return 0;
3207 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3208 * to the dst dependence graph.
3209 * If the source or destination node of the edge is not in the destination
3210 * graph, then it must be a backward proximity edge and it should simply
3211 * be ignored.
3213 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3214 struct isl_sched_graph *src,
3215 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3217 int i;
3218 enum isl_edge_type t;
3220 dst->n_edge = 0;
3221 for (i = 0; i < src->n_edge; ++i) {
3222 struct isl_sched_edge *edge = &src->edge[i];
3223 isl_map *map;
3224 isl_union_map *tagged_condition;
3225 isl_union_map *tagged_validity;
3226 struct isl_sched_node *dst_src, *dst_dst;
3228 if (!edge_pred(edge, data))
3229 continue;
3231 if (isl_map_plain_is_empty(edge->map))
3232 continue;
3234 dst_src = graph_find_node(ctx, dst, edge->src->space);
3235 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3236 if (!dst_src || !dst_dst) {
3237 if (is_validity(edge) || is_conditional_validity(edge))
3238 isl_die(ctx, isl_error_internal,
3239 "backward (conditional) validity edge",
3240 return -1);
3241 continue;
3244 map = isl_map_copy(edge->map);
3245 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3246 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3248 dst->edge[dst->n_edge].src = dst_src;
3249 dst->edge[dst->n_edge].dst = dst_dst;
3250 dst->edge[dst->n_edge].map = map;
3251 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3252 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3253 dst->edge[dst->n_edge].types = edge->types;
3254 dst->n_edge++;
3256 if (edge->tagged_condition && !tagged_condition)
3257 return -1;
3258 if (edge->tagged_validity && !tagged_validity)
3259 return -1;
3261 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3262 if (edge !=
3263 graph_find_edge(src, t, edge->src, edge->dst))
3264 continue;
3265 if (graph_edge_table_add(ctx, dst, t,
3266 &dst->edge[dst->n_edge - 1]) < 0)
3267 return -1;
3271 return 0;
3274 /* Compute the maximal number of variables over all nodes.
3275 * This is the maximal number of linearly independent schedule
3276 * rows that we need to compute.
3277 * Just in case we end up in a part of the dependence graph
3278 * with only lower-dimensional domains, we make sure we will
3279 * compute the required amount of extra linearly independent rows.
3281 static int compute_maxvar(struct isl_sched_graph *graph)
3283 int i;
3285 graph->maxvar = 0;
3286 for (i = 0; i < graph->n; ++i) {
3287 struct isl_sched_node *node = &graph->node[i];
3288 int nvar;
3290 if (node_update_cmap(node) < 0)
3291 return -1;
3292 nvar = node->nvar + graph->n_row - node->rank;
3293 if (nvar > graph->maxvar)
3294 graph->maxvar = nvar;
3297 return 0;
3300 /* Extract the subgraph of "graph" that consists of the node satisfying
3301 * "node_pred" and the edges satisfying "edge_pred" and store
3302 * the result in "sub".
3304 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3305 int (*node_pred)(struct isl_sched_node *node, int data),
3306 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3307 int data, struct isl_sched_graph *sub)
3309 int i, n = 0, n_edge = 0;
3310 int t;
3312 for (i = 0; i < graph->n; ++i)
3313 if (node_pred(&graph->node[i], data))
3314 ++n;
3315 for (i = 0; i < graph->n_edge; ++i)
3316 if (edge_pred(&graph->edge[i], data))
3317 ++n_edge;
3318 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3319 return -1;
3320 if (copy_nodes(sub, graph, node_pred, data) < 0)
3321 return -1;
3322 if (graph_init_table(ctx, sub) < 0)
3323 return -1;
3324 for (t = 0; t <= isl_edge_last; ++t)
3325 sub->max_edge[t] = graph->max_edge[t];
3326 if (graph_init_edge_tables(ctx, sub) < 0)
3327 return -1;
3328 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3329 return -1;
3330 sub->n_row = graph->n_row;
3331 sub->max_row = graph->max_row;
3332 sub->n_total_row = graph->n_total_row;
3333 sub->band_start = graph->band_start;
3335 return 0;
3338 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3339 struct isl_sched_graph *graph);
3340 static __isl_give isl_schedule_node *compute_schedule_wcc(
3341 isl_schedule_node *node, struct isl_sched_graph *graph);
3343 /* Compute a schedule for a subgraph of "graph". In particular, for
3344 * the graph composed of nodes that satisfy node_pred and edges that
3345 * that satisfy edge_pred.
3346 * If the subgraph is known to consist of a single component, then wcc should
3347 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3348 * Otherwise, we call compute_schedule, which will check whether the subgraph
3349 * is connected.
3351 * The schedule is inserted at "node" and the updated schedule node
3352 * is returned.
3354 static __isl_give isl_schedule_node *compute_sub_schedule(
3355 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3356 struct isl_sched_graph *graph,
3357 int (*node_pred)(struct isl_sched_node *node, int data),
3358 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3359 int data, int wcc)
3361 struct isl_sched_graph split = { 0 };
3363 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3364 &split) < 0)
3365 goto error;
3367 if (wcc)
3368 node = compute_schedule_wcc(node, &split);
3369 else
3370 node = compute_schedule(node, &split);
3372 graph_free(ctx, &split);
3373 return node;
3374 error:
3375 graph_free(ctx, &split);
3376 return isl_schedule_node_free(node);
3379 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3381 return edge->src->scc == scc && edge->dst->scc == scc;
3384 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3386 return edge->dst->scc <= scc;
3389 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3391 return edge->src->scc >= scc;
3394 /* Reset the current band by dropping all its schedule rows.
3396 static int reset_band(struct isl_sched_graph *graph)
3398 int i;
3399 int drop;
3401 drop = graph->n_total_row - graph->band_start;
3402 graph->n_total_row -= drop;
3403 graph->n_row -= drop;
3405 for (i = 0; i < graph->n; ++i) {
3406 struct isl_sched_node *node = &graph->node[i];
3408 isl_map_free(node->sched_map);
3409 node->sched_map = NULL;
3411 node->sched = isl_mat_drop_rows(node->sched,
3412 graph->band_start, drop);
3414 if (!node->sched)
3415 return -1;
3418 return 0;
3421 /* Split the current graph into two parts and compute a schedule for each
3422 * part individually. In particular, one part consists of all SCCs up
3423 * to and including graph->src_scc, while the other part contains the other
3424 * SCCs. The split is enforced by a sequence node inserted at position "node"
3425 * in the schedule tree. Return the updated schedule node.
3426 * If either of these two parts consists of a sequence, then it is spliced
3427 * into the sequence containing the two parts.
3429 * The current band is reset. It would be possible to reuse
3430 * the previously computed rows as the first rows in the next
3431 * band, but recomputing them may result in better rows as we are looking
3432 * at a smaller part of the dependence graph.
3434 static __isl_give isl_schedule_node *compute_split_schedule(
3435 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3437 int is_seq;
3438 isl_ctx *ctx;
3439 isl_union_set_list *filters;
3441 if (!node)
3442 return NULL;
3444 if (reset_band(graph) < 0)
3445 return isl_schedule_node_free(node);
3447 next_band(graph);
3449 ctx = isl_schedule_node_get_ctx(node);
3450 filters = extract_split(ctx, graph);
3451 node = isl_schedule_node_insert_sequence(node, filters);
3452 node = isl_schedule_node_child(node, 1);
3453 node = isl_schedule_node_child(node, 0);
3455 node = compute_sub_schedule(node, ctx, graph,
3456 &node_scc_at_least, &edge_src_scc_at_least,
3457 graph->src_scc + 1, 0);
3458 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3459 node = isl_schedule_node_parent(node);
3460 node = isl_schedule_node_parent(node);
3461 if (is_seq)
3462 node = isl_schedule_node_sequence_splice_child(node, 1);
3463 node = isl_schedule_node_child(node, 0);
3464 node = isl_schedule_node_child(node, 0);
3465 node = compute_sub_schedule(node, ctx, graph,
3466 &node_scc_at_most, &edge_dst_scc_at_most,
3467 graph->src_scc, 0);
3468 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3469 node = isl_schedule_node_parent(node);
3470 node = isl_schedule_node_parent(node);
3471 if (is_seq)
3472 node = isl_schedule_node_sequence_splice_child(node, 0);
3474 return node;
3477 /* Insert a band node at position "node" in the schedule tree corresponding
3478 * to the current band in "graph". Mark the band node permutable
3479 * if "permutable" is set.
3480 * The partial schedules and the coincidence property are extracted
3481 * from the graph nodes.
3482 * Return the updated schedule node.
3484 static __isl_give isl_schedule_node *insert_current_band(
3485 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3486 int permutable)
3488 int i;
3489 int start, end, n;
3490 isl_multi_aff *ma;
3491 isl_multi_pw_aff *mpa;
3492 isl_multi_union_pw_aff *mupa;
3494 if (!node)
3495 return NULL;
3497 if (graph->n < 1)
3498 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3499 "graph should have at least one node",
3500 return isl_schedule_node_free(node));
3502 start = graph->band_start;
3503 end = graph->n_total_row;
3504 n = end - start;
3506 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3507 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3508 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3510 for (i = 1; i < graph->n; ++i) {
3511 isl_multi_union_pw_aff *mupa_i;
3513 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3514 start, n);
3515 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3516 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3517 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3519 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3521 for (i = 0; i < n; ++i)
3522 node = isl_schedule_node_band_member_set_coincident(node, i,
3523 graph->node[0].coincident[start + i]);
3524 node = isl_schedule_node_band_set_permutable(node, permutable);
3526 return node;
3529 /* Update the dependence relations based on the current schedule,
3530 * add the current band to "node" and then continue with the computation
3531 * of the next band.
3532 * Return the updated schedule node.
3534 static __isl_give isl_schedule_node *compute_next_band(
3535 __isl_take isl_schedule_node *node,
3536 struct isl_sched_graph *graph, int permutable)
3538 isl_ctx *ctx;
3540 if (!node)
3541 return NULL;
3543 ctx = isl_schedule_node_get_ctx(node);
3544 if (update_edges(ctx, graph) < 0)
3545 return isl_schedule_node_free(node);
3546 node = insert_current_band(node, graph, permutable);
3547 next_band(graph);
3549 node = isl_schedule_node_child(node, 0);
3550 node = compute_schedule(node, graph);
3551 node = isl_schedule_node_parent(node);
3553 return node;
3556 /* Add the constraints "coef" derived from an edge from "node" to itself
3557 * to graph->lp in order to respect the dependences and to try and carry them.
3558 * "pos" is the sequence number of the edge that needs to be carried.
3559 * "coef" represents general constraints on coefficients (c_0, c_n, c_x)
3560 * of valid constraints for (y - x) with x and y instances of the node.
3562 * The constraints added to graph->lp need to enforce
3564 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3565 * = c_j_x (y - x) >= e_i
3567 * for each (x,y) in the dependence relation of the edge.
3568 * That is, (-e_i, 0, c_j_x) needs to be plugged in for (c_0, c_n, c_x),
3569 * taking into account that each coefficient in c_j_x is represented
3570 * as a pair of non-negative coefficients.
3572 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3573 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3575 int offset;
3576 isl_ctx *ctx;
3577 isl_dim_map *dim_map;
3579 if (!coef)
3580 return isl_stat_error;
3582 ctx = isl_basic_set_get_ctx(coef);
3583 offset = coef_var_offset(coef);
3584 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3585 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3586 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3588 return isl_stat_ok;
3591 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3592 * to graph->lp in order to respect the dependences and to try and carry them.
3593 * "pos" is the sequence number of the edge that needs to be carried.
3594 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3595 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3597 * The constraints added to graph->lp need to enforce
3599 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3601 * for each (x,y) in the dependence relation of the edge.
3602 * That is,
3603 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3604 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3605 * taking into account that each coefficient in c_j_x and c_k_x is represented
3606 * as a pair of non-negative coefficients.
3608 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3609 struct isl_sched_node *src, struct isl_sched_node *dst,
3610 __isl_take isl_basic_set *coef, int pos)
3612 int offset;
3613 isl_ctx *ctx;
3614 isl_dim_map *dim_map;
3616 if (!coef)
3617 return isl_stat_error;
3619 ctx = isl_basic_set_get_ctx(coef);
3620 offset = coef_var_offset(coef);
3621 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3622 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3623 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3625 return isl_stat_ok;
3628 /* Data structure collecting information used during the construction
3629 * of an LP for carrying dependences.
3631 * "intra" is a sequence of coefficient constraints for intra-node edges.
3632 * "inter" is a sequence of coefficient constraints for inter-node edges.
3634 struct isl_carry {
3635 isl_basic_set_list *intra;
3636 isl_basic_set_list *inter;
3639 /* Free all the data stored in "carry".
3641 static void isl_carry_clear(struct isl_carry *carry)
3643 isl_basic_set_list_free(carry->intra);
3644 isl_basic_set_list_free(carry->inter);
3647 /* Return a pointer to the node in "graph" that lives in "space".
3648 * If the requested node has been compressed, then "space"
3649 * corresponds to the compressed space.
3651 * First try and see if "space" is the space of an uncompressed node.
3652 * If so, return that node.
3653 * Otherwise, "space" was constructed by construct_compressed_id and
3654 * contains a user pointer pointing to the node in the tuple id.
3656 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3657 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3659 isl_id *id;
3660 struct isl_sched_node *node;
3662 if (!space)
3663 return NULL;
3665 node = graph_find_node(ctx, graph, space);
3666 if (node)
3667 return node;
3669 id = isl_space_get_tuple_id(space, isl_dim_set);
3670 node = isl_id_get_user(id);
3671 isl_id_free(id);
3673 if (!node)
3674 return NULL;
3676 if (!(node >= &graph->node[0] && node < &graph->node[graph->n]))
3677 isl_die(ctx, isl_error_internal,
3678 "space points to invalid node", return NULL);
3680 return node;
3683 /* Internal data structure for add_all_constraints.
3685 * "graph" is the schedule constraint graph for which an LP problem
3686 * is being constructed.
3687 * "pos" is the position of the next edge that needs to be carried.
3689 struct isl_add_all_constraints_data {
3690 isl_ctx *ctx;
3691 struct isl_sched_graph *graph;
3692 int pos;
3695 /* Add the constraints "coef" derived from an edge from a node to itself
3696 * to data->graph->lp in order to respect the dependences and
3697 * to try and carry them.
3699 * The space of "coef" is of the form
3701 * coefficients[[c_cst, c_n] -> S[c_x]]
3703 * with S[c_x] the (compressed) space of the node.
3704 * Extract the node from the space and call add_intra_constraints.
3706 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3708 struct isl_add_all_constraints_data *data = user;
3709 isl_space *space;
3710 struct isl_sched_node *node;
3712 space = isl_basic_set_get_space(coef);
3713 space = isl_space_range(isl_space_unwrap(space));
3714 node = graph_find_compressed_node(data->ctx, data->graph, space);
3715 isl_space_free(space);
3716 return add_intra_constraints(data->graph, node, coef, data->pos++);
3719 /* Add the constraints "coef" derived from an edge from a node j
3720 * to a node k to data->graph->lp in order to respect the dependences and
3721 * to try and carry them.
3723 * The space of "coef" is of the form
3725 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3727 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3728 * Extract the nodes from the space and call add_inter_constraints.
3730 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3732 struct isl_add_all_constraints_data *data = user;
3733 isl_space *space, *dom;
3734 struct isl_sched_node *src, *dst;
3736 space = isl_basic_set_get_space(coef);
3737 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3738 dom = isl_space_domain(isl_space_copy(space));
3739 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3740 isl_space_free(dom);
3741 space = isl_space_range(space);
3742 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3743 isl_space_free(space);
3745 return add_inter_constraints(data->graph, src, dst, coef, data->pos++);
3748 /* Add constraints to graph->lp that force all (conditional) validity
3749 * dependences to be respected and attempt to carry them.
3750 * "intra" is the sequence of coefficient constraints for intra-node edges.
3751 * "inter" is the sequence of coefficient constraints for inter-node edges.
3753 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3754 __isl_keep isl_basic_set_list *intra,
3755 __isl_keep isl_basic_set_list *inter)
3757 struct isl_add_all_constraints_data data = { ctx, graph };
3759 data.pos = 0;
3760 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3761 return isl_stat_error;
3762 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3763 return isl_stat_error;
3764 return isl_stat_ok;
3767 /* Internal data structure for count_all_constraints
3768 * for keeping track of the number of equality and inequality constraints.
3770 struct isl_sched_count {
3771 int n_eq;
3772 int n_ineq;
3775 /* Add the number of equality and inequality constraints of "bset"
3776 * to data->n_eq and data->n_ineq.
3778 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
3780 struct isl_sched_count *data = user;
3782 data->n_eq += isl_basic_set_n_equality(bset);
3783 data->n_ineq += isl_basic_set_n_inequality(bset);
3784 isl_basic_set_free(bset);
3786 return isl_stat_ok;
3789 /* Count the number of equality and inequality constraints
3790 * that will be added to the carry_lp problem.
3791 * We count each edge exactly once.
3792 * "intra" is the sequence of coefficient constraints for intra-node edges.
3793 * "inter" is the sequence of coefficient constraints for inter-node edges.
3795 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
3796 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
3798 struct isl_sched_count data;
3800 data.n_eq = data.n_ineq = 0;
3801 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
3802 return isl_stat_error;
3803 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
3804 return isl_stat_error;
3806 *n_eq = data.n_eq;
3807 *n_ineq = data.n_ineq;
3809 return isl_stat_ok;
3812 /* Construct an LP problem for finding schedule coefficients
3813 * such that the schedule carries as many validity dependences as possible.
3814 * In particular, for each dependence i, we bound the dependence distance
3815 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3816 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3817 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3818 * "intra" is the sequence of coefficient constraints for intra-node edges.
3819 * "inter" is the sequence of coefficient constraints for inter-node edges.
3820 * "n_edge" is the total number of edges.
3822 * All variables of the LP are non-negative. The actual coefficients
3823 * may be negative, so each coefficient is represented as the difference
3824 * of two non-negative variables. The negative part always appears
3825 * immediately before the positive part.
3826 * Other than that, the variables have the following order
3828 * - sum of (1 - e_i) over all edges
3829 * - sum of all c_n coefficients
3830 * (unconstrained when computing non-parametric schedules)
3831 * - sum of positive and negative parts of all c_x coefficients
3832 * - for each edge
3833 * - e_i
3834 * - for each node
3835 * - c_i_0
3836 * - c_i_n (if parametric)
3837 * - positive and negative parts of c_i_x, in opposite order
3839 * The constraints are those from the (validity) edges plus three equalities
3840 * to express the sums and n_edge inequalities to express e_i <= 1.
3842 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
3843 int n_edge, __isl_keep isl_basic_set_list *intra,
3844 __isl_keep isl_basic_set_list *inter)
3846 int i;
3847 int k;
3848 isl_space *dim;
3849 unsigned total;
3850 int n_eq, n_ineq;
3852 total = 3 + n_edge;
3853 for (i = 0; i < graph->n; ++i) {
3854 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3855 node->start = total;
3856 total += 1 + node->nparam + 2 * node->nvar;
3859 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
3860 return isl_stat_error;
3862 dim = isl_space_set_alloc(ctx, 0, total);
3863 isl_basic_set_free(graph->lp);
3864 n_eq += 3;
3865 n_ineq += n_edge;
3866 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3867 graph->lp = isl_basic_set_set_rational(graph->lp);
3869 k = isl_basic_set_alloc_equality(graph->lp);
3870 if (k < 0)
3871 return isl_stat_error;
3872 isl_seq_clr(graph->lp->eq[k], 1 + total);
3873 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3874 isl_int_set_si(graph->lp->eq[k][1], 1);
3875 for (i = 0; i < n_edge; ++i)
3876 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3878 if (add_param_sum_constraint(graph, 1) < 0)
3879 return isl_stat_error;
3880 if (add_var_sum_constraint(graph, 2) < 0)
3881 return isl_stat_error;
3883 for (i = 0; i < n_edge; ++i) {
3884 k = isl_basic_set_alloc_inequality(graph->lp);
3885 if (k < 0)
3886 return isl_stat_error;
3887 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3888 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3889 isl_int_set_si(graph->lp->ineq[k][0], 1);
3892 if (add_all_constraints(ctx, graph, intra, inter) < 0)
3893 return isl_stat_error;
3895 return isl_stat_ok;
3898 static __isl_give isl_schedule_node *compute_component_schedule(
3899 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3900 int wcc);
3902 /* Comparison function for sorting the statements based on
3903 * the corresponding value in "r".
3905 static int smaller_value(const void *a, const void *b, void *data)
3907 isl_vec *r = data;
3908 const int *i1 = a;
3909 const int *i2 = b;
3911 return isl_int_cmp(r->el[*i1], r->el[*i2]);
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 split off the remainder of the
3917 * constant term modulo this 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 enforced
3923 * by a sequence node with the children placed in the order
3924 * of this remainder.
3925 * In particular, we assign an scc index based on the remainder and
3926 * then rely on compute_component_schedule to insert the sequence and
3927 * to continue the schedule construction on each part.
3929 static __isl_give isl_schedule_node *split_scaled(
3930 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3932 int i;
3933 int row;
3934 int scc;
3935 isl_ctx *ctx;
3936 isl_int gcd, gcd_i;
3937 isl_vec *r;
3938 int *order;
3940 if (!node)
3941 return NULL;
3943 ctx = isl_schedule_node_get_ctx(node);
3944 if (!ctx->opt->schedule_split_scaled)
3945 return compute_next_band(node, graph, 0);
3946 if (graph->n <= 1)
3947 return compute_next_band(node, graph, 0);
3949 isl_int_init(gcd);
3950 isl_int_init(gcd_i);
3952 isl_int_set_si(gcd, 0);
3954 row = isl_mat_rows(graph->node[0].sched) - 1;
3956 for (i = 0; i < graph->n; ++i) {
3957 struct isl_sched_node *node = &graph->node[i];
3958 int cols = isl_mat_cols(node->sched);
3960 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3961 isl_int_gcd(gcd, gcd, gcd_i);
3964 isl_int_clear(gcd_i);
3966 if (isl_int_cmp_si(gcd, 1) <= 0) {
3967 isl_int_clear(gcd);
3968 return compute_next_band(node, graph, 0);
3971 r = isl_vec_alloc(ctx, graph->n);
3972 order = isl_calloc_array(ctx, int, graph->n);
3973 if (!r || !order)
3974 goto error;
3976 for (i = 0; i < graph->n; ++i) {
3977 struct isl_sched_node *node = &graph->node[i];
3979 order[i] = i;
3980 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
3981 isl_int_fdiv_q(node->sched->row[row][0],
3982 node->sched->row[row][0], gcd);
3983 isl_int_mul(node->sched->row[row][0],
3984 node->sched->row[row][0], gcd);
3985 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3986 if (!node->sched)
3987 goto error;
3990 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
3991 goto error;
3993 scc = 0;
3994 for (i = 0; i < graph->n; ++i) {
3995 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
3996 ++scc;
3997 graph->node[order[i]].scc = scc;
3999 graph->scc = ++scc;
4000 graph->weak = 0;
4002 isl_int_clear(gcd);
4003 isl_vec_free(r);
4004 free(order);
4006 if (update_edges(ctx, graph) < 0)
4007 return isl_schedule_node_free(node);
4008 node = insert_current_band(node, graph, 0);
4009 next_band(graph);
4011 node = isl_schedule_node_child(node, 0);
4012 node = compute_component_schedule(node, graph, 0);
4013 node = isl_schedule_node_parent(node);
4015 return node;
4016 error:
4017 isl_vec_free(r);
4018 free(order);
4019 isl_int_clear(gcd);
4020 return isl_schedule_node_free(node);
4023 /* Is the schedule row "sol" trivial on node "node"?
4024 * That is, is the solution zero on the dimensions linearly independent of
4025 * the previously found solutions?
4026 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4028 * Each coefficient is represented as the difference between
4029 * two non-negative values in "sol".
4030 * We construct the schedule row s and check if it is linearly
4031 * independent of previously computed schedule rows
4032 * by computing T s, with T the linear combinations that are zero
4033 * on linearly dependent schedule rows.
4034 * If the result consists of all zeros, then the solution is trivial.
4036 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4038 int trivial;
4039 isl_vec *node_sol;
4041 if (!sol)
4042 return -1;
4043 if (node->nvar == node->rank)
4044 return 0;
4046 node_sol = extract_var_coef(node, sol);
4047 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4048 if (!node_sol)
4049 return -1;
4051 trivial = isl_seq_first_non_zero(node_sol->el,
4052 node->nvar - node->rank) == -1;
4054 isl_vec_free(node_sol);
4056 return trivial;
4059 /* Is the schedule row "sol" trivial on any node where it should
4060 * not be trivial?
4061 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4063 static int is_any_trivial(struct isl_sched_graph *graph,
4064 __isl_keep isl_vec *sol)
4066 int i;
4068 for (i = 0; i < graph->n; ++i) {
4069 struct isl_sched_node *node = &graph->node[i];
4070 int trivial;
4072 if (!needs_row(graph, node))
4073 continue;
4074 trivial = is_trivial(node, sol);
4075 if (trivial < 0 || trivial)
4076 return trivial;
4079 return 0;
4082 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4083 * If so, return the position of the coalesced dimension.
4084 * Otherwise, return node->nvar or -1 on error.
4086 * In particular, look for pairs of coefficients c_i and c_j such that
4087 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
4088 * If any such pair is found, then return i.
4089 * If size_i is infinity, then no check on c_i needs to be performed.
4091 static int find_node_coalescing(struct isl_sched_node *node,
4092 __isl_keep isl_vec *sol)
4094 int i, j;
4095 isl_int max;
4096 isl_vec *csol;
4098 if (node->nvar <= 1)
4099 return node->nvar;
4101 csol = extract_var_coef(node, sol);
4102 if (!csol)
4103 return -1;
4104 isl_int_init(max);
4105 for (i = 0; i < node->nvar; ++i) {
4106 isl_val *v;
4108 if (isl_int_is_zero(csol->el[i]))
4109 continue;
4110 v = isl_multi_val_get_val(node->sizes, i);
4111 if (!v)
4112 goto error;
4113 if (!isl_val_is_int(v)) {
4114 isl_val_free(v);
4115 continue;
4117 isl_int_mul(max, v->n, csol->el[i]);
4118 isl_val_free(v);
4120 for (j = 0; j < node->nvar; ++j) {
4121 if (j == i)
4122 continue;
4123 if (isl_int_abs_ge(csol->el[j], max))
4124 break;
4126 if (j < node->nvar)
4127 break;
4130 isl_int_clear(max);
4131 isl_vec_free(csol);
4132 return i;
4133 error:
4134 isl_int_clear(max);
4135 isl_vec_free(csol);
4136 return -1;
4139 /* Force the schedule coefficient at position "pos" of "node" to be zero
4140 * in "tl".
4141 * The coefficient is encoded as the difference between two non-negative
4142 * variables. Force these two variables to have the same value.
4144 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4145 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4147 int dim;
4148 isl_ctx *ctx;
4149 isl_vec *eq;
4151 ctx = isl_space_get_ctx(node->space);
4152 dim = isl_tab_lexmin_dim(tl);
4153 if (dim < 0)
4154 return isl_tab_lexmin_free(tl);
4155 eq = isl_vec_alloc(ctx, 1 + dim);
4156 eq = isl_vec_clr(eq);
4157 if (!eq)
4158 return isl_tab_lexmin_free(tl);
4160 pos = 1 + node_var_coef_pos(node, pos);
4161 isl_int_set_si(eq->el[pos], 1);
4162 isl_int_set_si(eq->el[pos + 1], -1);
4163 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4164 isl_vec_free(eq);
4166 return tl;
4169 /* Return the lexicographically smallest rational point in the basic set
4170 * from which "tl" was constructed, double checking that this input set
4171 * was not empty.
4173 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4175 isl_vec *sol;
4177 sol = isl_tab_lexmin_get_solution(tl);
4178 if (!sol)
4179 return NULL;
4180 if (sol->size == 0)
4181 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4182 "error in schedule construction",
4183 return isl_vec_free(sol));
4184 return sol;
4187 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4188 * carry any of the "n_edge" groups of dependences?
4189 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4190 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4191 * by the edge are carried by the solution.
4192 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4193 * one of those is carried.
4195 * Note that despite the fact that the problem is solved using a rational
4196 * solver, the solution is guaranteed to be integral.
4197 * Specifically, the dependence distance lower bounds e_i (and therefore
4198 * also their sum) are integers. See Lemma 5 of [1].
4200 * Any potential denominator of the sum is cleared by this function.
4201 * The denominator is not relevant for any of the other elements
4202 * in the solution.
4204 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4205 * Problem, Part II: Multi-Dimensional Time.
4206 * In Intl. Journal of Parallel Programming, 1992.
4208 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4210 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4211 isl_int_set_si(sol->el[0], 1);
4212 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4215 /* Return the lexicographically smallest rational point in "lp",
4216 * assuming that all variables are non-negative and performing some
4217 * additional sanity checks.
4218 * If "want_integral" is set, then compute the lexicographically smallest
4219 * integer point instead.
4220 * In particular, "lp" should not be empty by construction.
4221 * Double check that this is the case.
4222 * If dependences are not carried for any of the "n_edge" edges,
4223 * then return an empty vector.
4225 * If the schedule_treat_coalescing option is set and
4226 * if the computed schedule performs loop coalescing on a given node,
4227 * i.e., if it is of the form
4229 * c_i i + c_j j + ...
4231 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4232 * to cut out this solution. Repeat this process until no more loop
4233 * coalescing occurs or until no more dependences can be carried.
4234 * In the latter case, revert to the previously computed solution.
4236 * If the caller requests an integral solution and if coalescing should
4237 * be treated, then perform the coalescing treatment first as
4238 * an integral solution computed before coalescing treatment
4239 * would carry the same number of edges and would therefore probably
4240 * also be coalescing.
4242 * To allow the coalescing treatment to be performed first,
4243 * the initial solution is allowed to be rational and it is only
4244 * cut out (if needed) in the next iteration, if no coalescing measures
4245 * were taken.
4247 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4248 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4250 int i, pos, cut;
4251 isl_ctx *ctx;
4252 isl_tab_lexmin *tl;
4253 isl_vec *sol, *prev = NULL;
4254 int treat_coalescing;
4256 if (!lp)
4257 return NULL;
4258 ctx = isl_basic_set_get_ctx(lp);
4259 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4260 tl = isl_tab_lexmin_from_basic_set(lp);
4262 cut = 0;
4263 do {
4264 int integral;
4266 if (cut)
4267 tl = isl_tab_lexmin_cut_to_integer(tl);
4268 sol = non_empty_solution(tl);
4269 if (!sol)
4270 goto error;
4272 integral = isl_int_is_one(sol->el[0]);
4273 if (!carries_dependences(sol, n_edge)) {
4274 if (!prev)
4275 prev = isl_vec_alloc(ctx, 0);
4276 isl_vec_free(sol);
4277 sol = prev;
4278 break;
4280 prev = isl_vec_free(prev);
4281 cut = want_integral && !integral;
4282 if (cut)
4283 prev = sol;
4284 if (!treat_coalescing)
4285 continue;
4286 for (i = 0; i < graph->n; ++i) {
4287 struct isl_sched_node *node = &graph->node[i];
4289 pos = find_node_coalescing(node, sol);
4290 if (pos < 0)
4291 goto error;
4292 if (pos < node->nvar)
4293 break;
4295 if (i < graph->n) {
4296 prev = sol;
4297 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4298 cut = 0;
4300 } while (prev);
4302 isl_tab_lexmin_free(tl);
4304 return sol;
4305 error:
4306 isl_tab_lexmin_free(tl);
4307 isl_vec_free(prev);
4308 isl_vec_free(sol);
4309 return NULL;
4312 /* If "edge" is an edge from a node to itself, then add the corresponding
4313 * dependence relation to "umap".
4314 * If "node" has been compressed, then the dependence relation
4315 * is also compressed first.
4317 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4318 struct isl_sched_edge *edge)
4320 isl_map *map;
4321 struct isl_sched_node *node = edge->src;
4323 if (edge->src != edge->dst)
4324 return umap;
4326 map = isl_map_copy(edge->map);
4327 if (node->compressed) {
4328 map = isl_map_preimage_domain_multi_aff(map,
4329 isl_multi_aff_copy(node->decompress));
4330 map = isl_map_preimage_range_multi_aff(map,
4331 isl_multi_aff_copy(node->decompress));
4333 umap = isl_union_map_add_map(umap, map);
4334 return umap;
4337 /* If "edge" is an edge from a node to another node, then add the corresponding
4338 * dependence relation to "umap".
4339 * If the source or destination nodes of "edge" have been compressed,
4340 * then the dependence relation is also compressed first.
4342 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4343 struct isl_sched_edge *edge)
4345 isl_map *map;
4347 if (edge->src == edge->dst)
4348 return umap;
4350 map = isl_map_copy(edge->map);
4351 if (edge->src->compressed)
4352 map = isl_map_preimage_domain_multi_aff(map,
4353 isl_multi_aff_copy(edge->src->decompress));
4354 if (edge->dst->compressed)
4355 map = isl_map_preimage_range_multi_aff(map,
4356 isl_multi_aff_copy(edge->dst->decompress));
4357 umap = isl_union_map_add_map(umap, map);
4358 return umap;
4361 /* For each (conditional) validity edge in "graph",
4362 * add the corresponding dependence relation using "add"
4363 * to a collection of dependence relations and return the result.
4364 * If "coincidence" is set, then coincidence edges are considered as well.
4366 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4367 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4368 struct isl_sched_edge *edge), int coincidence)
4370 int i;
4371 isl_space *space;
4372 isl_union_map *umap;
4374 space = isl_space_copy(graph->node[0].space);
4375 umap = isl_union_map_empty(space);
4377 for (i = 0; i < graph->n_edge; ++i) {
4378 struct isl_sched_edge *edge = &graph->edge[i];
4380 if (!is_any_validity(edge) &&
4381 (!coincidence || !is_coincidence(edge)))
4382 continue;
4384 umap = add(umap, edge);
4387 return umap;
4390 /* For each dependence relation on a (conditional) validity edge
4391 * from a node to itself,
4392 * construct the set of coefficients of valid constraints for elements
4393 * in that dependence relation and collect the results.
4394 * If "coincidence" is set, then coincidence edges are considered as well.
4396 * In particular, for each dependence relation R, constraints
4397 * on coefficients (c_0, c_n, c_x) are constructed such that
4399 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4401 * This computation is essentially the same as that performed
4402 * by intra_coefficients, except that it operates on multiple
4403 * edges together.
4405 * Note that if a dependence relation is a union of basic maps,
4406 * then each basic map needs to be treated individually as it may only
4407 * be possible to carry the dependences expressed by some of those
4408 * basic maps and not all of them.
4409 * The collected validity constraints are therefore not coalesced and
4410 * it is assumed that they are not coalesced automatically.
4411 * Duplicate basic maps can be removed, however.
4412 * In particular, if the same basic map appears as a disjunct
4413 * in multiple edges, then it only needs to be carried once.
4415 static __isl_give isl_basic_set_list *collect_intra_validity(
4416 struct isl_sched_graph *graph, int coincidence)
4418 isl_union_map *intra;
4419 isl_union_set *delta;
4420 isl_basic_set_list *list;
4422 intra = collect_validity(graph, &add_intra, coincidence);
4423 delta = isl_union_map_deltas(intra);
4424 delta = isl_union_set_remove_divs(delta);
4425 list = isl_union_set_get_basic_set_list(delta);
4426 isl_union_set_free(delta);
4428 return isl_basic_set_list_coefficients(list);
4431 /* For each dependence relation on a (conditional) validity edge
4432 * from a node to some other node,
4433 * construct the set of coefficients of valid constraints for elements
4434 * in that dependence relation and collect the results.
4435 * If "coincidence" is set, then coincidence edges are considered as well.
4437 * In particular, for each dependence relation R, constraints
4438 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4440 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4442 * This computation is essentially the same as that performed
4443 * by inter_coefficients, except that it operates on multiple
4444 * edges together.
4446 * Note that if a dependence relation is a union of basic maps,
4447 * then each basic map needs to be treated individually as it may only
4448 * be possible to carry the dependences expressed by some of those
4449 * basic maps and not all of them.
4450 * The collected validity constraints are therefore not coalesced and
4451 * it is assumed that they are not coalesced automatically.
4452 * Duplicate basic maps can be removed, however.
4453 * In particular, if the same basic map appears as a disjunct
4454 * in multiple edges, then it only needs to be carried once.
4456 static __isl_give isl_basic_set_list *collect_inter_validity(
4457 struct isl_sched_graph *graph, int coincidence)
4459 isl_union_map *inter;
4460 isl_union_set *wrap;
4461 isl_basic_set_list *list;
4463 inter = collect_validity(graph, &add_inter, coincidence);
4464 inter = isl_union_map_remove_divs(inter);
4465 wrap = isl_union_map_wrap(inter);
4466 list = isl_union_set_get_basic_set_list(wrap);
4467 isl_union_set_free(wrap);
4468 return isl_basic_set_list_coefficients(list);
4471 /* Construct an LP problem for finding schedule coefficients
4472 * such that the schedule carries as many of the validity dependences
4473 * as possible and
4474 * return the lexicographically smallest non-trivial solution.
4475 * If "fallback" is set, then the carrying is performed as a fallback
4476 * for the Pluto-like scheduler.
4477 * If "coincidence" is set, then try and carry coincidence edges as well.
4479 * The variable "n_edge" stores the number of groups that should be carried.
4480 * If none of the "n_edge" groups can be carried
4481 * then return an empty vector.
4482 * If, moreover, "n_edge" is zero, then the LP problem does not even
4483 * need to be constructed.
4485 * If a fallback solution is being computed, then compute an integral solution
4486 * for the coefficients rather than using the numerators
4487 * of a rational solution.
4489 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4490 struct isl_sched_graph *graph, int fallback, int coincidence)
4492 int n_intra, n_inter;
4493 int n_edge;
4494 isl_basic_set *lp;
4495 struct isl_carry carry = { 0 };
4497 carry.intra = collect_intra_validity(graph, coincidence);
4498 carry.inter = collect_inter_validity(graph, coincidence);
4499 if (!carry.intra || !carry.inter)
4500 goto error;
4501 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4502 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4503 n_edge = n_intra + n_inter;
4504 if (n_edge == 0) {
4505 isl_carry_clear(&carry);
4506 return isl_vec_alloc(ctx, 0);
4509 if (setup_carry_lp(ctx, graph, n_edge, carry.intra, carry.inter) < 0)
4510 goto error;
4512 isl_carry_clear(&carry);
4513 lp = isl_basic_set_copy(graph->lp);
4514 return non_neg_lexmin(graph, lp, n_edge, fallback);
4515 error:
4516 isl_carry_clear(&carry);
4517 return NULL;
4520 /* Construct a schedule row for each node such that as many validity dependences
4521 * as possible are carried and then continue with the next band.
4522 * If "fallback" is set, then the carrying is performed as a fallback
4523 * for the Pluto-like scheduler.
4524 * If "coincidence" is set, then try and carry coincidence edges as well.
4526 * If there are no validity dependences, then no dependence can be carried and
4527 * the procedure is guaranteed to fail. If there is more than one component,
4528 * then try computing a schedule on each component separately
4529 * to prevent or at least postpone this failure.
4531 * If a schedule row is computed, then check that dependences are carried
4532 * for at least one of the edges.
4534 * If the computed schedule row turns out to be trivial on one or
4535 * more nodes where it should not be trivial, then we throw it away
4536 * and try again on each component separately.
4538 * If there is only one component, then we accept the schedule row anyway,
4539 * but we do not consider it as a complete row and therefore do not
4540 * increment graph->n_row. Note that the ranks of the nodes that
4541 * do get a non-trivial schedule part will get updated regardless and
4542 * graph->maxvar is computed based on these ranks. The test for
4543 * whether more schedule rows are required in compute_schedule_wcc
4544 * is therefore not affected.
4546 * Insert a band corresponding to the schedule row at position "node"
4547 * of the schedule tree and continue with the construction of the schedule.
4548 * This insertion and the continued construction is performed by split_scaled
4549 * after optionally checking for non-trivial common divisors.
4551 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
4552 struct isl_sched_graph *graph, int fallback, int coincidence)
4554 int trivial;
4555 isl_ctx *ctx;
4556 isl_vec *sol;
4558 if (!node)
4559 return NULL;
4561 ctx = isl_schedule_node_get_ctx(node);
4562 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
4563 if (!sol)
4564 return isl_schedule_node_free(node);
4565 if (sol->size == 0) {
4566 isl_vec_free(sol);
4567 if (graph->scc > 1)
4568 return compute_component_schedule(node, graph, 1);
4569 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
4570 return isl_schedule_node_free(node));
4573 trivial = is_any_trivial(graph, sol);
4574 if (trivial < 0) {
4575 sol = isl_vec_free(sol);
4576 } else if (trivial && graph->scc > 1) {
4577 isl_vec_free(sol);
4578 return compute_component_schedule(node, graph, 1);
4581 if (update_schedule(graph, sol, 0) < 0)
4582 return isl_schedule_node_free(node);
4583 if (trivial)
4584 graph->n_row--;
4586 return split_scaled(node, graph);
4589 /* Construct a schedule row for each node such that as many validity dependences
4590 * as possible are carried and then continue with the next band.
4591 * Do so as a fallback for the Pluto-like scheduler.
4592 * If "coincidence" is set, then try and carry coincidence edges as well.
4594 static __isl_give isl_schedule_node *carry_fallback(
4595 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4596 int coincidence)
4598 return carry(node, graph, 1, coincidence);
4601 /* Construct a schedule row for each node such that as many validity dependences
4602 * as possible are carried and then continue with the next band.
4603 * Do so for the case where the Feautrier scheduler was selected
4604 * by the user.
4606 static __isl_give isl_schedule_node *carry_feautrier(
4607 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4609 return carry(node, graph, 0, 0);
4612 /* Construct a schedule row for each node such that as many validity dependences
4613 * as possible are carried and then continue with the next band.
4614 * Do so as a fallback for the Pluto-like scheduler.
4616 static __isl_give isl_schedule_node *carry_dependences(
4617 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4619 return carry_fallback(node, graph, 0);
4622 /* Construct a schedule row for each node such that as many validity or
4623 * coincidence dependences as possible are carried and
4624 * then continue with the next band.
4625 * Do so as a fallback for the Pluto-like scheduler.
4627 static __isl_give isl_schedule_node *carry_coincidence(
4628 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4630 return carry_fallback(node, graph, 1);
4633 /* Topologically sort statements mapped to the same schedule iteration
4634 * and add insert a sequence node in front of "node"
4635 * corresponding to this order.
4636 * If "initialized" is set, then it may be assumed that compute_maxvar
4637 * has been called on the current band. Otherwise, call
4638 * compute_maxvar if and before carry_dependences gets called.
4640 * If it turns out to be impossible to sort the statements apart,
4641 * because different dependences impose different orderings
4642 * on the statements, then we extend the schedule such that
4643 * it carries at least one more dependence.
4645 static __isl_give isl_schedule_node *sort_statements(
4646 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4647 int initialized)
4649 isl_ctx *ctx;
4650 isl_union_set_list *filters;
4652 if (!node)
4653 return NULL;
4655 ctx = isl_schedule_node_get_ctx(node);
4656 if (graph->n < 1)
4657 isl_die(ctx, isl_error_internal,
4658 "graph should have at least one node",
4659 return isl_schedule_node_free(node));
4661 if (graph->n == 1)
4662 return node;
4664 if (update_edges(ctx, graph) < 0)
4665 return isl_schedule_node_free(node);
4667 if (graph->n_edge == 0)
4668 return node;
4670 if (detect_sccs(ctx, graph) < 0)
4671 return isl_schedule_node_free(node);
4673 next_band(graph);
4674 if (graph->scc < graph->n) {
4675 if (!initialized && compute_maxvar(graph) < 0)
4676 return isl_schedule_node_free(node);
4677 return carry_dependences(node, graph);
4680 filters = extract_sccs(ctx, graph);
4681 node = isl_schedule_node_insert_sequence(node, filters);
4683 return node;
4686 /* Are there any (non-empty) (conditional) validity edges in the graph?
4688 static int has_validity_edges(struct isl_sched_graph *graph)
4690 int i;
4692 for (i = 0; i < graph->n_edge; ++i) {
4693 int empty;
4695 empty = isl_map_plain_is_empty(graph->edge[i].map);
4696 if (empty < 0)
4697 return -1;
4698 if (empty)
4699 continue;
4700 if (is_any_validity(&graph->edge[i]))
4701 return 1;
4704 return 0;
4707 /* Should we apply a Feautrier step?
4708 * That is, did the user request the Feautrier algorithm and are
4709 * there any validity dependences (left)?
4711 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4713 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4714 return 0;
4716 return has_validity_edges(graph);
4719 /* Compute a schedule for a connected dependence graph using Feautrier's
4720 * multi-dimensional scheduling algorithm and return the updated schedule node.
4722 * The original algorithm is described in [1].
4723 * The main idea is to minimize the number of scheduling dimensions, by
4724 * trying to satisfy as many dependences as possible per scheduling dimension.
4726 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4727 * Problem, Part II: Multi-Dimensional Time.
4728 * In Intl. Journal of Parallel Programming, 1992.
4730 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4731 isl_schedule_node *node, struct isl_sched_graph *graph)
4733 return carry_feautrier(node, graph);
4736 /* Turn off the "local" bit on all (condition) edges.
4738 static void clear_local_edges(struct isl_sched_graph *graph)
4740 int i;
4742 for (i = 0; i < graph->n_edge; ++i)
4743 if (is_condition(&graph->edge[i]))
4744 clear_local(&graph->edge[i]);
4747 /* Does "graph" have both condition and conditional validity edges?
4749 static int need_condition_check(struct isl_sched_graph *graph)
4751 int i;
4752 int any_condition = 0;
4753 int any_conditional_validity = 0;
4755 for (i = 0; i < graph->n_edge; ++i) {
4756 if (is_condition(&graph->edge[i]))
4757 any_condition = 1;
4758 if (is_conditional_validity(&graph->edge[i]))
4759 any_conditional_validity = 1;
4762 return any_condition && any_conditional_validity;
4765 /* Does "graph" contain any coincidence edge?
4767 static int has_any_coincidence(struct isl_sched_graph *graph)
4769 int i;
4771 for (i = 0; i < graph->n_edge; ++i)
4772 if (is_coincidence(&graph->edge[i]))
4773 return 1;
4775 return 0;
4778 /* Extract the final schedule row as a map with the iteration domain
4779 * of "node" as domain.
4781 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4783 isl_multi_aff *ma;
4784 int row;
4786 row = isl_mat_rows(node->sched) - 1;
4787 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
4788 return isl_map_from_multi_aff(ma);
4791 /* Is the conditional validity dependence in the edge with index "edge_index"
4792 * violated by the latest (i.e., final) row of the schedule?
4793 * That is, is i scheduled after j
4794 * for any conditional validity dependence i -> j?
4796 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4798 isl_map *src_sched, *dst_sched, *map;
4799 struct isl_sched_edge *edge = &graph->edge[edge_index];
4800 int empty;
4802 src_sched = final_row(edge->src);
4803 dst_sched = final_row(edge->dst);
4804 map = isl_map_copy(edge->map);
4805 map = isl_map_apply_domain(map, src_sched);
4806 map = isl_map_apply_range(map, dst_sched);
4807 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4808 empty = isl_map_is_empty(map);
4809 isl_map_free(map);
4811 if (empty < 0)
4812 return -1;
4814 return !empty;
4817 /* Does "graph" have any satisfied condition edges that
4818 * are adjacent to the conditional validity constraint with
4819 * domain "conditional_source" and range "conditional_sink"?
4821 * A satisfied condition is one that is not local.
4822 * If a condition was forced to be local already (i.e., marked as local)
4823 * then there is no need to check if it is in fact local.
4825 * Additionally, mark all adjacent condition edges found as local.
4827 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4828 __isl_keep isl_union_set *conditional_source,
4829 __isl_keep isl_union_set *conditional_sink)
4831 int i;
4832 int any = 0;
4834 for (i = 0; i < graph->n_edge; ++i) {
4835 int adjacent, local;
4836 isl_union_map *condition;
4838 if (!is_condition(&graph->edge[i]))
4839 continue;
4840 if (is_local(&graph->edge[i]))
4841 continue;
4843 condition = graph->edge[i].tagged_condition;
4844 adjacent = domain_intersects(condition, conditional_sink);
4845 if (adjacent >= 0 && !adjacent)
4846 adjacent = range_intersects(condition,
4847 conditional_source);
4848 if (adjacent < 0)
4849 return -1;
4850 if (!adjacent)
4851 continue;
4853 set_local(&graph->edge[i]);
4855 local = is_condition_false(&graph->edge[i]);
4856 if (local < 0)
4857 return -1;
4858 if (!local)
4859 any = 1;
4862 return any;
4865 /* Are there any violated conditional validity dependences with
4866 * adjacent condition dependences that are not local with respect
4867 * to the current schedule?
4868 * That is, is the conditional validity constraint violated?
4870 * Additionally, mark all those adjacent condition dependences as local.
4871 * We also mark those adjacent condition dependences that were not marked
4872 * as local before, but just happened to be local already. This ensures
4873 * that they remain local if the schedule is recomputed.
4875 * We first collect domain and range of all violated conditional validity
4876 * dependences and then check if there are any adjacent non-local
4877 * condition dependences.
4879 static int has_violated_conditional_constraint(isl_ctx *ctx,
4880 struct isl_sched_graph *graph)
4882 int i;
4883 int any = 0;
4884 isl_union_set *source, *sink;
4886 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4887 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4888 for (i = 0; i < graph->n_edge; ++i) {
4889 isl_union_set *uset;
4890 isl_union_map *umap;
4891 int violated;
4893 if (!is_conditional_validity(&graph->edge[i]))
4894 continue;
4896 violated = is_violated(graph, i);
4897 if (violated < 0)
4898 goto error;
4899 if (!violated)
4900 continue;
4902 any = 1;
4904 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4905 uset = isl_union_map_domain(umap);
4906 source = isl_union_set_union(source, uset);
4907 source = isl_union_set_coalesce(source);
4909 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4910 uset = isl_union_map_range(umap);
4911 sink = isl_union_set_union(sink, uset);
4912 sink = isl_union_set_coalesce(sink);
4915 if (any)
4916 any = has_adjacent_true_conditions(graph, source, sink);
4918 isl_union_set_free(source);
4919 isl_union_set_free(sink);
4920 return any;
4921 error:
4922 isl_union_set_free(source);
4923 isl_union_set_free(sink);
4924 return -1;
4927 /* Examine the current band (the rows between graph->band_start and
4928 * graph->n_total_row), deciding whether to drop it or add it to "node"
4929 * and then continue with the computation of the next band, if any.
4930 * If "initialized" is set, then it may be assumed that compute_maxvar
4931 * has been called on the current band. Otherwise, call
4932 * compute_maxvar if and before carry_dependences gets called.
4934 * The caller keeps looking for a new row as long as
4935 * graph->n_row < graph->maxvar. If the latest attempt to find
4936 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4937 * then we either
4938 * - split between SCCs and start over (assuming we found an interesting
4939 * pair of SCCs between which to split)
4940 * - continue with the next band (assuming the current band has at least
4941 * one row)
4942 * - if outer coincidence needs to be enforced, then try to carry as many
4943 * validity or coincidence dependences as possible and
4944 * continue with the next band
4945 * - try to carry as many validity dependences as possible and
4946 * continue with the next band
4947 * In each case, we first insert a band node in the schedule tree
4948 * if any rows have been computed.
4950 * If the caller managed to complete the schedule, we insert a band node
4951 * (if any schedule rows were computed) and we finish off by topologically
4952 * sorting the statements based on the remaining dependences.
4954 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4955 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4956 int initialized)
4958 int insert;
4960 if (!node)
4961 return NULL;
4963 if (graph->n_row < graph->maxvar) {
4964 isl_ctx *ctx;
4965 int empty = graph->n_total_row == graph->band_start;
4967 ctx = isl_schedule_node_get_ctx(node);
4968 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4969 return compute_next_band(node, graph, 1);
4970 if (graph->src_scc >= 0)
4971 return compute_split_schedule(node, graph);
4972 if (!empty)
4973 return compute_next_band(node, graph, 1);
4974 if (!initialized && compute_maxvar(graph) < 0)
4975 return isl_schedule_node_free(node);
4976 if (isl_options_get_schedule_outer_coincidence(ctx))
4977 return carry_coincidence(node, graph);
4978 return carry_dependences(node, graph);
4981 insert = graph->n_total_row > graph->band_start;
4982 if (insert) {
4983 node = insert_current_band(node, graph, 1);
4984 node = isl_schedule_node_child(node, 0);
4986 node = sort_statements(node, graph, initialized);
4987 if (insert)
4988 node = isl_schedule_node_parent(node);
4990 return node;
4993 /* Construct a band of schedule rows for a connected dependence graph.
4994 * The caller is responsible for determining the strongly connected
4995 * components and calling compute_maxvar first.
4997 * We try to find a sequence of as many schedule rows as possible that result
4998 * in non-negative dependence distances (independent of the previous rows
4999 * in the sequence, i.e., such that the sequence is tilable), with as
5000 * many of the initial rows as possible satisfying the coincidence constraints.
5001 * The computation stops if we can't find any more rows or if we have found
5002 * all the rows we wanted to find.
5004 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5005 * outermost dimension to satisfy the coincidence constraints. If this
5006 * turns out to be impossible, we fall back on the general scheme above
5007 * and try to carry as many dependences as possible.
5009 * If "graph" contains both condition and conditional validity dependences,
5010 * then we need to check that that the conditional schedule constraint
5011 * is satisfied, i.e., there are no violated conditional validity dependences
5012 * that are adjacent to any non-local condition dependences.
5013 * If there are, then we mark all those adjacent condition dependences
5014 * as local and recompute the current band. Those dependences that
5015 * are marked local will then be forced to be local.
5016 * The initial computation is performed with no dependences marked as local.
5017 * If we are lucky, then there will be no violated conditional validity
5018 * dependences adjacent to any non-local condition dependences.
5019 * Otherwise, we mark some additional condition dependences as local and
5020 * recompute. We continue this process until there are no violations left or
5021 * until we are no longer able to compute a schedule.
5022 * Since there are only a finite number of dependences,
5023 * there will only be a finite number of iterations.
5025 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5026 struct isl_sched_graph *graph)
5028 int has_coincidence;
5029 int use_coincidence;
5030 int force_coincidence = 0;
5031 int check_conditional;
5033 if (sort_sccs(graph) < 0)
5034 return isl_stat_error;
5036 clear_local_edges(graph);
5037 check_conditional = need_condition_check(graph);
5038 has_coincidence = has_any_coincidence(graph);
5040 if (ctx->opt->schedule_outer_coincidence)
5041 force_coincidence = 1;
5043 use_coincidence = has_coincidence;
5044 while (graph->n_row < graph->maxvar) {
5045 isl_vec *sol;
5046 int violated;
5047 int coincident;
5049 graph->src_scc = -1;
5050 graph->dst_scc = -1;
5052 if (setup_lp(ctx, graph, use_coincidence) < 0)
5053 return isl_stat_error;
5054 sol = solve_lp(ctx, graph);
5055 if (!sol)
5056 return isl_stat_error;
5057 if (sol->size == 0) {
5058 int empty = graph->n_total_row == graph->band_start;
5060 isl_vec_free(sol);
5061 if (use_coincidence && (!force_coincidence || !empty)) {
5062 use_coincidence = 0;
5063 continue;
5065 return isl_stat_ok;
5067 coincident = !has_coincidence || use_coincidence;
5068 if (update_schedule(graph, sol, coincident) < 0)
5069 return isl_stat_error;
5071 if (!check_conditional)
5072 continue;
5073 violated = has_violated_conditional_constraint(ctx, graph);
5074 if (violated < 0)
5075 return isl_stat_error;
5076 if (!violated)
5077 continue;
5078 if (reset_band(graph) < 0)
5079 return isl_stat_error;
5080 use_coincidence = has_coincidence;
5083 return isl_stat_ok;
5086 /* Compute a schedule for a connected dependence graph by considering
5087 * the graph as a whole and return the updated schedule node.
5089 * The actual schedule rows of the current band are computed by
5090 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5091 * care of integrating the band into "node" and continuing
5092 * the computation.
5094 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5095 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5097 isl_ctx *ctx;
5099 if (!node)
5100 return NULL;
5102 ctx = isl_schedule_node_get_ctx(node);
5103 if (compute_schedule_wcc_band(ctx, graph) < 0)
5104 return isl_schedule_node_free(node);
5106 return compute_schedule_finish_band(node, graph, 1);
5109 /* Clustering information used by compute_schedule_wcc_clustering.
5111 * "n" is the number of SCCs in the original dependence graph
5112 * "scc" is an array of "n" elements, each representing an SCC
5113 * of the original dependence graph. All entries in the same cluster
5114 * have the same number of schedule rows.
5115 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5116 * where each cluster is represented by the index of the first SCC
5117 * in the cluster. Initially, each SCC belongs to a cluster containing
5118 * only that SCC.
5120 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5121 * track of which SCCs need to be merged.
5123 * "cluster" contains the merged clusters of SCCs after the clustering
5124 * has completed.
5126 * "scc_node" is a temporary data structure used inside copy_partial.
5127 * For each SCC, it keeps track of the number of nodes in the SCC
5128 * that have already been copied.
5130 struct isl_clustering {
5131 int n;
5132 struct isl_sched_graph *scc;
5133 struct isl_sched_graph *cluster;
5134 int *scc_cluster;
5135 int *scc_node;
5136 int *scc_in_merge;
5139 /* Initialize the clustering data structure "c" from "graph".
5141 * In particular, allocate memory, extract the SCCs from "graph"
5142 * into c->scc, initialize scc_cluster and construct
5143 * a band of schedule rows for each SCC.
5144 * Within each SCC, there is only one SCC by definition.
5145 * Each SCC initially belongs to a cluster containing only that SCC.
5147 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5148 struct isl_sched_graph *graph)
5150 int i;
5152 c->n = graph->scc;
5153 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5154 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5155 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5156 c->scc_node = isl_calloc_array(ctx, int, c->n);
5157 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5158 if (!c->scc || !c->cluster ||
5159 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5160 return isl_stat_error;
5162 for (i = 0; i < c->n; ++i) {
5163 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5164 &edge_scc_exactly, i, &c->scc[i]) < 0)
5165 return isl_stat_error;
5166 c->scc[i].scc = 1;
5167 if (compute_maxvar(&c->scc[i]) < 0)
5168 return isl_stat_error;
5169 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5170 return isl_stat_error;
5171 c->scc_cluster[i] = i;
5174 return isl_stat_ok;
5177 /* Free all memory allocated for "c".
5179 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5181 int i;
5183 if (c->scc)
5184 for (i = 0; i < c->n; ++i)
5185 graph_free(ctx, &c->scc[i]);
5186 free(c->scc);
5187 if (c->cluster)
5188 for (i = 0; i < c->n; ++i)
5189 graph_free(ctx, &c->cluster[i]);
5190 free(c->cluster);
5191 free(c->scc_cluster);
5192 free(c->scc_node);
5193 free(c->scc_in_merge);
5196 /* Should we refrain from merging the cluster in "graph" with
5197 * any other cluster?
5198 * In particular, is its current schedule band empty and incomplete.
5200 static int bad_cluster(struct isl_sched_graph *graph)
5202 return graph->n_row < graph->maxvar &&
5203 graph->n_total_row == graph->band_start;
5206 /* Is "edge" a proximity edge with a non-empty dependence relation?
5208 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5210 if (!is_proximity(edge))
5211 return isl_bool_false;
5212 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5215 /* Return the index of an edge in "graph" that can be used to merge
5216 * two clusters in "c".
5217 * Return graph->n_edge if no such edge can be found.
5218 * Return -1 on error.
5220 * In particular, return a proximity edge between two clusters
5221 * that is not marked "no_merge" and such that neither of the
5222 * two clusters has an incomplete, empty band.
5224 * If there are multiple such edges, then try and find the most
5225 * appropriate edge to use for merging. In particular, pick the edge
5226 * with the greatest weight. If there are multiple of those,
5227 * then pick one with the shortest distance between
5228 * the two cluster representatives.
5230 static int find_proximity(struct isl_sched_graph *graph,
5231 struct isl_clustering *c)
5233 int i, best = graph->n_edge, best_dist, best_weight;
5235 for (i = 0; i < graph->n_edge; ++i) {
5236 struct isl_sched_edge *edge = &graph->edge[i];
5237 int dist, weight;
5238 isl_bool prox;
5240 prox = is_non_empty_proximity(edge);
5241 if (prox < 0)
5242 return -1;
5243 if (!prox)
5244 continue;
5245 if (edge->no_merge)
5246 continue;
5247 if (bad_cluster(&c->scc[edge->src->scc]) ||
5248 bad_cluster(&c->scc[edge->dst->scc]))
5249 continue;
5250 dist = c->scc_cluster[edge->dst->scc] -
5251 c->scc_cluster[edge->src->scc];
5252 if (dist == 0)
5253 continue;
5254 weight = edge->weight;
5255 if (best < graph->n_edge) {
5256 if (best_weight > weight)
5257 continue;
5258 if (best_weight == weight && best_dist <= dist)
5259 continue;
5261 best = i;
5262 best_dist = dist;
5263 best_weight = weight;
5266 return best;
5269 /* Internal data structure used in mark_merge_sccs.
5271 * "graph" is the dependence graph in which a strongly connected
5272 * component is constructed.
5273 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5274 * "src" and "dst" are the indices of the nodes that are being merged.
5276 struct isl_mark_merge_sccs_data {
5277 struct isl_sched_graph *graph;
5278 int *scc_cluster;
5279 int src;
5280 int dst;
5283 /* Check whether the cluster containing node "i" depends on the cluster
5284 * containing node "j". If "i" and "j" belong to the same cluster,
5285 * then they are taken to depend on each other to ensure that
5286 * the resulting strongly connected component consists of complete
5287 * clusters. Furthermore, if "i" and "j" are the two nodes that
5288 * are being merged, then they are taken to depend on each other as well.
5289 * Otherwise, check if there is a (conditional) validity dependence
5290 * from node[j] to node[i], forcing node[i] to follow node[j].
5292 static isl_bool cluster_follows(int i, int j, void *user)
5294 struct isl_mark_merge_sccs_data *data = user;
5295 struct isl_sched_graph *graph = data->graph;
5296 int *scc_cluster = data->scc_cluster;
5298 if (data->src == i && data->dst == j)
5299 return isl_bool_true;
5300 if (data->src == j && data->dst == i)
5301 return isl_bool_true;
5302 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5303 return isl_bool_true;
5305 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5308 /* Mark all SCCs that belong to either of the two clusters in "c"
5309 * connected by the edge in "graph" with index "edge", or to any
5310 * of the intermediate clusters.
5311 * The marking is recorded in c->scc_in_merge.
5313 * The given edge has been selected for merging two clusters,
5314 * meaning that there is at least a proximity edge between the two nodes.
5315 * However, there may also be (indirect) validity dependences
5316 * between the two nodes. When merging the two clusters, all clusters
5317 * containing one or more of the intermediate nodes along the
5318 * indirect validity dependences need to be merged in as well.
5320 * First collect all such nodes by computing the strongly connected
5321 * component (SCC) containing the two nodes connected by the edge, where
5322 * the two nodes are considered to depend on each other to make
5323 * sure they end up in the same SCC. Similarly, each node is considered
5324 * to depend on every other node in the same cluster to ensure
5325 * that the SCC consists of complete clusters.
5327 * Then the original SCCs that contain any of these nodes are marked
5328 * in c->scc_in_merge.
5330 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5331 int edge, struct isl_clustering *c)
5333 struct isl_mark_merge_sccs_data data;
5334 struct isl_tarjan_graph *g;
5335 int i;
5337 for (i = 0; i < c->n; ++i)
5338 c->scc_in_merge[i] = 0;
5340 data.graph = graph;
5341 data.scc_cluster = c->scc_cluster;
5342 data.src = graph->edge[edge].src - graph->node;
5343 data.dst = graph->edge[edge].dst - graph->node;
5345 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5346 &cluster_follows, &data);
5347 if (!g)
5348 goto error;
5350 i = g->op;
5351 if (i < 3)
5352 isl_die(ctx, isl_error_internal,
5353 "expecting at least two nodes in component",
5354 goto error);
5355 if (g->order[--i] != -1)
5356 isl_die(ctx, isl_error_internal,
5357 "expecting end of component marker", goto error);
5359 for (--i; i >= 0 && g->order[i] != -1; --i) {
5360 int scc = graph->node[g->order[i]].scc;
5361 c->scc_in_merge[scc] = 1;
5364 isl_tarjan_graph_free(g);
5365 return isl_stat_ok;
5366 error:
5367 isl_tarjan_graph_free(g);
5368 return isl_stat_error;
5371 /* Construct the identifier "cluster_i".
5373 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5375 char name[40];
5377 snprintf(name, sizeof(name), "cluster_%d", i);
5378 return isl_id_alloc(ctx, name, NULL);
5381 /* Construct the space of the cluster with index "i" containing
5382 * the strongly connected component "scc".
5384 * In particular, construct a space called cluster_i with dimension equal
5385 * to the number of schedule rows in the current band of "scc".
5387 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5389 int nvar;
5390 isl_space *space;
5391 isl_id *id;
5393 nvar = scc->n_total_row - scc->band_start;
5394 space = isl_space_copy(scc->node[0].space);
5395 space = isl_space_params(space);
5396 space = isl_space_set_from_params(space);
5397 space = isl_space_add_dims(space, isl_dim_set, nvar);
5398 id = cluster_id(isl_space_get_ctx(space), i);
5399 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5401 return space;
5404 /* Collect the domain of the graph for merging clusters.
5406 * In particular, for each cluster with first SCC "i", construct
5407 * a set in the space called cluster_i with dimension equal
5408 * to the number of schedule rows in the current band of the cluster.
5410 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5411 struct isl_sched_graph *graph, struct isl_clustering *c)
5413 int i;
5414 isl_space *space;
5415 isl_union_set *domain;
5417 space = isl_space_params_alloc(ctx, 0);
5418 domain = isl_union_set_empty(space);
5420 for (i = 0; i < graph->scc; ++i) {
5421 isl_space *space;
5423 if (!c->scc_in_merge[i])
5424 continue;
5425 if (c->scc_cluster[i] != i)
5426 continue;
5427 space = cluster_space(&c->scc[i], i);
5428 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5431 return domain;
5434 /* Construct a map from the original instances to the corresponding
5435 * cluster instance in the current bands of the clusters in "c".
5437 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5438 struct isl_sched_graph *graph, struct isl_clustering *c)
5440 int i, j;
5441 isl_space *space;
5442 isl_union_map *cluster_map;
5444 space = isl_space_params_alloc(ctx, 0);
5445 cluster_map = isl_union_map_empty(space);
5446 for (i = 0; i < graph->scc; ++i) {
5447 int start, n;
5448 isl_id *id;
5450 if (!c->scc_in_merge[i])
5451 continue;
5453 id = cluster_id(ctx, c->scc_cluster[i]);
5454 start = c->scc[i].band_start;
5455 n = c->scc[i].n_total_row - start;
5456 for (j = 0; j < c->scc[i].n; ++j) {
5457 isl_multi_aff *ma;
5458 isl_map *map;
5459 struct isl_sched_node *node = &c->scc[i].node[j];
5461 ma = node_extract_partial_schedule_multi_aff(node,
5462 start, n);
5463 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5464 isl_id_copy(id));
5465 map = isl_map_from_multi_aff(ma);
5466 cluster_map = isl_union_map_add_map(cluster_map, map);
5468 isl_id_free(id);
5471 return cluster_map;
5474 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5475 * that are not isl_edge_condition or isl_edge_conditional_validity.
5477 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5478 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5479 __isl_take isl_schedule_constraints *sc)
5481 enum isl_edge_type t;
5483 if (!sc)
5484 return NULL;
5486 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5487 if (t == isl_edge_condition ||
5488 t == isl_edge_conditional_validity)
5489 continue;
5490 if (!is_type(edge, t))
5491 continue;
5492 sc = isl_schedule_constraints_add(sc, t,
5493 isl_union_map_copy(umap));
5496 return sc;
5499 /* Add schedule constraints of types isl_edge_condition and
5500 * isl_edge_conditional_validity to "sc" by applying "umap" to
5501 * the domains of the wrapped relations in domain and range
5502 * of the corresponding tagged constraints of "edge".
5504 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5505 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5506 __isl_take isl_schedule_constraints *sc)
5508 enum isl_edge_type t;
5509 isl_union_map *tagged;
5511 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5512 if (!is_type(edge, t))
5513 continue;
5514 if (t == isl_edge_condition)
5515 tagged = isl_union_map_copy(edge->tagged_condition);
5516 else
5517 tagged = isl_union_map_copy(edge->tagged_validity);
5518 tagged = isl_union_map_zip(tagged);
5519 tagged = isl_union_map_apply_domain(tagged,
5520 isl_union_map_copy(umap));
5521 tagged = isl_union_map_zip(tagged);
5522 sc = isl_schedule_constraints_add(sc, t, tagged);
5523 if (!sc)
5524 return NULL;
5527 return sc;
5530 /* Given a mapping "cluster_map" from the original instances to
5531 * the cluster instances, add schedule constraints on the clusters
5532 * to "sc" corresponding to the original constraints represented by "edge".
5534 * For non-tagged dependence constraints, the cluster constraints
5535 * are obtained by applying "cluster_map" to the edge->map.
5537 * For tagged dependence constraints, "cluster_map" needs to be applied
5538 * to the domains of the wrapped relations in domain and range
5539 * of the tagged dependence constraints. Pick out the mappings
5540 * from these domains from "cluster_map" and construct their product.
5541 * This mapping can then be applied to the pair of domains.
5543 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5544 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5545 __isl_take isl_schedule_constraints *sc)
5547 isl_union_map *umap;
5548 isl_space *space;
5549 isl_union_set *uset;
5550 isl_union_map *umap1, *umap2;
5552 if (!sc)
5553 return NULL;
5555 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5556 umap = isl_union_map_apply_domain(umap,
5557 isl_union_map_copy(cluster_map));
5558 umap = isl_union_map_apply_range(umap,
5559 isl_union_map_copy(cluster_map));
5560 sc = add_non_conditional_constraints(edge, umap, sc);
5561 isl_union_map_free(umap);
5563 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5564 return sc;
5566 space = isl_space_domain(isl_map_get_space(edge->map));
5567 uset = isl_union_set_from_set(isl_set_universe(space));
5568 umap1 = isl_union_map_copy(cluster_map);
5569 umap1 = isl_union_map_intersect_domain(umap1, uset);
5570 space = isl_space_range(isl_map_get_space(edge->map));
5571 uset = isl_union_set_from_set(isl_set_universe(space));
5572 umap2 = isl_union_map_copy(cluster_map);
5573 umap2 = isl_union_map_intersect_domain(umap2, uset);
5574 umap = isl_union_map_product(umap1, umap2);
5576 sc = add_conditional_constraints(edge, umap, sc);
5578 isl_union_map_free(umap);
5579 return sc;
5582 /* Given a mapping "cluster_map" from the original instances to
5583 * the cluster instances, add schedule constraints on the clusters
5584 * to "sc" corresponding to all edges in "graph" between nodes that
5585 * belong to SCCs that are marked for merging in "scc_in_merge".
5587 static __isl_give isl_schedule_constraints *collect_constraints(
5588 struct isl_sched_graph *graph, int *scc_in_merge,
5589 __isl_keep isl_union_map *cluster_map,
5590 __isl_take isl_schedule_constraints *sc)
5592 int i;
5594 for (i = 0; i < graph->n_edge; ++i) {
5595 struct isl_sched_edge *edge = &graph->edge[i];
5597 if (!scc_in_merge[edge->src->scc])
5598 continue;
5599 if (!scc_in_merge[edge->dst->scc])
5600 continue;
5601 sc = collect_edge_constraints(edge, cluster_map, sc);
5604 return sc;
5607 /* Construct a dependence graph for scheduling clusters with respect
5608 * to each other and store the result in "merge_graph".
5609 * In particular, the nodes of the graph correspond to the schedule
5610 * dimensions of the current bands of those clusters that have been
5611 * marked for merging in "c".
5613 * First construct an isl_schedule_constraints object for this domain
5614 * by transforming the edges in "graph" to the domain.
5615 * Then initialize a dependence graph for scheduling from these
5616 * constraints.
5618 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5619 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5621 isl_union_set *domain;
5622 isl_union_map *cluster_map;
5623 isl_schedule_constraints *sc;
5624 isl_stat r;
5626 domain = collect_domain(ctx, graph, c);
5627 sc = isl_schedule_constraints_on_domain(domain);
5628 if (!sc)
5629 return isl_stat_error;
5630 cluster_map = collect_cluster_map(ctx, graph, c);
5631 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5632 isl_union_map_free(cluster_map);
5634 r = graph_init(merge_graph, sc);
5636 isl_schedule_constraints_free(sc);
5638 return r;
5641 /* Compute the maximal number of remaining schedule rows that still need
5642 * to be computed for the nodes that belong to clusters with the maximal
5643 * dimension for the current band (i.e., the band that is to be merged).
5644 * Only clusters that are about to be merged are considered.
5645 * "maxvar" is the maximal dimension for the current band.
5646 * "c" contains information about the clusters.
5648 * Return the maximal number of remaining schedule rows or -1 on error.
5650 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5652 int i, j;
5653 int max_slack;
5655 max_slack = 0;
5656 for (i = 0; i < c->n; ++i) {
5657 int nvar;
5658 struct isl_sched_graph *scc;
5660 if (!c->scc_in_merge[i])
5661 continue;
5662 scc = &c->scc[i];
5663 nvar = scc->n_total_row - scc->band_start;
5664 if (nvar != maxvar)
5665 continue;
5666 for (j = 0; j < scc->n; ++j) {
5667 struct isl_sched_node *node = &scc->node[j];
5668 int slack;
5670 if (node_update_cmap(node) < 0)
5671 return -1;
5672 slack = node->nvar - node->rank;
5673 if (slack > max_slack)
5674 max_slack = slack;
5678 return max_slack;
5681 /* If there are any clusters where the dimension of the current band
5682 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5683 * if there are any nodes in such a cluster where the number
5684 * of remaining schedule rows that still need to be computed
5685 * is greater than "max_slack", then return the smallest current band
5686 * dimension of all these clusters. Otherwise return the original value
5687 * of "maxvar". Return -1 in case of any error.
5688 * Only clusters that are about to be merged are considered.
5689 * "c" contains information about the clusters.
5691 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5692 struct isl_clustering *c)
5694 int i, j;
5696 for (i = 0; i < c->n; ++i) {
5697 int nvar;
5698 struct isl_sched_graph *scc;
5700 if (!c->scc_in_merge[i])
5701 continue;
5702 scc = &c->scc[i];
5703 nvar = scc->n_total_row - scc->band_start;
5704 if (nvar >= maxvar)
5705 continue;
5706 for (j = 0; j < scc->n; ++j) {
5707 struct isl_sched_node *node = &scc->node[j];
5708 int slack;
5710 if (node_update_cmap(node) < 0)
5711 return -1;
5712 slack = node->nvar - node->rank;
5713 if (slack > max_slack) {
5714 maxvar = nvar;
5715 break;
5720 return maxvar;
5723 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5724 * that still need to be computed. In particular, if there is a node
5725 * in a cluster where the dimension of the current band is smaller
5726 * than merge_graph->maxvar, but the number of remaining schedule rows
5727 * is greater than that of any node in a cluster with the maximal
5728 * dimension for the current band (i.e., merge_graph->maxvar),
5729 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5730 * of those clusters. Without this adjustment, the total number of
5731 * schedule dimensions would be increased, resulting in a skewed view
5732 * of the number of coincident dimensions.
5733 * "c" contains information about the clusters.
5735 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5736 * then there is no point in attempting any merge since it will be rejected
5737 * anyway. Set merge_graph->maxvar to zero in such cases.
5739 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5740 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5742 int max_slack, maxvar;
5744 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5745 if (max_slack < 0)
5746 return isl_stat_error;
5747 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5748 if (maxvar < 0)
5749 return isl_stat_error;
5751 if (maxvar < merge_graph->maxvar) {
5752 if (isl_options_get_schedule_maximize_band_depth(ctx))
5753 merge_graph->maxvar = 0;
5754 else
5755 merge_graph->maxvar = maxvar;
5758 return isl_stat_ok;
5761 /* Return the number of coincident dimensions in the current band of "graph",
5762 * where the nodes of "graph" are assumed to be scheduled by a single band.
5764 static int get_n_coincident(struct isl_sched_graph *graph)
5766 int i;
5768 for (i = graph->band_start; i < graph->n_total_row; ++i)
5769 if (!graph->node[0].coincident[i])
5770 break;
5772 return i - graph->band_start;
5775 /* Should the clusters be merged based on the cluster schedule
5776 * in the current (and only) band of "merge_graph", given that
5777 * coincidence should be maximized?
5779 * If the number of coincident schedule dimensions in the merged band
5780 * would be less than the maximal number of coincident schedule dimensions
5781 * in any of the merged clusters, then the clusters should not be merged.
5783 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5784 struct isl_sched_graph *merge_graph)
5786 int i;
5787 int n_coincident;
5788 int max_coincident;
5790 max_coincident = 0;
5791 for (i = 0; i < c->n; ++i) {
5792 if (!c->scc_in_merge[i])
5793 continue;
5794 n_coincident = get_n_coincident(&c->scc[i]);
5795 if (n_coincident > max_coincident)
5796 max_coincident = n_coincident;
5799 n_coincident = get_n_coincident(merge_graph);
5801 return n_coincident >= max_coincident;
5804 /* Return the transformation on "node" expressed by the current (and only)
5805 * band of "merge_graph" applied to the clusters in "c".
5807 * First find the representation of "node" in its SCC in "c" and
5808 * extract the transformation expressed by the current band.
5809 * Then extract the transformation applied by "merge_graph"
5810 * to the cluster to which this SCC belongs.
5811 * Combine the two to obtain the complete transformation on the node.
5813 * Note that the range of the first transformation is an anonymous space,
5814 * while the domain of the second is named "cluster_X". The range
5815 * of the former therefore needs to be adjusted before the two
5816 * can be combined.
5818 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5819 struct isl_sched_node *node, struct isl_clustering *c,
5820 struct isl_sched_graph *merge_graph)
5822 struct isl_sched_node *scc_node, *cluster_node;
5823 int start, n;
5824 isl_id *id;
5825 isl_space *space;
5826 isl_multi_aff *ma, *ma2;
5828 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5829 start = c->scc[node->scc].band_start;
5830 n = c->scc[node->scc].n_total_row - start;
5831 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5832 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5833 cluster_node = graph_find_node(ctx, merge_graph, space);
5834 if (space && !cluster_node)
5835 isl_die(ctx, isl_error_internal, "unable to find cluster",
5836 space = isl_space_free(space));
5837 id = isl_space_get_tuple_id(space, isl_dim_set);
5838 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5839 isl_space_free(space);
5840 n = merge_graph->n_total_row;
5841 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5842 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5844 return isl_map_from_multi_aff(ma);
5847 /* Give a set of distances "set", are they bounded by a small constant
5848 * in direction "pos"?
5849 * In practice, check if they are bounded by 2 by checking that there
5850 * are no elements with a value greater than or equal to 3 or
5851 * smaller than or equal to -3.
5853 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5855 isl_bool bounded;
5856 isl_set *test;
5858 if (!set)
5859 return isl_bool_error;
5861 test = isl_set_copy(set);
5862 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5863 bounded = isl_set_is_empty(test);
5864 isl_set_free(test);
5866 if (bounded < 0 || !bounded)
5867 return bounded;
5869 test = isl_set_copy(set);
5870 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5871 bounded = isl_set_is_empty(test);
5872 isl_set_free(test);
5874 return bounded;
5877 /* Does the set "set" have a fixed (but possible parametric) value
5878 * at dimension "pos"?
5880 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5882 int n;
5883 isl_bool single;
5885 if (!set)
5886 return isl_bool_error;
5887 set = isl_set_copy(set);
5888 n = isl_set_dim(set, isl_dim_set);
5889 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5890 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5891 single = isl_set_is_singleton(set);
5892 isl_set_free(set);
5894 return single;
5897 /* Does "map" have a fixed (but possible parametric) value
5898 * at dimension "pos" of either its domain or its range?
5900 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5902 isl_set *set;
5903 isl_bool single;
5905 set = isl_map_domain(isl_map_copy(map));
5906 single = has_single_value(set, pos);
5907 isl_set_free(set);
5909 if (single < 0 || single)
5910 return single;
5912 set = isl_map_range(isl_map_copy(map));
5913 single = has_single_value(set, pos);
5914 isl_set_free(set);
5916 return single;
5919 /* Does the edge "edge" from "graph" have bounded dependence distances
5920 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5922 * Extract the complete transformations of the source and destination
5923 * nodes of the edge, apply them to the edge constraints and
5924 * compute the differences. Finally, check if these differences are bounded
5925 * in each direction.
5927 * If the dimension of the band is greater than the number of
5928 * dimensions that can be expected to be optimized by the edge
5929 * (based on its weight), then also allow the differences to be unbounded
5930 * in the remaining dimensions, but only if either the source or
5931 * the destination has a fixed value in that direction.
5932 * This allows a statement that produces values that are used by
5933 * several instances of another statement to be merged with that
5934 * other statement.
5935 * However, merging such clusters will introduce an inherently
5936 * large proximity distance inside the merged cluster, meaning
5937 * that proximity distances will no longer be optimized in
5938 * subsequent merges. These merges are therefore only allowed
5939 * after all other possible merges have been tried.
5940 * The first time such a merge is encountered, the weight of the edge
5941 * is replaced by a negative weight. The second time (i.e., after
5942 * all merges over edges with a non-negative weight have been tried),
5943 * the merge is allowed.
5945 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5946 struct isl_sched_graph *graph, struct isl_clustering *c,
5947 struct isl_sched_graph *merge_graph)
5949 int i, n, n_slack;
5950 isl_bool bounded;
5951 isl_map *map, *t;
5952 isl_set *dist;
5954 map = isl_map_copy(edge->map);
5955 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5956 map = isl_map_apply_domain(map, t);
5957 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5958 map = isl_map_apply_range(map, t);
5959 dist = isl_map_deltas(isl_map_copy(map));
5961 bounded = isl_bool_true;
5962 n = isl_set_dim(dist, isl_dim_set);
5963 n_slack = n - edge->weight;
5964 if (edge->weight < 0)
5965 n_slack -= graph->max_weight + 1;
5966 for (i = 0; i < n; ++i) {
5967 isl_bool bounded_i, singular_i;
5969 bounded_i = distance_is_bounded(dist, i);
5970 if (bounded_i < 0)
5971 goto error;
5972 if (bounded_i)
5973 continue;
5974 if (edge->weight >= 0)
5975 bounded = isl_bool_false;
5976 n_slack--;
5977 if (n_slack < 0)
5978 break;
5979 singular_i = has_singular_src_or_dst(map, i);
5980 if (singular_i < 0)
5981 goto error;
5982 if (singular_i)
5983 continue;
5984 bounded = isl_bool_false;
5985 break;
5987 if (!bounded && i >= n && edge->weight >= 0)
5988 edge->weight -= graph->max_weight + 1;
5989 isl_map_free(map);
5990 isl_set_free(dist);
5992 return bounded;
5993 error:
5994 isl_map_free(map);
5995 isl_set_free(dist);
5996 return isl_bool_error;
5999 /* Should the clusters be merged based on the cluster schedule
6000 * in the current (and only) band of "merge_graph"?
6001 * "graph" is the original dependence graph, while "c" records
6002 * which SCCs are involved in the latest merge.
6004 * In particular, is there at least one proximity constraint
6005 * that is optimized by the merge?
6007 * A proximity constraint is considered to be optimized
6008 * if the dependence distances are small.
6010 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6011 struct isl_sched_graph *graph, struct isl_clustering *c,
6012 struct isl_sched_graph *merge_graph)
6014 int i;
6016 for (i = 0; i < graph->n_edge; ++i) {
6017 struct isl_sched_edge *edge = &graph->edge[i];
6018 isl_bool bounded;
6020 if (!is_proximity(edge))
6021 continue;
6022 if (!c->scc_in_merge[edge->src->scc])
6023 continue;
6024 if (!c->scc_in_merge[edge->dst->scc])
6025 continue;
6026 if (c->scc_cluster[edge->dst->scc] ==
6027 c->scc_cluster[edge->src->scc])
6028 continue;
6029 bounded = has_bounded_distances(ctx, edge, graph, c,
6030 merge_graph);
6031 if (bounded < 0 || bounded)
6032 return bounded;
6035 return isl_bool_false;
6038 /* Should the clusters be merged based on the cluster schedule
6039 * in the current (and only) band of "merge_graph"?
6040 * "graph" is the original dependence graph, while "c" records
6041 * which SCCs are involved in the latest merge.
6043 * If the current band is empty, then the clusters should not be merged.
6045 * If the band depth should be maximized and the merge schedule
6046 * is incomplete (meaning that the dimension of some of the schedule
6047 * bands in the original schedule will be reduced), then the clusters
6048 * should not be merged.
6050 * If the schedule_maximize_coincidence option is set, then check that
6051 * the number of coincident schedule dimensions is not reduced.
6053 * Finally, only allow the merge if at least one proximity
6054 * constraint is optimized.
6056 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6057 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6059 if (merge_graph->n_total_row == merge_graph->band_start)
6060 return isl_bool_false;
6062 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6063 merge_graph->n_total_row < merge_graph->maxvar)
6064 return isl_bool_false;
6066 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6067 isl_bool ok;
6069 ok = ok_to_merge_coincident(c, merge_graph);
6070 if (ok < 0 || !ok)
6071 return ok;
6074 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6077 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6078 * of the schedule in "node" and return the result.
6080 * That is, essentially compute
6082 * T * N(first:first+n-1)
6084 * taking into account the constant term and the parameter coefficients
6085 * in "t_node".
6087 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6088 struct isl_sched_node *t_node, struct isl_sched_node *node,
6089 int first, int n)
6091 int i, j;
6092 isl_mat *t;
6093 int n_row, n_col, n_param, n_var;
6095 n_param = node->nparam;
6096 n_var = node->nvar;
6097 n_row = isl_mat_rows(t_node->sched);
6098 n_col = isl_mat_cols(node->sched);
6099 t = isl_mat_alloc(ctx, n_row, n_col);
6100 if (!t)
6101 return NULL;
6102 for (i = 0; i < n_row; ++i) {
6103 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6104 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6105 for (j = 0; j < n; ++j)
6106 isl_seq_addmul(t->row[i],
6107 t_node->sched->row[i][1 + n_param + j],
6108 node->sched->row[first + j],
6109 1 + n_param + n_var);
6111 return t;
6114 /* Apply the cluster schedule in "t_node" to the current band
6115 * schedule of the nodes in "graph".
6117 * In particular, replace the rows starting at band_start
6118 * by the result of applying the cluster schedule in "t_node"
6119 * to the original rows.
6121 * The coincidence of the schedule is determined by the coincidence
6122 * of the cluster schedule.
6124 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6125 struct isl_sched_node *t_node)
6127 int i, j;
6128 int n_new;
6129 int start, n;
6131 start = graph->band_start;
6132 n = graph->n_total_row - start;
6134 n_new = isl_mat_rows(t_node->sched);
6135 for (i = 0; i < graph->n; ++i) {
6136 struct isl_sched_node *node = &graph->node[i];
6137 isl_mat *t;
6139 t = node_transformation(ctx, t_node, node, start, n);
6140 node->sched = isl_mat_drop_rows(node->sched, start, n);
6141 node->sched = isl_mat_concat(node->sched, t);
6142 node->sched_map = isl_map_free(node->sched_map);
6143 if (!node->sched)
6144 return isl_stat_error;
6145 for (j = 0; j < n_new; ++j)
6146 node->coincident[start + j] = t_node->coincident[j];
6148 graph->n_total_row -= n;
6149 graph->n_row -= n;
6150 graph->n_total_row += n_new;
6151 graph->n_row += n_new;
6153 return isl_stat_ok;
6156 /* Merge the clusters marked for merging in "c" into a single
6157 * cluster using the cluster schedule in the current band of "merge_graph".
6158 * The representative SCC for the new cluster is the SCC with
6159 * the smallest index.
6161 * The current band schedule of each SCC in the new cluster is obtained
6162 * by applying the schedule of the corresponding original cluster
6163 * to the original band schedule.
6164 * All SCCs in the new cluster have the same number of schedule rows.
6166 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6167 struct isl_sched_graph *merge_graph)
6169 int i;
6170 int cluster = -1;
6171 isl_space *space;
6173 for (i = 0; i < c->n; ++i) {
6174 struct isl_sched_node *node;
6176 if (!c->scc_in_merge[i])
6177 continue;
6178 if (cluster < 0)
6179 cluster = i;
6180 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6181 if (!space)
6182 return isl_stat_error;
6183 node = graph_find_node(ctx, merge_graph, space);
6184 isl_space_free(space);
6185 if (!node)
6186 isl_die(ctx, isl_error_internal,
6187 "unable to find cluster",
6188 return isl_stat_error);
6189 if (transform(ctx, &c->scc[i], node) < 0)
6190 return isl_stat_error;
6191 c->scc_cluster[i] = cluster;
6194 return isl_stat_ok;
6197 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6198 * by scheduling the current cluster bands with respect to each other.
6200 * Construct a dependence graph with a space for each cluster and
6201 * with the coordinates of each space corresponding to the schedule
6202 * dimensions of the current band of that cluster.
6203 * Construct a cluster schedule in this cluster dependence graph and
6204 * apply it to the current cluster bands if it is applicable
6205 * according to ok_to_merge.
6207 * If the number of remaining schedule dimensions in a cluster
6208 * with a non-maximal current schedule dimension is greater than
6209 * the number of remaining schedule dimensions in clusters
6210 * with a maximal current schedule dimension, then restrict
6211 * the number of rows to be computed in the cluster schedule
6212 * to the minimal such non-maximal current schedule dimension.
6213 * Do this by adjusting merge_graph.maxvar.
6215 * Return isl_bool_true if the clusters have effectively been merged
6216 * into a single cluster.
6218 * Note that since the standard scheduling algorithm minimizes the maximal
6219 * distance over proximity constraints, the proximity constraints between
6220 * the merged clusters may not be optimized any further than what is
6221 * sufficient to bring the distances within the limits of the internal
6222 * proximity constraints inside the individual clusters.
6223 * It may therefore make sense to perform an additional translation step
6224 * to bring the clusters closer to each other, while maintaining
6225 * the linear part of the merging schedule found using the standard
6226 * scheduling algorithm.
6228 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6229 struct isl_clustering *c)
6231 struct isl_sched_graph merge_graph = { 0 };
6232 isl_bool merged;
6234 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6235 goto error;
6237 if (compute_maxvar(&merge_graph) < 0)
6238 goto error;
6239 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6240 goto error;
6241 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6242 goto error;
6243 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6244 if (merged && merge(ctx, c, &merge_graph) < 0)
6245 goto error;
6247 graph_free(ctx, &merge_graph);
6248 return merged;
6249 error:
6250 graph_free(ctx, &merge_graph);
6251 return isl_bool_error;
6254 /* Is there any edge marked "no_merge" between two SCCs that are
6255 * about to be merged (i.e., that are set in "scc_in_merge")?
6256 * "merge_edge" is the proximity edge along which the clusters of SCCs
6257 * are going to be merged.
6259 * If there is any edge between two SCCs with a negative weight,
6260 * while the weight of "merge_edge" is non-negative, then this
6261 * means that the edge was postponed. "merge_edge" should then
6262 * also be postponed since merging along the edge with negative weight should
6263 * be postponed until all edges with non-negative weight have been tried.
6264 * Replace the weight of "merge_edge" by a negative weight as well and
6265 * tell the caller not to attempt a merge.
6267 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6268 struct isl_sched_edge *merge_edge)
6270 int i;
6272 for (i = 0; i < graph->n_edge; ++i) {
6273 struct isl_sched_edge *edge = &graph->edge[i];
6275 if (!scc_in_merge[edge->src->scc])
6276 continue;
6277 if (!scc_in_merge[edge->dst->scc])
6278 continue;
6279 if (edge->no_merge)
6280 return 1;
6281 if (merge_edge->weight >= 0 && edge->weight < 0) {
6282 merge_edge->weight -= graph->max_weight + 1;
6283 return 1;
6287 return 0;
6290 /* Merge the two clusters in "c" connected by the edge in "graph"
6291 * with index "edge" into a single cluster.
6292 * If it turns out to be impossible to merge these two clusters,
6293 * then mark the edge as "no_merge" such that it will not be
6294 * considered again.
6296 * First mark all SCCs that need to be merged. This includes the SCCs
6297 * in the two clusters, but it may also include the SCCs
6298 * of intermediate clusters.
6299 * If there is already a no_merge edge between any pair of such SCCs,
6300 * then simply mark the current edge as no_merge as well.
6301 * Likewise, if any of those edges was postponed by has_bounded_distances,
6302 * then postpone the current edge as well.
6303 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6304 * if the clusters did not end up getting merged, unless the non-merge
6305 * is due to the fact that the edge was postponed. This postponement
6306 * can be recognized by a change in weight (from non-negative to negative).
6308 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6309 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6311 isl_bool merged;
6312 int edge_weight = graph->edge[edge].weight;
6314 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6315 return isl_stat_error;
6317 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6318 merged = isl_bool_false;
6319 else
6320 merged = try_merge(ctx, graph, c);
6321 if (merged < 0)
6322 return isl_stat_error;
6323 if (!merged && edge_weight == graph->edge[edge].weight)
6324 graph->edge[edge].no_merge = 1;
6326 return isl_stat_ok;
6329 /* Does "node" belong to the cluster identified by "cluster"?
6331 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6333 return node->cluster == cluster;
6336 /* Does "edge" connect two nodes belonging to the cluster
6337 * identified by "cluster"?
6339 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6341 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6344 /* Swap the schedule of "node1" and "node2".
6345 * Both nodes have been derived from the same node in a common parent graph.
6346 * Since the "coincident" field is shared with that node
6347 * in the parent graph, there is no need to also swap this field.
6349 static void swap_sched(struct isl_sched_node *node1,
6350 struct isl_sched_node *node2)
6352 isl_mat *sched;
6353 isl_map *sched_map;
6355 sched = node1->sched;
6356 node1->sched = node2->sched;
6357 node2->sched = sched;
6359 sched_map = node1->sched_map;
6360 node1->sched_map = node2->sched_map;
6361 node2->sched_map = sched_map;
6364 /* Copy the current band schedule from the SCCs that form the cluster
6365 * with index "pos" to the actual cluster at position "pos".
6366 * By construction, the index of the first SCC that belongs to the cluster
6367 * is also "pos".
6369 * The order of the nodes inside both the SCCs and the cluster
6370 * is assumed to be same as the order in the original "graph".
6372 * Since the SCC graphs will no longer be used after this function,
6373 * the schedules are actually swapped rather than copied.
6375 static isl_stat copy_partial(struct isl_sched_graph *graph,
6376 struct isl_clustering *c, int pos)
6378 int i, j;
6380 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6381 c->cluster[pos].n_row = c->scc[pos].n_row;
6382 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6383 j = 0;
6384 for (i = 0; i < graph->n; ++i) {
6385 int k;
6386 int s;
6388 if (graph->node[i].cluster != pos)
6389 continue;
6390 s = graph->node[i].scc;
6391 k = c->scc_node[s]++;
6392 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6393 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6394 c->cluster[pos].maxvar = c->scc[s].maxvar;
6395 ++j;
6398 return isl_stat_ok;
6401 /* Is there a (conditional) validity dependence from node[j] to node[i],
6402 * forcing node[i] to follow node[j] or do the nodes belong to the same
6403 * cluster?
6405 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6407 struct isl_sched_graph *graph = user;
6409 if (graph->node[i].cluster == graph->node[j].cluster)
6410 return isl_bool_true;
6411 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6414 /* Extract the merged clusters of SCCs in "graph", sort them, and
6415 * store them in c->clusters. Update c->scc_cluster accordingly.
6417 * First keep track of the cluster containing the SCC to which a node
6418 * belongs in the node itself.
6419 * Then extract the clusters into c->clusters, copying the current
6420 * band schedule from the SCCs that belong to the cluster.
6421 * Do this only once per cluster.
6423 * Finally, topologically sort the clusters and update c->scc_cluster
6424 * to match the new scc numbering. While the SCCs were originally
6425 * sorted already, some SCCs that depend on some other SCCs may
6426 * have been merged with SCCs that appear before these other SCCs.
6427 * A reordering may therefore be required.
6429 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6430 struct isl_clustering *c)
6432 int i;
6434 for (i = 0; i < graph->n; ++i)
6435 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6437 for (i = 0; i < graph->scc; ++i) {
6438 if (c->scc_cluster[i] != i)
6439 continue;
6440 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6441 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6442 return isl_stat_error;
6443 c->cluster[i].src_scc = -1;
6444 c->cluster[i].dst_scc = -1;
6445 if (copy_partial(graph, c, i) < 0)
6446 return isl_stat_error;
6449 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6450 return isl_stat_error;
6451 for (i = 0; i < graph->n; ++i)
6452 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6454 return isl_stat_ok;
6457 /* Compute weights on the proximity edges of "graph" that can
6458 * be used by find_proximity to find the most appropriate
6459 * proximity edge to use to merge two clusters in "c".
6460 * The weights are also used by has_bounded_distances to determine
6461 * whether the merge should be allowed.
6462 * Store the maximum of the computed weights in graph->max_weight.
6464 * The computed weight is a measure for the number of remaining schedule
6465 * dimensions that can still be completely aligned.
6466 * In particular, compute the number of equalities between
6467 * input dimensions and output dimensions in the proximity constraints.
6468 * The directions that are already handled by outer schedule bands
6469 * are projected out prior to determining this number.
6471 * Edges that will never be considered by find_proximity are ignored.
6473 static isl_stat compute_weights(struct isl_sched_graph *graph,
6474 struct isl_clustering *c)
6476 int i;
6478 graph->max_weight = 0;
6480 for (i = 0; i < graph->n_edge; ++i) {
6481 struct isl_sched_edge *edge = &graph->edge[i];
6482 struct isl_sched_node *src = edge->src;
6483 struct isl_sched_node *dst = edge->dst;
6484 isl_basic_map *hull;
6485 isl_bool prox;
6486 int n_in, n_out;
6488 prox = is_non_empty_proximity(edge);
6489 if (prox < 0)
6490 return isl_stat_error;
6491 if (!prox)
6492 continue;
6493 if (bad_cluster(&c->scc[edge->src->scc]) ||
6494 bad_cluster(&c->scc[edge->dst->scc]))
6495 continue;
6496 if (c->scc_cluster[edge->dst->scc] ==
6497 c->scc_cluster[edge->src->scc])
6498 continue;
6500 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6501 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6502 isl_mat_copy(src->ctrans));
6503 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6504 isl_mat_copy(dst->ctrans));
6505 hull = isl_basic_map_project_out(hull,
6506 isl_dim_in, 0, src->rank);
6507 hull = isl_basic_map_project_out(hull,
6508 isl_dim_out, 0, dst->rank);
6509 hull = isl_basic_map_remove_divs(hull);
6510 n_in = isl_basic_map_dim(hull, isl_dim_in);
6511 n_out = isl_basic_map_dim(hull, isl_dim_out);
6512 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6513 isl_dim_in, 0, n_in);
6514 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6515 isl_dim_out, 0, n_out);
6516 if (!hull)
6517 return isl_stat_error;
6518 edge->weight = isl_basic_map_n_equality(hull);
6519 isl_basic_map_free(hull);
6521 if (edge->weight > graph->max_weight)
6522 graph->max_weight = edge->weight;
6525 return isl_stat_ok;
6528 /* Call compute_schedule_finish_band on each of the clusters in "c"
6529 * in their topological order. This order is determined by the scc
6530 * fields of the nodes in "graph".
6531 * Combine the results in a sequence expressing the topological order.
6533 * If there is only one cluster left, then there is no need to introduce
6534 * a sequence node. Also, in this case, the cluster necessarily contains
6535 * the SCC at position 0 in the original graph and is therefore also
6536 * stored in the first cluster of "c".
6538 static __isl_give isl_schedule_node *finish_bands_clustering(
6539 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6540 struct isl_clustering *c)
6542 int i;
6543 isl_ctx *ctx;
6544 isl_union_set_list *filters;
6546 if (graph->scc == 1)
6547 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6549 ctx = isl_schedule_node_get_ctx(node);
6551 filters = extract_sccs(ctx, graph);
6552 node = isl_schedule_node_insert_sequence(node, filters);
6554 for (i = 0; i < graph->scc; ++i) {
6555 int j = c->scc_cluster[i];
6556 node = isl_schedule_node_child(node, i);
6557 node = isl_schedule_node_child(node, 0);
6558 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6559 node = isl_schedule_node_parent(node);
6560 node = isl_schedule_node_parent(node);
6563 return node;
6566 /* Compute a schedule for a connected dependence graph by first considering
6567 * each strongly connected component (SCC) in the graph separately and then
6568 * incrementally combining them into clusters.
6569 * Return the updated schedule node.
6571 * Initially, each cluster consists of a single SCC, each with its
6572 * own band schedule. The algorithm then tries to merge pairs
6573 * of clusters along a proximity edge until no more suitable
6574 * proximity edges can be found. During this merging, the schedule
6575 * is maintained in the individual SCCs.
6576 * After the merging is completed, the full resulting clusters
6577 * are extracted and in finish_bands_clustering,
6578 * compute_schedule_finish_band is called on each of them to integrate
6579 * the band into "node" and to continue the computation.
6581 * compute_weights initializes the weights that are used by find_proximity.
6583 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6584 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6586 isl_ctx *ctx;
6587 struct isl_clustering c;
6588 int i;
6590 ctx = isl_schedule_node_get_ctx(node);
6592 if (clustering_init(ctx, &c, graph) < 0)
6593 goto error;
6595 if (compute_weights(graph, &c) < 0)
6596 goto error;
6598 for (;;) {
6599 i = find_proximity(graph, &c);
6600 if (i < 0)
6601 goto error;
6602 if (i >= graph->n_edge)
6603 break;
6604 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6605 goto error;
6608 if (extract_clusters(ctx, graph, &c) < 0)
6609 goto error;
6611 node = finish_bands_clustering(node, graph, &c);
6613 clustering_free(ctx, &c);
6614 return node;
6615 error:
6616 clustering_free(ctx, &c);
6617 return isl_schedule_node_free(node);
6620 /* Compute a schedule for a connected dependence graph and return
6621 * the updated schedule node.
6623 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6624 * as many validity dependences as possible. When all validity dependences
6625 * are satisfied we extend the schedule to a full-dimensional schedule.
6627 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6628 * depending on whether the user has selected the option to try and
6629 * compute a schedule for the entire (weakly connected) component first.
6630 * If there is only a single strongly connected component (SCC), then
6631 * there is no point in trying to combine SCCs
6632 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6633 * is called instead.
6635 static __isl_give isl_schedule_node *compute_schedule_wcc(
6636 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6638 isl_ctx *ctx;
6640 if (!node)
6641 return NULL;
6643 ctx = isl_schedule_node_get_ctx(node);
6644 if (detect_sccs(ctx, graph) < 0)
6645 return isl_schedule_node_free(node);
6647 if (compute_maxvar(graph) < 0)
6648 return isl_schedule_node_free(node);
6650 if (need_feautrier_step(ctx, graph))
6651 return compute_schedule_wcc_feautrier(node, graph);
6653 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6654 return compute_schedule_wcc_whole(node, graph);
6655 else
6656 return compute_schedule_wcc_clustering(node, graph);
6659 /* Compute a schedule for each group of nodes identified by node->scc
6660 * separately and then combine them in a sequence node (or as set node
6661 * if graph->weak is set) inserted at position "node" of the schedule tree.
6662 * Return the updated schedule node.
6664 * If "wcc" is set then each of the groups belongs to a single
6665 * weakly connected component in the dependence graph so that
6666 * there is no need for compute_sub_schedule to look for weakly
6667 * connected components.
6669 static __isl_give isl_schedule_node *compute_component_schedule(
6670 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6671 int wcc)
6673 int component;
6674 isl_ctx *ctx;
6675 isl_union_set_list *filters;
6677 if (!node)
6678 return NULL;
6679 ctx = isl_schedule_node_get_ctx(node);
6681 filters = extract_sccs(ctx, graph);
6682 if (graph->weak)
6683 node = isl_schedule_node_insert_set(node, filters);
6684 else
6685 node = isl_schedule_node_insert_sequence(node, filters);
6687 for (component = 0; component < graph->scc; ++component) {
6688 node = isl_schedule_node_child(node, component);
6689 node = isl_schedule_node_child(node, 0);
6690 node = compute_sub_schedule(node, ctx, graph,
6691 &node_scc_exactly,
6692 &edge_scc_exactly, component, wcc);
6693 node = isl_schedule_node_parent(node);
6694 node = isl_schedule_node_parent(node);
6697 return node;
6700 /* Compute a schedule for the given dependence graph and insert it at "node".
6701 * Return the updated schedule node.
6703 * We first check if the graph is connected (through validity and conditional
6704 * validity dependences) and, if not, compute a schedule
6705 * for each component separately.
6706 * If the schedule_serialize_sccs option is set, then we check for strongly
6707 * connected components instead and compute a separate schedule for
6708 * each such strongly connected component.
6710 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6711 struct isl_sched_graph *graph)
6713 isl_ctx *ctx;
6715 if (!node)
6716 return NULL;
6718 ctx = isl_schedule_node_get_ctx(node);
6719 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6720 if (detect_sccs(ctx, graph) < 0)
6721 return isl_schedule_node_free(node);
6722 } else {
6723 if (detect_wccs(ctx, graph) < 0)
6724 return isl_schedule_node_free(node);
6727 if (graph->scc > 1)
6728 return compute_component_schedule(node, graph, 1);
6730 return compute_schedule_wcc(node, graph);
6733 /* Compute a schedule on sc->domain that respects the given schedule
6734 * constraints.
6736 * In particular, the schedule respects all the validity dependences.
6737 * If the default isl scheduling algorithm is used, it tries to minimize
6738 * the dependence distances over the proximity dependences.
6739 * If Feautrier's scheduling algorithm is used, the proximity dependence
6740 * distances are only minimized during the extension to a full-dimensional
6741 * schedule.
6743 * If there are any condition and conditional validity dependences,
6744 * then the conditional validity dependences may be violated inside
6745 * a tilable band, provided they have no adjacent non-local
6746 * condition dependences.
6748 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6749 __isl_take isl_schedule_constraints *sc)
6751 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6752 struct isl_sched_graph graph = { 0 };
6753 isl_schedule *sched;
6754 isl_schedule_node *node;
6755 isl_union_set *domain;
6757 sc = isl_schedule_constraints_align_params(sc);
6759 domain = isl_schedule_constraints_get_domain(sc);
6760 if (isl_union_set_n_set(domain) == 0) {
6761 isl_schedule_constraints_free(sc);
6762 return isl_schedule_from_domain(domain);
6765 if (graph_init(&graph, sc) < 0)
6766 domain = isl_union_set_free(domain);
6768 node = isl_schedule_node_from_domain(domain);
6769 node = isl_schedule_node_child(node, 0);
6770 if (graph.n > 0)
6771 node = compute_schedule(node, &graph);
6772 sched = isl_schedule_node_get_schedule(node);
6773 isl_schedule_node_free(node);
6775 graph_free(ctx, &graph);
6776 isl_schedule_constraints_free(sc);
6778 return sched;
6781 /* Compute a schedule for the given union of domains that respects
6782 * all the validity dependences and minimizes
6783 * the dependence distances over the proximity dependences.
6785 * This function is kept for backward compatibility.
6787 __isl_give isl_schedule *isl_union_set_compute_schedule(
6788 __isl_take isl_union_set *domain,
6789 __isl_take isl_union_map *validity,
6790 __isl_take isl_union_map *proximity)
6792 isl_schedule_constraints *sc;
6794 sc = isl_schedule_constraints_on_domain(domain);
6795 sc = isl_schedule_constraints_set_validity(sc, validity);
6796 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6798 return isl_schedule_constraints_compute_schedule(sc);