ignore computed schedule of timing test case
[isl.git] / isl_scheduler.c
blobd15675b2e224d4b3fd1f39b1475c1411d7580f06
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 * Actually, we do not construct constraints for the c_i_x themselves,
1699 * but for the coefficients of c_i_x written as a linear combination
1700 * of the columns in node->cmap.
1702 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1703 struct isl_sched_edge *edge)
1705 int offset;
1706 isl_map *map = isl_map_copy(edge->map);
1707 isl_ctx *ctx = isl_map_get_ctx(map);
1708 isl_dim_map *dim_map;
1709 isl_basic_set *coef;
1710 struct isl_sched_node *node = edge->src;
1712 coef = intra_coefficients(graph, node, map);
1714 offset = coef_var_offset(coef);
1716 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1717 offset, isl_mat_copy(node->cmap));
1718 if (!coef)
1719 return isl_stat_error;
1721 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1722 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1724 return isl_stat_ok;
1727 /* Add constraints to graph->lp that force validity for the given
1728 * dependence from node i to node j.
1729 * That is, add constraints that enforce
1731 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1733 * for each (x,y) in R.
1734 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1735 * of valid constraints for R and then plug in
1736 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1737 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1738 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1740 * Actually, we do not construct constraints for the c_*_x themselves,
1741 * but for the coefficients of c_*_x written as a linear combination
1742 * of the columns in node->cmap.
1744 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1745 struct isl_sched_edge *edge)
1747 int offset;
1748 isl_map *map;
1749 isl_ctx *ctx;
1750 isl_dim_map *dim_map;
1751 isl_basic_set *coef;
1752 struct isl_sched_node *src = edge->src;
1753 struct isl_sched_node *dst = edge->dst;
1755 if (!graph->lp)
1756 return isl_stat_error;
1758 map = isl_map_copy(edge->map);
1759 ctx = isl_map_get_ctx(map);
1760 coef = inter_coefficients(graph, edge, map);
1762 offset = coef_var_offset(coef);
1764 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1765 offset, isl_mat_copy(src->cmap));
1766 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1767 offset + src->nvar, isl_mat_copy(dst->cmap));
1768 if (!coef)
1769 return isl_stat_error;
1771 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1773 edge->start = graph->lp->n_ineq;
1774 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1775 if (!graph->lp)
1776 return isl_stat_error;
1777 edge->end = graph->lp->n_ineq;
1779 return isl_stat_ok;
1782 /* Add constraints to graph->lp that bound the dependence distance for the given
1783 * dependence from a node i to itself.
1784 * If s = 1, we add the constraint
1786 * c_i_x (y - x) <= m_0 + m_n n
1788 * or
1790 * -c_i_x (y - x) + m_0 + m_n n >= 0
1792 * for each (x,y) in R.
1793 * If s = -1, we add the constraint
1795 * -c_i_x (y - x) <= m_0 + m_n n
1797 * or
1799 * c_i_x (y - x) + m_0 + m_n n >= 0
1801 * for each (x,y) in R.
1802 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1803 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1804 * with each coefficient (except m_0) represented as a pair of non-negative
1805 * coefficients.
1807 * Actually, we do not construct constraints for the c_i_x themselves,
1808 * but for the coefficients of c_i_x written as a linear combination
1809 * of the columns in node->cmap.
1812 * If "local" is set, then we add constraints
1814 * c_i_x (y - x) <= 0
1816 * or
1818 * -c_i_x (y - x) <= 0
1820 * instead, forcing the dependence distance to be (less than or) equal to 0.
1821 * That is, we plug in (0, 0, -s * c_i_x),
1822 * Note that dependences marked local are treated as validity constraints
1823 * by add_all_validity_constraints and therefore also have
1824 * their distances bounded by 0 from below.
1826 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1827 struct isl_sched_edge *edge, int s, int local)
1829 int offset;
1830 unsigned nparam;
1831 isl_map *map = isl_map_copy(edge->map);
1832 isl_ctx *ctx = isl_map_get_ctx(map);
1833 isl_dim_map *dim_map;
1834 isl_basic_set *coef;
1835 struct isl_sched_node *node = edge->src;
1837 coef = intra_coefficients(graph, node, map);
1839 offset = coef_var_offset(coef);
1841 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1842 offset, isl_mat_copy(node->cmap));
1843 if (!coef)
1844 return isl_stat_error;
1846 nparam = isl_space_dim(node->space, isl_dim_param);
1847 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1849 if (!local) {
1850 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1851 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1852 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1854 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1856 return isl_stat_ok;
1859 /* Add constraints to graph->lp that bound the dependence distance for the given
1860 * dependence from node i to node j.
1861 * If s = 1, we add the constraint
1863 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1864 * <= m_0 + m_n n
1866 * or
1868 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1869 * m_0 + m_n n >= 0
1871 * for each (x,y) in R.
1872 * If s = -1, we add the constraint
1874 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1875 * <= m_0 + m_n n
1877 * or
1879 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1880 * m_0 + m_n n >= 0
1882 * for each (x,y) in R.
1883 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1884 * of valid constraints for R and then plug in
1885 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1886 * s*c_i_x, -s*c_j_x)
1887 * with each coefficient (except m_0, c_*_0 and c_*_n)
1888 * represented as a pair of non-negative coefficients.
1890 * Actually, we do not construct constraints for the c_*_x themselves,
1891 * but for the coefficients of c_*_x written as a linear combination
1892 * of the columns in node->cmap.
1895 * If "local" is set (and s = 1), then we add constraints
1897 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1899 * or
1901 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
1903 * instead, forcing the dependence distance to be (less than or) equal to 0.
1904 * That is, we plug in
1905 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
1906 * Note that dependences marked local are treated as validity constraints
1907 * by add_all_validity_constraints and therefore also have
1908 * their distances bounded by 0 from below.
1910 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1911 struct isl_sched_edge *edge, int s, int local)
1913 int offset;
1914 unsigned nparam;
1915 isl_map *map = isl_map_copy(edge->map);
1916 isl_ctx *ctx = isl_map_get_ctx(map);
1917 isl_dim_map *dim_map;
1918 isl_basic_set *coef;
1919 struct isl_sched_node *src = edge->src;
1920 struct isl_sched_node *dst = edge->dst;
1922 coef = inter_coefficients(graph, edge, map);
1924 offset = coef_var_offset(coef);
1926 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1927 offset, isl_mat_copy(src->cmap));
1928 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1929 offset + src->nvar, isl_mat_copy(dst->cmap));
1930 if (!coef)
1931 return isl_stat_error;
1933 nparam = isl_space_dim(src->space, isl_dim_param);
1934 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1936 if (!local) {
1937 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1938 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1939 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1942 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1944 return isl_stat_ok;
1947 /* Add all validity constraints to graph->lp.
1949 * An edge that is forced to be local needs to have its dependence
1950 * distances equal to zero. We take care of bounding them by 0 from below
1951 * here. add_all_proximity_constraints takes care of bounding them by 0
1952 * from above.
1954 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1955 * Otherwise, we ignore them.
1957 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1958 int use_coincidence)
1960 int i;
1962 for (i = 0; i < graph->n_edge; ++i) {
1963 struct isl_sched_edge *edge = &graph->edge[i];
1964 int local;
1966 local = is_local(edge) ||
1967 (is_coincidence(edge) && use_coincidence);
1968 if (!is_validity(edge) && !local)
1969 continue;
1970 if (edge->src != edge->dst)
1971 continue;
1972 if (add_intra_validity_constraints(graph, edge) < 0)
1973 return -1;
1976 for (i = 0; i < graph->n_edge; ++i) {
1977 struct isl_sched_edge *edge = &graph->edge[i];
1978 int local;
1980 local = is_local(edge) ||
1981 (is_coincidence(edge) && use_coincidence);
1982 if (!is_validity(edge) && !local)
1983 continue;
1984 if (edge->src == edge->dst)
1985 continue;
1986 if (add_inter_validity_constraints(graph, edge) < 0)
1987 return -1;
1990 return 0;
1993 /* Add constraints to graph->lp that bound the dependence distance
1994 * for all dependence relations.
1995 * If a given proximity dependence is identical to a validity
1996 * dependence, then the dependence distance is already bounded
1997 * from below (by zero), so we only need to bound the distance
1998 * from above. (This includes the case of "local" dependences
1999 * which are treated as validity dependence by add_all_validity_constraints.)
2000 * Otherwise, we need to bound the distance both from above and from below.
2002 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2003 * Otherwise, we ignore them.
2005 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2006 int use_coincidence)
2008 int i;
2010 for (i = 0; i < graph->n_edge; ++i) {
2011 struct isl_sched_edge *edge = &graph->edge[i];
2012 int local;
2014 local = is_local(edge) ||
2015 (is_coincidence(edge) && use_coincidence);
2016 if (!is_proximity(edge) && !local)
2017 continue;
2018 if (edge->src == edge->dst &&
2019 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
2020 return -1;
2021 if (edge->src != edge->dst &&
2022 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
2023 return -1;
2024 if (is_validity(edge) || local)
2025 continue;
2026 if (edge->src == edge->dst &&
2027 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2028 return -1;
2029 if (edge->src != edge->dst &&
2030 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2031 return -1;
2034 return 0;
2037 /* Normalize the rows of "indep" such that all rows are lexicographically
2038 * positive and such that each row contains as many final zeros as possible,
2039 * given the choice for the previous rows.
2040 * Do this by performing elementary row operations.
2042 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2044 indep = isl_mat_reverse_gauss(indep);
2045 indep = isl_mat_lexnonneg_rows(indep);
2046 return indep;
2049 /* Compute a basis for the rows in the linear part of the schedule
2050 * and extend this basis to a full basis. The remaining rows
2051 * can then be used to force linear independence from the rows
2052 * in the schedule.
2054 * In particular, given the schedule rows S, we compute
2056 * S = H Q
2057 * S U = H
2059 * with H the Hermite normal form of S. That is, all but the
2060 * first rank columns of H are zero and so each row in S is
2061 * a linear combination of the first rank rows of Q.
2062 * The matrix Q is then transposed because we will write the
2063 * coefficients of the next schedule row as a column vector s
2064 * and express this s as a linear combination s = Q c of the
2065 * computed basis.
2066 * Transposing S U = H yields
2068 * U^T S^T = H^T
2070 * with all but the first rank rows of H^T zero.
2071 * The last rows of U^T are therefore linear combinations
2072 * of schedule coefficients that are all zero on schedule
2073 * coefficients that are linearly dependent on the rows of S.
2074 * At least one of these combinations is non-zero on
2075 * linearly independent schedule coefficients.
2076 * The rows are normalized to involve as few of the last
2077 * coefficients as possible and to have a positive initial value.
2079 static int node_update_cmap(struct isl_sched_node *node)
2081 isl_mat *H, *U, *Q;
2082 int n_row = isl_mat_rows(node->sched);
2084 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2085 1 + node->nparam, node->nvar);
2087 H = isl_mat_left_hermite(H, 0, &U, &Q);
2088 isl_mat_free(node->cmap);
2089 isl_mat_free(node->indep);
2090 isl_mat_free(node->ctrans);
2091 node->ctrans = isl_mat_copy(Q);
2092 node->cmap = isl_mat_transpose(Q);
2093 node->indep = isl_mat_transpose(U);
2094 node->rank = isl_mat_initial_non_zero_cols(H);
2095 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2096 node->indep = normalize_independent(node->indep);
2097 isl_mat_free(H);
2099 if (!node->cmap || !node->indep || !node->ctrans || node->rank < 0)
2100 return -1;
2101 return 0;
2104 /* Is "edge" marked as a validity or a conditional validity edge?
2106 static int is_any_validity(struct isl_sched_edge *edge)
2108 return is_validity(edge) || is_conditional_validity(edge);
2111 /* How many times should we count the constraints in "edge"?
2113 * We count as follows
2114 * validity -> 1 (>= 0)
2115 * validity+proximity -> 2 (>= 0 and upper bound)
2116 * proximity -> 2 (lower and upper bound)
2117 * local(+any) -> 2 (>= 0 and <= 0)
2119 * If an edge is only marked conditional_validity then it counts
2120 * as zero since it is only checked afterwards.
2122 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2123 * Otherwise, we ignore them.
2125 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2127 if (is_proximity(edge) || is_local(edge))
2128 return 2;
2129 if (use_coincidence && is_coincidence(edge))
2130 return 2;
2131 if (is_validity(edge))
2132 return 1;
2133 return 0;
2136 /* Count the number of equality and inequality constraints
2137 * that will be added for the given map.
2139 * "use_coincidence" is set if we should take into account coincidence edges.
2141 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2142 struct isl_sched_edge *edge, __isl_take isl_map *map,
2143 int *n_eq, int *n_ineq, int use_coincidence)
2145 isl_basic_set *coef;
2146 int f = edge_multiplicity(edge, use_coincidence);
2148 if (f == 0) {
2149 isl_map_free(map);
2150 return isl_stat_ok;
2153 if (edge->src == edge->dst)
2154 coef = intra_coefficients(graph, edge->src, map);
2155 else
2156 coef = inter_coefficients(graph, edge, map);
2157 if (!coef)
2158 return isl_stat_error;
2159 *n_eq += f * isl_basic_set_n_equality(coef);
2160 *n_ineq += f * isl_basic_set_n_inequality(coef);
2161 isl_basic_set_free(coef);
2163 return isl_stat_ok;
2166 /* Count the number of equality and inequality constraints
2167 * that will be added to the main lp problem.
2168 * We count as follows
2169 * validity -> 1 (>= 0)
2170 * validity+proximity -> 2 (>= 0 and upper bound)
2171 * proximity -> 2 (lower and upper bound)
2172 * local(+any) -> 2 (>= 0 and <= 0)
2174 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2175 * Otherwise, we ignore them.
2177 static int count_constraints(struct isl_sched_graph *graph,
2178 int *n_eq, int *n_ineq, int use_coincidence)
2180 int i;
2182 *n_eq = *n_ineq = 0;
2183 for (i = 0; i < graph->n_edge; ++i) {
2184 struct isl_sched_edge *edge = &graph->edge[i];
2185 isl_map *map = isl_map_copy(edge->map);
2187 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2188 use_coincidence) < 0)
2189 return -1;
2192 return 0;
2195 /* Count the number of constraints that will be added by
2196 * add_bound_constant_constraints to bound the values of the constant terms
2197 * and increment *n_eq and *n_ineq accordingly.
2199 * In practice, add_bound_constant_constraints only adds inequalities.
2201 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2202 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2204 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2205 return isl_stat_ok;
2207 *n_ineq += graph->n;
2209 return isl_stat_ok;
2212 /* Add constraints to bound the values of the constant terms in the schedule,
2213 * if requested by the user.
2215 * The maximal value of the constant terms is defined by the option
2216 * "schedule_max_constant_term".
2218 * Within each node, the coefficients have the following order:
2219 * - c_i_0
2220 * - c_i_n (if parametric)
2221 * - positive and negative parts of c_i_x
2223 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2224 struct isl_sched_graph *graph)
2226 int i, k;
2227 int max;
2228 int total;
2230 max = isl_options_get_schedule_max_constant_term(ctx);
2231 if (max == -1)
2232 return isl_stat_ok;
2234 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2236 for (i = 0; i < graph->n; ++i) {
2237 struct isl_sched_node *node = &graph->node[i];
2238 k = isl_basic_set_alloc_inequality(graph->lp);
2239 if (k < 0)
2240 return isl_stat_error;
2241 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2242 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2243 isl_int_set_si(graph->lp->ineq[k][0], max);
2246 return isl_stat_ok;
2249 /* Count the number of constraints that will be added by
2250 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2251 * accordingly.
2253 * In practice, add_bound_coefficient_constraints only adds inequalities.
2255 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2256 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2258 int i;
2260 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2261 !isl_options_get_schedule_treat_coalescing(ctx))
2262 return 0;
2264 for (i = 0; i < graph->n; ++i)
2265 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2267 return 0;
2270 /* Add constraints to graph->lp that bound the values of
2271 * the parameter schedule coefficients of "node" to "max" and
2272 * the variable schedule coefficients to the corresponding entry
2273 * in node->max.
2274 * In either case, a negative value means that no bound needs to be imposed.
2276 * For parameter coefficients, this amounts to adding a constraint
2278 * c_n <= max
2280 * i.e.,
2282 * -c_n + max >= 0
2284 * The variables coefficients are, however, not represented directly.
2285 * Instead, the variables coefficients c_x are written as a linear
2286 * combination c_x = cmap c_z of some other coefficients c_z,
2287 * which are in turn encoded as c_z = c_z^+ - c_z^-.
2288 * Let a_j be the elements of row i of node->cmap, then
2290 * -max_i <= c_x_i <= max_i
2292 * is encoded as
2294 * -max_i <= \sum_j a_j (c_z_j^+ - c_z_j^-) <= max_i
2296 * or
2298 * -\sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2299 * \sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2301 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2302 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2304 int i, j, k;
2305 int total;
2306 isl_vec *ineq;
2308 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2310 for (j = 0; j < node->nparam; ++j) {
2311 int dim;
2313 if (max < 0)
2314 continue;
2316 k = isl_basic_set_alloc_inequality(graph->lp);
2317 if (k < 0)
2318 return isl_stat_error;
2319 dim = 1 + node->start + 1 + j;
2320 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2321 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2322 isl_int_set_si(graph->lp->ineq[k][0], max);
2325 ineq = isl_vec_alloc(ctx, 1 + total);
2326 ineq = isl_vec_clr(ineq);
2327 if (!ineq)
2328 return isl_stat_error;
2329 for (i = 0; i < node->nvar; ++i) {
2330 int pos = 1 + node_var_coef_offset(node);
2332 if (isl_int_is_neg(node->max->el[i]))
2333 continue;
2335 for (j = 0; j < node->nvar; ++j) {
2336 int pos_j = 1 + node_var_coef_pos(node, j);
2338 isl_int_set(ineq->el[pos_j], node->cmap->row[i][j]);
2339 isl_int_neg(ineq->el[pos_j], node->cmap->row[i][j]);
2341 isl_int_set(ineq->el[0], node->max->el[i]);
2343 k = isl_basic_set_alloc_inequality(graph->lp);
2344 if (k < 0)
2345 goto error;
2346 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2348 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2 * node->nvar);
2349 k = isl_basic_set_alloc_inequality(graph->lp);
2350 if (k < 0)
2351 goto error;
2352 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2354 isl_vec_free(ineq);
2356 return isl_stat_ok;
2357 error:
2358 isl_vec_free(ineq);
2359 return isl_stat_error;
2362 /* Add constraints that bound the values of the variable and parameter
2363 * coefficients of the schedule.
2365 * The maximal value of the coefficients is defined by the option
2366 * 'schedule_max_coefficient' and the entries in node->max.
2367 * These latter entries are only set if either the schedule_max_coefficient
2368 * option or the schedule_treat_coalescing option is set.
2370 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2371 struct isl_sched_graph *graph)
2373 int i;
2374 int max;
2376 max = isl_options_get_schedule_max_coefficient(ctx);
2378 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2379 return isl_stat_ok;
2381 for (i = 0; i < graph->n; ++i) {
2382 struct isl_sched_node *node = &graph->node[i];
2384 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2385 return isl_stat_error;
2388 return isl_stat_ok;
2391 /* Add a constraint to graph->lp that equates the value at position
2392 * "sum_pos" to the sum of the "n" values starting at "first".
2394 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2395 int sum_pos, int first, int n)
2397 int i, k;
2398 int total;
2400 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2402 k = isl_basic_set_alloc_equality(graph->lp);
2403 if (k < 0)
2404 return isl_stat_error;
2405 isl_seq_clr(graph->lp->eq[k], 1 + total);
2406 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2407 for (i = 0; i < n; ++i)
2408 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2410 return isl_stat_ok;
2413 /* Add a constraint to graph->lp that equates the value at position
2414 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2416 * Within each node, the coefficients have the following order:
2417 * - c_i_0
2418 * - c_i_n (if parametric)
2419 * - positive and negative parts of c_i_x
2421 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2422 int sum_pos)
2424 int i, j, k;
2425 int total;
2427 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2429 k = isl_basic_set_alloc_equality(graph->lp);
2430 if (k < 0)
2431 return isl_stat_error;
2432 isl_seq_clr(graph->lp->eq[k], 1 + total);
2433 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2434 for (i = 0; i < graph->n; ++i) {
2435 int pos = 1 + graph->node[i].start + 1;
2437 for (j = 0; j < graph->node[i].nparam; ++j)
2438 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2441 return isl_stat_ok;
2444 /* Add a constraint to graph->lp that equates the value at position
2445 * "sum_pos" to the sum of the variable coefficients of all nodes.
2447 * Within each node, the coefficients have the following order:
2448 * - c_i_0
2449 * - c_i_n (if parametric)
2450 * - positive and negative parts of c_i_x
2452 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2453 int sum_pos)
2455 int i, j, k;
2456 int total;
2458 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2460 k = isl_basic_set_alloc_equality(graph->lp);
2461 if (k < 0)
2462 return isl_stat_error;
2463 isl_seq_clr(graph->lp->eq[k], 1 + total);
2464 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2465 for (i = 0; i < graph->n; ++i) {
2466 struct isl_sched_node *node = &graph->node[i];
2467 int pos = 1 + node_var_coef_offset(node);
2469 for (j = 0; j < 2 * node->nvar; ++j)
2470 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2473 return isl_stat_ok;
2476 /* Construct an ILP problem for finding schedule coefficients
2477 * that result in non-negative, but small dependence distances
2478 * over all dependences.
2479 * In particular, the dependence distances over proximity edges
2480 * are bounded by m_0 + m_n n and we compute schedule coefficients
2481 * with small values (preferably zero) of m_n and m_0.
2483 * All variables of the ILP are non-negative. The actual coefficients
2484 * may be negative, so each coefficient is represented as the difference
2485 * of two non-negative variables. The negative part always appears
2486 * immediately before the positive part.
2487 * Other than that, the variables have the following order
2489 * - sum of positive and negative parts of m_n coefficients
2490 * - m_0
2491 * - sum of all c_n coefficients
2492 * (unconstrained when computing non-parametric schedules)
2493 * - sum of positive and negative parts of all c_x coefficients
2494 * - positive and negative parts of m_n coefficients
2495 * - for each node
2496 * - c_i_0
2497 * - c_i_n (if parametric)
2498 * - positive and negative parts of c_i_x, in opposite order
2500 * The c_i_x are not represented directly, but through the columns of
2501 * node->cmap. That is, the computed values are for variable t_i_x
2502 * such that c_i_x = Q t_i_x with Q equal to node->cmap.
2504 * The constraints are those from the edges plus two or three equalities
2505 * to express the sums.
2507 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2508 * Otherwise, we ignore them.
2510 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2511 int use_coincidence)
2513 int i;
2514 unsigned nparam;
2515 unsigned total;
2516 isl_space *space;
2517 int parametric;
2518 int param_pos;
2519 int n_eq, n_ineq;
2521 parametric = ctx->opt->schedule_parametric;
2522 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2523 param_pos = 4;
2524 total = param_pos + 2 * nparam;
2525 for (i = 0; i < graph->n; ++i) {
2526 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2527 if (node_update_cmap(node) < 0)
2528 return isl_stat_error;
2529 node->start = total;
2530 total += 1 + node->nparam + 2 * node->nvar;
2533 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2534 return isl_stat_error;
2535 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2536 return isl_stat_error;
2537 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2538 return isl_stat_error;
2540 space = isl_space_set_alloc(ctx, 0, total);
2541 isl_basic_set_free(graph->lp);
2542 n_eq += 2 + parametric;
2544 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2546 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2547 return isl_stat_error;
2548 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2549 return isl_stat_error;
2550 if (add_var_sum_constraint(graph, 3) < 0)
2551 return isl_stat_error;
2552 if (add_bound_constant_constraints(ctx, graph) < 0)
2553 return isl_stat_error;
2554 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2555 return isl_stat_error;
2556 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2557 return isl_stat_error;
2558 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2559 return isl_stat_error;
2561 return isl_stat_ok;
2564 /* Analyze the conflicting constraint found by
2565 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2566 * constraint of one of the edges between distinct nodes, living, moreover
2567 * in distinct SCCs, then record the source and sink SCC as this may
2568 * be a good place to cut between SCCs.
2570 static int check_conflict(int con, void *user)
2572 int i;
2573 struct isl_sched_graph *graph = user;
2575 if (graph->src_scc >= 0)
2576 return 0;
2578 con -= graph->lp->n_eq;
2580 if (con >= graph->lp->n_ineq)
2581 return 0;
2583 for (i = 0; i < graph->n_edge; ++i) {
2584 if (!is_validity(&graph->edge[i]))
2585 continue;
2586 if (graph->edge[i].src == graph->edge[i].dst)
2587 continue;
2588 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2589 continue;
2590 if (graph->edge[i].start > con)
2591 continue;
2592 if (graph->edge[i].end <= con)
2593 continue;
2594 graph->src_scc = graph->edge[i].src->scc;
2595 graph->dst_scc = graph->edge[i].dst->scc;
2598 return 0;
2601 /* Check whether the next schedule row of the given node needs to be
2602 * non-trivial. Lower-dimensional domains may have some trivial rows,
2603 * but as soon as the number of remaining required non-trivial rows
2604 * is as large as the number or remaining rows to be computed,
2605 * all remaining rows need to be non-trivial.
2607 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2609 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2612 /* Construct a non-triviality region with "n" directions
2613 * over "n_var" coefficients.
2614 * Each direction corresponds to a schedule coefficient,
2615 * where each schedule coefficient is encoded as the difference
2616 * of two non-negative variables, c^+_i - c^-_i
2617 * with c^-_i at position 2 * i and c^+_i at position 2 * i + 1.
2618 * The order of the directions is the same as that of the node variables,
2619 * but the pairs of non-negative variables representing the coefficients
2620 * are stored in the opposite order.
2621 * The first direction therefore corresponds to the last such pair.
2622 * Furthermore, if the number of variables is greater than the number
2623 * of directions, then the directions correspond to the last node variables,
2624 * i.e., the first pairs of non-negative variables.
2626 static __isl_give isl_mat *construct_trivial(isl_ctx *ctx, int n, int n_var)
2628 isl_mat *mat;
2629 int i, off;
2631 off = n_var - n;
2632 mat = isl_mat_zero(ctx, n, 2 * n_var);
2633 for (i = 0; i < n; ++i) {
2634 mat = isl_mat_set_element_si(mat, i, 2 * (n - 1 - i), -1);
2635 mat = isl_mat_set_element_si(mat, i, 2 * (n - 1 - i) + 1, 1);
2638 return mat;
2641 /* Solve the ILP problem constructed in setup_lp.
2642 * For each node such that all the remaining rows of its schedule
2643 * need to be non-trivial, we construct a non-triviality region.
2644 * This region imposes that the next row is independent of previous rows.
2645 * In particular the coefficients c_i_x are represented by t_i_x
2646 * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
2647 * its first columns span the rows of the previously computed part
2648 * of the schedule. The non-triviality region enforces that at least
2649 * one of the remaining components of t_i_x is non-zero, i.e.,
2650 * that the new schedule row depends on at least one of the remaining
2651 * columns of Q.
2653 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2655 int i;
2656 isl_vec *sol;
2657 isl_basic_set *lp;
2659 for (i = 0; i < graph->n; ++i) {
2660 struct isl_sched_node *node = &graph->node[i];
2661 int skip = node->rank;
2662 isl_mat *trivial;
2664 graph->region[i].pos = node_var_coef_offset(node);
2665 if (needs_row(graph, node))
2666 trivial = construct_trivial(ctx, node->nvar - skip,
2667 node->nvar);
2668 else
2669 trivial = isl_mat_zero(ctx, 0, 0);
2670 graph->region[i].trivial = trivial;
2672 lp = isl_basic_set_copy(graph->lp);
2673 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2674 graph->region, &check_conflict, graph);
2675 for (i = 0; i < graph->n; ++i)
2676 isl_mat_free(graph->region[i].trivial);
2677 return sol;
2680 /* Extract the coefficients for the variables of "node" from "sol".
2682 * Within each node, the coefficients have the following order:
2683 * - c_i_0
2684 * - c_i_n (if parametric)
2685 * - positive and negative parts of c_i_x
2687 * The c_i_x^- appear before their c_i_x^+ counterpart.
2688 * Furthermore, the order of these pairs is the opposite of that
2689 * of the corresponding coefficients.
2691 * Return c_i_x = c_i_x^+ - c_i_x^-
2693 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2694 __isl_keep isl_vec *sol)
2696 int i;
2697 int pos;
2698 isl_vec *csol;
2700 if (!sol)
2701 return NULL;
2702 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2703 if (!csol)
2704 return NULL;
2706 pos = 1 + node_var_coef_offset(node);
2707 for (i = 0; i < node->nvar; ++i)
2708 isl_int_sub(csol->el[node->nvar - 1 - i],
2709 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2711 return csol;
2714 /* Update the schedules of all nodes based on the given solution
2715 * of the LP problem.
2716 * The new row is added to the current band.
2717 * All possibly negative coefficients are encoded as a difference
2718 * of two non-negative variables, so we need to perform the subtraction
2719 * here. Moreover, if use_cmap is set, then the solution does
2720 * not refer to the actual coefficients c_i_x, but instead to variables
2721 * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
2722 * In this case, we then also need to perform this multiplication
2723 * to obtain the values of c_i_x.
2725 * If coincident is set, then the caller guarantees that the new
2726 * row satisfies the coincidence constraints.
2728 static int update_schedule(struct isl_sched_graph *graph,
2729 __isl_take isl_vec *sol, int use_cmap, int coincident)
2731 int i, j;
2732 isl_vec *csol = NULL;
2734 if (!sol)
2735 goto error;
2736 if (sol->size == 0)
2737 isl_die(sol->ctx, isl_error_internal,
2738 "no solution found", goto error);
2739 if (graph->n_total_row >= graph->max_row)
2740 isl_die(sol->ctx, isl_error_internal,
2741 "too many schedule rows", goto error);
2743 for (i = 0; i < graph->n; ++i) {
2744 struct isl_sched_node *node = &graph->node[i];
2745 int pos = node->start;
2746 int row = isl_mat_rows(node->sched);
2748 isl_vec_free(csol);
2749 csol = extract_var_coef(node, sol);
2750 if (!csol)
2751 goto error;
2753 isl_map_free(node->sched_map);
2754 node->sched_map = NULL;
2755 node->sched = isl_mat_add_rows(node->sched, 1);
2756 if (!node->sched)
2757 goto error;
2758 for (j = 0; j < 1 + node->nparam; ++j)
2759 node->sched = isl_mat_set_element(node->sched,
2760 row, j, sol->el[1 + pos + j]);
2761 if (use_cmap)
2762 csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
2763 csol);
2764 if (!csol)
2765 goto error;
2766 for (j = 0; j < node->nvar; ++j)
2767 node->sched = isl_mat_set_element(node->sched,
2768 row, 1 + node->nparam + j, csol->el[j]);
2769 node->coincident[graph->n_total_row] = coincident;
2771 isl_vec_free(sol);
2772 isl_vec_free(csol);
2774 graph->n_row++;
2775 graph->n_total_row++;
2777 return 0;
2778 error:
2779 isl_vec_free(sol);
2780 isl_vec_free(csol);
2781 return -1;
2784 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2785 * and return this isl_aff.
2787 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2788 struct isl_sched_node *node, int row)
2790 int j;
2791 isl_int v;
2792 isl_aff *aff;
2794 isl_int_init(v);
2796 aff = isl_aff_zero_on_domain(ls);
2797 isl_mat_get_element(node->sched, row, 0, &v);
2798 aff = isl_aff_set_constant(aff, v);
2799 for (j = 0; j < node->nparam; ++j) {
2800 isl_mat_get_element(node->sched, row, 1 + j, &v);
2801 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2803 for (j = 0; j < node->nvar; ++j) {
2804 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2805 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2808 isl_int_clear(v);
2810 return aff;
2813 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2814 * and return this multi_aff.
2816 * The result is defined over the uncompressed node domain.
2818 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2819 struct isl_sched_node *node, int first, int n)
2821 int i;
2822 isl_space *space;
2823 isl_local_space *ls;
2824 isl_aff *aff;
2825 isl_multi_aff *ma;
2826 int nrow;
2828 if (!node)
2829 return NULL;
2830 nrow = isl_mat_rows(node->sched);
2831 if (node->compressed)
2832 space = isl_multi_aff_get_domain_space(node->decompress);
2833 else
2834 space = isl_space_copy(node->space);
2835 ls = isl_local_space_from_space(isl_space_copy(space));
2836 space = isl_space_from_domain(space);
2837 space = isl_space_add_dims(space, isl_dim_out, n);
2838 ma = isl_multi_aff_zero(space);
2840 for (i = first; i < first + n; ++i) {
2841 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2842 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2845 isl_local_space_free(ls);
2847 if (node->compressed)
2848 ma = isl_multi_aff_pullback_multi_aff(ma,
2849 isl_multi_aff_copy(node->compress));
2851 return ma;
2854 /* Convert node->sched into a multi_aff and return this multi_aff.
2856 * The result is defined over the uncompressed node domain.
2858 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2859 struct isl_sched_node *node)
2861 int nrow;
2863 nrow = isl_mat_rows(node->sched);
2864 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2867 /* Convert node->sched into a map and return this map.
2869 * The result is cached in node->sched_map, which needs to be released
2870 * whenever node->sched is updated.
2871 * It is defined over the uncompressed node domain.
2873 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2875 if (!node->sched_map) {
2876 isl_multi_aff *ma;
2878 ma = node_extract_schedule_multi_aff(node);
2879 node->sched_map = isl_map_from_multi_aff(ma);
2882 return isl_map_copy(node->sched_map);
2885 /* Construct a map that can be used to update a dependence relation
2886 * based on the current schedule.
2887 * That is, construct a map expressing that source and sink
2888 * are executed within the same iteration of the current schedule.
2889 * This map can then be intersected with the dependence relation.
2890 * This is not the most efficient way, but this shouldn't be a critical
2891 * operation.
2893 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2894 struct isl_sched_node *dst)
2896 isl_map *src_sched, *dst_sched;
2898 src_sched = node_extract_schedule(src);
2899 dst_sched = node_extract_schedule(dst);
2900 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2903 /* Intersect the domains of the nested relations in domain and range
2904 * of "umap" with "map".
2906 static __isl_give isl_union_map *intersect_domains(
2907 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2909 isl_union_set *uset;
2911 umap = isl_union_map_zip(umap);
2912 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2913 umap = isl_union_map_intersect_domain(umap, uset);
2914 umap = isl_union_map_zip(umap);
2915 return umap;
2918 /* Update the dependence relation of the given edge based
2919 * on the current schedule.
2920 * If the dependence is carried completely by the current schedule, then
2921 * it is removed from the edge_tables. It is kept in the list of edges
2922 * as otherwise all edge_tables would have to be recomputed.
2924 static int update_edge(struct isl_sched_graph *graph,
2925 struct isl_sched_edge *edge)
2927 int empty;
2928 isl_map *id;
2930 id = specializer(edge->src, edge->dst);
2931 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2932 if (!edge->map)
2933 goto error;
2935 if (edge->tagged_condition) {
2936 edge->tagged_condition =
2937 intersect_domains(edge->tagged_condition, id);
2938 if (!edge->tagged_condition)
2939 goto error;
2941 if (edge->tagged_validity) {
2942 edge->tagged_validity =
2943 intersect_domains(edge->tagged_validity, id);
2944 if (!edge->tagged_validity)
2945 goto error;
2948 empty = isl_map_plain_is_empty(edge->map);
2949 if (empty < 0)
2950 goto error;
2951 if (empty)
2952 graph_remove_edge(graph, edge);
2954 isl_map_free(id);
2955 return 0;
2956 error:
2957 isl_map_free(id);
2958 return -1;
2961 /* Does the domain of "umap" intersect "uset"?
2963 static int domain_intersects(__isl_keep isl_union_map *umap,
2964 __isl_keep isl_union_set *uset)
2966 int empty;
2968 umap = isl_union_map_copy(umap);
2969 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2970 empty = isl_union_map_is_empty(umap);
2971 isl_union_map_free(umap);
2973 return empty < 0 ? -1 : !empty;
2976 /* Does the range of "umap" intersect "uset"?
2978 static int range_intersects(__isl_keep isl_union_map *umap,
2979 __isl_keep isl_union_set *uset)
2981 int empty;
2983 umap = isl_union_map_copy(umap);
2984 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2985 empty = isl_union_map_is_empty(umap);
2986 isl_union_map_free(umap);
2988 return empty < 0 ? -1 : !empty;
2991 /* Are the condition dependences of "edge" local with respect to
2992 * the current schedule?
2994 * That is, are domain and range of the condition dependences mapped
2995 * to the same point?
2997 * In other words, is the condition false?
2999 static int is_condition_false(struct isl_sched_edge *edge)
3001 isl_union_map *umap;
3002 isl_map *map, *sched, *test;
3003 int empty, local;
3005 empty = isl_union_map_is_empty(edge->tagged_condition);
3006 if (empty < 0 || empty)
3007 return empty;
3009 umap = isl_union_map_copy(edge->tagged_condition);
3010 umap = isl_union_map_zip(umap);
3011 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3012 map = isl_map_from_union_map(umap);
3014 sched = node_extract_schedule(edge->src);
3015 map = isl_map_apply_domain(map, sched);
3016 sched = node_extract_schedule(edge->dst);
3017 map = isl_map_apply_range(map, sched);
3019 test = isl_map_identity(isl_map_get_space(map));
3020 local = isl_map_is_subset(map, test);
3021 isl_map_free(map);
3022 isl_map_free(test);
3024 return local;
3027 /* For each conditional validity constraint that is adjacent
3028 * to a condition with domain in condition_source or range in condition_sink,
3029 * turn it into an unconditional validity constraint.
3031 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3032 __isl_take isl_union_set *condition_source,
3033 __isl_take isl_union_set *condition_sink)
3035 int i;
3037 condition_source = isl_union_set_coalesce(condition_source);
3038 condition_sink = isl_union_set_coalesce(condition_sink);
3040 for (i = 0; i < graph->n_edge; ++i) {
3041 int adjacent;
3042 isl_union_map *validity;
3044 if (!is_conditional_validity(&graph->edge[i]))
3045 continue;
3046 if (is_validity(&graph->edge[i]))
3047 continue;
3049 validity = graph->edge[i].tagged_validity;
3050 adjacent = domain_intersects(validity, condition_sink);
3051 if (adjacent >= 0 && !adjacent)
3052 adjacent = range_intersects(validity, condition_source);
3053 if (adjacent < 0)
3054 goto error;
3055 if (!adjacent)
3056 continue;
3058 set_validity(&graph->edge[i]);
3061 isl_union_set_free(condition_source);
3062 isl_union_set_free(condition_sink);
3063 return 0;
3064 error:
3065 isl_union_set_free(condition_source);
3066 isl_union_set_free(condition_sink);
3067 return -1;
3070 /* Update the dependence relations of all edges based on the current schedule
3071 * and enforce conditional validity constraints that are adjacent
3072 * to satisfied condition constraints.
3074 * First check if any of the condition constraints are satisfied
3075 * (i.e., not local to the outer schedule) and keep track of
3076 * their domain and range.
3077 * Then update all dependence relations (which removes the non-local
3078 * constraints).
3079 * Finally, if any condition constraints turned out to be satisfied,
3080 * then turn all adjacent conditional validity constraints into
3081 * unconditional validity constraints.
3083 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3085 int i;
3086 int any = 0;
3087 isl_union_set *source, *sink;
3089 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3090 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3091 for (i = 0; i < graph->n_edge; ++i) {
3092 int local;
3093 isl_union_set *uset;
3094 isl_union_map *umap;
3096 if (!is_condition(&graph->edge[i]))
3097 continue;
3098 if (is_local(&graph->edge[i]))
3099 continue;
3100 local = is_condition_false(&graph->edge[i]);
3101 if (local < 0)
3102 goto error;
3103 if (local)
3104 continue;
3106 any = 1;
3108 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3109 uset = isl_union_map_domain(umap);
3110 source = isl_union_set_union(source, uset);
3112 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3113 uset = isl_union_map_range(umap);
3114 sink = isl_union_set_union(sink, uset);
3117 for (i = graph->n_edge - 1; i >= 0; --i) {
3118 if (update_edge(graph, &graph->edge[i]) < 0)
3119 goto error;
3122 if (any)
3123 return unconditionalize_adjacent_validity(graph, source, sink);
3125 isl_union_set_free(source);
3126 isl_union_set_free(sink);
3127 return 0;
3128 error:
3129 isl_union_set_free(source);
3130 isl_union_set_free(sink);
3131 return -1;
3134 static void next_band(struct isl_sched_graph *graph)
3136 graph->band_start = graph->n_total_row;
3139 /* Return the union of the universe domains of the nodes in "graph"
3140 * that satisfy "pred".
3142 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3143 struct isl_sched_graph *graph,
3144 int (*pred)(struct isl_sched_node *node, int data), int data)
3146 int i;
3147 isl_set *set;
3148 isl_union_set *dom;
3150 for (i = 0; i < graph->n; ++i)
3151 if (pred(&graph->node[i], data))
3152 break;
3154 if (i >= graph->n)
3155 isl_die(ctx, isl_error_internal,
3156 "empty component", return NULL);
3158 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3159 dom = isl_union_set_from_set(set);
3161 for (i = i + 1; i < graph->n; ++i) {
3162 if (!pred(&graph->node[i], data))
3163 continue;
3164 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3165 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3168 return dom;
3171 /* Return a list of unions of universe domains, where each element
3172 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3174 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3175 struct isl_sched_graph *graph)
3177 int i;
3178 isl_union_set_list *filters;
3180 filters = isl_union_set_list_alloc(ctx, graph->scc);
3181 for (i = 0; i < graph->scc; ++i) {
3182 isl_union_set *dom;
3184 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3185 filters = isl_union_set_list_add(filters, dom);
3188 return filters;
3191 /* Return a list of two unions of universe domains, one for the SCCs up
3192 * to and including graph->src_scc and another for the other SCCs.
3194 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3195 struct isl_sched_graph *graph)
3197 isl_union_set *dom;
3198 isl_union_set_list *filters;
3200 filters = isl_union_set_list_alloc(ctx, 2);
3201 dom = isl_sched_graph_domain(ctx, graph,
3202 &node_scc_at_most, graph->src_scc);
3203 filters = isl_union_set_list_add(filters, dom);
3204 dom = isl_sched_graph_domain(ctx, graph,
3205 &node_scc_at_least, graph->src_scc + 1);
3206 filters = isl_union_set_list_add(filters, dom);
3208 return filters;
3211 /* Copy nodes that satisfy node_pred from the src dependence graph
3212 * to the dst dependence graph.
3214 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3215 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3217 int i;
3219 dst->n = 0;
3220 for (i = 0; i < src->n; ++i) {
3221 int j;
3223 if (!node_pred(&src->node[i], data))
3224 continue;
3226 j = dst->n;
3227 dst->node[j].space = isl_space_copy(src->node[i].space);
3228 dst->node[j].compressed = src->node[i].compressed;
3229 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3230 dst->node[j].compress =
3231 isl_multi_aff_copy(src->node[i].compress);
3232 dst->node[j].decompress =
3233 isl_multi_aff_copy(src->node[i].decompress);
3234 dst->node[j].nvar = src->node[i].nvar;
3235 dst->node[j].nparam = src->node[i].nparam;
3236 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3237 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3238 dst->node[j].coincident = src->node[i].coincident;
3239 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3240 dst->node[j].max = isl_vec_copy(src->node[i].max);
3241 dst->n++;
3243 if (!dst->node[j].space || !dst->node[j].sched)
3244 return -1;
3245 if (dst->node[j].compressed &&
3246 (!dst->node[j].hull || !dst->node[j].compress ||
3247 !dst->node[j].decompress))
3248 return -1;
3251 return 0;
3254 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3255 * to the dst dependence graph.
3256 * If the source or destination node of the edge is not in the destination
3257 * graph, then it must be a backward proximity edge and it should simply
3258 * be ignored.
3260 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3261 struct isl_sched_graph *src,
3262 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3264 int i;
3265 enum isl_edge_type t;
3267 dst->n_edge = 0;
3268 for (i = 0; i < src->n_edge; ++i) {
3269 struct isl_sched_edge *edge = &src->edge[i];
3270 isl_map *map;
3271 isl_union_map *tagged_condition;
3272 isl_union_map *tagged_validity;
3273 struct isl_sched_node *dst_src, *dst_dst;
3275 if (!edge_pred(edge, data))
3276 continue;
3278 if (isl_map_plain_is_empty(edge->map))
3279 continue;
3281 dst_src = graph_find_node(ctx, dst, edge->src->space);
3282 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3283 if (!dst_src || !dst_dst) {
3284 if (is_validity(edge) || is_conditional_validity(edge))
3285 isl_die(ctx, isl_error_internal,
3286 "backward (conditional) validity edge",
3287 return -1);
3288 continue;
3291 map = isl_map_copy(edge->map);
3292 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3293 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3295 dst->edge[dst->n_edge].src = dst_src;
3296 dst->edge[dst->n_edge].dst = dst_dst;
3297 dst->edge[dst->n_edge].map = map;
3298 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3299 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3300 dst->edge[dst->n_edge].types = edge->types;
3301 dst->n_edge++;
3303 if (edge->tagged_condition && !tagged_condition)
3304 return -1;
3305 if (edge->tagged_validity && !tagged_validity)
3306 return -1;
3308 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3309 if (edge !=
3310 graph_find_edge(src, t, edge->src, edge->dst))
3311 continue;
3312 if (graph_edge_table_add(ctx, dst, t,
3313 &dst->edge[dst->n_edge - 1]) < 0)
3314 return -1;
3318 return 0;
3321 /* Compute the maximal number of variables over all nodes.
3322 * This is the maximal number of linearly independent schedule
3323 * rows that we need to compute.
3324 * Just in case we end up in a part of the dependence graph
3325 * with only lower-dimensional domains, we make sure we will
3326 * compute the required amount of extra linearly independent rows.
3328 static int compute_maxvar(struct isl_sched_graph *graph)
3330 int i;
3332 graph->maxvar = 0;
3333 for (i = 0; i < graph->n; ++i) {
3334 struct isl_sched_node *node = &graph->node[i];
3335 int nvar;
3337 if (node_update_cmap(node) < 0)
3338 return -1;
3339 nvar = node->nvar + graph->n_row - node->rank;
3340 if (nvar > graph->maxvar)
3341 graph->maxvar = nvar;
3344 return 0;
3347 /* Extract the subgraph of "graph" that consists of the node satisfying
3348 * "node_pred" and the edges satisfying "edge_pred" and store
3349 * the result in "sub".
3351 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3352 int (*node_pred)(struct isl_sched_node *node, int data),
3353 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3354 int data, struct isl_sched_graph *sub)
3356 int i, n = 0, n_edge = 0;
3357 int t;
3359 for (i = 0; i < graph->n; ++i)
3360 if (node_pred(&graph->node[i], data))
3361 ++n;
3362 for (i = 0; i < graph->n_edge; ++i)
3363 if (edge_pred(&graph->edge[i], data))
3364 ++n_edge;
3365 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3366 return -1;
3367 if (copy_nodes(sub, graph, node_pred, data) < 0)
3368 return -1;
3369 if (graph_init_table(ctx, sub) < 0)
3370 return -1;
3371 for (t = 0; t <= isl_edge_last; ++t)
3372 sub->max_edge[t] = graph->max_edge[t];
3373 if (graph_init_edge_tables(ctx, sub) < 0)
3374 return -1;
3375 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3376 return -1;
3377 sub->n_row = graph->n_row;
3378 sub->max_row = graph->max_row;
3379 sub->n_total_row = graph->n_total_row;
3380 sub->band_start = graph->band_start;
3382 return 0;
3385 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3386 struct isl_sched_graph *graph);
3387 static __isl_give isl_schedule_node *compute_schedule_wcc(
3388 isl_schedule_node *node, struct isl_sched_graph *graph);
3390 /* Compute a schedule for a subgraph of "graph". In particular, for
3391 * the graph composed of nodes that satisfy node_pred and edges that
3392 * that satisfy edge_pred.
3393 * If the subgraph is known to consist of a single component, then wcc should
3394 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3395 * Otherwise, we call compute_schedule, which will check whether the subgraph
3396 * is connected.
3398 * The schedule is inserted at "node" and the updated schedule node
3399 * is returned.
3401 static __isl_give isl_schedule_node *compute_sub_schedule(
3402 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3403 struct isl_sched_graph *graph,
3404 int (*node_pred)(struct isl_sched_node *node, int data),
3405 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3406 int data, int wcc)
3408 struct isl_sched_graph split = { 0 };
3410 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3411 &split) < 0)
3412 goto error;
3414 if (wcc)
3415 node = compute_schedule_wcc(node, &split);
3416 else
3417 node = compute_schedule(node, &split);
3419 graph_free(ctx, &split);
3420 return node;
3421 error:
3422 graph_free(ctx, &split);
3423 return isl_schedule_node_free(node);
3426 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3428 return edge->src->scc == scc && edge->dst->scc == scc;
3431 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3433 return edge->dst->scc <= scc;
3436 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3438 return edge->src->scc >= scc;
3441 /* Reset the current band by dropping all its schedule rows.
3443 static int reset_band(struct isl_sched_graph *graph)
3445 int i;
3446 int drop;
3448 drop = graph->n_total_row - graph->band_start;
3449 graph->n_total_row -= drop;
3450 graph->n_row -= drop;
3452 for (i = 0; i < graph->n; ++i) {
3453 struct isl_sched_node *node = &graph->node[i];
3455 isl_map_free(node->sched_map);
3456 node->sched_map = NULL;
3458 node->sched = isl_mat_drop_rows(node->sched,
3459 graph->band_start, drop);
3461 if (!node->sched)
3462 return -1;
3465 return 0;
3468 /* Split the current graph into two parts and compute a schedule for each
3469 * part individually. In particular, one part consists of all SCCs up
3470 * to and including graph->src_scc, while the other part contains the other
3471 * SCCs. The split is enforced by a sequence node inserted at position "node"
3472 * in the schedule tree. Return the updated schedule node.
3473 * If either of these two parts consists of a sequence, then it is spliced
3474 * into the sequence containing the two parts.
3476 * The current band is reset. It would be possible to reuse
3477 * the previously computed rows as the first rows in the next
3478 * band, but recomputing them may result in better rows as we are looking
3479 * at a smaller part of the dependence graph.
3481 static __isl_give isl_schedule_node *compute_split_schedule(
3482 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3484 int is_seq;
3485 isl_ctx *ctx;
3486 isl_union_set_list *filters;
3488 if (!node)
3489 return NULL;
3491 if (reset_band(graph) < 0)
3492 return isl_schedule_node_free(node);
3494 next_band(graph);
3496 ctx = isl_schedule_node_get_ctx(node);
3497 filters = extract_split(ctx, graph);
3498 node = isl_schedule_node_insert_sequence(node, filters);
3499 node = isl_schedule_node_child(node, 1);
3500 node = isl_schedule_node_child(node, 0);
3502 node = compute_sub_schedule(node, ctx, graph,
3503 &node_scc_at_least, &edge_src_scc_at_least,
3504 graph->src_scc + 1, 0);
3505 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3506 node = isl_schedule_node_parent(node);
3507 node = isl_schedule_node_parent(node);
3508 if (is_seq)
3509 node = isl_schedule_node_sequence_splice_child(node, 1);
3510 node = isl_schedule_node_child(node, 0);
3511 node = isl_schedule_node_child(node, 0);
3512 node = compute_sub_schedule(node, ctx, graph,
3513 &node_scc_at_most, &edge_dst_scc_at_most,
3514 graph->src_scc, 0);
3515 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3516 node = isl_schedule_node_parent(node);
3517 node = isl_schedule_node_parent(node);
3518 if (is_seq)
3519 node = isl_schedule_node_sequence_splice_child(node, 0);
3521 return node;
3524 /* Insert a band node at position "node" in the schedule tree corresponding
3525 * to the current band in "graph". Mark the band node permutable
3526 * if "permutable" is set.
3527 * The partial schedules and the coincidence property are extracted
3528 * from the graph nodes.
3529 * Return the updated schedule node.
3531 static __isl_give isl_schedule_node *insert_current_band(
3532 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3533 int permutable)
3535 int i;
3536 int start, end, n;
3537 isl_multi_aff *ma;
3538 isl_multi_pw_aff *mpa;
3539 isl_multi_union_pw_aff *mupa;
3541 if (!node)
3542 return NULL;
3544 if (graph->n < 1)
3545 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3546 "graph should have at least one node",
3547 return isl_schedule_node_free(node));
3549 start = graph->band_start;
3550 end = graph->n_total_row;
3551 n = end - start;
3553 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3554 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3555 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3557 for (i = 1; i < graph->n; ++i) {
3558 isl_multi_union_pw_aff *mupa_i;
3560 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3561 start, n);
3562 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3563 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3564 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3566 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3568 for (i = 0; i < n; ++i)
3569 node = isl_schedule_node_band_member_set_coincident(node, i,
3570 graph->node[0].coincident[start + i]);
3571 node = isl_schedule_node_band_set_permutable(node, permutable);
3573 return node;
3576 /* Update the dependence relations based on the current schedule,
3577 * add the current band to "node" and then continue with the computation
3578 * of the next band.
3579 * Return the updated schedule node.
3581 static __isl_give isl_schedule_node *compute_next_band(
3582 __isl_take isl_schedule_node *node,
3583 struct isl_sched_graph *graph, int permutable)
3585 isl_ctx *ctx;
3587 if (!node)
3588 return NULL;
3590 ctx = isl_schedule_node_get_ctx(node);
3591 if (update_edges(ctx, graph) < 0)
3592 return isl_schedule_node_free(node);
3593 node = insert_current_band(node, graph, permutable);
3594 next_band(graph);
3596 node = isl_schedule_node_child(node, 0);
3597 node = compute_schedule(node, graph);
3598 node = isl_schedule_node_parent(node);
3600 return node;
3603 /* Add the constraints "coef" derived from an edge from "node" to itself
3604 * to graph->lp in order to respect the dependences and to try and carry them.
3605 * "pos" is the sequence number of the edge that needs to be carried.
3606 * "coef" represents general constraints on coefficients (c_0, c_n, c_x)
3607 * of valid constraints for (y - x) with x and y instances of the node.
3609 * The constraints added to graph->lp need to enforce
3611 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3612 * = c_j_x (y - x) >= e_i
3614 * for each (x,y) in the dependence relation of the edge.
3615 * That is, (-e_i, 0, c_j_x) needs to be plugged in for (c_0, c_n, c_x),
3616 * taking into account that each coefficient in c_j_x is represented
3617 * as a pair of non-negative coefficients.
3619 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3620 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3622 int offset;
3623 isl_ctx *ctx;
3624 isl_dim_map *dim_map;
3626 if (!coef)
3627 return isl_stat_error;
3629 ctx = isl_basic_set_get_ctx(coef);
3630 offset = coef_var_offset(coef);
3631 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3632 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3633 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3635 return isl_stat_ok;
3638 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3639 * to graph->lp in order to respect the dependences and to try and carry them.
3640 * "pos" is the sequence number of the edge that needs to be carried.
3641 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3642 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3644 * The constraints added to graph->lp need to enforce
3646 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3648 * for each (x,y) in the dependence relation of the edge.
3649 * That is,
3650 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3651 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3652 * taking into account that each coefficient in c_j_x and c_k_x is represented
3653 * as a pair of non-negative coefficients.
3655 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3656 struct isl_sched_node *src, struct isl_sched_node *dst,
3657 __isl_take isl_basic_set *coef, int pos)
3659 int offset;
3660 isl_ctx *ctx;
3661 isl_dim_map *dim_map;
3663 if (!coef)
3664 return isl_stat_error;
3666 ctx = isl_basic_set_get_ctx(coef);
3667 offset = coef_var_offset(coef);
3668 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3669 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3670 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3672 return isl_stat_ok;
3675 /* Data structure collecting information used during the construction
3676 * of an LP for carrying dependences.
3678 * "intra" is a sequence of coefficient constraints for intra-node edges.
3679 * "inter" is a sequence of coefficient constraints for inter-node edges.
3681 struct isl_carry {
3682 isl_basic_set_list *intra;
3683 isl_basic_set_list *inter;
3686 /* Free all the data stored in "carry".
3688 static void isl_carry_clear(struct isl_carry *carry)
3690 isl_basic_set_list_free(carry->intra);
3691 isl_basic_set_list_free(carry->inter);
3694 /* Return a pointer to the node in "graph" that lives in "space".
3695 * If the requested node has been compressed, then "space"
3696 * corresponds to the compressed space.
3698 * First try and see if "space" is the space of an uncompressed node.
3699 * If so, return that node.
3700 * Otherwise, "space" was constructed by construct_compressed_id and
3701 * contains a user pointer pointing to the node in the tuple id.
3703 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3704 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3706 isl_id *id;
3707 struct isl_sched_node *node;
3709 if (!space)
3710 return NULL;
3712 node = graph_find_node(ctx, graph, space);
3713 if (node)
3714 return node;
3716 id = isl_space_get_tuple_id(space, isl_dim_set);
3717 node = isl_id_get_user(id);
3718 isl_id_free(id);
3720 if (!node)
3721 return NULL;
3723 if (!(node >= &graph->node[0] && node < &graph->node[graph->n]))
3724 isl_die(ctx, isl_error_internal,
3725 "space points to invalid node", return NULL);
3727 return node;
3730 /* Internal data structure for add_all_constraints.
3732 * "graph" is the schedule constraint graph for which an LP problem
3733 * is being constructed.
3734 * "pos" is the position of the next edge that needs to be carried.
3736 struct isl_add_all_constraints_data {
3737 isl_ctx *ctx;
3738 struct isl_sched_graph *graph;
3739 int pos;
3742 /* Add the constraints "coef" derived from an edge from a node to itself
3743 * to data->graph->lp in order to respect the dependences and
3744 * to try and carry them.
3746 * The space of "coef" is of the form
3748 * coefficients[[c_cst, c_n] -> S[c_x]]
3750 * with S[c_x] the (compressed) space of the node.
3751 * Extract the node from the space and call add_intra_constraints.
3753 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3755 struct isl_add_all_constraints_data *data = user;
3756 isl_space *space;
3757 struct isl_sched_node *node;
3759 space = isl_basic_set_get_space(coef);
3760 space = isl_space_range(isl_space_unwrap(space));
3761 node = graph_find_compressed_node(data->ctx, data->graph, space);
3762 isl_space_free(space);
3763 return add_intra_constraints(data->graph, node, coef, data->pos++);
3766 /* Add the constraints "coef" derived from an edge from a node j
3767 * to a node k to data->graph->lp in order to respect the dependences and
3768 * to try and carry them.
3770 * The space of "coef" is of the form
3772 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3774 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3775 * Extract the nodes from the space and call add_inter_constraints.
3777 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3779 struct isl_add_all_constraints_data *data = user;
3780 isl_space *space, *dom;
3781 struct isl_sched_node *src, *dst;
3783 space = isl_basic_set_get_space(coef);
3784 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3785 dom = isl_space_domain(isl_space_copy(space));
3786 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3787 isl_space_free(dom);
3788 space = isl_space_range(space);
3789 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3790 isl_space_free(space);
3792 return add_inter_constraints(data->graph, src, dst, coef, data->pos++);
3795 /* Add constraints to graph->lp that force all (conditional) validity
3796 * dependences to be respected and attempt to carry them.
3797 * "intra" is the sequence of coefficient constraints for intra-node edges.
3798 * "inter" is the sequence of coefficient constraints for inter-node edges.
3800 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3801 __isl_keep isl_basic_set_list *intra,
3802 __isl_keep isl_basic_set_list *inter)
3804 struct isl_add_all_constraints_data data = { ctx, graph };
3806 data.pos = 0;
3807 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3808 return isl_stat_error;
3809 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3810 return isl_stat_error;
3811 return isl_stat_ok;
3814 /* Internal data structure for count_all_constraints
3815 * for keeping track of the number of equality and inequality constraints.
3817 struct isl_sched_count {
3818 int n_eq;
3819 int n_ineq;
3822 /* Add the number of equality and inequality constraints of "bset"
3823 * to data->n_eq and data->n_ineq.
3825 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
3827 struct isl_sched_count *data = user;
3829 data->n_eq += isl_basic_set_n_equality(bset);
3830 data->n_ineq += isl_basic_set_n_inequality(bset);
3831 isl_basic_set_free(bset);
3833 return isl_stat_ok;
3836 /* Count the number of equality and inequality constraints
3837 * that will be added to the carry_lp problem.
3838 * We count each edge exactly once.
3839 * "intra" is the sequence of coefficient constraints for intra-node edges.
3840 * "inter" is the sequence of coefficient constraints for inter-node edges.
3842 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
3843 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
3845 struct isl_sched_count data;
3847 data.n_eq = data.n_ineq = 0;
3848 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
3849 return isl_stat_error;
3850 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
3851 return isl_stat_error;
3853 *n_eq = data.n_eq;
3854 *n_ineq = data.n_ineq;
3856 return isl_stat_ok;
3859 /* Construct an LP problem for finding schedule coefficients
3860 * such that the schedule carries as many validity dependences as possible.
3861 * In particular, for each dependence i, we bound the dependence distance
3862 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3863 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3864 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3865 * "intra" is the sequence of coefficient constraints for intra-node edges.
3866 * "inter" is the sequence of coefficient constraints for inter-node edges.
3867 * "n_edge" is the total number of edges.
3869 * All variables of the LP are non-negative. The actual coefficients
3870 * may be negative, so each coefficient is represented as the difference
3871 * of two non-negative variables. The negative part always appears
3872 * immediately before the positive part.
3873 * Other than that, the variables have the following order
3875 * - sum of (1 - e_i) over all edges
3876 * - sum of all c_n coefficients
3877 * (unconstrained when computing non-parametric schedules)
3878 * - sum of positive and negative parts of all c_x coefficients
3879 * - for each edge
3880 * - e_i
3881 * - for each node
3882 * - c_i_0
3883 * - c_i_n (if parametric)
3884 * - positive and negative parts of c_i_x, in opposite order
3886 * The constraints are those from the (validity) edges plus three equalities
3887 * to express the sums and n_edge inequalities to express e_i <= 1.
3889 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
3890 int n_edge, __isl_keep isl_basic_set_list *intra,
3891 __isl_keep isl_basic_set_list *inter)
3893 int i;
3894 int k;
3895 isl_space *dim;
3896 unsigned total;
3897 int n_eq, n_ineq;
3899 total = 3 + n_edge;
3900 for (i = 0; i < graph->n; ++i) {
3901 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3902 node->start = total;
3903 total += 1 + node->nparam + 2 * node->nvar;
3906 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
3907 return isl_stat_error;
3909 dim = isl_space_set_alloc(ctx, 0, total);
3910 isl_basic_set_free(graph->lp);
3911 n_eq += 3;
3912 n_ineq += n_edge;
3913 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3914 graph->lp = isl_basic_set_set_rational(graph->lp);
3916 k = isl_basic_set_alloc_equality(graph->lp);
3917 if (k < 0)
3918 return isl_stat_error;
3919 isl_seq_clr(graph->lp->eq[k], 1 + total);
3920 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3921 isl_int_set_si(graph->lp->eq[k][1], 1);
3922 for (i = 0; i < n_edge; ++i)
3923 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3925 if (add_param_sum_constraint(graph, 1) < 0)
3926 return isl_stat_error;
3927 if (add_var_sum_constraint(graph, 2) < 0)
3928 return isl_stat_error;
3930 for (i = 0; i < n_edge; ++i) {
3931 k = isl_basic_set_alloc_inequality(graph->lp);
3932 if (k < 0)
3933 return isl_stat_error;
3934 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3935 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3936 isl_int_set_si(graph->lp->ineq[k][0], 1);
3939 if (add_all_constraints(ctx, graph, intra, inter) < 0)
3940 return isl_stat_error;
3942 return isl_stat_ok;
3945 static __isl_give isl_schedule_node *compute_component_schedule(
3946 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3947 int wcc);
3949 /* Comparison function for sorting the statements based on
3950 * the corresponding value in "r".
3952 static int smaller_value(const void *a, const void *b, void *data)
3954 isl_vec *r = data;
3955 const int *i1 = a;
3956 const int *i2 = b;
3958 return isl_int_cmp(r->el[*i1], r->el[*i2]);
3961 /* If the schedule_split_scaled option is set and if the linear
3962 * parts of the scheduling rows for all nodes in the graphs have
3963 * a non-trivial common divisor, then split off the remainder of the
3964 * constant term modulo this common divisor from the linear part.
3965 * Otherwise, insert a band node directly and continue with
3966 * the construction of the schedule.
3968 * If a non-trivial common divisor is found, then
3969 * the linear part is reduced and the remainder is enforced
3970 * by a sequence node with the children placed in the order
3971 * of this remainder.
3972 * In particular, we assign an scc index based on the remainder and
3973 * then rely on compute_component_schedule to insert the sequence and
3974 * to continue the schedule construction on each part.
3976 static __isl_give isl_schedule_node *split_scaled(
3977 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3979 int i;
3980 int row;
3981 int scc;
3982 isl_ctx *ctx;
3983 isl_int gcd, gcd_i;
3984 isl_vec *r;
3985 int *order;
3987 if (!node)
3988 return NULL;
3990 ctx = isl_schedule_node_get_ctx(node);
3991 if (!ctx->opt->schedule_split_scaled)
3992 return compute_next_band(node, graph, 0);
3993 if (graph->n <= 1)
3994 return compute_next_band(node, graph, 0);
3996 isl_int_init(gcd);
3997 isl_int_init(gcd_i);
3999 isl_int_set_si(gcd, 0);
4001 row = isl_mat_rows(graph->node[0].sched) - 1;
4003 for (i = 0; i < graph->n; ++i) {
4004 struct isl_sched_node *node = &graph->node[i];
4005 int cols = isl_mat_cols(node->sched);
4007 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4008 isl_int_gcd(gcd, gcd, gcd_i);
4011 isl_int_clear(gcd_i);
4013 if (isl_int_cmp_si(gcd, 1) <= 0) {
4014 isl_int_clear(gcd);
4015 return compute_next_band(node, graph, 0);
4018 r = isl_vec_alloc(ctx, graph->n);
4019 order = isl_calloc_array(ctx, int, graph->n);
4020 if (!r || !order)
4021 goto error;
4023 for (i = 0; i < graph->n; ++i) {
4024 struct isl_sched_node *node = &graph->node[i];
4026 order[i] = i;
4027 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
4028 isl_int_fdiv_q(node->sched->row[row][0],
4029 node->sched->row[row][0], gcd);
4030 isl_int_mul(node->sched->row[row][0],
4031 node->sched->row[row][0], gcd);
4032 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4033 if (!node->sched)
4034 goto error;
4037 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
4038 goto error;
4040 scc = 0;
4041 for (i = 0; i < graph->n; ++i) {
4042 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
4043 ++scc;
4044 graph->node[order[i]].scc = scc;
4046 graph->scc = ++scc;
4047 graph->weak = 0;
4049 isl_int_clear(gcd);
4050 isl_vec_free(r);
4051 free(order);
4053 if (update_edges(ctx, graph) < 0)
4054 return isl_schedule_node_free(node);
4055 node = insert_current_band(node, graph, 0);
4056 next_band(graph);
4058 node = isl_schedule_node_child(node, 0);
4059 node = compute_component_schedule(node, graph, 0);
4060 node = isl_schedule_node_parent(node);
4062 return node;
4063 error:
4064 isl_vec_free(r);
4065 free(order);
4066 isl_int_clear(gcd);
4067 return isl_schedule_node_free(node);
4070 /* Is the schedule row "sol" trivial on node "node"?
4071 * That is, is the solution zero on the dimensions linearly independent of
4072 * the previously found solutions?
4073 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4075 * Each coefficient is represented as the difference between
4076 * two non-negative values in "sol". "sol" has been computed
4077 * in terms of the original iterators (i.e., without use of cmap).
4078 * We construct the schedule row s and check if it is linearly
4079 * independent of previously computed schedule rows
4080 * by computing T s, with T the linear combinations that are zero
4081 * on linearly dependent schedule rows.
4082 * If the result consists of all zeros, then the solution is trivial.
4084 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4086 int trivial;
4087 isl_vec *node_sol;
4089 if (!sol)
4090 return -1;
4091 if (node->nvar == node->rank)
4092 return 0;
4094 node_sol = extract_var_coef(node, sol);
4095 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4096 if (!node_sol)
4097 return -1;
4099 trivial = isl_seq_first_non_zero(node_sol->el,
4100 node->nvar - node->rank) == -1;
4102 isl_vec_free(node_sol);
4104 return trivial;
4107 /* Is the schedule row "sol" trivial on any node where it should
4108 * not be trivial?
4109 * "sol" has been computed in terms of the original iterators
4110 * (i.e., without use of cmap).
4111 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4113 static int is_any_trivial(struct isl_sched_graph *graph,
4114 __isl_keep isl_vec *sol)
4116 int i;
4118 for (i = 0; i < graph->n; ++i) {
4119 struct isl_sched_node *node = &graph->node[i];
4120 int trivial;
4122 if (!needs_row(graph, node))
4123 continue;
4124 trivial = is_trivial(node, sol);
4125 if (trivial < 0 || trivial)
4126 return trivial;
4129 return 0;
4132 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4133 * If so, return the position of the coalesced dimension.
4134 * Otherwise, return node->nvar or -1 on error.
4136 * In particular, look for pairs of coefficients c_i and c_j such that
4137 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
4138 * If any such pair is found, then return i.
4139 * If size_i is infinity, then no check on c_i needs to be performed.
4141 static int find_node_coalescing(struct isl_sched_node *node,
4142 __isl_keep isl_vec *sol)
4144 int i, j;
4145 isl_int max;
4146 isl_vec *csol;
4148 if (node->nvar <= 1)
4149 return node->nvar;
4151 csol = extract_var_coef(node, sol);
4152 if (!csol)
4153 return -1;
4154 isl_int_init(max);
4155 for (i = 0; i < node->nvar; ++i) {
4156 isl_val *v;
4158 if (isl_int_is_zero(csol->el[i]))
4159 continue;
4160 v = isl_multi_val_get_val(node->sizes, i);
4161 if (!v)
4162 goto error;
4163 if (!isl_val_is_int(v)) {
4164 isl_val_free(v);
4165 continue;
4167 isl_int_mul(max, v->n, csol->el[i]);
4168 isl_val_free(v);
4170 for (j = 0; j < node->nvar; ++j) {
4171 if (j == i)
4172 continue;
4173 if (isl_int_abs_ge(csol->el[j], max))
4174 break;
4176 if (j < node->nvar)
4177 break;
4180 isl_int_clear(max);
4181 isl_vec_free(csol);
4182 return i;
4183 error:
4184 isl_int_clear(max);
4185 isl_vec_free(csol);
4186 return -1;
4189 /* Force the schedule coefficient at position "pos" of "node" to be zero
4190 * in "tl".
4191 * The coefficient is encoded as the difference between two non-negative
4192 * variables. Force these two variables to have the same value.
4194 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4195 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4197 int dim;
4198 isl_ctx *ctx;
4199 isl_vec *eq;
4201 ctx = isl_space_get_ctx(node->space);
4202 dim = isl_tab_lexmin_dim(tl);
4203 if (dim < 0)
4204 return isl_tab_lexmin_free(tl);
4205 eq = isl_vec_alloc(ctx, 1 + dim);
4206 eq = isl_vec_clr(eq);
4207 if (!eq)
4208 return isl_tab_lexmin_free(tl);
4210 pos = 1 + node_var_coef_pos(node, pos);
4211 isl_int_set_si(eq->el[pos], 1);
4212 isl_int_set_si(eq->el[pos + 1], -1);
4213 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4214 isl_vec_free(eq);
4216 return tl;
4219 /* Return the lexicographically smallest rational point in the basic set
4220 * from which "tl" was constructed, double checking that this input set
4221 * was not empty.
4223 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4225 isl_vec *sol;
4227 sol = isl_tab_lexmin_get_solution(tl);
4228 if (!sol)
4229 return NULL;
4230 if (sol->size == 0)
4231 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4232 "error in schedule construction",
4233 return isl_vec_free(sol));
4234 return sol;
4237 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4238 * carry any of the "n_edge" groups of dependences?
4239 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4240 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4241 * by the edge are carried by the solution.
4242 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4243 * one of those is carried.
4245 * Note that despite the fact that the problem is solved using a rational
4246 * solver, the solution is guaranteed to be integral.
4247 * Specifically, the dependence distance lower bounds e_i (and therefore
4248 * also their sum) are integers. See Lemma 5 of [1].
4250 * Any potential denominator of the sum is cleared by this function.
4251 * The denominator is not relevant for any of the other elements
4252 * in the solution.
4254 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4255 * Problem, Part II: Multi-Dimensional Time.
4256 * In Intl. Journal of Parallel Programming, 1992.
4258 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4260 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4261 isl_int_set_si(sol->el[0], 1);
4262 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4265 /* Return the lexicographically smallest rational point in "lp",
4266 * assuming that all variables are non-negative and performing some
4267 * additional sanity checks.
4268 * If "want_integral" is set, then compute the lexicographically smallest
4269 * integer point instead.
4270 * In particular, "lp" should not be empty by construction.
4271 * Double check that this is the case.
4272 * If dependences are not carried for any of the "n_edge" edges,
4273 * then return an empty vector.
4275 * If the schedule_treat_coalescing option is set and
4276 * if the computed schedule performs loop coalescing on a given node,
4277 * i.e., if it is of the form
4279 * c_i i + c_j j + ...
4281 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4282 * to cut out this solution. Repeat this process until no more loop
4283 * coalescing occurs or until no more dependences can be carried.
4284 * In the latter case, revert to the previously computed solution.
4286 * If the caller requests an integral solution and if coalescing should
4287 * be treated, then perform the coalescing treatment first as
4288 * an integral solution computed before coalescing treatment
4289 * would carry the same number of edges and would therefore probably
4290 * also be coalescing.
4292 * To allow the coalescing treatment to be performed first,
4293 * the initial solution is allowed to be rational and it is only
4294 * cut out (if needed) in the next iteration, if no coalescing measures
4295 * were taken.
4297 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4298 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4300 int i, pos, cut;
4301 isl_ctx *ctx;
4302 isl_tab_lexmin *tl;
4303 isl_vec *sol, *prev = NULL;
4304 int treat_coalescing;
4306 if (!lp)
4307 return NULL;
4308 ctx = isl_basic_set_get_ctx(lp);
4309 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4310 tl = isl_tab_lexmin_from_basic_set(lp);
4312 cut = 0;
4313 do {
4314 int integral;
4316 if (cut)
4317 tl = isl_tab_lexmin_cut_to_integer(tl);
4318 sol = non_empty_solution(tl);
4319 if (!sol)
4320 goto error;
4322 integral = isl_int_is_one(sol->el[0]);
4323 if (!carries_dependences(sol, n_edge)) {
4324 if (!prev)
4325 prev = isl_vec_alloc(ctx, 0);
4326 isl_vec_free(sol);
4327 sol = prev;
4328 break;
4330 prev = isl_vec_free(prev);
4331 cut = want_integral && !integral;
4332 if (cut)
4333 prev = sol;
4334 if (!treat_coalescing)
4335 continue;
4336 for (i = 0; i < graph->n; ++i) {
4337 struct isl_sched_node *node = &graph->node[i];
4339 pos = find_node_coalescing(node, sol);
4340 if (pos < 0)
4341 goto error;
4342 if (pos < node->nvar)
4343 break;
4345 if (i < graph->n) {
4346 prev = sol;
4347 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4348 cut = 0;
4350 } while (prev);
4352 isl_tab_lexmin_free(tl);
4354 return sol;
4355 error:
4356 isl_tab_lexmin_free(tl);
4357 isl_vec_free(prev);
4358 isl_vec_free(sol);
4359 return NULL;
4362 /* If "edge" is an edge from a node to itself, then add the corresponding
4363 * dependence relation to "umap".
4364 * If "node" has been compressed, then the dependence relation
4365 * is also compressed first.
4367 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4368 struct isl_sched_edge *edge)
4370 isl_map *map;
4371 struct isl_sched_node *node = edge->src;
4373 if (edge->src != edge->dst)
4374 return umap;
4376 map = isl_map_copy(edge->map);
4377 if (node->compressed) {
4378 map = isl_map_preimage_domain_multi_aff(map,
4379 isl_multi_aff_copy(node->decompress));
4380 map = isl_map_preimage_range_multi_aff(map,
4381 isl_multi_aff_copy(node->decompress));
4383 umap = isl_union_map_add_map(umap, map);
4384 return umap;
4387 /* If "edge" is an edge from a node to another node, then add the corresponding
4388 * dependence relation to "umap".
4389 * If the source or destination nodes of "edge" have been compressed,
4390 * then the dependence relation is also compressed first.
4392 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4393 struct isl_sched_edge *edge)
4395 isl_map *map;
4397 if (edge->src == edge->dst)
4398 return umap;
4400 map = isl_map_copy(edge->map);
4401 if (edge->src->compressed)
4402 map = isl_map_preimage_domain_multi_aff(map,
4403 isl_multi_aff_copy(edge->src->decompress));
4404 if (edge->dst->compressed)
4405 map = isl_map_preimage_range_multi_aff(map,
4406 isl_multi_aff_copy(edge->dst->decompress));
4407 umap = isl_union_map_add_map(umap, map);
4408 return umap;
4411 /* For each (conditional) validity edge in "graph",
4412 * add the corresponding dependence relation using "add"
4413 * to a collection of dependence relations and return the result.
4414 * If "coincidence" is set, then coincidence edges are considered as well.
4416 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4417 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4418 struct isl_sched_edge *edge), int coincidence)
4420 int i;
4421 isl_space *space;
4422 isl_union_map *umap;
4424 space = isl_space_copy(graph->node[0].space);
4425 umap = isl_union_map_empty(space);
4427 for (i = 0; i < graph->n_edge; ++i) {
4428 struct isl_sched_edge *edge = &graph->edge[i];
4430 if (!is_any_validity(edge) &&
4431 (!coincidence || !is_coincidence(edge)))
4432 continue;
4434 umap = add(umap, edge);
4437 return umap;
4440 /* For each dependence relation on a (conditional) validity edge
4441 * from a node to itself,
4442 * construct the set of coefficients of valid constraints for elements
4443 * in that dependence relation and collect the results.
4444 * If "coincidence" is set, then coincidence edges are considered as well.
4446 * In particular, for each dependence relation R, constraints
4447 * on coefficients (c_0, c_n, c_x) are constructed such that
4449 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4451 * This computation is essentially the same as that performed
4452 * by intra_coefficients, except that it operates on multiple
4453 * edges together.
4455 * Note that if a dependence relation is a union of basic maps,
4456 * then each basic map needs to be treated individually as it may only
4457 * be possible to carry the dependences expressed by some of those
4458 * basic maps and not all of them.
4459 * The collected validity constraints are therefore not coalesced and
4460 * it is assumed that they are not coalesced automatically.
4461 * Duplicate basic maps can be removed, however.
4462 * In particular, if the same basic map appears as a disjunct
4463 * in multiple edges, then it only needs to be carried once.
4465 static __isl_give isl_basic_set_list *collect_intra_validity(
4466 struct isl_sched_graph *graph, int coincidence)
4468 isl_union_map *intra;
4469 isl_union_set *delta;
4470 isl_basic_set_list *list;
4472 intra = collect_validity(graph, &add_intra, coincidence);
4473 delta = isl_union_map_deltas(intra);
4474 delta = isl_union_set_remove_divs(delta);
4475 list = isl_union_set_get_basic_set_list(delta);
4476 isl_union_set_free(delta);
4478 return isl_basic_set_list_coefficients(list);
4481 /* For each dependence relation on a (conditional) validity edge
4482 * from a node to some other node,
4483 * construct the set of coefficients of valid constraints for elements
4484 * in that dependence relation and collect the results.
4485 * If "coincidence" is set, then coincidence edges are considered as well.
4487 * In particular, for each dependence relation R, constraints
4488 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4490 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4492 * This computation is essentially the same as that performed
4493 * by inter_coefficients, except that it operates on multiple
4494 * edges together.
4496 * Note that if a dependence relation is a union of basic maps,
4497 * then each basic map needs to be treated individually as it may only
4498 * be possible to carry the dependences expressed by some of those
4499 * basic maps and not all of them.
4500 * The collected validity constraints are therefore not coalesced and
4501 * it is assumed that they are not coalesced automatically.
4502 * Duplicate basic maps can be removed, however.
4503 * In particular, if the same basic map appears as a disjunct
4504 * in multiple edges, then it only needs to be carried once.
4506 static __isl_give isl_basic_set_list *collect_inter_validity(
4507 struct isl_sched_graph *graph, int coincidence)
4509 isl_union_map *inter;
4510 isl_union_set *wrap;
4511 isl_basic_set_list *list;
4513 inter = collect_validity(graph, &add_inter, coincidence);
4514 inter = isl_union_map_remove_divs(inter);
4515 wrap = isl_union_map_wrap(inter);
4516 list = isl_union_set_get_basic_set_list(wrap);
4517 isl_union_set_free(wrap);
4518 return isl_basic_set_list_coefficients(list);
4521 /* Construct an LP problem for finding schedule coefficients
4522 * such that the schedule carries as many of the validity dependences
4523 * as possible and
4524 * return the lexicographically smallest non-trivial solution.
4525 * If "fallback" is set, then the carrying is performed as a fallback
4526 * for the Pluto-like scheduler.
4527 * If "coincidence" is set, then try and carry coincidence edges as well.
4529 * The variable "n_edge" stores the number of groups that should be carried.
4530 * If none of the "n_edge" groups can be carried
4531 * then return an empty vector.
4532 * If, moreover, "n_edge" is zero, then the LP problem does not even
4533 * need to be constructed.
4535 * If a fallback solution is being computed, then compute an integral solution
4536 * for the coefficients rather than using the numerators
4537 * of a rational solution.
4539 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4540 struct isl_sched_graph *graph, int fallback, int coincidence)
4542 int n_intra, n_inter;
4543 int n_edge;
4544 isl_basic_set *lp;
4545 struct isl_carry carry = { 0 };
4547 carry.intra = collect_intra_validity(graph, coincidence);
4548 carry.inter = collect_inter_validity(graph, coincidence);
4549 if (!carry.intra || !carry.inter)
4550 goto error;
4551 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4552 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4553 n_edge = n_intra + n_inter;
4554 if (n_edge == 0) {
4555 isl_carry_clear(&carry);
4556 return isl_vec_alloc(ctx, 0);
4559 if (setup_carry_lp(ctx, graph, n_edge, carry.intra, carry.inter) < 0)
4560 goto error;
4562 isl_carry_clear(&carry);
4563 lp = isl_basic_set_copy(graph->lp);
4564 return non_neg_lexmin(graph, lp, n_edge, fallback);
4565 error:
4566 isl_carry_clear(&carry);
4567 return NULL;
4570 /* Construct a schedule row for each node such that as many validity dependences
4571 * as possible are carried and then continue with the next band.
4572 * If "fallback" is set, then the carrying is performed as a fallback
4573 * for the Pluto-like scheduler.
4574 * If "coincidence" is set, then try and carry coincidence edges as well.
4576 * If there are no validity dependences, then no dependence can be carried and
4577 * the procedure is guaranteed to fail. If there is more than one component,
4578 * then try computing a schedule on each component separately
4579 * to prevent or at least postpone this failure.
4581 * If a schedule row is computed, then check that dependences are carried
4582 * for at least one of the edges.
4584 * If the computed schedule row turns out to be trivial on one or
4585 * more nodes where it should not be trivial, then we throw it away
4586 * and try again on each component separately.
4588 * If there is only one component, then we accept the schedule row anyway,
4589 * but we do not consider it as a complete row and therefore do not
4590 * increment graph->n_row. Note that the ranks of the nodes that
4591 * do get a non-trivial schedule part will get updated regardless and
4592 * graph->maxvar is computed based on these ranks. The test for
4593 * whether more schedule rows are required in compute_schedule_wcc
4594 * is therefore not affected.
4596 * Insert a band corresponding to the schedule row at position "node"
4597 * of the schedule tree and continue with the construction of the schedule.
4598 * This insertion and the continued construction is performed by split_scaled
4599 * after optionally checking for non-trivial common divisors.
4601 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
4602 struct isl_sched_graph *graph, int fallback, int coincidence)
4604 int trivial;
4605 isl_ctx *ctx;
4606 isl_vec *sol;
4608 if (!node)
4609 return NULL;
4611 ctx = isl_schedule_node_get_ctx(node);
4612 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
4613 if (!sol)
4614 return isl_schedule_node_free(node);
4615 if (sol->size == 0) {
4616 isl_vec_free(sol);
4617 if (graph->scc > 1)
4618 return compute_component_schedule(node, graph, 1);
4619 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
4620 return isl_schedule_node_free(node));
4623 trivial = is_any_trivial(graph, sol);
4624 if (trivial < 0) {
4625 sol = isl_vec_free(sol);
4626 } else if (trivial && graph->scc > 1) {
4627 isl_vec_free(sol);
4628 return compute_component_schedule(node, graph, 1);
4631 if (update_schedule(graph, sol, 0, 0) < 0)
4632 return isl_schedule_node_free(node);
4633 if (trivial)
4634 graph->n_row--;
4636 return split_scaled(node, graph);
4639 /* Construct a schedule row for each node such that as many validity dependences
4640 * as possible are carried and then continue with the next band.
4641 * Do so as a fallback for the Pluto-like scheduler.
4642 * If "coincidence" is set, then try and carry coincidence edges as well.
4644 static __isl_give isl_schedule_node *carry_fallback(
4645 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4646 int coincidence)
4648 return carry(node, graph, 1, coincidence);
4651 /* Construct a schedule row for each node such that as many validity dependences
4652 * as possible are carried and then continue with the next band.
4653 * Do so for the case where the Feautrier scheduler was selected
4654 * by the user.
4656 static __isl_give isl_schedule_node *carry_feautrier(
4657 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4659 return carry(node, graph, 0, 0);
4662 /* Construct a schedule row for each node such that as many validity dependences
4663 * as possible are carried and then continue with the next band.
4664 * Do so as a fallback for the Pluto-like scheduler.
4666 static __isl_give isl_schedule_node *carry_dependences(
4667 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4669 return carry_fallback(node, graph, 0);
4672 /* Construct a schedule row for each node such that as many validity or
4673 * coincidence dependences as possible are carried and
4674 * then continue with the next band.
4675 * Do so as a fallback for the Pluto-like scheduler.
4677 static __isl_give isl_schedule_node *carry_coincidence(
4678 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4680 return carry_fallback(node, graph, 1);
4683 /* Topologically sort statements mapped to the same schedule iteration
4684 * and add insert a sequence node in front of "node"
4685 * corresponding to this order.
4686 * If "initialized" is set, then it may be assumed that compute_maxvar
4687 * has been called on the current band. Otherwise, call
4688 * compute_maxvar if and before carry_dependences gets called.
4690 * If it turns out to be impossible to sort the statements apart,
4691 * because different dependences impose different orderings
4692 * on the statements, then we extend the schedule such that
4693 * it carries at least one more dependence.
4695 static __isl_give isl_schedule_node *sort_statements(
4696 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4697 int initialized)
4699 isl_ctx *ctx;
4700 isl_union_set_list *filters;
4702 if (!node)
4703 return NULL;
4705 ctx = isl_schedule_node_get_ctx(node);
4706 if (graph->n < 1)
4707 isl_die(ctx, isl_error_internal,
4708 "graph should have at least one node",
4709 return isl_schedule_node_free(node));
4711 if (graph->n == 1)
4712 return node;
4714 if (update_edges(ctx, graph) < 0)
4715 return isl_schedule_node_free(node);
4717 if (graph->n_edge == 0)
4718 return node;
4720 if (detect_sccs(ctx, graph) < 0)
4721 return isl_schedule_node_free(node);
4723 next_band(graph);
4724 if (graph->scc < graph->n) {
4725 if (!initialized && compute_maxvar(graph) < 0)
4726 return isl_schedule_node_free(node);
4727 return carry_dependences(node, graph);
4730 filters = extract_sccs(ctx, graph);
4731 node = isl_schedule_node_insert_sequence(node, filters);
4733 return node;
4736 /* Are there any (non-empty) (conditional) validity edges in the graph?
4738 static int has_validity_edges(struct isl_sched_graph *graph)
4740 int i;
4742 for (i = 0; i < graph->n_edge; ++i) {
4743 int empty;
4745 empty = isl_map_plain_is_empty(graph->edge[i].map);
4746 if (empty < 0)
4747 return -1;
4748 if (empty)
4749 continue;
4750 if (is_any_validity(&graph->edge[i]))
4751 return 1;
4754 return 0;
4757 /* Should we apply a Feautrier step?
4758 * That is, did the user request the Feautrier algorithm and are
4759 * there any validity dependences (left)?
4761 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4763 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4764 return 0;
4766 return has_validity_edges(graph);
4769 /* Compute a schedule for a connected dependence graph using Feautrier's
4770 * multi-dimensional scheduling algorithm and return the updated schedule node.
4772 * The original algorithm is described in [1].
4773 * The main idea is to minimize the number of scheduling dimensions, by
4774 * trying to satisfy as many dependences as possible per scheduling dimension.
4776 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4777 * Problem, Part II: Multi-Dimensional Time.
4778 * In Intl. Journal of Parallel Programming, 1992.
4780 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4781 isl_schedule_node *node, struct isl_sched_graph *graph)
4783 return carry_feautrier(node, graph);
4786 /* Turn off the "local" bit on all (condition) edges.
4788 static void clear_local_edges(struct isl_sched_graph *graph)
4790 int i;
4792 for (i = 0; i < graph->n_edge; ++i)
4793 if (is_condition(&graph->edge[i]))
4794 clear_local(&graph->edge[i]);
4797 /* Does "graph" have both condition and conditional validity edges?
4799 static int need_condition_check(struct isl_sched_graph *graph)
4801 int i;
4802 int any_condition = 0;
4803 int any_conditional_validity = 0;
4805 for (i = 0; i < graph->n_edge; ++i) {
4806 if (is_condition(&graph->edge[i]))
4807 any_condition = 1;
4808 if (is_conditional_validity(&graph->edge[i]))
4809 any_conditional_validity = 1;
4812 return any_condition && any_conditional_validity;
4815 /* Does "graph" contain any coincidence edge?
4817 static int has_any_coincidence(struct isl_sched_graph *graph)
4819 int i;
4821 for (i = 0; i < graph->n_edge; ++i)
4822 if (is_coincidence(&graph->edge[i]))
4823 return 1;
4825 return 0;
4828 /* Extract the final schedule row as a map with the iteration domain
4829 * of "node" as domain.
4831 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4833 isl_multi_aff *ma;
4834 int row;
4836 row = isl_mat_rows(node->sched) - 1;
4837 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
4838 return isl_map_from_multi_aff(ma);
4841 /* Is the conditional validity dependence in the edge with index "edge_index"
4842 * violated by the latest (i.e., final) row of the schedule?
4843 * That is, is i scheduled after j
4844 * for any conditional validity dependence i -> j?
4846 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4848 isl_map *src_sched, *dst_sched, *map;
4849 struct isl_sched_edge *edge = &graph->edge[edge_index];
4850 int empty;
4852 src_sched = final_row(edge->src);
4853 dst_sched = final_row(edge->dst);
4854 map = isl_map_copy(edge->map);
4855 map = isl_map_apply_domain(map, src_sched);
4856 map = isl_map_apply_range(map, dst_sched);
4857 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4858 empty = isl_map_is_empty(map);
4859 isl_map_free(map);
4861 if (empty < 0)
4862 return -1;
4864 return !empty;
4867 /* Does "graph" have any satisfied condition edges that
4868 * are adjacent to the conditional validity constraint with
4869 * domain "conditional_source" and range "conditional_sink"?
4871 * A satisfied condition is one that is not local.
4872 * If a condition was forced to be local already (i.e., marked as local)
4873 * then there is no need to check if it is in fact local.
4875 * Additionally, mark all adjacent condition edges found as local.
4877 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4878 __isl_keep isl_union_set *conditional_source,
4879 __isl_keep isl_union_set *conditional_sink)
4881 int i;
4882 int any = 0;
4884 for (i = 0; i < graph->n_edge; ++i) {
4885 int adjacent, local;
4886 isl_union_map *condition;
4888 if (!is_condition(&graph->edge[i]))
4889 continue;
4890 if (is_local(&graph->edge[i]))
4891 continue;
4893 condition = graph->edge[i].tagged_condition;
4894 adjacent = domain_intersects(condition, conditional_sink);
4895 if (adjacent >= 0 && !adjacent)
4896 adjacent = range_intersects(condition,
4897 conditional_source);
4898 if (adjacent < 0)
4899 return -1;
4900 if (!adjacent)
4901 continue;
4903 set_local(&graph->edge[i]);
4905 local = is_condition_false(&graph->edge[i]);
4906 if (local < 0)
4907 return -1;
4908 if (!local)
4909 any = 1;
4912 return any;
4915 /* Are there any violated conditional validity dependences with
4916 * adjacent condition dependences that are not local with respect
4917 * to the current schedule?
4918 * That is, is the conditional validity constraint violated?
4920 * Additionally, mark all those adjacent condition dependences as local.
4921 * We also mark those adjacent condition dependences that were not marked
4922 * as local before, but just happened to be local already. This ensures
4923 * that they remain local if the schedule is recomputed.
4925 * We first collect domain and range of all violated conditional validity
4926 * dependences and then check if there are any adjacent non-local
4927 * condition dependences.
4929 static int has_violated_conditional_constraint(isl_ctx *ctx,
4930 struct isl_sched_graph *graph)
4932 int i;
4933 int any = 0;
4934 isl_union_set *source, *sink;
4936 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4937 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4938 for (i = 0; i < graph->n_edge; ++i) {
4939 isl_union_set *uset;
4940 isl_union_map *umap;
4941 int violated;
4943 if (!is_conditional_validity(&graph->edge[i]))
4944 continue;
4946 violated = is_violated(graph, i);
4947 if (violated < 0)
4948 goto error;
4949 if (!violated)
4950 continue;
4952 any = 1;
4954 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4955 uset = isl_union_map_domain(umap);
4956 source = isl_union_set_union(source, uset);
4957 source = isl_union_set_coalesce(source);
4959 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4960 uset = isl_union_map_range(umap);
4961 sink = isl_union_set_union(sink, uset);
4962 sink = isl_union_set_coalesce(sink);
4965 if (any)
4966 any = has_adjacent_true_conditions(graph, source, sink);
4968 isl_union_set_free(source);
4969 isl_union_set_free(sink);
4970 return any;
4971 error:
4972 isl_union_set_free(source);
4973 isl_union_set_free(sink);
4974 return -1;
4977 /* Examine the current band (the rows between graph->band_start and
4978 * graph->n_total_row), deciding whether to drop it or add it to "node"
4979 * and then continue with the computation of the next band, if any.
4980 * If "initialized" is set, then it may be assumed that compute_maxvar
4981 * has been called on the current band. Otherwise, call
4982 * compute_maxvar if and before carry_dependences gets called.
4984 * The caller keeps looking for a new row as long as
4985 * graph->n_row < graph->maxvar. If the latest attempt to find
4986 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4987 * then we either
4988 * - split between SCCs and start over (assuming we found an interesting
4989 * pair of SCCs between which to split)
4990 * - continue with the next band (assuming the current band has at least
4991 * one row)
4992 * - if outer coincidence needs to be enforced, then try to carry as many
4993 * validity or coincidence dependences as possible and
4994 * continue with the next band
4995 * - try to carry as many validity dependences as possible and
4996 * continue with the next band
4997 * In each case, we first insert a band node in the schedule tree
4998 * if any rows have been computed.
5000 * If the caller managed to complete the schedule, we insert a band node
5001 * (if any schedule rows were computed) and we finish off by topologically
5002 * sorting the statements based on the remaining dependences.
5004 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5005 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5006 int initialized)
5008 int insert;
5010 if (!node)
5011 return NULL;
5013 if (graph->n_row < graph->maxvar) {
5014 isl_ctx *ctx;
5015 int empty = graph->n_total_row == graph->band_start;
5017 ctx = isl_schedule_node_get_ctx(node);
5018 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5019 return compute_next_band(node, graph, 1);
5020 if (graph->src_scc >= 0)
5021 return compute_split_schedule(node, graph);
5022 if (!empty)
5023 return compute_next_band(node, graph, 1);
5024 if (!initialized && compute_maxvar(graph) < 0)
5025 return isl_schedule_node_free(node);
5026 if (isl_options_get_schedule_outer_coincidence(ctx))
5027 return carry_coincidence(node, graph);
5028 return carry_dependences(node, graph);
5031 insert = graph->n_total_row > graph->band_start;
5032 if (insert) {
5033 node = insert_current_band(node, graph, 1);
5034 node = isl_schedule_node_child(node, 0);
5036 node = sort_statements(node, graph, initialized);
5037 if (insert)
5038 node = isl_schedule_node_parent(node);
5040 return node;
5043 /* Construct a band of schedule rows for a connected dependence graph.
5044 * The caller is responsible for determining the strongly connected
5045 * components and calling compute_maxvar first.
5047 * We try to find a sequence of as many schedule rows as possible that result
5048 * in non-negative dependence distances (independent of the previous rows
5049 * in the sequence, i.e., such that the sequence is tilable), with as
5050 * many of the initial rows as possible satisfying the coincidence constraints.
5051 * The computation stops if we can't find any more rows or if we have found
5052 * all the rows we wanted to find.
5054 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5055 * outermost dimension to satisfy the coincidence constraints. If this
5056 * turns out to be impossible, we fall back on the general scheme above
5057 * and try to carry as many dependences as possible.
5059 * If "graph" contains both condition and conditional validity dependences,
5060 * then we need to check that that the conditional schedule constraint
5061 * is satisfied, i.e., there are no violated conditional validity dependences
5062 * that are adjacent to any non-local condition dependences.
5063 * If there are, then we mark all those adjacent condition dependences
5064 * as local and recompute the current band. Those dependences that
5065 * are marked local will then be forced to be local.
5066 * The initial computation is performed with no dependences marked as local.
5067 * If we are lucky, then there will be no violated conditional validity
5068 * dependences adjacent to any non-local condition dependences.
5069 * Otherwise, we mark some additional condition dependences as local and
5070 * recompute. We continue this process until there are no violations left or
5071 * until we are no longer able to compute a schedule.
5072 * Since there are only a finite number of dependences,
5073 * there will only be a finite number of iterations.
5075 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5076 struct isl_sched_graph *graph)
5078 int has_coincidence;
5079 int use_coincidence;
5080 int force_coincidence = 0;
5081 int check_conditional;
5083 if (sort_sccs(graph) < 0)
5084 return isl_stat_error;
5086 clear_local_edges(graph);
5087 check_conditional = need_condition_check(graph);
5088 has_coincidence = has_any_coincidence(graph);
5090 if (ctx->opt->schedule_outer_coincidence)
5091 force_coincidence = 1;
5093 use_coincidence = has_coincidence;
5094 while (graph->n_row < graph->maxvar) {
5095 isl_vec *sol;
5096 int violated;
5097 int coincident;
5099 graph->src_scc = -1;
5100 graph->dst_scc = -1;
5102 if (setup_lp(ctx, graph, use_coincidence) < 0)
5103 return isl_stat_error;
5104 sol = solve_lp(ctx, graph);
5105 if (!sol)
5106 return isl_stat_error;
5107 if (sol->size == 0) {
5108 int empty = graph->n_total_row == graph->band_start;
5110 isl_vec_free(sol);
5111 if (use_coincidence && (!force_coincidence || !empty)) {
5112 use_coincidence = 0;
5113 continue;
5115 return isl_stat_ok;
5117 coincident = !has_coincidence || use_coincidence;
5118 if (update_schedule(graph, sol, 1, coincident) < 0)
5119 return isl_stat_error;
5121 if (!check_conditional)
5122 continue;
5123 violated = has_violated_conditional_constraint(ctx, graph);
5124 if (violated < 0)
5125 return isl_stat_error;
5126 if (!violated)
5127 continue;
5128 if (reset_band(graph) < 0)
5129 return isl_stat_error;
5130 use_coincidence = has_coincidence;
5133 return isl_stat_ok;
5136 /* Compute a schedule for a connected dependence graph by considering
5137 * the graph as a whole and return the updated schedule node.
5139 * The actual schedule rows of the current band are computed by
5140 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5141 * care of integrating the band into "node" and continuing
5142 * the computation.
5144 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5145 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5147 isl_ctx *ctx;
5149 if (!node)
5150 return NULL;
5152 ctx = isl_schedule_node_get_ctx(node);
5153 if (compute_schedule_wcc_band(ctx, graph) < 0)
5154 return isl_schedule_node_free(node);
5156 return compute_schedule_finish_band(node, graph, 1);
5159 /* Clustering information used by compute_schedule_wcc_clustering.
5161 * "n" is the number of SCCs in the original dependence graph
5162 * "scc" is an array of "n" elements, each representing an SCC
5163 * of the original dependence graph. All entries in the same cluster
5164 * have the same number of schedule rows.
5165 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5166 * where each cluster is represented by the index of the first SCC
5167 * in the cluster. Initially, each SCC belongs to a cluster containing
5168 * only that SCC.
5170 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5171 * track of which SCCs need to be merged.
5173 * "cluster" contains the merged clusters of SCCs after the clustering
5174 * has completed.
5176 * "scc_node" is a temporary data structure used inside copy_partial.
5177 * For each SCC, it keeps track of the number of nodes in the SCC
5178 * that have already been copied.
5180 struct isl_clustering {
5181 int n;
5182 struct isl_sched_graph *scc;
5183 struct isl_sched_graph *cluster;
5184 int *scc_cluster;
5185 int *scc_node;
5186 int *scc_in_merge;
5189 /* Initialize the clustering data structure "c" from "graph".
5191 * In particular, allocate memory, extract the SCCs from "graph"
5192 * into c->scc, initialize scc_cluster and construct
5193 * a band of schedule rows for each SCC.
5194 * Within each SCC, there is only one SCC by definition.
5195 * Each SCC initially belongs to a cluster containing only that SCC.
5197 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5198 struct isl_sched_graph *graph)
5200 int i;
5202 c->n = graph->scc;
5203 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5204 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5205 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5206 c->scc_node = isl_calloc_array(ctx, int, c->n);
5207 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5208 if (!c->scc || !c->cluster ||
5209 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5210 return isl_stat_error;
5212 for (i = 0; i < c->n; ++i) {
5213 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5214 &edge_scc_exactly, i, &c->scc[i]) < 0)
5215 return isl_stat_error;
5216 c->scc[i].scc = 1;
5217 if (compute_maxvar(&c->scc[i]) < 0)
5218 return isl_stat_error;
5219 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5220 return isl_stat_error;
5221 c->scc_cluster[i] = i;
5224 return isl_stat_ok;
5227 /* Free all memory allocated for "c".
5229 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5231 int i;
5233 if (c->scc)
5234 for (i = 0; i < c->n; ++i)
5235 graph_free(ctx, &c->scc[i]);
5236 free(c->scc);
5237 if (c->cluster)
5238 for (i = 0; i < c->n; ++i)
5239 graph_free(ctx, &c->cluster[i]);
5240 free(c->cluster);
5241 free(c->scc_cluster);
5242 free(c->scc_node);
5243 free(c->scc_in_merge);
5246 /* Should we refrain from merging the cluster in "graph" with
5247 * any other cluster?
5248 * In particular, is its current schedule band empty and incomplete.
5250 static int bad_cluster(struct isl_sched_graph *graph)
5252 return graph->n_row < graph->maxvar &&
5253 graph->n_total_row == graph->band_start;
5256 /* Is "edge" a proximity edge with a non-empty dependence relation?
5258 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5260 if (!is_proximity(edge))
5261 return isl_bool_false;
5262 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5265 /* Return the index of an edge in "graph" that can be used to merge
5266 * two clusters in "c".
5267 * Return graph->n_edge if no such edge can be found.
5268 * Return -1 on error.
5270 * In particular, return a proximity edge between two clusters
5271 * that is not marked "no_merge" and such that neither of the
5272 * two clusters has an incomplete, empty band.
5274 * If there are multiple such edges, then try and find the most
5275 * appropriate edge to use for merging. In particular, pick the edge
5276 * with the greatest weight. If there are multiple of those,
5277 * then pick one with the shortest distance between
5278 * the two cluster representatives.
5280 static int find_proximity(struct isl_sched_graph *graph,
5281 struct isl_clustering *c)
5283 int i, best = graph->n_edge, best_dist, best_weight;
5285 for (i = 0; i < graph->n_edge; ++i) {
5286 struct isl_sched_edge *edge = &graph->edge[i];
5287 int dist, weight;
5288 isl_bool prox;
5290 prox = is_non_empty_proximity(edge);
5291 if (prox < 0)
5292 return -1;
5293 if (!prox)
5294 continue;
5295 if (edge->no_merge)
5296 continue;
5297 if (bad_cluster(&c->scc[edge->src->scc]) ||
5298 bad_cluster(&c->scc[edge->dst->scc]))
5299 continue;
5300 dist = c->scc_cluster[edge->dst->scc] -
5301 c->scc_cluster[edge->src->scc];
5302 if (dist == 0)
5303 continue;
5304 weight = edge->weight;
5305 if (best < graph->n_edge) {
5306 if (best_weight > weight)
5307 continue;
5308 if (best_weight == weight && best_dist <= dist)
5309 continue;
5311 best = i;
5312 best_dist = dist;
5313 best_weight = weight;
5316 return best;
5319 /* Internal data structure used in mark_merge_sccs.
5321 * "graph" is the dependence graph in which a strongly connected
5322 * component is constructed.
5323 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5324 * "src" and "dst" are the indices of the nodes that are being merged.
5326 struct isl_mark_merge_sccs_data {
5327 struct isl_sched_graph *graph;
5328 int *scc_cluster;
5329 int src;
5330 int dst;
5333 /* Check whether the cluster containing node "i" depends on the cluster
5334 * containing node "j". If "i" and "j" belong to the same cluster,
5335 * then they are taken to depend on each other to ensure that
5336 * the resulting strongly connected component consists of complete
5337 * clusters. Furthermore, if "i" and "j" are the two nodes that
5338 * are being merged, then they are taken to depend on each other as well.
5339 * Otherwise, check if there is a (conditional) validity dependence
5340 * from node[j] to node[i], forcing node[i] to follow node[j].
5342 static isl_bool cluster_follows(int i, int j, void *user)
5344 struct isl_mark_merge_sccs_data *data = user;
5345 struct isl_sched_graph *graph = data->graph;
5346 int *scc_cluster = data->scc_cluster;
5348 if (data->src == i && data->dst == j)
5349 return isl_bool_true;
5350 if (data->src == j && data->dst == i)
5351 return isl_bool_true;
5352 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5353 return isl_bool_true;
5355 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5358 /* Mark all SCCs that belong to either of the two clusters in "c"
5359 * connected by the edge in "graph" with index "edge", or to any
5360 * of the intermediate clusters.
5361 * The marking is recorded in c->scc_in_merge.
5363 * The given edge has been selected for merging two clusters,
5364 * meaning that there is at least a proximity edge between the two nodes.
5365 * However, there may also be (indirect) validity dependences
5366 * between the two nodes. When merging the two clusters, all clusters
5367 * containing one or more of the intermediate nodes along the
5368 * indirect validity dependences need to be merged in as well.
5370 * First collect all such nodes by computing the strongly connected
5371 * component (SCC) containing the two nodes connected by the edge, where
5372 * the two nodes are considered to depend on each other to make
5373 * sure they end up in the same SCC. Similarly, each node is considered
5374 * to depend on every other node in the same cluster to ensure
5375 * that the SCC consists of complete clusters.
5377 * Then the original SCCs that contain any of these nodes are marked
5378 * in c->scc_in_merge.
5380 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5381 int edge, struct isl_clustering *c)
5383 struct isl_mark_merge_sccs_data data;
5384 struct isl_tarjan_graph *g;
5385 int i;
5387 for (i = 0; i < c->n; ++i)
5388 c->scc_in_merge[i] = 0;
5390 data.graph = graph;
5391 data.scc_cluster = c->scc_cluster;
5392 data.src = graph->edge[edge].src - graph->node;
5393 data.dst = graph->edge[edge].dst - graph->node;
5395 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5396 &cluster_follows, &data);
5397 if (!g)
5398 goto error;
5400 i = g->op;
5401 if (i < 3)
5402 isl_die(ctx, isl_error_internal,
5403 "expecting at least two nodes in component",
5404 goto error);
5405 if (g->order[--i] != -1)
5406 isl_die(ctx, isl_error_internal,
5407 "expecting end of component marker", goto error);
5409 for (--i; i >= 0 && g->order[i] != -1; --i) {
5410 int scc = graph->node[g->order[i]].scc;
5411 c->scc_in_merge[scc] = 1;
5414 isl_tarjan_graph_free(g);
5415 return isl_stat_ok;
5416 error:
5417 isl_tarjan_graph_free(g);
5418 return isl_stat_error;
5421 /* Construct the identifier "cluster_i".
5423 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5425 char name[40];
5427 snprintf(name, sizeof(name), "cluster_%d", i);
5428 return isl_id_alloc(ctx, name, NULL);
5431 /* Construct the space of the cluster with index "i" containing
5432 * the strongly connected component "scc".
5434 * In particular, construct a space called cluster_i with dimension equal
5435 * to the number of schedule rows in the current band of "scc".
5437 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5439 int nvar;
5440 isl_space *space;
5441 isl_id *id;
5443 nvar = scc->n_total_row - scc->band_start;
5444 space = isl_space_copy(scc->node[0].space);
5445 space = isl_space_params(space);
5446 space = isl_space_set_from_params(space);
5447 space = isl_space_add_dims(space, isl_dim_set, nvar);
5448 id = cluster_id(isl_space_get_ctx(space), i);
5449 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5451 return space;
5454 /* Collect the domain of the graph for merging clusters.
5456 * In particular, for each cluster with first SCC "i", construct
5457 * a set in the space called cluster_i with dimension equal
5458 * to the number of schedule rows in the current band of the cluster.
5460 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5461 struct isl_sched_graph *graph, struct isl_clustering *c)
5463 int i;
5464 isl_space *space;
5465 isl_union_set *domain;
5467 space = isl_space_params_alloc(ctx, 0);
5468 domain = isl_union_set_empty(space);
5470 for (i = 0; i < graph->scc; ++i) {
5471 isl_space *space;
5473 if (!c->scc_in_merge[i])
5474 continue;
5475 if (c->scc_cluster[i] != i)
5476 continue;
5477 space = cluster_space(&c->scc[i], i);
5478 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5481 return domain;
5484 /* Construct a map from the original instances to the corresponding
5485 * cluster instance in the current bands of the clusters in "c".
5487 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5488 struct isl_sched_graph *graph, struct isl_clustering *c)
5490 int i, j;
5491 isl_space *space;
5492 isl_union_map *cluster_map;
5494 space = isl_space_params_alloc(ctx, 0);
5495 cluster_map = isl_union_map_empty(space);
5496 for (i = 0; i < graph->scc; ++i) {
5497 int start, n;
5498 isl_id *id;
5500 if (!c->scc_in_merge[i])
5501 continue;
5503 id = cluster_id(ctx, c->scc_cluster[i]);
5504 start = c->scc[i].band_start;
5505 n = c->scc[i].n_total_row - start;
5506 for (j = 0; j < c->scc[i].n; ++j) {
5507 isl_multi_aff *ma;
5508 isl_map *map;
5509 struct isl_sched_node *node = &c->scc[i].node[j];
5511 ma = node_extract_partial_schedule_multi_aff(node,
5512 start, n);
5513 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5514 isl_id_copy(id));
5515 map = isl_map_from_multi_aff(ma);
5516 cluster_map = isl_union_map_add_map(cluster_map, map);
5518 isl_id_free(id);
5521 return cluster_map;
5524 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5525 * that are not isl_edge_condition or isl_edge_conditional_validity.
5527 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5528 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5529 __isl_take isl_schedule_constraints *sc)
5531 enum isl_edge_type t;
5533 if (!sc)
5534 return NULL;
5536 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5537 if (t == isl_edge_condition ||
5538 t == isl_edge_conditional_validity)
5539 continue;
5540 if (!is_type(edge, t))
5541 continue;
5542 sc = isl_schedule_constraints_add(sc, t,
5543 isl_union_map_copy(umap));
5546 return sc;
5549 /* Add schedule constraints of types isl_edge_condition and
5550 * isl_edge_conditional_validity to "sc" by applying "umap" to
5551 * the domains of the wrapped relations in domain and range
5552 * of the corresponding tagged constraints of "edge".
5554 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5555 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5556 __isl_take isl_schedule_constraints *sc)
5558 enum isl_edge_type t;
5559 isl_union_map *tagged;
5561 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5562 if (!is_type(edge, t))
5563 continue;
5564 if (t == isl_edge_condition)
5565 tagged = isl_union_map_copy(edge->tagged_condition);
5566 else
5567 tagged = isl_union_map_copy(edge->tagged_validity);
5568 tagged = isl_union_map_zip(tagged);
5569 tagged = isl_union_map_apply_domain(tagged,
5570 isl_union_map_copy(umap));
5571 tagged = isl_union_map_zip(tagged);
5572 sc = isl_schedule_constraints_add(sc, t, tagged);
5573 if (!sc)
5574 return NULL;
5577 return sc;
5580 /* Given a mapping "cluster_map" from the original instances to
5581 * the cluster instances, add schedule constraints on the clusters
5582 * to "sc" corresponding to the original constraints represented by "edge".
5584 * For non-tagged dependence constraints, the cluster constraints
5585 * are obtained by applying "cluster_map" to the edge->map.
5587 * For tagged dependence constraints, "cluster_map" needs to be applied
5588 * to the domains of the wrapped relations in domain and range
5589 * of the tagged dependence constraints. Pick out the mappings
5590 * from these domains from "cluster_map" and construct their product.
5591 * This mapping can then be applied to the pair of domains.
5593 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5594 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5595 __isl_take isl_schedule_constraints *sc)
5597 isl_union_map *umap;
5598 isl_space *space;
5599 isl_union_set *uset;
5600 isl_union_map *umap1, *umap2;
5602 if (!sc)
5603 return NULL;
5605 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5606 umap = isl_union_map_apply_domain(umap,
5607 isl_union_map_copy(cluster_map));
5608 umap = isl_union_map_apply_range(umap,
5609 isl_union_map_copy(cluster_map));
5610 sc = add_non_conditional_constraints(edge, umap, sc);
5611 isl_union_map_free(umap);
5613 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5614 return sc;
5616 space = isl_space_domain(isl_map_get_space(edge->map));
5617 uset = isl_union_set_from_set(isl_set_universe(space));
5618 umap1 = isl_union_map_copy(cluster_map);
5619 umap1 = isl_union_map_intersect_domain(umap1, uset);
5620 space = isl_space_range(isl_map_get_space(edge->map));
5621 uset = isl_union_set_from_set(isl_set_universe(space));
5622 umap2 = isl_union_map_copy(cluster_map);
5623 umap2 = isl_union_map_intersect_domain(umap2, uset);
5624 umap = isl_union_map_product(umap1, umap2);
5626 sc = add_conditional_constraints(edge, umap, sc);
5628 isl_union_map_free(umap);
5629 return sc;
5632 /* Given a mapping "cluster_map" from the original instances to
5633 * the cluster instances, add schedule constraints on the clusters
5634 * to "sc" corresponding to all edges in "graph" between nodes that
5635 * belong to SCCs that are marked for merging in "scc_in_merge".
5637 static __isl_give isl_schedule_constraints *collect_constraints(
5638 struct isl_sched_graph *graph, int *scc_in_merge,
5639 __isl_keep isl_union_map *cluster_map,
5640 __isl_take isl_schedule_constraints *sc)
5642 int i;
5644 for (i = 0; i < graph->n_edge; ++i) {
5645 struct isl_sched_edge *edge = &graph->edge[i];
5647 if (!scc_in_merge[edge->src->scc])
5648 continue;
5649 if (!scc_in_merge[edge->dst->scc])
5650 continue;
5651 sc = collect_edge_constraints(edge, cluster_map, sc);
5654 return sc;
5657 /* Construct a dependence graph for scheduling clusters with respect
5658 * to each other and store the result in "merge_graph".
5659 * In particular, the nodes of the graph correspond to the schedule
5660 * dimensions of the current bands of those clusters that have been
5661 * marked for merging in "c".
5663 * First construct an isl_schedule_constraints object for this domain
5664 * by transforming the edges in "graph" to the domain.
5665 * Then initialize a dependence graph for scheduling from these
5666 * constraints.
5668 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5669 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5671 isl_union_set *domain;
5672 isl_union_map *cluster_map;
5673 isl_schedule_constraints *sc;
5674 isl_stat r;
5676 domain = collect_domain(ctx, graph, c);
5677 sc = isl_schedule_constraints_on_domain(domain);
5678 if (!sc)
5679 return isl_stat_error;
5680 cluster_map = collect_cluster_map(ctx, graph, c);
5681 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5682 isl_union_map_free(cluster_map);
5684 r = graph_init(merge_graph, sc);
5686 isl_schedule_constraints_free(sc);
5688 return r;
5691 /* Compute the maximal number of remaining schedule rows that still need
5692 * to be computed for the nodes that belong to clusters with the maximal
5693 * dimension for the current band (i.e., the band that is to be merged).
5694 * Only clusters that are about to be merged are considered.
5695 * "maxvar" is the maximal dimension for the current band.
5696 * "c" contains information about the clusters.
5698 * Return the maximal number of remaining schedule rows or -1 on error.
5700 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5702 int i, j;
5703 int max_slack;
5705 max_slack = 0;
5706 for (i = 0; i < c->n; ++i) {
5707 int nvar;
5708 struct isl_sched_graph *scc;
5710 if (!c->scc_in_merge[i])
5711 continue;
5712 scc = &c->scc[i];
5713 nvar = scc->n_total_row - scc->band_start;
5714 if (nvar != maxvar)
5715 continue;
5716 for (j = 0; j < scc->n; ++j) {
5717 struct isl_sched_node *node = &scc->node[j];
5718 int slack;
5720 if (node_update_cmap(node) < 0)
5721 return -1;
5722 slack = node->nvar - node->rank;
5723 if (slack > max_slack)
5724 max_slack = slack;
5728 return max_slack;
5731 /* If there are any clusters where the dimension of the current band
5732 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5733 * if there are any nodes in such a cluster where the number
5734 * of remaining schedule rows that still need to be computed
5735 * is greater than "max_slack", then return the smallest current band
5736 * dimension of all these clusters. Otherwise return the original value
5737 * of "maxvar". Return -1 in case of any error.
5738 * Only clusters that are about to be merged are considered.
5739 * "c" contains information about the clusters.
5741 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5742 struct isl_clustering *c)
5744 int i, j;
5746 for (i = 0; i < c->n; ++i) {
5747 int nvar;
5748 struct isl_sched_graph *scc;
5750 if (!c->scc_in_merge[i])
5751 continue;
5752 scc = &c->scc[i];
5753 nvar = scc->n_total_row - scc->band_start;
5754 if (nvar >= maxvar)
5755 continue;
5756 for (j = 0; j < scc->n; ++j) {
5757 struct isl_sched_node *node = &scc->node[j];
5758 int slack;
5760 if (node_update_cmap(node) < 0)
5761 return -1;
5762 slack = node->nvar - node->rank;
5763 if (slack > max_slack) {
5764 maxvar = nvar;
5765 break;
5770 return maxvar;
5773 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5774 * that still need to be computed. In particular, if there is a node
5775 * in a cluster where the dimension of the current band is smaller
5776 * than merge_graph->maxvar, but the number of remaining schedule rows
5777 * is greater than that of any node in a cluster with the maximal
5778 * dimension for the current band (i.e., merge_graph->maxvar),
5779 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5780 * of those clusters. Without this adjustment, the total number of
5781 * schedule dimensions would be increased, resulting in a skewed view
5782 * of the number of coincident dimensions.
5783 * "c" contains information about the clusters.
5785 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5786 * then there is no point in attempting any merge since it will be rejected
5787 * anyway. Set merge_graph->maxvar to zero in such cases.
5789 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5790 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5792 int max_slack, maxvar;
5794 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5795 if (max_slack < 0)
5796 return isl_stat_error;
5797 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5798 if (maxvar < 0)
5799 return isl_stat_error;
5801 if (maxvar < merge_graph->maxvar) {
5802 if (isl_options_get_schedule_maximize_band_depth(ctx))
5803 merge_graph->maxvar = 0;
5804 else
5805 merge_graph->maxvar = maxvar;
5808 return isl_stat_ok;
5811 /* Return the number of coincident dimensions in the current band of "graph",
5812 * where the nodes of "graph" are assumed to be scheduled by a single band.
5814 static int get_n_coincident(struct isl_sched_graph *graph)
5816 int i;
5818 for (i = graph->band_start; i < graph->n_total_row; ++i)
5819 if (!graph->node[0].coincident[i])
5820 break;
5822 return i - graph->band_start;
5825 /* Should the clusters be merged based on the cluster schedule
5826 * in the current (and only) band of "merge_graph", given that
5827 * coincidence should be maximized?
5829 * If the number of coincident schedule dimensions in the merged band
5830 * would be less than the maximal number of coincident schedule dimensions
5831 * in any of the merged clusters, then the clusters should not be merged.
5833 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5834 struct isl_sched_graph *merge_graph)
5836 int i;
5837 int n_coincident;
5838 int max_coincident;
5840 max_coincident = 0;
5841 for (i = 0; i < c->n; ++i) {
5842 if (!c->scc_in_merge[i])
5843 continue;
5844 n_coincident = get_n_coincident(&c->scc[i]);
5845 if (n_coincident > max_coincident)
5846 max_coincident = n_coincident;
5849 n_coincident = get_n_coincident(merge_graph);
5851 return n_coincident >= max_coincident;
5854 /* Return the transformation on "node" expressed by the current (and only)
5855 * band of "merge_graph" applied to the clusters in "c".
5857 * First find the representation of "node" in its SCC in "c" and
5858 * extract the transformation expressed by the current band.
5859 * Then extract the transformation applied by "merge_graph"
5860 * to the cluster to which this SCC belongs.
5861 * Combine the two to obtain the complete transformation on the node.
5863 * Note that the range of the first transformation is an anonymous space,
5864 * while the domain of the second is named "cluster_X". The range
5865 * of the former therefore needs to be adjusted before the two
5866 * can be combined.
5868 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5869 struct isl_sched_node *node, struct isl_clustering *c,
5870 struct isl_sched_graph *merge_graph)
5872 struct isl_sched_node *scc_node, *cluster_node;
5873 int start, n;
5874 isl_id *id;
5875 isl_space *space;
5876 isl_multi_aff *ma, *ma2;
5878 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5879 start = c->scc[node->scc].band_start;
5880 n = c->scc[node->scc].n_total_row - start;
5881 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5882 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5883 cluster_node = graph_find_node(ctx, merge_graph, space);
5884 if (space && !cluster_node)
5885 isl_die(ctx, isl_error_internal, "unable to find cluster",
5886 space = isl_space_free(space));
5887 id = isl_space_get_tuple_id(space, isl_dim_set);
5888 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5889 isl_space_free(space);
5890 n = merge_graph->n_total_row;
5891 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5892 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5894 return isl_map_from_multi_aff(ma);
5897 /* Give a set of distances "set", are they bounded by a small constant
5898 * in direction "pos"?
5899 * In practice, check if they are bounded by 2 by checking that there
5900 * are no elements with a value greater than or equal to 3 or
5901 * smaller than or equal to -3.
5903 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5905 isl_bool bounded;
5906 isl_set *test;
5908 if (!set)
5909 return isl_bool_error;
5911 test = isl_set_copy(set);
5912 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5913 bounded = isl_set_is_empty(test);
5914 isl_set_free(test);
5916 if (bounded < 0 || !bounded)
5917 return bounded;
5919 test = isl_set_copy(set);
5920 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5921 bounded = isl_set_is_empty(test);
5922 isl_set_free(test);
5924 return bounded;
5927 /* Does the set "set" have a fixed (but possible parametric) value
5928 * at dimension "pos"?
5930 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5932 int n;
5933 isl_bool single;
5935 if (!set)
5936 return isl_bool_error;
5937 set = isl_set_copy(set);
5938 n = isl_set_dim(set, isl_dim_set);
5939 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5940 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5941 single = isl_set_is_singleton(set);
5942 isl_set_free(set);
5944 return single;
5947 /* Does "map" have a fixed (but possible parametric) value
5948 * at dimension "pos" of either its domain or its range?
5950 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5952 isl_set *set;
5953 isl_bool single;
5955 set = isl_map_domain(isl_map_copy(map));
5956 single = has_single_value(set, pos);
5957 isl_set_free(set);
5959 if (single < 0 || single)
5960 return single;
5962 set = isl_map_range(isl_map_copy(map));
5963 single = has_single_value(set, pos);
5964 isl_set_free(set);
5966 return single;
5969 /* Does the edge "edge" from "graph" have bounded dependence distances
5970 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5972 * Extract the complete transformations of the source and destination
5973 * nodes of the edge, apply them to the edge constraints and
5974 * compute the differences. Finally, check if these differences are bounded
5975 * in each direction.
5977 * If the dimension of the band is greater than the number of
5978 * dimensions that can be expected to be optimized by the edge
5979 * (based on its weight), then also allow the differences to be unbounded
5980 * in the remaining dimensions, but only if either the source or
5981 * the destination has a fixed value in that direction.
5982 * This allows a statement that produces values that are used by
5983 * several instances of another statement to be merged with that
5984 * other statement.
5985 * However, merging such clusters will introduce an inherently
5986 * large proximity distance inside the merged cluster, meaning
5987 * that proximity distances will no longer be optimized in
5988 * subsequent merges. These merges are therefore only allowed
5989 * after all other possible merges have been tried.
5990 * The first time such a merge is encountered, the weight of the edge
5991 * is replaced by a negative weight. The second time (i.e., after
5992 * all merges over edges with a non-negative weight have been tried),
5993 * the merge is allowed.
5995 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5996 struct isl_sched_graph *graph, struct isl_clustering *c,
5997 struct isl_sched_graph *merge_graph)
5999 int i, n, n_slack;
6000 isl_bool bounded;
6001 isl_map *map, *t;
6002 isl_set *dist;
6004 map = isl_map_copy(edge->map);
6005 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6006 map = isl_map_apply_domain(map, t);
6007 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6008 map = isl_map_apply_range(map, t);
6009 dist = isl_map_deltas(isl_map_copy(map));
6011 bounded = isl_bool_true;
6012 n = isl_set_dim(dist, isl_dim_set);
6013 n_slack = n - edge->weight;
6014 if (edge->weight < 0)
6015 n_slack -= graph->max_weight + 1;
6016 for (i = 0; i < n; ++i) {
6017 isl_bool bounded_i, singular_i;
6019 bounded_i = distance_is_bounded(dist, i);
6020 if (bounded_i < 0)
6021 goto error;
6022 if (bounded_i)
6023 continue;
6024 if (edge->weight >= 0)
6025 bounded = isl_bool_false;
6026 n_slack--;
6027 if (n_slack < 0)
6028 break;
6029 singular_i = has_singular_src_or_dst(map, i);
6030 if (singular_i < 0)
6031 goto error;
6032 if (singular_i)
6033 continue;
6034 bounded = isl_bool_false;
6035 break;
6037 if (!bounded && i >= n && edge->weight >= 0)
6038 edge->weight -= graph->max_weight + 1;
6039 isl_map_free(map);
6040 isl_set_free(dist);
6042 return bounded;
6043 error:
6044 isl_map_free(map);
6045 isl_set_free(dist);
6046 return isl_bool_error;
6049 /* Should the clusters be merged based on the cluster schedule
6050 * in the current (and only) band of "merge_graph"?
6051 * "graph" is the original dependence graph, while "c" records
6052 * which SCCs are involved in the latest merge.
6054 * In particular, is there at least one proximity constraint
6055 * that is optimized by the merge?
6057 * A proximity constraint is considered to be optimized
6058 * if the dependence distances are small.
6060 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6061 struct isl_sched_graph *graph, struct isl_clustering *c,
6062 struct isl_sched_graph *merge_graph)
6064 int i;
6066 for (i = 0; i < graph->n_edge; ++i) {
6067 struct isl_sched_edge *edge = &graph->edge[i];
6068 isl_bool bounded;
6070 if (!is_proximity(edge))
6071 continue;
6072 if (!c->scc_in_merge[edge->src->scc])
6073 continue;
6074 if (!c->scc_in_merge[edge->dst->scc])
6075 continue;
6076 if (c->scc_cluster[edge->dst->scc] ==
6077 c->scc_cluster[edge->src->scc])
6078 continue;
6079 bounded = has_bounded_distances(ctx, edge, graph, c,
6080 merge_graph);
6081 if (bounded < 0 || bounded)
6082 return bounded;
6085 return isl_bool_false;
6088 /* Should the clusters be merged based on the cluster schedule
6089 * in the current (and only) band of "merge_graph"?
6090 * "graph" is the original dependence graph, while "c" records
6091 * which SCCs are involved in the latest merge.
6093 * If the current band is empty, then the clusters should not be merged.
6095 * If the band depth should be maximized and the merge schedule
6096 * is incomplete (meaning that the dimension of some of the schedule
6097 * bands in the original schedule will be reduced), then the clusters
6098 * should not be merged.
6100 * If the schedule_maximize_coincidence option is set, then check that
6101 * the number of coincident schedule dimensions is not reduced.
6103 * Finally, only allow the merge if at least one proximity
6104 * constraint is optimized.
6106 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6107 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6109 if (merge_graph->n_total_row == merge_graph->band_start)
6110 return isl_bool_false;
6112 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6113 merge_graph->n_total_row < merge_graph->maxvar)
6114 return isl_bool_false;
6116 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6117 isl_bool ok;
6119 ok = ok_to_merge_coincident(c, merge_graph);
6120 if (ok < 0 || !ok)
6121 return ok;
6124 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6127 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6128 * of the schedule in "node" and return the result.
6130 * That is, essentially compute
6132 * T * N(first:first+n-1)
6134 * taking into account the constant term and the parameter coefficients
6135 * in "t_node".
6137 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6138 struct isl_sched_node *t_node, struct isl_sched_node *node,
6139 int first, int n)
6141 int i, j;
6142 isl_mat *t;
6143 int n_row, n_col, n_param, n_var;
6145 n_param = node->nparam;
6146 n_var = node->nvar;
6147 n_row = isl_mat_rows(t_node->sched);
6148 n_col = isl_mat_cols(node->sched);
6149 t = isl_mat_alloc(ctx, n_row, n_col);
6150 if (!t)
6151 return NULL;
6152 for (i = 0; i < n_row; ++i) {
6153 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6154 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6155 for (j = 0; j < n; ++j)
6156 isl_seq_addmul(t->row[i],
6157 t_node->sched->row[i][1 + n_param + j],
6158 node->sched->row[first + j],
6159 1 + n_param + n_var);
6161 return t;
6164 /* Apply the cluster schedule in "t_node" to the current band
6165 * schedule of the nodes in "graph".
6167 * In particular, replace the rows starting at band_start
6168 * by the result of applying the cluster schedule in "t_node"
6169 * to the original rows.
6171 * The coincidence of the schedule is determined by the coincidence
6172 * of the cluster schedule.
6174 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6175 struct isl_sched_node *t_node)
6177 int i, j;
6178 int n_new;
6179 int start, n;
6181 start = graph->band_start;
6182 n = graph->n_total_row - start;
6184 n_new = isl_mat_rows(t_node->sched);
6185 for (i = 0; i < graph->n; ++i) {
6186 struct isl_sched_node *node = &graph->node[i];
6187 isl_mat *t;
6189 t = node_transformation(ctx, t_node, node, start, n);
6190 node->sched = isl_mat_drop_rows(node->sched, start, n);
6191 node->sched = isl_mat_concat(node->sched, t);
6192 node->sched_map = isl_map_free(node->sched_map);
6193 if (!node->sched)
6194 return isl_stat_error;
6195 for (j = 0; j < n_new; ++j)
6196 node->coincident[start + j] = t_node->coincident[j];
6198 graph->n_total_row -= n;
6199 graph->n_row -= n;
6200 graph->n_total_row += n_new;
6201 graph->n_row += n_new;
6203 return isl_stat_ok;
6206 /* Merge the clusters marked for merging in "c" into a single
6207 * cluster using the cluster schedule in the current band of "merge_graph".
6208 * The representative SCC for the new cluster is the SCC with
6209 * the smallest index.
6211 * The current band schedule of each SCC in the new cluster is obtained
6212 * by applying the schedule of the corresponding original cluster
6213 * to the original band schedule.
6214 * All SCCs in the new cluster have the same number of schedule rows.
6216 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6217 struct isl_sched_graph *merge_graph)
6219 int i;
6220 int cluster = -1;
6221 isl_space *space;
6223 for (i = 0; i < c->n; ++i) {
6224 struct isl_sched_node *node;
6226 if (!c->scc_in_merge[i])
6227 continue;
6228 if (cluster < 0)
6229 cluster = i;
6230 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6231 if (!space)
6232 return isl_stat_error;
6233 node = graph_find_node(ctx, merge_graph, space);
6234 isl_space_free(space);
6235 if (!node)
6236 isl_die(ctx, isl_error_internal,
6237 "unable to find cluster",
6238 return isl_stat_error);
6239 if (transform(ctx, &c->scc[i], node) < 0)
6240 return isl_stat_error;
6241 c->scc_cluster[i] = cluster;
6244 return isl_stat_ok;
6247 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6248 * by scheduling the current cluster bands with respect to each other.
6250 * Construct a dependence graph with a space for each cluster and
6251 * with the coordinates of each space corresponding to the schedule
6252 * dimensions of the current band of that cluster.
6253 * Construct a cluster schedule in this cluster dependence graph and
6254 * apply it to the current cluster bands if it is applicable
6255 * according to ok_to_merge.
6257 * If the number of remaining schedule dimensions in a cluster
6258 * with a non-maximal current schedule dimension is greater than
6259 * the number of remaining schedule dimensions in clusters
6260 * with a maximal current schedule dimension, then restrict
6261 * the number of rows to be computed in the cluster schedule
6262 * to the minimal such non-maximal current schedule dimension.
6263 * Do this by adjusting merge_graph.maxvar.
6265 * Return isl_bool_true if the clusters have effectively been merged
6266 * into a single cluster.
6268 * Note that since the standard scheduling algorithm minimizes the maximal
6269 * distance over proximity constraints, the proximity constraints between
6270 * the merged clusters may not be optimized any further than what is
6271 * sufficient to bring the distances within the limits of the internal
6272 * proximity constraints inside the individual clusters.
6273 * It may therefore make sense to perform an additional translation step
6274 * to bring the clusters closer to each other, while maintaining
6275 * the linear part of the merging schedule found using the standard
6276 * scheduling algorithm.
6278 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6279 struct isl_clustering *c)
6281 struct isl_sched_graph merge_graph = { 0 };
6282 isl_bool merged;
6284 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6285 goto error;
6287 if (compute_maxvar(&merge_graph) < 0)
6288 goto error;
6289 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6290 goto error;
6291 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6292 goto error;
6293 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6294 if (merged && merge(ctx, c, &merge_graph) < 0)
6295 goto error;
6297 graph_free(ctx, &merge_graph);
6298 return merged;
6299 error:
6300 graph_free(ctx, &merge_graph);
6301 return isl_bool_error;
6304 /* Is there any edge marked "no_merge" between two SCCs that are
6305 * about to be merged (i.e., that are set in "scc_in_merge")?
6306 * "merge_edge" is the proximity edge along which the clusters of SCCs
6307 * are going to be merged.
6309 * If there is any edge between two SCCs with a negative weight,
6310 * while the weight of "merge_edge" is non-negative, then this
6311 * means that the edge was postponed. "merge_edge" should then
6312 * also be postponed since merging along the edge with negative weight should
6313 * be postponed until all edges with non-negative weight have been tried.
6314 * Replace the weight of "merge_edge" by a negative weight as well and
6315 * tell the caller not to attempt a merge.
6317 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6318 struct isl_sched_edge *merge_edge)
6320 int i;
6322 for (i = 0; i < graph->n_edge; ++i) {
6323 struct isl_sched_edge *edge = &graph->edge[i];
6325 if (!scc_in_merge[edge->src->scc])
6326 continue;
6327 if (!scc_in_merge[edge->dst->scc])
6328 continue;
6329 if (edge->no_merge)
6330 return 1;
6331 if (merge_edge->weight >= 0 && edge->weight < 0) {
6332 merge_edge->weight -= graph->max_weight + 1;
6333 return 1;
6337 return 0;
6340 /* Merge the two clusters in "c" connected by the edge in "graph"
6341 * with index "edge" into a single cluster.
6342 * If it turns out to be impossible to merge these two clusters,
6343 * then mark the edge as "no_merge" such that it will not be
6344 * considered again.
6346 * First mark all SCCs that need to be merged. This includes the SCCs
6347 * in the two clusters, but it may also include the SCCs
6348 * of intermediate clusters.
6349 * If there is already a no_merge edge between any pair of such SCCs,
6350 * then simply mark the current edge as no_merge as well.
6351 * Likewise, if any of those edges was postponed by has_bounded_distances,
6352 * then postpone the current edge as well.
6353 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6354 * if the clusters did not end up getting merged, unless the non-merge
6355 * is due to the fact that the edge was postponed. This postponement
6356 * can be recognized by a change in weight (from non-negative to negative).
6358 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6359 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6361 isl_bool merged;
6362 int edge_weight = graph->edge[edge].weight;
6364 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6365 return isl_stat_error;
6367 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6368 merged = isl_bool_false;
6369 else
6370 merged = try_merge(ctx, graph, c);
6371 if (merged < 0)
6372 return isl_stat_error;
6373 if (!merged && edge_weight == graph->edge[edge].weight)
6374 graph->edge[edge].no_merge = 1;
6376 return isl_stat_ok;
6379 /* Does "node" belong to the cluster identified by "cluster"?
6381 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6383 return node->cluster == cluster;
6386 /* Does "edge" connect two nodes belonging to the cluster
6387 * identified by "cluster"?
6389 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6391 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6394 /* Swap the schedule of "node1" and "node2".
6395 * Both nodes have been derived from the same node in a common parent graph.
6396 * Since the "coincident" field is shared with that node
6397 * in the parent graph, there is no need to also swap this field.
6399 static void swap_sched(struct isl_sched_node *node1,
6400 struct isl_sched_node *node2)
6402 isl_mat *sched;
6403 isl_map *sched_map;
6405 sched = node1->sched;
6406 node1->sched = node2->sched;
6407 node2->sched = sched;
6409 sched_map = node1->sched_map;
6410 node1->sched_map = node2->sched_map;
6411 node2->sched_map = sched_map;
6414 /* Copy the current band schedule from the SCCs that form the cluster
6415 * with index "pos" to the actual cluster at position "pos".
6416 * By construction, the index of the first SCC that belongs to the cluster
6417 * is also "pos".
6419 * The order of the nodes inside both the SCCs and the cluster
6420 * is assumed to be same as the order in the original "graph".
6422 * Since the SCC graphs will no longer be used after this function,
6423 * the schedules are actually swapped rather than copied.
6425 static isl_stat copy_partial(struct isl_sched_graph *graph,
6426 struct isl_clustering *c, int pos)
6428 int i, j;
6430 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6431 c->cluster[pos].n_row = c->scc[pos].n_row;
6432 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6433 j = 0;
6434 for (i = 0; i < graph->n; ++i) {
6435 int k;
6436 int s;
6438 if (graph->node[i].cluster != pos)
6439 continue;
6440 s = graph->node[i].scc;
6441 k = c->scc_node[s]++;
6442 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6443 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6444 c->cluster[pos].maxvar = c->scc[s].maxvar;
6445 ++j;
6448 return isl_stat_ok;
6451 /* Is there a (conditional) validity dependence from node[j] to node[i],
6452 * forcing node[i] to follow node[j] or do the nodes belong to the same
6453 * cluster?
6455 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6457 struct isl_sched_graph *graph = user;
6459 if (graph->node[i].cluster == graph->node[j].cluster)
6460 return isl_bool_true;
6461 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6464 /* Extract the merged clusters of SCCs in "graph", sort them, and
6465 * store them in c->clusters. Update c->scc_cluster accordingly.
6467 * First keep track of the cluster containing the SCC to which a node
6468 * belongs in the node itself.
6469 * Then extract the clusters into c->clusters, copying the current
6470 * band schedule from the SCCs that belong to the cluster.
6471 * Do this only once per cluster.
6473 * Finally, topologically sort the clusters and update c->scc_cluster
6474 * to match the new scc numbering. While the SCCs were originally
6475 * sorted already, some SCCs that depend on some other SCCs may
6476 * have been merged with SCCs that appear before these other SCCs.
6477 * A reordering may therefore be required.
6479 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6480 struct isl_clustering *c)
6482 int i;
6484 for (i = 0; i < graph->n; ++i)
6485 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6487 for (i = 0; i < graph->scc; ++i) {
6488 if (c->scc_cluster[i] != i)
6489 continue;
6490 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6491 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6492 return isl_stat_error;
6493 c->cluster[i].src_scc = -1;
6494 c->cluster[i].dst_scc = -1;
6495 if (copy_partial(graph, c, i) < 0)
6496 return isl_stat_error;
6499 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6500 return isl_stat_error;
6501 for (i = 0; i < graph->n; ++i)
6502 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6504 return isl_stat_ok;
6507 /* Compute weights on the proximity edges of "graph" that can
6508 * be used by find_proximity to find the most appropriate
6509 * proximity edge to use to merge two clusters in "c".
6510 * The weights are also used by has_bounded_distances to determine
6511 * whether the merge should be allowed.
6512 * Store the maximum of the computed weights in graph->max_weight.
6514 * The computed weight is a measure for the number of remaining schedule
6515 * dimensions that can still be completely aligned.
6516 * In particular, compute the number of equalities between
6517 * input dimensions and output dimensions in the proximity constraints.
6518 * The directions that are already handled by outer schedule bands
6519 * are projected out prior to determining this number.
6521 * Edges that will never be considered by find_proximity are ignored.
6523 static isl_stat compute_weights(struct isl_sched_graph *graph,
6524 struct isl_clustering *c)
6526 int i;
6528 graph->max_weight = 0;
6530 for (i = 0; i < graph->n_edge; ++i) {
6531 struct isl_sched_edge *edge = &graph->edge[i];
6532 struct isl_sched_node *src = edge->src;
6533 struct isl_sched_node *dst = edge->dst;
6534 isl_basic_map *hull;
6535 isl_bool prox;
6536 int n_in, n_out;
6538 prox = is_non_empty_proximity(edge);
6539 if (prox < 0)
6540 return isl_stat_error;
6541 if (!prox)
6542 continue;
6543 if (bad_cluster(&c->scc[edge->src->scc]) ||
6544 bad_cluster(&c->scc[edge->dst->scc]))
6545 continue;
6546 if (c->scc_cluster[edge->dst->scc] ==
6547 c->scc_cluster[edge->src->scc])
6548 continue;
6550 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6551 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6552 isl_mat_copy(src->ctrans));
6553 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6554 isl_mat_copy(dst->ctrans));
6555 hull = isl_basic_map_project_out(hull,
6556 isl_dim_in, 0, src->rank);
6557 hull = isl_basic_map_project_out(hull,
6558 isl_dim_out, 0, dst->rank);
6559 hull = isl_basic_map_remove_divs(hull);
6560 n_in = isl_basic_map_dim(hull, isl_dim_in);
6561 n_out = isl_basic_map_dim(hull, isl_dim_out);
6562 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6563 isl_dim_in, 0, n_in);
6564 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6565 isl_dim_out, 0, n_out);
6566 if (!hull)
6567 return isl_stat_error;
6568 edge->weight = isl_basic_map_n_equality(hull);
6569 isl_basic_map_free(hull);
6571 if (edge->weight > graph->max_weight)
6572 graph->max_weight = edge->weight;
6575 return isl_stat_ok;
6578 /* Call compute_schedule_finish_band on each of the clusters in "c"
6579 * in their topological order. This order is determined by the scc
6580 * fields of the nodes in "graph".
6581 * Combine the results in a sequence expressing the topological order.
6583 * If there is only one cluster left, then there is no need to introduce
6584 * a sequence node. Also, in this case, the cluster necessarily contains
6585 * the SCC at position 0 in the original graph and is therefore also
6586 * stored in the first cluster of "c".
6588 static __isl_give isl_schedule_node *finish_bands_clustering(
6589 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6590 struct isl_clustering *c)
6592 int i;
6593 isl_ctx *ctx;
6594 isl_union_set_list *filters;
6596 if (graph->scc == 1)
6597 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6599 ctx = isl_schedule_node_get_ctx(node);
6601 filters = extract_sccs(ctx, graph);
6602 node = isl_schedule_node_insert_sequence(node, filters);
6604 for (i = 0; i < graph->scc; ++i) {
6605 int j = c->scc_cluster[i];
6606 node = isl_schedule_node_child(node, i);
6607 node = isl_schedule_node_child(node, 0);
6608 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6609 node = isl_schedule_node_parent(node);
6610 node = isl_schedule_node_parent(node);
6613 return node;
6616 /* Compute a schedule for a connected dependence graph by first considering
6617 * each strongly connected component (SCC) in the graph separately and then
6618 * incrementally combining them into clusters.
6619 * Return the updated schedule node.
6621 * Initially, each cluster consists of a single SCC, each with its
6622 * own band schedule. The algorithm then tries to merge pairs
6623 * of clusters along a proximity edge until no more suitable
6624 * proximity edges can be found. During this merging, the schedule
6625 * is maintained in the individual SCCs.
6626 * After the merging is completed, the full resulting clusters
6627 * are extracted and in finish_bands_clustering,
6628 * compute_schedule_finish_band is called on each of them to integrate
6629 * the band into "node" and to continue the computation.
6631 * compute_weights initializes the weights that are used by find_proximity.
6633 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6634 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6636 isl_ctx *ctx;
6637 struct isl_clustering c;
6638 int i;
6640 ctx = isl_schedule_node_get_ctx(node);
6642 if (clustering_init(ctx, &c, graph) < 0)
6643 goto error;
6645 if (compute_weights(graph, &c) < 0)
6646 goto error;
6648 for (;;) {
6649 i = find_proximity(graph, &c);
6650 if (i < 0)
6651 goto error;
6652 if (i >= graph->n_edge)
6653 break;
6654 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6655 goto error;
6658 if (extract_clusters(ctx, graph, &c) < 0)
6659 goto error;
6661 node = finish_bands_clustering(node, graph, &c);
6663 clustering_free(ctx, &c);
6664 return node;
6665 error:
6666 clustering_free(ctx, &c);
6667 return isl_schedule_node_free(node);
6670 /* Compute a schedule for a connected dependence graph and return
6671 * the updated schedule node.
6673 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6674 * as many validity dependences as possible. When all validity dependences
6675 * are satisfied we extend the schedule to a full-dimensional schedule.
6677 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6678 * depending on whether the user has selected the option to try and
6679 * compute a schedule for the entire (weakly connected) component first.
6680 * If there is only a single strongly connected component (SCC), then
6681 * there is no point in trying to combine SCCs
6682 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6683 * is called instead.
6685 static __isl_give isl_schedule_node *compute_schedule_wcc(
6686 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6688 isl_ctx *ctx;
6690 if (!node)
6691 return NULL;
6693 ctx = isl_schedule_node_get_ctx(node);
6694 if (detect_sccs(ctx, graph) < 0)
6695 return isl_schedule_node_free(node);
6697 if (compute_maxvar(graph) < 0)
6698 return isl_schedule_node_free(node);
6700 if (need_feautrier_step(ctx, graph))
6701 return compute_schedule_wcc_feautrier(node, graph);
6703 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6704 return compute_schedule_wcc_whole(node, graph);
6705 else
6706 return compute_schedule_wcc_clustering(node, graph);
6709 /* Compute a schedule for each group of nodes identified by node->scc
6710 * separately and then combine them in a sequence node (or as set node
6711 * if graph->weak is set) inserted at position "node" of the schedule tree.
6712 * Return the updated schedule node.
6714 * If "wcc" is set then each of the groups belongs to a single
6715 * weakly connected component in the dependence graph so that
6716 * there is no need for compute_sub_schedule to look for weakly
6717 * connected components.
6719 static __isl_give isl_schedule_node *compute_component_schedule(
6720 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6721 int wcc)
6723 int component;
6724 isl_ctx *ctx;
6725 isl_union_set_list *filters;
6727 if (!node)
6728 return NULL;
6729 ctx = isl_schedule_node_get_ctx(node);
6731 filters = extract_sccs(ctx, graph);
6732 if (graph->weak)
6733 node = isl_schedule_node_insert_set(node, filters);
6734 else
6735 node = isl_schedule_node_insert_sequence(node, filters);
6737 for (component = 0; component < graph->scc; ++component) {
6738 node = isl_schedule_node_child(node, component);
6739 node = isl_schedule_node_child(node, 0);
6740 node = compute_sub_schedule(node, ctx, graph,
6741 &node_scc_exactly,
6742 &edge_scc_exactly, component, wcc);
6743 node = isl_schedule_node_parent(node);
6744 node = isl_schedule_node_parent(node);
6747 return node;
6750 /* Compute a schedule for the given dependence graph and insert it at "node".
6751 * Return the updated schedule node.
6753 * We first check if the graph is connected (through validity and conditional
6754 * validity dependences) and, if not, compute a schedule
6755 * for each component separately.
6756 * If the schedule_serialize_sccs option is set, then we check for strongly
6757 * connected components instead and compute a separate schedule for
6758 * each such strongly connected component.
6760 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6761 struct isl_sched_graph *graph)
6763 isl_ctx *ctx;
6765 if (!node)
6766 return NULL;
6768 ctx = isl_schedule_node_get_ctx(node);
6769 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6770 if (detect_sccs(ctx, graph) < 0)
6771 return isl_schedule_node_free(node);
6772 } else {
6773 if (detect_wccs(ctx, graph) < 0)
6774 return isl_schedule_node_free(node);
6777 if (graph->scc > 1)
6778 return compute_component_schedule(node, graph, 1);
6780 return compute_schedule_wcc(node, graph);
6783 /* Compute a schedule on sc->domain that respects the given schedule
6784 * constraints.
6786 * In particular, the schedule respects all the validity dependences.
6787 * If the default isl scheduling algorithm is used, it tries to minimize
6788 * the dependence distances over the proximity dependences.
6789 * If Feautrier's scheduling algorithm is used, the proximity dependence
6790 * distances are only minimized during the extension to a full-dimensional
6791 * schedule.
6793 * If there are any condition and conditional validity dependences,
6794 * then the conditional validity dependences may be violated inside
6795 * a tilable band, provided they have no adjacent non-local
6796 * condition dependences.
6798 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6799 __isl_take isl_schedule_constraints *sc)
6801 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6802 struct isl_sched_graph graph = { 0 };
6803 isl_schedule *sched;
6804 isl_schedule_node *node;
6805 isl_union_set *domain;
6807 sc = isl_schedule_constraints_align_params(sc);
6809 domain = isl_schedule_constraints_get_domain(sc);
6810 if (isl_union_set_n_set(domain) == 0) {
6811 isl_schedule_constraints_free(sc);
6812 return isl_schedule_from_domain(domain);
6815 if (graph_init(&graph, sc) < 0)
6816 domain = isl_union_set_free(domain);
6818 node = isl_schedule_node_from_domain(domain);
6819 node = isl_schedule_node_child(node, 0);
6820 if (graph.n > 0)
6821 node = compute_schedule(node, &graph);
6822 sched = isl_schedule_node_get_schedule(node);
6823 isl_schedule_node_free(node);
6825 graph_free(ctx, &graph);
6826 isl_schedule_constraints_free(sc);
6828 return sched;
6831 /* Compute a schedule for the given union of domains that respects
6832 * all the validity dependences and minimizes
6833 * the dependence distances over the proximity dependences.
6835 * This function is kept for backward compatibility.
6837 __isl_give isl_schedule *isl_union_set_compute_schedule(
6838 __isl_take isl_union_set *domain,
6839 __isl_take isl_union_map *validity,
6840 __isl_take isl_union_map *proximity)
6842 isl_schedule_constraints *sc;
6844 sc = isl_schedule_constraints_on_domain(domain);
6845 sc = isl_schedule_constraints_set_validity(sc, validity);
6846 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6848 return isl_schedule_constraints_compute_schedule(sc);