isl_scheduler.c: extract out shared node_var_coef_pos
[isl.git] / isl_scheduler.c
blob3f5116b24f5b522f6a2ea8dd7b44133e98e9b4dd
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 * cinv is the inverse of cmap.
65 * ctrans is the transpose of cmap.
66 * start is the first variable in the LP problem in the sequences that
67 * represents the schedule coefficients of this node
68 * nvar is the dimension of the domain
69 * nparam is the number of parameters or 0 if we are not constructing
70 * a parametric schedule
72 * If compressed is set, then hull represents the constraints
73 * that were used to derive the compression, while compress and
74 * decompress map the original space to the compressed space and
75 * vice versa.
77 * scc is the index of SCC (or WCC) this node belongs to
79 * "cluster" is only used inside extract_clusters and identifies
80 * the cluster of SCCs that the node belongs to.
82 * coincident contains a boolean for each of the rows of the schedule,
83 * indicating whether the corresponding scheduling dimension satisfies
84 * the coincidence constraints in the sense that the corresponding
85 * dependence distances are zero.
87 * If the schedule_treat_coalescing option is set, then
88 * "sizes" contains the sizes of the (compressed) instance set
89 * in each direction. If there is no fixed size in a given direction,
90 * then the corresponding size value is set to infinity.
91 * If the schedule_treat_coalescing option or the schedule_max_coefficient
92 * option is set, then "max" contains the maximal values for
93 * schedule coefficients of the (compressed) variables. If no bound
94 * needs to be imposed on a particular variable, then the corresponding
95 * value is negative.
97 struct isl_sched_node {
98 isl_space *space;
99 int compressed;
100 isl_set *hull;
101 isl_multi_aff *compress;
102 isl_multi_aff *decompress;
103 isl_mat *sched;
104 isl_map *sched_map;
105 int rank;
106 isl_mat *cmap;
107 isl_mat *cinv;
108 isl_mat *ctrans;
109 int start;
110 int nvar;
111 int nparam;
113 int scc;
114 int cluster;
116 int *coincident;
118 isl_multi_val *sizes;
119 isl_vec *max;
122 static int node_has_tuples(const void *entry, const void *val)
124 struct isl_sched_node *node = (struct isl_sched_node *)entry;
125 isl_space *space = (isl_space *) val;
127 return isl_space_has_equal_tuples(node->space, space);
130 static int node_scc_exactly(struct isl_sched_node *node, int scc)
132 return node->scc == scc;
135 static int node_scc_at_most(struct isl_sched_node *node, int scc)
137 return node->scc <= scc;
140 static int node_scc_at_least(struct isl_sched_node *node, int scc)
142 return node->scc >= scc;
145 /* An edge in the dependence graph. An edge may be used to
146 * ensure validity of the generated schedule, to minimize the dependence
147 * distance or both
149 * map is the dependence relation, with i -> j in the map if j depends on i
150 * tagged_condition and tagged_validity contain the union of all tagged
151 * condition or conditional validity dependence relations that
152 * specialize the dependence relation "map"; that is,
153 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
154 * or "tagged_validity", then i -> j is an element of "map".
155 * If these fields are NULL, then they represent the empty relation.
156 * src is the source node
157 * dst is the sink node
159 * types is a bit vector containing the types of this edge.
160 * validity is set if the edge is used to ensure correctness
161 * coincidence is used to enforce zero dependence distances
162 * proximity is set if the edge is used to minimize dependence distances
163 * condition is set if the edge represents a condition
164 * for a conditional validity schedule constraint
165 * local can only be set for condition edges and indicates that
166 * the dependence distance over the edge should be zero
167 * conditional_validity is set if the edge is used to conditionally
168 * ensure correctness
170 * For validity edges, start and end mark the sequence of inequality
171 * constraints in the LP problem that encode the validity constraint
172 * corresponding to this edge.
174 * During clustering, an edge may be marked "no_merge" if it should
175 * not be used to merge clusters.
176 * The weight is also only used during clustering and it is
177 * an indication of how many schedule dimensions on either side
178 * of the schedule constraints can be aligned.
179 * If the weight is negative, then this means that this edge was postponed
180 * by has_bounded_distances or any_no_merge. The original weight can
181 * be retrieved by adding 1 + graph->max_weight, with "graph"
182 * the graph containing this edge.
184 struct isl_sched_edge {
185 isl_map *map;
186 isl_union_map *tagged_condition;
187 isl_union_map *tagged_validity;
189 struct isl_sched_node *src;
190 struct isl_sched_node *dst;
192 unsigned types;
194 int start;
195 int end;
197 int no_merge;
198 int weight;
201 /* Is "edge" marked as being of type "type"?
203 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
205 return ISL_FL_ISSET(edge->types, 1 << type);
208 /* Mark "edge" as being of type "type".
210 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
212 ISL_FL_SET(edge->types, 1 << type);
215 /* No longer mark "edge" as being of type "type"?
217 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
219 ISL_FL_CLR(edge->types, 1 << type);
222 /* Is "edge" marked as a validity edge?
224 static int is_validity(struct isl_sched_edge *edge)
226 return is_type(edge, isl_edge_validity);
229 /* Mark "edge" as a validity edge.
231 static void set_validity(struct isl_sched_edge *edge)
233 set_type(edge, isl_edge_validity);
236 /* Is "edge" marked as a proximity edge?
238 static int is_proximity(struct isl_sched_edge *edge)
240 return is_type(edge, isl_edge_proximity);
243 /* Is "edge" marked as a local edge?
245 static int is_local(struct isl_sched_edge *edge)
247 return is_type(edge, isl_edge_local);
250 /* Mark "edge" as a local edge.
252 static void set_local(struct isl_sched_edge *edge)
254 set_type(edge, isl_edge_local);
257 /* No longer mark "edge" as a local edge.
259 static void clear_local(struct isl_sched_edge *edge)
261 clear_type(edge, isl_edge_local);
264 /* Is "edge" marked as a coincidence edge?
266 static int is_coincidence(struct isl_sched_edge *edge)
268 return is_type(edge, isl_edge_coincidence);
271 /* Is "edge" marked as a condition edge?
273 static int is_condition(struct isl_sched_edge *edge)
275 return is_type(edge, isl_edge_condition);
278 /* Is "edge" marked as a conditional validity edge?
280 static int is_conditional_validity(struct isl_sched_edge *edge)
282 return is_type(edge, isl_edge_conditional_validity);
285 /* Internal information about the dependence graph used during
286 * the construction of the schedule.
288 * intra_hmap is a cache, mapping dependence relations to their dual,
289 * for dependences from a node to itself
290 * inter_hmap is a cache, mapping dependence relations to their dual,
291 * for dependences between distinct nodes
292 * if compression is involved then the key for these maps
293 * is the original, uncompressed dependence relation, while
294 * the value is the dual of the compressed dependence relation.
296 * n is the number of nodes
297 * node is the list of nodes
298 * maxvar is the maximal number of variables over all nodes
299 * max_row is the allocated number of rows in the schedule
300 * n_row is the current (maximal) number of linearly independent
301 * rows in the node schedules
302 * n_total_row is the current number of rows in the node schedules
303 * band_start is the starting row in the node schedules of the current band
304 * root is set if this graph is the original dependence graph,
305 * without any splitting
307 * sorted contains a list of node indices sorted according to the
308 * SCC to which a node belongs
310 * n_edge is the number of edges
311 * edge is the list of edges
312 * max_edge contains the maximal number of edges of each type;
313 * in particular, it contains the number of edges in the inital graph.
314 * edge_table contains pointers into the edge array, hashed on the source
315 * and sink spaces; there is one such table for each type;
316 * a given edge may be referenced from more than one table
317 * if the corresponding relation appears in more than one of the
318 * sets of dependences; however, for each type there is only
319 * a single edge between a given pair of source and sink space
320 * in the entire graph
322 * node_table contains pointers into the node array, hashed on the space tuples
324 * region contains a list of variable sequences that should be non-trivial
326 * lp contains the (I)LP problem used to obtain new schedule rows
328 * src_scc and dst_scc are the source and sink SCCs of an edge with
329 * conflicting constraints
331 * scc represents the number of components
332 * weak is set if the components are weakly connected
334 * max_weight is used during clustering and represents the maximal
335 * weight of the relevant proximity edges.
337 struct isl_sched_graph {
338 isl_map_to_basic_set *intra_hmap;
339 isl_map_to_basic_set *inter_hmap;
341 struct isl_sched_node *node;
342 int n;
343 int maxvar;
344 int max_row;
345 int n_row;
347 int *sorted;
349 int n_total_row;
350 int band_start;
352 int root;
354 struct isl_sched_edge *edge;
355 int n_edge;
356 int max_edge[isl_edge_last + 1];
357 struct isl_hash_table *edge_table[isl_edge_last + 1];
359 struct isl_hash_table *node_table;
360 struct isl_trivial_region *region;
362 isl_basic_set *lp;
364 int src_scc;
365 int dst_scc;
367 int scc;
368 int weak;
370 int max_weight;
373 /* Initialize node_table based on the list of nodes.
375 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
377 int i;
379 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
380 if (!graph->node_table)
381 return -1;
383 for (i = 0; i < graph->n; ++i) {
384 struct isl_hash_table_entry *entry;
385 uint32_t hash;
387 hash = isl_space_get_tuple_hash(graph->node[i].space);
388 entry = isl_hash_table_find(ctx, graph->node_table, hash,
389 &node_has_tuples,
390 graph->node[i].space, 1);
391 if (!entry)
392 return -1;
393 entry->data = &graph->node[i];
396 return 0;
399 /* Return a pointer to the node that lives within the given space,
400 * or NULL if there is no such node.
402 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
403 struct isl_sched_graph *graph, __isl_keep isl_space *space)
405 struct isl_hash_table_entry *entry;
406 uint32_t hash;
408 hash = isl_space_get_tuple_hash(space);
409 entry = isl_hash_table_find(ctx, graph->node_table, hash,
410 &node_has_tuples, space, 0);
412 return entry ? entry->data : NULL;
415 static int edge_has_src_and_dst(const void *entry, const void *val)
417 const struct isl_sched_edge *edge = entry;
418 const struct isl_sched_edge *temp = val;
420 return edge->src == temp->src && edge->dst == temp->dst;
423 /* Add the given edge to graph->edge_table[type].
425 static isl_stat graph_edge_table_add(isl_ctx *ctx,
426 struct isl_sched_graph *graph, enum isl_edge_type type,
427 struct isl_sched_edge *edge)
429 struct isl_hash_table_entry *entry;
430 uint32_t hash;
432 hash = isl_hash_init();
433 hash = isl_hash_builtin(hash, edge->src);
434 hash = isl_hash_builtin(hash, edge->dst);
435 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
436 &edge_has_src_and_dst, edge, 1);
437 if (!entry)
438 return isl_stat_error;
439 entry->data = edge;
441 return isl_stat_ok;
444 /* Allocate the edge_tables based on the maximal number of edges of
445 * each type.
447 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
449 int i;
451 for (i = 0; i <= isl_edge_last; ++i) {
452 graph->edge_table[i] = isl_hash_table_alloc(ctx,
453 graph->max_edge[i]);
454 if (!graph->edge_table[i])
455 return -1;
458 return 0;
461 /* If graph->edge_table[type] contains an edge from the given source
462 * to the given destination, then return the hash table entry of this edge.
463 * Otherwise, return NULL.
465 static struct isl_hash_table_entry *graph_find_edge_entry(
466 struct isl_sched_graph *graph,
467 enum isl_edge_type type,
468 struct isl_sched_node *src, struct isl_sched_node *dst)
470 isl_ctx *ctx = isl_space_get_ctx(src->space);
471 uint32_t hash;
472 struct isl_sched_edge temp = { .src = src, .dst = dst };
474 hash = isl_hash_init();
475 hash = isl_hash_builtin(hash, temp.src);
476 hash = isl_hash_builtin(hash, temp.dst);
477 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
478 &edge_has_src_and_dst, &temp, 0);
482 /* If graph->edge_table[type] contains an edge from the given source
483 * to the given destination, then return this edge.
484 * Otherwise, return NULL.
486 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
487 enum isl_edge_type type,
488 struct isl_sched_node *src, struct isl_sched_node *dst)
490 struct isl_hash_table_entry *entry;
492 entry = graph_find_edge_entry(graph, type, src, dst);
493 if (!entry)
494 return NULL;
496 return entry->data;
499 /* Check whether the dependence graph has an edge of the given type
500 * between the given two nodes.
502 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
503 enum isl_edge_type type,
504 struct isl_sched_node *src, struct isl_sched_node *dst)
506 struct isl_sched_edge *edge;
507 isl_bool empty;
509 edge = graph_find_edge(graph, type, src, dst);
510 if (!edge)
511 return 0;
513 empty = isl_map_plain_is_empty(edge->map);
514 if (empty < 0)
515 return isl_bool_error;
517 return !empty;
520 /* Look for any edge with the same src, dst and map fields as "model".
522 * Return the matching edge if one can be found.
523 * Return "model" if no matching edge is found.
524 * Return NULL on error.
526 static struct isl_sched_edge *graph_find_matching_edge(
527 struct isl_sched_graph *graph, struct isl_sched_edge *model)
529 enum isl_edge_type i;
530 struct isl_sched_edge *edge;
532 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
533 int is_equal;
535 edge = graph_find_edge(graph, i, model->src, model->dst);
536 if (!edge)
537 continue;
538 is_equal = isl_map_plain_is_equal(model->map, edge->map);
539 if (is_equal < 0)
540 return NULL;
541 if (is_equal)
542 return edge;
545 return model;
548 /* Remove the given edge from all the edge_tables that refer to it.
550 static void graph_remove_edge(struct isl_sched_graph *graph,
551 struct isl_sched_edge *edge)
553 isl_ctx *ctx = isl_map_get_ctx(edge->map);
554 enum isl_edge_type i;
556 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
557 struct isl_hash_table_entry *entry;
559 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
560 if (!entry)
561 continue;
562 if (entry->data != edge)
563 continue;
564 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
568 /* Check whether the dependence graph has any edge
569 * between the given two nodes.
571 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
572 struct isl_sched_node *src, struct isl_sched_node *dst)
574 enum isl_edge_type i;
575 isl_bool r;
577 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
578 r = graph_has_edge(graph, i, src, dst);
579 if (r < 0 || r)
580 return r;
583 return r;
586 /* Check whether the dependence graph has a validity edge
587 * between the given two nodes.
589 * Conditional validity edges are essentially validity edges that
590 * can be ignored if the corresponding condition edges are iteration private.
591 * Here, we are only checking for the presence of validity
592 * edges, so we need to consider the conditional validity edges too.
593 * In particular, this function is used during the detection
594 * of strongly connected components and we cannot ignore
595 * conditional validity edges during this detection.
597 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
598 struct isl_sched_node *src, struct isl_sched_node *dst)
600 isl_bool r;
602 r = graph_has_edge(graph, isl_edge_validity, src, dst);
603 if (r < 0 || r)
604 return r;
606 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
609 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
610 int n_node, int n_edge)
612 int i;
614 graph->n = n_node;
615 graph->n_edge = n_edge;
616 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
617 graph->sorted = isl_calloc_array(ctx, int, graph->n);
618 graph->region = isl_alloc_array(ctx,
619 struct isl_trivial_region, graph->n);
620 graph->edge = isl_calloc_array(ctx,
621 struct isl_sched_edge, graph->n_edge);
623 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
624 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
626 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
627 !graph->sorted)
628 return -1;
630 for(i = 0; i < graph->n; ++i)
631 graph->sorted[i] = i;
633 return 0;
636 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
638 int i;
640 isl_map_to_basic_set_free(graph->intra_hmap);
641 isl_map_to_basic_set_free(graph->inter_hmap);
643 if (graph->node)
644 for (i = 0; i < graph->n; ++i) {
645 isl_space_free(graph->node[i].space);
646 isl_set_free(graph->node[i].hull);
647 isl_multi_aff_free(graph->node[i].compress);
648 isl_multi_aff_free(graph->node[i].decompress);
649 isl_mat_free(graph->node[i].sched);
650 isl_map_free(graph->node[i].sched_map);
651 isl_mat_free(graph->node[i].cmap);
652 isl_mat_free(graph->node[i].cinv);
653 isl_mat_free(graph->node[i].ctrans);
654 if (graph->root)
655 free(graph->node[i].coincident);
656 isl_multi_val_free(graph->node[i].sizes);
657 isl_vec_free(graph->node[i].max);
659 free(graph->node);
660 free(graph->sorted);
661 if (graph->edge)
662 for (i = 0; i < graph->n_edge; ++i) {
663 isl_map_free(graph->edge[i].map);
664 isl_union_map_free(graph->edge[i].tagged_condition);
665 isl_union_map_free(graph->edge[i].tagged_validity);
667 free(graph->edge);
668 free(graph->region);
669 for (i = 0; i <= isl_edge_last; ++i)
670 isl_hash_table_free(ctx, graph->edge_table[i]);
671 isl_hash_table_free(ctx, graph->node_table);
672 isl_basic_set_free(graph->lp);
675 /* For each "set" on which this function is called, increment
676 * graph->n by one and update graph->maxvar.
678 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
680 struct isl_sched_graph *graph = user;
681 int nvar = isl_set_dim(set, isl_dim_set);
683 graph->n++;
684 if (nvar > graph->maxvar)
685 graph->maxvar = nvar;
687 isl_set_free(set);
689 return isl_stat_ok;
692 /* Compute the number of rows that should be allocated for the schedule.
693 * In particular, we need one row for each variable or one row
694 * for each basic map in the dependences.
695 * Note that it is practically impossible to exhaust both
696 * the number of dependences and the number of variables.
698 static isl_stat compute_max_row(struct isl_sched_graph *graph,
699 __isl_keep isl_schedule_constraints *sc)
701 int n_edge;
702 isl_stat r;
703 isl_union_set *domain;
705 graph->n = 0;
706 graph->maxvar = 0;
707 domain = isl_schedule_constraints_get_domain(sc);
708 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
709 isl_union_set_free(domain);
710 if (r < 0)
711 return isl_stat_error;
712 n_edge = isl_schedule_constraints_n_basic_map(sc);
713 if (n_edge < 0)
714 return isl_stat_error;
715 graph->max_row = n_edge + graph->maxvar;
717 return isl_stat_ok;
720 /* Does "bset" have any defining equalities for its set variables?
722 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
724 int i, n;
726 if (!bset)
727 return isl_bool_error;
729 n = isl_basic_set_dim(bset, isl_dim_set);
730 for (i = 0; i < n; ++i) {
731 isl_bool has;
733 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
734 NULL);
735 if (has < 0 || has)
736 return has;
739 return isl_bool_false;
742 /* Set the entries of node->max to the value of the schedule_max_coefficient
743 * option, if set.
745 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
747 int max;
749 max = isl_options_get_schedule_max_coefficient(ctx);
750 if (max == -1)
751 return isl_stat_ok;
753 node->max = isl_vec_alloc(ctx, node->nvar);
754 node->max = isl_vec_set_si(node->max, max);
755 if (!node->max)
756 return isl_stat_error;
758 return isl_stat_ok;
761 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
762 * option (if set) and half of the minimum of the sizes in the other
763 * dimensions. If the minimum of the sizes is one, half of the size
764 * is zero and this value is reset to one.
765 * If the global minimum is unbounded (i.e., if both
766 * the schedule_max_coefficient is not set and the sizes in the other
767 * dimensions are unbounded), then store a negative value.
768 * If the schedule coefficient is close to the size of the instance set
769 * in another dimension, then the schedule may represent a loop
770 * coalescing transformation (especially if the coefficient
771 * in that other dimension is one). Forcing the coefficient to be
772 * smaller than or equal to half the minimal size should avoid this
773 * situation.
775 static isl_stat compute_max_coefficient(isl_ctx *ctx,
776 struct isl_sched_node *node)
778 int max;
779 int i, j;
780 isl_vec *v;
782 max = isl_options_get_schedule_max_coefficient(ctx);
783 v = isl_vec_alloc(ctx, node->nvar);
784 if (!v)
785 return isl_stat_error;
787 for (i = 0; i < node->nvar; ++i) {
788 isl_int_set_si(v->el[i], max);
789 isl_int_mul_si(v->el[i], v->el[i], 2);
792 for (i = 0; i < node->nvar; ++i) {
793 isl_val *size;
795 size = isl_multi_val_get_val(node->sizes, i);
796 if (!size)
797 goto error;
798 if (!isl_val_is_int(size)) {
799 isl_val_free(size);
800 continue;
802 for (j = 0; j < node->nvar; ++j) {
803 if (j == i)
804 continue;
805 if (isl_int_is_neg(v->el[j]) ||
806 isl_int_gt(v->el[j], size->n))
807 isl_int_set(v->el[j], size->n);
809 isl_val_free(size);
812 for (i = 0; i < node->nvar; ++i) {
813 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
814 if (isl_int_is_zero(v->el[i]))
815 isl_int_set_si(v->el[i], 1);
818 node->max = v;
819 return isl_stat_ok;
820 error:
821 isl_vec_free(v);
822 return isl_stat_error;
825 /* Compute and return the size of "set" in dimension "dim".
826 * The size is taken to be the difference in values for that variable
827 * for fixed values of the other variables.
828 * In particular, the variable is first isolated from the other variables
829 * in the range of a map
831 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
833 * and then duplicated
835 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
837 * The shared variables are then projected out and the maximal value
838 * of i_dim' - i_dim is computed.
840 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
842 isl_map *map;
843 isl_local_space *ls;
844 isl_aff *obj;
845 isl_val *v;
847 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
848 map = isl_map_project_out(map, isl_dim_in, dim, 1);
849 map = isl_map_range_product(map, isl_map_copy(map));
850 map = isl_set_unwrap(isl_map_range(map));
851 set = isl_map_deltas(map);
852 ls = isl_local_space_from_space(isl_set_get_space(set));
853 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
854 v = isl_set_max_val(set, obj);
855 isl_aff_free(obj);
856 isl_set_free(set);
858 return v;
861 /* Compute the size of the instance set "set" of "node", after compression,
862 * as well as bounds on the corresponding coefficients, if needed.
864 * The sizes are needed when the schedule_treat_coalescing option is set.
865 * The bounds are needed when the schedule_treat_coalescing option or
866 * the schedule_max_coefficient option is set.
868 * If the schedule_treat_coalescing option is not set, then at most
869 * the bounds need to be set and this is done in set_max_coefficient.
870 * Otherwise, compress the domain if needed, compute the size
871 * in each direction and store the results in node->size.
872 * Finally, set the bounds on the coefficients based on the sizes
873 * and the schedule_max_coefficient option in compute_max_coefficient.
875 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
876 __isl_take isl_set *set)
878 int j, n;
879 isl_multi_val *mv;
881 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
882 isl_set_free(set);
883 return set_max_coefficient(ctx, node);
886 if (node->compressed)
887 set = isl_set_preimage_multi_aff(set,
888 isl_multi_aff_copy(node->decompress));
889 mv = isl_multi_val_zero(isl_set_get_space(set));
890 n = isl_set_dim(set, isl_dim_set);
891 for (j = 0; j < n; ++j) {
892 isl_val *v;
894 v = compute_size(isl_set_copy(set), j);
895 mv = isl_multi_val_set_val(mv, j, v);
897 node->sizes = mv;
898 isl_set_free(set);
899 if (!node->sizes)
900 return isl_stat_error;
901 return compute_max_coefficient(ctx, node);
904 /* Add a new node to the graph representing the given instance set.
905 * "nvar" is the (possibly compressed) number of variables and
906 * may be smaller than then number of set variables in "set"
907 * if "compressed" is set.
908 * If "compressed" is set, then "hull" represents the constraints
909 * that were used to derive the compression, while "compress" and
910 * "decompress" map the original space to the compressed space and
911 * vice versa.
912 * If "compressed" is not set, then "hull", "compress" and "decompress"
913 * should be NULL.
915 * Compute the size of the instance set and bounds on the coefficients,
916 * if needed.
918 static isl_stat add_node(struct isl_sched_graph *graph,
919 __isl_take isl_set *set, int nvar, int compressed,
920 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
921 __isl_take isl_multi_aff *decompress)
923 int nparam;
924 isl_ctx *ctx;
925 isl_mat *sched;
926 isl_space *space;
927 int *coincident;
928 struct isl_sched_node *node;
930 if (!set)
931 return isl_stat_error;
933 ctx = isl_set_get_ctx(set);
934 nparam = isl_set_dim(set, isl_dim_param);
935 if (!ctx->opt->schedule_parametric)
936 nparam = 0;
937 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
938 node = &graph->node[graph->n];
939 graph->n++;
940 space = isl_set_get_space(set);
941 node->space = space;
942 node->nvar = nvar;
943 node->nparam = nparam;
944 node->sched = sched;
945 node->sched_map = NULL;
946 coincident = isl_calloc_array(ctx, int, graph->max_row);
947 node->coincident = coincident;
948 node->compressed = compressed;
949 node->hull = hull;
950 node->compress = compress;
951 node->decompress = decompress;
952 if (compute_sizes_and_max(ctx, node, set) < 0)
953 return isl_stat_error;
955 if (!space || !sched || (graph->max_row && !coincident))
956 return isl_stat_error;
957 if (compressed && (!hull || !compress || !decompress))
958 return isl_stat_error;
960 return isl_stat_ok;
963 /* Construct an identifier for node "node", which will represent "set".
964 * The name of the identifier is either "compressed" or
965 * "compressed_<name>", with <name> the name of the space of "set".
966 * The user pointer of the identifier points to "node".
968 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
969 struct isl_sched_node *node)
971 isl_bool has_name;
972 isl_ctx *ctx;
973 isl_id *id;
974 isl_printer *p;
975 const char *name;
976 char *id_name;
978 has_name = isl_set_has_tuple_name(set);
979 if (has_name < 0)
980 return NULL;
982 ctx = isl_set_get_ctx(set);
983 if (!has_name)
984 return isl_id_alloc(ctx, "compressed", node);
986 p = isl_printer_to_str(ctx);
987 name = isl_set_get_tuple_name(set);
988 p = isl_printer_print_str(p, "compressed_");
989 p = isl_printer_print_str(p, name);
990 id_name = isl_printer_get_str(p);
991 isl_printer_free(p);
993 id = isl_id_alloc(ctx, id_name, node);
994 free(id_name);
996 return id;
999 /* Add a new node to the graph representing the given set.
1001 * If any of the set variables is defined by an equality, then
1002 * we perform variable compression such that we can perform
1003 * the scheduling on the compressed domain.
1004 * In this case, an identifier is used that references the new node
1005 * such that each compressed space is unique and
1006 * such that the node can be recovered from the compressed space.
1008 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1010 int nvar;
1011 isl_bool has_equality;
1012 isl_id *id;
1013 isl_basic_set *hull;
1014 isl_set *hull_set;
1015 isl_morph *morph;
1016 isl_multi_aff *compress, *decompress;
1017 struct isl_sched_graph *graph = user;
1019 hull = isl_set_affine_hull(isl_set_copy(set));
1020 hull = isl_basic_set_remove_divs(hull);
1021 nvar = isl_set_dim(set, isl_dim_set);
1022 has_equality = has_any_defining_equality(hull);
1024 if (has_equality < 0)
1025 goto error;
1026 if (!has_equality) {
1027 isl_basic_set_free(hull);
1028 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1031 id = construct_compressed_id(set, &graph->node[graph->n]);
1032 morph = isl_basic_set_variable_compression_with_id(hull,
1033 isl_dim_set, id);
1034 isl_id_free(id);
1035 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1036 compress = isl_morph_get_var_multi_aff(morph);
1037 morph = isl_morph_inverse(morph);
1038 decompress = isl_morph_get_var_multi_aff(morph);
1039 isl_morph_free(morph);
1041 hull_set = isl_set_from_basic_set(hull);
1042 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1043 error:
1044 isl_basic_set_free(hull);
1045 isl_set_free(set);
1046 return isl_stat_error;
1049 struct isl_extract_edge_data {
1050 enum isl_edge_type type;
1051 struct isl_sched_graph *graph;
1054 /* Merge edge2 into edge1, freeing the contents of edge2.
1055 * Return 0 on success and -1 on failure.
1057 * edge1 and edge2 are assumed to have the same value for the map field.
1059 static int merge_edge(struct isl_sched_edge *edge1,
1060 struct isl_sched_edge *edge2)
1062 edge1->types |= edge2->types;
1063 isl_map_free(edge2->map);
1065 if (is_condition(edge2)) {
1066 if (!edge1->tagged_condition)
1067 edge1->tagged_condition = edge2->tagged_condition;
1068 else
1069 edge1->tagged_condition =
1070 isl_union_map_union(edge1->tagged_condition,
1071 edge2->tagged_condition);
1074 if (is_conditional_validity(edge2)) {
1075 if (!edge1->tagged_validity)
1076 edge1->tagged_validity = edge2->tagged_validity;
1077 else
1078 edge1->tagged_validity =
1079 isl_union_map_union(edge1->tagged_validity,
1080 edge2->tagged_validity);
1083 if (is_condition(edge2) && !edge1->tagged_condition)
1084 return -1;
1085 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1086 return -1;
1088 return 0;
1091 /* Insert dummy tags in domain and range of "map".
1093 * In particular, if "map" is of the form
1095 * A -> B
1097 * then return
1099 * [A -> dummy_tag] -> [B -> dummy_tag]
1101 * where the dummy_tags are identical and equal to any dummy tags
1102 * introduced by any other call to this function.
1104 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1106 static char dummy;
1107 isl_ctx *ctx;
1108 isl_id *id;
1109 isl_space *space;
1110 isl_set *domain, *range;
1112 ctx = isl_map_get_ctx(map);
1114 id = isl_id_alloc(ctx, NULL, &dummy);
1115 space = isl_space_params(isl_map_get_space(map));
1116 space = isl_space_set_from_params(space);
1117 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1118 space = isl_space_map_from_set(space);
1120 domain = isl_map_wrap(map);
1121 range = isl_map_wrap(isl_map_universe(space));
1122 map = isl_map_from_domain_and_range(domain, range);
1123 map = isl_map_zip(map);
1125 return map;
1128 /* Given that at least one of "src" or "dst" is compressed, return
1129 * a map between the spaces of these nodes restricted to the affine
1130 * hull that was used in the compression.
1132 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1133 struct isl_sched_node *dst)
1135 isl_set *dom, *ran;
1137 if (src->compressed)
1138 dom = isl_set_copy(src->hull);
1139 else
1140 dom = isl_set_universe(isl_space_copy(src->space));
1141 if (dst->compressed)
1142 ran = isl_set_copy(dst->hull);
1143 else
1144 ran = isl_set_universe(isl_space_copy(dst->space));
1146 return isl_map_from_domain_and_range(dom, ran);
1149 /* Intersect the domains of the nested relations in domain and range
1150 * of "tagged" with "map".
1152 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1153 __isl_keep isl_map *map)
1155 isl_set *set;
1157 tagged = isl_map_zip(tagged);
1158 set = isl_map_wrap(isl_map_copy(map));
1159 tagged = isl_map_intersect_domain(tagged, set);
1160 tagged = isl_map_zip(tagged);
1161 return tagged;
1164 /* Return a pointer to the node that lives in the domain space of "map"
1165 * or NULL if there is no such node.
1167 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1168 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1170 struct isl_sched_node *node;
1171 isl_space *space;
1173 space = isl_space_domain(isl_map_get_space(map));
1174 node = graph_find_node(ctx, graph, space);
1175 isl_space_free(space);
1177 return node;
1180 /* Return a pointer to the node that lives in the range space of "map"
1181 * or NULL if there is no such node.
1183 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1184 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1186 struct isl_sched_node *node;
1187 isl_space *space;
1189 space = isl_space_range(isl_map_get_space(map));
1190 node = graph_find_node(ctx, graph, space);
1191 isl_space_free(space);
1193 return node;
1196 /* Add a new edge to the graph based on the given map
1197 * and add it to data->graph->edge_table[data->type].
1198 * If a dependence relation of a given type happens to be identical
1199 * to one of the dependence relations of a type that was added before,
1200 * then we don't create a new edge, but instead mark the original edge
1201 * as also representing a dependence of the current type.
1203 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1204 * may be specified as "tagged" dependence relations. That is, "map"
1205 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1206 * the dependence on iterations and a and b are tags.
1207 * edge->map is set to the relation containing the elements i -> j,
1208 * while edge->tagged_condition and edge->tagged_validity contain
1209 * the union of all the "map" relations
1210 * for which extract_edge is called that result in the same edge->map.
1212 * If the source or the destination node is compressed, then
1213 * intersect both "map" and "tagged" with the constraints that
1214 * were used to construct the compression.
1215 * This ensures that there are no schedule constraints defined
1216 * outside of these domains, while the scheduler no longer has
1217 * any control over those outside parts.
1219 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1221 isl_ctx *ctx = isl_map_get_ctx(map);
1222 struct isl_extract_edge_data *data = user;
1223 struct isl_sched_graph *graph = data->graph;
1224 struct isl_sched_node *src, *dst;
1225 struct isl_sched_edge *edge;
1226 isl_map *tagged = NULL;
1228 if (data->type == isl_edge_condition ||
1229 data->type == isl_edge_conditional_validity) {
1230 if (isl_map_can_zip(map)) {
1231 tagged = isl_map_copy(map);
1232 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1233 } else {
1234 tagged = insert_dummy_tags(isl_map_copy(map));
1238 src = find_domain_node(ctx, graph, map);
1239 dst = find_range_node(ctx, graph, map);
1241 if (!src || !dst) {
1242 isl_map_free(map);
1243 isl_map_free(tagged);
1244 return isl_stat_ok;
1247 if (src->compressed || dst->compressed) {
1248 isl_map *hull;
1249 hull = extract_hull(src, dst);
1250 if (tagged)
1251 tagged = map_intersect_domains(tagged, hull);
1252 map = isl_map_intersect(map, hull);
1255 graph->edge[graph->n_edge].src = src;
1256 graph->edge[graph->n_edge].dst = dst;
1257 graph->edge[graph->n_edge].map = map;
1258 graph->edge[graph->n_edge].types = 0;
1259 graph->edge[graph->n_edge].tagged_condition = NULL;
1260 graph->edge[graph->n_edge].tagged_validity = NULL;
1261 set_type(&graph->edge[graph->n_edge], data->type);
1262 if (data->type == isl_edge_condition)
1263 graph->edge[graph->n_edge].tagged_condition =
1264 isl_union_map_from_map(tagged);
1265 if (data->type == isl_edge_conditional_validity)
1266 graph->edge[graph->n_edge].tagged_validity =
1267 isl_union_map_from_map(tagged);
1269 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1270 if (!edge) {
1271 graph->n_edge++;
1272 return isl_stat_error;
1274 if (edge == &graph->edge[graph->n_edge])
1275 return graph_edge_table_add(ctx, graph, data->type,
1276 &graph->edge[graph->n_edge++]);
1278 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1279 return -1;
1281 return graph_edge_table_add(ctx, graph, data->type, edge);
1284 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1286 * The context is included in the domain before the nodes of
1287 * the graphs are extracted in order to be able to exploit
1288 * any possible additional equalities.
1289 * Note that this intersection is only performed locally here.
1291 static isl_stat graph_init(struct isl_sched_graph *graph,
1292 __isl_keep isl_schedule_constraints *sc)
1294 isl_ctx *ctx;
1295 isl_union_set *domain;
1296 isl_union_map *c;
1297 struct isl_extract_edge_data data;
1298 enum isl_edge_type i;
1299 isl_stat r;
1301 if (!sc)
1302 return isl_stat_error;
1304 ctx = isl_schedule_constraints_get_ctx(sc);
1306 domain = isl_schedule_constraints_get_domain(sc);
1307 graph->n = isl_union_set_n_set(domain);
1308 isl_union_set_free(domain);
1310 if (graph_alloc(ctx, graph, graph->n,
1311 isl_schedule_constraints_n_map(sc)) < 0)
1312 return isl_stat_error;
1314 if (compute_max_row(graph, sc) < 0)
1315 return isl_stat_error;
1316 graph->root = 1;
1317 graph->n = 0;
1318 domain = isl_schedule_constraints_get_domain(sc);
1319 domain = isl_union_set_intersect_params(domain,
1320 isl_schedule_constraints_get_context(sc));
1321 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1322 isl_union_set_free(domain);
1323 if (r < 0)
1324 return isl_stat_error;
1325 if (graph_init_table(ctx, graph) < 0)
1326 return isl_stat_error;
1327 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1328 c = isl_schedule_constraints_get(sc, i);
1329 graph->max_edge[i] = isl_union_map_n_map(c);
1330 isl_union_map_free(c);
1331 if (!c)
1332 return isl_stat_error;
1334 if (graph_init_edge_tables(ctx, graph) < 0)
1335 return isl_stat_error;
1336 graph->n_edge = 0;
1337 data.graph = graph;
1338 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1339 isl_stat r;
1341 data.type = i;
1342 c = isl_schedule_constraints_get(sc, i);
1343 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1344 isl_union_map_free(c);
1345 if (r < 0)
1346 return isl_stat_error;
1349 return isl_stat_ok;
1352 /* Check whether there is any dependence from node[j] to node[i]
1353 * or from node[i] to node[j].
1355 static isl_bool node_follows_weak(int i, int j, void *user)
1357 isl_bool f;
1358 struct isl_sched_graph *graph = user;
1360 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1361 if (f < 0 || f)
1362 return f;
1363 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1366 /* Check whether there is a (conditional) validity dependence from node[j]
1367 * to node[i], forcing node[i] to follow node[j].
1369 static isl_bool node_follows_strong(int i, int j, void *user)
1371 struct isl_sched_graph *graph = user;
1373 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1376 /* Use Tarjan's algorithm for computing the strongly connected components
1377 * in the dependence graph only considering those edges defined by "follows".
1379 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1380 isl_bool (*follows)(int i, int j, void *user))
1382 int i, n;
1383 struct isl_tarjan_graph *g = NULL;
1385 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1386 if (!g)
1387 return -1;
1389 graph->scc = 0;
1390 i = 0;
1391 n = graph->n;
1392 while (n) {
1393 while (g->order[i] != -1) {
1394 graph->node[g->order[i]].scc = graph->scc;
1395 --n;
1396 ++i;
1398 ++i;
1399 graph->scc++;
1402 isl_tarjan_graph_free(g);
1404 return 0;
1407 /* Apply Tarjan's algorithm to detect the strongly connected components
1408 * in the dependence graph.
1409 * Only consider the (conditional) validity dependences and clear "weak".
1411 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1413 graph->weak = 0;
1414 return detect_ccs(ctx, graph, &node_follows_strong);
1417 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1418 * in the dependence graph.
1419 * Consider all dependences and set "weak".
1421 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1423 graph->weak = 1;
1424 return detect_ccs(ctx, graph, &node_follows_weak);
1427 static int cmp_scc(const void *a, const void *b, void *data)
1429 struct isl_sched_graph *graph = data;
1430 const int *i1 = a;
1431 const int *i2 = b;
1433 return graph->node[*i1].scc - graph->node[*i2].scc;
1436 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1438 static int sort_sccs(struct isl_sched_graph *graph)
1440 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1443 /* Given a dependence relation R from "node" to itself,
1444 * construct the set of coefficients of valid constraints for elements
1445 * in that dependence relation.
1446 * In particular, the result contains tuples of coefficients
1447 * c_0, c_n, c_x such that
1449 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1451 * or, equivalently,
1453 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1455 * We choose here to compute the dual of delta R.
1456 * Alternatively, we could have computed the dual of R, resulting
1457 * in a set of tuples c_0, c_n, c_x, c_y, and then
1458 * plugged in (c_0, c_n, c_x, -c_x).
1460 * If "node" has been compressed, then the dependence relation
1461 * is also compressed before the set of coefficients is computed.
1463 static __isl_give isl_basic_set *intra_coefficients(
1464 struct isl_sched_graph *graph, struct isl_sched_node *node,
1465 __isl_take isl_map *map)
1467 isl_set *delta;
1468 isl_map *key;
1469 isl_basic_set *coef;
1470 isl_maybe_isl_basic_set m;
1472 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1473 if (m.valid < 0 || m.valid) {
1474 isl_map_free(map);
1475 return m.value;
1478 key = isl_map_copy(map);
1479 if (node->compressed) {
1480 map = isl_map_preimage_domain_multi_aff(map,
1481 isl_multi_aff_copy(node->decompress));
1482 map = isl_map_preimage_range_multi_aff(map,
1483 isl_multi_aff_copy(node->decompress));
1485 delta = isl_set_remove_divs(isl_map_deltas(map));
1486 coef = isl_set_coefficients(delta);
1487 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1488 isl_basic_set_copy(coef));
1490 return coef;
1493 /* Given a dependence relation R, construct the set of coefficients
1494 * of valid constraints for elements in that dependence relation.
1495 * In particular, the result contains tuples of coefficients
1496 * c_0, c_n, c_x, c_y such that
1498 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1500 * If the source or destination nodes of "edge" have been compressed,
1501 * then the dependence relation is also compressed before
1502 * the set of coefficients is computed.
1504 static __isl_give isl_basic_set *inter_coefficients(
1505 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1506 __isl_take isl_map *map)
1508 isl_set *set;
1509 isl_map *key;
1510 isl_basic_set *coef;
1511 isl_maybe_isl_basic_set m;
1513 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1514 if (m.valid < 0 || m.valid) {
1515 isl_map_free(map);
1516 return m.value;
1519 key = isl_map_copy(map);
1520 if (edge->src->compressed)
1521 map = isl_map_preimage_domain_multi_aff(map,
1522 isl_multi_aff_copy(edge->src->decompress));
1523 if (edge->dst->compressed)
1524 map = isl_map_preimage_range_multi_aff(map,
1525 isl_multi_aff_copy(edge->dst->decompress));
1526 set = isl_map_wrap(isl_map_remove_divs(map));
1527 coef = isl_set_coefficients(set);
1528 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1529 isl_basic_set_copy(coef));
1531 return coef;
1534 /* Return the position of the coefficients of the variables in
1535 * the coefficients constraints "coef".
1537 * The space of "coef" is of the form
1539 * { coefficients[[cst, params] -> S] }
1541 * Return the position of S.
1543 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1545 int offset;
1546 isl_space *space;
1548 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1549 offset = isl_space_dim(space, isl_dim_in);
1550 isl_space_free(space);
1552 return offset;
1555 /* Return the offset of the coefficients of the variables of "node"
1556 * within the (I)LP.
1558 * Within each node, the coefficients have the following order:
1559 * - c_i_0
1560 * - c_i_n (if parametric)
1561 * - positive and negative parts of c_i_x
1563 static int node_var_coef_offset(struct isl_sched_node *node)
1565 return node->start + 1 + node->nparam;
1568 /* Return the position of the pair of variables encoding
1569 * coefficient "i" of "node".
1571 * The order of these variable pairs is the same as that of the coefficients,
1572 * with 2 variables per coefficient.
1574 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1576 return node_var_coef_offset(node) + 2 * i;
1579 /* Construct an isl_dim_map for mapping constraints on coefficients
1580 * for "node" to the corresponding positions in graph->lp.
1581 * "offset" is the offset of the coefficients for the variables
1582 * in the input constraints.
1583 * "s" is the sign of the mapping.
1585 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1586 * The mapping produced by this function essentially plugs in
1587 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1588 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1589 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1591 * The caller can extend the mapping to also map the other coefficients
1592 * (and therefore not plug in 0).
1594 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1595 struct isl_sched_graph *graph, struct isl_sched_node *node,
1596 int offset, int s)
1598 int pos;
1599 unsigned total;
1600 isl_dim_map *dim_map;
1602 if (!node)
1603 return NULL;
1605 total = isl_basic_set_total_dim(graph->lp);
1606 pos = node_var_coef_pos(node, 0);
1607 dim_map = isl_dim_map_alloc(ctx, total);
1608 isl_dim_map_range(dim_map, pos, 2, offset, 1, node->nvar, -s);
1609 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, node->nvar, s);
1611 return dim_map;
1614 /* Construct an isl_dim_map for mapping constraints on coefficients
1615 * for "src" (node i) and "dst" (node j) to the corresponding positions
1616 * in graph->lp.
1617 * "offset" is the offset of the coefficients for the variables of "src"
1618 * in the input constraints.
1619 * "s" is the sign of the mapping.
1621 * The input constraints are given in terms of the coefficients
1622 * (c_0, c_n, c_x, c_y).
1623 * The mapping produced by this function essentially plugs in
1624 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1625 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1626 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1627 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1628 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1630 * The caller can further extend the mapping.
1632 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1633 struct isl_sched_graph *graph, struct isl_sched_node *src,
1634 struct isl_sched_node *dst, int offset, int s)
1636 int pos;
1637 unsigned total;
1638 isl_dim_map *dim_map;
1640 if (!src || !dst)
1641 return NULL;
1643 total = isl_basic_set_total_dim(graph->lp);
1644 dim_map = isl_dim_map_alloc(ctx, total);
1646 isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, s);
1647 isl_dim_map_range(dim_map, dst->start + 1, 1, 1, 1, dst->nparam, s);
1648 pos = node_var_coef_pos(dst, 0);
1649 isl_dim_map_range(dim_map, pos, 2, offset + src->nvar, 1,
1650 dst->nvar, -s);
1651 isl_dim_map_range(dim_map, pos + 1, 2, offset + src->nvar, 1,
1652 dst->nvar, s);
1654 isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -s);
1655 isl_dim_map_range(dim_map, src->start + 1, 1, 1, 1, src->nparam, -s);
1656 pos = node_var_coef_pos(src, 0);
1657 isl_dim_map_range(dim_map, pos, 2, offset, 1, src->nvar, s);
1658 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, src->nvar, -s);
1660 return dim_map;
1663 /* Add the constraints from "src" to "dst" using "dim_map",
1664 * after making sure there is enough room in "dst" for the extra constraints.
1666 static __isl_give isl_basic_set *add_constraints_dim_map(
1667 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1668 __isl_take isl_dim_map *dim_map)
1670 int n_eq, n_ineq;
1672 n_eq = isl_basic_set_n_equality(src);
1673 n_ineq = isl_basic_set_n_inequality(src);
1674 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1675 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1676 return dst;
1679 /* Add constraints to graph->lp that force validity for the given
1680 * dependence from a node i to itself.
1681 * That is, add constraints that enforce
1683 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1684 * = c_i_x (y - x) >= 0
1686 * for each (x,y) in R.
1687 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1688 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1689 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1690 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1692 * Actually, we do not construct constraints for the c_i_x themselves,
1693 * but for the coefficients of c_i_x written as a linear combination
1694 * of the columns in node->cmap.
1696 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1697 struct isl_sched_edge *edge)
1699 int offset;
1700 isl_map *map = isl_map_copy(edge->map);
1701 isl_ctx *ctx = isl_map_get_ctx(map);
1702 isl_dim_map *dim_map;
1703 isl_basic_set *coef;
1704 struct isl_sched_node *node = edge->src;
1706 coef = intra_coefficients(graph, node, map);
1708 offset = coef_var_offset(coef);
1710 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1711 offset, isl_mat_copy(node->cmap));
1712 if (!coef)
1713 return isl_stat_error;
1715 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1716 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1718 return isl_stat_ok;
1721 /* Add constraints to graph->lp that force validity for the given
1722 * dependence from node i to node j.
1723 * That is, add constraints that enforce
1725 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1727 * for each (x,y) in R.
1728 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1729 * of valid constraints for R and then plug in
1730 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1731 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1732 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1734 * Actually, we do not construct constraints for the c_*_x themselves,
1735 * but for the coefficients of c_*_x written as a linear combination
1736 * of the columns in node->cmap.
1738 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1739 struct isl_sched_edge *edge)
1741 int offset;
1742 isl_map *map;
1743 isl_ctx *ctx;
1744 isl_dim_map *dim_map;
1745 isl_basic_set *coef;
1746 struct isl_sched_node *src = edge->src;
1747 struct isl_sched_node *dst = edge->dst;
1749 if (!graph->lp)
1750 return isl_stat_error;
1752 map = isl_map_copy(edge->map);
1753 ctx = isl_map_get_ctx(map);
1754 coef = inter_coefficients(graph, edge, map);
1756 offset = coef_var_offset(coef);
1758 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1759 offset, isl_mat_copy(src->cmap));
1760 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1761 offset + src->nvar, isl_mat_copy(dst->cmap));
1762 if (!coef)
1763 return isl_stat_error;
1765 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1767 edge->start = graph->lp->n_ineq;
1768 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1769 if (!graph->lp)
1770 return isl_stat_error;
1771 edge->end = graph->lp->n_ineq;
1773 return isl_stat_ok;
1776 /* Add constraints to graph->lp that bound the dependence distance for the given
1777 * dependence from a node i to itself.
1778 * If s = 1, we add the constraint
1780 * c_i_x (y - x) <= m_0 + m_n n
1782 * or
1784 * -c_i_x (y - x) + m_0 + m_n n >= 0
1786 * for each (x,y) in R.
1787 * If s = -1, we add the constraint
1789 * -c_i_x (y - x) <= m_0 + m_n n
1791 * or
1793 * c_i_x (y - x) + m_0 + m_n n >= 0
1795 * for each (x,y) in R.
1796 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1797 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1798 * with each coefficient (except m_0) represented as a pair of non-negative
1799 * coefficients.
1801 * Actually, we do not construct constraints for the c_i_x themselves,
1802 * but for the coefficients of c_i_x written as a linear combination
1803 * of the columns in node->cmap.
1806 * If "local" is set, then we add constraints
1808 * c_i_x (y - x) <= 0
1810 * or
1812 * -c_i_x (y - x) <= 0
1814 * instead, forcing the dependence distance to be (less than or) equal to 0.
1815 * That is, we plug in (0, 0, -s * c_i_x),
1816 * Note that dependences marked local are treated as validity constraints
1817 * by add_all_validity_constraints and therefore also have
1818 * their distances bounded by 0 from below.
1820 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1821 struct isl_sched_edge *edge, int s, int local)
1823 int offset;
1824 unsigned nparam;
1825 isl_map *map = isl_map_copy(edge->map);
1826 isl_ctx *ctx = isl_map_get_ctx(map);
1827 isl_dim_map *dim_map;
1828 isl_basic_set *coef;
1829 struct isl_sched_node *node = edge->src;
1831 coef = intra_coefficients(graph, node, map);
1833 offset = coef_var_offset(coef);
1835 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1836 offset, isl_mat_copy(node->cmap));
1837 if (!coef)
1838 return isl_stat_error;
1840 nparam = isl_space_dim(node->space, isl_dim_param);
1841 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1843 if (!local) {
1844 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1845 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1846 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1848 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1850 return isl_stat_ok;
1853 /* Add constraints to graph->lp that bound the dependence distance for the given
1854 * dependence from node i to node j.
1855 * If s = 1, we add the constraint
1857 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1858 * <= m_0 + m_n n
1860 * or
1862 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1863 * m_0 + m_n n >= 0
1865 * for each (x,y) in R.
1866 * If s = -1, we add the constraint
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
1871 * or
1873 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1874 * m_0 + m_n n >= 0
1876 * for each (x,y) in R.
1877 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1878 * of valid constraints for R and then plug in
1879 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1880 * s*c_i_x, -s*c_j_x)
1881 * with each coefficient (except m_0, c_*_0 and c_*_n)
1882 * represented as a pair of non-negative coefficients.
1884 * Actually, we do not construct constraints for the c_*_x themselves,
1885 * but for the coefficients of c_*_x written as a linear combination
1886 * of the columns in node->cmap.
1889 * If "local" is set (and s = 1), then we add constraints
1891 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1893 * or
1895 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
1897 * instead, forcing the dependence distance to be (less than or) equal to 0.
1898 * That is, we plug in
1899 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
1900 * Note that dependences marked local are treated as validity constraints
1901 * by add_all_validity_constraints and therefore also have
1902 * their distances bounded by 0 from below.
1904 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1905 struct isl_sched_edge *edge, int s, int local)
1907 int offset;
1908 unsigned nparam;
1909 isl_map *map = isl_map_copy(edge->map);
1910 isl_ctx *ctx = isl_map_get_ctx(map);
1911 isl_dim_map *dim_map;
1912 isl_basic_set *coef;
1913 struct isl_sched_node *src = edge->src;
1914 struct isl_sched_node *dst = edge->dst;
1916 coef = inter_coefficients(graph, edge, map);
1918 offset = coef_var_offset(coef);
1920 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1921 offset, isl_mat_copy(src->cmap));
1922 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1923 offset + src->nvar, isl_mat_copy(dst->cmap));
1924 if (!coef)
1925 return isl_stat_error;
1927 nparam = isl_space_dim(src->space, isl_dim_param);
1928 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1930 if (!local) {
1931 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1932 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1933 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1936 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1938 return isl_stat_ok;
1941 /* Add all validity constraints to graph->lp.
1943 * An edge that is forced to be local needs to have its dependence
1944 * distances equal to zero. We take care of bounding them by 0 from below
1945 * here. add_all_proximity_constraints takes care of bounding them by 0
1946 * from above.
1948 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1949 * Otherwise, we ignore them.
1951 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1952 int use_coincidence)
1954 int i;
1956 for (i = 0; i < graph->n_edge; ++i) {
1957 struct isl_sched_edge *edge = &graph->edge[i];
1958 int local;
1960 local = is_local(edge) ||
1961 (is_coincidence(edge) && use_coincidence);
1962 if (!is_validity(edge) && !local)
1963 continue;
1964 if (edge->src != edge->dst)
1965 continue;
1966 if (add_intra_validity_constraints(graph, edge) < 0)
1967 return -1;
1970 for (i = 0; i < graph->n_edge; ++i) {
1971 struct isl_sched_edge *edge = &graph->edge[i];
1972 int local;
1974 local = is_local(edge) ||
1975 (is_coincidence(edge) && use_coincidence);
1976 if (!is_validity(edge) && !local)
1977 continue;
1978 if (edge->src == edge->dst)
1979 continue;
1980 if (add_inter_validity_constraints(graph, edge) < 0)
1981 return -1;
1984 return 0;
1987 /* Add constraints to graph->lp that bound the dependence distance
1988 * for all dependence relations.
1989 * If a given proximity dependence is identical to a validity
1990 * dependence, then the dependence distance is already bounded
1991 * from below (by zero), so we only need to bound the distance
1992 * from above. (This includes the case of "local" dependences
1993 * which are treated as validity dependence by add_all_validity_constraints.)
1994 * Otherwise, we need to bound the distance both from above and from below.
1996 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1997 * Otherwise, we ignore them.
1999 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2000 int use_coincidence)
2002 int i;
2004 for (i = 0; i < graph->n_edge; ++i) {
2005 struct isl_sched_edge *edge = &graph->edge[i];
2006 int local;
2008 local = is_local(edge) ||
2009 (is_coincidence(edge) && use_coincidence);
2010 if (!is_proximity(edge) && !local)
2011 continue;
2012 if (edge->src == edge->dst &&
2013 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
2014 return -1;
2015 if (edge->src != edge->dst &&
2016 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
2017 return -1;
2018 if (is_validity(edge) || local)
2019 continue;
2020 if (edge->src == edge->dst &&
2021 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2022 return -1;
2023 if (edge->src != edge->dst &&
2024 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2025 return -1;
2028 return 0;
2031 /* Compute a basis for the rows in the linear part of the schedule
2032 * and extend this basis to a full basis. The remaining rows
2033 * can then be used to force linear independence from the rows
2034 * in the schedule.
2036 * In particular, given the schedule rows S, we compute
2038 * S = H Q
2039 * S U = H
2041 * with H the Hermite normal form of S. That is, all but the
2042 * first rank columns of H are zero and so each row in S is
2043 * a linear combination of the first rank rows of Q.
2044 * The matrix Q is then transposed because we will write the
2045 * coefficients of the next schedule row as a column vector s
2046 * and express this s as a linear combination s = Q c of the
2047 * computed basis.
2048 * Similarly, the matrix U is transposed such that we can
2049 * compute the coefficients c = U s from a schedule row s.
2051 static int node_update_cmap(struct isl_sched_node *node)
2053 isl_mat *H, *U, *Q;
2054 int n_row = isl_mat_rows(node->sched);
2056 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2057 1 + node->nparam, node->nvar);
2059 H = isl_mat_left_hermite(H, 0, &U, &Q);
2060 isl_mat_free(node->cmap);
2061 isl_mat_free(node->cinv);
2062 isl_mat_free(node->ctrans);
2063 node->ctrans = isl_mat_copy(Q);
2064 node->cmap = isl_mat_transpose(Q);
2065 node->cinv = isl_mat_transpose(U);
2066 node->rank = isl_mat_initial_non_zero_cols(H);
2067 isl_mat_free(H);
2069 if (!node->cmap || !node->cinv || !node->ctrans || node->rank < 0)
2070 return -1;
2071 return 0;
2074 /* Is "edge" marked as a validity or a conditional validity edge?
2076 static int is_any_validity(struct isl_sched_edge *edge)
2078 return is_validity(edge) || is_conditional_validity(edge);
2081 /* How many times should we count the constraints in "edge"?
2083 * We count as follows
2084 * validity -> 1 (>= 0)
2085 * validity+proximity -> 2 (>= 0 and upper bound)
2086 * proximity -> 2 (lower and upper bound)
2087 * local(+any) -> 2 (>= 0 and <= 0)
2089 * If an edge is only marked conditional_validity then it counts
2090 * as zero since it is only checked afterwards.
2092 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2093 * Otherwise, we ignore them.
2095 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2097 if (is_proximity(edge) || is_local(edge))
2098 return 2;
2099 if (use_coincidence && is_coincidence(edge))
2100 return 2;
2101 if (is_validity(edge))
2102 return 1;
2103 return 0;
2106 /* Count the number of equality and inequality constraints
2107 * that will be added for the given map.
2109 * "use_coincidence" is set if we should take into account coincidence edges.
2111 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2112 struct isl_sched_edge *edge, __isl_take isl_map *map,
2113 int *n_eq, int *n_ineq, int use_coincidence)
2115 isl_basic_set *coef;
2116 int f = edge_multiplicity(edge, use_coincidence);
2118 if (f == 0) {
2119 isl_map_free(map);
2120 return isl_stat_ok;
2123 if (edge->src == edge->dst)
2124 coef = intra_coefficients(graph, edge->src, map);
2125 else
2126 coef = inter_coefficients(graph, edge, map);
2127 if (!coef)
2128 return isl_stat_error;
2129 *n_eq += f * isl_basic_set_n_equality(coef);
2130 *n_ineq += f * isl_basic_set_n_inequality(coef);
2131 isl_basic_set_free(coef);
2133 return isl_stat_ok;
2136 /* Count the number of equality and inequality constraints
2137 * that will be added to the main lp problem.
2138 * We count as follows
2139 * validity -> 1 (>= 0)
2140 * validity+proximity -> 2 (>= 0 and upper bound)
2141 * proximity -> 2 (lower and upper bound)
2142 * local(+any) -> 2 (>= 0 and <= 0)
2144 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2145 * Otherwise, we ignore them.
2147 static int count_constraints(struct isl_sched_graph *graph,
2148 int *n_eq, int *n_ineq, int use_coincidence)
2150 int i;
2152 *n_eq = *n_ineq = 0;
2153 for (i = 0; i < graph->n_edge; ++i) {
2154 struct isl_sched_edge *edge = &graph->edge[i];
2155 isl_map *map = isl_map_copy(edge->map);
2157 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2158 use_coincidence) < 0)
2159 return -1;
2162 return 0;
2165 /* Count the number of constraints that will be added by
2166 * add_bound_constant_constraints to bound the values of the constant terms
2167 * and increment *n_eq and *n_ineq accordingly.
2169 * In practice, add_bound_constant_constraints only adds inequalities.
2171 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2172 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2174 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2175 return isl_stat_ok;
2177 *n_ineq += graph->n;
2179 return isl_stat_ok;
2182 /* Add constraints to bound the values of the constant terms in the schedule,
2183 * if requested by the user.
2185 * The maximal value of the constant terms is defined by the option
2186 * "schedule_max_constant_term".
2188 * Within each node, the coefficients have the following order:
2189 * - c_i_0
2190 * - c_i_n (if parametric)
2191 * - positive and negative parts of c_i_x
2193 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2194 struct isl_sched_graph *graph)
2196 int i, k;
2197 int max;
2198 int total;
2200 max = isl_options_get_schedule_max_constant_term(ctx);
2201 if (max == -1)
2202 return isl_stat_ok;
2204 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2206 for (i = 0; i < graph->n; ++i) {
2207 struct isl_sched_node *node = &graph->node[i];
2208 k = isl_basic_set_alloc_inequality(graph->lp);
2209 if (k < 0)
2210 return isl_stat_error;
2211 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2212 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2213 isl_int_set_si(graph->lp->ineq[k][0], max);
2216 return isl_stat_ok;
2219 /* Count the number of constraints that will be added by
2220 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2221 * accordingly.
2223 * In practice, add_bound_coefficient_constraints only adds inequalities.
2225 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2226 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2228 int i;
2230 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2231 !isl_options_get_schedule_treat_coalescing(ctx))
2232 return 0;
2234 for (i = 0; i < graph->n; ++i)
2235 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2237 return 0;
2240 /* Add constraints to graph->lp that bound the values of
2241 * the parameter schedule coefficients of "node" to "max" and
2242 * the variable schedule coefficients to the corresponding entry
2243 * in node->max.
2244 * In either case, a negative value means that no bound needs to be imposed.
2246 * For parameter coefficients, this amounts to adding a constraint
2248 * c_n <= max
2250 * i.e.,
2252 * -c_n + max >= 0
2254 * The variables coefficients are, however, not represented directly.
2255 * Instead, the variables coefficients c_x are written as a linear
2256 * combination c_x = cmap c_z of some other coefficients c_z,
2257 * which are in turn encoded as c_z = c_z^+ - c_z^-.
2258 * Let a_j be the elements of row i of node->cmap, then
2260 * -max_i <= c_x_i <= max_i
2262 * is encoded as
2264 * -max_i <= \sum_j a_j (c_z_j^+ - c_z_j^-) <= max_i
2266 * or
2268 * -\sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2269 * \sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2271 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2272 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2274 int i, j, k;
2275 int total;
2276 isl_vec *ineq;
2278 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2280 for (j = 0; j < node->nparam; ++j) {
2281 int dim;
2283 if (max < 0)
2284 continue;
2286 k = isl_basic_set_alloc_inequality(graph->lp);
2287 if (k < 0)
2288 return isl_stat_error;
2289 dim = 1 + node->start + 1 + j;
2290 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2291 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2292 isl_int_set_si(graph->lp->ineq[k][0], max);
2295 ineq = isl_vec_alloc(ctx, 1 + total);
2296 ineq = isl_vec_clr(ineq);
2297 if (!ineq)
2298 return isl_stat_error;
2299 for (i = 0; i < node->nvar; ++i) {
2300 int pos = 1 + node_var_coef_offset(node);
2302 if (isl_int_is_neg(node->max->el[i]))
2303 continue;
2305 for (j = 0; j < node->nvar; ++j) {
2306 int pos_j = 1 + node_var_coef_pos(node, j);
2308 isl_int_set(ineq->el[pos_j], node->cmap->row[i][j]);
2309 isl_int_neg(ineq->el[pos_j], node->cmap->row[i][j]);
2311 isl_int_set(ineq->el[0], node->max->el[i]);
2313 k = isl_basic_set_alloc_inequality(graph->lp);
2314 if (k < 0)
2315 goto error;
2316 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2318 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2 * node->nvar);
2319 k = isl_basic_set_alloc_inequality(graph->lp);
2320 if (k < 0)
2321 goto error;
2322 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2324 isl_vec_free(ineq);
2326 return isl_stat_ok;
2327 error:
2328 isl_vec_free(ineq);
2329 return isl_stat_error;
2332 /* Add constraints that bound the values of the variable and parameter
2333 * coefficients of the schedule.
2335 * The maximal value of the coefficients is defined by the option
2336 * 'schedule_max_coefficient' and the entries in node->max.
2337 * These latter entries are only set if either the schedule_max_coefficient
2338 * option or the schedule_treat_coalescing option is set.
2340 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2341 struct isl_sched_graph *graph)
2343 int i;
2344 int max;
2346 max = isl_options_get_schedule_max_coefficient(ctx);
2348 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2349 return isl_stat_ok;
2351 for (i = 0; i < graph->n; ++i) {
2352 struct isl_sched_node *node = &graph->node[i];
2354 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2355 return isl_stat_error;
2358 return isl_stat_ok;
2361 /* Add a constraint to graph->lp that equates the value at position
2362 * "sum_pos" to the sum of the "n" values starting at "first".
2364 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2365 int sum_pos, int first, int n)
2367 int i, k;
2368 int total;
2370 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2372 k = isl_basic_set_alloc_equality(graph->lp);
2373 if (k < 0)
2374 return isl_stat_error;
2375 isl_seq_clr(graph->lp->eq[k], 1 + total);
2376 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2377 for (i = 0; i < n; ++i)
2378 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2380 return isl_stat_ok;
2383 /* Add a constraint to graph->lp that equates the value at position
2384 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2386 * Within each node, the coefficients have the following order:
2387 * - c_i_0
2388 * - c_i_n (if parametric)
2389 * - positive and negative parts of c_i_x
2391 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2392 int sum_pos)
2394 int i, j, k;
2395 int total;
2397 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2399 k = isl_basic_set_alloc_equality(graph->lp);
2400 if (k < 0)
2401 return isl_stat_error;
2402 isl_seq_clr(graph->lp->eq[k], 1 + total);
2403 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2404 for (i = 0; i < graph->n; ++i) {
2405 int pos = 1 + graph->node[i].start + 1;
2407 for (j = 0; j < graph->node[i].nparam; ++j)
2408 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2411 return isl_stat_ok;
2414 /* Add a constraint to graph->lp that equates the value at position
2415 * "sum_pos" to the sum of the variable coefficients of all nodes.
2417 * Within each node, the coefficients have the following order:
2418 * - c_i_0
2419 * - c_i_n (if parametric)
2420 * - positive and negative parts of c_i_x
2422 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2423 int sum_pos)
2425 int i, j, k;
2426 int total;
2428 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2430 k = isl_basic_set_alloc_equality(graph->lp);
2431 if (k < 0)
2432 return isl_stat_error;
2433 isl_seq_clr(graph->lp->eq[k], 1 + total);
2434 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2435 for (i = 0; i < graph->n; ++i) {
2436 struct isl_sched_node *node = &graph->node[i];
2437 int pos = 1 + node_var_coef_offset(node);
2439 for (j = 0; j < 2 * node->nvar; ++j)
2440 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2443 return isl_stat_ok;
2446 /* Construct an ILP problem for finding schedule coefficients
2447 * that result in non-negative, but small dependence distances
2448 * over all dependences.
2449 * In particular, the dependence distances over proximity edges
2450 * are bounded by m_0 + m_n n and we compute schedule coefficients
2451 * with small values (preferably zero) of m_n and m_0.
2453 * All variables of the ILP are non-negative. The actual coefficients
2454 * may be negative, so each coefficient is represented as the difference
2455 * of two non-negative variables. The negative part always appears
2456 * immediately before the positive part.
2457 * Other than that, the variables have the following order
2459 * - sum of positive and negative parts of m_n coefficients
2460 * - m_0
2461 * - sum of all c_n coefficients
2462 * (unconstrained when computing non-parametric schedules)
2463 * - sum of positive and negative parts of all c_x coefficients
2464 * - positive and negative parts of m_n coefficients
2465 * - for each node
2466 * - c_i_0
2467 * - c_i_n (if parametric)
2468 * - positive and negative parts of c_i_x
2470 * The c_i_x are not represented directly, but through the columns of
2471 * node->cmap. That is, the computed values are for variable t_i_x
2472 * such that c_i_x = Q t_i_x with Q equal to node->cmap.
2474 * The constraints are those from the edges plus two or three equalities
2475 * to express the sums.
2477 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2478 * Otherwise, we ignore them.
2480 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2481 int use_coincidence)
2483 int i;
2484 unsigned nparam;
2485 unsigned total;
2486 isl_space *space;
2487 int parametric;
2488 int param_pos;
2489 int n_eq, n_ineq;
2491 parametric = ctx->opt->schedule_parametric;
2492 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2493 param_pos = 4;
2494 total = param_pos + 2 * nparam;
2495 for (i = 0; i < graph->n; ++i) {
2496 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2497 if (node_update_cmap(node) < 0)
2498 return isl_stat_error;
2499 node->start = total;
2500 total += 1 + node->nparam + 2 * node->nvar;
2503 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2504 return isl_stat_error;
2505 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2506 return isl_stat_error;
2507 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2508 return isl_stat_error;
2510 space = isl_space_set_alloc(ctx, 0, total);
2511 isl_basic_set_free(graph->lp);
2512 n_eq += 2 + parametric;
2514 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2516 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2517 return isl_stat_error;
2518 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2519 return isl_stat_error;
2520 if (add_var_sum_constraint(graph, 3) < 0)
2521 return isl_stat_error;
2522 if (add_bound_constant_constraints(ctx, graph) < 0)
2523 return isl_stat_error;
2524 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2525 return isl_stat_error;
2526 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2527 return isl_stat_error;
2528 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2529 return isl_stat_error;
2531 return isl_stat_ok;
2534 /* Analyze the conflicting constraint found by
2535 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2536 * constraint of one of the edges between distinct nodes, living, moreover
2537 * in distinct SCCs, then record the source and sink SCC as this may
2538 * be a good place to cut between SCCs.
2540 static int check_conflict(int con, void *user)
2542 int i;
2543 struct isl_sched_graph *graph = user;
2545 if (graph->src_scc >= 0)
2546 return 0;
2548 con -= graph->lp->n_eq;
2550 if (con >= graph->lp->n_ineq)
2551 return 0;
2553 for (i = 0; i < graph->n_edge; ++i) {
2554 if (!is_validity(&graph->edge[i]))
2555 continue;
2556 if (graph->edge[i].src == graph->edge[i].dst)
2557 continue;
2558 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2559 continue;
2560 if (graph->edge[i].start > con)
2561 continue;
2562 if (graph->edge[i].end <= con)
2563 continue;
2564 graph->src_scc = graph->edge[i].src->scc;
2565 graph->dst_scc = graph->edge[i].dst->scc;
2568 return 0;
2571 /* Check whether the next schedule row of the given node needs to be
2572 * non-trivial. Lower-dimensional domains may have some trivial rows,
2573 * but as soon as the number of remaining required non-trivial rows
2574 * is as large as the number or remaining rows to be computed,
2575 * all remaining rows need to be non-trivial.
2577 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2579 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2582 /* Construct a non-triviality region with "n" directions
2583 * over "n_var" coefficients.
2584 * Each direction corresponds to a schedule coefficient,
2585 * where each schedule coefficient is encoded as the difference
2586 * of two non-negative variables, c^+_i - c^-_i
2587 * with c^-_i at position 2 * i and c^+_i at position 2 * i + 1.
2588 * The order of the directions is the same as that of the variables,
2589 * but if the number of variables is greater than the number of directions,
2590 * then the directions correspond to the last variables.
2592 static __isl_give isl_mat *construct_trivial(isl_ctx *ctx, int n, int n_var)
2594 isl_mat *mat;
2595 int i, off;
2597 off = n_var - n;
2598 mat = isl_mat_zero(ctx, n, 2 * n_var);
2599 for (i = 0; i < n; ++i) {
2600 mat = isl_mat_set_element_si(mat, i, 2 * (off + i), -1);
2601 mat = isl_mat_set_element_si(mat, i, 2 * (off + i) + 1, 1);
2604 return mat;
2607 /* Solve the ILP problem constructed in setup_lp.
2608 * For each node such that all the remaining rows of its schedule
2609 * need to be non-trivial, we construct a non-triviality region.
2610 * This region imposes that the next row is independent of previous rows.
2611 * In particular the coefficients c_i_x are represented by t_i_x
2612 * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
2613 * its first columns span the rows of the previously computed part
2614 * of the schedule. The non-triviality region enforces that at least
2615 * one of the remaining components of t_i_x is non-zero, i.e.,
2616 * that the new schedule row depends on at least one of the remaining
2617 * columns of Q.
2619 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2621 int i;
2622 isl_vec *sol;
2623 isl_basic_set *lp;
2625 for (i = 0; i < graph->n; ++i) {
2626 struct isl_sched_node *node = &graph->node[i];
2627 int skip = node->rank;
2628 isl_mat *trivial;
2630 graph->region[i].pos = node_var_coef_offset(node);
2631 if (needs_row(graph, node))
2632 trivial = construct_trivial(ctx, node->nvar - skip,
2633 node->nvar);
2634 else
2635 trivial = isl_mat_zero(ctx, 0, 0);
2636 graph->region[i].trivial = trivial;
2638 lp = isl_basic_set_copy(graph->lp);
2639 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2640 graph->region, &check_conflict, graph);
2641 for (i = 0; i < graph->n; ++i)
2642 isl_mat_free(graph->region[i].trivial);
2643 return sol;
2646 /* Extract the coefficients for the variables of "node" from "sol".
2648 * Within each node, the coefficients have the following order:
2649 * - c_i_0
2650 * - c_i_n (if parametric)
2651 * - positive and negative parts of c_i_x
2653 * The c_i_x^- appear before their c_i_x^+ counterpart.
2655 * Return c_i_x = c_i_x^+ - c_i_x^-
2657 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2658 __isl_keep isl_vec *sol)
2660 int i;
2661 int pos;
2662 isl_vec *csol;
2664 if (!sol)
2665 return NULL;
2666 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2667 if (!csol)
2668 return NULL;
2670 pos = 1 + node_var_coef_offset(node);
2671 for (i = 0; i < node->nvar; ++i)
2672 isl_int_sub(csol->el[i],
2673 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2675 return csol;
2678 /* Update the schedules of all nodes based on the given solution
2679 * of the LP problem.
2680 * The new row is added to the current band.
2681 * All possibly negative coefficients are encoded as a difference
2682 * of two non-negative variables, so we need to perform the subtraction
2683 * here. Moreover, if use_cmap is set, then the solution does
2684 * not refer to the actual coefficients c_i_x, but instead to variables
2685 * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
2686 * In this case, we then also need to perform this multiplication
2687 * to obtain the values of c_i_x.
2689 * If coincident is set, then the caller guarantees that the new
2690 * row satisfies the coincidence constraints.
2692 static int update_schedule(struct isl_sched_graph *graph,
2693 __isl_take isl_vec *sol, int use_cmap, int coincident)
2695 int i, j;
2696 isl_vec *csol = NULL;
2698 if (!sol)
2699 goto error;
2700 if (sol->size == 0)
2701 isl_die(sol->ctx, isl_error_internal,
2702 "no solution found", goto error);
2703 if (graph->n_total_row >= graph->max_row)
2704 isl_die(sol->ctx, isl_error_internal,
2705 "too many schedule rows", goto error);
2707 for (i = 0; i < graph->n; ++i) {
2708 struct isl_sched_node *node = &graph->node[i];
2709 int pos = node->start;
2710 int row = isl_mat_rows(node->sched);
2712 isl_vec_free(csol);
2713 csol = extract_var_coef(node, sol);
2714 if (!csol)
2715 goto error;
2717 isl_map_free(node->sched_map);
2718 node->sched_map = NULL;
2719 node->sched = isl_mat_add_rows(node->sched, 1);
2720 if (!node->sched)
2721 goto error;
2722 for (j = 0; j < 1 + node->nparam; ++j)
2723 node->sched = isl_mat_set_element(node->sched,
2724 row, j, sol->el[1 + pos + j]);
2725 if (use_cmap)
2726 csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
2727 csol);
2728 if (!csol)
2729 goto error;
2730 for (j = 0; j < node->nvar; ++j)
2731 node->sched = isl_mat_set_element(node->sched,
2732 row, 1 + node->nparam + j, csol->el[j]);
2733 node->coincident[graph->n_total_row] = coincident;
2735 isl_vec_free(sol);
2736 isl_vec_free(csol);
2738 graph->n_row++;
2739 graph->n_total_row++;
2741 return 0;
2742 error:
2743 isl_vec_free(sol);
2744 isl_vec_free(csol);
2745 return -1;
2748 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2749 * and return this isl_aff.
2751 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2752 struct isl_sched_node *node, int row)
2754 int j;
2755 isl_int v;
2756 isl_aff *aff;
2758 isl_int_init(v);
2760 aff = isl_aff_zero_on_domain(ls);
2761 isl_mat_get_element(node->sched, row, 0, &v);
2762 aff = isl_aff_set_constant(aff, v);
2763 for (j = 0; j < node->nparam; ++j) {
2764 isl_mat_get_element(node->sched, row, 1 + j, &v);
2765 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2767 for (j = 0; j < node->nvar; ++j) {
2768 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2769 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2772 isl_int_clear(v);
2774 return aff;
2777 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2778 * and return this multi_aff.
2780 * The result is defined over the uncompressed node domain.
2782 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2783 struct isl_sched_node *node, int first, int n)
2785 int i;
2786 isl_space *space;
2787 isl_local_space *ls;
2788 isl_aff *aff;
2789 isl_multi_aff *ma;
2790 int nrow;
2792 if (!node)
2793 return NULL;
2794 nrow = isl_mat_rows(node->sched);
2795 if (node->compressed)
2796 space = isl_multi_aff_get_domain_space(node->decompress);
2797 else
2798 space = isl_space_copy(node->space);
2799 ls = isl_local_space_from_space(isl_space_copy(space));
2800 space = isl_space_from_domain(space);
2801 space = isl_space_add_dims(space, isl_dim_out, n);
2802 ma = isl_multi_aff_zero(space);
2804 for (i = first; i < first + n; ++i) {
2805 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2806 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2809 isl_local_space_free(ls);
2811 if (node->compressed)
2812 ma = isl_multi_aff_pullback_multi_aff(ma,
2813 isl_multi_aff_copy(node->compress));
2815 return ma;
2818 /* Convert node->sched into a multi_aff and return this multi_aff.
2820 * The result is defined over the uncompressed node domain.
2822 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2823 struct isl_sched_node *node)
2825 int nrow;
2827 nrow = isl_mat_rows(node->sched);
2828 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2831 /* Convert node->sched into a map and return this map.
2833 * The result is cached in node->sched_map, which needs to be released
2834 * whenever node->sched is updated.
2835 * It is defined over the uncompressed node domain.
2837 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2839 if (!node->sched_map) {
2840 isl_multi_aff *ma;
2842 ma = node_extract_schedule_multi_aff(node);
2843 node->sched_map = isl_map_from_multi_aff(ma);
2846 return isl_map_copy(node->sched_map);
2849 /* Construct a map that can be used to update a dependence relation
2850 * based on the current schedule.
2851 * That is, construct a map expressing that source and sink
2852 * are executed within the same iteration of the current schedule.
2853 * This map can then be intersected with the dependence relation.
2854 * This is not the most efficient way, but this shouldn't be a critical
2855 * operation.
2857 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2858 struct isl_sched_node *dst)
2860 isl_map *src_sched, *dst_sched;
2862 src_sched = node_extract_schedule(src);
2863 dst_sched = node_extract_schedule(dst);
2864 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2867 /* Intersect the domains of the nested relations in domain and range
2868 * of "umap" with "map".
2870 static __isl_give isl_union_map *intersect_domains(
2871 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2873 isl_union_set *uset;
2875 umap = isl_union_map_zip(umap);
2876 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2877 umap = isl_union_map_intersect_domain(umap, uset);
2878 umap = isl_union_map_zip(umap);
2879 return umap;
2882 /* Update the dependence relation of the given edge based
2883 * on the current schedule.
2884 * If the dependence is carried completely by the current schedule, then
2885 * it is removed from the edge_tables. It is kept in the list of edges
2886 * as otherwise all edge_tables would have to be recomputed.
2888 static int update_edge(struct isl_sched_graph *graph,
2889 struct isl_sched_edge *edge)
2891 int empty;
2892 isl_map *id;
2894 id = specializer(edge->src, edge->dst);
2895 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2896 if (!edge->map)
2897 goto error;
2899 if (edge->tagged_condition) {
2900 edge->tagged_condition =
2901 intersect_domains(edge->tagged_condition, id);
2902 if (!edge->tagged_condition)
2903 goto error;
2905 if (edge->tagged_validity) {
2906 edge->tagged_validity =
2907 intersect_domains(edge->tagged_validity, id);
2908 if (!edge->tagged_validity)
2909 goto error;
2912 empty = isl_map_plain_is_empty(edge->map);
2913 if (empty < 0)
2914 goto error;
2915 if (empty)
2916 graph_remove_edge(graph, edge);
2918 isl_map_free(id);
2919 return 0;
2920 error:
2921 isl_map_free(id);
2922 return -1;
2925 /* Does the domain of "umap" intersect "uset"?
2927 static int domain_intersects(__isl_keep isl_union_map *umap,
2928 __isl_keep isl_union_set *uset)
2930 int empty;
2932 umap = isl_union_map_copy(umap);
2933 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2934 empty = isl_union_map_is_empty(umap);
2935 isl_union_map_free(umap);
2937 return empty < 0 ? -1 : !empty;
2940 /* Does the range of "umap" intersect "uset"?
2942 static int range_intersects(__isl_keep isl_union_map *umap,
2943 __isl_keep isl_union_set *uset)
2945 int empty;
2947 umap = isl_union_map_copy(umap);
2948 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2949 empty = isl_union_map_is_empty(umap);
2950 isl_union_map_free(umap);
2952 return empty < 0 ? -1 : !empty;
2955 /* Are the condition dependences of "edge" local with respect to
2956 * the current schedule?
2958 * That is, are domain and range of the condition dependences mapped
2959 * to the same point?
2961 * In other words, is the condition false?
2963 static int is_condition_false(struct isl_sched_edge *edge)
2965 isl_union_map *umap;
2966 isl_map *map, *sched, *test;
2967 int empty, local;
2969 empty = isl_union_map_is_empty(edge->tagged_condition);
2970 if (empty < 0 || empty)
2971 return empty;
2973 umap = isl_union_map_copy(edge->tagged_condition);
2974 umap = isl_union_map_zip(umap);
2975 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2976 map = isl_map_from_union_map(umap);
2978 sched = node_extract_schedule(edge->src);
2979 map = isl_map_apply_domain(map, sched);
2980 sched = node_extract_schedule(edge->dst);
2981 map = isl_map_apply_range(map, sched);
2983 test = isl_map_identity(isl_map_get_space(map));
2984 local = isl_map_is_subset(map, test);
2985 isl_map_free(map);
2986 isl_map_free(test);
2988 return local;
2991 /* For each conditional validity constraint that is adjacent
2992 * to a condition with domain in condition_source or range in condition_sink,
2993 * turn it into an unconditional validity constraint.
2995 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2996 __isl_take isl_union_set *condition_source,
2997 __isl_take isl_union_set *condition_sink)
2999 int i;
3001 condition_source = isl_union_set_coalesce(condition_source);
3002 condition_sink = isl_union_set_coalesce(condition_sink);
3004 for (i = 0; i < graph->n_edge; ++i) {
3005 int adjacent;
3006 isl_union_map *validity;
3008 if (!is_conditional_validity(&graph->edge[i]))
3009 continue;
3010 if (is_validity(&graph->edge[i]))
3011 continue;
3013 validity = graph->edge[i].tagged_validity;
3014 adjacent = domain_intersects(validity, condition_sink);
3015 if (adjacent >= 0 && !adjacent)
3016 adjacent = range_intersects(validity, condition_source);
3017 if (adjacent < 0)
3018 goto error;
3019 if (!adjacent)
3020 continue;
3022 set_validity(&graph->edge[i]);
3025 isl_union_set_free(condition_source);
3026 isl_union_set_free(condition_sink);
3027 return 0;
3028 error:
3029 isl_union_set_free(condition_source);
3030 isl_union_set_free(condition_sink);
3031 return -1;
3034 /* Update the dependence relations of all edges based on the current schedule
3035 * and enforce conditional validity constraints that are adjacent
3036 * to satisfied condition constraints.
3038 * First check if any of the condition constraints are satisfied
3039 * (i.e., not local to the outer schedule) and keep track of
3040 * their domain and range.
3041 * Then update all dependence relations (which removes the non-local
3042 * constraints).
3043 * Finally, if any condition constraints turned out to be satisfied,
3044 * then turn all adjacent conditional validity constraints into
3045 * unconditional validity constraints.
3047 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3049 int i;
3050 int any = 0;
3051 isl_union_set *source, *sink;
3053 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3054 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3055 for (i = 0; i < graph->n_edge; ++i) {
3056 int local;
3057 isl_union_set *uset;
3058 isl_union_map *umap;
3060 if (!is_condition(&graph->edge[i]))
3061 continue;
3062 if (is_local(&graph->edge[i]))
3063 continue;
3064 local = is_condition_false(&graph->edge[i]);
3065 if (local < 0)
3066 goto error;
3067 if (local)
3068 continue;
3070 any = 1;
3072 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3073 uset = isl_union_map_domain(umap);
3074 source = isl_union_set_union(source, uset);
3076 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3077 uset = isl_union_map_range(umap);
3078 sink = isl_union_set_union(sink, uset);
3081 for (i = graph->n_edge - 1; i >= 0; --i) {
3082 if (update_edge(graph, &graph->edge[i]) < 0)
3083 goto error;
3086 if (any)
3087 return unconditionalize_adjacent_validity(graph, source, sink);
3089 isl_union_set_free(source);
3090 isl_union_set_free(sink);
3091 return 0;
3092 error:
3093 isl_union_set_free(source);
3094 isl_union_set_free(sink);
3095 return -1;
3098 static void next_band(struct isl_sched_graph *graph)
3100 graph->band_start = graph->n_total_row;
3103 /* Return the union of the universe domains of the nodes in "graph"
3104 * that satisfy "pred".
3106 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3107 struct isl_sched_graph *graph,
3108 int (*pred)(struct isl_sched_node *node, int data), int data)
3110 int i;
3111 isl_set *set;
3112 isl_union_set *dom;
3114 for (i = 0; i < graph->n; ++i)
3115 if (pred(&graph->node[i], data))
3116 break;
3118 if (i >= graph->n)
3119 isl_die(ctx, isl_error_internal,
3120 "empty component", return NULL);
3122 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3123 dom = isl_union_set_from_set(set);
3125 for (i = i + 1; i < graph->n; ++i) {
3126 if (!pred(&graph->node[i], data))
3127 continue;
3128 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3129 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3132 return dom;
3135 /* Return a list of unions of universe domains, where each element
3136 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3138 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3139 struct isl_sched_graph *graph)
3141 int i;
3142 isl_union_set_list *filters;
3144 filters = isl_union_set_list_alloc(ctx, graph->scc);
3145 for (i = 0; i < graph->scc; ++i) {
3146 isl_union_set *dom;
3148 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3149 filters = isl_union_set_list_add(filters, dom);
3152 return filters;
3155 /* Return a list of two unions of universe domains, one for the SCCs up
3156 * to and including graph->src_scc and another for the other SCCs.
3158 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3159 struct isl_sched_graph *graph)
3161 isl_union_set *dom;
3162 isl_union_set_list *filters;
3164 filters = isl_union_set_list_alloc(ctx, 2);
3165 dom = isl_sched_graph_domain(ctx, graph,
3166 &node_scc_at_most, graph->src_scc);
3167 filters = isl_union_set_list_add(filters, dom);
3168 dom = isl_sched_graph_domain(ctx, graph,
3169 &node_scc_at_least, graph->src_scc + 1);
3170 filters = isl_union_set_list_add(filters, dom);
3172 return filters;
3175 /* Copy nodes that satisfy node_pred from the src dependence graph
3176 * to the dst dependence graph.
3178 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3179 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3181 int i;
3183 dst->n = 0;
3184 for (i = 0; i < src->n; ++i) {
3185 int j;
3187 if (!node_pred(&src->node[i], data))
3188 continue;
3190 j = dst->n;
3191 dst->node[j].space = isl_space_copy(src->node[i].space);
3192 dst->node[j].compressed = src->node[i].compressed;
3193 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3194 dst->node[j].compress =
3195 isl_multi_aff_copy(src->node[i].compress);
3196 dst->node[j].decompress =
3197 isl_multi_aff_copy(src->node[i].decompress);
3198 dst->node[j].nvar = src->node[i].nvar;
3199 dst->node[j].nparam = src->node[i].nparam;
3200 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3201 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3202 dst->node[j].coincident = src->node[i].coincident;
3203 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3204 dst->node[j].max = isl_vec_copy(src->node[i].max);
3205 dst->n++;
3207 if (!dst->node[j].space || !dst->node[j].sched)
3208 return -1;
3209 if (dst->node[j].compressed &&
3210 (!dst->node[j].hull || !dst->node[j].compress ||
3211 !dst->node[j].decompress))
3212 return -1;
3215 return 0;
3218 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3219 * to the dst dependence graph.
3220 * If the source or destination node of the edge is not in the destination
3221 * graph, then it must be a backward proximity edge and it should simply
3222 * be ignored.
3224 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3225 struct isl_sched_graph *src,
3226 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3228 int i;
3229 enum isl_edge_type t;
3231 dst->n_edge = 0;
3232 for (i = 0; i < src->n_edge; ++i) {
3233 struct isl_sched_edge *edge = &src->edge[i];
3234 isl_map *map;
3235 isl_union_map *tagged_condition;
3236 isl_union_map *tagged_validity;
3237 struct isl_sched_node *dst_src, *dst_dst;
3239 if (!edge_pred(edge, data))
3240 continue;
3242 if (isl_map_plain_is_empty(edge->map))
3243 continue;
3245 dst_src = graph_find_node(ctx, dst, edge->src->space);
3246 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3247 if (!dst_src || !dst_dst) {
3248 if (is_validity(edge) || is_conditional_validity(edge))
3249 isl_die(ctx, isl_error_internal,
3250 "backward (conditional) validity edge",
3251 return -1);
3252 continue;
3255 map = isl_map_copy(edge->map);
3256 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3257 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3259 dst->edge[dst->n_edge].src = dst_src;
3260 dst->edge[dst->n_edge].dst = dst_dst;
3261 dst->edge[dst->n_edge].map = map;
3262 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3263 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3264 dst->edge[dst->n_edge].types = edge->types;
3265 dst->n_edge++;
3267 if (edge->tagged_condition && !tagged_condition)
3268 return -1;
3269 if (edge->tagged_validity && !tagged_validity)
3270 return -1;
3272 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3273 if (edge !=
3274 graph_find_edge(src, t, edge->src, edge->dst))
3275 continue;
3276 if (graph_edge_table_add(ctx, dst, t,
3277 &dst->edge[dst->n_edge - 1]) < 0)
3278 return -1;
3282 return 0;
3285 /* Compute the maximal number of variables over all nodes.
3286 * This is the maximal number of linearly independent schedule
3287 * rows that we need to compute.
3288 * Just in case we end up in a part of the dependence graph
3289 * with only lower-dimensional domains, we make sure we will
3290 * compute the required amount of extra linearly independent rows.
3292 static int compute_maxvar(struct isl_sched_graph *graph)
3294 int i;
3296 graph->maxvar = 0;
3297 for (i = 0; i < graph->n; ++i) {
3298 struct isl_sched_node *node = &graph->node[i];
3299 int nvar;
3301 if (node_update_cmap(node) < 0)
3302 return -1;
3303 nvar = node->nvar + graph->n_row - node->rank;
3304 if (nvar > graph->maxvar)
3305 graph->maxvar = nvar;
3308 return 0;
3311 /* Extract the subgraph of "graph" that consists of the node satisfying
3312 * "node_pred" and the edges satisfying "edge_pred" and store
3313 * the result in "sub".
3315 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3316 int (*node_pred)(struct isl_sched_node *node, int data),
3317 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3318 int data, struct isl_sched_graph *sub)
3320 int i, n = 0, n_edge = 0;
3321 int t;
3323 for (i = 0; i < graph->n; ++i)
3324 if (node_pred(&graph->node[i], data))
3325 ++n;
3326 for (i = 0; i < graph->n_edge; ++i)
3327 if (edge_pred(&graph->edge[i], data))
3328 ++n_edge;
3329 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3330 return -1;
3331 if (copy_nodes(sub, graph, node_pred, data) < 0)
3332 return -1;
3333 if (graph_init_table(ctx, sub) < 0)
3334 return -1;
3335 for (t = 0; t <= isl_edge_last; ++t)
3336 sub->max_edge[t] = graph->max_edge[t];
3337 if (graph_init_edge_tables(ctx, sub) < 0)
3338 return -1;
3339 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3340 return -1;
3341 sub->n_row = graph->n_row;
3342 sub->max_row = graph->max_row;
3343 sub->n_total_row = graph->n_total_row;
3344 sub->band_start = graph->band_start;
3346 return 0;
3349 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3350 struct isl_sched_graph *graph);
3351 static __isl_give isl_schedule_node *compute_schedule_wcc(
3352 isl_schedule_node *node, struct isl_sched_graph *graph);
3354 /* Compute a schedule for a subgraph of "graph". In particular, for
3355 * the graph composed of nodes that satisfy node_pred and edges that
3356 * that satisfy edge_pred.
3357 * If the subgraph is known to consist of a single component, then wcc should
3358 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3359 * Otherwise, we call compute_schedule, which will check whether the subgraph
3360 * is connected.
3362 * The schedule is inserted at "node" and the updated schedule node
3363 * is returned.
3365 static __isl_give isl_schedule_node *compute_sub_schedule(
3366 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3367 struct isl_sched_graph *graph,
3368 int (*node_pred)(struct isl_sched_node *node, int data),
3369 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3370 int data, int wcc)
3372 struct isl_sched_graph split = { 0 };
3374 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3375 &split) < 0)
3376 goto error;
3378 if (wcc)
3379 node = compute_schedule_wcc(node, &split);
3380 else
3381 node = compute_schedule(node, &split);
3383 graph_free(ctx, &split);
3384 return node;
3385 error:
3386 graph_free(ctx, &split);
3387 return isl_schedule_node_free(node);
3390 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3392 return edge->src->scc == scc && edge->dst->scc == scc;
3395 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3397 return edge->dst->scc <= scc;
3400 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3402 return edge->src->scc >= scc;
3405 /* Reset the current band by dropping all its schedule rows.
3407 static int reset_band(struct isl_sched_graph *graph)
3409 int i;
3410 int drop;
3412 drop = graph->n_total_row - graph->band_start;
3413 graph->n_total_row -= drop;
3414 graph->n_row -= drop;
3416 for (i = 0; i < graph->n; ++i) {
3417 struct isl_sched_node *node = &graph->node[i];
3419 isl_map_free(node->sched_map);
3420 node->sched_map = NULL;
3422 node->sched = isl_mat_drop_rows(node->sched,
3423 graph->band_start, drop);
3425 if (!node->sched)
3426 return -1;
3429 return 0;
3432 /* Split the current graph into two parts and compute a schedule for each
3433 * part individually. In particular, one part consists of all SCCs up
3434 * to and including graph->src_scc, while the other part contains the other
3435 * SCCs. The split is enforced by a sequence node inserted at position "node"
3436 * in the schedule tree. Return the updated schedule node.
3437 * If either of these two parts consists of a sequence, then it is spliced
3438 * into the sequence containing the two parts.
3440 * The current band is reset. It would be possible to reuse
3441 * the previously computed rows as the first rows in the next
3442 * band, but recomputing them may result in better rows as we are looking
3443 * at a smaller part of the dependence graph.
3445 static __isl_give isl_schedule_node *compute_split_schedule(
3446 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3448 int is_seq;
3449 isl_ctx *ctx;
3450 isl_union_set_list *filters;
3452 if (!node)
3453 return NULL;
3455 if (reset_band(graph) < 0)
3456 return isl_schedule_node_free(node);
3458 next_band(graph);
3460 ctx = isl_schedule_node_get_ctx(node);
3461 filters = extract_split(ctx, graph);
3462 node = isl_schedule_node_insert_sequence(node, filters);
3463 node = isl_schedule_node_child(node, 1);
3464 node = isl_schedule_node_child(node, 0);
3466 node = compute_sub_schedule(node, ctx, graph,
3467 &node_scc_at_least, &edge_src_scc_at_least,
3468 graph->src_scc + 1, 0);
3469 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3470 node = isl_schedule_node_parent(node);
3471 node = isl_schedule_node_parent(node);
3472 if (is_seq)
3473 node = isl_schedule_node_sequence_splice_child(node, 1);
3474 node = isl_schedule_node_child(node, 0);
3475 node = isl_schedule_node_child(node, 0);
3476 node = compute_sub_schedule(node, ctx, graph,
3477 &node_scc_at_most, &edge_dst_scc_at_most,
3478 graph->src_scc, 0);
3479 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3480 node = isl_schedule_node_parent(node);
3481 node = isl_schedule_node_parent(node);
3482 if (is_seq)
3483 node = isl_schedule_node_sequence_splice_child(node, 0);
3485 return node;
3488 /* Insert a band node at position "node" in the schedule tree corresponding
3489 * to the current band in "graph". Mark the band node permutable
3490 * if "permutable" is set.
3491 * The partial schedules and the coincidence property are extracted
3492 * from the graph nodes.
3493 * Return the updated schedule node.
3495 static __isl_give isl_schedule_node *insert_current_band(
3496 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3497 int permutable)
3499 int i;
3500 int start, end, n;
3501 isl_multi_aff *ma;
3502 isl_multi_pw_aff *mpa;
3503 isl_multi_union_pw_aff *mupa;
3505 if (!node)
3506 return NULL;
3508 if (graph->n < 1)
3509 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3510 "graph should have at least one node",
3511 return isl_schedule_node_free(node));
3513 start = graph->band_start;
3514 end = graph->n_total_row;
3515 n = end - start;
3517 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3518 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3519 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3521 for (i = 1; i < graph->n; ++i) {
3522 isl_multi_union_pw_aff *mupa_i;
3524 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3525 start, n);
3526 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3527 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3528 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3530 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3532 for (i = 0; i < n; ++i)
3533 node = isl_schedule_node_band_member_set_coincident(node, i,
3534 graph->node[0].coincident[start + i]);
3535 node = isl_schedule_node_band_set_permutable(node, permutable);
3537 return node;
3540 /* Update the dependence relations based on the current schedule,
3541 * add the current band to "node" and then continue with the computation
3542 * of the next band.
3543 * Return the updated schedule node.
3545 static __isl_give isl_schedule_node *compute_next_band(
3546 __isl_take isl_schedule_node *node,
3547 struct isl_sched_graph *graph, int permutable)
3549 isl_ctx *ctx;
3551 if (!node)
3552 return NULL;
3554 ctx = isl_schedule_node_get_ctx(node);
3555 if (update_edges(ctx, graph) < 0)
3556 return isl_schedule_node_free(node);
3557 node = insert_current_band(node, graph, permutable);
3558 next_band(graph);
3560 node = isl_schedule_node_child(node, 0);
3561 node = compute_schedule(node, graph);
3562 node = isl_schedule_node_parent(node);
3564 return node;
3567 /* Add the constraints "coef" derived from an edge from "node" to itself
3568 * to graph->lp in order to respect the dependences and to try and carry them.
3569 * "pos" is the sequence number of the edge that needs to be carried.
3570 * "coef" represents general constraints on coefficients (c_0, c_n, c_x)
3571 * of valid constraints for (y - x) with x and y instances of the node.
3573 * The constraints added to graph->lp need to enforce
3575 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3576 * = c_j_x (y - x) >= e_i
3578 * for each (x,y) in the dependence relation of the edge.
3579 * That is, (-e_i, 0, c_j_x) needs to be plugged in for (c_0, c_n, c_x),
3580 * taking into account that each coefficient in c_j_x is represented
3581 * as a pair of non-negative coefficients.
3583 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3584 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3586 int offset;
3587 isl_ctx *ctx;
3588 isl_dim_map *dim_map;
3590 if (!coef)
3591 return isl_stat_error;
3593 ctx = isl_basic_set_get_ctx(coef);
3594 offset = coef_var_offset(coef);
3595 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3596 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3597 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3599 return isl_stat_ok;
3602 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3603 * to graph->lp in order to respect the dependences and to try and carry them.
3604 * "pos" is the sequence number of the edge that needs to be carried.
3605 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3606 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3608 * The constraints added to graph->lp need to enforce
3610 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3612 * for each (x,y) in the dependence relation of the edge.
3613 * That is,
3614 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3615 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3616 * taking into account that each coefficient in c_j_x and c_k_x is represented
3617 * as a pair of non-negative coefficients.
3619 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3620 struct isl_sched_node *src, struct isl_sched_node *dst,
3621 __isl_take isl_basic_set *coef, int pos)
3623 int offset;
3624 isl_ctx *ctx;
3625 isl_dim_map *dim_map;
3627 if (!coef)
3628 return isl_stat_error;
3630 ctx = isl_basic_set_get_ctx(coef);
3631 offset = coef_var_offset(coef);
3632 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3633 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3634 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3636 return isl_stat_ok;
3639 /* Data structure collecting information used during the construction
3640 * of an LP for carrying dependences.
3642 * "intra" is a sequence of coefficient constraints for intra-node edges.
3643 * "inter" is a sequence of coefficient constraints for inter-node edges.
3645 struct isl_carry {
3646 isl_basic_set_list *intra;
3647 isl_basic_set_list *inter;
3650 /* Free all the data stored in "carry".
3652 static void isl_carry_clear(struct isl_carry *carry)
3654 isl_basic_set_list_free(carry->intra);
3655 isl_basic_set_list_free(carry->inter);
3658 /* Return a pointer to the node in "graph" that lives in "space".
3659 * If the requested node has been compressed, then "space"
3660 * corresponds to the compressed space.
3662 * First try and see if "space" is the space of an uncompressed node.
3663 * If so, return that node.
3664 * Otherwise, "space" was constructed by construct_compressed_id and
3665 * contains a user pointer pointing to the node in the tuple id.
3667 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3668 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3670 isl_id *id;
3671 struct isl_sched_node *node;
3673 if (!space)
3674 return NULL;
3676 node = graph_find_node(ctx, graph, space);
3677 if (node)
3678 return node;
3680 id = isl_space_get_tuple_id(space, isl_dim_set);
3681 node = isl_id_get_user(id);
3682 isl_id_free(id);
3684 if (!node)
3685 return NULL;
3687 if (!(node >= &graph->node[0] && node < &graph->node[graph->n]))
3688 isl_die(ctx, isl_error_internal,
3689 "space points to invalid node", return NULL);
3691 return node;
3694 /* Internal data structure for add_all_constraints.
3696 * "graph" is the schedule constraint graph for which an LP problem
3697 * is being constructed.
3698 * "pos" is the position of the next edge that needs to be carried.
3700 struct isl_add_all_constraints_data {
3701 isl_ctx *ctx;
3702 struct isl_sched_graph *graph;
3703 int pos;
3706 /* Add the constraints "coef" derived from an edge from a node to itself
3707 * to data->graph->lp in order to respect the dependences and
3708 * to try and carry them.
3710 * The space of "coef" is of the form
3712 * coefficients[[c_cst, c_n] -> S[c_x]]
3714 * with S[c_x] the (compressed) space of the node.
3715 * Extract the node from the space and call add_intra_constraints.
3717 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3719 struct isl_add_all_constraints_data *data = user;
3720 isl_space *space;
3721 struct isl_sched_node *node;
3723 space = isl_basic_set_get_space(coef);
3724 space = isl_space_range(isl_space_unwrap(space));
3725 node = graph_find_compressed_node(data->ctx, data->graph, space);
3726 isl_space_free(space);
3727 return add_intra_constraints(data->graph, node, coef, data->pos++);
3730 /* Add the constraints "coef" derived from an edge from a node j
3731 * to a node k to data->graph->lp in order to respect the dependences and
3732 * to try and carry them.
3734 * The space of "coef" is of the form
3736 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3738 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3739 * Extract the nodes from the space and call add_inter_constraints.
3741 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3743 struct isl_add_all_constraints_data *data = user;
3744 isl_space *space, *dom;
3745 struct isl_sched_node *src, *dst;
3747 space = isl_basic_set_get_space(coef);
3748 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3749 dom = isl_space_domain(isl_space_copy(space));
3750 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3751 isl_space_free(dom);
3752 space = isl_space_range(space);
3753 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3754 isl_space_free(space);
3756 return add_inter_constraints(data->graph, src, dst, coef, data->pos++);
3759 /* Add constraints to graph->lp that force all (conditional) validity
3760 * dependences to be respected and attempt to carry them.
3761 * "intra" is the sequence of coefficient constraints for intra-node edges.
3762 * "inter" is the sequence of coefficient constraints for inter-node edges.
3764 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3765 __isl_keep isl_basic_set_list *intra,
3766 __isl_keep isl_basic_set_list *inter)
3768 struct isl_add_all_constraints_data data = { ctx, graph };
3770 data.pos = 0;
3771 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3772 return isl_stat_error;
3773 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3774 return isl_stat_error;
3775 return isl_stat_ok;
3778 /* Internal data structure for count_all_constraints
3779 * for keeping track of the number of equality and inequality constraints.
3781 struct isl_sched_count {
3782 int n_eq;
3783 int n_ineq;
3786 /* Add the number of equality and inequality constraints of "bset"
3787 * to data->n_eq and data->n_ineq.
3789 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
3791 struct isl_sched_count *data = user;
3793 data->n_eq += isl_basic_set_n_equality(bset);
3794 data->n_ineq += isl_basic_set_n_inequality(bset);
3795 isl_basic_set_free(bset);
3797 return isl_stat_ok;
3800 /* Count the number of equality and inequality constraints
3801 * that will be added to the carry_lp problem.
3802 * We count each edge exactly once.
3803 * "intra" is the sequence of coefficient constraints for intra-node edges.
3804 * "inter" is the sequence of coefficient constraints for inter-node edges.
3806 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
3807 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
3809 struct isl_sched_count data;
3811 data.n_eq = data.n_ineq = 0;
3812 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
3813 return isl_stat_error;
3814 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
3815 return isl_stat_error;
3817 *n_eq = data.n_eq;
3818 *n_ineq = data.n_ineq;
3820 return isl_stat_ok;
3823 /* Construct an LP problem for finding schedule coefficients
3824 * such that the schedule carries as many validity dependences as possible.
3825 * In particular, for each dependence i, we bound the dependence distance
3826 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3827 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3828 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3829 * "intra" is the sequence of coefficient constraints for intra-node edges.
3830 * "inter" is the sequence of coefficient constraints for inter-node edges.
3831 * "n_edge" is the total number of edges.
3833 * All variables of the LP are non-negative. The actual coefficients
3834 * may be negative, so each coefficient is represented as the difference
3835 * of two non-negative variables. The negative part always appears
3836 * immediately before the positive part.
3837 * Other than that, the variables have the following order
3839 * - sum of (1 - e_i) over all edges
3840 * - sum of all c_n coefficients
3841 * (unconstrained when computing non-parametric schedules)
3842 * - sum of positive and negative parts of all c_x coefficients
3843 * - for each edge
3844 * - e_i
3845 * - for each node
3846 * - c_i_0
3847 * - c_i_n (if parametric)
3848 * - positive and negative parts of c_i_x
3850 * The constraints are those from the (validity) edges plus three equalities
3851 * to express the sums and n_edge inequalities to express e_i <= 1.
3853 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
3854 int n_edge, __isl_keep isl_basic_set_list *intra,
3855 __isl_keep isl_basic_set_list *inter)
3857 int i;
3858 int k;
3859 isl_space *dim;
3860 unsigned total;
3861 int n_eq, n_ineq;
3863 total = 3 + n_edge;
3864 for (i = 0; i < graph->n; ++i) {
3865 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3866 node->start = total;
3867 total += 1 + node->nparam + 2 * node->nvar;
3870 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
3871 return isl_stat_error;
3873 dim = isl_space_set_alloc(ctx, 0, total);
3874 isl_basic_set_free(graph->lp);
3875 n_eq += 3;
3876 n_ineq += n_edge;
3877 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3878 graph->lp = isl_basic_set_set_rational(graph->lp);
3880 k = isl_basic_set_alloc_equality(graph->lp);
3881 if (k < 0)
3882 return isl_stat_error;
3883 isl_seq_clr(graph->lp->eq[k], 1 + total);
3884 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3885 isl_int_set_si(graph->lp->eq[k][1], 1);
3886 for (i = 0; i < n_edge; ++i)
3887 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3889 if (add_param_sum_constraint(graph, 1) < 0)
3890 return isl_stat_error;
3891 if (add_var_sum_constraint(graph, 2) < 0)
3892 return isl_stat_error;
3894 for (i = 0; i < n_edge; ++i) {
3895 k = isl_basic_set_alloc_inequality(graph->lp);
3896 if (k < 0)
3897 return isl_stat_error;
3898 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3899 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3900 isl_int_set_si(graph->lp->ineq[k][0], 1);
3903 if (add_all_constraints(ctx, graph, intra, inter) < 0)
3904 return isl_stat_error;
3906 return isl_stat_ok;
3909 static __isl_give isl_schedule_node *compute_component_schedule(
3910 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3911 int wcc);
3913 /* Comparison function for sorting the statements based on
3914 * the corresponding value in "r".
3916 static int smaller_value(const void *a, const void *b, void *data)
3918 isl_vec *r = data;
3919 const int *i1 = a;
3920 const int *i2 = b;
3922 return isl_int_cmp(r->el[*i1], r->el[*i2]);
3925 /* If the schedule_split_scaled option is set and if the linear
3926 * parts of the scheduling rows for all nodes in the graphs have
3927 * a non-trivial common divisor, then split off the remainder of the
3928 * constant term modulo this common divisor from the linear part.
3929 * Otherwise, insert a band node directly and continue with
3930 * the construction of the schedule.
3932 * If a non-trivial common divisor is found, then
3933 * the linear part is reduced and the remainder is enforced
3934 * by a sequence node with the children placed in the order
3935 * of this remainder.
3936 * In particular, we assign an scc index based on the remainder and
3937 * then rely on compute_component_schedule to insert the sequence and
3938 * to continue the schedule construction on each part.
3940 static __isl_give isl_schedule_node *split_scaled(
3941 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3943 int i;
3944 int row;
3945 int scc;
3946 isl_ctx *ctx;
3947 isl_int gcd, gcd_i;
3948 isl_vec *r;
3949 int *order;
3951 if (!node)
3952 return NULL;
3954 ctx = isl_schedule_node_get_ctx(node);
3955 if (!ctx->opt->schedule_split_scaled)
3956 return compute_next_band(node, graph, 0);
3957 if (graph->n <= 1)
3958 return compute_next_band(node, graph, 0);
3960 isl_int_init(gcd);
3961 isl_int_init(gcd_i);
3963 isl_int_set_si(gcd, 0);
3965 row = isl_mat_rows(graph->node[0].sched) - 1;
3967 for (i = 0; i < graph->n; ++i) {
3968 struct isl_sched_node *node = &graph->node[i];
3969 int cols = isl_mat_cols(node->sched);
3971 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3972 isl_int_gcd(gcd, gcd, gcd_i);
3975 isl_int_clear(gcd_i);
3977 if (isl_int_cmp_si(gcd, 1) <= 0) {
3978 isl_int_clear(gcd);
3979 return compute_next_band(node, graph, 0);
3982 r = isl_vec_alloc(ctx, graph->n);
3983 order = isl_calloc_array(ctx, int, graph->n);
3984 if (!r || !order)
3985 goto error;
3987 for (i = 0; i < graph->n; ++i) {
3988 struct isl_sched_node *node = &graph->node[i];
3990 order[i] = i;
3991 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
3992 isl_int_fdiv_q(node->sched->row[row][0],
3993 node->sched->row[row][0], gcd);
3994 isl_int_mul(node->sched->row[row][0],
3995 node->sched->row[row][0], gcd);
3996 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3997 if (!node->sched)
3998 goto error;
4001 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
4002 goto error;
4004 scc = 0;
4005 for (i = 0; i < graph->n; ++i) {
4006 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
4007 ++scc;
4008 graph->node[order[i]].scc = scc;
4010 graph->scc = ++scc;
4011 graph->weak = 0;
4013 isl_int_clear(gcd);
4014 isl_vec_free(r);
4015 free(order);
4017 if (update_edges(ctx, graph) < 0)
4018 return isl_schedule_node_free(node);
4019 node = insert_current_band(node, graph, 0);
4020 next_band(graph);
4022 node = isl_schedule_node_child(node, 0);
4023 node = compute_component_schedule(node, graph, 0);
4024 node = isl_schedule_node_parent(node);
4026 return node;
4027 error:
4028 isl_vec_free(r);
4029 free(order);
4030 isl_int_clear(gcd);
4031 return isl_schedule_node_free(node);
4034 /* Is the schedule row "sol" trivial on node "node"?
4035 * That is, is the solution zero on the dimensions linearly independent of
4036 * the previously found solutions?
4037 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4039 * Each coefficient is represented as the difference between
4040 * two non-negative values in "sol". "sol" has been computed
4041 * in terms of the original iterators (i.e., without use of cmap).
4042 * We construct the schedule row s and write it as a linear
4043 * combination of (linear combinations of) previously computed schedule rows.
4044 * s = Q c or c = U s.
4045 * If the final entries of c are all zero, then the solution is trivial.
4047 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4049 int trivial;
4050 isl_vec *node_sol;
4052 if (!sol)
4053 return -1;
4054 if (node->nvar == node->rank)
4055 return 0;
4057 node_sol = extract_var_coef(node, sol);
4058 node_sol = isl_mat_vec_product(isl_mat_copy(node->cinv), node_sol);
4059 if (!node_sol)
4060 return -1;
4062 trivial = isl_seq_first_non_zero(node_sol->el + node->rank,
4063 node->nvar - node->rank) == -1;
4065 isl_vec_free(node_sol);
4067 return trivial;
4070 /* Is the schedule row "sol" trivial on any node where it should
4071 * not be trivial?
4072 * "sol" has been computed in terms of the original iterators
4073 * (i.e., without use of cmap).
4074 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4076 static int is_any_trivial(struct isl_sched_graph *graph,
4077 __isl_keep isl_vec *sol)
4079 int i;
4081 for (i = 0; i < graph->n; ++i) {
4082 struct isl_sched_node *node = &graph->node[i];
4083 int trivial;
4085 if (!needs_row(graph, node))
4086 continue;
4087 trivial = is_trivial(node, sol);
4088 if (trivial < 0 || trivial)
4089 return trivial;
4092 return 0;
4095 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4096 * If so, return the position of the coalesced dimension.
4097 * Otherwise, return node->nvar or -1 on error.
4099 * In particular, look for pairs of coefficients c_i and c_j such that
4100 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
4101 * If any such pair is found, then return i.
4102 * If size_i is infinity, then no check on c_i needs to be performed.
4104 static int find_node_coalescing(struct isl_sched_node *node,
4105 __isl_keep isl_vec *sol)
4107 int i, j;
4108 isl_int max;
4109 isl_vec *csol;
4111 if (node->nvar <= 1)
4112 return node->nvar;
4114 csol = extract_var_coef(node, sol);
4115 if (!csol)
4116 return -1;
4117 isl_int_init(max);
4118 for (i = 0; i < node->nvar; ++i) {
4119 isl_val *v;
4121 if (isl_int_is_zero(csol->el[i]))
4122 continue;
4123 v = isl_multi_val_get_val(node->sizes, i);
4124 if (!v)
4125 goto error;
4126 if (!isl_val_is_int(v)) {
4127 isl_val_free(v);
4128 continue;
4130 isl_int_mul(max, v->n, csol->el[i]);
4131 isl_val_free(v);
4133 for (j = 0; j < node->nvar; ++j) {
4134 if (j == i)
4135 continue;
4136 if (isl_int_abs_ge(csol->el[j], max))
4137 break;
4139 if (j < node->nvar)
4140 break;
4143 isl_int_clear(max);
4144 isl_vec_free(csol);
4145 return i;
4146 error:
4147 isl_int_clear(max);
4148 isl_vec_free(csol);
4149 return -1;
4152 /* Force the schedule coefficient at position "pos" of "node" to be zero
4153 * in "tl".
4154 * The coefficient is encoded as the difference between two non-negative
4155 * variables. Force these two variables to have the same value.
4157 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4158 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4160 int dim;
4161 isl_ctx *ctx;
4162 isl_vec *eq;
4164 ctx = isl_space_get_ctx(node->space);
4165 dim = isl_tab_lexmin_dim(tl);
4166 if (dim < 0)
4167 return isl_tab_lexmin_free(tl);
4168 eq = isl_vec_alloc(ctx, 1 + dim);
4169 eq = isl_vec_clr(eq);
4170 if (!eq)
4171 return isl_tab_lexmin_free(tl);
4173 pos = 1 + node_var_coef_pos(node, pos);
4174 isl_int_set_si(eq->el[pos], 1);
4175 isl_int_set_si(eq->el[pos + 1], -1);
4176 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4177 isl_vec_free(eq);
4179 return tl;
4182 /* Return the lexicographically smallest rational point in the basic set
4183 * from which "tl" was constructed, double checking that this input set
4184 * was not empty.
4186 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4188 isl_vec *sol;
4190 sol = isl_tab_lexmin_get_solution(tl);
4191 if (!sol)
4192 return NULL;
4193 if (sol->size == 0)
4194 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4195 "error in schedule construction",
4196 return isl_vec_free(sol));
4197 return sol;
4200 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4201 * carry any of the "n_edge" groups of dependences?
4202 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4203 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4204 * by the edge are carried by the solution.
4205 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4206 * one of those is carried.
4208 * Note that despite the fact that the problem is solved using a rational
4209 * solver, the solution is guaranteed to be integral.
4210 * Specifically, the dependence distance lower bounds e_i (and therefore
4211 * also their sum) are integers. See Lemma 5 of [1].
4213 * Any potential denominator of the sum is cleared by this function.
4214 * The denominator is not relevant for any of the other elements
4215 * in the solution.
4217 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4218 * Problem, Part II: Multi-Dimensional Time.
4219 * In Intl. Journal of Parallel Programming, 1992.
4221 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4223 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4224 isl_int_set_si(sol->el[0], 1);
4225 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4228 /* Return the lexicographically smallest rational point in "lp",
4229 * assuming that all variables are non-negative and performing some
4230 * additional sanity checks.
4231 * If "want_integral" is set, then compute the lexicographically smallest
4232 * integer point instead.
4233 * In particular, "lp" should not be empty by construction.
4234 * Double check that this is the case.
4235 * If dependences are not carried for any of the "n_edge" edges,
4236 * then return an empty vector.
4238 * If the schedule_treat_coalescing option is set and
4239 * if the computed schedule performs loop coalescing on a given node,
4240 * i.e., if it is of the form
4242 * c_i i + c_j j + ...
4244 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4245 * to cut out this solution. Repeat this process until no more loop
4246 * coalescing occurs or until no more dependences can be carried.
4247 * In the latter case, revert to the previously computed solution.
4249 * If the caller requests an integral solution and if coalescing should
4250 * be treated, then perform the coalescing treatment first as
4251 * an integral solution computed before coalescing treatment
4252 * would carry the same number of edges and would therefore probably
4253 * also be coalescing.
4255 * To allow the coalescing treatment to be performed first,
4256 * the initial solution is allowed to be rational and it is only
4257 * cut out (if needed) in the next iteration, if no coalescing measures
4258 * were taken.
4260 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4261 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4263 int i, pos, cut;
4264 isl_ctx *ctx;
4265 isl_tab_lexmin *tl;
4266 isl_vec *sol, *prev = NULL;
4267 int treat_coalescing;
4269 if (!lp)
4270 return NULL;
4271 ctx = isl_basic_set_get_ctx(lp);
4272 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4273 tl = isl_tab_lexmin_from_basic_set(lp);
4275 cut = 0;
4276 do {
4277 int integral;
4279 if (cut)
4280 tl = isl_tab_lexmin_cut_to_integer(tl);
4281 sol = non_empty_solution(tl);
4282 if (!sol)
4283 goto error;
4285 integral = isl_int_is_one(sol->el[0]);
4286 if (!carries_dependences(sol, n_edge)) {
4287 if (!prev)
4288 prev = isl_vec_alloc(ctx, 0);
4289 isl_vec_free(sol);
4290 sol = prev;
4291 break;
4293 prev = isl_vec_free(prev);
4294 cut = want_integral && !integral;
4295 if (cut)
4296 prev = sol;
4297 if (!treat_coalescing)
4298 continue;
4299 for (i = 0; i < graph->n; ++i) {
4300 struct isl_sched_node *node = &graph->node[i];
4302 pos = find_node_coalescing(node, sol);
4303 if (pos < 0)
4304 goto error;
4305 if (pos < node->nvar)
4306 break;
4308 if (i < graph->n) {
4309 prev = sol;
4310 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4311 cut = 0;
4313 } while (prev);
4315 isl_tab_lexmin_free(tl);
4317 return sol;
4318 error:
4319 isl_tab_lexmin_free(tl);
4320 isl_vec_free(prev);
4321 isl_vec_free(sol);
4322 return NULL;
4325 /* If "edge" is an edge from a node to itself, then add the corresponding
4326 * dependence relation to "umap".
4327 * If "node" has been compressed, then the dependence relation
4328 * is also compressed first.
4330 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4331 struct isl_sched_edge *edge)
4333 isl_map *map;
4334 struct isl_sched_node *node = edge->src;
4336 if (edge->src != edge->dst)
4337 return umap;
4339 map = isl_map_copy(edge->map);
4340 if (node->compressed) {
4341 map = isl_map_preimage_domain_multi_aff(map,
4342 isl_multi_aff_copy(node->decompress));
4343 map = isl_map_preimage_range_multi_aff(map,
4344 isl_multi_aff_copy(node->decompress));
4346 umap = isl_union_map_add_map(umap, map);
4347 return umap;
4350 /* If "edge" is an edge from a node to another node, then add the corresponding
4351 * dependence relation to "umap".
4352 * If the source or destination nodes of "edge" have been compressed,
4353 * then the dependence relation is also compressed first.
4355 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4356 struct isl_sched_edge *edge)
4358 isl_map *map;
4360 if (edge->src == edge->dst)
4361 return umap;
4363 map = isl_map_copy(edge->map);
4364 if (edge->src->compressed)
4365 map = isl_map_preimage_domain_multi_aff(map,
4366 isl_multi_aff_copy(edge->src->decompress));
4367 if (edge->dst->compressed)
4368 map = isl_map_preimage_range_multi_aff(map,
4369 isl_multi_aff_copy(edge->dst->decompress));
4370 umap = isl_union_map_add_map(umap, map);
4371 return umap;
4374 /* For each (conditional) validity edge in "graph",
4375 * add the corresponding dependence relation using "add"
4376 * to a collection of dependence relations and return the result.
4377 * If "coincidence" is set, then coincidence edges are considered as well.
4379 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4380 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4381 struct isl_sched_edge *edge), int coincidence)
4383 int i;
4384 isl_space *space;
4385 isl_union_map *umap;
4387 space = isl_space_copy(graph->node[0].space);
4388 umap = isl_union_map_empty(space);
4390 for (i = 0; i < graph->n_edge; ++i) {
4391 struct isl_sched_edge *edge = &graph->edge[i];
4393 if (!is_any_validity(edge) &&
4394 (!coincidence || !is_coincidence(edge)))
4395 continue;
4397 umap = add(umap, edge);
4400 return umap;
4403 /* For each dependence relation on a (conditional) validity edge
4404 * from a node to itself,
4405 * construct the set of coefficients of valid constraints for elements
4406 * in that dependence relation and collect the results.
4407 * If "coincidence" is set, then coincidence edges are considered as well.
4409 * In particular, for each dependence relation R, constraints
4410 * on coefficients (c_0, c_n, c_x) are constructed such that
4412 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4414 * This computation is essentially the same as that performed
4415 * by intra_coefficients, except that it operates on multiple
4416 * edges together.
4418 * Note that if a dependence relation is a union of basic maps,
4419 * then each basic map needs to be treated individually as it may only
4420 * be possible to carry the dependences expressed by some of those
4421 * basic maps and not all of them.
4422 * The collected validity constraints are therefore not coalesced and
4423 * it is assumed that they are not coalesced automatically.
4424 * Duplicate basic maps can be removed, however.
4425 * In particular, if the same basic map appears as a disjunct
4426 * in multiple edges, then it only needs to be carried once.
4428 static __isl_give isl_basic_set_list *collect_intra_validity(
4429 struct isl_sched_graph *graph, int coincidence)
4431 isl_union_map *intra;
4432 isl_union_set *delta;
4433 isl_basic_set_list *list;
4435 intra = collect_validity(graph, &add_intra, coincidence);
4436 delta = isl_union_map_deltas(intra);
4437 delta = isl_union_set_remove_divs(delta);
4438 list = isl_union_set_get_basic_set_list(delta);
4439 isl_union_set_free(delta);
4441 return isl_basic_set_list_coefficients(list);
4444 /* For each dependence relation on a (conditional) validity edge
4445 * from a node to some other node,
4446 * construct the set of coefficients of valid constraints for elements
4447 * in that dependence relation and collect the results.
4448 * If "coincidence" is set, then coincidence edges are considered as well.
4450 * In particular, for each dependence relation R, constraints
4451 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4453 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4455 * This computation is essentially the same as that performed
4456 * by inter_coefficients, except that it operates on multiple
4457 * edges together.
4459 * Note that if a dependence relation is a union of basic maps,
4460 * then each basic map needs to be treated individually as it may only
4461 * be possible to carry the dependences expressed by some of those
4462 * basic maps and not all of them.
4463 * The collected validity constraints are therefore not coalesced and
4464 * it is assumed that they are not coalesced automatically.
4465 * Duplicate basic maps can be removed, however.
4466 * In particular, if the same basic map appears as a disjunct
4467 * in multiple edges, then it only needs to be carried once.
4469 static __isl_give isl_basic_set_list *collect_inter_validity(
4470 struct isl_sched_graph *graph, int coincidence)
4472 isl_union_map *inter;
4473 isl_union_set *wrap;
4474 isl_basic_set_list *list;
4476 inter = collect_validity(graph, &add_inter, coincidence);
4477 inter = isl_union_map_remove_divs(inter);
4478 wrap = isl_union_map_wrap(inter);
4479 list = isl_union_set_get_basic_set_list(wrap);
4480 isl_union_set_free(wrap);
4481 return isl_basic_set_list_coefficients(list);
4484 /* Construct an LP problem for finding schedule coefficients
4485 * such that the schedule carries as many of the validity dependences
4486 * as possible and
4487 * return the lexicographically smallest non-trivial solution.
4488 * If "fallback" is set, then the carrying is performed as a fallback
4489 * for the Pluto-like scheduler.
4490 * If "coincidence" is set, then try and carry coincidence edges as well.
4492 * The variable "n_edge" stores the number of groups that should be carried.
4493 * If none of the "n_edge" groups can be carried
4494 * then return an empty vector.
4495 * If, moreover, "n_edge" is zero, then the LP problem does not even
4496 * need to be constructed.
4498 * If a fallback solution is being computed, then compute an integral solution
4499 * for the coefficients rather than using the numerators
4500 * of a rational solution.
4502 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4503 struct isl_sched_graph *graph, int fallback, int coincidence)
4505 int n_intra, n_inter;
4506 int n_edge;
4507 isl_basic_set *lp;
4508 struct isl_carry carry = { 0 };
4510 carry.intra = collect_intra_validity(graph, coincidence);
4511 carry.inter = collect_inter_validity(graph, coincidence);
4512 if (!carry.intra || !carry.inter)
4513 goto error;
4514 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4515 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4516 n_edge = n_intra + n_inter;
4517 if (n_edge == 0) {
4518 isl_carry_clear(&carry);
4519 return isl_vec_alloc(ctx, 0);
4522 if (setup_carry_lp(ctx, graph, n_edge, carry.intra, carry.inter) < 0)
4523 goto error;
4525 isl_carry_clear(&carry);
4526 lp = isl_basic_set_copy(graph->lp);
4527 return non_neg_lexmin(graph, lp, n_edge, fallback);
4528 error:
4529 isl_carry_clear(&carry);
4530 return NULL;
4533 /* Construct a schedule row for each node such that as many validity dependences
4534 * as possible are carried and then continue with the next band.
4535 * If "fallback" is set, then the carrying is performed as a fallback
4536 * for the Pluto-like scheduler.
4537 * If "coincidence" is set, then try and carry coincidence edges as well.
4539 * If there are no validity dependences, then no dependence can be carried and
4540 * the procedure is guaranteed to fail. If there is more than one component,
4541 * then try computing a schedule on each component separately
4542 * to prevent or at least postpone this failure.
4544 * If a schedule row is computed, then check that dependences are carried
4545 * for at least one of the edges.
4547 * If the computed schedule row turns out to be trivial on one or
4548 * more nodes where it should not be trivial, then we throw it away
4549 * and try again on each component separately.
4551 * If there is only one component, then we accept the schedule row anyway,
4552 * but we do not consider it as a complete row and therefore do not
4553 * increment graph->n_row. Note that the ranks of the nodes that
4554 * do get a non-trivial schedule part will get updated regardless and
4555 * graph->maxvar is computed based on these ranks. The test for
4556 * whether more schedule rows are required in compute_schedule_wcc
4557 * is therefore not affected.
4559 * Insert a band corresponding to the schedule row at position "node"
4560 * of the schedule tree and continue with the construction of the schedule.
4561 * This insertion and the continued construction is performed by split_scaled
4562 * after optionally checking for non-trivial common divisors.
4564 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
4565 struct isl_sched_graph *graph, int fallback, int coincidence)
4567 int trivial;
4568 isl_ctx *ctx;
4569 isl_vec *sol;
4571 if (!node)
4572 return NULL;
4574 ctx = isl_schedule_node_get_ctx(node);
4575 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
4576 if (!sol)
4577 return isl_schedule_node_free(node);
4578 if (sol->size == 0) {
4579 isl_vec_free(sol);
4580 if (graph->scc > 1)
4581 return compute_component_schedule(node, graph, 1);
4582 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
4583 return isl_schedule_node_free(node));
4586 trivial = is_any_trivial(graph, sol);
4587 if (trivial < 0) {
4588 sol = isl_vec_free(sol);
4589 } else if (trivial && graph->scc > 1) {
4590 isl_vec_free(sol);
4591 return compute_component_schedule(node, graph, 1);
4594 if (update_schedule(graph, sol, 0, 0) < 0)
4595 return isl_schedule_node_free(node);
4596 if (trivial)
4597 graph->n_row--;
4599 return split_scaled(node, graph);
4602 /* Construct a schedule row for each node such that as many validity dependences
4603 * as possible are carried and then continue with the next band.
4604 * Do so as a fallback for the Pluto-like scheduler.
4605 * If "coincidence" is set, then try and carry coincidence edges as well.
4607 static __isl_give isl_schedule_node *carry_fallback(
4608 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4609 int coincidence)
4611 return carry(node, graph, 1, coincidence);
4614 /* Construct a schedule row for each node such that as many validity dependences
4615 * as possible are carried and then continue with the next band.
4616 * Do so for the case where the Feautrier scheduler was selected
4617 * by the user.
4619 static __isl_give isl_schedule_node *carry_feautrier(
4620 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4622 return carry(node, graph, 0, 0);
4625 /* Construct a schedule row for each node such that as many validity dependences
4626 * as possible are carried and then continue with the next band.
4627 * Do so as a fallback for the Pluto-like scheduler.
4629 static __isl_give isl_schedule_node *carry_dependences(
4630 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4632 return carry_fallback(node, graph, 0);
4635 /* Construct a schedule row for each node such that as many validity or
4636 * coincidence dependences as possible are carried and
4637 * then continue with the next band.
4638 * Do so as a fallback for the Pluto-like scheduler.
4640 static __isl_give isl_schedule_node *carry_coincidence(
4641 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4643 return carry_fallback(node, graph, 1);
4646 /* Topologically sort statements mapped to the same schedule iteration
4647 * and add insert a sequence node in front of "node"
4648 * corresponding to this order.
4649 * If "initialized" is set, then it may be assumed that compute_maxvar
4650 * has been called on the current band. Otherwise, call
4651 * compute_maxvar if and before carry_dependences gets called.
4653 * If it turns out to be impossible to sort the statements apart,
4654 * because different dependences impose different orderings
4655 * on the statements, then we extend the schedule such that
4656 * it carries at least one more dependence.
4658 static __isl_give isl_schedule_node *sort_statements(
4659 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4660 int initialized)
4662 isl_ctx *ctx;
4663 isl_union_set_list *filters;
4665 if (!node)
4666 return NULL;
4668 ctx = isl_schedule_node_get_ctx(node);
4669 if (graph->n < 1)
4670 isl_die(ctx, isl_error_internal,
4671 "graph should have at least one node",
4672 return isl_schedule_node_free(node));
4674 if (graph->n == 1)
4675 return node;
4677 if (update_edges(ctx, graph) < 0)
4678 return isl_schedule_node_free(node);
4680 if (graph->n_edge == 0)
4681 return node;
4683 if (detect_sccs(ctx, graph) < 0)
4684 return isl_schedule_node_free(node);
4686 next_band(graph);
4687 if (graph->scc < graph->n) {
4688 if (!initialized && compute_maxvar(graph) < 0)
4689 return isl_schedule_node_free(node);
4690 return carry_dependences(node, graph);
4693 filters = extract_sccs(ctx, graph);
4694 node = isl_schedule_node_insert_sequence(node, filters);
4696 return node;
4699 /* Are there any (non-empty) (conditional) validity edges in the graph?
4701 static int has_validity_edges(struct isl_sched_graph *graph)
4703 int i;
4705 for (i = 0; i < graph->n_edge; ++i) {
4706 int empty;
4708 empty = isl_map_plain_is_empty(graph->edge[i].map);
4709 if (empty < 0)
4710 return -1;
4711 if (empty)
4712 continue;
4713 if (is_any_validity(&graph->edge[i]))
4714 return 1;
4717 return 0;
4720 /* Should we apply a Feautrier step?
4721 * That is, did the user request the Feautrier algorithm and are
4722 * there any validity dependences (left)?
4724 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4726 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4727 return 0;
4729 return has_validity_edges(graph);
4732 /* Compute a schedule for a connected dependence graph using Feautrier's
4733 * multi-dimensional scheduling algorithm and return the updated schedule node.
4735 * The original algorithm is described in [1].
4736 * The main idea is to minimize the number of scheduling dimensions, by
4737 * trying to satisfy as many dependences as possible per scheduling dimension.
4739 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4740 * Problem, Part II: Multi-Dimensional Time.
4741 * In Intl. Journal of Parallel Programming, 1992.
4743 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4744 isl_schedule_node *node, struct isl_sched_graph *graph)
4746 return carry_feautrier(node, graph);
4749 /* Turn off the "local" bit on all (condition) edges.
4751 static void clear_local_edges(struct isl_sched_graph *graph)
4753 int i;
4755 for (i = 0; i < graph->n_edge; ++i)
4756 if (is_condition(&graph->edge[i]))
4757 clear_local(&graph->edge[i]);
4760 /* Does "graph" have both condition and conditional validity edges?
4762 static int need_condition_check(struct isl_sched_graph *graph)
4764 int i;
4765 int any_condition = 0;
4766 int any_conditional_validity = 0;
4768 for (i = 0; i < graph->n_edge; ++i) {
4769 if (is_condition(&graph->edge[i]))
4770 any_condition = 1;
4771 if (is_conditional_validity(&graph->edge[i]))
4772 any_conditional_validity = 1;
4775 return any_condition && any_conditional_validity;
4778 /* Does "graph" contain any coincidence edge?
4780 static int has_any_coincidence(struct isl_sched_graph *graph)
4782 int i;
4784 for (i = 0; i < graph->n_edge; ++i)
4785 if (is_coincidence(&graph->edge[i]))
4786 return 1;
4788 return 0;
4791 /* Extract the final schedule row as a map with the iteration domain
4792 * of "node" as domain.
4794 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4796 isl_multi_aff *ma;
4797 int row;
4799 row = isl_mat_rows(node->sched) - 1;
4800 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
4801 return isl_map_from_multi_aff(ma);
4804 /* Is the conditional validity dependence in the edge with index "edge_index"
4805 * violated by the latest (i.e., final) row of the schedule?
4806 * That is, is i scheduled after j
4807 * for any conditional validity dependence i -> j?
4809 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4811 isl_map *src_sched, *dst_sched, *map;
4812 struct isl_sched_edge *edge = &graph->edge[edge_index];
4813 int empty;
4815 src_sched = final_row(edge->src);
4816 dst_sched = final_row(edge->dst);
4817 map = isl_map_copy(edge->map);
4818 map = isl_map_apply_domain(map, src_sched);
4819 map = isl_map_apply_range(map, dst_sched);
4820 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4821 empty = isl_map_is_empty(map);
4822 isl_map_free(map);
4824 if (empty < 0)
4825 return -1;
4827 return !empty;
4830 /* Does "graph" have any satisfied condition edges that
4831 * are adjacent to the conditional validity constraint with
4832 * domain "conditional_source" and range "conditional_sink"?
4834 * A satisfied condition is one that is not local.
4835 * If a condition was forced to be local already (i.e., marked as local)
4836 * then there is no need to check if it is in fact local.
4838 * Additionally, mark all adjacent condition edges found as local.
4840 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4841 __isl_keep isl_union_set *conditional_source,
4842 __isl_keep isl_union_set *conditional_sink)
4844 int i;
4845 int any = 0;
4847 for (i = 0; i < graph->n_edge; ++i) {
4848 int adjacent, local;
4849 isl_union_map *condition;
4851 if (!is_condition(&graph->edge[i]))
4852 continue;
4853 if (is_local(&graph->edge[i]))
4854 continue;
4856 condition = graph->edge[i].tagged_condition;
4857 adjacent = domain_intersects(condition, conditional_sink);
4858 if (adjacent >= 0 && !adjacent)
4859 adjacent = range_intersects(condition,
4860 conditional_source);
4861 if (adjacent < 0)
4862 return -1;
4863 if (!adjacent)
4864 continue;
4866 set_local(&graph->edge[i]);
4868 local = is_condition_false(&graph->edge[i]);
4869 if (local < 0)
4870 return -1;
4871 if (!local)
4872 any = 1;
4875 return any;
4878 /* Are there any violated conditional validity dependences with
4879 * adjacent condition dependences that are not local with respect
4880 * to the current schedule?
4881 * That is, is the conditional validity constraint violated?
4883 * Additionally, mark all those adjacent condition dependences as local.
4884 * We also mark those adjacent condition dependences that were not marked
4885 * as local before, but just happened to be local already. This ensures
4886 * that they remain local if the schedule is recomputed.
4888 * We first collect domain and range of all violated conditional validity
4889 * dependences and then check if there are any adjacent non-local
4890 * condition dependences.
4892 static int has_violated_conditional_constraint(isl_ctx *ctx,
4893 struct isl_sched_graph *graph)
4895 int i;
4896 int any = 0;
4897 isl_union_set *source, *sink;
4899 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4900 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4901 for (i = 0; i < graph->n_edge; ++i) {
4902 isl_union_set *uset;
4903 isl_union_map *umap;
4904 int violated;
4906 if (!is_conditional_validity(&graph->edge[i]))
4907 continue;
4909 violated = is_violated(graph, i);
4910 if (violated < 0)
4911 goto error;
4912 if (!violated)
4913 continue;
4915 any = 1;
4917 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4918 uset = isl_union_map_domain(umap);
4919 source = isl_union_set_union(source, uset);
4920 source = isl_union_set_coalesce(source);
4922 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4923 uset = isl_union_map_range(umap);
4924 sink = isl_union_set_union(sink, uset);
4925 sink = isl_union_set_coalesce(sink);
4928 if (any)
4929 any = has_adjacent_true_conditions(graph, source, sink);
4931 isl_union_set_free(source);
4932 isl_union_set_free(sink);
4933 return any;
4934 error:
4935 isl_union_set_free(source);
4936 isl_union_set_free(sink);
4937 return -1;
4940 /* Examine the current band (the rows between graph->band_start and
4941 * graph->n_total_row), deciding whether to drop it or add it to "node"
4942 * and then continue with the computation of the next band, if any.
4943 * If "initialized" is set, then it may be assumed that compute_maxvar
4944 * has been called on the current band. Otherwise, call
4945 * compute_maxvar if and before carry_dependences gets called.
4947 * The caller keeps looking for a new row as long as
4948 * graph->n_row < graph->maxvar. If the latest attempt to find
4949 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4950 * then we either
4951 * - split between SCCs and start over (assuming we found an interesting
4952 * pair of SCCs between which to split)
4953 * - continue with the next band (assuming the current band has at least
4954 * one row)
4955 * - if outer coincidence needs to be enforced, then try to carry as many
4956 * validity or coincidence dependences as possible and
4957 * continue with the next band
4958 * - try to carry as many validity dependences as possible and
4959 * continue with the next band
4960 * In each case, we first insert a band node in the schedule tree
4961 * if any rows have been computed.
4963 * If the caller managed to complete the schedule, we insert a band node
4964 * (if any schedule rows were computed) and we finish off by topologically
4965 * sorting the statements based on the remaining dependences.
4967 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4968 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4969 int initialized)
4971 int insert;
4973 if (!node)
4974 return NULL;
4976 if (graph->n_row < graph->maxvar) {
4977 isl_ctx *ctx;
4978 int empty = graph->n_total_row == graph->band_start;
4980 ctx = isl_schedule_node_get_ctx(node);
4981 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4982 return compute_next_band(node, graph, 1);
4983 if (graph->src_scc >= 0)
4984 return compute_split_schedule(node, graph);
4985 if (!empty)
4986 return compute_next_band(node, graph, 1);
4987 if (!initialized && compute_maxvar(graph) < 0)
4988 return isl_schedule_node_free(node);
4989 if (isl_options_get_schedule_outer_coincidence(ctx))
4990 return carry_coincidence(node, graph);
4991 return carry_dependences(node, graph);
4994 insert = graph->n_total_row > graph->band_start;
4995 if (insert) {
4996 node = insert_current_band(node, graph, 1);
4997 node = isl_schedule_node_child(node, 0);
4999 node = sort_statements(node, graph, initialized);
5000 if (insert)
5001 node = isl_schedule_node_parent(node);
5003 return node;
5006 /* Construct a band of schedule rows for a connected dependence graph.
5007 * The caller is responsible for determining the strongly connected
5008 * components and calling compute_maxvar first.
5010 * We try to find a sequence of as many schedule rows as possible that result
5011 * in non-negative dependence distances (independent of the previous rows
5012 * in the sequence, i.e., such that the sequence is tilable), with as
5013 * many of the initial rows as possible satisfying the coincidence constraints.
5014 * The computation stops if we can't find any more rows or if we have found
5015 * all the rows we wanted to find.
5017 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5018 * outermost dimension to satisfy the coincidence constraints. If this
5019 * turns out to be impossible, we fall back on the general scheme above
5020 * and try to carry as many dependences as possible.
5022 * If "graph" contains both condition and conditional validity dependences,
5023 * then we need to check that that the conditional schedule constraint
5024 * is satisfied, i.e., there are no violated conditional validity dependences
5025 * that are adjacent to any non-local condition dependences.
5026 * If there are, then we mark all those adjacent condition dependences
5027 * as local and recompute the current band. Those dependences that
5028 * are marked local will then be forced to be local.
5029 * The initial computation is performed with no dependences marked as local.
5030 * If we are lucky, then there will be no violated conditional validity
5031 * dependences adjacent to any non-local condition dependences.
5032 * Otherwise, we mark some additional condition dependences as local and
5033 * recompute. We continue this process until there are no violations left or
5034 * until we are no longer able to compute a schedule.
5035 * Since there are only a finite number of dependences,
5036 * there will only be a finite number of iterations.
5038 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5039 struct isl_sched_graph *graph)
5041 int has_coincidence;
5042 int use_coincidence;
5043 int force_coincidence = 0;
5044 int check_conditional;
5046 if (sort_sccs(graph) < 0)
5047 return isl_stat_error;
5049 clear_local_edges(graph);
5050 check_conditional = need_condition_check(graph);
5051 has_coincidence = has_any_coincidence(graph);
5053 if (ctx->opt->schedule_outer_coincidence)
5054 force_coincidence = 1;
5056 use_coincidence = has_coincidence;
5057 while (graph->n_row < graph->maxvar) {
5058 isl_vec *sol;
5059 int violated;
5060 int coincident;
5062 graph->src_scc = -1;
5063 graph->dst_scc = -1;
5065 if (setup_lp(ctx, graph, use_coincidence) < 0)
5066 return isl_stat_error;
5067 sol = solve_lp(ctx, graph);
5068 if (!sol)
5069 return isl_stat_error;
5070 if (sol->size == 0) {
5071 int empty = graph->n_total_row == graph->band_start;
5073 isl_vec_free(sol);
5074 if (use_coincidence && (!force_coincidence || !empty)) {
5075 use_coincidence = 0;
5076 continue;
5078 return isl_stat_ok;
5080 coincident = !has_coincidence || use_coincidence;
5081 if (update_schedule(graph, sol, 1, coincident) < 0)
5082 return isl_stat_error;
5084 if (!check_conditional)
5085 continue;
5086 violated = has_violated_conditional_constraint(ctx, graph);
5087 if (violated < 0)
5088 return isl_stat_error;
5089 if (!violated)
5090 continue;
5091 if (reset_band(graph) < 0)
5092 return isl_stat_error;
5093 use_coincidence = has_coincidence;
5096 return isl_stat_ok;
5099 /* Compute a schedule for a connected dependence graph by considering
5100 * the graph as a whole and return the updated schedule node.
5102 * The actual schedule rows of the current band are computed by
5103 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5104 * care of integrating the band into "node" and continuing
5105 * the computation.
5107 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5108 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5110 isl_ctx *ctx;
5112 if (!node)
5113 return NULL;
5115 ctx = isl_schedule_node_get_ctx(node);
5116 if (compute_schedule_wcc_band(ctx, graph) < 0)
5117 return isl_schedule_node_free(node);
5119 return compute_schedule_finish_band(node, graph, 1);
5122 /* Clustering information used by compute_schedule_wcc_clustering.
5124 * "n" is the number of SCCs in the original dependence graph
5125 * "scc" is an array of "n" elements, each representing an SCC
5126 * of the original dependence graph. All entries in the same cluster
5127 * have the same number of schedule rows.
5128 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5129 * where each cluster is represented by the index of the first SCC
5130 * in the cluster. Initially, each SCC belongs to a cluster containing
5131 * only that SCC.
5133 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5134 * track of which SCCs need to be merged.
5136 * "cluster" contains the merged clusters of SCCs after the clustering
5137 * has completed.
5139 * "scc_node" is a temporary data structure used inside copy_partial.
5140 * For each SCC, it keeps track of the number of nodes in the SCC
5141 * that have already been copied.
5143 struct isl_clustering {
5144 int n;
5145 struct isl_sched_graph *scc;
5146 struct isl_sched_graph *cluster;
5147 int *scc_cluster;
5148 int *scc_node;
5149 int *scc_in_merge;
5152 /* Initialize the clustering data structure "c" from "graph".
5154 * In particular, allocate memory, extract the SCCs from "graph"
5155 * into c->scc, initialize scc_cluster and construct
5156 * a band of schedule rows for each SCC.
5157 * Within each SCC, there is only one SCC by definition.
5158 * Each SCC initially belongs to a cluster containing only that SCC.
5160 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5161 struct isl_sched_graph *graph)
5163 int i;
5165 c->n = graph->scc;
5166 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5167 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5168 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5169 c->scc_node = isl_calloc_array(ctx, int, c->n);
5170 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5171 if (!c->scc || !c->cluster ||
5172 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5173 return isl_stat_error;
5175 for (i = 0; i < c->n; ++i) {
5176 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5177 &edge_scc_exactly, i, &c->scc[i]) < 0)
5178 return isl_stat_error;
5179 c->scc[i].scc = 1;
5180 if (compute_maxvar(&c->scc[i]) < 0)
5181 return isl_stat_error;
5182 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5183 return isl_stat_error;
5184 c->scc_cluster[i] = i;
5187 return isl_stat_ok;
5190 /* Free all memory allocated for "c".
5192 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5194 int i;
5196 if (c->scc)
5197 for (i = 0; i < c->n; ++i)
5198 graph_free(ctx, &c->scc[i]);
5199 free(c->scc);
5200 if (c->cluster)
5201 for (i = 0; i < c->n; ++i)
5202 graph_free(ctx, &c->cluster[i]);
5203 free(c->cluster);
5204 free(c->scc_cluster);
5205 free(c->scc_node);
5206 free(c->scc_in_merge);
5209 /* Should we refrain from merging the cluster in "graph" with
5210 * any other cluster?
5211 * In particular, is its current schedule band empty and incomplete.
5213 static int bad_cluster(struct isl_sched_graph *graph)
5215 return graph->n_row < graph->maxvar &&
5216 graph->n_total_row == graph->band_start;
5219 /* Is "edge" a proximity edge with a non-empty dependence relation?
5221 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5223 if (!is_proximity(edge))
5224 return isl_bool_false;
5225 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5228 /* Return the index of an edge in "graph" that can be used to merge
5229 * two clusters in "c".
5230 * Return graph->n_edge if no such edge can be found.
5231 * Return -1 on error.
5233 * In particular, return a proximity edge between two clusters
5234 * that is not marked "no_merge" and such that neither of the
5235 * two clusters has an incomplete, empty band.
5237 * If there are multiple such edges, then try and find the most
5238 * appropriate edge to use for merging. In particular, pick the edge
5239 * with the greatest weight. If there are multiple of those,
5240 * then pick one with the shortest distance between
5241 * the two cluster representatives.
5243 static int find_proximity(struct isl_sched_graph *graph,
5244 struct isl_clustering *c)
5246 int i, best = graph->n_edge, best_dist, best_weight;
5248 for (i = 0; i < graph->n_edge; ++i) {
5249 struct isl_sched_edge *edge = &graph->edge[i];
5250 int dist, weight;
5251 isl_bool prox;
5253 prox = is_non_empty_proximity(edge);
5254 if (prox < 0)
5255 return -1;
5256 if (!prox)
5257 continue;
5258 if (edge->no_merge)
5259 continue;
5260 if (bad_cluster(&c->scc[edge->src->scc]) ||
5261 bad_cluster(&c->scc[edge->dst->scc]))
5262 continue;
5263 dist = c->scc_cluster[edge->dst->scc] -
5264 c->scc_cluster[edge->src->scc];
5265 if (dist == 0)
5266 continue;
5267 weight = edge->weight;
5268 if (best < graph->n_edge) {
5269 if (best_weight > weight)
5270 continue;
5271 if (best_weight == weight && best_dist <= dist)
5272 continue;
5274 best = i;
5275 best_dist = dist;
5276 best_weight = weight;
5279 return best;
5282 /* Internal data structure used in mark_merge_sccs.
5284 * "graph" is the dependence graph in which a strongly connected
5285 * component is constructed.
5286 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5287 * "src" and "dst" are the indices of the nodes that are being merged.
5289 struct isl_mark_merge_sccs_data {
5290 struct isl_sched_graph *graph;
5291 int *scc_cluster;
5292 int src;
5293 int dst;
5296 /* Check whether the cluster containing node "i" depends on the cluster
5297 * containing node "j". If "i" and "j" belong to the same cluster,
5298 * then they are taken to depend on each other to ensure that
5299 * the resulting strongly connected component consists of complete
5300 * clusters. Furthermore, if "i" and "j" are the two nodes that
5301 * are being merged, then they are taken to depend on each other as well.
5302 * Otherwise, check if there is a (conditional) validity dependence
5303 * from node[j] to node[i], forcing node[i] to follow node[j].
5305 static isl_bool cluster_follows(int i, int j, void *user)
5307 struct isl_mark_merge_sccs_data *data = user;
5308 struct isl_sched_graph *graph = data->graph;
5309 int *scc_cluster = data->scc_cluster;
5311 if (data->src == i && data->dst == j)
5312 return isl_bool_true;
5313 if (data->src == j && data->dst == i)
5314 return isl_bool_true;
5315 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5316 return isl_bool_true;
5318 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5321 /* Mark all SCCs that belong to either of the two clusters in "c"
5322 * connected by the edge in "graph" with index "edge", or to any
5323 * of the intermediate clusters.
5324 * The marking is recorded in c->scc_in_merge.
5326 * The given edge has been selected for merging two clusters,
5327 * meaning that there is at least a proximity edge between the two nodes.
5328 * However, there may also be (indirect) validity dependences
5329 * between the two nodes. When merging the two clusters, all clusters
5330 * containing one or more of the intermediate nodes along the
5331 * indirect validity dependences need to be merged in as well.
5333 * First collect all such nodes by computing the strongly connected
5334 * component (SCC) containing the two nodes connected by the edge, where
5335 * the two nodes are considered to depend on each other to make
5336 * sure they end up in the same SCC. Similarly, each node is considered
5337 * to depend on every other node in the same cluster to ensure
5338 * that the SCC consists of complete clusters.
5340 * Then the original SCCs that contain any of these nodes are marked
5341 * in c->scc_in_merge.
5343 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5344 int edge, struct isl_clustering *c)
5346 struct isl_mark_merge_sccs_data data;
5347 struct isl_tarjan_graph *g;
5348 int i;
5350 for (i = 0; i < c->n; ++i)
5351 c->scc_in_merge[i] = 0;
5353 data.graph = graph;
5354 data.scc_cluster = c->scc_cluster;
5355 data.src = graph->edge[edge].src - graph->node;
5356 data.dst = graph->edge[edge].dst - graph->node;
5358 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5359 &cluster_follows, &data);
5360 if (!g)
5361 goto error;
5363 i = g->op;
5364 if (i < 3)
5365 isl_die(ctx, isl_error_internal,
5366 "expecting at least two nodes in component",
5367 goto error);
5368 if (g->order[--i] != -1)
5369 isl_die(ctx, isl_error_internal,
5370 "expecting end of component marker", goto error);
5372 for (--i; i >= 0 && g->order[i] != -1; --i) {
5373 int scc = graph->node[g->order[i]].scc;
5374 c->scc_in_merge[scc] = 1;
5377 isl_tarjan_graph_free(g);
5378 return isl_stat_ok;
5379 error:
5380 isl_tarjan_graph_free(g);
5381 return isl_stat_error;
5384 /* Construct the identifier "cluster_i".
5386 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5388 char name[40];
5390 snprintf(name, sizeof(name), "cluster_%d", i);
5391 return isl_id_alloc(ctx, name, NULL);
5394 /* Construct the space of the cluster with index "i" containing
5395 * the strongly connected component "scc".
5397 * In particular, construct a space called cluster_i with dimension equal
5398 * to the number of schedule rows in the current band of "scc".
5400 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5402 int nvar;
5403 isl_space *space;
5404 isl_id *id;
5406 nvar = scc->n_total_row - scc->band_start;
5407 space = isl_space_copy(scc->node[0].space);
5408 space = isl_space_params(space);
5409 space = isl_space_set_from_params(space);
5410 space = isl_space_add_dims(space, isl_dim_set, nvar);
5411 id = cluster_id(isl_space_get_ctx(space), i);
5412 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5414 return space;
5417 /* Collect the domain of the graph for merging clusters.
5419 * In particular, for each cluster with first SCC "i", construct
5420 * a set in the space called cluster_i with dimension equal
5421 * to the number of schedule rows in the current band of the cluster.
5423 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5424 struct isl_sched_graph *graph, struct isl_clustering *c)
5426 int i;
5427 isl_space *space;
5428 isl_union_set *domain;
5430 space = isl_space_params_alloc(ctx, 0);
5431 domain = isl_union_set_empty(space);
5433 for (i = 0; i < graph->scc; ++i) {
5434 isl_space *space;
5436 if (!c->scc_in_merge[i])
5437 continue;
5438 if (c->scc_cluster[i] != i)
5439 continue;
5440 space = cluster_space(&c->scc[i], i);
5441 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5444 return domain;
5447 /* Construct a map from the original instances to the corresponding
5448 * cluster instance in the current bands of the clusters in "c".
5450 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5451 struct isl_sched_graph *graph, struct isl_clustering *c)
5453 int i, j;
5454 isl_space *space;
5455 isl_union_map *cluster_map;
5457 space = isl_space_params_alloc(ctx, 0);
5458 cluster_map = isl_union_map_empty(space);
5459 for (i = 0; i < graph->scc; ++i) {
5460 int start, n;
5461 isl_id *id;
5463 if (!c->scc_in_merge[i])
5464 continue;
5466 id = cluster_id(ctx, c->scc_cluster[i]);
5467 start = c->scc[i].band_start;
5468 n = c->scc[i].n_total_row - start;
5469 for (j = 0; j < c->scc[i].n; ++j) {
5470 isl_multi_aff *ma;
5471 isl_map *map;
5472 struct isl_sched_node *node = &c->scc[i].node[j];
5474 ma = node_extract_partial_schedule_multi_aff(node,
5475 start, n);
5476 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5477 isl_id_copy(id));
5478 map = isl_map_from_multi_aff(ma);
5479 cluster_map = isl_union_map_add_map(cluster_map, map);
5481 isl_id_free(id);
5484 return cluster_map;
5487 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5488 * that are not isl_edge_condition or isl_edge_conditional_validity.
5490 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5491 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5492 __isl_take isl_schedule_constraints *sc)
5494 enum isl_edge_type t;
5496 if (!sc)
5497 return NULL;
5499 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5500 if (t == isl_edge_condition ||
5501 t == isl_edge_conditional_validity)
5502 continue;
5503 if (!is_type(edge, t))
5504 continue;
5505 sc = isl_schedule_constraints_add(sc, t,
5506 isl_union_map_copy(umap));
5509 return sc;
5512 /* Add schedule constraints of types isl_edge_condition and
5513 * isl_edge_conditional_validity to "sc" by applying "umap" to
5514 * the domains of the wrapped relations in domain and range
5515 * of the corresponding tagged constraints of "edge".
5517 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5518 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5519 __isl_take isl_schedule_constraints *sc)
5521 enum isl_edge_type t;
5522 isl_union_map *tagged;
5524 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5525 if (!is_type(edge, t))
5526 continue;
5527 if (t == isl_edge_condition)
5528 tagged = isl_union_map_copy(edge->tagged_condition);
5529 else
5530 tagged = isl_union_map_copy(edge->tagged_validity);
5531 tagged = isl_union_map_zip(tagged);
5532 tagged = isl_union_map_apply_domain(tagged,
5533 isl_union_map_copy(umap));
5534 tagged = isl_union_map_zip(tagged);
5535 sc = isl_schedule_constraints_add(sc, t, tagged);
5536 if (!sc)
5537 return NULL;
5540 return sc;
5543 /* Given a mapping "cluster_map" from the original instances to
5544 * the cluster instances, add schedule constraints on the clusters
5545 * to "sc" corresponding to the original constraints represented by "edge".
5547 * For non-tagged dependence constraints, the cluster constraints
5548 * are obtained by applying "cluster_map" to the edge->map.
5550 * For tagged dependence constraints, "cluster_map" needs to be applied
5551 * to the domains of the wrapped relations in domain and range
5552 * of the tagged dependence constraints. Pick out the mappings
5553 * from these domains from "cluster_map" and construct their product.
5554 * This mapping can then be applied to the pair of domains.
5556 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5557 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5558 __isl_take isl_schedule_constraints *sc)
5560 isl_union_map *umap;
5561 isl_space *space;
5562 isl_union_set *uset;
5563 isl_union_map *umap1, *umap2;
5565 if (!sc)
5566 return NULL;
5568 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5569 umap = isl_union_map_apply_domain(umap,
5570 isl_union_map_copy(cluster_map));
5571 umap = isl_union_map_apply_range(umap,
5572 isl_union_map_copy(cluster_map));
5573 sc = add_non_conditional_constraints(edge, umap, sc);
5574 isl_union_map_free(umap);
5576 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5577 return sc;
5579 space = isl_space_domain(isl_map_get_space(edge->map));
5580 uset = isl_union_set_from_set(isl_set_universe(space));
5581 umap1 = isl_union_map_copy(cluster_map);
5582 umap1 = isl_union_map_intersect_domain(umap1, uset);
5583 space = isl_space_range(isl_map_get_space(edge->map));
5584 uset = isl_union_set_from_set(isl_set_universe(space));
5585 umap2 = isl_union_map_copy(cluster_map);
5586 umap2 = isl_union_map_intersect_domain(umap2, uset);
5587 umap = isl_union_map_product(umap1, umap2);
5589 sc = add_conditional_constraints(edge, umap, sc);
5591 isl_union_map_free(umap);
5592 return sc;
5595 /* Given a mapping "cluster_map" from the original instances to
5596 * the cluster instances, add schedule constraints on the clusters
5597 * to "sc" corresponding to all edges in "graph" between nodes that
5598 * belong to SCCs that are marked for merging in "scc_in_merge".
5600 static __isl_give isl_schedule_constraints *collect_constraints(
5601 struct isl_sched_graph *graph, int *scc_in_merge,
5602 __isl_keep isl_union_map *cluster_map,
5603 __isl_take isl_schedule_constraints *sc)
5605 int i;
5607 for (i = 0; i < graph->n_edge; ++i) {
5608 struct isl_sched_edge *edge = &graph->edge[i];
5610 if (!scc_in_merge[edge->src->scc])
5611 continue;
5612 if (!scc_in_merge[edge->dst->scc])
5613 continue;
5614 sc = collect_edge_constraints(edge, cluster_map, sc);
5617 return sc;
5620 /* Construct a dependence graph for scheduling clusters with respect
5621 * to each other and store the result in "merge_graph".
5622 * In particular, the nodes of the graph correspond to the schedule
5623 * dimensions of the current bands of those clusters that have been
5624 * marked for merging in "c".
5626 * First construct an isl_schedule_constraints object for this domain
5627 * by transforming the edges in "graph" to the domain.
5628 * Then initialize a dependence graph for scheduling from these
5629 * constraints.
5631 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5632 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5634 isl_union_set *domain;
5635 isl_union_map *cluster_map;
5636 isl_schedule_constraints *sc;
5637 isl_stat r;
5639 domain = collect_domain(ctx, graph, c);
5640 sc = isl_schedule_constraints_on_domain(domain);
5641 if (!sc)
5642 return isl_stat_error;
5643 cluster_map = collect_cluster_map(ctx, graph, c);
5644 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5645 isl_union_map_free(cluster_map);
5647 r = graph_init(merge_graph, sc);
5649 isl_schedule_constraints_free(sc);
5651 return r;
5654 /* Compute the maximal number of remaining schedule rows that still need
5655 * to be computed for the nodes that belong to clusters with the maximal
5656 * dimension for the current band (i.e., the band that is to be merged).
5657 * Only clusters that are about to be merged are considered.
5658 * "maxvar" is the maximal dimension for the current band.
5659 * "c" contains information about the clusters.
5661 * Return the maximal number of remaining schedule rows or -1 on error.
5663 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5665 int i, j;
5666 int max_slack;
5668 max_slack = 0;
5669 for (i = 0; i < c->n; ++i) {
5670 int nvar;
5671 struct isl_sched_graph *scc;
5673 if (!c->scc_in_merge[i])
5674 continue;
5675 scc = &c->scc[i];
5676 nvar = scc->n_total_row - scc->band_start;
5677 if (nvar != maxvar)
5678 continue;
5679 for (j = 0; j < scc->n; ++j) {
5680 struct isl_sched_node *node = &scc->node[j];
5681 int slack;
5683 if (node_update_cmap(node) < 0)
5684 return -1;
5685 slack = node->nvar - node->rank;
5686 if (slack > max_slack)
5687 max_slack = slack;
5691 return max_slack;
5694 /* If there are any clusters where the dimension of the current band
5695 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5696 * if there are any nodes in such a cluster where the number
5697 * of remaining schedule rows that still need to be computed
5698 * is greater than "max_slack", then return the smallest current band
5699 * dimension of all these clusters. Otherwise return the original value
5700 * of "maxvar". Return -1 in case of any error.
5701 * Only clusters that are about to be merged are considered.
5702 * "c" contains information about the clusters.
5704 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5705 struct isl_clustering *c)
5707 int i, j;
5709 for (i = 0; i < c->n; ++i) {
5710 int nvar;
5711 struct isl_sched_graph *scc;
5713 if (!c->scc_in_merge[i])
5714 continue;
5715 scc = &c->scc[i];
5716 nvar = scc->n_total_row - scc->band_start;
5717 if (nvar >= maxvar)
5718 continue;
5719 for (j = 0; j < scc->n; ++j) {
5720 struct isl_sched_node *node = &scc->node[j];
5721 int slack;
5723 if (node_update_cmap(node) < 0)
5724 return -1;
5725 slack = node->nvar - node->rank;
5726 if (slack > max_slack) {
5727 maxvar = nvar;
5728 break;
5733 return maxvar;
5736 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5737 * that still need to be computed. In particular, if there is a node
5738 * in a cluster where the dimension of the current band is smaller
5739 * than merge_graph->maxvar, but the number of remaining schedule rows
5740 * is greater than that of any node in a cluster with the maximal
5741 * dimension for the current band (i.e., merge_graph->maxvar),
5742 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5743 * of those clusters. Without this adjustment, the total number of
5744 * schedule dimensions would be increased, resulting in a skewed view
5745 * of the number of coincident dimensions.
5746 * "c" contains information about the clusters.
5748 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5749 * then there is no point in attempting any merge since it will be rejected
5750 * anyway. Set merge_graph->maxvar to zero in such cases.
5752 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5753 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5755 int max_slack, maxvar;
5757 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5758 if (max_slack < 0)
5759 return isl_stat_error;
5760 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5761 if (maxvar < 0)
5762 return isl_stat_error;
5764 if (maxvar < merge_graph->maxvar) {
5765 if (isl_options_get_schedule_maximize_band_depth(ctx))
5766 merge_graph->maxvar = 0;
5767 else
5768 merge_graph->maxvar = maxvar;
5771 return isl_stat_ok;
5774 /* Return the number of coincident dimensions in the current band of "graph",
5775 * where the nodes of "graph" are assumed to be scheduled by a single band.
5777 static int get_n_coincident(struct isl_sched_graph *graph)
5779 int i;
5781 for (i = graph->band_start; i < graph->n_total_row; ++i)
5782 if (!graph->node[0].coincident[i])
5783 break;
5785 return i - graph->band_start;
5788 /* Should the clusters be merged based on the cluster schedule
5789 * in the current (and only) band of "merge_graph", given that
5790 * coincidence should be maximized?
5792 * If the number of coincident schedule dimensions in the merged band
5793 * would be less than the maximal number of coincident schedule dimensions
5794 * in any of the merged clusters, then the clusters should not be merged.
5796 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5797 struct isl_sched_graph *merge_graph)
5799 int i;
5800 int n_coincident;
5801 int max_coincident;
5803 max_coincident = 0;
5804 for (i = 0; i < c->n; ++i) {
5805 if (!c->scc_in_merge[i])
5806 continue;
5807 n_coincident = get_n_coincident(&c->scc[i]);
5808 if (n_coincident > max_coincident)
5809 max_coincident = n_coincident;
5812 n_coincident = get_n_coincident(merge_graph);
5814 return n_coincident >= max_coincident;
5817 /* Return the transformation on "node" expressed by the current (and only)
5818 * band of "merge_graph" applied to the clusters in "c".
5820 * First find the representation of "node" in its SCC in "c" and
5821 * extract the transformation expressed by the current band.
5822 * Then extract the transformation applied by "merge_graph"
5823 * to the cluster to which this SCC belongs.
5824 * Combine the two to obtain the complete transformation on the node.
5826 * Note that the range of the first transformation is an anonymous space,
5827 * while the domain of the second is named "cluster_X". The range
5828 * of the former therefore needs to be adjusted before the two
5829 * can be combined.
5831 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5832 struct isl_sched_node *node, struct isl_clustering *c,
5833 struct isl_sched_graph *merge_graph)
5835 struct isl_sched_node *scc_node, *cluster_node;
5836 int start, n;
5837 isl_id *id;
5838 isl_space *space;
5839 isl_multi_aff *ma, *ma2;
5841 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5842 start = c->scc[node->scc].band_start;
5843 n = c->scc[node->scc].n_total_row - start;
5844 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5845 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5846 cluster_node = graph_find_node(ctx, merge_graph, space);
5847 if (space && !cluster_node)
5848 isl_die(ctx, isl_error_internal, "unable to find cluster",
5849 space = isl_space_free(space));
5850 id = isl_space_get_tuple_id(space, isl_dim_set);
5851 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5852 isl_space_free(space);
5853 n = merge_graph->n_total_row;
5854 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5855 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5857 return isl_map_from_multi_aff(ma);
5860 /* Give a set of distances "set", are they bounded by a small constant
5861 * in direction "pos"?
5862 * In practice, check if they are bounded by 2 by checking that there
5863 * are no elements with a value greater than or equal to 3 or
5864 * smaller than or equal to -3.
5866 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5868 isl_bool bounded;
5869 isl_set *test;
5871 if (!set)
5872 return isl_bool_error;
5874 test = isl_set_copy(set);
5875 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5876 bounded = isl_set_is_empty(test);
5877 isl_set_free(test);
5879 if (bounded < 0 || !bounded)
5880 return bounded;
5882 test = isl_set_copy(set);
5883 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5884 bounded = isl_set_is_empty(test);
5885 isl_set_free(test);
5887 return bounded;
5890 /* Does the set "set" have a fixed (but possible parametric) value
5891 * at dimension "pos"?
5893 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5895 int n;
5896 isl_bool single;
5898 if (!set)
5899 return isl_bool_error;
5900 set = isl_set_copy(set);
5901 n = isl_set_dim(set, isl_dim_set);
5902 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5903 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5904 single = isl_set_is_singleton(set);
5905 isl_set_free(set);
5907 return single;
5910 /* Does "map" have a fixed (but possible parametric) value
5911 * at dimension "pos" of either its domain or its range?
5913 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5915 isl_set *set;
5916 isl_bool single;
5918 set = isl_map_domain(isl_map_copy(map));
5919 single = has_single_value(set, pos);
5920 isl_set_free(set);
5922 if (single < 0 || single)
5923 return single;
5925 set = isl_map_range(isl_map_copy(map));
5926 single = has_single_value(set, pos);
5927 isl_set_free(set);
5929 return single;
5932 /* Does the edge "edge" from "graph" have bounded dependence distances
5933 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5935 * Extract the complete transformations of the source and destination
5936 * nodes of the edge, apply them to the edge constraints and
5937 * compute the differences. Finally, check if these differences are bounded
5938 * in each direction.
5940 * If the dimension of the band is greater than the number of
5941 * dimensions that can be expected to be optimized by the edge
5942 * (based on its weight), then also allow the differences to be unbounded
5943 * in the remaining dimensions, but only if either the source or
5944 * the destination has a fixed value in that direction.
5945 * This allows a statement that produces values that are used by
5946 * several instances of another statement to be merged with that
5947 * other statement.
5948 * However, merging such clusters will introduce an inherently
5949 * large proximity distance inside the merged cluster, meaning
5950 * that proximity distances will no longer be optimized in
5951 * subsequent merges. These merges are therefore only allowed
5952 * after all other possible merges have been tried.
5953 * The first time such a merge is encountered, the weight of the edge
5954 * is replaced by a negative weight. The second time (i.e., after
5955 * all merges over edges with a non-negative weight have been tried),
5956 * the merge is allowed.
5958 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5959 struct isl_sched_graph *graph, struct isl_clustering *c,
5960 struct isl_sched_graph *merge_graph)
5962 int i, n, n_slack;
5963 isl_bool bounded;
5964 isl_map *map, *t;
5965 isl_set *dist;
5967 map = isl_map_copy(edge->map);
5968 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5969 map = isl_map_apply_domain(map, t);
5970 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5971 map = isl_map_apply_range(map, t);
5972 dist = isl_map_deltas(isl_map_copy(map));
5974 bounded = isl_bool_true;
5975 n = isl_set_dim(dist, isl_dim_set);
5976 n_slack = n - edge->weight;
5977 if (edge->weight < 0)
5978 n_slack -= graph->max_weight + 1;
5979 for (i = 0; i < n; ++i) {
5980 isl_bool bounded_i, singular_i;
5982 bounded_i = distance_is_bounded(dist, i);
5983 if (bounded_i < 0)
5984 goto error;
5985 if (bounded_i)
5986 continue;
5987 if (edge->weight >= 0)
5988 bounded = isl_bool_false;
5989 n_slack--;
5990 if (n_slack < 0)
5991 break;
5992 singular_i = has_singular_src_or_dst(map, i);
5993 if (singular_i < 0)
5994 goto error;
5995 if (singular_i)
5996 continue;
5997 bounded = isl_bool_false;
5998 break;
6000 if (!bounded && i >= n && edge->weight >= 0)
6001 edge->weight -= graph->max_weight + 1;
6002 isl_map_free(map);
6003 isl_set_free(dist);
6005 return bounded;
6006 error:
6007 isl_map_free(map);
6008 isl_set_free(dist);
6009 return isl_bool_error;
6012 /* Should the clusters be merged based on the cluster schedule
6013 * in the current (and only) band of "merge_graph"?
6014 * "graph" is the original dependence graph, while "c" records
6015 * which SCCs are involved in the latest merge.
6017 * In particular, is there at least one proximity constraint
6018 * that is optimized by the merge?
6020 * A proximity constraint is considered to be optimized
6021 * if the dependence distances are small.
6023 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6024 struct isl_sched_graph *graph, struct isl_clustering *c,
6025 struct isl_sched_graph *merge_graph)
6027 int i;
6029 for (i = 0; i < graph->n_edge; ++i) {
6030 struct isl_sched_edge *edge = &graph->edge[i];
6031 isl_bool bounded;
6033 if (!is_proximity(edge))
6034 continue;
6035 if (!c->scc_in_merge[edge->src->scc])
6036 continue;
6037 if (!c->scc_in_merge[edge->dst->scc])
6038 continue;
6039 if (c->scc_cluster[edge->dst->scc] ==
6040 c->scc_cluster[edge->src->scc])
6041 continue;
6042 bounded = has_bounded_distances(ctx, edge, graph, c,
6043 merge_graph);
6044 if (bounded < 0 || bounded)
6045 return bounded;
6048 return isl_bool_false;
6051 /* Should the clusters be merged based on the cluster schedule
6052 * in the current (and only) band of "merge_graph"?
6053 * "graph" is the original dependence graph, while "c" records
6054 * which SCCs are involved in the latest merge.
6056 * If the current band is empty, then the clusters should not be merged.
6058 * If the band depth should be maximized and the merge schedule
6059 * is incomplete (meaning that the dimension of some of the schedule
6060 * bands in the original schedule will be reduced), then the clusters
6061 * should not be merged.
6063 * If the schedule_maximize_coincidence option is set, then check that
6064 * the number of coincident schedule dimensions is not reduced.
6066 * Finally, only allow the merge if at least one proximity
6067 * constraint is optimized.
6069 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6070 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6072 if (merge_graph->n_total_row == merge_graph->band_start)
6073 return isl_bool_false;
6075 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6076 merge_graph->n_total_row < merge_graph->maxvar)
6077 return isl_bool_false;
6079 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6080 isl_bool ok;
6082 ok = ok_to_merge_coincident(c, merge_graph);
6083 if (ok < 0 || !ok)
6084 return ok;
6087 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6090 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6091 * of the schedule in "node" and return the result.
6093 * That is, essentially compute
6095 * T * N(first:first+n-1)
6097 * taking into account the constant term and the parameter coefficients
6098 * in "t_node".
6100 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6101 struct isl_sched_node *t_node, struct isl_sched_node *node,
6102 int first, int n)
6104 int i, j;
6105 isl_mat *t;
6106 int n_row, n_col, n_param, n_var;
6108 n_param = node->nparam;
6109 n_var = node->nvar;
6110 n_row = isl_mat_rows(t_node->sched);
6111 n_col = isl_mat_cols(node->sched);
6112 t = isl_mat_alloc(ctx, n_row, n_col);
6113 if (!t)
6114 return NULL;
6115 for (i = 0; i < n_row; ++i) {
6116 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6117 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6118 for (j = 0; j < n; ++j)
6119 isl_seq_addmul(t->row[i],
6120 t_node->sched->row[i][1 + n_param + j],
6121 node->sched->row[first + j],
6122 1 + n_param + n_var);
6124 return t;
6127 /* Apply the cluster schedule in "t_node" to the current band
6128 * schedule of the nodes in "graph".
6130 * In particular, replace the rows starting at band_start
6131 * by the result of applying the cluster schedule in "t_node"
6132 * to the original rows.
6134 * The coincidence of the schedule is determined by the coincidence
6135 * of the cluster schedule.
6137 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6138 struct isl_sched_node *t_node)
6140 int i, j;
6141 int n_new;
6142 int start, n;
6144 start = graph->band_start;
6145 n = graph->n_total_row - start;
6147 n_new = isl_mat_rows(t_node->sched);
6148 for (i = 0; i < graph->n; ++i) {
6149 struct isl_sched_node *node = &graph->node[i];
6150 isl_mat *t;
6152 t = node_transformation(ctx, t_node, node, start, n);
6153 node->sched = isl_mat_drop_rows(node->sched, start, n);
6154 node->sched = isl_mat_concat(node->sched, t);
6155 node->sched_map = isl_map_free(node->sched_map);
6156 if (!node->sched)
6157 return isl_stat_error;
6158 for (j = 0; j < n_new; ++j)
6159 node->coincident[start + j] = t_node->coincident[j];
6161 graph->n_total_row -= n;
6162 graph->n_row -= n;
6163 graph->n_total_row += n_new;
6164 graph->n_row += n_new;
6166 return isl_stat_ok;
6169 /* Merge the clusters marked for merging in "c" into a single
6170 * cluster using the cluster schedule in the current band of "merge_graph".
6171 * The representative SCC for the new cluster is the SCC with
6172 * the smallest index.
6174 * The current band schedule of each SCC in the new cluster is obtained
6175 * by applying the schedule of the corresponding original cluster
6176 * to the original band schedule.
6177 * All SCCs in the new cluster have the same number of schedule rows.
6179 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6180 struct isl_sched_graph *merge_graph)
6182 int i;
6183 int cluster = -1;
6184 isl_space *space;
6186 for (i = 0; i < c->n; ++i) {
6187 struct isl_sched_node *node;
6189 if (!c->scc_in_merge[i])
6190 continue;
6191 if (cluster < 0)
6192 cluster = i;
6193 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6194 if (!space)
6195 return isl_stat_error;
6196 node = graph_find_node(ctx, merge_graph, space);
6197 isl_space_free(space);
6198 if (!node)
6199 isl_die(ctx, isl_error_internal,
6200 "unable to find cluster",
6201 return isl_stat_error);
6202 if (transform(ctx, &c->scc[i], node) < 0)
6203 return isl_stat_error;
6204 c->scc_cluster[i] = cluster;
6207 return isl_stat_ok;
6210 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6211 * by scheduling the current cluster bands with respect to each other.
6213 * Construct a dependence graph with a space for each cluster and
6214 * with the coordinates of each space corresponding to the schedule
6215 * dimensions of the current band of that cluster.
6216 * Construct a cluster schedule in this cluster dependence graph and
6217 * apply it to the current cluster bands if it is applicable
6218 * according to ok_to_merge.
6220 * If the number of remaining schedule dimensions in a cluster
6221 * with a non-maximal current schedule dimension is greater than
6222 * the number of remaining schedule dimensions in clusters
6223 * with a maximal current schedule dimension, then restrict
6224 * the number of rows to be computed in the cluster schedule
6225 * to the minimal such non-maximal current schedule dimension.
6226 * Do this by adjusting merge_graph.maxvar.
6228 * Return isl_bool_true if the clusters have effectively been merged
6229 * into a single cluster.
6231 * Note that since the standard scheduling algorithm minimizes the maximal
6232 * distance over proximity constraints, the proximity constraints between
6233 * the merged clusters may not be optimized any further than what is
6234 * sufficient to bring the distances within the limits of the internal
6235 * proximity constraints inside the individual clusters.
6236 * It may therefore make sense to perform an additional translation step
6237 * to bring the clusters closer to each other, while maintaining
6238 * the linear part of the merging schedule found using the standard
6239 * scheduling algorithm.
6241 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6242 struct isl_clustering *c)
6244 struct isl_sched_graph merge_graph = { 0 };
6245 isl_bool merged;
6247 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6248 goto error;
6250 if (compute_maxvar(&merge_graph) < 0)
6251 goto error;
6252 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6253 goto error;
6254 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6255 goto error;
6256 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6257 if (merged && merge(ctx, c, &merge_graph) < 0)
6258 goto error;
6260 graph_free(ctx, &merge_graph);
6261 return merged;
6262 error:
6263 graph_free(ctx, &merge_graph);
6264 return isl_bool_error;
6267 /* Is there any edge marked "no_merge" between two SCCs that are
6268 * about to be merged (i.e., that are set in "scc_in_merge")?
6269 * "merge_edge" is the proximity edge along which the clusters of SCCs
6270 * are going to be merged.
6272 * If there is any edge between two SCCs with a negative weight,
6273 * while the weight of "merge_edge" is non-negative, then this
6274 * means that the edge was postponed. "merge_edge" should then
6275 * also be postponed since merging along the edge with negative weight should
6276 * be postponed until all edges with non-negative weight have been tried.
6277 * Replace the weight of "merge_edge" by a negative weight as well and
6278 * tell the caller not to attempt a merge.
6280 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6281 struct isl_sched_edge *merge_edge)
6283 int i;
6285 for (i = 0; i < graph->n_edge; ++i) {
6286 struct isl_sched_edge *edge = &graph->edge[i];
6288 if (!scc_in_merge[edge->src->scc])
6289 continue;
6290 if (!scc_in_merge[edge->dst->scc])
6291 continue;
6292 if (edge->no_merge)
6293 return 1;
6294 if (merge_edge->weight >= 0 && edge->weight < 0) {
6295 merge_edge->weight -= graph->max_weight + 1;
6296 return 1;
6300 return 0;
6303 /* Merge the two clusters in "c" connected by the edge in "graph"
6304 * with index "edge" into a single cluster.
6305 * If it turns out to be impossible to merge these two clusters,
6306 * then mark the edge as "no_merge" such that it will not be
6307 * considered again.
6309 * First mark all SCCs that need to be merged. This includes the SCCs
6310 * in the two clusters, but it may also include the SCCs
6311 * of intermediate clusters.
6312 * If there is already a no_merge edge between any pair of such SCCs,
6313 * then simply mark the current edge as no_merge as well.
6314 * Likewise, if any of those edges was postponed by has_bounded_distances,
6315 * then postpone the current edge as well.
6316 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6317 * if the clusters did not end up getting merged, unless the non-merge
6318 * is due to the fact that the edge was postponed. This postponement
6319 * can be recognized by a change in weight (from non-negative to negative).
6321 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6322 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6324 isl_bool merged;
6325 int edge_weight = graph->edge[edge].weight;
6327 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6328 return isl_stat_error;
6330 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6331 merged = isl_bool_false;
6332 else
6333 merged = try_merge(ctx, graph, c);
6334 if (merged < 0)
6335 return isl_stat_error;
6336 if (!merged && edge_weight == graph->edge[edge].weight)
6337 graph->edge[edge].no_merge = 1;
6339 return isl_stat_ok;
6342 /* Does "node" belong to the cluster identified by "cluster"?
6344 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6346 return node->cluster == cluster;
6349 /* Does "edge" connect two nodes belonging to the cluster
6350 * identified by "cluster"?
6352 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6354 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6357 /* Swap the schedule of "node1" and "node2".
6358 * Both nodes have been derived from the same node in a common parent graph.
6359 * Since the "coincident" field is shared with that node
6360 * in the parent graph, there is no need to also swap this field.
6362 static void swap_sched(struct isl_sched_node *node1,
6363 struct isl_sched_node *node2)
6365 isl_mat *sched;
6366 isl_map *sched_map;
6368 sched = node1->sched;
6369 node1->sched = node2->sched;
6370 node2->sched = sched;
6372 sched_map = node1->sched_map;
6373 node1->sched_map = node2->sched_map;
6374 node2->sched_map = sched_map;
6377 /* Copy the current band schedule from the SCCs that form the cluster
6378 * with index "pos" to the actual cluster at position "pos".
6379 * By construction, the index of the first SCC that belongs to the cluster
6380 * is also "pos".
6382 * The order of the nodes inside both the SCCs and the cluster
6383 * is assumed to be same as the order in the original "graph".
6385 * Since the SCC graphs will no longer be used after this function,
6386 * the schedules are actually swapped rather than copied.
6388 static isl_stat copy_partial(struct isl_sched_graph *graph,
6389 struct isl_clustering *c, int pos)
6391 int i, j;
6393 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6394 c->cluster[pos].n_row = c->scc[pos].n_row;
6395 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6396 j = 0;
6397 for (i = 0; i < graph->n; ++i) {
6398 int k;
6399 int s;
6401 if (graph->node[i].cluster != pos)
6402 continue;
6403 s = graph->node[i].scc;
6404 k = c->scc_node[s]++;
6405 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6406 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6407 c->cluster[pos].maxvar = c->scc[s].maxvar;
6408 ++j;
6411 return isl_stat_ok;
6414 /* Is there a (conditional) validity dependence from node[j] to node[i],
6415 * forcing node[i] to follow node[j] or do the nodes belong to the same
6416 * cluster?
6418 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6420 struct isl_sched_graph *graph = user;
6422 if (graph->node[i].cluster == graph->node[j].cluster)
6423 return isl_bool_true;
6424 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6427 /* Extract the merged clusters of SCCs in "graph", sort them, and
6428 * store them in c->clusters. Update c->scc_cluster accordingly.
6430 * First keep track of the cluster containing the SCC to which a node
6431 * belongs in the node itself.
6432 * Then extract the clusters into c->clusters, copying the current
6433 * band schedule from the SCCs that belong to the cluster.
6434 * Do this only once per cluster.
6436 * Finally, topologically sort the clusters and update c->scc_cluster
6437 * to match the new scc numbering. While the SCCs were originally
6438 * sorted already, some SCCs that depend on some other SCCs may
6439 * have been merged with SCCs that appear before these other SCCs.
6440 * A reordering may therefore be required.
6442 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6443 struct isl_clustering *c)
6445 int i;
6447 for (i = 0; i < graph->n; ++i)
6448 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6450 for (i = 0; i < graph->scc; ++i) {
6451 if (c->scc_cluster[i] != i)
6452 continue;
6453 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6454 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6455 return isl_stat_error;
6456 c->cluster[i].src_scc = -1;
6457 c->cluster[i].dst_scc = -1;
6458 if (copy_partial(graph, c, i) < 0)
6459 return isl_stat_error;
6462 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6463 return isl_stat_error;
6464 for (i = 0; i < graph->n; ++i)
6465 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6467 return isl_stat_ok;
6470 /* Compute weights on the proximity edges of "graph" that can
6471 * be used by find_proximity to find the most appropriate
6472 * proximity edge to use to merge two clusters in "c".
6473 * The weights are also used by has_bounded_distances to determine
6474 * whether the merge should be allowed.
6475 * Store the maximum of the computed weights in graph->max_weight.
6477 * The computed weight is a measure for the number of remaining schedule
6478 * dimensions that can still be completely aligned.
6479 * In particular, compute the number of equalities between
6480 * input dimensions and output dimensions in the proximity constraints.
6481 * The directions that are already handled by outer schedule bands
6482 * are projected out prior to determining this number.
6484 * Edges that will never be considered by find_proximity are ignored.
6486 static isl_stat compute_weights(struct isl_sched_graph *graph,
6487 struct isl_clustering *c)
6489 int i;
6491 graph->max_weight = 0;
6493 for (i = 0; i < graph->n_edge; ++i) {
6494 struct isl_sched_edge *edge = &graph->edge[i];
6495 struct isl_sched_node *src = edge->src;
6496 struct isl_sched_node *dst = edge->dst;
6497 isl_basic_map *hull;
6498 isl_bool prox;
6499 int n_in, n_out;
6501 prox = is_non_empty_proximity(edge);
6502 if (prox < 0)
6503 return isl_stat_error;
6504 if (!prox)
6505 continue;
6506 if (bad_cluster(&c->scc[edge->src->scc]) ||
6507 bad_cluster(&c->scc[edge->dst->scc]))
6508 continue;
6509 if (c->scc_cluster[edge->dst->scc] ==
6510 c->scc_cluster[edge->src->scc])
6511 continue;
6513 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6514 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6515 isl_mat_copy(src->ctrans));
6516 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6517 isl_mat_copy(dst->ctrans));
6518 hull = isl_basic_map_project_out(hull,
6519 isl_dim_in, 0, src->rank);
6520 hull = isl_basic_map_project_out(hull,
6521 isl_dim_out, 0, dst->rank);
6522 hull = isl_basic_map_remove_divs(hull);
6523 n_in = isl_basic_map_dim(hull, isl_dim_in);
6524 n_out = isl_basic_map_dim(hull, isl_dim_out);
6525 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6526 isl_dim_in, 0, n_in);
6527 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6528 isl_dim_out, 0, n_out);
6529 if (!hull)
6530 return isl_stat_error;
6531 edge->weight = isl_basic_map_n_equality(hull);
6532 isl_basic_map_free(hull);
6534 if (edge->weight > graph->max_weight)
6535 graph->max_weight = edge->weight;
6538 return isl_stat_ok;
6541 /* Call compute_schedule_finish_band on each of the clusters in "c"
6542 * in their topological order. This order is determined by the scc
6543 * fields of the nodes in "graph".
6544 * Combine the results in a sequence expressing the topological order.
6546 * If there is only one cluster left, then there is no need to introduce
6547 * a sequence node. Also, in this case, the cluster necessarily contains
6548 * the SCC at position 0 in the original graph and is therefore also
6549 * stored in the first cluster of "c".
6551 static __isl_give isl_schedule_node *finish_bands_clustering(
6552 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6553 struct isl_clustering *c)
6555 int i;
6556 isl_ctx *ctx;
6557 isl_union_set_list *filters;
6559 if (graph->scc == 1)
6560 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6562 ctx = isl_schedule_node_get_ctx(node);
6564 filters = extract_sccs(ctx, graph);
6565 node = isl_schedule_node_insert_sequence(node, filters);
6567 for (i = 0; i < graph->scc; ++i) {
6568 int j = c->scc_cluster[i];
6569 node = isl_schedule_node_child(node, i);
6570 node = isl_schedule_node_child(node, 0);
6571 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6572 node = isl_schedule_node_parent(node);
6573 node = isl_schedule_node_parent(node);
6576 return node;
6579 /* Compute a schedule for a connected dependence graph by first considering
6580 * each strongly connected component (SCC) in the graph separately and then
6581 * incrementally combining them into clusters.
6582 * Return the updated schedule node.
6584 * Initially, each cluster consists of a single SCC, each with its
6585 * own band schedule. The algorithm then tries to merge pairs
6586 * of clusters along a proximity edge until no more suitable
6587 * proximity edges can be found. During this merging, the schedule
6588 * is maintained in the individual SCCs.
6589 * After the merging is completed, the full resulting clusters
6590 * are extracted and in finish_bands_clustering,
6591 * compute_schedule_finish_band is called on each of them to integrate
6592 * the band into "node" and to continue the computation.
6594 * compute_weights initializes the weights that are used by find_proximity.
6596 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6597 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6599 isl_ctx *ctx;
6600 struct isl_clustering c;
6601 int i;
6603 ctx = isl_schedule_node_get_ctx(node);
6605 if (clustering_init(ctx, &c, graph) < 0)
6606 goto error;
6608 if (compute_weights(graph, &c) < 0)
6609 goto error;
6611 for (;;) {
6612 i = find_proximity(graph, &c);
6613 if (i < 0)
6614 goto error;
6615 if (i >= graph->n_edge)
6616 break;
6617 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6618 goto error;
6621 if (extract_clusters(ctx, graph, &c) < 0)
6622 goto error;
6624 node = finish_bands_clustering(node, graph, &c);
6626 clustering_free(ctx, &c);
6627 return node;
6628 error:
6629 clustering_free(ctx, &c);
6630 return isl_schedule_node_free(node);
6633 /* Compute a schedule for a connected dependence graph and return
6634 * the updated schedule node.
6636 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6637 * as many validity dependences as possible. When all validity dependences
6638 * are satisfied we extend the schedule to a full-dimensional schedule.
6640 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6641 * depending on whether the user has selected the option to try and
6642 * compute a schedule for the entire (weakly connected) component first.
6643 * If there is only a single strongly connected component (SCC), then
6644 * there is no point in trying to combine SCCs
6645 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6646 * is called instead.
6648 static __isl_give isl_schedule_node *compute_schedule_wcc(
6649 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6651 isl_ctx *ctx;
6653 if (!node)
6654 return NULL;
6656 ctx = isl_schedule_node_get_ctx(node);
6657 if (detect_sccs(ctx, graph) < 0)
6658 return isl_schedule_node_free(node);
6660 if (compute_maxvar(graph) < 0)
6661 return isl_schedule_node_free(node);
6663 if (need_feautrier_step(ctx, graph))
6664 return compute_schedule_wcc_feautrier(node, graph);
6666 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6667 return compute_schedule_wcc_whole(node, graph);
6668 else
6669 return compute_schedule_wcc_clustering(node, graph);
6672 /* Compute a schedule for each group of nodes identified by node->scc
6673 * separately and then combine them in a sequence node (or as set node
6674 * if graph->weak is set) inserted at position "node" of the schedule tree.
6675 * Return the updated schedule node.
6677 * If "wcc" is set then each of the groups belongs to a single
6678 * weakly connected component in the dependence graph so that
6679 * there is no need for compute_sub_schedule to look for weakly
6680 * connected components.
6682 static __isl_give isl_schedule_node *compute_component_schedule(
6683 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6684 int wcc)
6686 int component;
6687 isl_ctx *ctx;
6688 isl_union_set_list *filters;
6690 if (!node)
6691 return NULL;
6692 ctx = isl_schedule_node_get_ctx(node);
6694 filters = extract_sccs(ctx, graph);
6695 if (graph->weak)
6696 node = isl_schedule_node_insert_set(node, filters);
6697 else
6698 node = isl_schedule_node_insert_sequence(node, filters);
6700 for (component = 0; component < graph->scc; ++component) {
6701 node = isl_schedule_node_child(node, component);
6702 node = isl_schedule_node_child(node, 0);
6703 node = compute_sub_schedule(node, ctx, graph,
6704 &node_scc_exactly,
6705 &edge_scc_exactly, component, wcc);
6706 node = isl_schedule_node_parent(node);
6707 node = isl_schedule_node_parent(node);
6710 return node;
6713 /* Compute a schedule for the given dependence graph and insert it at "node".
6714 * Return the updated schedule node.
6716 * We first check if the graph is connected (through validity and conditional
6717 * validity dependences) and, if not, compute a schedule
6718 * for each component separately.
6719 * If the schedule_serialize_sccs option is set, then we check for strongly
6720 * connected components instead and compute a separate schedule for
6721 * each such strongly connected component.
6723 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6724 struct isl_sched_graph *graph)
6726 isl_ctx *ctx;
6728 if (!node)
6729 return NULL;
6731 ctx = isl_schedule_node_get_ctx(node);
6732 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6733 if (detect_sccs(ctx, graph) < 0)
6734 return isl_schedule_node_free(node);
6735 } else {
6736 if (detect_wccs(ctx, graph) < 0)
6737 return isl_schedule_node_free(node);
6740 if (graph->scc > 1)
6741 return compute_component_schedule(node, graph, 1);
6743 return compute_schedule_wcc(node, graph);
6746 /* Compute a schedule on sc->domain that respects the given schedule
6747 * constraints.
6749 * In particular, the schedule respects all the validity dependences.
6750 * If the default isl scheduling algorithm is used, it tries to minimize
6751 * the dependence distances over the proximity dependences.
6752 * If Feautrier's scheduling algorithm is used, the proximity dependence
6753 * distances are only minimized during the extension to a full-dimensional
6754 * schedule.
6756 * If there are any condition and conditional validity dependences,
6757 * then the conditional validity dependences may be violated inside
6758 * a tilable band, provided they have no adjacent non-local
6759 * condition dependences.
6761 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6762 __isl_take isl_schedule_constraints *sc)
6764 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6765 struct isl_sched_graph graph = { 0 };
6766 isl_schedule *sched;
6767 isl_schedule_node *node;
6768 isl_union_set *domain;
6770 sc = isl_schedule_constraints_align_params(sc);
6772 domain = isl_schedule_constraints_get_domain(sc);
6773 if (isl_union_set_n_set(domain) == 0) {
6774 isl_schedule_constraints_free(sc);
6775 return isl_schedule_from_domain(domain);
6778 if (graph_init(&graph, sc) < 0)
6779 domain = isl_union_set_free(domain);
6781 node = isl_schedule_node_from_domain(domain);
6782 node = isl_schedule_node_child(node, 0);
6783 if (graph.n > 0)
6784 node = compute_schedule(node, &graph);
6785 sched = isl_schedule_node_get_schedule(node);
6786 isl_schedule_node_free(node);
6788 graph_free(ctx, &graph);
6789 isl_schedule_constraints_free(sc);
6791 return sched;
6794 /* Compute a schedule for the given union of domains that respects
6795 * all the validity dependences and minimizes
6796 * the dependence distances over the proximity dependences.
6798 * This function is kept for backward compatibility.
6800 __isl_give isl_schedule *isl_union_set_compute_schedule(
6801 __isl_take isl_union_set *domain,
6802 __isl_take isl_union_map *validity,
6803 __isl_take isl_union_map *proximity)
6805 isl_schedule_constraints *sc;
6807 sc = isl_schedule_constraints_on_domain(domain);
6808 sc = isl_schedule_constraints_set_validity(sc, validity);
6809 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6811 return isl_schedule_constraints_compute_schedule(sc);