drop isl_basic_map_drop_inputs
[isl.git] / isl_scheduler.c
blob46da9c6326dc227b95325ffc5fb141d39daa3f22
1 /*
2 * Copyright 2011 INRIA Saclay
3 * Copyright 2012-2014 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
5 * Copyright 2016 INRIA Paris
7 * Use of this software is governed by the MIT license
9 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
10 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
11 * 91893 Orsay, France
12 * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
13 * and Centre de Recherche Inria de Paris, 2 rue Simone Iff - Voie DQ12,
14 * CS 42112, 75589 Paris Cedex 12, France
17 #include <isl_ctx_private.h>
18 #include <isl_map_private.h>
19 #include <isl_space_private.h>
20 #include <isl_aff_private.h>
21 #include <isl/hash.h>
22 #include <isl/constraint.h>
23 #include <isl/schedule.h>
24 #include <isl_schedule_constraints.h>
25 #include <isl/schedule_node.h>
26 #include <isl_mat_private.h>
27 #include <isl_vec_private.h>
28 #include <isl/set.h>
29 #include <isl/union_set.h>
30 #include <isl_seq.h>
31 #include <isl_tab.h>
32 #include <isl_dim_map.h>
33 #include <isl/map_to_basic_set.h>
34 #include <isl_sort.h>
35 #include <isl_options_private.h>
36 #include <isl_tarjan.h>
37 #include <isl_morph.h>
38 #include <isl/ilp.h>
39 #include <isl_val_private.h>
42 * The scheduling algorithm implemented in this file was inspired by
43 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
44 * Parallelization and Locality Optimization in the Polyhedral Model".
48 /* Internal information about a node that is used during the construction
49 * of a schedule.
50 * space represents the space in which the domain lives
51 * sched is a matrix representation of the schedule being constructed
52 * for this node; if compressed is set, then this schedule is
53 * defined over the compressed domain space
54 * sched_map is an isl_map representation of the same (partial) schedule
55 * sched_map may be NULL; if compressed is set, then this map
56 * is defined over the uncompressed domain space
57 * rank is the number of linearly independent rows in the linear part
58 * of sched
59 * the columns of cmap represent a change of basis for the schedule
60 * coefficients; the first rank columns span the linear part of
61 * the schedule rows
62 * cinv is the inverse of cmap.
63 * ctrans is the transpose of cmap.
64 * start is the first variable in the LP problem in the sequences that
65 * represents the schedule coefficients of this node
66 * nvar is the dimension of the domain
67 * nparam is the number of parameters or 0 if we are not constructing
68 * a parametric schedule
70 * If compressed is set, then hull represents the constraints
71 * that were used to derive the compression, while compress and
72 * decompress map the original space to the compressed space and
73 * vice versa.
75 * scc is the index of SCC (or WCC) this node belongs to
77 * "cluster" is only used inside extract_clusters and identifies
78 * the cluster of SCCs that the node belongs to.
80 * coincident contains a boolean for each of the rows of the schedule,
81 * indicating whether the corresponding scheduling dimension satisfies
82 * the coincidence constraints in the sense that the corresponding
83 * dependence distances are zero.
85 * If the schedule_treat_coalescing option is set, then
86 * "sizes" contains the sizes of the (compressed) instance set
87 * in each direction. If there is no fixed size in a given direction,
88 * then the corresponding size value is set to infinity.
89 * If the schedule_treat_coalescing option or the schedule_max_coefficient
90 * option is set, then "max" contains the maximal values for
91 * schedule coefficients of the (compressed) variables. If no bound
92 * needs to be imposed on a particular variable, then the corresponding
93 * value is negative.
95 struct isl_sched_node {
96 isl_space *space;
97 int compressed;
98 isl_set *hull;
99 isl_multi_aff *compress;
100 isl_multi_aff *decompress;
101 isl_mat *sched;
102 isl_map *sched_map;
103 int rank;
104 isl_mat *cmap;
105 isl_mat *cinv;
106 isl_mat *ctrans;
107 int start;
108 int nvar;
109 int nparam;
111 int scc;
112 int cluster;
114 int *coincident;
116 isl_multi_val *sizes;
117 isl_vec *max;
120 static int node_has_space(const void *entry, const void *val)
122 struct isl_sched_node *node = (struct isl_sched_node *)entry;
123 isl_space *dim = (isl_space *)val;
125 return isl_space_is_equal(node->space, dim);
128 static int node_scc_exactly(struct isl_sched_node *node, int scc)
130 return node->scc == scc;
133 static int node_scc_at_most(struct isl_sched_node *node, int scc)
135 return node->scc <= scc;
138 static int node_scc_at_least(struct isl_sched_node *node, int scc)
140 return node->scc >= scc;
143 /* An edge in the dependence graph. An edge may be used to
144 * ensure validity of the generated schedule, to minimize the dependence
145 * distance or both
147 * map is the dependence relation, with i -> j in the map if j depends on i
148 * tagged_condition and tagged_validity contain the union of all tagged
149 * condition or conditional validity dependence relations that
150 * specialize the dependence relation "map"; that is,
151 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
152 * or "tagged_validity", then i -> j is an element of "map".
153 * If these fields are NULL, then they represent the empty relation.
154 * src is the source node
155 * dst is the sink node
157 * types is a bit vector containing the types of this edge.
158 * validity is set if the edge is used to ensure correctness
159 * coincidence is used to enforce zero dependence distances
160 * proximity is set if the edge is used to minimize dependence distances
161 * condition is set if the edge represents a condition
162 * for a conditional validity schedule constraint
163 * local can only be set for condition edges and indicates that
164 * the dependence distance over the edge should be zero
165 * conditional_validity is set if the edge is used to conditionally
166 * ensure correctness
168 * For validity edges, start and end mark the sequence of inequality
169 * constraints in the LP problem that encode the validity constraint
170 * corresponding to this edge.
172 * During clustering, an edge may be marked "no_merge" if it should
173 * not be used to merge clusters.
174 * The weight is also only used during clustering and it is
175 * an indication of how many schedule dimensions on either side
176 * of the schedule constraints can be aligned.
177 * If the weight is negative, then this means that this edge was postponed
178 * by has_bounded_distances or any_no_merge. The original weight can
179 * be retrieved by adding 1 + graph->max_weight, with "graph"
180 * the graph containing this edge.
182 struct isl_sched_edge {
183 isl_map *map;
184 isl_union_map *tagged_condition;
185 isl_union_map *tagged_validity;
187 struct isl_sched_node *src;
188 struct isl_sched_node *dst;
190 unsigned types;
192 int start;
193 int end;
195 int no_merge;
196 int weight;
199 /* Is "edge" marked as being of type "type"?
201 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
203 return ISL_FL_ISSET(edge->types, 1 << type);
206 /* Mark "edge" as being of type "type".
208 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
210 ISL_FL_SET(edge->types, 1 << type);
213 /* No longer mark "edge" as being of type "type"?
215 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
217 ISL_FL_CLR(edge->types, 1 << type);
220 /* Is "edge" marked as a validity edge?
222 static int is_validity(struct isl_sched_edge *edge)
224 return is_type(edge, isl_edge_validity);
227 /* Mark "edge" as a validity edge.
229 static void set_validity(struct isl_sched_edge *edge)
231 set_type(edge, isl_edge_validity);
234 /* Is "edge" marked as a proximity edge?
236 static int is_proximity(struct isl_sched_edge *edge)
238 return is_type(edge, isl_edge_proximity);
241 /* Is "edge" marked as a local edge?
243 static int is_local(struct isl_sched_edge *edge)
245 return is_type(edge, isl_edge_local);
248 /* Mark "edge" as a local edge.
250 static void set_local(struct isl_sched_edge *edge)
252 set_type(edge, isl_edge_local);
255 /* No longer mark "edge" as a local edge.
257 static void clear_local(struct isl_sched_edge *edge)
259 clear_type(edge, isl_edge_local);
262 /* Is "edge" marked as a coincidence edge?
264 static int is_coincidence(struct isl_sched_edge *edge)
266 return is_type(edge, isl_edge_coincidence);
269 /* Is "edge" marked as a condition edge?
271 static int is_condition(struct isl_sched_edge *edge)
273 return is_type(edge, isl_edge_condition);
276 /* Is "edge" marked as a conditional validity edge?
278 static int is_conditional_validity(struct isl_sched_edge *edge)
280 return is_type(edge, isl_edge_conditional_validity);
283 /* Internal information about the dependence graph used during
284 * the construction of the schedule.
286 * intra_hmap is a cache, mapping dependence relations to their dual,
287 * for dependences from a node to itself
288 * inter_hmap is a cache, mapping dependence relations to their dual,
289 * for dependences between distinct nodes
290 * if compression is involved then the key for these maps
291 * is the original, uncompressed dependence relation, while
292 * the value is the dual of the compressed dependence relation.
294 * n is the number of nodes
295 * node is the list of nodes
296 * maxvar is the maximal number of variables over all nodes
297 * max_row is the allocated number of rows in the schedule
298 * n_row is the current (maximal) number of linearly independent
299 * rows in the node schedules
300 * n_total_row is the current number of rows in the node schedules
301 * band_start is the starting row in the node schedules of the current band
302 * root is set if this graph is the original dependence graph,
303 * without any splitting
305 * sorted contains a list of node indices sorted according to the
306 * SCC to which a node belongs
308 * n_edge is the number of edges
309 * edge is the list of edges
310 * max_edge contains the maximal number of edges of each type;
311 * in particular, it contains the number of edges in the inital graph.
312 * edge_table contains pointers into the edge array, hashed on the source
313 * and sink spaces; there is one such table for each type;
314 * a given edge may be referenced from more than one table
315 * if the corresponding relation appears in more than one of the
316 * sets of dependences; however, for each type there is only
317 * a single edge between a given pair of source and sink space
318 * in the entire graph
320 * node_table contains pointers into the node array, hashed on the space
322 * region contains a list of variable sequences that should be non-trivial
324 * lp contains the (I)LP problem used to obtain new schedule rows
326 * src_scc and dst_scc are the source and sink SCCs of an edge with
327 * conflicting constraints
329 * scc represents the number of components
330 * weak is set if the components are weakly connected
332 * max_weight is used during clustering and represents the maximal
333 * weight of the relevant proximity edges.
335 struct isl_sched_graph {
336 isl_map_to_basic_set *intra_hmap;
337 isl_map_to_basic_set *inter_hmap;
339 struct isl_sched_node *node;
340 int n;
341 int maxvar;
342 int max_row;
343 int n_row;
345 int *sorted;
347 int n_total_row;
348 int band_start;
350 int root;
352 struct isl_sched_edge *edge;
353 int n_edge;
354 int max_edge[isl_edge_last + 1];
355 struct isl_hash_table *edge_table[isl_edge_last + 1];
357 struct isl_hash_table *node_table;
358 struct isl_region *region;
360 isl_basic_set *lp;
362 int src_scc;
363 int dst_scc;
365 int scc;
366 int weak;
368 int max_weight;
371 /* Initialize node_table based on the list of nodes.
373 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
375 int i;
377 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
378 if (!graph->node_table)
379 return -1;
381 for (i = 0; i < graph->n; ++i) {
382 struct isl_hash_table_entry *entry;
383 uint32_t hash;
385 hash = isl_space_get_hash(graph->node[i].space);
386 entry = isl_hash_table_find(ctx, graph->node_table, hash,
387 &node_has_space,
388 graph->node[i].space, 1);
389 if (!entry)
390 return -1;
391 entry->data = &graph->node[i];
394 return 0;
397 /* Return a pointer to the node that lives within the given space,
398 * or NULL if there is no such node.
400 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
401 struct isl_sched_graph *graph, __isl_keep isl_space *dim)
403 struct isl_hash_table_entry *entry;
404 uint32_t hash;
406 hash = isl_space_get_hash(dim);
407 entry = isl_hash_table_find(ctx, graph->node_table, hash,
408 &node_has_space, dim, 0);
410 return entry ? entry->data : NULL;
413 static int edge_has_src_and_dst(const void *entry, const void *val)
415 const struct isl_sched_edge *edge = entry;
416 const struct isl_sched_edge *temp = val;
418 return edge->src == temp->src && edge->dst == temp->dst;
421 /* Add the given edge to graph->edge_table[type].
423 static isl_stat graph_edge_table_add(isl_ctx *ctx,
424 struct isl_sched_graph *graph, enum isl_edge_type type,
425 struct isl_sched_edge *edge)
427 struct isl_hash_table_entry *entry;
428 uint32_t hash;
430 hash = isl_hash_init();
431 hash = isl_hash_builtin(hash, edge->src);
432 hash = isl_hash_builtin(hash, edge->dst);
433 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
434 &edge_has_src_and_dst, edge, 1);
435 if (!entry)
436 return isl_stat_error;
437 entry->data = edge;
439 return isl_stat_ok;
442 /* Allocate the edge_tables based on the maximal number of edges of
443 * each type.
445 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
447 int i;
449 for (i = 0; i <= isl_edge_last; ++i) {
450 graph->edge_table[i] = isl_hash_table_alloc(ctx,
451 graph->max_edge[i]);
452 if (!graph->edge_table[i])
453 return -1;
456 return 0;
459 /* If graph->edge_table[type] contains an edge from the given source
460 * to the given destination, then return the hash table entry of this edge.
461 * Otherwise, return NULL.
463 static struct isl_hash_table_entry *graph_find_edge_entry(
464 struct isl_sched_graph *graph,
465 enum isl_edge_type type,
466 struct isl_sched_node *src, struct isl_sched_node *dst)
468 isl_ctx *ctx = isl_space_get_ctx(src->space);
469 uint32_t hash;
470 struct isl_sched_edge temp = { .src = src, .dst = dst };
472 hash = isl_hash_init();
473 hash = isl_hash_builtin(hash, temp.src);
474 hash = isl_hash_builtin(hash, temp.dst);
475 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
476 &edge_has_src_and_dst, &temp, 0);
480 /* If graph->edge_table[type] contains an edge from the given source
481 * to the given destination, then return this edge.
482 * Otherwise, return NULL.
484 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
485 enum isl_edge_type type,
486 struct isl_sched_node *src, struct isl_sched_node *dst)
488 struct isl_hash_table_entry *entry;
490 entry = graph_find_edge_entry(graph, type, src, dst);
491 if (!entry)
492 return NULL;
494 return entry->data;
497 /* Check whether the dependence graph has an edge of the given type
498 * between the given two nodes.
500 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
501 enum isl_edge_type type,
502 struct isl_sched_node *src, struct isl_sched_node *dst)
504 struct isl_sched_edge *edge;
505 isl_bool empty;
507 edge = graph_find_edge(graph, type, src, dst);
508 if (!edge)
509 return 0;
511 empty = isl_map_plain_is_empty(edge->map);
512 if (empty < 0)
513 return isl_bool_error;
515 return !empty;
518 /* Look for any edge with the same src, dst and map fields as "model".
520 * Return the matching edge if one can be found.
521 * Return "model" if no matching edge is found.
522 * Return NULL on error.
524 static struct isl_sched_edge *graph_find_matching_edge(
525 struct isl_sched_graph *graph, struct isl_sched_edge *model)
527 enum isl_edge_type i;
528 struct isl_sched_edge *edge;
530 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
531 int is_equal;
533 edge = graph_find_edge(graph, i, model->src, model->dst);
534 if (!edge)
535 continue;
536 is_equal = isl_map_plain_is_equal(model->map, edge->map);
537 if (is_equal < 0)
538 return NULL;
539 if (is_equal)
540 return edge;
543 return model;
546 /* Remove the given edge from all the edge_tables that refer to it.
548 static void graph_remove_edge(struct isl_sched_graph *graph,
549 struct isl_sched_edge *edge)
551 isl_ctx *ctx = isl_map_get_ctx(edge->map);
552 enum isl_edge_type i;
554 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
555 struct isl_hash_table_entry *entry;
557 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
558 if (!entry)
559 continue;
560 if (entry->data != edge)
561 continue;
562 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
566 /* Check whether the dependence graph has any edge
567 * between the given two nodes.
569 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
570 struct isl_sched_node *src, struct isl_sched_node *dst)
572 enum isl_edge_type i;
573 isl_bool r;
575 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
576 r = graph_has_edge(graph, i, src, dst);
577 if (r < 0 || r)
578 return r;
581 return r;
584 /* Check whether the dependence graph has a validity edge
585 * between the given two nodes.
587 * Conditional validity edges are essentially validity edges that
588 * can be ignored if the corresponding condition edges are iteration private.
589 * Here, we are only checking for the presence of validity
590 * edges, so we need to consider the conditional validity edges too.
591 * In particular, this function is used during the detection
592 * of strongly connected components and we cannot ignore
593 * conditional validity edges during this detection.
595 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
596 struct isl_sched_node *src, struct isl_sched_node *dst)
598 isl_bool r;
600 r = graph_has_edge(graph, isl_edge_validity, src, dst);
601 if (r < 0 || r)
602 return r;
604 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
607 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
608 int n_node, int n_edge)
610 int i;
612 graph->n = n_node;
613 graph->n_edge = n_edge;
614 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
615 graph->sorted = isl_calloc_array(ctx, int, graph->n);
616 graph->region = isl_alloc_array(ctx, struct isl_region, graph->n);
617 graph->edge = isl_calloc_array(ctx,
618 struct isl_sched_edge, graph->n_edge);
620 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
621 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
623 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
624 !graph->sorted)
625 return -1;
627 for(i = 0; i < graph->n; ++i)
628 graph->sorted[i] = i;
630 return 0;
633 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
635 int i;
637 isl_map_to_basic_set_free(graph->intra_hmap);
638 isl_map_to_basic_set_free(graph->inter_hmap);
640 if (graph->node)
641 for (i = 0; i < graph->n; ++i) {
642 isl_space_free(graph->node[i].space);
643 isl_set_free(graph->node[i].hull);
644 isl_multi_aff_free(graph->node[i].compress);
645 isl_multi_aff_free(graph->node[i].decompress);
646 isl_mat_free(graph->node[i].sched);
647 isl_map_free(graph->node[i].sched_map);
648 isl_mat_free(graph->node[i].cmap);
649 isl_mat_free(graph->node[i].cinv);
650 isl_mat_free(graph->node[i].ctrans);
651 if (graph->root)
652 free(graph->node[i].coincident);
653 isl_multi_val_free(graph->node[i].sizes);
654 isl_vec_free(graph->node[i].max);
656 free(graph->node);
657 free(graph->sorted);
658 if (graph->edge)
659 for (i = 0; i < graph->n_edge; ++i) {
660 isl_map_free(graph->edge[i].map);
661 isl_union_map_free(graph->edge[i].tagged_condition);
662 isl_union_map_free(graph->edge[i].tagged_validity);
664 free(graph->edge);
665 free(graph->region);
666 for (i = 0; i <= isl_edge_last; ++i)
667 isl_hash_table_free(ctx, graph->edge_table[i]);
668 isl_hash_table_free(ctx, graph->node_table);
669 isl_basic_set_free(graph->lp);
672 /* For each "set" on which this function is called, increment
673 * graph->n by one and update graph->maxvar.
675 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
677 struct isl_sched_graph *graph = user;
678 int nvar = isl_set_dim(set, isl_dim_set);
680 graph->n++;
681 if (nvar > graph->maxvar)
682 graph->maxvar = nvar;
684 isl_set_free(set);
686 return isl_stat_ok;
689 /* Compute the number of rows that should be allocated for the schedule.
690 * In particular, we need one row for each variable or one row
691 * for each basic map in the dependences.
692 * Note that it is practically impossible to exhaust both
693 * the number of dependences and the number of variables.
695 static isl_stat compute_max_row(struct isl_sched_graph *graph,
696 __isl_keep isl_schedule_constraints *sc)
698 int n_edge;
699 isl_stat r;
700 isl_union_set *domain;
702 graph->n = 0;
703 graph->maxvar = 0;
704 domain = isl_schedule_constraints_get_domain(sc);
705 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
706 isl_union_set_free(domain);
707 if (r < 0)
708 return isl_stat_error;
709 n_edge = isl_schedule_constraints_n_basic_map(sc);
710 if (n_edge < 0)
711 return isl_stat_error;
712 graph->max_row = n_edge + graph->maxvar;
714 return isl_stat_ok;
717 /* Does "bset" have any defining equalities for its set variables?
719 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
721 int i, n;
723 if (!bset)
724 return isl_bool_error;
726 n = isl_basic_set_dim(bset, isl_dim_set);
727 for (i = 0; i < n; ++i) {
728 isl_bool has;
730 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
731 NULL);
732 if (has < 0 || has)
733 return has;
736 return isl_bool_false;
739 /* Set the entries of node->max to the value of the schedule_max_coefficient
740 * option, if set.
742 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
744 int max;
746 max = isl_options_get_schedule_max_coefficient(ctx);
747 if (max == -1)
748 return isl_stat_ok;
750 node->max = isl_vec_alloc(ctx, node->nvar);
751 node->max = isl_vec_set_si(node->max, max);
752 if (!node->max)
753 return isl_stat_error;
755 return isl_stat_ok;
758 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
759 * option (if set) and half of the minimum of the sizes in the other
760 * dimensions. If the minimum of the sizes is one, half of the size
761 * is zero and this value is reset to one.
762 * If the global minimum is unbounded (i.e., if both
763 * the schedule_max_coefficient is not set and the sizes in the other
764 * dimensions are unbounded), then store a negative value.
765 * If the schedule coefficient is close to the size of the instance set
766 * in another dimension, then the schedule may represent a loop
767 * coalescing transformation (especially if the coefficient
768 * in that other dimension is one). Forcing the coefficient to be
769 * smaller than or equal to half the minimal size should avoid this
770 * situation.
772 static isl_stat compute_max_coefficient(isl_ctx *ctx,
773 struct isl_sched_node *node)
775 int max;
776 int i, j;
777 isl_vec *v;
779 max = isl_options_get_schedule_max_coefficient(ctx);
780 v = isl_vec_alloc(ctx, node->nvar);
781 if (!v)
782 return isl_stat_error;
784 for (i = 0; i < node->nvar; ++i) {
785 isl_int_set_si(v->el[i], max);
786 isl_int_mul_si(v->el[i], v->el[i], 2);
789 for (i = 0; i < node->nvar; ++i) {
790 isl_val *size;
792 size = isl_multi_val_get_val(node->sizes, i);
793 if (!size)
794 goto error;
795 if (!isl_val_is_int(size)) {
796 isl_val_free(size);
797 continue;
799 for (j = 0; j < node->nvar; ++j) {
800 if (j == i)
801 continue;
802 if (isl_int_is_neg(v->el[j]) ||
803 isl_int_gt(v->el[j], size->n))
804 isl_int_set(v->el[j], size->n);
806 isl_val_free(size);
809 for (i = 0; i < node->nvar; ++i) {
810 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
811 if (isl_int_is_zero(v->el[i]))
812 isl_int_set_si(v->el[i], 1);
815 node->max = v;
816 return isl_stat_ok;
817 error:
818 isl_vec_free(v);
819 return isl_stat_error;
822 /* Compute and return the size of "set" in dimension "dim".
823 * The size is taken to be the difference in values for that variable
824 * for fixed values of the other variables.
825 * In particular, the variable is first isolated from the other variables
826 * in the range of a map
828 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
830 * and then duplicated
832 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
834 * The shared variables are then projected out and the maximal value
835 * of i_dim' - i_dim is computed.
837 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
839 isl_map *map;
840 isl_local_space *ls;
841 isl_aff *obj;
842 isl_val *v;
844 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
845 map = isl_map_project_out(map, isl_dim_in, dim, 1);
846 map = isl_map_range_product(map, isl_map_copy(map));
847 map = isl_set_unwrap(isl_map_range(map));
848 set = isl_map_deltas(map);
849 ls = isl_local_space_from_space(isl_set_get_space(set));
850 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
851 v = isl_set_max_val(set, obj);
852 isl_aff_free(obj);
853 isl_set_free(set);
855 return v;
858 /* Compute the size of the instance set "set" of "node", after compression,
859 * as well as bounds on the corresponding coefficients, if needed.
861 * The sizes are needed when the schedule_treat_coalescing option is set.
862 * The bounds are needed when the schedule_treat_coalescing option or
863 * the schedule_max_coefficient option is set.
865 * If the schedule_treat_coalescing option is not set, then at most
866 * the bounds need to be set and this is done in set_max_coefficient.
867 * Otherwise, compress the domain if needed, compute the size
868 * in each direction and store the results in node->size.
869 * Finally, set the bounds on the coefficients based on the sizes
870 * and the schedule_max_coefficient option in compute_max_coefficient.
872 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
873 __isl_take isl_set *set)
875 int j, n;
876 isl_multi_val *mv;
878 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
879 isl_set_free(set);
880 return set_max_coefficient(ctx, node);
883 if (node->compressed)
884 set = isl_set_preimage_multi_aff(set,
885 isl_multi_aff_copy(node->decompress));
886 mv = isl_multi_val_zero(isl_set_get_space(set));
887 n = isl_set_dim(set, isl_dim_set);
888 for (j = 0; j < n; ++j) {
889 isl_val *v;
891 v = compute_size(isl_set_copy(set), j);
892 mv = isl_multi_val_set_val(mv, j, v);
894 node->sizes = mv;
895 isl_set_free(set);
896 if (!node->sizes)
897 return isl_stat_error;
898 return compute_max_coefficient(ctx, node);
901 /* Add a new node to the graph representing the given instance set.
902 * "nvar" is the (possibly compressed) number of variables and
903 * may be smaller than then number of set variables in "set"
904 * if "compressed" is set.
905 * If "compressed" is set, then "hull" represents the constraints
906 * that were used to derive the compression, while "compress" and
907 * "decompress" map the original space to the compressed space and
908 * vice versa.
909 * If "compressed" is not set, then "hull", "compress" and "decompress"
910 * should be NULL.
912 * Compute the size of the instance set and bounds on the coefficients,
913 * if needed.
915 static isl_stat add_node(struct isl_sched_graph *graph,
916 __isl_take isl_set *set, int nvar, int compressed,
917 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
918 __isl_take isl_multi_aff *decompress)
920 int nparam;
921 isl_ctx *ctx;
922 isl_mat *sched;
923 isl_space *space;
924 int *coincident;
925 struct isl_sched_node *node;
927 if (!set)
928 return isl_stat_error;
930 ctx = isl_set_get_ctx(set);
931 nparam = isl_set_dim(set, isl_dim_param);
932 if (!ctx->opt->schedule_parametric)
933 nparam = 0;
934 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
935 node = &graph->node[graph->n];
936 graph->n++;
937 space = isl_set_get_space(set);
938 node->space = space;
939 node->nvar = nvar;
940 node->nparam = nparam;
941 node->sched = sched;
942 node->sched_map = NULL;
943 coincident = isl_calloc_array(ctx, int, graph->max_row);
944 node->coincident = coincident;
945 node->compressed = compressed;
946 node->hull = hull;
947 node->compress = compress;
948 node->decompress = decompress;
949 if (compute_sizes_and_max(ctx, node, set) < 0)
950 return isl_stat_error;
952 if (!space || !sched || (graph->max_row && !coincident))
953 return isl_stat_error;
954 if (compressed && (!hull || !compress || !decompress))
955 return isl_stat_error;
957 return isl_stat_ok;
960 /* Add a new node to the graph representing the given set.
962 * If any of the set variables is defined by an equality, then
963 * we perform variable compression such that we can perform
964 * the scheduling on the compressed domain.
966 static isl_stat extract_node(__isl_take isl_set *set, void *user)
968 int nvar;
969 isl_bool has_equality;
970 isl_basic_set *hull;
971 isl_set *hull_set;
972 isl_morph *morph;
973 isl_multi_aff *compress, *decompress;
974 struct isl_sched_graph *graph = user;
976 hull = isl_set_affine_hull(isl_set_copy(set));
977 hull = isl_basic_set_remove_divs(hull);
978 nvar = isl_set_dim(set, isl_dim_set);
979 has_equality = has_any_defining_equality(hull);
981 if (has_equality < 0)
982 goto error;
983 if (!has_equality) {
984 isl_basic_set_free(hull);
985 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
988 morph = isl_basic_set_variable_compression(hull, isl_dim_set);
989 nvar = isl_morph_ran_dim(morph, isl_dim_set);
990 compress = isl_morph_get_var_multi_aff(morph);
991 morph = isl_morph_inverse(morph);
992 decompress = isl_morph_get_var_multi_aff(morph);
993 isl_morph_free(morph);
995 hull_set = isl_set_from_basic_set(hull);
996 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
997 error:
998 isl_basic_set_free(hull);
999 isl_set_free(set);
1000 return isl_stat_error;
1003 struct isl_extract_edge_data {
1004 enum isl_edge_type type;
1005 struct isl_sched_graph *graph;
1008 /* Merge edge2 into edge1, freeing the contents of edge2.
1009 * Return 0 on success and -1 on failure.
1011 * edge1 and edge2 are assumed to have the same value for the map field.
1013 static int merge_edge(struct isl_sched_edge *edge1,
1014 struct isl_sched_edge *edge2)
1016 edge1->types |= edge2->types;
1017 isl_map_free(edge2->map);
1019 if (is_condition(edge2)) {
1020 if (!edge1->tagged_condition)
1021 edge1->tagged_condition = edge2->tagged_condition;
1022 else
1023 edge1->tagged_condition =
1024 isl_union_map_union(edge1->tagged_condition,
1025 edge2->tagged_condition);
1028 if (is_conditional_validity(edge2)) {
1029 if (!edge1->tagged_validity)
1030 edge1->tagged_validity = edge2->tagged_validity;
1031 else
1032 edge1->tagged_validity =
1033 isl_union_map_union(edge1->tagged_validity,
1034 edge2->tagged_validity);
1037 if (is_condition(edge2) && !edge1->tagged_condition)
1038 return -1;
1039 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1040 return -1;
1042 return 0;
1045 /* Insert dummy tags in domain and range of "map".
1047 * In particular, if "map" is of the form
1049 * A -> B
1051 * then return
1053 * [A -> dummy_tag] -> [B -> dummy_tag]
1055 * where the dummy_tags are identical and equal to any dummy tags
1056 * introduced by any other call to this function.
1058 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1060 static char dummy;
1061 isl_ctx *ctx;
1062 isl_id *id;
1063 isl_space *space;
1064 isl_set *domain, *range;
1066 ctx = isl_map_get_ctx(map);
1068 id = isl_id_alloc(ctx, NULL, &dummy);
1069 space = isl_space_params(isl_map_get_space(map));
1070 space = isl_space_set_from_params(space);
1071 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1072 space = isl_space_map_from_set(space);
1074 domain = isl_map_wrap(map);
1075 range = isl_map_wrap(isl_map_universe(space));
1076 map = isl_map_from_domain_and_range(domain, range);
1077 map = isl_map_zip(map);
1079 return map;
1082 /* Given that at least one of "src" or "dst" is compressed, return
1083 * a map between the spaces of these nodes restricted to the affine
1084 * hull that was used in the compression.
1086 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1087 struct isl_sched_node *dst)
1089 isl_set *dom, *ran;
1091 if (src->compressed)
1092 dom = isl_set_copy(src->hull);
1093 else
1094 dom = isl_set_universe(isl_space_copy(src->space));
1095 if (dst->compressed)
1096 ran = isl_set_copy(dst->hull);
1097 else
1098 ran = isl_set_universe(isl_space_copy(dst->space));
1100 return isl_map_from_domain_and_range(dom, ran);
1103 /* Intersect the domains of the nested relations in domain and range
1104 * of "tagged" with "map".
1106 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1107 __isl_keep isl_map *map)
1109 isl_set *set;
1111 tagged = isl_map_zip(tagged);
1112 set = isl_map_wrap(isl_map_copy(map));
1113 tagged = isl_map_intersect_domain(tagged, set);
1114 tagged = isl_map_zip(tagged);
1115 return tagged;
1118 /* Return a pointer to the node that lives in the domain space of "map"
1119 * or NULL if there is no such node.
1121 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1122 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1124 struct isl_sched_node *node;
1125 isl_space *space;
1127 space = isl_space_domain(isl_map_get_space(map));
1128 node = graph_find_node(ctx, graph, space);
1129 isl_space_free(space);
1131 return node;
1134 /* Return a pointer to the node that lives in the range space of "map"
1135 * or NULL if there is no such node.
1137 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1138 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1140 struct isl_sched_node *node;
1141 isl_space *space;
1143 space = isl_space_range(isl_map_get_space(map));
1144 node = graph_find_node(ctx, graph, space);
1145 isl_space_free(space);
1147 return node;
1150 /* Add a new edge to the graph based on the given map
1151 * and add it to data->graph->edge_table[data->type].
1152 * If a dependence relation of a given type happens to be identical
1153 * to one of the dependence relations of a type that was added before,
1154 * then we don't create a new edge, but instead mark the original edge
1155 * as also representing a dependence of the current type.
1157 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1158 * may be specified as "tagged" dependence relations. That is, "map"
1159 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1160 * the dependence on iterations and a and b are tags.
1161 * edge->map is set to the relation containing the elements i -> j,
1162 * while edge->tagged_condition and edge->tagged_validity contain
1163 * the union of all the "map" relations
1164 * for which extract_edge is called that result in the same edge->map.
1166 * If the source or the destination node is compressed, then
1167 * intersect both "map" and "tagged" with the constraints that
1168 * were used to construct the compression.
1169 * This ensures that there are no schedule constraints defined
1170 * outside of these domains, while the scheduler no longer has
1171 * any control over those outside parts.
1173 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1175 isl_ctx *ctx = isl_map_get_ctx(map);
1176 struct isl_extract_edge_data *data = user;
1177 struct isl_sched_graph *graph = data->graph;
1178 struct isl_sched_node *src, *dst;
1179 struct isl_sched_edge *edge;
1180 isl_map *tagged = NULL;
1182 if (data->type == isl_edge_condition ||
1183 data->type == isl_edge_conditional_validity) {
1184 if (isl_map_can_zip(map)) {
1185 tagged = isl_map_copy(map);
1186 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1187 } else {
1188 tagged = insert_dummy_tags(isl_map_copy(map));
1192 src = find_domain_node(ctx, graph, map);
1193 dst = find_range_node(ctx, graph, map);
1195 if (!src || !dst) {
1196 isl_map_free(map);
1197 isl_map_free(tagged);
1198 return isl_stat_ok;
1201 if (src->compressed || dst->compressed) {
1202 isl_map *hull;
1203 hull = extract_hull(src, dst);
1204 if (tagged)
1205 tagged = map_intersect_domains(tagged, hull);
1206 map = isl_map_intersect(map, hull);
1209 graph->edge[graph->n_edge].src = src;
1210 graph->edge[graph->n_edge].dst = dst;
1211 graph->edge[graph->n_edge].map = map;
1212 graph->edge[graph->n_edge].types = 0;
1213 graph->edge[graph->n_edge].tagged_condition = NULL;
1214 graph->edge[graph->n_edge].tagged_validity = NULL;
1215 set_type(&graph->edge[graph->n_edge], data->type);
1216 if (data->type == isl_edge_condition)
1217 graph->edge[graph->n_edge].tagged_condition =
1218 isl_union_map_from_map(tagged);
1219 if (data->type == isl_edge_conditional_validity)
1220 graph->edge[graph->n_edge].tagged_validity =
1221 isl_union_map_from_map(tagged);
1223 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1224 if (!edge) {
1225 graph->n_edge++;
1226 return isl_stat_error;
1228 if (edge == &graph->edge[graph->n_edge])
1229 return graph_edge_table_add(ctx, graph, data->type,
1230 &graph->edge[graph->n_edge++]);
1232 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1233 return -1;
1235 return graph_edge_table_add(ctx, graph, data->type, edge);
1238 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1240 * The context is included in the domain before the nodes of
1241 * the graphs are extracted in order to be able to exploit
1242 * any possible additional equalities.
1243 * Note that this intersection is only performed locally here.
1245 static isl_stat graph_init(struct isl_sched_graph *graph,
1246 __isl_keep isl_schedule_constraints *sc)
1248 isl_ctx *ctx;
1249 isl_union_set *domain;
1250 isl_union_map *c;
1251 struct isl_extract_edge_data data;
1252 enum isl_edge_type i;
1253 isl_stat r;
1255 if (!sc)
1256 return isl_stat_error;
1258 ctx = isl_schedule_constraints_get_ctx(sc);
1260 domain = isl_schedule_constraints_get_domain(sc);
1261 graph->n = isl_union_set_n_set(domain);
1262 isl_union_set_free(domain);
1264 if (graph_alloc(ctx, graph, graph->n,
1265 isl_schedule_constraints_n_map(sc)) < 0)
1266 return isl_stat_error;
1268 if (compute_max_row(graph, sc) < 0)
1269 return isl_stat_error;
1270 graph->root = 1;
1271 graph->n = 0;
1272 domain = isl_schedule_constraints_get_domain(sc);
1273 domain = isl_union_set_intersect_params(domain,
1274 isl_schedule_constraints_get_context(sc));
1275 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1276 isl_union_set_free(domain);
1277 if (r < 0)
1278 return isl_stat_error;
1279 if (graph_init_table(ctx, graph) < 0)
1280 return isl_stat_error;
1281 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1282 c = isl_schedule_constraints_get(sc, i);
1283 graph->max_edge[i] = isl_union_map_n_map(c);
1284 isl_union_map_free(c);
1285 if (!c)
1286 return isl_stat_error;
1288 if (graph_init_edge_tables(ctx, graph) < 0)
1289 return isl_stat_error;
1290 graph->n_edge = 0;
1291 data.graph = graph;
1292 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1293 isl_stat r;
1295 data.type = i;
1296 c = isl_schedule_constraints_get(sc, i);
1297 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1298 isl_union_map_free(c);
1299 if (r < 0)
1300 return isl_stat_error;
1303 return isl_stat_ok;
1306 /* Check whether there is any dependence from node[j] to node[i]
1307 * or from node[i] to node[j].
1309 static isl_bool node_follows_weak(int i, int j, void *user)
1311 isl_bool f;
1312 struct isl_sched_graph *graph = user;
1314 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1315 if (f < 0 || f)
1316 return f;
1317 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1320 /* Check whether there is a (conditional) validity dependence from node[j]
1321 * to node[i], forcing node[i] to follow node[j].
1323 static isl_bool node_follows_strong(int i, int j, void *user)
1325 struct isl_sched_graph *graph = user;
1327 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1330 /* Use Tarjan's algorithm for computing the strongly connected components
1331 * in the dependence graph only considering those edges defined by "follows".
1333 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1334 isl_bool (*follows)(int i, int j, void *user))
1336 int i, n;
1337 struct isl_tarjan_graph *g = NULL;
1339 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1340 if (!g)
1341 return -1;
1343 graph->scc = 0;
1344 i = 0;
1345 n = graph->n;
1346 while (n) {
1347 while (g->order[i] != -1) {
1348 graph->node[g->order[i]].scc = graph->scc;
1349 --n;
1350 ++i;
1352 ++i;
1353 graph->scc++;
1356 isl_tarjan_graph_free(g);
1358 return 0;
1361 /* Apply Tarjan's algorithm to detect the strongly connected components
1362 * in the dependence graph.
1363 * Only consider the (conditional) validity dependences and clear "weak".
1365 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1367 graph->weak = 0;
1368 return detect_ccs(ctx, graph, &node_follows_strong);
1371 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1372 * in the dependence graph.
1373 * Consider all dependences and set "weak".
1375 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1377 graph->weak = 1;
1378 return detect_ccs(ctx, graph, &node_follows_weak);
1381 static int cmp_scc(const void *a, const void *b, void *data)
1383 struct isl_sched_graph *graph = data;
1384 const int *i1 = a;
1385 const int *i2 = b;
1387 return graph->node[*i1].scc - graph->node[*i2].scc;
1390 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1392 static int sort_sccs(struct isl_sched_graph *graph)
1394 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1397 /* Given a dependence relation R from "node" to itself,
1398 * construct the set of coefficients of valid constraints for elements
1399 * in that dependence relation.
1400 * In particular, the result contains tuples of coefficients
1401 * c_0, c_n, c_x such that
1403 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1405 * or, equivalently,
1407 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1409 * We choose here to compute the dual of delta R.
1410 * Alternatively, we could have computed the dual of R, resulting
1411 * in a set of tuples c_0, c_n, c_x, c_y, and then
1412 * plugged in (c_0, c_n, c_x, -c_x).
1414 * If "node" has been compressed, then the dependence relation
1415 * is also compressed before the set of coefficients is computed.
1417 static __isl_give isl_basic_set *intra_coefficients(
1418 struct isl_sched_graph *graph, struct isl_sched_node *node,
1419 __isl_take isl_map *map)
1421 isl_set *delta;
1422 isl_map *key;
1423 isl_basic_set *coef;
1424 isl_maybe_isl_basic_set m;
1426 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1427 if (m.valid < 0 || m.valid) {
1428 isl_map_free(map);
1429 return m.value;
1432 key = isl_map_copy(map);
1433 if (node->compressed) {
1434 map = isl_map_preimage_domain_multi_aff(map,
1435 isl_multi_aff_copy(node->decompress));
1436 map = isl_map_preimage_range_multi_aff(map,
1437 isl_multi_aff_copy(node->decompress));
1439 delta = isl_set_remove_divs(isl_map_deltas(map));
1440 coef = isl_set_coefficients(delta);
1441 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1442 isl_basic_set_copy(coef));
1444 return coef;
1447 /* Given a dependence relation R, construct the set of coefficients
1448 * of valid constraints for elements in that dependence relation.
1449 * In particular, the result contains tuples of coefficients
1450 * c_0, c_n, c_x, c_y such that
1452 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1454 * If the source or destination nodes of "edge" have been compressed,
1455 * then the dependence relation is also compressed before
1456 * the set of coefficients is computed.
1458 static __isl_give isl_basic_set *inter_coefficients(
1459 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1460 __isl_take isl_map *map)
1462 isl_set *set;
1463 isl_map *key;
1464 isl_basic_set *coef;
1465 isl_maybe_isl_basic_set m;
1467 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1468 if (m.valid < 0 || m.valid) {
1469 isl_map_free(map);
1470 return m.value;
1473 key = isl_map_copy(map);
1474 if (edge->src->compressed)
1475 map = isl_map_preimage_domain_multi_aff(map,
1476 isl_multi_aff_copy(edge->src->decompress));
1477 if (edge->dst->compressed)
1478 map = isl_map_preimage_range_multi_aff(map,
1479 isl_multi_aff_copy(edge->dst->decompress));
1480 set = isl_map_wrap(isl_map_remove_divs(map));
1481 coef = isl_set_coefficients(set);
1482 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1483 isl_basic_set_copy(coef));
1485 return coef;
1488 /* Return the position of the coefficients of the variables in
1489 * the coefficients constraints "coef".
1491 * The space of "coef" is of the form
1493 * { coefficients[[cst, params] -> S] }
1495 * Return the position of S.
1497 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1499 int offset;
1500 isl_space *space;
1502 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1503 offset = isl_space_dim(space, isl_dim_in);
1504 isl_space_free(space);
1506 return offset;
1509 /* Return the offset of the coefficients of the variables of "node"
1510 * within the (I)LP.
1512 * Within each node, the coefficients have the following order:
1513 * - c_i_0
1514 * - c_i_n (if parametric)
1515 * - positive and negative parts of c_i_x
1517 static int node_var_coef_offset(struct isl_sched_node *node)
1519 return node->start + 1 + node->nparam;
1522 /* Construct an isl_dim_map for mapping constraints on coefficients
1523 * for "node" to the corresponding positions in graph->lp.
1524 * "offset" is the offset of the coefficients for the variables
1525 * in the input constraints.
1526 * "s" is the sign of the mapping.
1528 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1529 * The mapping produced by this function essentially plugs in
1530 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1531 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1532 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1534 * The caller can extend the mapping to also map the other coefficients
1535 * (and therefore not plug in 0).
1537 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1538 struct isl_sched_graph *graph, struct isl_sched_node *node,
1539 int offset, int s)
1541 int pos;
1542 unsigned total;
1543 isl_dim_map *dim_map;
1545 total = isl_basic_set_total_dim(graph->lp);
1546 pos = node_var_coef_offset(node);
1547 dim_map = isl_dim_map_alloc(ctx, total);
1548 isl_dim_map_range(dim_map, pos, 2, offset, 1, node->nvar, -s);
1549 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, node->nvar, s);
1551 return dim_map;
1554 /* Construct an isl_dim_map for mapping constraints on coefficients
1555 * for "src" (node i) and "dst" (node j) to the corresponding positions
1556 * in graph->lp.
1557 * "offset" is the offset of the coefficients for the variables of "src"
1558 * in the input constraints.
1559 * "s" is the sign of the mapping.
1561 * The input constraints are given in terms of the coefficients
1562 * (c_0, c_n, c_x, c_y).
1563 * The mapping produced by this function essentially plugs in
1564 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1565 * c_j_x^+ - c_j_x^-, -(c_i_x^+ - c_i_x^-)) if s = 1 and
1566 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1567 * - (c_j_x^+ - c_j_x^-), c_i_x^+ - c_i_x^-) if s = -1.
1568 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1570 * The caller can further extend the mapping.
1572 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1573 struct isl_sched_graph *graph, struct isl_sched_node *src,
1574 struct isl_sched_node *dst, int offset, int s)
1576 int pos;
1577 unsigned total;
1578 isl_dim_map *dim_map;
1580 total = isl_basic_set_total_dim(graph->lp);
1581 dim_map = isl_dim_map_alloc(ctx, total);
1583 isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, s);
1584 isl_dim_map_range(dim_map, dst->start + 1, 1, 1, 1, dst->nparam, s);
1585 pos = node_var_coef_offset(dst);
1586 isl_dim_map_range(dim_map, pos, 2, offset + src->nvar, 1,
1587 dst->nvar, -s);
1588 isl_dim_map_range(dim_map, pos + 1, 2, offset + src->nvar, 1,
1589 dst->nvar, s);
1591 isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -s);
1592 isl_dim_map_range(dim_map, src->start + 1, 1, 1, 1, src->nparam, -s);
1593 pos = node_var_coef_offset(src);
1594 isl_dim_map_range(dim_map, pos, 2, offset, 1, src->nvar, s);
1595 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, src->nvar, -s);
1597 return dim_map;
1600 /* Add constraints to graph->lp that force validity for the given
1601 * dependence from a node i to itself.
1602 * That is, add constraints that enforce
1604 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1605 * = c_i_x (y - x) >= 0
1607 * for each (x,y) in R.
1608 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1609 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1610 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1611 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1613 * Actually, we do not construct constraints for the c_i_x themselves,
1614 * but for the coefficients of c_i_x written as a linear combination
1615 * of the columns in node->cmap.
1617 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1618 struct isl_sched_edge *edge)
1620 int offset;
1621 isl_map *map = isl_map_copy(edge->map);
1622 isl_ctx *ctx = isl_map_get_ctx(map);
1623 isl_dim_map *dim_map;
1624 isl_basic_set *coef;
1625 struct isl_sched_node *node = edge->src;
1627 coef = intra_coefficients(graph, node, map);
1629 offset = coef_var_offset(coef);
1631 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1632 offset, isl_mat_copy(node->cmap));
1633 if (!coef)
1634 return isl_stat_error;
1636 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1637 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1638 coef->n_eq, coef->n_ineq);
1639 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1640 coef, dim_map);
1642 return isl_stat_ok;
1645 /* Add constraints to graph->lp that force validity for the given
1646 * dependence from node i to node j.
1647 * That is, add constraints that enforce
1649 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1651 * for each (x,y) in R.
1652 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1653 * of valid constraints for R and then plug in
1654 * (c_j_0 - c_i_0, c_j_n - c_i_n, c_j_x^+ - c_j_x^- - (c_i_x^+ - c_i_x^-)),
1655 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1656 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1658 * Actually, we do not construct constraints for the c_*_x themselves,
1659 * but for the coefficients of c_*_x written as a linear combination
1660 * of the columns in node->cmap.
1662 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1663 struct isl_sched_edge *edge)
1665 int offset;
1666 isl_map *map = isl_map_copy(edge->map);
1667 isl_ctx *ctx = isl_map_get_ctx(map);
1668 isl_dim_map *dim_map;
1669 isl_basic_set *coef;
1670 struct isl_sched_node *src = edge->src;
1671 struct isl_sched_node *dst = edge->dst;
1673 coef = inter_coefficients(graph, edge, map);
1675 offset = coef_var_offset(coef);
1677 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1678 offset, isl_mat_copy(src->cmap));
1679 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1680 offset + src->nvar, isl_mat_copy(dst->cmap));
1681 if (!coef)
1682 return isl_stat_error;
1684 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1686 edge->start = graph->lp->n_ineq;
1687 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1688 coef->n_eq, coef->n_ineq);
1689 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1690 coef, dim_map);
1691 if (!graph->lp)
1692 return isl_stat_error;
1693 edge->end = graph->lp->n_ineq;
1695 return isl_stat_ok;
1698 /* Add constraints to graph->lp that bound the dependence distance for the given
1699 * dependence from a node i to itself.
1700 * If s = 1, we add the constraint
1702 * c_i_x (y - x) <= m_0 + m_n n
1704 * or
1706 * -c_i_x (y - x) + m_0 + m_n n >= 0
1708 * for each (x,y) in R.
1709 * If s = -1, we add the constraint
1711 * -c_i_x (y - x) <= m_0 + m_n n
1713 * or
1715 * c_i_x (y - x) + m_0 + m_n n >= 0
1717 * for each (x,y) in R.
1718 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1719 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1720 * with each coefficient (except m_0) represented as a pair of non-negative
1721 * coefficients.
1723 * Actually, we do not construct constraints for the c_i_x themselves,
1724 * but for the coefficients of c_i_x written as a linear combination
1725 * of the columns in node->cmap.
1728 * If "local" is set, then we add constraints
1730 * c_i_x (y - x) <= 0
1732 * or
1734 * -c_i_x (y - x) <= 0
1736 * instead, forcing the dependence distance to be (less than or) equal to 0.
1737 * That is, we plug in (0, 0, -s * c_i_x),
1738 * Note that dependences marked local are treated as validity constraints
1739 * by add_all_validity_constraints and therefore also have
1740 * their distances bounded by 0 from below.
1742 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1743 struct isl_sched_edge *edge, int s, int local)
1745 int offset;
1746 unsigned nparam;
1747 isl_map *map = isl_map_copy(edge->map);
1748 isl_ctx *ctx = isl_map_get_ctx(map);
1749 isl_dim_map *dim_map;
1750 isl_basic_set *coef;
1751 struct isl_sched_node *node = edge->src;
1753 coef = intra_coefficients(graph, node, map);
1755 offset = coef_var_offset(coef);
1757 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1758 offset, isl_mat_copy(node->cmap));
1759 if (!coef)
1760 return isl_stat_error;
1762 nparam = isl_space_dim(node->space, isl_dim_param);
1763 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1765 if (!local) {
1766 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1767 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1768 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1770 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1771 coef->n_eq, coef->n_ineq);
1772 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1773 coef, dim_map);
1775 return isl_stat_ok;
1778 /* Add constraints to graph->lp that bound the dependence distance for the given
1779 * dependence from node i to node j.
1780 * If s = 1, we add the constraint
1782 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1783 * <= m_0 + m_n n
1785 * or
1787 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1788 * m_0 + m_n n >= 0
1790 * for each (x,y) in R.
1791 * If s = -1, we add the constraint
1793 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1794 * <= m_0 + m_n n
1796 * or
1798 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1799 * m_0 + m_n n >= 0
1801 * for each (x,y) in R.
1802 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1803 * of valid constraints for R and then plug in
1804 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1805 * -s*c_j_x+s*c_i_x)
1806 * with each coefficient (except m_0, c_*_0 and c_*_n)
1807 * represented as a pair of non-negative coefficients.
1809 * Actually, we do not construct constraints for the c_*_x themselves,
1810 * but for the coefficients of c_*_x written as a linear combination
1811 * of the columns in node->cmap.
1814 * If "local" is set, then we add constraints
1816 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1818 * or
1820 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)) <= 0
1822 * instead, forcing the dependence distance to be (less than or) equal to 0.
1823 * That is, we plug in
1824 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, -s*c_j_x+s*c_i_x).
1825 * Note that dependences marked local are treated as validity constraints
1826 * by add_all_validity_constraints and therefore also have
1827 * their distances bounded by 0 from below.
1829 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1830 struct isl_sched_edge *edge, int s, int local)
1832 int offset;
1833 unsigned nparam;
1834 isl_map *map = isl_map_copy(edge->map);
1835 isl_ctx *ctx = isl_map_get_ctx(map);
1836 isl_dim_map *dim_map;
1837 isl_basic_set *coef;
1838 struct isl_sched_node *src = edge->src;
1839 struct isl_sched_node *dst = edge->dst;
1841 coef = inter_coefficients(graph, edge, map);
1843 offset = coef_var_offset(coef);
1845 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1846 offset, isl_mat_copy(src->cmap));
1847 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1848 offset + src->nvar, isl_mat_copy(dst->cmap));
1849 if (!coef)
1850 return isl_stat_error;
1852 nparam = isl_space_dim(src->space, isl_dim_param);
1853 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1855 if (!local) {
1856 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1857 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1858 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1861 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1862 coef->n_eq, coef->n_ineq);
1863 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1864 coef, dim_map);
1866 return isl_stat_ok;
1869 /* Add all validity constraints to graph->lp.
1871 * An edge that is forced to be local needs to have its dependence
1872 * distances equal to zero. We take care of bounding them by 0 from below
1873 * here. add_all_proximity_constraints takes care of bounding them by 0
1874 * from above.
1876 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1877 * Otherwise, we ignore them.
1879 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1880 int use_coincidence)
1882 int i;
1884 for (i = 0; i < graph->n_edge; ++i) {
1885 struct isl_sched_edge *edge= &graph->edge[i];
1886 int local;
1888 local = is_local(edge) ||
1889 (is_coincidence(edge) && use_coincidence);
1890 if (!is_validity(edge) && !local)
1891 continue;
1892 if (edge->src != edge->dst)
1893 continue;
1894 if (add_intra_validity_constraints(graph, edge) < 0)
1895 return -1;
1898 for (i = 0; i < graph->n_edge; ++i) {
1899 struct isl_sched_edge *edge = &graph->edge[i];
1900 int local;
1902 local = is_local(edge) ||
1903 (is_coincidence(edge) && use_coincidence);
1904 if (!is_validity(edge) && !local)
1905 continue;
1906 if (edge->src == edge->dst)
1907 continue;
1908 if (add_inter_validity_constraints(graph, edge) < 0)
1909 return -1;
1912 return 0;
1915 /* Add constraints to graph->lp that bound the dependence distance
1916 * for all dependence relations.
1917 * If a given proximity dependence is identical to a validity
1918 * dependence, then the dependence distance is already bounded
1919 * from below (by zero), so we only need to bound the distance
1920 * from above. (This includes the case of "local" dependences
1921 * which are treated as validity dependence by add_all_validity_constraints.)
1922 * Otherwise, we need to bound the distance both from above and from below.
1924 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1925 * Otherwise, we ignore them.
1927 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
1928 int use_coincidence)
1930 int i;
1932 for (i = 0; i < graph->n_edge; ++i) {
1933 struct isl_sched_edge *edge= &graph->edge[i];
1934 int local;
1936 local = is_local(edge) ||
1937 (is_coincidence(edge) && use_coincidence);
1938 if (!is_proximity(edge) && !local)
1939 continue;
1940 if (edge->src == edge->dst &&
1941 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
1942 return -1;
1943 if (edge->src != edge->dst &&
1944 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
1945 return -1;
1946 if (is_validity(edge) || local)
1947 continue;
1948 if (edge->src == edge->dst &&
1949 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
1950 return -1;
1951 if (edge->src != edge->dst &&
1952 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
1953 return -1;
1956 return 0;
1959 /* Compute a basis for the rows in the linear part of the schedule
1960 * and extend this basis to a full basis. The remaining rows
1961 * can then be used to force linear independence from the rows
1962 * in the schedule.
1964 * In particular, given the schedule rows S, we compute
1966 * S = H Q
1967 * S U = H
1969 * with H the Hermite normal form of S. That is, all but the
1970 * first rank columns of H are zero and so each row in S is
1971 * a linear combination of the first rank rows of Q.
1972 * The matrix Q is then transposed because we will write the
1973 * coefficients of the next schedule row as a column vector s
1974 * and express this s as a linear combination s = Q c of the
1975 * computed basis.
1976 * Similarly, the matrix U is transposed such that we can
1977 * compute the coefficients c = U s from a schedule row s.
1979 static int node_update_cmap(struct isl_sched_node *node)
1981 isl_mat *H, *U, *Q;
1982 int n_row = isl_mat_rows(node->sched);
1984 H = isl_mat_sub_alloc(node->sched, 0, n_row,
1985 1 + node->nparam, node->nvar);
1987 H = isl_mat_left_hermite(H, 0, &U, &Q);
1988 isl_mat_free(node->cmap);
1989 isl_mat_free(node->cinv);
1990 isl_mat_free(node->ctrans);
1991 node->ctrans = isl_mat_copy(Q);
1992 node->cmap = isl_mat_transpose(Q);
1993 node->cinv = isl_mat_transpose(U);
1994 node->rank = isl_mat_initial_non_zero_cols(H);
1995 isl_mat_free(H);
1997 if (!node->cmap || !node->cinv || !node->ctrans || node->rank < 0)
1998 return -1;
1999 return 0;
2002 /* Is "edge" marked as a validity or a conditional validity edge?
2004 static int is_any_validity(struct isl_sched_edge *edge)
2006 return is_validity(edge) || is_conditional_validity(edge);
2009 /* How many times should we count the constraints in "edge"?
2011 * If carry is set, then we are counting the number of
2012 * (validity or conditional validity) constraints that will be added
2013 * in setup_carry_lp and we count each edge exactly once.
2015 * Otherwise, we count as follows
2016 * validity -> 1 (>= 0)
2017 * validity+proximity -> 2 (>= 0 and upper bound)
2018 * proximity -> 2 (lower and upper bound)
2019 * local(+any) -> 2 (>= 0 and <= 0)
2021 * If an edge is only marked conditional_validity then it counts
2022 * as zero since it is only checked afterwards.
2024 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2025 * Otherwise, we ignore them.
2027 static int edge_multiplicity(struct isl_sched_edge *edge, int carry,
2028 int use_coincidence)
2030 if (carry)
2031 return 1;
2032 if (is_proximity(edge) || is_local(edge))
2033 return 2;
2034 if (use_coincidence && is_coincidence(edge))
2035 return 2;
2036 if (is_validity(edge))
2037 return 1;
2038 return 0;
2041 /* Count the number of equality and inequality constraints
2042 * that will be added for the given map.
2044 * "use_coincidence" is set if we should take into account coincidence edges.
2046 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2047 struct isl_sched_edge *edge, __isl_take isl_map *map,
2048 int *n_eq, int *n_ineq, int carry, int use_coincidence)
2050 isl_basic_set *coef;
2051 int f = edge_multiplicity(edge, carry, use_coincidence);
2053 if (f == 0) {
2054 isl_map_free(map);
2055 return isl_stat_ok;
2058 if (edge->src == edge->dst)
2059 coef = intra_coefficients(graph, edge->src, map);
2060 else
2061 coef = inter_coefficients(graph, edge, map);
2062 if (!coef)
2063 return isl_stat_error;
2064 *n_eq += f * coef->n_eq;
2065 *n_ineq += f * coef->n_ineq;
2066 isl_basic_set_free(coef);
2068 return isl_stat_ok;
2071 /* Count the number of equality and inequality constraints
2072 * that will be added to the main lp problem.
2073 * We count as follows
2074 * validity -> 1 (>= 0)
2075 * validity+proximity -> 2 (>= 0 and upper bound)
2076 * proximity -> 2 (lower and upper bound)
2077 * local(+any) -> 2 (>= 0 and <= 0)
2079 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2080 * Otherwise, we ignore them.
2082 static int count_constraints(struct isl_sched_graph *graph,
2083 int *n_eq, int *n_ineq, int use_coincidence)
2085 int i;
2087 *n_eq = *n_ineq = 0;
2088 for (i = 0; i < graph->n_edge; ++i) {
2089 struct isl_sched_edge *edge= &graph->edge[i];
2090 isl_map *map = isl_map_copy(edge->map);
2092 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2093 0, use_coincidence) < 0)
2094 return -1;
2097 return 0;
2100 /* Count the number of constraints that will be added by
2101 * add_bound_constant_constraints to bound the values of the constant terms
2102 * and increment *n_eq and *n_ineq accordingly.
2104 * In practice, add_bound_constant_constraints only adds inequalities.
2106 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2107 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2109 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2110 return isl_stat_ok;
2112 *n_ineq += graph->n;
2114 return isl_stat_ok;
2117 /* Add constraints to bound the values of the constant terms in the schedule,
2118 * if requested by the user.
2120 * The maximal value of the constant terms is defined by the option
2121 * "schedule_max_constant_term".
2123 * Within each node, the coefficients have the following order:
2124 * - c_i_0
2125 * - c_i_n (if parametric)
2126 * - positive and negative parts of c_i_x
2128 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2129 struct isl_sched_graph *graph)
2131 int i, k;
2132 int max;
2133 int total;
2135 max = isl_options_get_schedule_max_constant_term(ctx);
2136 if (max == -1)
2137 return isl_stat_ok;
2139 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2141 for (i = 0; i < graph->n; ++i) {
2142 struct isl_sched_node *node = &graph->node[i];
2143 k = isl_basic_set_alloc_inequality(graph->lp);
2144 if (k < 0)
2145 return isl_stat_error;
2146 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2147 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2148 isl_int_set_si(graph->lp->ineq[k][0], max);
2151 return isl_stat_ok;
2154 /* Count the number of constraints that will be added by
2155 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2156 * accordingly.
2158 * In practice, add_bound_coefficient_constraints only adds inequalities.
2160 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2161 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2163 int i;
2165 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2166 !isl_options_get_schedule_treat_coalescing(ctx))
2167 return 0;
2169 for (i = 0; i < graph->n; ++i)
2170 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2172 return 0;
2175 /* Add constraints to graph->lp that bound the values of
2176 * the parameter schedule coefficients of "node" to "max" and
2177 * the variable schedule coefficients to the corresponding entry
2178 * in node->max.
2179 * In either case, a negative value means that no bound needs to be imposed.
2181 * For parameter coefficients, this amounts to adding a constraint
2183 * c_n <= max
2185 * i.e.,
2187 * -c_n + max >= 0
2189 * The variables coefficients are, however, not represented directly.
2190 * Instead, the variables coefficients c_x are written as a linear
2191 * combination c_x = cmap c_z of some other coefficients c_z,
2192 * which are in turn encoded as c_z = c_z^+ - c_z^-.
2193 * Let a_j be the elements of row i of node->cmap, then
2195 * -max_i <= c_x_i <= max_i
2197 * is encoded as
2199 * -max_i <= \sum_j a_j (c_z_j^+ - c_z_j^-) <= max_i
2201 * or
2203 * -\sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2204 * \sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2206 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2207 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2209 int i, j, k;
2210 int total;
2211 isl_vec *ineq;
2213 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2215 for (j = 0; j < node->nparam; ++j) {
2216 int dim;
2218 if (max < 0)
2219 continue;
2221 k = isl_basic_set_alloc_inequality(graph->lp);
2222 if (k < 0)
2223 return isl_stat_error;
2224 dim = 1 + node->start + 1 + j;
2225 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2226 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2227 isl_int_set_si(graph->lp->ineq[k][0], max);
2230 ineq = isl_vec_alloc(ctx, 1 + total);
2231 ineq = isl_vec_clr(ineq);
2232 if (!ineq)
2233 return isl_stat_error;
2234 for (i = 0; i < node->nvar; ++i) {
2235 int pos = 1 + node_var_coef_offset(node);
2237 if (isl_int_is_neg(node->max->el[i]))
2238 continue;
2240 for (j = 0; j < node->nvar; ++j) {
2241 isl_int_set(ineq->el[pos + 2 * j],
2242 node->cmap->row[i][j]);
2243 isl_int_neg(ineq->el[pos + 2 * j + 1],
2244 node->cmap->row[i][j]);
2246 isl_int_set(ineq->el[0], node->max->el[i]);
2248 k = isl_basic_set_alloc_inequality(graph->lp);
2249 if (k < 0)
2250 goto error;
2251 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2253 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2 * node->nvar);
2254 k = isl_basic_set_alloc_inequality(graph->lp);
2255 if (k < 0)
2256 goto error;
2257 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2259 isl_vec_free(ineq);
2261 return isl_stat_ok;
2262 error:
2263 isl_vec_free(ineq);
2264 return isl_stat_error;
2267 /* Add constraints that bound the values of the variable and parameter
2268 * coefficients of the schedule.
2270 * The maximal value of the coefficients is defined by the option
2271 * 'schedule_max_coefficient' and the entries in node->max.
2272 * These latter entries are only set if either the schedule_max_coefficient
2273 * option or the schedule_treat_coalescing option is set.
2275 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2276 struct isl_sched_graph *graph)
2278 int i;
2279 int max;
2281 max = isl_options_get_schedule_max_coefficient(ctx);
2283 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2284 return isl_stat_ok;
2286 for (i = 0; i < graph->n; ++i) {
2287 struct isl_sched_node *node = &graph->node[i];
2289 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2290 return isl_stat_error;
2293 return isl_stat_ok;
2296 /* Add a constraint to graph->lp that equates the value at position
2297 * "sum_pos" to the sum of the "n" values starting at "first".
2299 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2300 int sum_pos, int first, int n)
2302 int i, k;
2303 int total;
2305 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2307 k = isl_basic_set_alloc_equality(graph->lp);
2308 if (k < 0)
2309 return isl_stat_error;
2310 isl_seq_clr(graph->lp->eq[k], 1 + total);
2311 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2312 for (i = 0; i < n; ++i)
2313 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2315 return isl_stat_ok;
2318 /* Add a constraint to graph->lp that equates the value at position
2319 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2321 * Within each node, the coefficients have the following order:
2322 * - c_i_0
2323 * - c_i_n (if parametric)
2324 * - positive and negative parts of c_i_x
2326 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2327 int sum_pos)
2329 int i, j, k;
2330 int total;
2332 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2334 k = isl_basic_set_alloc_equality(graph->lp);
2335 if (k < 0)
2336 return isl_stat_error;
2337 isl_seq_clr(graph->lp->eq[k], 1 + total);
2338 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2339 for (i = 0; i < graph->n; ++i) {
2340 int pos = 1 + graph->node[i].start + 1;
2342 for (j = 0; j < graph->node[i].nparam; ++j)
2343 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2346 return isl_stat_ok;
2349 /* Add a constraint to graph->lp that equates the value at position
2350 * "sum_pos" to the sum of the variable coefficients of all nodes.
2352 * Within each node, the coefficients have the following order:
2353 * - c_i_0
2354 * - c_i_n (if parametric)
2355 * - positive and negative parts of c_i_x
2357 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2358 int sum_pos)
2360 int i, j, k;
2361 int total;
2363 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2365 k = isl_basic_set_alloc_equality(graph->lp);
2366 if (k < 0)
2367 return isl_stat_error;
2368 isl_seq_clr(graph->lp->eq[k], 1 + total);
2369 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2370 for (i = 0; i < graph->n; ++i) {
2371 struct isl_sched_node *node = &graph->node[i];
2372 int pos = 1 + node_var_coef_offset(node);
2374 for (j = 0; j < 2 * node->nvar; ++j)
2375 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2378 return isl_stat_ok;
2381 /* Construct an ILP problem for finding schedule coefficients
2382 * that result in non-negative, but small dependence distances
2383 * over all dependences.
2384 * In particular, the dependence distances over proximity edges
2385 * are bounded by m_0 + m_n n and we compute schedule coefficients
2386 * with small values (preferably zero) of m_n and m_0.
2388 * All variables of the ILP are non-negative. The actual coefficients
2389 * may be negative, so each coefficient is represented as the difference
2390 * of two non-negative variables. The negative part always appears
2391 * immediately before the positive part.
2392 * Other than that, the variables have the following order
2394 * - sum of positive and negative parts of m_n coefficients
2395 * - m_0
2396 * - sum of all c_n coefficients
2397 * (unconstrained when computing non-parametric schedules)
2398 * - sum of positive and negative parts of all c_x coefficients
2399 * - positive and negative parts of m_n coefficients
2400 * - for each node
2401 * - c_i_0
2402 * - c_i_n (if parametric)
2403 * - positive and negative parts of c_i_x
2405 * The c_i_x are not represented directly, but through the columns of
2406 * node->cmap. That is, the computed values are for variable t_i_x
2407 * such that c_i_x = Q t_i_x with Q equal to node->cmap.
2409 * The constraints are those from the edges plus two or three equalities
2410 * to express the sums.
2412 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2413 * Otherwise, we ignore them.
2415 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2416 int use_coincidence)
2418 int i;
2419 unsigned nparam;
2420 unsigned total;
2421 isl_space *space;
2422 int parametric;
2423 int param_pos;
2424 int n_eq, n_ineq;
2426 parametric = ctx->opt->schedule_parametric;
2427 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2428 param_pos = 4;
2429 total = param_pos + 2 * nparam;
2430 for (i = 0; i < graph->n; ++i) {
2431 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2432 if (node_update_cmap(node) < 0)
2433 return isl_stat_error;
2434 node->start = total;
2435 total += 1 + node->nparam + 2 * node->nvar;
2438 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2439 return isl_stat_error;
2440 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2441 return isl_stat_error;
2442 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2443 return isl_stat_error;
2445 space = isl_space_set_alloc(ctx, 0, total);
2446 isl_basic_set_free(graph->lp);
2447 n_eq += 2 + parametric;
2449 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2451 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2452 return isl_stat_error;
2453 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2454 return isl_stat_error;
2455 if (add_var_sum_constraint(graph, 3) < 0)
2456 return isl_stat_error;
2457 if (add_bound_constant_constraints(ctx, graph) < 0)
2458 return isl_stat_error;
2459 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2460 return isl_stat_error;
2461 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2462 return isl_stat_error;
2463 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2464 return isl_stat_error;
2466 return isl_stat_ok;
2469 /* Analyze the conflicting constraint found by
2470 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2471 * constraint of one of the edges between distinct nodes, living, moreover
2472 * in distinct SCCs, then record the source and sink SCC as this may
2473 * be a good place to cut between SCCs.
2475 static int check_conflict(int con, void *user)
2477 int i;
2478 struct isl_sched_graph *graph = user;
2480 if (graph->src_scc >= 0)
2481 return 0;
2483 con -= graph->lp->n_eq;
2485 if (con >= graph->lp->n_ineq)
2486 return 0;
2488 for (i = 0; i < graph->n_edge; ++i) {
2489 if (!is_validity(&graph->edge[i]))
2490 continue;
2491 if (graph->edge[i].src == graph->edge[i].dst)
2492 continue;
2493 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2494 continue;
2495 if (graph->edge[i].start > con)
2496 continue;
2497 if (graph->edge[i].end <= con)
2498 continue;
2499 graph->src_scc = graph->edge[i].src->scc;
2500 graph->dst_scc = graph->edge[i].dst->scc;
2503 return 0;
2506 /* Check whether the next schedule row of the given node needs to be
2507 * non-trivial. Lower-dimensional domains may have some trivial rows,
2508 * but as soon as the number of remaining required non-trivial rows
2509 * is as large as the number or remaining rows to be computed,
2510 * all remaining rows need to be non-trivial.
2512 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2514 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2517 /* Solve the ILP problem constructed in setup_lp.
2518 * For each node such that all the remaining rows of its schedule
2519 * need to be non-trivial, we construct a non-triviality region.
2520 * This region imposes that the next row is independent of previous rows.
2521 * In particular the coefficients c_i_x are represented by t_i_x
2522 * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
2523 * its first columns span the rows of the previously computed part
2524 * of the schedule. The non-triviality region enforces that at least
2525 * one of the remaining components of t_i_x is non-zero, i.e.,
2526 * that the new schedule row depends on at least one of the remaining
2527 * columns of Q.
2529 static __isl_give isl_vec *solve_lp(struct isl_sched_graph *graph)
2531 int i;
2532 isl_vec *sol;
2533 isl_basic_set *lp;
2535 for (i = 0; i < graph->n; ++i) {
2536 struct isl_sched_node *node = &graph->node[i];
2537 int skip = node->rank;
2538 graph->region[i].pos = node_var_coef_offset(node) + 2 * skip;
2539 if (needs_row(graph, node))
2540 graph->region[i].len = 2 * (node->nvar - skip);
2541 else
2542 graph->region[i].len = 0;
2544 lp = isl_basic_set_copy(graph->lp);
2545 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2546 graph->region, &check_conflict, graph);
2547 return sol;
2550 /* Extract the coefficients for the variables of "node" from "sol".
2552 * Within each node, the coefficients have the following order:
2553 * - c_i_0
2554 * - c_i_n (if parametric)
2555 * - positive and negative parts of c_i_x
2557 * The c_i_x^- appear before their c_i_x^+ counterpart.
2559 * Return c_i_x = c_i_x^+ - c_i_x^-
2561 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2562 __isl_keep isl_vec *sol)
2564 int i;
2565 int pos;
2566 isl_vec *csol;
2568 if (!sol)
2569 return NULL;
2570 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2571 if (!csol)
2572 return NULL;
2574 pos = 1 + node_var_coef_offset(node);
2575 for (i = 0; i < node->nvar; ++i)
2576 isl_int_sub(csol->el[i],
2577 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2579 return csol;
2582 /* Update the schedules of all nodes based on the given solution
2583 * of the LP problem.
2584 * The new row is added to the current band.
2585 * All possibly negative coefficients are encoded as a difference
2586 * of two non-negative variables, so we need to perform the subtraction
2587 * here. Moreover, if use_cmap is set, then the solution does
2588 * not refer to the actual coefficients c_i_x, but instead to variables
2589 * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
2590 * In this case, we then also need to perform this multiplication
2591 * to obtain the values of c_i_x.
2593 * If coincident is set, then the caller guarantees that the new
2594 * row satisfies the coincidence constraints.
2596 static int update_schedule(struct isl_sched_graph *graph,
2597 __isl_take isl_vec *sol, int use_cmap, int coincident)
2599 int i, j;
2600 isl_vec *csol = NULL;
2602 if (!sol)
2603 goto error;
2604 if (sol->size == 0)
2605 isl_die(sol->ctx, isl_error_internal,
2606 "no solution found", goto error);
2607 if (graph->n_total_row >= graph->max_row)
2608 isl_die(sol->ctx, isl_error_internal,
2609 "too many schedule rows", goto error);
2611 for (i = 0; i < graph->n; ++i) {
2612 struct isl_sched_node *node = &graph->node[i];
2613 int pos = node->start;
2614 int row = isl_mat_rows(node->sched);
2616 isl_vec_free(csol);
2617 csol = extract_var_coef(node, sol);
2618 if (!csol)
2619 goto error;
2621 isl_map_free(node->sched_map);
2622 node->sched_map = NULL;
2623 node->sched = isl_mat_add_rows(node->sched, 1);
2624 if (!node->sched)
2625 goto error;
2626 for (j = 0; j < 1 + node->nparam; ++j)
2627 node->sched = isl_mat_set_element(node->sched,
2628 row, j, sol->el[1 + pos + j]);
2629 if (use_cmap)
2630 csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
2631 csol);
2632 if (!csol)
2633 goto error;
2634 for (j = 0; j < node->nvar; ++j)
2635 node->sched = isl_mat_set_element(node->sched,
2636 row, 1 + node->nparam + j, csol->el[j]);
2637 node->coincident[graph->n_total_row] = coincident;
2639 isl_vec_free(sol);
2640 isl_vec_free(csol);
2642 graph->n_row++;
2643 graph->n_total_row++;
2645 return 0;
2646 error:
2647 isl_vec_free(sol);
2648 isl_vec_free(csol);
2649 return -1;
2652 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2653 * and return this isl_aff.
2655 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2656 struct isl_sched_node *node, int row)
2658 int j;
2659 isl_int v;
2660 isl_aff *aff;
2662 isl_int_init(v);
2664 aff = isl_aff_zero_on_domain(ls);
2665 isl_mat_get_element(node->sched, row, 0, &v);
2666 aff = isl_aff_set_constant(aff, v);
2667 for (j = 0; j < node->nparam; ++j) {
2668 isl_mat_get_element(node->sched, row, 1 + j, &v);
2669 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2671 for (j = 0; j < node->nvar; ++j) {
2672 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2673 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2676 isl_int_clear(v);
2678 return aff;
2681 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2682 * and return this multi_aff.
2684 * The result is defined over the uncompressed node domain.
2686 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2687 struct isl_sched_node *node, int first, int n)
2689 int i;
2690 isl_space *space;
2691 isl_local_space *ls;
2692 isl_aff *aff;
2693 isl_multi_aff *ma;
2694 int nrow;
2696 if (!node)
2697 return NULL;
2698 nrow = isl_mat_rows(node->sched);
2699 if (node->compressed)
2700 space = isl_multi_aff_get_domain_space(node->decompress);
2701 else
2702 space = isl_space_copy(node->space);
2703 ls = isl_local_space_from_space(isl_space_copy(space));
2704 space = isl_space_from_domain(space);
2705 space = isl_space_add_dims(space, isl_dim_out, n);
2706 ma = isl_multi_aff_zero(space);
2708 for (i = first; i < first + n; ++i) {
2709 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2710 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2713 isl_local_space_free(ls);
2715 if (node->compressed)
2716 ma = isl_multi_aff_pullback_multi_aff(ma,
2717 isl_multi_aff_copy(node->compress));
2719 return ma;
2722 /* Convert node->sched into a multi_aff and return this multi_aff.
2724 * The result is defined over the uncompressed node domain.
2726 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2727 struct isl_sched_node *node)
2729 int nrow;
2731 nrow = isl_mat_rows(node->sched);
2732 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2735 /* Convert node->sched into a map and return this map.
2737 * The result is cached in node->sched_map, which needs to be released
2738 * whenever node->sched is updated.
2739 * It is defined over the uncompressed node domain.
2741 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2743 if (!node->sched_map) {
2744 isl_multi_aff *ma;
2746 ma = node_extract_schedule_multi_aff(node);
2747 node->sched_map = isl_map_from_multi_aff(ma);
2750 return isl_map_copy(node->sched_map);
2753 /* Construct a map that can be used to update a dependence relation
2754 * based on the current schedule.
2755 * That is, construct a map expressing that source and sink
2756 * are executed within the same iteration of the current schedule.
2757 * This map can then be intersected with the dependence relation.
2758 * This is not the most efficient way, but this shouldn't be a critical
2759 * operation.
2761 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2762 struct isl_sched_node *dst)
2764 isl_map *src_sched, *dst_sched;
2766 src_sched = node_extract_schedule(src);
2767 dst_sched = node_extract_schedule(dst);
2768 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2771 /* Intersect the domains of the nested relations in domain and range
2772 * of "umap" with "map".
2774 static __isl_give isl_union_map *intersect_domains(
2775 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2777 isl_union_set *uset;
2779 umap = isl_union_map_zip(umap);
2780 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2781 umap = isl_union_map_intersect_domain(umap, uset);
2782 umap = isl_union_map_zip(umap);
2783 return umap;
2786 /* Update the dependence relation of the given edge based
2787 * on the current schedule.
2788 * If the dependence is carried completely by the current schedule, then
2789 * it is removed from the edge_tables. It is kept in the list of edges
2790 * as otherwise all edge_tables would have to be recomputed.
2792 static int update_edge(struct isl_sched_graph *graph,
2793 struct isl_sched_edge *edge)
2795 int empty;
2796 isl_map *id;
2798 id = specializer(edge->src, edge->dst);
2799 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2800 if (!edge->map)
2801 goto error;
2803 if (edge->tagged_condition) {
2804 edge->tagged_condition =
2805 intersect_domains(edge->tagged_condition, id);
2806 if (!edge->tagged_condition)
2807 goto error;
2809 if (edge->tagged_validity) {
2810 edge->tagged_validity =
2811 intersect_domains(edge->tagged_validity, id);
2812 if (!edge->tagged_validity)
2813 goto error;
2816 empty = isl_map_plain_is_empty(edge->map);
2817 if (empty < 0)
2818 goto error;
2819 if (empty)
2820 graph_remove_edge(graph, edge);
2822 isl_map_free(id);
2823 return 0;
2824 error:
2825 isl_map_free(id);
2826 return -1;
2829 /* Does the domain of "umap" intersect "uset"?
2831 static int domain_intersects(__isl_keep isl_union_map *umap,
2832 __isl_keep isl_union_set *uset)
2834 int empty;
2836 umap = isl_union_map_copy(umap);
2837 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2838 empty = isl_union_map_is_empty(umap);
2839 isl_union_map_free(umap);
2841 return empty < 0 ? -1 : !empty;
2844 /* Does the range of "umap" intersect "uset"?
2846 static int range_intersects(__isl_keep isl_union_map *umap,
2847 __isl_keep isl_union_set *uset)
2849 int empty;
2851 umap = isl_union_map_copy(umap);
2852 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2853 empty = isl_union_map_is_empty(umap);
2854 isl_union_map_free(umap);
2856 return empty < 0 ? -1 : !empty;
2859 /* Are the condition dependences of "edge" local with respect to
2860 * the current schedule?
2862 * That is, are domain and range of the condition dependences mapped
2863 * to the same point?
2865 * In other words, is the condition false?
2867 static int is_condition_false(struct isl_sched_edge *edge)
2869 isl_union_map *umap;
2870 isl_map *map, *sched, *test;
2871 int empty, local;
2873 empty = isl_union_map_is_empty(edge->tagged_condition);
2874 if (empty < 0 || empty)
2875 return empty;
2877 umap = isl_union_map_copy(edge->tagged_condition);
2878 umap = isl_union_map_zip(umap);
2879 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2880 map = isl_map_from_union_map(umap);
2882 sched = node_extract_schedule(edge->src);
2883 map = isl_map_apply_domain(map, sched);
2884 sched = node_extract_schedule(edge->dst);
2885 map = isl_map_apply_range(map, sched);
2887 test = isl_map_identity(isl_map_get_space(map));
2888 local = isl_map_is_subset(map, test);
2889 isl_map_free(map);
2890 isl_map_free(test);
2892 return local;
2895 /* For each conditional validity constraint that is adjacent
2896 * to a condition with domain in condition_source or range in condition_sink,
2897 * turn it into an unconditional validity constraint.
2899 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2900 __isl_take isl_union_set *condition_source,
2901 __isl_take isl_union_set *condition_sink)
2903 int i;
2905 condition_source = isl_union_set_coalesce(condition_source);
2906 condition_sink = isl_union_set_coalesce(condition_sink);
2908 for (i = 0; i < graph->n_edge; ++i) {
2909 int adjacent;
2910 isl_union_map *validity;
2912 if (!is_conditional_validity(&graph->edge[i]))
2913 continue;
2914 if (is_validity(&graph->edge[i]))
2915 continue;
2917 validity = graph->edge[i].tagged_validity;
2918 adjacent = domain_intersects(validity, condition_sink);
2919 if (adjacent >= 0 && !adjacent)
2920 adjacent = range_intersects(validity, condition_source);
2921 if (adjacent < 0)
2922 goto error;
2923 if (!adjacent)
2924 continue;
2926 set_validity(&graph->edge[i]);
2929 isl_union_set_free(condition_source);
2930 isl_union_set_free(condition_sink);
2931 return 0;
2932 error:
2933 isl_union_set_free(condition_source);
2934 isl_union_set_free(condition_sink);
2935 return -1;
2938 /* Update the dependence relations of all edges based on the current schedule
2939 * and enforce conditional validity constraints that are adjacent
2940 * to satisfied condition constraints.
2942 * First check if any of the condition constraints are satisfied
2943 * (i.e., not local to the outer schedule) and keep track of
2944 * their domain and range.
2945 * Then update all dependence relations (which removes the non-local
2946 * constraints).
2947 * Finally, if any condition constraints turned out to be satisfied,
2948 * then turn all adjacent conditional validity constraints into
2949 * unconditional validity constraints.
2951 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
2953 int i;
2954 int any = 0;
2955 isl_union_set *source, *sink;
2957 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
2958 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
2959 for (i = 0; i < graph->n_edge; ++i) {
2960 int local;
2961 isl_union_set *uset;
2962 isl_union_map *umap;
2964 if (!is_condition(&graph->edge[i]))
2965 continue;
2966 if (is_local(&graph->edge[i]))
2967 continue;
2968 local = is_condition_false(&graph->edge[i]);
2969 if (local < 0)
2970 goto error;
2971 if (local)
2972 continue;
2974 any = 1;
2976 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
2977 uset = isl_union_map_domain(umap);
2978 source = isl_union_set_union(source, uset);
2980 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
2981 uset = isl_union_map_range(umap);
2982 sink = isl_union_set_union(sink, uset);
2985 for (i = graph->n_edge - 1; i >= 0; --i) {
2986 if (update_edge(graph, &graph->edge[i]) < 0)
2987 goto error;
2990 if (any)
2991 return unconditionalize_adjacent_validity(graph, source, sink);
2993 isl_union_set_free(source);
2994 isl_union_set_free(sink);
2995 return 0;
2996 error:
2997 isl_union_set_free(source);
2998 isl_union_set_free(sink);
2999 return -1;
3002 static void next_band(struct isl_sched_graph *graph)
3004 graph->band_start = graph->n_total_row;
3007 /* Return the union of the universe domains of the nodes in "graph"
3008 * that satisfy "pred".
3010 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3011 struct isl_sched_graph *graph,
3012 int (*pred)(struct isl_sched_node *node, int data), int data)
3014 int i;
3015 isl_set *set;
3016 isl_union_set *dom;
3018 for (i = 0; i < graph->n; ++i)
3019 if (pred(&graph->node[i], data))
3020 break;
3022 if (i >= graph->n)
3023 isl_die(ctx, isl_error_internal,
3024 "empty component", return NULL);
3026 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3027 dom = isl_union_set_from_set(set);
3029 for (i = i + 1; i < graph->n; ++i) {
3030 if (!pred(&graph->node[i], data))
3031 continue;
3032 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3033 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3036 return dom;
3039 /* Return a list of unions of universe domains, where each element
3040 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3042 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3043 struct isl_sched_graph *graph)
3045 int i;
3046 isl_union_set_list *filters;
3048 filters = isl_union_set_list_alloc(ctx, graph->scc);
3049 for (i = 0; i < graph->scc; ++i) {
3050 isl_union_set *dom;
3052 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3053 filters = isl_union_set_list_add(filters, dom);
3056 return filters;
3059 /* Return a list of two unions of universe domains, one for the SCCs up
3060 * to and including graph->src_scc and another for the other SCCs.
3062 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3063 struct isl_sched_graph *graph)
3065 isl_union_set *dom;
3066 isl_union_set_list *filters;
3068 filters = isl_union_set_list_alloc(ctx, 2);
3069 dom = isl_sched_graph_domain(ctx, graph,
3070 &node_scc_at_most, graph->src_scc);
3071 filters = isl_union_set_list_add(filters, dom);
3072 dom = isl_sched_graph_domain(ctx, graph,
3073 &node_scc_at_least, graph->src_scc + 1);
3074 filters = isl_union_set_list_add(filters, dom);
3076 return filters;
3079 /* Copy nodes that satisfy node_pred from the src dependence graph
3080 * to the dst dependence graph.
3082 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3083 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3085 int i;
3087 dst->n = 0;
3088 for (i = 0; i < src->n; ++i) {
3089 int j;
3091 if (!node_pred(&src->node[i], data))
3092 continue;
3094 j = dst->n;
3095 dst->node[j].space = isl_space_copy(src->node[i].space);
3096 dst->node[j].compressed = src->node[i].compressed;
3097 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3098 dst->node[j].compress =
3099 isl_multi_aff_copy(src->node[i].compress);
3100 dst->node[j].decompress =
3101 isl_multi_aff_copy(src->node[i].decompress);
3102 dst->node[j].nvar = src->node[i].nvar;
3103 dst->node[j].nparam = src->node[i].nparam;
3104 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3105 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3106 dst->node[j].coincident = src->node[i].coincident;
3107 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3108 dst->node[j].max = isl_vec_copy(src->node[i].max);
3109 dst->n++;
3111 if (!dst->node[j].space || !dst->node[j].sched)
3112 return -1;
3113 if (dst->node[j].compressed &&
3114 (!dst->node[j].hull || !dst->node[j].compress ||
3115 !dst->node[j].decompress))
3116 return -1;
3119 return 0;
3122 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3123 * to the dst dependence graph.
3124 * If the source or destination node of the edge is not in the destination
3125 * graph, then it must be a backward proximity edge and it should simply
3126 * be ignored.
3128 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3129 struct isl_sched_graph *src,
3130 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3132 int i;
3133 enum isl_edge_type t;
3135 dst->n_edge = 0;
3136 for (i = 0; i < src->n_edge; ++i) {
3137 struct isl_sched_edge *edge = &src->edge[i];
3138 isl_map *map;
3139 isl_union_map *tagged_condition;
3140 isl_union_map *tagged_validity;
3141 struct isl_sched_node *dst_src, *dst_dst;
3143 if (!edge_pred(edge, data))
3144 continue;
3146 if (isl_map_plain_is_empty(edge->map))
3147 continue;
3149 dst_src = graph_find_node(ctx, dst, edge->src->space);
3150 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3151 if (!dst_src || !dst_dst) {
3152 if (is_validity(edge) || is_conditional_validity(edge))
3153 isl_die(ctx, isl_error_internal,
3154 "backward (conditional) validity edge",
3155 return -1);
3156 continue;
3159 map = isl_map_copy(edge->map);
3160 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3161 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3163 dst->edge[dst->n_edge].src = dst_src;
3164 dst->edge[dst->n_edge].dst = dst_dst;
3165 dst->edge[dst->n_edge].map = map;
3166 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3167 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3168 dst->edge[dst->n_edge].types = edge->types;
3169 dst->n_edge++;
3171 if (edge->tagged_condition && !tagged_condition)
3172 return -1;
3173 if (edge->tagged_validity && !tagged_validity)
3174 return -1;
3176 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3177 if (edge !=
3178 graph_find_edge(src, t, edge->src, edge->dst))
3179 continue;
3180 if (graph_edge_table_add(ctx, dst, t,
3181 &dst->edge[dst->n_edge - 1]) < 0)
3182 return -1;
3186 return 0;
3189 /* Compute the maximal number of variables over all nodes.
3190 * This is the maximal number of linearly independent schedule
3191 * rows that we need to compute.
3192 * Just in case we end up in a part of the dependence graph
3193 * with only lower-dimensional domains, we make sure we will
3194 * compute the required amount of extra linearly independent rows.
3196 static int compute_maxvar(struct isl_sched_graph *graph)
3198 int i;
3200 graph->maxvar = 0;
3201 for (i = 0; i < graph->n; ++i) {
3202 struct isl_sched_node *node = &graph->node[i];
3203 int nvar;
3205 if (node_update_cmap(node) < 0)
3206 return -1;
3207 nvar = node->nvar + graph->n_row - node->rank;
3208 if (nvar > graph->maxvar)
3209 graph->maxvar = nvar;
3212 return 0;
3215 /* Extract the subgraph of "graph" that consists of the node satisfying
3216 * "node_pred" and the edges satisfying "edge_pred" and store
3217 * the result in "sub".
3219 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3220 int (*node_pred)(struct isl_sched_node *node, int data),
3221 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3222 int data, struct isl_sched_graph *sub)
3224 int i, n = 0, n_edge = 0;
3225 int t;
3227 for (i = 0; i < graph->n; ++i)
3228 if (node_pred(&graph->node[i], data))
3229 ++n;
3230 for (i = 0; i < graph->n_edge; ++i)
3231 if (edge_pred(&graph->edge[i], data))
3232 ++n_edge;
3233 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3234 return -1;
3235 if (copy_nodes(sub, graph, node_pred, data) < 0)
3236 return -1;
3237 if (graph_init_table(ctx, sub) < 0)
3238 return -1;
3239 for (t = 0; t <= isl_edge_last; ++t)
3240 sub->max_edge[t] = graph->max_edge[t];
3241 if (graph_init_edge_tables(ctx, sub) < 0)
3242 return -1;
3243 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3244 return -1;
3245 sub->n_row = graph->n_row;
3246 sub->max_row = graph->max_row;
3247 sub->n_total_row = graph->n_total_row;
3248 sub->band_start = graph->band_start;
3250 return 0;
3253 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3254 struct isl_sched_graph *graph);
3255 static __isl_give isl_schedule_node *compute_schedule_wcc(
3256 isl_schedule_node *node, struct isl_sched_graph *graph);
3258 /* Compute a schedule for a subgraph of "graph". In particular, for
3259 * the graph composed of nodes that satisfy node_pred and edges that
3260 * that satisfy edge_pred.
3261 * If the subgraph is known to consist of a single component, then wcc should
3262 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3263 * Otherwise, we call compute_schedule, which will check whether the subgraph
3264 * is connected.
3266 * The schedule is inserted at "node" and the updated schedule node
3267 * is returned.
3269 static __isl_give isl_schedule_node *compute_sub_schedule(
3270 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3271 struct isl_sched_graph *graph,
3272 int (*node_pred)(struct isl_sched_node *node, int data),
3273 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3274 int data, int wcc)
3276 struct isl_sched_graph split = { 0 };
3278 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3279 &split) < 0)
3280 goto error;
3282 if (wcc)
3283 node = compute_schedule_wcc(node, &split);
3284 else
3285 node = compute_schedule(node, &split);
3287 graph_free(ctx, &split);
3288 return node;
3289 error:
3290 graph_free(ctx, &split);
3291 return isl_schedule_node_free(node);
3294 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3296 return edge->src->scc == scc && edge->dst->scc == scc;
3299 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3301 return edge->dst->scc <= scc;
3304 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3306 return edge->src->scc >= scc;
3309 /* Reset the current band by dropping all its schedule rows.
3311 static int reset_band(struct isl_sched_graph *graph)
3313 int i;
3314 int drop;
3316 drop = graph->n_total_row - graph->band_start;
3317 graph->n_total_row -= drop;
3318 graph->n_row -= drop;
3320 for (i = 0; i < graph->n; ++i) {
3321 struct isl_sched_node *node = &graph->node[i];
3323 isl_map_free(node->sched_map);
3324 node->sched_map = NULL;
3326 node->sched = isl_mat_drop_rows(node->sched,
3327 graph->band_start, drop);
3329 if (!node->sched)
3330 return -1;
3333 return 0;
3336 /* Split the current graph into two parts and compute a schedule for each
3337 * part individually. In particular, one part consists of all SCCs up
3338 * to and including graph->src_scc, while the other part contains the other
3339 * SCCs. The split is enforced by a sequence node inserted at position "node"
3340 * in the schedule tree. Return the updated schedule node.
3341 * If either of these two parts consists of a sequence, then it is spliced
3342 * into the sequence containing the two parts.
3344 * The current band is reset. It would be possible to reuse
3345 * the previously computed rows as the first rows in the next
3346 * band, but recomputing them may result in better rows as we are looking
3347 * at a smaller part of the dependence graph.
3349 static __isl_give isl_schedule_node *compute_split_schedule(
3350 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3352 int is_seq;
3353 isl_ctx *ctx;
3354 isl_union_set_list *filters;
3356 if (!node)
3357 return NULL;
3359 if (reset_band(graph) < 0)
3360 return isl_schedule_node_free(node);
3362 next_band(graph);
3364 ctx = isl_schedule_node_get_ctx(node);
3365 filters = extract_split(ctx, graph);
3366 node = isl_schedule_node_insert_sequence(node, filters);
3367 node = isl_schedule_node_child(node, 1);
3368 node = isl_schedule_node_child(node, 0);
3370 node = compute_sub_schedule(node, ctx, graph,
3371 &node_scc_at_least, &edge_src_scc_at_least,
3372 graph->src_scc + 1, 0);
3373 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3374 node = isl_schedule_node_parent(node);
3375 node = isl_schedule_node_parent(node);
3376 if (is_seq)
3377 node = isl_schedule_node_sequence_splice_child(node, 1);
3378 node = isl_schedule_node_child(node, 0);
3379 node = isl_schedule_node_child(node, 0);
3380 node = compute_sub_schedule(node, ctx, graph,
3381 &node_scc_at_most, &edge_dst_scc_at_most,
3382 graph->src_scc, 0);
3383 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3384 node = isl_schedule_node_parent(node);
3385 node = isl_schedule_node_parent(node);
3386 if (is_seq)
3387 node = isl_schedule_node_sequence_splice_child(node, 0);
3389 return node;
3392 /* Insert a band node at position "node" in the schedule tree corresponding
3393 * to the current band in "graph". Mark the band node permutable
3394 * if "permutable" is set.
3395 * The partial schedules and the coincidence property are extracted
3396 * from the graph nodes.
3397 * Return the updated schedule node.
3399 static __isl_give isl_schedule_node *insert_current_band(
3400 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3401 int permutable)
3403 int i;
3404 int start, end, n;
3405 isl_multi_aff *ma;
3406 isl_multi_pw_aff *mpa;
3407 isl_multi_union_pw_aff *mupa;
3409 if (!node)
3410 return NULL;
3412 if (graph->n < 1)
3413 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3414 "graph should have at least one node",
3415 return isl_schedule_node_free(node));
3417 start = graph->band_start;
3418 end = graph->n_total_row;
3419 n = end - start;
3421 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3422 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3423 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3425 for (i = 1; i < graph->n; ++i) {
3426 isl_multi_union_pw_aff *mupa_i;
3428 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3429 start, n);
3430 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3431 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3432 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3434 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3436 for (i = 0; i < n; ++i)
3437 node = isl_schedule_node_band_member_set_coincident(node, i,
3438 graph->node[0].coincident[start + i]);
3439 node = isl_schedule_node_band_set_permutable(node, permutable);
3441 return node;
3444 /* Update the dependence relations based on the current schedule,
3445 * add the current band to "node" and then continue with the computation
3446 * of the next band.
3447 * Return the updated schedule node.
3449 static __isl_give isl_schedule_node *compute_next_band(
3450 __isl_take isl_schedule_node *node,
3451 struct isl_sched_graph *graph, int permutable)
3453 isl_ctx *ctx;
3455 if (!node)
3456 return NULL;
3458 ctx = isl_schedule_node_get_ctx(node);
3459 if (update_edges(ctx, graph) < 0)
3460 return isl_schedule_node_free(node);
3461 node = insert_current_band(node, graph, permutable);
3462 next_band(graph);
3464 node = isl_schedule_node_child(node, 0);
3465 node = compute_schedule(node, graph);
3466 node = isl_schedule_node_parent(node);
3468 return node;
3471 /* Add constraints to graph->lp that force the dependence "map" (which
3472 * is part of the dependence relation of "edge")
3473 * to be respected and attempt to carry it, where the edge is one from
3474 * a node j to itself. "pos" is the sequence number of the given map.
3475 * That is, add constraints that enforce
3477 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3478 * = c_j_x (y - x) >= e_i
3480 * for each (x,y) in R.
3481 * We obtain general constraints on coefficients (c_0, c_n, c_x)
3482 * of valid constraints for (y - x) and then plug in (-e_i, 0, c_j_x),
3483 * with each coefficient in c_j_x represented as a pair of non-negative
3484 * coefficients.
3486 static int add_intra_constraints(struct isl_sched_graph *graph,
3487 struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
3489 int offset;
3490 isl_ctx *ctx = isl_map_get_ctx(map);
3491 isl_dim_map *dim_map;
3492 isl_basic_set *coef;
3493 struct isl_sched_node *node = edge->src;
3495 coef = intra_coefficients(graph, node, map);
3496 if (!coef)
3497 return -1;
3499 offset = coef_var_offset(coef);
3500 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3501 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3502 graph->lp = isl_basic_set_extend_constraints(graph->lp,
3503 coef->n_eq, coef->n_ineq);
3504 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
3505 coef, dim_map);
3507 return 0;
3510 /* Add constraints to graph->lp that force the dependence "map" (which
3511 * is part of the dependence relation of "edge")
3512 * to be respected and attempt to carry it, where the edge is one from
3513 * node j to node k. "pos" is the sequence number of the given map.
3514 * That is, add constraints that enforce
3516 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3518 * for each (x,y) in R.
3519 * We obtain general constraints on coefficients (c_0, c_n, c_x)
3520 * of valid constraints for R and then plug in
3521 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, c_k_x - c_j_x)
3522 * with each coefficient (except e_i, c_*_0 and c_*_n)
3523 * represented as a pair of non-negative coefficients.
3525 static int add_inter_constraints(struct isl_sched_graph *graph,
3526 struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
3528 int offset;
3529 isl_ctx *ctx = isl_map_get_ctx(map);
3530 isl_dim_map *dim_map;
3531 isl_basic_set *coef;
3532 struct isl_sched_node *src = edge->src;
3533 struct isl_sched_node *dst = edge->dst;
3535 coef = inter_coefficients(graph, edge, map);
3536 if (!coef)
3537 return -1;
3539 offset = coef_var_offset(coef);
3540 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3541 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3542 graph->lp = isl_basic_set_extend_constraints(graph->lp,
3543 coef->n_eq, coef->n_ineq);
3544 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
3545 coef, dim_map);
3547 return 0;
3550 /* Add constraints to graph->lp that force all (conditional) validity
3551 * dependences to be respected and attempt to carry them.
3553 static isl_stat add_all_constraints(struct isl_sched_graph *graph)
3555 int i, j;
3556 int pos;
3558 pos = 0;
3559 for (i = 0; i < graph->n_edge; ++i) {
3560 struct isl_sched_edge *edge= &graph->edge[i];
3562 if (!is_any_validity(edge))
3563 continue;
3565 for (j = 0; j < edge->map->n; ++j) {
3566 isl_basic_map *bmap;
3567 isl_map *map;
3569 bmap = isl_basic_map_copy(edge->map->p[j]);
3570 map = isl_map_from_basic_map(bmap);
3572 if (edge->src == edge->dst &&
3573 add_intra_constraints(graph, edge, map, pos) < 0)
3574 return isl_stat_error;
3575 if (edge->src != edge->dst &&
3576 add_inter_constraints(graph, edge, map, pos) < 0)
3577 return isl_stat_error;
3578 ++pos;
3582 return isl_stat_ok;
3585 /* Count the number of equality and inequality constraints
3586 * that will be added to the carry_lp problem.
3587 * We count each edge exactly once.
3589 static isl_stat count_all_constraints(struct isl_sched_graph *graph,
3590 int *n_eq, int *n_ineq)
3592 int i, j;
3594 *n_eq = *n_ineq = 0;
3595 for (i = 0; i < graph->n_edge; ++i) {
3596 struct isl_sched_edge *edge= &graph->edge[i];
3598 if (!is_any_validity(edge))
3599 continue;
3601 for (j = 0; j < edge->map->n; ++j) {
3602 isl_basic_map *bmap;
3603 isl_map *map;
3605 bmap = isl_basic_map_copy(edge->map->p[j]);
3606 map = isl_map_from_basic_map(bmap);
3608 if (count_map_constraints(graph, edge, map,
3609 n_eq, n_ineq, 1, 0) < 0)
3610 return isl_stat_error;
3614 return isl_stat_ok;
3617 /* Construct an LP problem for finding schedule coefficients
3618 * such that the schedule carries as many dependences as possible.
3619 * In particular, for each dependence i, we bound the dependence distance
3620 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3621 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3622 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3623 * Note that if the dependence relation is a union of basic maps,
3624 * then we have to consider each basic map individually as it may only
3625 * be possible to carry the dependences expressed by some of those
3626 * basic maps and not all of them.
3627 * Below, we consider each of those basic maps as a separate "edge".
3629 * All variables of the LP are non-negative. The actual coefficients
3630 * may be negative, so each coefficient is represented as the difference
3631 * of two non-negative variables. The negative part always appears
3632 * immediately before the positive part.
3633 * Other than that, the variables have the following order
3635 * - sum of (1 - e_i) over all edges
3636 * - sum of all c_n coefficients
3637 * (unconstrained when computing non-parametric schedules)
3638 * - sum of positive and negative parts of all c_x coefficients
3639 * - for each edge
3640 * - e_i
3641 * - for each node
3642 * - c_i_0
3643 * - c_i_n (if parametric)
3644 * - positive and negative parts of c_i_x
3646 * The constraints are those from the (validity) edges plus three equalities
3647 * to express the sums and n_edge inequalities to express e_i <= 1.
3649 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
3651 int i;
3652 int k;
3653 isl_space *dim;
3654 unsigned total;
3655 int n_eq, n_ineq;
3656 int n_edge;
3658 n_edge = 0;
3659 for (i = 0; i < graph->n_edge; ++i)
3660 n_edge += graph->edge[i].map->n;
3662 total = 3 + n_edge;
3663 for (i = 0; i < graph->n; ++i) {
3664 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3665 node->start = total;
3666 total += 1 + node->nparam + 2 * node->nvar;
3669 if (count_all_constraints(graph, &n_eq, &n_ineq) < 0)
3670 return isl_stat_error;
3672 dim = isl_space_set_alloc(ctx, 0, total);
3673 isl_basic_set_free(graph->lp);
3674 n_eq += 3;
3675 n_ineq += n_edge;
3676 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3677 graph->lp = isl_basic_set_set_rational(graph->lp);
3679 k = isl_basic_set_alloc_equality(graph->lp);
3680 if (k < 0)
3681 return isl_stat_error;
3682 isl_seq_clr(graph->lp->eq[k], 1 + total);
3683 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3684 isl_int_set_si(graph->lp->eq[k][1], 1);
3685 for (i = 0; i < n_edge; ++i)
3686 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3688 if (add_param_sum_constraint(graph, 1) < 0)
3689 return isl_stat_error;
3690 if (add_var_sum_constraint(graph, 2) < 0)
3691 return isl_stat_error;
3693 for (i = 0; i < n_edge; ++i) {
3694 k = isl_basic_set_alloc_inequality(graph->lp);
3695 if (k < 0)
3696 return isl_stat_error;
3697 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3698 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3699 isl_int_set_si(graph->lp->ineq[k][0], 1);
3702 if (add_all_constraints(graph) < 0)
3703 return isl_stat_error;
3705 return isl_stat_ok;
3708 static __isl_give isl_schedule_node *compute_component_schedule(
3709 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3710 int wcc);
3712 /* Comparison function for sorting the statements based on
3713 * the corresponding value in "r".
3715 static int smaller_value(const void *a, const void *b, void *data)
3717 isl_vec *r = data;
3718 const int *i1 = a;
3719 const int *i2 = b;
3721 return isl_int_cmp(r->el[*i1], r->el[*i2]);
3724 /* If the schedule_split_scaled option is set and if the linear
3725 * parts of the scheduling rows for all nodes in the graphs have
3726 * a non-trivial common divisor, then split off the remainder of the
3727 * constant term modulo this common divisor from the linear part.
3728 * Otherwise, insert a band node directly and continue with
3729 * the construction of the schedule.
3731 * If a non-trivial common divisor is found, then
3732 * the linear part is reduced and the remainder is enforced
3733 * by a sequence node with the children placed in the order
3734 * of this remainder.
3735 * In particular, we assign an scc index based on the remainder and
3736 * then rely on compute_component_schedule to insert the sequence and
3737 * to continue the schedule construction on each part.
3739 static __isl_give isl_schedule_node *split_scaled(
3740 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3742 int i;
3743 int row;
3744 int scc;
3745 isl_ctx *ctx;
3746 isl_int gcd, gcd_i;
3747 isl_vec *r;
3748 int *order;
3750 if (!node)
3751 return NULL;
3753 ctx = isl_schedule_node_get_ctx(node);
3754 if (!ctx->opt->schedule_split_scaled)
3755 return compute_next_band(node, graph, 0);
3756 if (graph->n <= 1)
3757 return compute_next_band(node, graph, 0);
3759 isl_int_init(gcd);
3760 isl_int_init(gcd_i);
3762 isl_int_set_si(gcd, 0);
3764 row = isl_mat_rows(graph->node[0].sched) - 1;
3766 for (i = 0; i < graph->n; ++i) {
3767 struct isl_sched_node *node = &graph->node[i];
3768 int cols = isl_mat_cols(node->sched);
3770 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3771 isl_int_gcd(gcd, gcd, gcd_i);
3774 isl_int_clear(gcd_i);
3776 if (isl_int_cmp_si(gcd, 1) <= 0) {
3777 isl_int_clear(gcd);
3778 return compute_next_band(node, graph, 0);
3781 r = isl_vec_alloc(ctx, graph->n);
3782 order = isl_calloc_array(ctx, int, graph->n);
3783 if (!r || !order)
3784 goto error;
3786 for (i = 0; i < graph->n; ++i) {
3787 struct isl_sched_node *node = &graph->node[i];
3789 order[i] = i;
3790 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
3791 isl_int_fdiv_q(node->sched->row[row][0],
3792 node->sched->row[row][0], gcd);
3793 isl_int_mul(node->sched->row[row][0],
3794 node->sched->row[row][0], gcd);
3795 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3796 if (!node->sched)
3797 goto error;
3800 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
3801 goto error;
3803 scc = 0;
3804 for (i = 0; i < graph->n; ++i) {
3805 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
3806 ++scc;
3807 graph->node[order[i]].scc = scc;
3809 graph->scc = ++scc;
3810 graph->weak = 0;
3812 isl_int_clear(gcd);
3813 isl_vec_free(r);
3814 free(order);
3816 if (update_edges(ctx, graph) < 0)
3817 return isl_schedule_node_free(node);
3818 node = insert_current_band(node, graph, 0);
3819 next_band(graph);
3821 node = isl_schedule_node_child(node, 0);
3822 node = compute_component_schedule(node, graph, 0);
3823 node = isl_schedule_node_parent(node);
3825 return node;
3826 error:
3827 isl_vec_free(r);
3828 free(order);
3829 isl_int_clear(gcd);
3830 return isl_schedule_node_free(node);
3833 /* Is the schedule row "sol" trivial on node "node"?
3834 * That is, is the solution zero on the dimensions orthogonal to
3835 * the previously found solutions?
3836 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
3838 * Each coefficient is represented as the difference between
3839 * two non-negative values in "sol". "sol" has been computed
3840 * in terms of the original iterators (i.e., without use of cmap).
3841 * We construct the schedule row s and write it as a linear
3842 * combination of (linear combinations of) previously computed schedule rows.
3843 * s = Q c or c = U s.
3844 * If the final entries of c are all zero, then the solution is trivial.
3846 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
3848 int trivial;
3849 isl_vec *node_sol;
3851 if (!sol)
3852 return -1;
3853 if (node->nvar == node->rank)
3854 return 0;
3856 node_sol = extract_var_coef(node, sol);
3857 node_sol = isl_mat_vec_product(isl_mat_copy(node->cinv), node_sol);
3858 if (!node_sol)
3859 return -1;
3861 trivial = isl_seq_first_non_zero(node_sol->el + node->rank,
3862 node->nvar - node->rank) == -1;
3864 isl_vec_free(node_sol);
3866 return trivial;
3869 /* Is the schedule row "sol" trivial on any node where it should
3870 * not be trivial?
3871 * "sol" has been computed in terms of the original iterators
3872 * (i.e., without use of cmap).
3873 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
3875 static int is_any_trivial(struct isl_sched_graph *graph,
3876 __isl_keep isl_vec *sol)
3878 int i;
3880 for (i = 0; i < graph->n; ++i) {
3881 struct isl_sched_node *node = &graph->node[i];
3882 int trivial;
3884 if (!needs_row(graph, node))
3885 continue;
3886 trivial = is_trivial(node, sol);
3887 if (trivial < 0 || trivial)
3888 return trivial;
3891 return 0;
3894 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
3895 * If so, return the position of the coalesced dimension.
3896 * Otherwise, return node->nvar or -1 on error.
3898 * In particular, look for pairs of coefficients c_i and c_j such that
3899 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
3900 * If any such pair is found, then return i.
3901 * If size_i is infinity, then no check on c_i needs to be performed.
3903 static int find_node_coalescing(struct isl_sched_node *node,
3904 __isl_keep isl_vec *sol)
3906 int i, j;
3907 isl_int max;
3908 isl_vec *csol;
3910 if (node->nvar <= 1)
3911 return node->nvar;
3913 csol = extract_var_coef(node, sol);
3914 if (!csol)
3915 return -1;
3916 isl_int_init(max);
3917 for (i = 0; i < node->nvar; ++i) {
3918 isl_val *v;
3920 if (isl_int_is_zero(csol->el[i]))
3921 continue;
3922 v = isl_multi_val_get_val(node->sizes, i);
3923 if (!v)
3924 goto error;
3925 if (!isl_val_is_int(v)) {
3926 isl_val_free(v);
3927 continue;
3929 isl_int_mul(max, v->n, csol->el[i]);
3930 isl_val_free(v);
3932 for (j = 0; j < node->nvar; ++j) {
3933 if (j == i)
3934 continue;
3935 if (isl_int_abs_ge(csol->el[j], max))
3936 break;
3938 if (j < node->nvar)
3939 break;
3942 isl_int_clear(max);
3943 isl_vec_free(csol);
3944 return i;
3945 error:
3946 isl_int_clear(max);
3947 isl_vec_free(csol);
3948 return -1;
3951 /* Force the schedule coefficient at position "pos" of "node" to be zero
3952 * in "tl".
3953 * The coefficient is encoded as the difference between two non-negative
3954 * variables. Force these two variables to have the same value.
3956 static __isl_give isl_tab_lexmin *zero_out_node_coef(
3957 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
3959 int dim;
3960 isl_ctx *ctx;
3961 isl_vec *eq;
3963 ctx = isl_space_get_ctx(node->space);
3964 dim = isl_tab_lexmin_dim(tl);
3965 if (dim < 0)
3966 return isl_tab_lexmin_free(tl);
3967 eq = isl_vec_alloc(ctx, 1 + dim);
3968 eq = isl_vec_clr(eq);
3969 if (!eq)
3970 return isl_tab_lexmin_free(tl);
3972 pos = 1 + node_var_coef_offset(node) + 2 * pos;
3973 isl_int_set_si(eq->el[pos], 1);
3974 isl_int_set_si(eq->el[pos + 1], -1);
3975 tl = isl_tab_lexmin_add_eq(tl, eq->el);
3976 isl_vec_free(eq);
3978 return tl;
3981 /* Return the lexicographically smallest rational point in the basic set
3982 * from which "tl" was constructed, double checking that this input set
3983 * was not empty.
3985 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
3987 isl_vec *sol;
3989 sol = isl_tab_lexmin_get_solution(tl);
3990 if (!sol)
3991 return NULL;
3992 if (sol->size == 0)
3993 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
3994 "error in schedule construction",
3995 return isl_vec_free(sol));
3996 return sol;
3999 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4000 * carry any of the "n_edge" groups of dependences?
4001 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4002 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4003 * by the edge are carried by the solution.
4004 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4005 * one of those is carried.
4007 * Note that despite the fact that the problem is solved using a rational
4008 * solver, the solution is guaranteed to be integral.
4009 * Specifically, the dependence distance lower bounds e_i (and therefore
4010 * also their sum) are integers. See Lemma 5 of [1].
4012 * Any potential denominator of the sum is cleared by this function.
4013 * The denominator is not relevant for any of the other elements
4014 * in the solution.
4016 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4017 * Problem, Part II: Multi-Dimensional Time.
4018 * In Intl. Journal of Parallel Programming, 1992.
4020 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4022 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4023 isl_int_set_si(sol->el[0], 1);
4024 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4027 /* Return the lexicographically smallest rational point in "lp",
4028 * assuming that all variables are non-negative and performing some
4029 * additional sanity checks.
4030 * In particular, "lp" should not be empty by construction.
4031 * Double check that this is the case.
4032 * Also, check that dependences are carried for at least one of
4033 * the "n_edge" edges.
4035 * If the computed schedule performs loop coalescing on a given node,
4036 * i.e., if it is of the form
4038 * c_i i + c_j j + ...
4040 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4041 * to cut out this solution. Repeat this process until no more loop
4042 * coalescing occurs or until no more dependences can be carried.
4043 * In the latter case, revert to the previously computed solution.
4045 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4046 __isl_take isl_basic_set *lp, int n_edge)
4048 int i, pos;
4049 isl_ctx *ctx;
4050 isl_tab_lexmin *tl;
4051 isl_vec *sol, *prev = NULL;
4052 int treat_coalescing;
4054 if (!lp)
4055 return NULL;
4056 ctx = isl_basic_set_get_ctx(lp);
4057 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4058 tl = isl_tab_lexmin_from_basic_set(lp);
4060 do {
4061 sol = non_empty_solution(tl);
4062 if (!sol)
4063 goto error;
4065 if (!carries_dependences(sol, n_edge)) {
4066 if (!prev)
4067 isl_die(ctx, isl_error_unknown,
4068 "unable to carry dependences",
4069 goto error);
4070 isl_vec_free(sol);
4071 sol = prev;
4072 break;
4074 prev = isl_vec_free(prev);
4075 if (!treat_coalescing)
4076 break;
4077 for (i = 0; i < graph->n; ++i) {
4078 struct isl_sched_node *node = &graph->node[i];
4080 pos = find_node_coalescing(node, sol);
4081 if (pos < 0)
4082 goto error;
4083 if (pos < node->nvar)
4084 break;
4086 if (i < graph->n) {
4087 prev = sol;
4088 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4090 } while (i < graph->n);
4092 isl_tab_lexmin_free(tl);
4094 return sol;
4095 error:
4096 isl_tab_lexmin_free(tl);
4097 isl_vec_free(prev);
4098 isl_vec_free(sol);
4099 return NULL;
4102 /* Construct a schedule row for each node such that as many dependences
4103 * as possible are carried and then continue with the next band.
4105 * If the computed schedule row turns out to be trivial on one or
4106 * more nodes where it should not be trivial, then we throw it away
4107 * and try again on each component separately.
4109 * If there is only one component, then we accept the schedule row anyway,
4110 * but we do not consider it as a complete row and therefore do not
4111 * increment graph->n_row. Note that the ranks of the nodes that
4112 * do get a non-trivial schedule part will get updated regardless and
4113 * graph->maxvar is computed based on these ranks. The test for
4114 * whether more schedule rows are required in compute_schedule_wcc
4115 * is therefore not affected.
4117 * Insert a band corresponding to the schedule row at position "node"
4118 * of the schedule tree and continue with the construction of the schedule.
4119 * This insertion and the continued construction is performed by split_scaled
4120 * after optionally checking for non-trivial common divisors.
4122 static __isl_give isl_schedule_node *carry_dependences(
4123 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4125 int i;
4126 int n_edge;
4127 int trivial;
4128 isl_ctx *ctx;
4129 isl_vec *sol;
4130 isl_basic_set *lp;
4132 if (!node)
4133 return NULL;
4135 n_edge = 0;
4136 for (i = 0; i < graph->n_edge; ++i)
4137 n_edge += graph->edge[i].map->n;
4139 ctx = isl_schedule_node_get_ctx(node);
4140 if (setup_carry_lp(ctx, graph) < 0)
4141 return isl_schedule_node_free(node);
4143 lp = isl_basic_set_copy(graph->lp);
4144 sol = non_neg_lexmin(graph, lp, n_edge);
4145 if (!sol)
4146 return isl_schedule_node_free(node);
4148 trivial = is_any_trivial(graph, sol);
4149 if (trivial < 0) {
4150 sol = isl_vec_free(sol);
4151 } else if (trivial && graph->scc > 1) {
4152 isl_vec_free(sol);
4153 return compute_component_schedule(node, graph, 1);
4156 if (update_schedule(graph, sol, 0, 0) < 0)
4157 return isl_schedule_node_free(node);
4158 if (trivial)
4159 graph->n_row--;
4161 return split_scaled(node, graph);
4164 /* Topologically sort statements mapped to the same schedule iteration
4165 * and add insert a sequence node in front of "node"
4166 * corresponding to this order.
4167 * If "initialized" is set, then it may be assumed that compute_maxvar
4168 * has been called on the current band. Otherwise, call
4169 * compute_maxvar if and before carry_dependences gets called.
4171 * If it turns out to be impossible to sort the statements apart,
4172 * because different dependences impose different orderings
4173 * on the statements, then we extend the schedule such that
4174 * it carries at least one more dependence.
4176 static __isl_give isl_schedule_node *sort_statements(
4177 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4178 int initialized)
4180 isl_ctx *ctx;
4181 isl_union_set_list *filters;
4183 if (!node)
4184 return NULL;
4186 ctx = isl_schedule_node_get_ctx(node);
4187 if (graph->n < 1)
4188 isl_die(ctx, isl_error_internal,
4189 "graph should have at least one node",
4190 return isl_schedule_node_free(node));
4192 if (graph->n == 1)
4193 return node;
4195 if (update_edges(ctx, graph) < 0)
4196 return isl_schedule_node_free(node);
4198 if (graph->n_edge == 0)
4199 return node;
4201 if (detect_sccs(ctx, graph) < 0)
4202 return isl_schedule_node_free(node);
4204 next_band(graph);
4205 if (graph->scc < graph->n) {
4206 if (!initialized && compute_maxvar(graph) < 0)
4207 return isl_schedule_node_free(node);
4208 return carry_dependences(node, graph);
4211 filters = extract_sccs(ctx, graph);
4212 node = isl_schedule_node_insert_sequence(node, filters);
4214 return node;
4217 /* Are there any (non-empty) (conditional) validity edges in the graph?
4219 static int has_validity_edges(struct isl_sched_graph *graph)
4221 int i;
4223 for (i = 0; i < graph->n_edge; ++i) {
4224 int empty;
4226 empty = isl_map_plain_is_empty(graph->edge[i].map);
4227 if (empty < 0)
4228 return -1;
4229 if (empty)
4230 continue;
4231 if (is_any_validity(&graph->edge[i]))
4232 return 1;
4235 return 0;
4238 /* Should we apply a Feautrier step?
4239 * That is, did the user request the Feautrier algorithm and are
4240 * there any validity dependences (left)?
4242 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4244 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4245 return 0;
4247 return has_validity_edges(graph);
4250 /* Compute a schedule for a connected dependence graph using Feautrier's
4251 * multi-dimensional scheduling algorithm and return the updated schedule node.
4253 * The original algorithm is described in [1].
4254 * The main idea is to minimize the number of scheduling dimensions, by
4255 * trying to satisfy as many dependences as possible per scheduling dimension.
4257 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4258 * Problem, Part II: Multi-Dimensional Time.
4259 * In Intl. Journal of Parallel Programming, 1992.
4261 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4262 isl_schedule_node *node, struct isl_sched_graph *graph)
4264 return carry_dependences(node, graph);
4267 /* Turn off the "local" bit on all (condition) edges.
4269 static void clear_local_edges(struct isl_sched_graph *graph)
4271 int i;
4273 for (i = 0; i < graph->n_edge; ++i)
4274 if (is_condition(&graph->edge[i]))
4275 clear_local(&graph->edge[i]);
4278 /* Does "graph" have both condition and conditional validity edges?
4280 static int need_condition_check(struct isl_sched_graph *graph)
4282 int i;
4283 int any_condition = 0;
4284 int any_conditional_validity = 0;
4286 for (i = 0; i < graph->n_edge; ++i) {
4287 if (is_condition(&graph->edge[i]))
4288 any_condition = 1;
4289 if (is_conditional_validity(&graph->edge[i]))
4290 any_conditional_validity = 1;
4293 return any_condition && any_conditional_validity;
4296 /* Does "graph" contain any coincidence edge?
4298 static int has_any_coincidence(struct isl_sched_graph *graph)
4300 int i;
4302 for (i = 0; i < graph->n_edge; ++i)
4303 if (is_coincidence(&graph->edge[i]))
4304 return 1;
4306 return 0;
4309 /* Extract the final schedule row as a map with the iteration domain
4310 * of "node" as domain.
4312 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4314 isl_local_space *ls;
4315 isl_aff *aff;
4316 int row;
4318 row = isl_mat_rows(node->sched) - 1;
4319 ls = isl_local_space_from_space(isl_space_copy(node->space));
4320 aff = extract_schedule_row(ls, node, row);
4321 return isl_map_from_aff(aff);
4324 /* Is the conditional validity dependence in the edge with index "edge_index"
4325 * violated by the latest (i.e., final) row of the schedule?
4326 * That is, is i scheduled after j
4327 * for any conditional validity dependence i -> j?
4329 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4331 isl_map *src_sched, *dst_sched, *map;
4332 struct isl_sched_edge *edge = &graph->edge[edge_index];
4333 int empty;
4335 src_sched = final_row(edge->src);
4336 dst_sched = final_row(edge->dst);
4337 map = isl_map_copy(edge->map);
4338 map = isl_map_apply_domain(map, src_sched);
4339 map = isl_map_apply_range(map, dst_sched);
4340 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4341 empty = isl_map_is_empty(map);
4342 isl_map_free(map);
4344 if (empty < 0)
4345 return -1;
4347 return !empty;
4350 /* Does "graph" have any satisfied condition edges that
4351 * are adjacent to the conditional validity constraint with
4352 * domain "conditional_source" and range "conditional_sink"?
4354 * A satisfied condition is one that is not local.
4355 * If a condition was forced to be local already (i.e., marked as local)
4356 * then there is no need to check if it is in fact local.
4358 * Additionally, mark all adjacent condition edges found as local.
4360 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4361 __isl_keep isl_union_set *conditional_source,
4362 __isl_keep isl_union_set *conditional_sink)
4364 int i;
4365 int any = 0;
4367 for (i = 0; i < graph->n_edge; ++i) {
4368 int adjacent, local;
4369 isl_union_map *condition;
4371 if (!is_condition(&graph->edge[i]))
4372 continue;
4373 if (is_local(&graph->edge[i]))
4374 continue;
4376 condition = graph->edge[i].tagged_condition;
4377 adjacent = domain_intersects(condition, conditional_sink);
4378 if (adjacent >= 0 && !adjacent)
4379 adjacent = range_intersects(condition,
4380 conditional_source);
4381 if (adjacent < 0)
4382 return -1;
4383 if (!adjacent)
4384 continue;
4386 set_local(&graph->edge[i]);
4388 local = is_condition_false(&graph->edge[i]);
4389 if (local < 0)
4390 return -1;
4391 if (!local)
4392 any = 1;
4395 return any;
4398 /* Are there any violated conditional validity dependences with
4399 * adjacent condition dependences that are not local with respect
4400 * to the current schedule?
4401 * That is, is the conditional validity constraint violated?
4403 * Additionally, mark all those adjacent condition dependences as local.
4404 * We also mark those adjacent condition dependences that were not marked
4405 * as local before, but just happened to be local already. This ensures
4406 * that they remain local if the schedule is recomputed.
4408 * We first collect domain and range of all violated conditional validity
4409 * dependences and then check if there are any adjacent non-local
4410 * condition dependences.
4412 static int has_violated_conditional_constraint(isl_ctx *ctx,
4413 struct isl_sched_graph *graph)
4415 int i;
4416 int any = 0;
4417 isl_union_set *source, *sink;
4419 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4420 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4421 for (i = 0; i < graph->n_edge; ++i) {
4422 isl_union_set *uset;
4423 isl_union_map *umap;
4424 int violated;
4426 if (!is_conditional_validity(&graph->edge[i]))
4427 continue;
4429 violated = is_violated(graph, i);
4430 if (violated < 0)
4431 goto error;
4432 if (!violated)
4433 continue;
4435 any = 1;
4437 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4438 uset = isl_union_map_domain(umap);
4439 source = isl_union_set_union(source, uset);
4440 source = isl_union_set_coalesce(source);
4442 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4443 uset = isl_union_map_range(umap);
4444 sink = isl_union_set_union(sink, uset);
4445 sink = isl_union_set_coalesce(sink);
4448 if (any)
4449 any = has_adjacent_true_conditions(graph, source, sink);
4451 isl_union_set_free(source);
4452 isl_union_set_free(sink);
4453 return any;
4454 error:
4455 isl_union_set_free(source);
4456 isl_union_set_free(sink);
4457 return -1;
4460 /* Examine the current band (the rows between graph->band_start and
4461 * graph->n_total_row), deciding whether to drop it or add it to "node"
4462 * and then continue with the computation of the next band, if any.
4463 * If "initialized" is set, then it may be assumed that compute_maxvar
4464 * has been called on the current band. Otherwise, call
4465 * compute_maxvar if and before carry_dependences gets called.
4467 * The caller keeps looking for a new row as long as
4468 * graph->n_row < graph->maxvar. If the latest attempt to find
4469 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4470 * then we either
4471 * - split between SCCs and start over (assuming we found an interesting
4472 * pair of SCCs between which to split)
4473 * - continue with the next band (assuming the current band has at least
4474 * one row)
4475 * - try to carry as many dependences as possible and continue with the next
4476 * band
4477 * In each case, we first insert a band node in the schedule tree
4478 * if any rows have been computed.
4480 * If the caller managed to complete the schedule, we insert a band node
4481 * (if any schedule rows were computed) and we finish off by topologically
4482 * sorting the statements based on the remaining dependences.
4484 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4485 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4486 int initialized)
4488 int insert;
4490 if (!node)
4491 return NULL;
4493 if (graph->n_row < graph->maxvar) {
4494 isl_ctx *ctx;
4495 int empty = graph->n_total_row == graph->band_start;
4497 ctx = isl_schedule_node_get_ctx(node);
4498 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4499 return compute_next_band(node, graph, 1);
4500 if (graph->src_scc >= 0)
4501 return compute_split_schedule(node, graph);
4502 if (!empty)
4503 return compute_next_band(node, graph, 1);
4504 if (!initialized && compute_maxvar(graph) < 0)
4505 return isl_schedule_node_free(node);
4506 return carry_dependences(node, graph);
4509 insert = graph->n_total_row > graph->band_start;
4510 if (insert) {
4511 node = insert_current_band(node, graph, 1);
4512 node = isl_schedule_node_child(node, 0);
4514 node = sort_statements(node, graph, initialized);
4515 if (insert)
4516 node = isl_schedule_node_parent(node);
4518 return node;
4521 /* Construct a band of schedule rows for a connected dependence graph.
4522 * The caller is responsible for determining the strongly connected
4523 * components and calling compute_maxvar first.
4525 * We try to find a sequence of as many schedule rows as possible that result
4526 * in non-negative dependence distances (independent of the previous rows
4527 * in the sequence, i.e., such that the sequence is tilable), with as
4528 * many of the initial rows as possible satisfying the coincidence constraints.
4529 * The computation stops if we can't find any more rows or if we have found
4530 * all the rows we wanted to find.
4532 * If ctx->opt->schedule_outer_coincidence is set, then we force the
4533 * outermost dimension to satisfy the coincidence constraints. If this
4534 * turns out to be impossible, we fall back on the general scheme above
4535 * and try to carry as many dependences as possible.
4537 * If "graph" contains both condition and conditional validity dependences,
4538 * then we need to check that that the conditional schedule constraint
4539 * is satisfied, i.e., there are no violated conditional validity dependences
4540 * that are adjacent to any non-local condition dependences.
4541 * If there are, then we mark all those adjacent condition dependences
4542 * as local and recompute the current band. Those dependences that
4543 * are marked local will then be forced to be local.
4544 * The initial computation is performed with no dependences marked as local.
4545 * If we are lucky, then there will be no violated conditional validity
4546 * dependences adjacent to any non-local condition dependences.
4547 * Otherwise, we mark some additional condition dependences as local and
4548 * recompute. We continue this process until there are no violations left or
4549 * until we are no longer able to compute a schedule.
4550 * Since there are only a finite number of dependences,
4551 * there will only be a finite number of iterations.
4553 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
4554 struct isl_sched_graph *graph)
4556 int has_coincidence;
4557 int use_coincidence;
4558 int force_coincidence = 0;
4559 int check_conditional;
4561 if (sort_sccs(graph) < 0)
4562 return isl_stat_error;
4564 clear_local_edges(graph);
4565 check_conditional = need_condition_check(graph);
4566 has_coincidence = has_any_coincidence(graph);
4568 if (ctx->opt->schedule_outer_coincidence)
4569 force_coincidence = 1;
4571 use_coincidence = has_coincidence;
4572 while (graph->n_row < graph->maxvar) {
4573 isl_vec *sol;
4574 int violated;
4575 int coincident;
4577 graph->src_scc = -1;
4578 graph->dst_scc = -1;
4580 if (setup_lp(ctx, graph, use_coincidence) < 0)
4581 return isl_stat_error;
4582 sol = solve_lp(graph);
4583 if (!sol)
4584 return isl_stat_error;
4585 if (sol->size == 0) {
4586 int empty = graph->n_total_row == graph->band_start;
4588 isl_vec_free(sol);
4589 if (use_coincidence && (!force_coincidence || !empty)) {
4590 use_coincidence = 0;
4591 continue;
4593 return isl_stat_ok;
4595 coincident = !has_coincidence || use_coincidence;
4596 if (update_schedule(graph, sol, 1, coincident) < 0)
4597 return isl_stat_error;
4599 if (!check_conditional)
4600 continue;
4601 violated = has_violated_conditional_constraint(ctx, graph);
4602 if (violated < 0)
4603 return isl_stat_error;
4604 if (!violated)
4605 continue;
4606 if (reset_band(graph) < 0)
4607 return isl_stat_error;
4608 use_coincidence = has_coincidence;
4611 return isl_stat_ok;
4614 /* Compute a schedule for a connected dependence graph by considering
4615 * the graph as a whole and return the updated schedule node.
4617 * The actual schedule rows of the current band are computed by
4618 * compute_schedule_wcc_band. compute_schedule_finish_band takes
4619 * care of integrating the band into "node" and continuing
4620 * the computation.
4622 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
4623 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4625 isl_ctx *ctx;
4627 if (!node)
4628 return NULL;
4630 ctx = isl_schedule_node_get_ctx(node);
4631 if (compute_schedule_wcc_band(ctx, graph) < 0)
4632 return isl_schedule_node_free(node);
4634 return compute_schedule_finish_band(node, graph, 1);
4637 /* Clustering information used by compute_schedule_wcc_clustering.
4639 * "n" is the number of SCCs in the original dependence graph
4640 * "scc" is an array of "n" elements, each representing an SCC
4641 * of the original dependence graph. All entries in the same cluster
4642 * have the same number of schedule rows.
4643 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
4644 * where each cluster is represented by the index of the first SCC
4645 * in the cluster. Initially, each SCC belongs to a cluster containing
4646 * only that SCC.
4648 * "scc_in_merge" is used by merge_clusters_along_edge to keep
4649 * track of which SCCs need to be merged.
4651 * "cluster" contains the merged clusters of SCCs after the clustering
4652 * has completed.
4654 * "scc_node" is a temporary data structure used inside copy_partial.
4655 * For each SCC, it keeps track of the number of nodes in the SCC
4656 * that have already been copied.
4658 struct isl_clustering {
4659 int n;
4660 struct isl_sched_graph *scc;
4661 struct isl_sched_graph *cluster;
4662 int *scc_cluster;
4663 int *scc_node;
4664 int *scc_in_merge;
4667 /* Initialize the clustering data structure "c" from "graph".
4669 * In particular, allocate memory, extract the SCCs from "graph"
4670 * into c->scc, initialize scc_cluster and construct
4671 * a band of schedule rows for each SCC.
4672 * Within each SCC, there is only one SCC by definition.
4673 * Each SCC initially belongs to a cluster containing only that SCC.
4675 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
4676 struct isl_sched_graph *graph)
4678 int i;
4680 c->n = graph->scc;
4681 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
4682 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
4683 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
4684 c->scc_node = isl_calloc_array(ctx, int, c->n);
4685 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
4686 if (!c->scc || !c->cluster ||
4687 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
4688 return isl_stat_error;
4690 for (i = 0; i < c->n; ++i) {
4691 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
4692 &edge_scc_exactly, i, &c->scc[i]) < 0)
4693 return isl_stat_error;
4694 c->scc[i].scc = 1;
4695 if (compute_maxvar(&c->scc[i]) < 0)
4696 return isl_stat_error;
4697 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
4698 return isl_stat_error;
4699 c->scc_cluster[i] = i;
4702 return isl_stat_ok;
4705 /* Free all memory allocated for "c".
4707 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
4709 int i;
4711 if (c->scc)
4712 for (i = 0; i < c->n; ++i)
4713 graph_free(ctx, &c->scc[i]);
4714 free(c->scc);
4715 if (c->cluster)
4716 for (i = 0; i < c->n; ++i)
4717 graph_free(ctx, &c->cluster[i]);
4718 free(c->cluster);
4719 free(c->scc_cluster);
4720 free(c->scc_node);
4721 free(c->scc_in_merge);
4724 /* Should we refrain from merging the cluster in "graph" with
4725 * any other cluster?
4726 * In particular, is its current schedule band empty and incomplete.
4728 static int bad_cluster(struct isl_sched_graph *graph)
4730 return graph->n_row < graph->maxvar &&
4731 graph->n_total_row == graph->band_start;
4734 /* Return the index of an edge in "graph" that can be used to merge
4735 * two clusters in "c".
4736 * Return graph->n_edge if no such edge can be found.
4737 * Return -1 on error.
4739 * In particular, return a proximity edge between two clusters
4740 * that is not marked "no_merge" and such that neither of the
4741 * two clusters has an incomplete, empty band.
4743 * If there are multiple such edges, then try and find the most
4744 * appropriate edge to use for merging. In particular, pick the edge
4745 * with the greatest weight. If there are multiple of those,
4746 * then pick one with the shortest distance between
4747 * the two cluster representatives.
4749 static int find_proximity(struct isl_sched_graph *graph,
4750 struct isl_clustering *c)
4752 int i, best = graph->n_edge, best_dist, best_weight;
4754 for (i = 0; i < graph->n_edge; ++i) {
4755 struct isl_sched_edge *edge = &graph->edge[i];
4756 int dist, weight;
4758 if (!is_proximity(edge))
4759 continue;
4760 if (edge->no_merge)
4761 continue;
4762 if (bad_cluster(&c->scc[edge->src->scc]) ||
4763 bad_cluster(&c->scc[edge->dst->scc]))
4764 continue;
4765 dist = c->scc_cluster[edge->dst->scc] -
4766 c->scc_cluster[edge->src->scc];
4767 if (dist == 0)
4768 continue;
4769 weight = edge->weight;
4770 if (best < graph->n_edge) {
4771 if (best_weight > weight)
4772 continue;
4773 if (best_weight == weight && best_dist <= dist)
4774 continue;
4776 best = i;
4777 best_dist = dist;
4778 best_weight = weight;
4781 return best;
4784 /* Internal data structure used in mark_merge_sccs.
4786 * "graph" is the dependence graph in which a strongly connected
4787 * component is constructed.
4788 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
4789 * "src" and "dst" are the indices of the nodes that are being merged.
4791 struct isl_mark_merge_sccs_data {
4792 struct isl_sched_graph *graph;
4793 int *scc_cluster;
4794 int src;
4795 int dst;
4798 /* Check whether the cluster containing node "i" depends on the cluster
4799 * containing node "j". If "i" and "j" belong to the same cluster,
4800 * then they are taken to depend on each other to ensure that
4801 * the resulting strongly connected component consists of complete
4802 * clusters. Furthermore, if "i" and "j" are the two nodes that
4803 * are being merged, then they are taken to depend on each other as well.
4804 * Otherwise, check if there is a (conditional) validity dependence
4805 * from node[j] to node[i], forcing node[i] to follow node[j].
4807 static isl_bool cluster_follows(int i, int j, void *user)
4809 struct isl_mark_merge_sccs_data *data = user;
4810 struct isl_sched_graph *graph = data->graph;
4811 int *scc_cluster = data->scc_cluster;
4813 if (data->src == i && data->dst == j)
4814 return isl_bool_true;
4815 if (data->src == j && data->dst == i)
4816 return isl_bool_true;
4817 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
4818 return isl_bool_true;
4820 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
4823 /* Mark all SCCs that belong to either of the two clusters in "c"
4824 * connected by the edge in "graph" with index "edge", or to any
4825 * of the intermediate clusters.
4826 * The marking is recorded in c->scc_in_merge.
4828 * The given edge has been selected for merging two clusters,
4829 * meaning that there is at least a proximity edge between the two nodes.
4830 * However, there may also be (indirect) validity dependences
4831 * between the two nodes. When merging the two clusters, all clusters
4832 * containing one or more of the intermediate nodes along the
4833 * indirect validity dependences need to be merged in as well.
4835 * First collect all such nodes by computing the strongly connected
4836 * component (SCC) containing the two nodes connected by the edge, where
4837 * the two nodes are considered to depend on each other to make
4838 * sure they end up in the same SCC. Similarly, each node is considered
4839 * to depend on every other node in the same cluster to ensure
4840 * that the SCC consists of complete clusters.
4842 * Then the original SCCs that contain any of these nodes are marked
4843 * in c->scc_in_merge.
4845 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
4846 int edge, struct isl_clustering *c)
4848 struct isl_mark_merge_sccs_data data;
4849 struct isl_tarjan_graph *g;
4850 int i;
4852 for (i = 0; i < c->n; ++i)
4853 c->scc_in_merge[i] = 0;
4855 data.graph = graph;
4856 data.scc_cluster = c->scc_cluster;
4857 data.src = graph->edge[edge].src - graph->node;
4858 data.dst = graph->edge[edge].dst - graph->node;
4860 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
4861 &cluster_follows, &data);
4862 if (!g)
4863 goto error;
4865 i = g->op;
4866 if (i < 3)
4867 isl_die(ctx, isl_error_internal,
4868 "expecting at least two nodes in component",
4869 goto error);
4870 if (g->order[--i] != -1)
4871 isl_die(ctx, isl_error_internal,
4872 "expecting end of component marker", goto error);
4874 for (--i; i >= 0 && g->order[i] != -1; --i) {
4875 int scc = graph->node[g->order[i]].scc;
4876 c->scc_in_merge[scc] = 1;
4879 isl_tarjan_graph_free(g);
4880 return isl_stat_ok;
4881 error:
4882 isl_tarjan_graph_free(g);
4883 return isl_stat_error;
4886 /* Construct the identifier "cluster_i".
4888 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
4890 char name[40];
4892 snprintf(name, sizeof(name), "cluster_%d", i);
4893 return isl_id_alloc(ctx, name, NULL);
4896 /* Construct the space of the cluster with index "i" containing
4897 * the strongly connected component "scc".
4899 * In particular, construct a space called cluster_i with dimension equal
4900 * to the number of schedule rows in the current band of "scc".
4902 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
4904 int nvar;
4905 isl_space *space;
4906 isl_id *id;
4908 nvar = scc->n_total_row - scc->band_start;
4909 space = isl_space_copy(scc->node[0].space);
4910 space = isl_space_params(space);
4911 space = isl_space_set_from_params(space);
4912 space = isl_space_add_dims(space, isl_dim_set, nvar);
4913 id = cluster_id(isl_space_get_ctx(space), i);
4914 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4916 return space;
4919 /* Collect the domain of the graph for merging clusters.
4921 * In particular, for each cluster with first SCC "i", construct
4922 * a set in the space called cluster_i with dimension equal
4923 * to the number of schedule rows in the current band of the cluster.
4925 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
4926 struct isl_sched_graph *graph, struct isl_clustering *c)
4928 int i;
4929 isl_space *space;
4930 isl_union_set *domain;
4932 space = isl_space_params_alloc(ctx, 0);
4933 domain = isl_union_set_empty(space);
4935 for (i = 0; i < graph->scc; ++i) {
4936 isl_space *space;
4938 if (!c->scc_in_merge[i])
4939 continue;
4940 if (c->scc_cluster[i] != i)
4941 continue;
4942 space = cluster_space(&c->scc[i], i);
4943 domain = isl_union_set_add_set(domain, isl_set_universe(space));
4946 return domain;
4949 /* Construct a map from the original instances to the corresponding
4950 * cluster instance in the current bands of the clusters in "c".
4952 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
4953 struct isl_sched_graph *graph, struct isl_clustering *c)
4955 int i, j;
4956 isl_space *space;
4957 isl_union_map *cluster_map;
4959 space = isl_space_params_alloc(ctx, 0);
4960 cluster_map = isl_union_map_empty(space);
4961 for (i = 0; i < graph->scc; ++i) {
4962 int start, n;
4963 isl_id *id;
4965 if (!c->scc_in_merge[i])
4966 continue;
4968 id = cluster_id(ctx, c->scc_cluster[i]);
4969 start = c->scc[i].band_start;
4970 n = c->scc[i].n_total_row - start;
4971 for (j = 0; j < c->scc[i].n; ++j) {
4972 isl_multi_aff *ma;
4973 isl_map *map;
4974 struct isl_sched_node *node = &c->scc[i].node[j];
4976 ma = node_extract_partial_schedule_multi_aff(node,
4977 start, n);
4978 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
4979 isl_id_copy(id));
4980 map = isl_map_from_multi_aff(ma);
4981 cluster_map = isl_union_map_add_map(cluster_map, map);
4983 isl_id_free(id);
4986 return cluster_map;
4989 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
4990 * that are not isl_edge_condition or isl_edge_conditional_validity.
4992 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
4993 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
4994 __isl_take isl_schedule_constraints *sc)
4996 enum isl_edge_type t;
4998 if (!sc)
4999 return NULL;
5001 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5002 if (t == isl_edge_condition ||
5003 t == isl_edge_conditional_validity)
5004 continue;
5005 if (!is_type(edge, t))
5006 continue;
5007 sc = isl_schedule_constraints_add(sc, t,
5008 isl_union_map_copy(umap));
5011 return sc;
5014 /* Add schedule constraints of types isl_edge_condition and
5015 * isl_edge_conditional_validity to "sc" by applying "umap" to
5016 * the domains of the wrapped relations in domain and range
5017 * of the corresponding tagged constraints of "edge".
5019 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5020 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5021 __isl_take isl_schedule_constraints *sc)
5023 enum isl_edge_type t;
5024 isl_union_map *tagged;
5026 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5027 if (!is_type(edge, t))
5028 continue;
5029 if (t == isl_edge_condition)
5030 tagged = isl_union_map_copy(edge->tagged_condition);
5031 else
5032 tagged = isl_union_map_copy(edge->tagged_validity);
5033 tagged = isl_union_map_zip(tagged);
5034 tagged = isl_union_map_apply_domain(tagged,
5035 isl_union_map_copy(umap));
5036 tagged = isl_union_map_zip(tagged);
5037 sc = isl_schedule_constraints_add(sc, t, tagged);
5038 if (!sc)
5039 return NULL;
5042 return sc;
5045 /* Given a mapping "cluster_map" from the original instances to
5046 * the cluster instances, add schedule constraints on the clusters
5047 * to "sc" corresponding to the original constraints represented by "edge".
5049 * For non-tagged dependence constraints, the cluster constraints
5050 * are obtained by applying "cluster_map" to the edge->map.
5052 * For tagged dependence constraints, "cluster_map" needs to be applied
5053 * to the domains of the wrapped relations in domain and range
5054 * of the tagged dependence constraints. Pick out the mappings
5055 * from these domains from "cluster_map" and construct their product.
5056 * This mapping can then be applied to the pair of domains.
5058 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5059 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5060 __isl_take isl_schedule_constraints *sc)
5062 isl_union_map *umap;
5063 isl_space *space;
5064 isl_union_set *uset;
5065 isl_union_map *umap1, *umap2;
5067 if (!sc)
5068 return NULL;
5070 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5071 umap = isl_union_map_apply_domain(umap,
5072 isl_union_map_copy(cluster_map));
5073 umap = isl_union_map_apply_range(umap,
5074 isl_union_map_copy(cluster_map));
5075 sc = add_non_conditional_constraints(edge, umap, sc);
5076 isl_union_map_free(umap);
5078 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5079 return sc;
5081 space = isl_space_domain(isl_map_get_space(edge->map));
5082 uset = isl_union_set_from_set(isl_set_universe(space));
5083 umap1 = isl_union_map_copy(cluster_map);
5084 umap1 = isl_union_map_intersect_domain(umap1, uset);
5085 space = isl_space_range(isl_map_get_space(edge->map));
5086 uset = isl_union_set_from_set(isl_set_universe(space));
5087 umap2 = isl_union_map_copy(cluster_map);
5088 umap2 = isl_union_map_intersect_domain(umap2, uset);
5089 umap = isl_union_map_product(umap1, umap2);
5091 sc = add_conditional_constraints(edge, umap, sc);
5093 isl_union_map_free(umap);
5094 return sc;
5097 /* Given a mapping "cluster_map" from the original instances to
5098 * the cluster instances, add schedule constraints on the clusters
5099 * to "sc" corresponding to all edges in "graph" between nodes that
5100 * belong to SCCs that are marked for merging in "scc_in_merge".
5102 static __isl_give isl_schedule_constraints *collect_constraints(
5103 struct isl_sched_graph *graph, int *scc_in_merge,
5104 __isl_keep isl_union_map *cluster_map,
5105 __isl_take isl_schedule_constraints *sc)
5107 int i;
5109 for (i = 0; i < graph->n_edge; ++i) {
5110 struct isl_sched_edge *edge = &graph->edge[i];
5112 if (!scc_in_merge[edge->src->scc])
5113 continue;
5114 if (!scc_in_merge[edge->dst->scc])
5115 continue;
5116 sc = collect_edge_constraints(edge, cluster_map, sc);
5119 return sc;
5122 /* Construct a dependence graph for scheduling clusters with respect
5123 * to each other and store the result in "merge_graph".
5124 * In particular, the nodes of the graph correspond to the schedule
5125 * dimensions of the current bands of those clusters that have been
5126 * marked for merging in "c".
5128 * First construct an isl_schedule_constraints object for this domain
5129 * by transforming the edges in "graph" to the domain.
5130 * Then initialize a dependence graph for scheduling from these
5131 * constraints.
5133 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5134 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5136 isl_union_set *domain;
5137 isl_union_map *cluster_map;
5138 isl_schedule_constraints *sc;
5139 isl_stat r;
5141 domain = collect_domain(ctx, graph, c);
5142 sc = isl_schedule_constraints_on_domain(domain);
5143 if (!sc)
5144 return isl_stat_error;
5145 cluster_map = collect_cluster_map(ctx, graph, c);
5146 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5147 isl_union_map_free(cluster_map);
5149 r = graph_init(merge_graph, sc);
5151 isl_schedule_constraints_free(sc);
5153 return r;
5156 /* Compute the maximal number of remaining schedule rows that still need
5157 * to be computed for the nodes that belong to clusters with the maximal
5158 * dimension for the current band (i.e., the band that is to be merged).
5159 * Only clusters that are about to be merged are considered.
5160 * "maxvar" is the maximal dimension for the current band.
5161 * "c" contains information about the clusters.
5163 * Return the maximal number of remaining schedule rows or -1 on error.
5165 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5167 int i, j;
5168 int max_slack;
5170 max_slack = 0;
5171 for (i = 0; i < c->n; ++i) {
5172 int nvar;
5173 struct isl_sched_graph *scc;
5175 if (!c->scc_in_merge[i])
5176 continue;
5177 scc = &c->scc[i];
5178 nvar = scc->n_total_row - scc->band_start;
5179 if (nvar != maxvar)
5180 continue;
5181 for (j = 0; j < scc->n; ++j) {
5182 struct isl_sched_node *node = &scc->node[j];
5183 int slack;
5185 if (node_update_cmap(node) < 0)
5186 return -1;
5187 slack = node->nvar - node->rank;
5188 if (slack > max_slack)
5189 max_slack = slack;
5193 return max_slack;
5196 /* If there are any clusters where the dimension of the current band
5197 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5198 * if there are any nodes in such a cluster where the number
5199 * of remaining schedule rows that still need to be computed
5200 * is greater than "max_slack", then return the smallest current band
5201 * dimension of all these clusters. Otherwise return the original value
5202 * of "maxvar". Return -1 in case of any error.
5203 * Only clusters that are about to be merged are considered.
5204 * "c" contains information about the clusters.
5206 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5207 struct isl_clustering *c)
5209 int i, j;
5211 for (i = 0; i < c->n; ++i) {
5212 int nvar;
5213 struct isl_sched_graph *scc;
5215 if (!c->scc_in_merge[i])
5216 continue;
5217 scc = &c->scc[i];
5218 nvar = scc->n_total_row - scc->band_start;
5219 if (nvar >= maxvar)
5220 continue;
5221 for (j = 0; j < scc->n; ++j) {
5222 struct isl_sched_node *node = &scc->node[j];
5223 int slack;
5225 if (node_update_cmap(node) < 0)
5226 return -1;
5227 slack = node->nvar - node->rank;
5228 if (slack > max_slack) {
5229 maxvar = nvar;
5230 break;
5235 return maxvar;
5238 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5239 * that still need to be computed. In particular, if there is a node
5240 * in a cluster where the dimension of the current band is smaller
5241 * than merge_graph->maxvar, but the number of remaining schedule rows
5242 * is greater than that of any node in a cluster with the maximal
5243 * dimension for the current band (i.e., merge_graph->maxvar),
5244 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5245 * of those clusters. Without this adjustment, the total number of
5246 * schedule dimensions would be increased, resulting in a skewed view
5247 * of the number of coincident dimensions.
5248 * "c" contains information about the clusters.
5250 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5251 * then there is no point in attempting any merge since it will be rejected
5252 * anyway. Set merge_graph->maxvar to zero in such cases.
5254 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5255 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5257 int max_slack, maxvar;
5259 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5260 if (max_slack < 0)
5261 return isl_stat_error;
5262 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5263 if (maxvar < 0)
5264 return isl_stat_error;
5266 if (maxvar < merge_graph->maxvar) {
5267 if (isl_options_get_schedule_maximize_band_depth(ctx))
5268 merge_graph->maxvar = 0;
5269 else
5270 merge_graph->maxvar = maxvar;
5273 return isl_stat_ok;
5276 /* Return the number of coincident dimensions in the current band of "graph",
5277 * where the nodes of "graph" are assumed to be scheduled by a single band.
5279 static int get_n_coincident(struct isl_sched_graph *graph)
5281 int i;
5283 for (i = graph->band_start; i < graph->n_total_row; ++i)
5284 if (!graph->node[0].coincident[i])
5285 break;
5287 return i - graph->band_start;
5290 /* Should the clusters be merged based on the cluster schedule
5291 * in the current (and only) band of "merge_graph", given that
5292 * coincidence should be maximized?
5294 * If the number of coincident schedule dimensions in the merged band
5295 * would be less than the maximal number of coincident schedule dimensions
5296 * in any of the merged clusters, then the clusters should not be merged.
5298 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5299 struct isl_sched_graph *merge_graph)
5301 int i;
5302 int n_coincident;
5303 int max_coincident;
5305 max_coincident = 0;
5306 for (i = 0; i < c->n; ++i) {
5307 if (!c->scc_in_merge[i])
5308 continue;
5309 n_coincident = get_n_coincident(&c->scc[i]);
5310 if (n_coincident > max_coincident)
5311 max_coincident = n_coincident;
5314 n_coincident = get_n_coincident(merge_graph);
5316 return n_coincident >= max_coincident;
5319 /* Return the transformation on "node" expressed by the current (and only)
5320 * band of "merge_graph" applied to the clusters in "c".
5322 * First find the representation of "node" in its SCC in "c" and
5323 * extract the transformation expressed by the current band.
5324 * Then extract the transformation applied by "merge_graph"
5325 * to the cluster to which this SCC belongs.
5326 * Combine the two to obtain the complete transformation on the node.
5328 * Note that the range of the first transformation is an anonymous space,
5329 * while the domain of the second is named "cluster_X". The range
5330 * of the former therefore needs to be adjusted before the two
5331 * can be combined.
5333 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5334 struct isl_sched_node *node, struct isl_clustering *c,
5335 struct isl_sched_graph *merge_graph)
5337 struct isl_sched_node *scc_node, *cluster_node;
5338 int start, n;
5339 isl_id *id;
5340 isl_space *space;
5341 isl_multi_aff *ma, *ma2;
5343 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5344 start = c->scc[node->scc].band_start;
5345 n = c->scc[node->scc].n_total_row - start;
5346 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5347 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5348 cluster_node = graph_find_node(ctx, merge_graph, space);
5349 if (space && !cluster_node)
5350 isl_die(ctx, isl_error_internal, "unable to find cluster",
5351 space = isl_space_free(space));
5352 id = isl_space_get_tuple_id(space, isl_dim_set);
5353 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5354 isl_space_free(space);
5355 n = merge_graph->n_total_row;
5356 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5357 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5359 return isl_map_from_multi_aff(ma);
5362 /* Give a set of distances "set", are they bounded by a small constant
5363 * in direction "pos"?
5364 * In practice, check if they are bounded by 2 by checking that there
5365 * are no elements with a value greater than or equal to 3 or
5366 * smaller than or equal to -3.
5368 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5370 isl_bool bounded;
5371 isl_set *test;
5373 if (!set)
5374 return isl_bool_error;
5376 test = isl_set_copy(set);
5377 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5378 bounded = isl_set_is_empty(test);
5379 isl_set_free(test);
5381 if (bounded < 0 || !bounded)
5382 return bounded;
5384 test = isl_set_copy(set);
5385 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5386 bounded = isl_set_is_empty(test);
5387 isl_set_free(test);
5389 return bounded;
5392 /* Does the set "set" have a fixed (but possible parametric) value
5393 * at dimension "pos"?
5395 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5397 int n;
5398 isl_bool single;
5400 if (!set)
5401 return isl_bool_error;
5402 set = isl_set_copy(set);
5403 n = isl_set_dim(set, isl_dim_set);
5404 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5405 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5406 single = isl_set_is_singleton(set);
5407 isl_set_free(set);
5409 return single;
5412 /* Does "map" have a fixed (but possible parametric) value
5413 * at dimension "pos" of either its domain or its range?
5415 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5417 isl_set *set;
5418 isl_bool single;
5420 set = isl_map_domain(isl_map_copy(map));
5421 single = has_single_value(set, pos);
5422 isl_set_free(set);
5424 if (single < 0 || single)
5425 return single;
5427 set = isl_map_range(isl_map_copy(map));
5428 single = has_single_value(set, pos);
5429 isl_set_free(set);
5431 return single;
5434 /* Does the edge "edge" from "graph" have bounded dependence distances
5435 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5437 * Extract the complete transformations of the source and destination
5438 * nodes of the edge, apply them to the edge constraints and
5439 * compute the differences. Finally, check if these differences are bounded
5440 * in each direction.
5442 * If the dimension of the band is greater than the number of
5443 * dimensions that can be expected to be optimized by the edge
5444 * (based on its weight), then also allow the differences to be unbounded
5445 * in the remaining dimensions, but only if either the source or
5446 * the destination has a fixed value in that direction.
5447 * This allows a statement that produces values that are used by
5448 * several instances of another statement to be merged with that
5449 * other statement.
5450 * However, merging such clusters will introduce an inherently
5451 * large proximity distance inside the merged cluster, meaning
5452 * that proximity distances will no longer be optimized in
5453 * subsequent merges. These merges are therefore only allowed
5454 * after all other possible merges have been tried.
5455 * The first time such a merge is encountered, the weight of the edge
5456 * is replaced by a negative weight. The second time (i.e., after
5457 * all merges over edges with a non-negative weight have been tried),
5458 * the merge is allowed.
5460 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5461 struct isl_sched_graph *graph, struct isl_clustering *c,
5462 struct isl_sched_graph *merge_graph)
5464 int i, n, n_slack;
5465 isl_bool bounded;
5466 isl_map *map, *t;
5467 isl_set *dist;
5469 map = isl_map_copy(edge->map);
5470 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5471 map = isl_map_apply_domain(map, t);
5472 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5473 map = isl_map_apply_range(map, t);
5474 dist = isl_map_deltas(isl_map_copy(map));
5476 bounded = isl_bool_true;
5477 n = isl_set_dim(dist, isl_dim_set);
5478 n_slack = n - edge->weight;
5479 if (edge->weight < 0)
5480 n_slack -= graph->max_weight + 1;
5481 for (i = 0; i < n; ++i) {
5482 isl_bool bounded_i, singular_i;
5484 bounded_i = distance_is_bounded(dist, i);
5485 if (bounded_i < 0)
5486 goto error;
5487 if (bounded_i)
5488 continue;
5489 if (edge->weight >= 0)
5490 bounded = isl_bool_false;
5491 n_slack--;
5492 if (n_slack < 0)
5493 break;
5494 singular_i = has_singular_src_or_dst(map, i);
5495 if (singular_i < 0)
5496 goto error;
5497 if (singular_i)
5498 continue;
5499 bounded = isl_bool_false;
5500 break;
5502 if (!bounded && i >= n && edge->weight >= 0)
5503 edge->weight -= graph->max_weight + 1;
5504 isl_map_free(map);
5505 isl_set_free(dist);
5507 return bounded;
5508 error:
5509 isl_map_free(map);
5510 isl_set_free(dist);
5511 return isl_bool_error;
5514 /* Should the clusters be merged based on the cluster schedule
5515 * in the current (and only) band of "merge_graph"?
5516 * "graph" is the original dependence graph, while "c" records
5517 * which SCCs are involved in the latest merge.
5519 * In particular, is there at least one proximity constraint
5520 * that is optimized by the merge?
5522 * A proximity constraint is considered to be optimized
5523 * if the dependence distances are small.
5525 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
5526 struct isl_sched_graph *graph, struct isl_clustering *c,
5527 struct isl_sched_graph *merge_graph)
5529 int i;
5531 for (i = 0; i < graph->n_edge; ++i) {
5532 struct isl_sched_edge *edge = &graph->edge[i];
5533 isl_bool bounded;
5535 if (!is_proximity(edge))
5536 continue;
5537 if (!c->scc_in_merge[edge->src->scc])
5538 continue;
5539 if (!c->scc_in_merge[edge->dst->scc])
5540 continue;
5541 if (c->scc_cluster[edge->dst->scc] ==
5542 c->scc_cluster[edge->src->scc])
5543 continue;
5544 bounded = has_bounded_distances(ctx, edge, graph, c,
5545 merge_graph);
5546 if (bounded < 0 || bounded)
5547 return bounded;
5550 return isl_bool_false;
5553 /* Should the clusters be merged based on the cluster schedule
5554 * in the current (and only) band of "merge_graph"?
5555 * "graph" is the original dependence graph, while "c" records
5556 * which SCCs are involved in the latest merge.
5558 * If the current band is empty, then the clusters should not be merged.
5560 * If the band depth should be maximized and the merge schedule
5561 * is incomplete (meaning that the dimension of some of the schedule
5562 * bands in the original schedule will be reduced), then the clusters
5563 * should not be merged.
5565 * If the schedule_maximize_coincidence option is set, then check that
5566 * the number of coincident schedule dimensions is not reduced.
5568 * Finally, only allow the merge if at least one proximity
5569 * constraint is optimized.
5571 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
5572 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5574 if (merge_graph->n_total_row == merge_graph->band_start)
5575 return isl_bool_false;
5577 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
5578 merge_graph->n_total_row < merge_graph->maxvar)
5579 return isl_bool_false;
5581 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
5582 isl_bool ok;
5584 ok = ok_to_merge_coincident(c, merge_graph);
5585 if (ok < 0 || !ok)
5586 return ok;
5589 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
5592 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
5593 * of the schedule in "node" and return the result.
5595 * That is, essentially compute
5597 * T * N(first:first+n-1)
5599 * taking into account the constant term and the parameter coefficients
5600 * in "t_node".
5602 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
5603 struct isl_sched_node *t_node, struct isl_sched_node *node,
5604 int first, int n)
5606 int i, j;
5607 isl_mat *t;
5608 int n_row, n_col, n_param, n_var;
5610 n_param = node->nparam;
5611 n_var = node->nvar;
5612 n_row = isl_mat_rows(t_node->sched);
5613 n_col = isl_mat_cols(node->sched);
5614 t = isl_mat_alloc(ctx, n_row, n_col);
5615 if (!t)
5616 return NULL;
5617 for (i = 0; i < n_row; ++i) {
5618 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
5619 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
5620 for (j = 0; j < n; ++j)
5621 isl_seq_addmul(t->row[i],
5622 t_node->sched->row[i][1 + n_param + j],
5623 node->sched->row[first + j],
5624 1 + n_param + n_var);
5626 return t;
5629 /* Apply the cluster schedule in "t_node" to the current band
5630 * schedule of the nodes in "graph".
5632 * In particular, replace the rows starting at band_start
5633 * by the result of applying the cluster schedule in "t_node"
5634 * to the original rows.
5636 * The coincidence of the schedule is determined by the coincidence
5637 * of the cluster schedule.
5639 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
5640 struct isl_sched_node *t_node)
5642 int i, j;
5643 int n_new;
5644 int start, n;
5646 start = graph->band_start;
5647 n = graph->n_total_row - start;
5649 n_new = isl_mat_rows(t_node->sched);
5650 for (i = 0; i < graph->n; ++i) {
5651 struct isl_sched_node *node = &graph->node[i];
5652 isl_mat *t;
5654 t = node_transformation(ctx, t_node, node, start, n);
5655 node->sched = isl_mat_drop_rows(node->sched, start, n);
5656 node->sched = isl_mat_concat(node->sched, t);
5657 node->sched_map = isl_map_free(node->sched_map);
5658 if (!node->sched)
5659 return isl_stat_error;
5660 for (j = 0; j < n_new; ++j)
5661 node->coincident[start + j] = t_node->coincident[j];
5663 graph->n_total_row -= n;
5664 graph->n_row -= n;
5665 graph->n_total_row += n_new;
5666 graph->n_row += n_new;
5668 return isl_stat_ok;
5671 /* Merge the clusters marked for merging in "c" into a single
5672 * cluster using the cluster schedule in the current band of "merge_graph".
5673 * The representative SCC for the new cluster is the SCC with
5674 * the smallest index.
5676 * The current band schedule of each SCC in the new cluster is obtained
5677 * by applying the schedule of the corresponding original cluster
5678 * to the original band schedule.
5679 * All SCCs in the new cluster have the same number of schedule rows.
5681 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
5682 struct isl_sched_graph *merge_graph)
5684 int i;
5685 int cluster = -1;
5686 isl_space *space;
5688 for (i = 0; i < c->n; ++i) {
5689 struct isl_sched_node *node;
5691 if (!c->scc_in_merge[i])
5692 continue;
5693 if (cluster < 0)
5694 cluster = i;
5695 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
5696 if (!space)
5697 return isl_stat_error;
5698 node = graph_find_node(ctx, merge_graph, space);
5699 isl_space_free(space);
5700 if (!node)
5701 isl_die(ctx, isl_error_internal,
5702 "unable to find cluster",
5703 return isl_stat_error);
5704 if (transform(ctx, &c->scc[i], node) < 0)
5705 return isl_stat_error;
5706 c->scc_cluster[i] = cluster;
5709 return isl_stat_ok;
5712 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
5713 * by scheduling the current cluster bands with respect to each other.
5715 * Construct a dependence graph with a space for each cluster and
5716 * with the coordinates of each space corresponding to the schedule
5717 * dimensions of the current band of that cluster.
5718 * Construct a cluster schedule in this cluster dependence graph and
5719 * apply it to the current cluster bands if it is applicable
5720 * according to ok_to_merge.
5722 * If the number of remaining schedule dimensions in a cluster
5723 * with a non-maximal current schedule dimension is greater than
5724 * the number of remaining schedule dimensions in clusters
5725 * with a maximal current schedule dimension, then restrict
5726 * the number of rows to be computed in the cluster schedule
5727 * to the minimal such non-maximal current schedule dimension.
5728 * Do this by adjusting merge_graph.maxvar.
5730 * Return isl_bool_true if the clusters have effectively been merged
5731 * into a single cluster.
5733 * Note that since the standard scheduling algorithm minimizes the maximal
5734 * distance over proximity constraints, the proximity constraints between
5735 * the merged clusters may not be optimized any further than what is
5736 * sufficient to bring the distances within the limits of the internal
5737 * proximity constraints inside the individual clusters.
5738 * It may therefore make sense to perform an additional translation step
5739 * to bring the clusters closer to each other, while maintaining
5740 * the linear part of the merging schedule found using the standard
5741 * scheduling algorithm.
5743 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
5744 struct isl_clustering *c)
5746 struct isl_sched_graph merge_graph = { 0 };
5747 isl_bool merged;
5749 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
5750 goto error;
5752 if (compute_maxvar(&merge_graph) < 0)
5753 goto error;
5754 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
5755 goto error;
5756 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
5757 goto error;
5758 merged = ok_to_merge(ctx, graph, c, &merge_graph);
5759 if (merged && merge(ctx, c, &merge_graph) < 0)
5760 goto error;
5762 graph_free(ctx, &merge_graph);
5763 return merged;
5764 error:
5765 graph_free(ctx, &merge_graph);
5766 return isl_bool_error;
5769 /* Is there any edge marked "no_merge" between two SCCs that are
5770 * about to be merged (i.e., that are set in "scc_in_merge")?
5771 * "merge_edge" is the proximity edge along which the clusters of SCCs
5772 * are going to be merged.
5774 * If there is any edge between two SCCs with a negative weight,
5775 * while the weight of "merge_edge" is non-negative, then this
5776 * means that the edge was postponed. "merge_edge" should then
5777 * also be postponed since merging along the edge with negative weight should
5778 * be postponed until all edges with non-negative weight have been tried.
5779 * Replace the weight of "merge_edge" by a negative weight as well and
5780 * tell the caller not to attempt a merge.
5782 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
5783 struct isl_sched_edge *merge_edge)
5785 int i;
5787 for (i = 0; i < graph->n_edge; ++i) {
5788 struct isl_sched_edge *edge = &graph->edge[i];
5790 if (!scc_in_merge[edge->src->scc])
5791 continue;
5792 if (!scc_in_merge[edge->dst->scc])
5793 continue;
5794 if (edge->no_merge)
5795 return 1;
5796 if (merge_edge->weight >= 0 && edge->weight < 0) {
5797 merge_edge->weight -= graph->max_weight + 1;
5798 return 1;
5802 return 0;
5805 /* Merge the two clusters in "c" connected by the edge in "graph"
5806 * with index "edge" into a single cluster.
5807 * If it turns out to be impossible to merge these two clusters,
5808 * then mark the edge as "no_merge" such that it will not be
5809 * considered again.
5811 * First mark all SCCs that need to be merged. This includes the SCCs
5812 * in the two clusters, but it may also include the SCCs
5813 * of intermediate clusters.
5814 * If there is already a no_merge edge between any pair of such SCCs,
5815 * then simply mark the current edge as no_merge as well.
5816 * Likewise, if any of those edges was postponed by has_bounded_distances,
5817 * then postpone the current edge as well.
5818 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
5819 * if the clusters did not end up getting merged, unless the non-merge
5820 * is due to the fact that the edge was postponed. This postponement
5821 * can be recognized by a change in weight (from non-negative to negative).
5823 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
5824 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
5826 isl_bool merged;
5827 int edge_weight = graph->edge[edge].weight;
5829 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
5830 return isl_stat_error;
5832 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
5833 merged = isl_bool_false;
5834 else
5835 merged = try_merge(ctx, graph, c);
5836 if (merged < 0)
5837 return isl_stat_error;
5838 if (!merged && edge_weight == graph->edge[edge].weight)
5839 graph->edge[edge].no_merge = 1;
5841 return isl_stat_ok;
5844 /* Does "node" belong to the cluster identified by "cluster"?
5846 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
5848 return node->cluster == cluster;
5851 /* Does "edge" connect two nodes belonging to the cluster
5852 * identified by "cluster"?
5854 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
5856 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
5859 /* Swap the schedule of "node1" and "node2".
5860 * Both nodes have been derived from the same node in a common parent graph.
5861 * Since the "coincident" field is shared with that node
5862 * in the parent graph, there is no need to also swap this field.
5864 static void swap_sched(struct isl_sched_node *node1,
5865 struct isl_sched_node *node2)
5867 isl_mat *sched;
5868 isl_map *sched_map;
5870 sched = node1->sched;
5871 node1->sched = node2->sched;
5872 node2->sched = sched;
5874 sched_map = node1->sched_map;
5875 node1->sched_map = node2->sched_map;
5876 node2->sched_map = sched_map;
5879 /* Copy the current band schedule from the SCCs that form the cluster
5880 * with index "pos" to the actual cluster at position "pos".
5881 * By construction, the index of the first SCC that belongs to the cluster
5882 * is also "pos".
5884 * The order of the nodes inside both the SCCs and the cluster
5885 * is assumed to be same as the order in the original "graph".
5887 * Since the SCC graphs will no longer be used after this function,
5888 * the schedules are actually swapped rather than copied.
5890 static isl_stat copy_partial(struct isl_sched_graph *graph,
5891 struct isl_clustering *c, int pos)
5893 int i, j;
5895 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
5896 c->cluster[pos].n_row = c->scc[pos].n_row;
5897 c->cluster[pos].maxvar = c->scc[pos].maxvar;
5898 j = 0;
5899 for (i = 0; i < graph->n; ++i) {
5900 int k;
5901 int s;
5903 if (graph->node[i].cluster != pos)
5904 continue;
5905 s = graph->node[i].scc;
5906 k = c->scc_node[s]++;
5907 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
5908 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
5909 c->cluster[pos].maxvar = c->scc[s].maxvar;
5910 ++j;
5913 return isl_stat_ok;
5916 /* Is there a (conditional) validity dependence from node[j] to node[i],
5917 * forcing node[i] to follow node[j] or do the nodes belong to the same
5918 * cluster?
5920 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
5922 struct isl_sched_graph *graph = user;
5924 if (graph->node[i].cluster == graph->node[j].cluster)
5925 return isl_bool_true;
5926 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5929 /* Extract the merged clusters of SCCs in "graph", sort them, and
5930 * store them in c->clusters. Update c->scc_cluster accordingly.
5932 * First keep track of the cluster containing the SCC to which a node
5933 * belongs in the node itself.
5934 * Then extract the clusters into c->clusters, copying the current
5935 * band schedule from the SCCs that belong to the cluster.
5936 * Do this only once per cluster.
5938 * Finally, topologically sort the clusters and update c->scc_cluster
5939 * to match the new scc numbering. While the SCCs were originally
5940 * sorted already, some SCCs that depend on some other SCCs may
5941 * have been merged with SCCs that appear before these other SCCs.
5942 * A reordering may therefore be required.
5944 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
5945 struct isl_clustering *c)
5947 int i;
5949 for (i = 0; i < graph->n; ++i)
5950 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
5952 for (i = 0; i < graph->scc; ++i) {
5953 if (c->scc_cluster[i] != i)
5954 continue;
5955 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
5956 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
5957 return isl_stat_error;
5958 c->cluster[i].src_scc = -1;
5959 c->cluster[i].dst_scc = -1;
5960 if (copy_partial(graph, c, i) < 0)
5961 return isl_stat_error;
5964 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
5965 return isl_stat_error;
5966 for (i = 0; i < graph->n; ++i)
5967 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
5969 return isl_stat_ok;
5972 /* Compute weights on the proximity edges of "graph" that can
5973 * be used by find_proximity to find the most appropriate
5974 * proximity edge to use to merge two clusters in "c".
5975 * The weights are also used by has_bounded_distances to determine
5976 * whether the merge should be allowed.
5977 * Store the maximum of the computed weights in graph->max_weight.
5979 * The computed weight is a measure for the number of remaining schedule
5980 * dimensions that can still be completely aligned.
5981 * In particular, compute the number of equalities between
5982 * input dimensions and output dimensions in the proximity constraints.
5983 * The directions that are already handled by outer schedule bands
5984 * are projected out prior to determining this number.
5986 * Edges that will never be considered by find_proximity are ignored.
5988 static isl_stat compute_weights(struct isl_sched_graph *graph,
5989 struct isl_clustering *c)
5991 int i;
5993 graph->max_weight = 0;
5995 for (i = 0; i < graph->n_edge; ++i) {
5996 struct isl_sched_edge *edge = &graph->edge[i];
5997 struct isl_sched_node *src = edge->src;
5998 struct isl_sched_node *dst = edge->dst;
5999 isl_basic_map *hull;
6000 int n_in, n_out;
6002 if (!is_proximity(edge))
6003 continue;
6004 if (bad_cluster(&c->scc[edge->src->scc]) ||
6005 bad_cluster(&c->scc[edge->dst->scc]))
6006 continue;
6007 if (c->scc_cluster[edge->dst->scc] ==
6008 c->scc_cluster[edge->src->scc])
6009 continue;
6011 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6012 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6013 isl_mat_copy(src->ctrans));
6014 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6015 isl_mat_copy(dst->ctrans));
6016 hull = isl_basic_map_project_out(hull,
6017 isl_dim_in, 0, src->rank);
6018 hull = isl_basic_map_project_out(hull,
6019 isl_dim_out, 0, dst->rank);
6020 hull = isl_basic_map_remove_divs(hull);
6021 n_in = isl_basic_map_dim(hull, isl_dim_in);
6022 n_out = isl_basic_map_dim(hull, isl_dim_out);
6023 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6024 isl_dim_in, 0, n_in);
6025 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6026 isl_dim_out, 0, n_out);
6027 if (!hull)
6028 return isl_stat_error;
6029 edge->weight = hull->n_eq;
6030 isl_basic_map_free(hull);
6032 if (edge->weight > graph->max_weight)
6033 graph->max_weight = edge->weight;
6036 return isl_stat_ok;
6039 /* Call compute_schedule_finish_band on each of the clusters in "c"
6040 * in their topological order. This order is determined by the scc
6041 * fields of the nodes in "graph".
6042 * Combine the results in a sequence expressing the topological order.
6044 * If there is only one cluster left, then there is no need to introduce
6045 * a sequence node. Also, in this case, the cluster necessarily contains
6046 * the SCC at position 0 in the original graph and is therefore also
6047 * stored in the first cluster of "c".
6049 static __isl_give isl_schedule_node *finish_bands_clustering(
6050 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6051 struct isl_clustering *c)
6053 int i;
6054 isl_ctx *ctx;
6055 isl_union_set_list *filters;
6057 if (graph->scc == 1)
6058 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6060 ctx = isl_schedule_node_get_ctx(node);
6062 filters = extract_sccs(ctx, graph);
6063 node = isl_schedule_node_insert_sequence(node, filters);
6065 for (i = 0; i < graph->scc; ++i) {
6066 int j = c->scc_cluster[i];
6067 node = isl_schedule_node_child(node, i);
6068 node = isl_schedule_node_child(node, 0);
6069 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6070 node = isl_schedule_node_parent(node);
6071 node = isl_schedule_node_parent(node);
6074 return node;
6077 /* Compute a schedule for a connected dependence graph by first considering
6078 * each strongly connected component (SCC) in the graph separately and then
6079 * incrementally combining them into clusters.
6080 * Return the updated schedule node.
6082 * Initially, each cluster consists of a single SCC, each with its
6083 * own band schedule. The algorithm then tries to merge pairs
6084 * of clusters along a proximity edge until no more suitable
6085 * proximity edges can be found. During this merging, the schedule
6086 * is maintained in the individual SCCs.
6087 * After the merging is completed, the full resulting clusters
6088 * are extracted and in finish_bands_clustering,
6089 * compute_schedule_finish_band is called on each of them to integrate
6090 * the band into "node" and to continue the computation.
6092 * compute_weights initializes the weights that are used by find_proximity.
6094 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6095 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6097 isl_ctx *ctx;
6098 struct isl_clustering c;
6099 int i;
6101 ctx = isl_schedule_node_get_ctx(node);
6103 if (clustering_init(ctx, &c, graph) < 0)
6104 goto error;
6106 if (compute_weights(graph, &c) < 0)
6107 goto error;
6109 for (;;) {
6110 i = find_proximity(graph, &c);
6111 if (i < 0)
6112 goto error;
6113 if (i >= graph->n_edge)
6114 break;
6115 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6116 goto error;
6119 if (extract_clusters(ctx, graph, &c) < 0)
6120 goto error;
6122 node = finish_bands_clustering(node, graph, &c);
6124 clustering_free(ctx, &c);
6125 return node;
6126 error:
6127 clustering_free(ctx, &c);
6128 return isl_schedule_node_free(node);
6131 /* Compute a schedule for a connected dependence graph and return
6132 * the updated schedule node.
6134 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6135 * as many validity dependences as possible. When all validity dependences
6136 * are satisfied we extend the schedule to a full-dimensional schedule.
6138 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6139 * depending on whether the user has selected the option to try and
6140 * compute a schedule for the entire (weakly connected) component first.
6141 * If there is only a single strongly connected component (SCC), then
6142 * there is no point in trying to combine SCCs
6143 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6144 * is called instead.
6146 static __isl_give isl_schedule_node *compute_schedule_wcc(
6147 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6149 isl_ctx *ctx;
6151 if (!node)
6152 return NULL;
6154 ctx = isl_schedule_node_get_ctx(node);
6155 if (detect_sccs(ctx, graph) < 0)
6156 return isl_schedule_node_free(node);
6158 if (compute_maxvar(graph) < 0)
6159 return isl_schedule_node_free(node);
6161 if (need_feautrier_step(ctx, graph))
6162 return compute_schedule_wcc_feautrier(node, graph);
6164 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6165 return compute_schedule_wcc_whole(node, graph);
6166 else
6167 return compute_schedule_wcc_clustering(node, graph);
6170 /* Compute a schedule for each group of nodes identified by node->scc
6171 * separately and then combine them in a sequence node (or as set node
6172 * if graph->weak is set) inserted at position "node" of the schedule tree.
6173 * Return the updated schedule node.
6175 * If "wcc" is set then each of the groups belongs to a single
6176 * weakly connected component in the dependence graph so that
6177 * there is no need for compute_sub_schedule to look for weakly
6178 * connected components.
6180 static __isl_give isl_schedule_node *compute_component_schedule(
6181 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6182 int wcc)
6184 int component;
6185 isl_ctx *ctx;
6186 isl_union_set_list *filters;
6188 if (!node)
6189 return NULL;
6190 ctx = isl_schedule_node_get_ctx(node);
6192 filters = extract_sccs(ctx, graph);
6193 if (graph->weak)
6194 node = isl_schedule_node_insert_set(node, filters);
6195 else
6196 node = isl_schedule_node_insert_sequence(node, filters);
6198 for (component = 0; component < graph->scc; ++component) {
6199 node = isl_schedule_node_child(node, component);
6200 node = isl_schedule_node_child(node, 0);
6201 node = compute_sub_schedule(node, ctx, graph,
6202 &node_scc_exactly,
6203 &edge_scc_exactly, component, wcc);
6204 node = isl_schedule_node_parent(node);
6205 node = isl_schedule_node_parent(node);
6208 return node;
6211 /* Compute a schedule for the given dependence graph and insert it at "node".
6212 * Return the updated schedule node.
6214 * We first check if the graph is connected (through validity and conditional
6215 * validity dependences) and, if not, compute a schedule
6216 * for each component separately.
6217 * If the schedule_serialize_sccs option is set, then we check for strongly
6218 * connected components instead and compute a separate schedule for
6219 * each such strongly connected component.
6221 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6222 struct isl_sched_graph *graph)
6224 isl_ctx *ctx;
6226 if (!node)
6227 return NULL;
6229 ctx = isl_schedule_node_get_ctx(node);
6230 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6231 if (detect_sccs(ctx, graph) < 0)
6232 return isl_schedule_node_free(node);
6233 } else {
6234 if (detect_wccs(ctx, graph) < 0)
6235 return isl_schedule_node_free(node);
6238 if (graph->scc > 1)
6239 return compute_component_schedule(node, graph, 1);
6241 return compute_schedule_wcc(node, graph);
6244 /* Compute a schedule on sc->domain that respects the given schedule
6245 * constraints.
6247 * In particular, the schedule respects all the validity dependences.
6248 * If the default isl scheduling algorithm is used, it tries to minimize
6249 * the dependence distances over the proximity dependences.
6250 * If Feautrier's scheduling algorithm is used, the proximity dependence
6251 * distances are only minimized during the extension to a full-dimensional
6252 * schedule.
6254 * If there are any condition and conditional validity dependences,
6255 * then the conditional validity dependences may be violated inside
6256 * a tilable band, provided they have no adjacent non-local
6257 * condition dependences.
6259 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6260 __isl_take isl_schedule_constraints *sc)
6262 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6263 struct isl_sched_graph graph = { 0 };
6264 isl_schedule *sched;
6265 isl_schedule_node *node;
6266 isl_union_set *domain;
6268 sc = isl_schedule_constraints_align_params(sc);
6270 domain = isl_schedule_constraints_get_domain(sc);
6271 if (isl_union_set_n_set(domain) == 0) {
6272 isl_schedule_constraints_free(sc);
6273 return isl_schedule_from_domain(domain);
6276 if (graph_init(&graph, sc) < 0)
6277 domain = isl_union_set_free(domain);
6279 node = isl_schedule_node_from_domain(domain);
6280 node = isl_schedule_node_child(node, 0);
6281 if (graph.n > 0)
6282 node = compute_schedule(node, &graph);
6283 sched = isl_schedule_node_get_schedule(node);
6284 isl_schedule_node_free(node);
6286 graph_free(ctx, &graph);
6287 isl_schedule_constraints_free(sc);
6289 return sched;
6292 /* Compute a schedule for the given union of domains that respects
6293 * all the validity dependences and minimizes
6294 * the dependence distances over the proximity dependences.
6296 * This function is kept for backward compatibility.
6298 __isl_give isl_schedule *isl_union_set_compute_schedule(
6299 __isl_take isl_union_set *domain,
6300 __isl_take isl_union_map *validity,
6301 __isl_take isl_union_map *proximity)
6303 isl_schedule_constraints *sc;
6305 sc = isl_schedule_constraints_on_domain(domain);
6306 sc = isl_schedule_constraints_set_validity(sc, validity);
6307 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6309 return isl_schedule_constraints_compute_schedule(sc);