mark isl_set_dim_is_unique as deprecated
[isl.git] / isl_scheduler.c
blob709e1ab8b7b10e7e739e870525d428a21f8b005e
1 /*
2 * Copyright 2011 INRIA Saclay
3 * Copyright 2012-2014 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
6 * Use of this software is governed by the MIT license
8 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
9 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
10 * 91893 Orsay, France
11 * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
14 #include <isl_ctx_private.h>
15 #include <isl_map_private.h>
16 #include <isl_space_private.h>
17 #include <isl_aff_private.h>
18 #include <isl/hash.h>
19 #include <isl/constraint.h>
20 #include <isl/schedule.h>
21 #include <isl_schedule_constraints.h>
22 #include <isl/schedule_node.h>
23 #include <isl_mat_private.h>
24 #include <isl_vec_private.h>
25 #include <isl/set.h>
26 #include <isl/union_set.h>
27 #include <isl_seq.h>
28 #include <isl_tab.h>
29 #include <isl_dim_map.h>
30 #include <isl/map_to_basic_set.h>
31 #include <isl_sort.h>
32 #include <isl_options_private.h>
33 #include <isl_tarjan.h>
34 #include <isl_morph.h>
35 #include <isl/ilp.h>
36 #include <isl_val_private.h>
39 * The scheduling algorithm implemented in this file was inspired by
40 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
41 * Parallelization and Locality Optimization in the Polyhedral Model".
45 /* Internal information about a node that is used during the construction
46 * of a schedule.
47 * space represents the space in which the domain lives
48 * sched is a matrix representation of the schedule being constructed
49 * for this node; if compressed is set, then this schedule is
50 * defined over the compressed domain space
51 * sched_map is an isl_map representation of the same (partial) schedule
52 * sched_map may be NULL; if compressed is set, then this map
53 * is defined over the uncompressed domain space
54 * rank is the number of linearly independent rows in the linear part
55 * of sched
56 * the columns of cmap represent a change of basis for the schedule
57 * coefficients; the first rank columns span the linear part of
58 * the schedule rows
59 * cinv is the inverse of cmap.
60 * ctrans is the transpose of cmap.
61 * start is the first variable in the LP problem in the sequences that
62 * represents the schedule coefficients of this node
63 * nvar is the dimension of the domain
64 * nparam is the number of parameters or 0 if we are not constructing
65 * a parametric schedule
67 * If compressed is set, then hull represents the constraints
68 * that were used to derive the compression, while compress and
69 * decompress map the original space to the compressed space and
70 * vice versa.
72 * scc is the index of SCC (or WCC) this node belongs to
74 * "cluster" is only used inside extract_clusters and identifies
75 * the cluster of SCCs that the node belongs to.
77 * coincident contains a boolean for each of the rows of the schedule,
78 * indicating whether the corresponding scheduling dimension satisfies
79 * the coincidence constraints in the sense that the corresponding
80 * dependence distances are zero.
82 * If the schedule_treat_coalescing option is set, then
83 * "sizes" contains the sizes of the (compressed) instance set
84 * in each direction. If there is no fixed size in a given direction,
85 * then the corresponding size value is set to infinity.
86 * If the schedule_treat_coalescing option or the schedule_max_coefficient
87 * option is set, then "max" contains the maximal values for
88 * schedule coefficients of the (compressed) variables. If no bound
89 * needs to be imposed on a particular variable, then the corresponding
90 * value is negative.
92 struct isl_sched_node {
93 isl_space *space;
94 int compressed;
95 isl_set *hull;
96 isl_multi_aff *compress;
97 isl_multi_aff *decompress;
98 isl_mat *sched;
99 isl_map *sched_map;
100 int rank;
101 isl_mat *cmap;
102 isl_mat *cinv;
103 isl_mat *ctrans;
104 int start;
105 int nvar;
106 int nparam;
108 int scc;
109 int cluster;
111 int *coincident;
113 isl_multi_val *sizes;
114 isl_vec *max;
117 static int node_has_space(const void *entry, const void *val)
119 struct isl_sched_node *node = (struct isl_sched_node *)entry;
120 isl_space *dim = (isl_space *)val;
122 return isl_space_is_equal(node->space, dim);
125 static int node_scc_exactly(struct isl_sched_node *node, int scc)
127 return node->scc == scc;
130 static int node_scc_at_most(struct isl_sched_node *node, int scc)
132 return node->scc <= scc;
135 static int node_scc_at_least(struct isl_sched_node *node, int scc)
137 return node->scc >= scc;
140 /* An edge in the dependence graph. An edge may be used to
141 * ensure validity of the generated schedule, to minimize the dependence
142 * distance or both
144 * map is the dependence relation, with i -> j in the map if j depends on i
145 * tagged_condition and tagged_validity contain the union of all tagged
146 * condition or conditional validity dependence relations that
147 * specialize the dependence relation "map"; that is,
148 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
149 * or "tagged_validity", then i -> j is an element of "map".
150 * If these fields are NULL, then they represent the empty relation.
151 * src is the source node
152 * dst is the sink node
154 * types is a bit vector containing the types of this edge.
155 * validity is set if the edge is used to ensure correctness
156 * coincidence is used to enforce zero dependence distances
157 * proximity is set if the edge is used to minimize dependence distances
158 * condition is set if the edge represents a condition
159 * for a conditional validity schedule constraint
160 * local can only be set for condition edges and indicates that
161 * the dependence distance over the edge should be zero
162 * conditional_validity is set if the edge is used to conditionally
163 * ensure correctness
165 * For validity edges, start and end mark the sequence of inequality
166 * constraints in the LP problem that encode the validity constraint
167 * corresponding to this edge.
169 * During clustering, an edge may be marked "no_merge" if it should
170 * not be used to merge clusters.
171 * The weight is also only used during clustering and it is
172 * an indication of how many schedule dimensions on either side
173 * of the schedule constraints can be aligned.
174 * If the weight is negative, then this means that this edge was postponed
175 * by has_bounded_distances or any_no_merge. The original weight can
176 * be retrieved by adding 1 + graph->max_weight, with "graph"
177 * the graph containing this edge.
179 struct isl_sched_edge {
180 isl_map *map;
181 isl_union_map *tagged_condition;
182 isl_union_map *tagged_validity;
184 struct isl_sched_node *src;
185 struct isl_sched_node *dst;
187 unsigned types;
189 int start;
190 int end;
192 int no_merge;
193 int weight;
196 /* Is "edge" marked as being of type "type"?
198 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
200 return ISL_FL_ISSET(edge->types, 1 << type);
203 /* Mark "edge" as being of type "type".
205 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
207 ISL_FL_SET(edge->types, 1 << type);
210 /* No longer mark "edge" as being of type "type"?
212 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
214 ISL_FL_CLR(edge->types, 1 << type);
217 /* Is "edge" marked as a validity edge?
219 static int is_validity(struct isl_sched_edge *edge)
221 return is_type(edge, isl_edge_validity);
224 /* Mark "edge" as a validity edge.
226 static void set_validity(struct isl_sched_edge *edge)
228 set_type(edge, isl_edge_validity);
231 /* Is "edge" marked as a proximity edge?
233 static int is_proximity(struct isl_sched_edge *edge)
235 return is_type(edge, isl_edge_proximity);
238 /* Is "edge" marked as a local edge?
240 static int is_local(struct isl_sched_edge *edge)
242 return is_type(edge, isl_edge_local);
245 /* Mark "edge" as a local edge.
247 static void set_local(struct isl_sched_edge *edge)
249 set_type(edge, isl_edge_local);
252 /* No longer mark "edge" as a local edge.
254 static void clear_local(struct isl_sched_edge *edge)
256 clear_type(edge, isl_edge_local);
259 /* Is "edge" marked as a coincidence edge?
261 static int is_coincidence(struct isl_sched_edge *edge)
263 return is_type(edge, isl_edge_coincidence);
266 /* Is "edge" marked as a condition edge?
268 static int is_condition(struct isl_sched_edge *edge)
270 return is_type(edge, isl_edge_condition);
273 /* Is "edge" marked as a conditional validity edge?
275 static int is_conditional_validity(struct isl_sched_edge *edge)
277 return is_type(edge, isl_edge_conditional_validity);
280 /* Internal information about the dependence graph used during
281 * the construction of the schedule.
283 * intra_hmap is a cache, mapping dependence relations to their dual,
284 * for dependences from a node to itself
285 * inter_hmap is a cache, mapping dependence relations to their dual,
286 * for dependences between distinct nodes
287 * if compression is involved then the key for these maps
288 * is the original, uncompressed dependence relation, while
289 * the value is the dual of the compressed dependence relation.
291 * n is the number of nodes
292 * node is the list of nodes
293 * maxvar is the maximal number of variables over all nodes
294 * max_row is the allocated number of rows in the schedule
295 * n_row is the current (maximal) number of linearly independent
296 * rows in the node schedules
297 * n_total_row is the current number of rows in the node schedules
298 * band_start is the starting row in the node schedules of the current band
299 * root is set if this graph is the original dependence graph,
300 * without any splitting
302 * sorted contains a list of node indices sorted according to the
303 * SCC to which a node belongs
305 * n_edge is the number of edges
306 * edge is the list of edges
307 * max_edge contains the maximal number of edges of each type;
308 * in particular, it contains the number of edges in the inital graph.
309 * edge_table contains pointers into the edge array, hashed on the source
310 * and sink spaces; there is one such table for each type;
311 * a given edge may be referenced from more than one table
312 * if the corresponding relation appears in more than one of the
313 * sets of dependences; however, for each type there is only
314 * a single edge between a given pair of source and sink space
315 * in the entire graph
317 * node_table contains pointers into the node array, hashed on the space
319 * region contains a list of variable sequences that should be non-trivial
321 * lp contains the (I)LP problem used to obtain new schedule rows
323 * src_scc and dst_scc are the source and sink SCCs of an edge with
324 * conflicting constraints
326 * scc represents the number of components
327 * weak is set if the components are weakly connected
329 * max_weight is used during clustering and represents the maximal
330 * weight of the relevant proximity edges.
332 struct isl_sched_graph {
333 isl_map_to_basic_set *intra_hmap;
334 isl_map_to_basic_set *inter_hmap;
336 struct isl_sched_node *node;
337 int n;
338 int maxvar;
339 int max_row;
340 int n_row;
342 int *sorted;
344 int n_total_row;
345 int band_start;
347 int root;
349 struct isl_sched_edge *edge;
350 int n_edge;
351 int max_edge[isl_edge_last + 1];
352 struct isl_hash_table *edge_table[isl_edge_last + 1];
354 struct isl_hash_table *node_table;
355 struct isl_region *region;
357 isl_basic_set *lp;
359 int src_scc;
360 int dst_scc;
362 int scc;
363 int weak;
365 int max_weight;
368 /* Initialize node_table based on the list of nodes.
370 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
372 int i;
374 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
375 if (!graph->node_table)
376 return -1;
378 for (i = 0; i < graph->n; ++i) {
379 struct isl_hash_table_entry *entry;
380 uint32_t hash;
382 hash = isl_space_get_hash(graph->node[i].space);
383 entry = isl_hash_table_find(ctx, graph->node_table, hash,
384 &node_has_space,
385 graph->node[i].space, 1);
386 if (!entry)
387 return -1;
388 entry->data = &graph->node[i];
391 return 0;
394 /* Return a pointer to the node that lives within the given space,
395 * or NULL if there is no such node.
397 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
398 struct isl_sched_graph *graph, __isl_keep isl_space *dim)
400 struct isl_hash_table_entry *entry;
401 uint32_t hash;
403 hash = isl_space_get_hash(dim);
404 entry = isl_hash_table_find(ctx, graph->node_table, hash,
405 &node_has_space, dim, 0);
407 return entry ? entry->data : NULL;
410 static int edge_has_src_and_dst(const void *entry, const void *val)
412 const struct isl_sched_edge *edge = entry;
413 const struct isl_sched_edge *temp = val;
415 return edge->src == temp->src && edge->dst == temp->dst;
418 /* Add the given edge to graph->edge_table[type].
420 static isl_stat graph_edge_table_add(isl_ctx *ctx,
421 struct isl_sched_graph *graph, enum isl_edge_type type,
422 struct isl_sched_edge *edge)
424 struct isl_hash_table_entry *entry;
425 uint32_t hash;
427 hash = isl_hash_init();
428 hash = isl_hash_builtin(hash, edge->src);
429 hash = isl_hash_builtin(hash, edge->dst);
430 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
431 &edge_has_src_and_dst, edge, 1);
432 if (!entry)
433 return isl_stat_error;
434 entry->data = edge;
436 return isl_stat_ok;
439 /* Allocate the edge_tables based on the maximal number of edges of
440 * each type.
442 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
444 int i;
446 for (i = 0; i <= isl_edge_last; ++i) {
447 graph->edge_table[i] = isl_hash_table_alloc(ctx,
448 graph->max_edge[i]);
449 if (!graph->edge_table[i])
450 return -1;
453 return 0;
456 /* If graph->edge_table[type] contains an edge from the given source
457 * to the given destination, then return the hash table entry of this edge.
458 * Otherwise, return NULL.
460 static struct isl_hash_table_entry *graph_find_edge_entry(
461 struct isl_sched_graph *graph,
462 enum isl_edge_type type,
463 struct isl_sched_node *src, struct isl_sched_node *dst)
465 isl_ctx *ctx = isl_space_get_ctx(src->space);
466 uint32_t hash;
467 struct isl_sched_edge temp = { .src = src, .dst = dst };
469 hash = isl_hash_init();
470 hash = isl_hash_builtin(hash, temp.src);
471 hash = isl_hash_builtin(hash, temp.dst);
472 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
473 &edge_has_src_and_dst, &temp, 0);
477 /* If graph->edge_table[type] contains an edge from the given source
478 * to the given destination, then return this edge.
479 * Otherwise, return NULL.
481 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
482 enum isl_edge_type type,
483 struct isl_sched_node *src, struct isl_sched_node *dst)
485 struct isl_hash_table_entry *entry;
487 entry = graph_find_edge_entry(graph, type, src, dst);
488 if (!entry)
489 return NULL;
491 return entry->data;
494 /* Check whether the dependence graph has an edge of the given type
495 * between the given two nodes.
497 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
498 enum isl_edge_type type,
499 struct isl_sched_node *src, struct isl_sched_node *dst)
501 struct isl_sched_edge *edge;
502 isl_bool empty;
504 edge = graph_find_edge(graph, type, src, dst);
505 if (!edge)
506 return 0;
508 empty = isl_map_plain_is_empty(edge->map);
509 if (empty < 0)
510 return isl_bool_error;
512 return !empty;
515 /* Look for any edge with the same src, dst and map fields as "model".
517 * Return the matching edge if one can be found.
518 * Return "model" if no matching edge is found.
519 * Return NULL on error.
521 static struct isl_sched_edge *graph_find_matching_edge(
522 struct isl_sched_graph *graph, struct isl_sched_edge *model)
524 enum isl_edge_type i;
525 struct isl_sched_edge *edge;
527 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
528 int is_equal;
530 edge = graph_find_edge(graph, i, model->src, model->dst);
531 if (!edge)
532 continue;
533 is_equal = isl_map_plain_is_equal(model->map, edge->map);
534 if (is_equal < 0)
535 return NULL;
536 if (is_equal)
537 return edge;
540 return model;
543 /* Remove the given edge from all the edge_tables that refer to it.
545 static void graph_remove_edge(struct isl_sched_graph *graph,
546 struct isl_sched_edge *edge)
548 isl_ctx *ctx = isl_map_get_ctx(edge->map);
549 enum isl_edge_type i;
551 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
552 struct isl_hash_table_entry *entry;
554 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
555 if (!entry)
556 continue;
557 if (entry->data != edge)
558 continue;
559 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
563 /* Check whether the dependence graph has any edge
564 * between the given two nodes.
566 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
567 struct isl_sched_node *src, struct isl_sched_node *dst)
569 enum isl_edge_type i;
570 isl_bool r;
572 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
573 r = graph_has_edge(graph, i, src, dst);
574 if (r < 0 || r)
575 return r;
578 return r;
581 /* Check whether the dependence graph has a validity edge
582 * between the given two nodes.
584 * Conditional validity edges are essentially validity edges that
585 * can be ignored if the corresponding condition edges are iteration private.
586 * Here, we are only checking for the presence of validity
587 * edges, so we need to consider the conditional validity edges too.
588 * In particular, this function is used during the detection
589 * of strongly connected components and we cannot ignore
590 * conditional validity edges during this detection.
592 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
593 struct isl_sched_node *src, struct isl_sched_node *dst)
595 isl_bool r;
597 r = graph_has_edge(graph, isl_edge_validity, src, dst);
598 if (r < 0 || r)
599 return r;
601 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
604 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
605 int n_node, int n_edge)
607 int i;
609 graph->n = n_node;
610 graph->n_edge = n_edge;
611 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
612 graph->sorted = isl_calloc_array(ctx, int, graph->n);
613 graph->region = isl_alloc_array(ctx, struct isl_region, graph->n);
614 graph->edge = isl_calloc_array(ctx,
615 struct isl_sched_edge, graph->n_edge);
617 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
618 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
620 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
621 !graph->sorted)
622 return -1;
624 for(i = 0; i < graph->n; ++i)
625 graph->sorted[i] = i;
627 return 0;
630 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
632 int i;
634 isl_map_to_basic_set_free(graph->intra_hmap);
635 isl_map_to_basic_set_free(graph->inter_hmap);
637 if (graph->node)
638 for (i = 0; i < graph->n; ++i) {
639 isl_space_free(graph->node[i].space);
640 isl_set_free(graph->node[i].hull);
641 isl_multi_aff_free(graph->node[i].compress);
642 isl_multi_aff_free(graph->node[i].decompress);
643 isl_mat_free(graph->node[i].sched);
644 isl_map_free(graph->node[i].sched_map);
645 isl_mat_free(graph->node[i].cmap);
646 isl_mat_free(graph->node[i].cinv);
647 isl_mat_free(graph->node[i].ctrans);
648 if (graph->root)
649 free(graph->node[i].coincident);
650 isl_multi_val_free(graph->node[i].sizes);
651 isl_vec_free(graph->node[i].max);
653 free(graph->node);
654 free(graph->sorted);
655 if (graph->edge)
656 for (i = 0; i < graph->n_edge; ++i) {
657 isl_map_free(graph->edge[i].map);
658 isl_union_map_free(graph->edge[i].tagged_condition);
659 isl_union_map_free(graph->edge[i].tagged_validity);
661 free(graph->edge);
662 free(graph->region);
663 for (i = 0; i <= isl_edge_last; ++i)
664 isl_hash_table_free(ctx, graph->edge_table[i]);
665 isl_hash_table_free(ctx, graph->node_table);
666 isl_basic_set_free(graph->lp);
669 /* For each "set" on which this function is called, increment
670 * graph->n by one and update graph->maxvar.
672 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
674 struct isl_sched_graph *graph = user;
675 int nvar = isl_set_dim(set, isl_dim_set);
677 graph->n++;
678 if (nvar > graph->maxvar)
679 graph->maxvar = nvar;
681 isl_set_free(set);
683 return isl_stat_ok;
686 /* Compute the number of rows that should be allocated for the schedule.
687 * In particular, we need one row for each variable or one row
688 * for each basic map in the dependences.
689 * Note that it is practically impossible to exhaust both
690 * the number of dependences and the number of variables.
692 static isl_stat compute_max_row(struct isl_sched_graph *graph,
693 __isl_keep isl_schedule_constraints *sc)
695 int n_edge;
696 isl_stat r;
697 isl_union_set *domain;
699 graph->n = 0;
700 graph->maxvar = 0;
701 domain = isl_schedule_constraints_get_domain(sc);
702 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
703 isl_union_set_free(domain);
704 if (r < 0)
705 return isl_stat_error;
706 n_edge = isl_schedule_constraints_n_basic_map(sc);
707 if (n_edge < 0)
708 return isl_stat_error;
709 graph->max_row = n_edge + graph->maxvar;
711 return isl_stat_ok;
714 /* Does "bset" have any defining equalities for its set variables?
716 static int has_any_defining_equality(__isl_keep isl_basic_set *bset)
718 int i, n;
720 if (!bset)
721 return -1;
723 n = isl_basic_set_dim(bset, isl_dim_set);
724 for (i = 0; i < n; ++i) {
725 int has;
727 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
728 NULL);
729 if (has < 0 || has)
730 return has;
733 return 0;
736 /* Set the entries of node->max to the value of the schedule_max_coefficient
737 * option, if set.
739 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
741 int max;
743 max = isl_options_get_schedule_max_coefficient(ctx);
744 if (max == -1)
745 return isl_stat_ok;
747 node->max = isl_vec_alloc(ctx, node->nvar);
748 node->max = isl_vec_set_si(node->max, max);
749 if (!node->max)
750 return isl_stat_error;
752 return isl_stat_ok;
755 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
756 * option (if set) and half of the minimum of the sizes in the other
757 * dimensions. If the minimum of the sizes is one, half of the size
758 * is zero and this value is reset to one.
759 * If the global minimum is unbounded (i.e., if both
760 * the schedule_max_coefficient is not set and the sizes in the other
761 * dimensions are unbounded), then store a negative value.
762 * If the schedule coefficient is close to the size of the instance set
763 * in another dimension, then the schedule may represent a loop
764 * coalescing transformation (especially if the coefficient
765 * in that other dimension is one). Forcing the coefficient to be
766 * smaller than or equal to half the minimal size should avoid this
767 * situation.
769 static isl_stat compute_max_coefficient(isl_ctx *ctx,
770 struct isl_sched_node *node)
772 int max;
773 int i, j;
774 isl_vec *v;
776 max = isl_options_get_schedule_max_coefficient(ctx);
777 v = isl_vec_alloc(ctx, node->nvar);
778 if (!v)
779 return isl_stat_error;
781 for (i = 0; i < node->nvar; ++i) {
782 isl_int_set_si(v->el[i], max);
783 isl_int_mul_si(v->el[i], v->el[i], 2);
786 for (i = 0; i < node->nvar; ++i) {
787 isl_val *size;
789 size = isl_multi_val_get_val(node->sizes, i);
790 if (!size)
791 goto error;
792 if (!isl_val_is_int(size)) {
793 isl_val_free(size);
794 continue;
796 for (j = 0; j < node->nvar; ++j) {
797 if (j == i)
798 continue;
799 if (isl_int_is_neg(v->el[j]) ||
800 isl_int_gt(v->el[j], size->n))
801 isl_int_set(v->el[j], size->n);
803 isl_val_free(size);
806 for (i = 0; i < node->nvar; ++i) {
807 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
808 if (isl_int_is_zero(v->el[i]))
809 isl_int_set_si(v->el[i], 1);
812 node->max = v;
813 return isl_stat_ok;
814 error:
815 isl_vec_free(v);
816 return isl_stat_error;
819 /* Compute and return the size of "set" in dimension "dim".
820 * The size is taken to be the difference in values for that variable
821 * for fixed values of the other variables.
822 * In particular, the variable is first isolated from the other variables
823 * in the range of a map
825 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
827 * and then duplicated
829 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
831 * The shared variables are then projected out and the maximal value
832 * of i_dim' - i_dim is computed.
834 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
836 isl_map *map;
837 isl_local_space *ls;
838 isl_aff *obj;
839 isl_val *v;
841 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
842 map = isl_map_project_out(map, isl_dim_in, dim, 1);
843 map = isl_map_range_product(map, isl_map_copy(map));
844 map = isl_set_unwrap(isl_map_range(map));
845 set = isl_map_deltas(map);
846 ls = isl_local_space_from_space(isl_set_get_space(set));
847 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
848 v = isl_set_max_val(set, obj);
849 isl_aff_free(obj);
850 isl_set_free(set);
852 return v;
855 /* Compute the size of the instance set "set" of "node", after compression,
856 * as well as bounds on the corresponding coefficients, if needed.
858 * The sizes are needed when the schedule_treat_coalescing option is set.
859 * The bounds are needed when the schedule_treat_coalescing option or
860 * the schedule_max_coefficient option is set.
862 * If the schedule_treat_coalescing option is not set, then at most
863 * the bounds need to be set and this is done in set_max_coefficient.
864 * Otherwise, compress the domain if needed, compute the size
865 * in each direction and store the results in node->size.
866 * Finally, set the bounds on the coefficients based on the sizes
867 * and the schedule_max_coefficient option in compute_max_coefficient.
869 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
870 __isl_take isl_set *set)
872 int j, n;
873 isl_multi_val *mv;
875 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
876 isl_set_free(set);
877 return set_max_coefficient(ctx, node);
880 if (node->compressed)
881 set = isl_set_preimage_multi_aff(set,
882 isl_multi_aff_copy(node->decompress));
883 mv = isl_multi_val_zero(isl_set_get_space(set));
884 n = isl_set_dim(set, isl_dim_set);
885 for (j = 0; j < n; ++j) {
886 isl_val *v;
888 v = compute_size(isl_set_copy(set), j);
889 mv = isl_multi_val_set_val(mv, j, v);
891 node->sizes = mv;
892 isl_set_free(set);
893 if (!node->sizes)
894 return isl_stat_error;
895 return compute_max_coefficient(ctx, node);
898 /* Add a new node to the graph representing the given instance set.
899 * "nvar" is the (possibly compressed) number of variables and
900 * may be smaller than then number of set variables in "set"
901 * if "compressed" is set.
902 * If "compressed" is set, then "hull" represents the constraints
903 * that were used to derive the compression, while "compress" and
904 * "decompress" map the original space to the compressed space and
905 * vice versa.
906 * If "compressed" is not set, then "hull", "compress" and "decompress"
907 * should be NULL.
909 * Compute the size of the instance set and bounds on the coefficients,
910 * if needed.
912 static isl_stat add_node(struct isl_sched_graph *graph,
913 __isl_take isl_set *set, int nvar, int compressed,
914 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
915 __isl_take isl_multi_aff *decompress)
917 int nparam;
918 isl_ctx *ctx;
919 isl_mat *sched;
920 isl_space *space;
921 int *coincident;
922 struct isl_sched_node *node;
924 if (!set)
925 return isl_stat_error;
927 ctx = isl_set_get_ctx(set);
928 nparam = isl_set_dim(set, isl_dim_param);
929 if (!ctx->opt->schedule_parametric)
930 nparam = 0;
931 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
932 node = &graph->node[graph->n];
933 graph->n++;
934 space = isl_set_get_space(set);
935 node->space = space;
936 node->nvar = nvar;
937 node->nparam = nparam;
938 node->sched = sched;
939 node->sched_map = NULL;
940 coincident = isl_calloc_array(ctx, int, graph->max_row);
941 node->coincident = coincident;
942 node->compressed = compressed;
943 node->hull = hull;
944 node->compress = compress;
945 node->decompress = decompress;
946 if (compute_sizes_and_max(ctx, node, set) < 0)
947 return isl_stat_error;
949 if (!space || !sched || (graph->max_row && !coincident))
950 return isl_stat_error;
951 if (compressed && (!hull || !compress || !decompress))
952 return isl_stat_error;
954 return isl_stat_ok;
957 /* Add a new node to the graph representing the given set.
959 * If any of the set variables is defined by an equality, then
960 * we perform variable compression such that we can perform
961 * the scheduling on the compressed domain.
963 static isl_stat extract_node(__isl_take isl_set *set, void *user)
965 int nvar;
966 int has_equality;
967 isl_basic_set *hull;
968 isl_set *hull_set;
969 isl_morph *morph;
970 isl_multi_aff *compress, *decompress;
971 struct isl_sched_graph *graph = user;
973 hull = isl_set_affine_hull(isl_set_copy(set));
974 hull = isl_basic_set_remove_divs(hull);
975 nvar = isl_set_dim(set, isl_dim_set);
976 has_equality = has_any_defining_equality(hull);
978 if (has_equality < 0)
979 goto error;
980 if (!has_equality) {
981 isl_basic_set_free(hull);
982 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
985 morph = isl_basic_set_variable_compression(hull, isl_dim_set);
986 nvar = isl_morph_ran_dim(morph, isl_dim_set);
987 compress = isl_morph_get_var_multi_aff(morph);
988 morph = isl_morph_inverse(morph);
989 decompress = isl_morph_get_var_multi_aff(morph);
990 isl_morph_free(morph);
992 hull_set = isl_set_from_basic_set(hull);
993 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
994 error:
995 isl_basic_set_free(hull);
996 isl_set_free(set);
997 return isl_stat_error;
1000 struct isl_extract_edge_data {
1001 enum isl_edge_type type;
1002 struct isl_sched_graph *graph;
1005 /* Merge edge2 into edge1, freeing the contents of edge2.
1006 * Return 0 on success and -1 on failure.
1008 * edge1 and edge2 are assumed to have the same value for the map field.
1010 static int merge_edge(struct isl_sched_edge *edge1,
1011 struct isl_sched_edge *edge2)
1013 edge1->types |= edge2->types;
1014 isl_map_free(edge2->map);
1016 if (is_condition(edge2)) {
1017 if (!edge1->tagged_condition)
1018 edge1->tagged_condition = edge2->tagged_condition;
1019 else
1020 edge1->tagged_condition =
1021 isl_union_map_union(edge1->tagged_condition,
1022 edge2->tagged_condition);
1025 if (is_conditional_validity(edge2)) {
1026 if (!edge1->tagged_validity)
1027 edge1->tagged_validity = edge2->tagged_validity;
1028 else
1029 edge1->tagged_validity =
1030 isl_union_map_union(edge1->tagged_validity,
1031 edge2->tagged_validity);
1034 if (is_condition(edge2) && !edge1->tagged_condition)
1035 return -1;
1036 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1037 return -1;
1039 return 0;
1042 /* Insert dummy tags in domain and range of "map".
1044 * In particular, if "map" is of the form
1046 * A -> B
1048 * then return
1050 * [A -> dummy_tag] -> [B -> dummy_tag]
1052 * where the dummy_tags are identical and equal to any dummy tags
1053 * introduced by any other call to this function.
1055 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1057 static char dummy;
1058 isl_ctx *ctx;
1059 isl_id *id;
1060 isl_space *space;
1061 isl_set *domain, *range;
1063 ctx = isl_map_get_ctx(map);
1065 id = isl_id_alloc(ctx, NULL, &dummy);
1066 space = isl_space_params(isl_map_get_space(map));
1067 space = isl_space_set_from_params(space);
1068 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1069 space = isl_space_map_from_set(space);
1071 domain = isl_map_wrap(map);
1072 range = isl_map_wrap(isl_map_universe(space));
1073 map = isl_map_from_domain_and_range(domain, range);
1074 map = isl_map_zip(map);
1076 return map;
1079 /* Given that at least one of "src" or "dst" is compressed, return
1080 * a map between the spaces of these nodes restricted to the affine
1081 * hull that was used in the compression.
1083 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1084 struct isl_sched_node *dst)
1086 isl_set *dom, *ran;
1088 if (src->compressed)
1089 dom = isl_set_copy(src->hull);
1090 else
1091 dom = isl_set_universe(isl_space_copy(src->space));
1092 if (dst->compressed)
1093 ran = isl_set_copy(dst->hull);
1094 else
1095 ran = isl_set_universe(isl_space_copy(dst->space));
1097 return isl_map_from_domain_and_range(dom, ran);
1100 /* Intersect the domains of the nested relations in domain and range
1101 * of "tagged" with "map".
1103 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1104 __isl_keep isl_map *map)
1106 isl_set *set;
1108 tagged = isl_map_zip(tagged);
1109 set = isl_map_wrap(isl_map_copy(map));
1110 tagged = isl_map_intersect_domain(tagged, set);
1111 tagged = isl_map_zip(tagged);
1112 return tagged;
1115 /* Return a pointer to the node that lives in the domain space of "map"
1116 * or NULL if there is no such node.
1118 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1119 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1121 struct isl_sched_node *node;
1122 isl_space *space;
1124 space = isl_space_domain(isl_map_get_space(map));
1125 node = graph_find_node(ctx, graph, space);
1126 isl_space_free(space);
1128 return node;
1131 /* Return a pointer to the node that lives in the range space of "map"
1132 * or NULL if there is no such node.
1134 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1135 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1137 struct isl_sched_node *node;
1138 isl_space *space;
1140 space = isl_space_range(isl_map_get_space(map));
1141 node = graph_find_node(ctx, graph, space);
1142 isl_space_free(space);
1144 return node;
1147 /* Add a new edge to the graph based on the given map
1148 * and add it to data->graph->edge_table[data->type].
1149 * If a dependence relation of a given type happens to be identical
1150 * to one of the dependence relations of a type that was added before,
1151 * then we don't create a new edge, but instead mark the original edge
1152 * as also representing a dependence of the current type.
1154 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1155 * may be specified as "tagged" dependence relations. That is, "map"
1156 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1157 * the dependence on iterations and a and b are tags.
1158 * edge->map is set to the relation containing the elements i -> j,
1159 * while edge->tagged_condition and edge->tagged_validity contain
1160 * the union of all the "map" relations
1161 * for which extract_edge is called that result in the same edge->map.
1163 * If the source or the destination node is compressed, then
1164 * intersect both "map" and "tagged" with the constraints that
1165 * were used to construct the compression.
1166 * This ensures that there are no schedule constraints defined
1167 * outside of these domains, while the scheduler no longer has
1168 * any control over those outside parts.
1170 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1172 isl_ctx *ctx = isl_map_get_ctx(map);
1173 struct isl_extract_edge_data *data = user;
1174 struct isl_sched_graph *graph = data->graph;
1175 struct isl_sched_node *src, *dst;
1176 struct isl_sched_edge *edge;
1177 isl_map *tagged = NULL;
1179 if (data->type == isl_edge_condition ||
1180 data->type == isl_edge_conditional_validity) {
1181 if (isl_map_can_zip(map)) {
1182 tagged = isl_map_copy(map);
1183 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1184 } else {
1185 tagged = insert_dummy_tags(isl_map_copy(map));
1189 src = find_domain_node(ctx, graph, map);
1190 dst = find_range_node(ctx, graph, map);
1192 if (!src || !dst) {
1193 isl_map_free(map);
1194 isl_map_free(tagged);
1195 return isl_stat_ok;
1198 if (src->compressed || dst->compressed) {
1199 isl_map *hull;
1200 hull = extract_hull(src, dst);
1201 if (tagged)
1202 tagged = map_intersect_domains(tagged, hull);
1203 map = isl_map_intersect(map, hull);
1206 graph->edge[graph->n_edge].src = src;
1207 graph->edge[graph->n_edge].dst = dst;
1208 graph->edge[graph->n_edge].map = map;
1209 graph->edge[graph->n_edge].types = 0;
1210 graph->edge[graph->n_edge].tagged_condition = NULL;
1211 graph->edge[graph->n_edge].tagged_validity = NULL;
1212 set_type(&graph->edge[graph->n_edge], data->type);
1213 if (data->type == isl_edge_condition)
1214 graph->edge[graph->n_edge].tagged_condition =
1215 isl_union_map_from_map(tagged);
1216 if (data->type == isl_edge_conditional_validity)
1217 graph->edge[graph->n_edge].tagged_validity =
1218 isl_union_map_from_map(tagged);
1220 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1221 if (!edge) {
1222 graph->n_edge++;
1223 return isl_stat_error;
1225 if (edge == &graph->edge[graph->n_edge])
1226 return graph_edge_table_add(ctx, graph, data->type,
1227 &graph->edge[graph->n_edge++]);
1229 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1230 return -1;
1232 return graph_edge_table_add(ctx, graph, data->type, edge);
1235 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1237 * The context is included in the domain before the nodes of
1238 * the graphs are extracted in order to be able to exploit
1239 * any possible additional equalities.
1240 * Note that this intersection is only performed locally here.
1242 static isl_stat graph_init(struct isl_sched_graph *graph,
1243 __isl_keep isl_schedule_constraints *sc)
1245 isl_ctx *ctx;
1246 isl_union_set *domain;
1247 isl_union_map *c;
1248 struct isl_extract_edge_data data;
1249 enum isl_edge_type i;
1250 isl_stat r;
1252 if (!sc)
1253 return isl_stat_error;
1255 ctx = isl_schedule_constraints_get_ctx(sc);
1257 domain = isl_schedule_constraints_get_domain(sc);
1258 graph->n = isl_union_set_n_set(domain);
1259 isl_union_set_free(domain);
1261 if (graph_alloc(ctx, graph, graph->n,
1262 isl_schedule_constraints_n_map(sc)) < 0)
1263 return isl_stat_error;
1265 if (compute_max_row(graph, sc) < 0)
1266 return isl_stat_error;
1267 graph->root = 1;
1268 graph->n = 0;
1269 domain = isl_schedule_constraints_get_domain(sc);
1270 domain = isl_union_set_intersect_params(domain,
1271 isl_schedule_constraints_get_context(sc));
1272 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1273 isl_union_set_free(domain);
1274 if (r < 0)
1275 return isl_stat_error;
1276 if (graph_init_table(ctx, graph) < 0)
1277 return isl_stat_error;
1278 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1279 c = isl_schedule_constraints_get(sc, i);
1280 graph->max_edge[i] = isl_union_map_n_map(c);
1281 isl_union_map_free(c);
1282 if (!c)
1283 return isl_stat_error;
1285 if (graph_init_edge_tables(ctx, graph) < 0)
1286 return isl_stat_error;
1287 graph->n_edge = 0;
1288 data.graph = graph;
1289 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1290 isl_stat r;
1292 data.type = i;
1293 c = isl_schedule_constraints_get(sc, i);
1294 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1295 isl_union_map_free(c);
1296 if (r < 0)
1297 return isl_stat_error;
1300 return isl_stat_ok;
1303 /* Check whether there is any dependence from node[j] to node[i]
1304 * or from node[i] to node[j].
1306 static isl_bool node_follows_weak(int i, int j, void *user)
1308 isl_bool f;
1309 struct isl_sched_graph *graph = user;
1311 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1312 if (f < 0 || f)
1313 return f;
1314 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1317 /* Check whether there is a (conditional) validity dependence from node[j]
1318 * to node[i], forcing node[i] to follow node[j].
1320 static isl_bool node_follows_strong(int i, int j, void *user)
1322 struct isl_sched_graph *graph = user;
1324 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1327 /* Use Tarjan's algorithm for computing the strongly connected components
1328 * in the dependence graph only considering those edges defined by "follows".
1330 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1331 isl_bool (*follows)(int i, int j, void *user))
1333 int i, n;
1334 struct isl_tarjan_graph *g = NULL;
1336 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1337 if (!g)
1338 return -1;
1340 graph->scc = 0;
1341 i = 0;
1342 n = graph->n;
1343 while (n) {
1344 while (g->order[i] != -1) {
1345 graph->node[g->order[i]].scc = graph->scc;
1346 --n;
1347 ++i;
1349 ++i;
1350 graph->scc++;
1353 isl_tarjan_graph_free(g);
1355 return 0;
1358 /* Apply Tarjan's algorithm to detect the strongly connected components
1359 * in the dependence graph.
1360 * Only consider the (conditional) validity dependences and clear "weak".
1362 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1364 graph->weak = 0;
1365 return detect_ccs(ctx, graph, &node_follows_strong);
1368 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1369 * in the dependence graph.
1370 * Consider all dependences and set "weak".
1372 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1374 graph->weak = 1;
1375 return detect_ccs(ctx, graph, &node_follows_weak);
1378 static int cmp_scc(const void *a, const void *b, void *data)
1380 struct isl_sched_graph *graph = data;
1381 const int *i1 = a;
1382 const int *i2 = b;
1384 return graph->node[*i1].scc - graph->node[*i2].scc;
1387 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1389 static int sort_sccs(struct isl_sched_graph *graph)
1391 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1394 /* Given a dependence relation R from "node" to itself,
1395 * construct the set of coefficients of valid constraints for elements
1396 * in that dependence relation.
1397 * In particular, the result contains tuples of coefficients
1398 * c_0, c_n, c_x such that
1400 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1402 * or, equivalently,
1404 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1406 * We choose here to compute the dual of delta R.
1407 * Alternatively, we could have computed the dual of R, resulting
1408 * in a set of tuples c_0, c_n, c_x, c_y, and then
1409 * plugged in (c_0, c_n, c_x, -c_x).
1411 * If "node" has been compressed, then the dependence relation
1412 * is also compressed before the set of coefficients is computed.
1414 static __isl_give isl_basic_set *intra_coefficients(
1415 struct isl_sched_graph *graph, struct isl_sched_node *node,
1416 __isl_take isl_map *map)
1418 isl_set *delta;
1419 isl_map *key;
1420 isl_basic_set *coef;
1421 isl_maybe_isl_basic_set m;
1423 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1424 if (m.valid < 0 || m.valid) {
1425 isl_map_free(map);
1426 return m.value;
1429 key = isl_map_copy(map);
1430 if (node->compressed) {
1431 map = isl_map_preimage_domain_multi_aff(map,
1432 isl_multi_aff_copy(node->decompress));
1433 map = isl_map_preimage_range_multi_aff(map,
1434 isl_multi_aff_copy(node->decompress));
1436 delta = isl_set_remove_divs(isl_map_deltas(map));
1437 coef = isl_set_coefficients(delta);
1438 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1439 isl_basic_set_copy(coef));
1441 return coef;
1444 /* Given a dependence relation R, construct the set of coefficients
1445 * of valid constraints for elements in that dependence relation.
1446 * In particular, the result contains tuples of coefficients
1447 * c_0, c_n, c_x, c_y such that
1449 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1451 * If the source or destination nodes of "edge" have been compressed,
1452 * then the dependence relation is also compressed before
1453 * the set of coefficients is computed.
1455 static __isl_give isl_basic_set *inter_coefficients(
1456 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1457 __isl_take isl_map *map)
1459 isl_set *set;
1460 isl_map *key;
1461 isl_basic_set *coef;
1462 isl_maybe_isl_basic_set m;
1464 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1465 if (m.valid < 0 || m.valid) {
1466 isl_map_free(map);
1467 return m.value;
1470 key = isl_map_copy(map);
1471 if (edge->src->compressed)
1472 map = isl_map_preimage_domain_multi_aff(map,
1473 isl_multi_aff_copy(edge->src->decompress));
1474 if (edge->dst->compressed)
1475 map = isl_map_preimage_range_multi_aff(map,
1476 isl_multi_aff_copy(edge->dst->decompress));
1477 set = isl_map_wrap(isl_map_remove_divs(map));
1478 coef = isl_set_coefficients(set);
1479 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1480 isl_basic_set_copy(coef));
1482 return coef;
1485 /* Return the position of the coefficients of the variables in
1486 * the coefficients constraints "coef".
1488 * The space of "coef" is of the form
1490 * { coefficients[[cst, params] -> S] }
1492 * Return the position of S.
1494 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1496 int offset;
1497 isl_space *space;
1499 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1500 offset = isl_space_dim(space, isl_dim_in);
1501 isl_space_free(space);
1503 return offset;
1506 /* Return the offset of the coefficients of the variables of "node"
1507 * within the (I)LP.
1509 * Within each node, the coefficients have the following order:
1510 * - c_i_0
1511 * - c_i_n (if parametric)
1512 * - positive and negative parts of c_i_x
1514 static int node_var_coef_offset(struct isl_sched_node *node)
1516 return node->start + 1 + node->nparam;
1519 /* Construct an isl_dim_map for mapping constraints on coefficients
1520 * for "node" to the corresponding positions in graph->lp.
1521 * "offset" is the offset of the coefficients for the variables
1522 * in the input constraints.
1523 * "s" is the sign of the mapping.
1525 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1526 * The mapping produced by this function essentially plugs in
1527 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1528 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1529 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1531 * The caller can extend the mapping to also map the other coefficients
1532 * (and therefore not plug in 0).
1534 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1535 struct isl_sched_graph *graph, struct isl_sched_node *node,
1536 int offset, int s)
1538 int pos;
1539 unsigned total;
1540 isl_dim_map *dim_map;
1542 total = isl_basic_set_total_dim(graph->lp);
1543 pos = node_var_coef_offset(node);
1544 dim_map = isl_dim_map_alloc(ctx, total);
1545 isl_dim_map_range(dim_map, pos, 2, offset, 1, node->nvar, -s);
1546 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, node->nvar, s);
1548 return dim_map;
1551 /* Construct an isl_dim_map for mapping constraints on coefficients
1552 * for "src" (node i) and "dst" (node j) to the corresponding positions
1553 * in graph->lp.
1554 * "offset" is the offset of the coefficients for the variables of "src"
1555 * in the input constraints.
1556 * "s" is the sign of the mapping.
1558 * The input constraints are given in terms of the coefficients
1559 * (c_0, c_n, c_x, c_y).
1560 * The mapping produced by this function essentially plugs in
1561 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1562 * c_j_x^+ - c_j_x^-, -(c_i_x^+ - c_i_x^-)) if s = 1 and
1563 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1564 * - (c_j_x^+ - c_j_x^-), c_i_x^+ - c_i_x^-) if s = -1.
1565 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1567 * The caller can further extend the mapping.
1569 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1570 struct isl_sched_graph *graph, struct isl_sched_node *src,
1571 struct isl_sched_node *dst, int offset, int s)
1573 int pos;
1574 unsigned total;
1575 isl_dim_map *dim_map;
1577 total = isl_basic_set_total_dim(graph->lp);
1578 dim_map = isl_dim_map_alloc(ctx, total);
1580 isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, s);
1581 isl_dim_map_range(dim_map, dst->start + 1, 1, 1, 1, dst->nparam, s);
1582 pos = node_var_coef_offset(dst);
1583 isl_dim_map_range(dim_map, pos, 2, offset + src->nvar, 1,
1584 dst->nvar, -s);
1585 isl_dim_map_range(dim_map, pos + 1, 2, offset + src->nvar, 1,
1586 dst->nvar, s);
1588 isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -s);
1589 isl_dim_map_range(dim_map, src->start + 1, 1, 1, 1, src->nparam, -s);
1590 pos = node_var_coef_offset(src);
1591 isl_dim_map_range(dim_map, pos, 2, offset, 1, src->nvar, s);
1592 isl_dim_map_range(dim_map, pos + 1, 2, offset, 1, src->nvar, -s);
1594 return dim_map;
1597 /* Add constraints to graph->lp that force validity for the given
1598 * dependence from a node i to itself.
1599 * That is, add constraints that enforce
1601 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1602 * = c_i_x (y - x) >= 0
1604 * for each (x,y) in R.
1605 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1606 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1607 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1608 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1610 * Actually, we do not construct constraints for the c_i_x themselves,
1611 * but for the coefficients of c_i_x written as a linear combination
1612 * of the columns in node->cmap.
1614 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1615 struct isl_sched_edge *edge)
1617 int offset;
1618 isl_map *map = isl_map_copy(edge->map);
1619 isl_ctx *ctx = isl_map_get_ctx(map);
1620 isl_dim_map *dim_map;
1621 isl_basic_set *coef;
1622 struct isl_sched_node *node = edge->src;
1624 coef = intra_coefficients(graph, node, map);
1626 offset = coef_var_offset(coef);
1628 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1629 offset, isl_mat_copy(node->cmap));
1630 if (!coef)
1631 return isl_stat_error;
1633 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1634 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1635 coef->n_eq, coef->n_ineq);
1636 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1637 coef, dim_map);
1639 return isl_stat_ok;
1642 /* Add constraints to graph->lp that force validity for the given
1643 * dependence from node i to node j.
1644 * That is, add constraints that enforce
1646 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1648 * for each (x,y) in R.
1649 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1650 * of valid constraints for R and then plug in
1651 * (c_j_0 - c_i_0, c_j_n - c_i_n, c_j_x^+ - c_j_x^- - (c_i_x^+ - c_i_x^-)),
1652 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1653 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1655 * Actually, we do not construct constraints for the c_*_x themselves,
1656 * but for the coefficients of c_*_x written as a linear combination
1657 * of the columns in node->cmap.
1659 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1660 struct isl_sched_edge *edge)
1662 int offset;
1663 isl_map *map = isl_map_copy(edge->map);
1664 isl_ctx *ctx = isl_map_get_ctx(map);
1665 isl_dim_map *dim_map;
1666 isl_basic_set *coef;
1667 struct isl_sched_node *src = edge->src;
1668 struct isl_sched_node *dst = edge->dst;
1670 coef = inter_coefficients(graph, edge, map);
1672 offset = coef_var_offset(coef);
1674 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1675 offset, isl_mat_copy(src->cmap));
1676 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1677 offset + src->nvar, isl_mat_copy(dst->cmap));
1678 if (!coef)
1679 return isl_stat_error;
1681 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1683 edge->start = graph->lp->n_ineq;
1684 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1685 coef->n_eq, coef->n_ineq);
1686 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1687 coef, dim_map);
1688 if (!graph->lp)
1689 return isl_stat_error;
1690 edge->end = graph->lp->n_ineq;
1692 return isl_stat_ok;
1695 /* Add constraints to graph->lp that bound the dependence distance for the given
1696 * dependence from a node i to itself.
1697 * If s = 1, we add the constraint
1699 * c_i_x (y - x) <= m_0 + m_n n
1701 * or
1703 * -c_i_x (y - x) + m_0 + m_n n >= 0
1705 * for each (x,y) in R.
1706 * If s = -1, we add the constraint
1708 * -c_i_x (y - x) <= m_0 + m_n n
1710 * or
1712 * c_i_x (y - x) + m_0 + m_n n >= 0
1714 * for each (x,y) in R.
1715 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1716 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1717 * with each coefficient (except m_0) represented as a pair of non-negative
1718 * coefficients.
1720 * Actually, we do not construct constraints for the c_i_x themselves,
1721 * but for the coefficients of c_i_x written as a linear combination
1722 * of the columns in node->cmap.
1725 * If "local" is set, then we add constraints
1727 * c_i_x (y - x) <= 0
1729 * or
1731 * -c_i_x (y - x) <= 0
1733 * instead, forcing the dependence distance to be (less than or) equal to 0.
1734 * That is, we plug in (0, 0, -s * c_i_x),
1735 * Note that dependences marked local are treated as validity constraints
1736 * by add_all_validity_constraints and therefore also have
1737 * their distances bounded by 0 from below.
1739 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1740 struct isl_sched_edge *edge, int s, int local)
1742 int offset;
1743 unsigned nparam;
1744 isl_map *map = isl_map_copy(edge->map);
1745 isl_ctx *ctx = isl_map_get_ctx(map);
1746 isl_dim_map *dim_map;
1747 isl_basic_set *coef;
1748 struct isl_sched_node *node = edge->src;
1750 coef = intra_coefficients(graph, node, map);
1752 offset = coef_var_offset(coef);
1754 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1755 offset, isl_mat_copy(node->cmap));
1756 if (!coef)
1757 return isl_stat_error;
1759 nparam = isl_space_dim(node->space, isl_dim_param);
1760 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1762 if (!local) {
1763 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1764 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1765 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1767 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1768 coef->n_eq, coef->n_ineq);
1769 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1770 coef, dim_map);
1772 return isl_stat_ok;
1775 /* Add constraints to graph->lp that bound the dependence distance for the given
1776 * dependence from node i to node j.
1777 * If s = 1, we add the constraint
1779 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1780 * <= m_0 + m_n n
1782 * or
1784 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1785 * m_0 + m_n n >= 0
1787 * for each (x,y) in R.
1788 * If s = -1, we add the constraint
1790 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1791 * <= m_0 + m_n n
1793 * or
1795 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1796 * m_0 + m_n n >= 0
1798 * for each (x,y) in R.
1799 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1800 * of valid constraints for R and then plug in
1801 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1802 * -s*c_j_x+s*c_i_x)
1803 * with each coefficient (except m_0, c_*_0 and c_*_n)
1804 * represented as a pair of non-negative coefficients.
1806 * Actually, we do not construct constraints for the c_*_x themselves,
1807 * but for the coefficients of c_*_x written as a linear combination
1808 * of the columns in node->cmap.
1811 * If "local" is set, then we add constraints
1813 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1815 * or
1817 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)) <= 0
1819 * instead, forcing the dependence distance to be (less than or) equal to 0.
1820 * That is, we plug in
1821 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, -s*c_j_x+s*c_i_x).
1822 * Note that dependences marked local are treated as validity constraints
1823 * by add_all_validity_constraints and therefore also have
1824 * their distances bounded by 0 from below.
1826 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1827 struct isl_sched_edge *edge, int s, int local)
1829 int offset;
1830 unsigned nparam;
1831 isl_map *map = isl_map_copy(edge->map);
1832 isl_ctx *ctx = isl_map_get_ctx(map);
1833 isl_dim_map *dim_map;
1834 isl_basic_set *coef;
1835 struct isl_sched_node *src = edge->src;
1836 struct isl_sched_node *dst = edge->dst;
1838 coef = inter_coefficients(graph, edge, map);
1840 offset = coef_var_offset(coef);
1842 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1843 offset, isl_mat_copy(src->cmap));
1844 coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1845 offset + src->nvar, isl_mat_copy(dst->cmap));
1846 if (!coef)
1847 return isl_stat_error;
1849 nparam = isl_space_dim(src->space, isl_dim_param);
1850 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1852 if (!local) {
1853 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1854 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1855 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1858 graph->lp = isl_basic_set_extend_constraints(graph->lp,
1859 coef->n_eq, coef->n_ineq);
1860 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1861 coef, dim_map);
1863 return isl_stat_ok;
1866 /* Add all validity constraints to graph->lp.
1868 * An edge that is forced to be local needs to have its dependence
1869 * distances equal to zero. We take care of bounding them by 0 from below
1870 * here. add_all_proximity_constraints takes care of bounding them by 0
1871 * from above.
1873 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1874 * Otherwise, we ignore them.
1876 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1877 int use_coincidence)
1879 int i;
1881 for (i = 0; i < graph->n_edge; ++i) {
1882 struct isl_sched_edge *edge= &graph->edge[i];
1883 int local;
1885 local = is_local(edge) ||
1886 (is_coincidence(edge) && use_coincidence);
1887 if (!is_validity(edge) && !local)
1888 continue;
1889 if (edge->src != edge->dst)
1890 continue;
1891 if (add_intra_validity_constraints(graph, edge) < 0)
1892 return -1;
1895 for (i = 0; i < graph->n_edge; ++i) {
1896 struct isl_sched_edge *edge = &graph->edge[i];
1897 int local;
1899 local = is_local(edge) ||
1900 (is_coincidence(edge) && use_coincidence);
1901 if (!is_validity(edge) && !local)
1902 continue;
1903 if (edge->src == edge->dst)
1904 continue;
1905 if (add_inter_validity_constraints(graph, edge) < 0)
1906 return -1;
1909 return 0;
1912 /* Add constraints to graph->lp that bound the dependence distance
1913 * for all dependence relations.
1914 * If a given proximity dependence is identical to a validity
1915 * dependence, then the dependence distance is already bounded
1916 * from below (by zero), so we only need to bound the distance
1917 * from above. (This includes the case of "local" dependences
1918 * which are treated as validity dependence by add_all_validity_constraints.)
1919 * Otherwise, we need to bound the distance both from above and from below.
1921 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1922 * Otherwise, we ignore them.
1924 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
1925 int use_coincidence)
1927 int i;
1929 for (i = 0; i < graph->n_edge; ++i) {
1930 struct isl_sched_edge *edge= &graph->edge[i];
1931 int local;
1933 local = is_local(edge) ||
1934 (is_coincidence(edge) && use_coincidence);
1935 if (!is_proximity(edge) && !local)
1936 continue;
1937 if (edge->src == edge->dst &&
1938 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
1939 return -1;
1940 if (edge->src != edge->dst &&
1941 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
1942 return -1;
1943 if (is_validity(edge) || local)
1944 continue;
1945 if (edge->src == edge->dst &&
1946 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
1947 return -1;
1948 if (edge->src != edge->dst &&
1949 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
1950 return -1;
1953 return 0;
1956 /* Compute a basis for the rows in the linear part of the schedule
1957 * and extend this basis to a full basis. The remaining rows
1958 * can then be used to force linear independence from the rows
1959 * in the schedule.
1961 * In particular, given the schedule rows S, we compute
1963 * S = H Q
1964 * S U = H
1966 * with H the Hermite normal form of S. That is, all but the
1967 * first rank columns of H are zero and so each row in S is
1968 * a linear combination of the first rank rows of Q.
1969 * The matrix Q is then transposed because we will write the
1970 * coefficients of the next schedule row as a column vector s
1971 * and express this s as a linear combination s = Q c of the
1972 * computed basis.
1973 * Similarly, the matrix U is transposed such that we can
1974 * compute the coefficients c = U s from a schedule row s.
1976 static int node_update_cmap(struct isl_sched_node *node)
1978 isl_mat *H, *U, *Q;
1979 int n_row = isl_mat_rows(node->sched);
1981 H = isl_mat_sub_alloc(node->sched, 0, n_row,
1982 1 + node->nparam, node->nvar);
1984 H = isl_mat_left_hermite(H, 0, &U, &Q);
1985 isl_mat_free(node->cmap);
1986 isl_mat_free(node->cinv);
1987 isl_mat_free(node->ctrans);
1988 node->ctrans = isl_mat_copy(Q);
1989 node->cmap = isl_mat_transpose(Q);
1990 node->cinv = isl_mat_transpose(U);
1991 node->rank = isl_mat_initial_non_zero_cols(H);
1992 isl_mat_free(H);
1994 if (!node->cmap || !node->cinv || !node->ctrans || node->rank < 0)
1995 return -1;
1996 return 0;
1999 /* Is "edge" marked as a validity or a conditional validity edge?
2001 static int is_any_validity(struct isl_sched_edge *edge)
2003 return is_validity(edge) || is_conditional_validity(edge);
2006 /* How many times should we count the constraints in "edge"?
2008 * If carry is set, then we are counting the number of
2009 * (validity or conditional validity) constraints that will be added
2010 * in setup_carry_lp and we count each edge exactly once.
2012 * Otherwise, we count as follows
2013 * validity -> 1 (>= 0)
2014 * validity+proximity -> 2 (>= 0 and upper bound)
2015 * proximity -> 2 (lower and upper bound)
2016 * local(+any) -> 2 (>= 0 and <= 0)
2018 * If an edge is only marked conditional_validity then it counts
2019 * as zero since it is only checked afterwards.
2021 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2022 * Otherwise, we ignore them.
2024 static int edge_multiplicity(struct isl_sched_edge *edge, int carry,
2025 int use_coincidence)
2027 if (carry)
2028 return 1;
2029 if (is_proximity(edge) || is_local(edge))
2030 return 2;
2031 if (use_coincidence && is_coincidence(edge))
2032 return 2;
2033 if (is_validity(edge))
2034 return 1;
2035 return 0;
2038 /* Count the number of equality and inequality constraints
2039 * that will be added for the given map.
2041 * "use_coincidence" is set if we should take into account coincidence edges.
2043 static int count_map_constraints(struct isl_sched_graph *graph,
2044 struct isl_sched_edge *edge, __isl_take isl_map *map,
2045 int *n_eq, int *n_ineq, int carry, int use_coincidence)
2047 isl_basic_set *coef;
2048 int f = edge_multiplicity(edge, carry, use_coincidence);
2050 if (f == 0) {
2051 isl_map_free(map);
2052 return 0;
2055 if (edge->src == edge->dst)
2056 coef = intra_coefficients(graph, edge->src, map);
2057 else
2058 coef = inter_coefficients(graph, edge, map);
2059 if (!coef)
2060 return -1;
2061 *n_eq += f * coef->n_eq;
2062 *n_ineq += f * coef->n_ineq;
2063 isl_basic_set_free(coef);
2065 return 0;
2068 /* Count the number of equality and inequality constraints
2069 * that will be added to the main lp problem.
2070 * We count as follows
2071 * validity -> 1 (>= 0)
2072 * validity+proximity -> 2 (>= 0 and upper bound)
2073 * proximity -> 2 (lower and upper bound)
2074 * local(+any) -> 2 (>= 0 and <= 0)
2076 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2077 * Otherwise, we ignore them.
2079 static int count_constraints(struct isl_sched_graph *graph,
2080 int *n_eq, int *n_ineq, int use_coincidence)
2082 int i;
2084 *n_eq = *n_ineq = 0;
2085 for (i = 0; i < graph->n_edge; ++i) {
2086 struct isl_sched_edge *edge= &graph->edge[i];
2087 isl_map *map = isl_map_copy(edge->map);
2089 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2090 0, use_coincidence) < 0)
2091 return -1;
2094 return 0;
2097 /* Count the number of constraints that will be added by
2098 * add_bound_constant_constraints to bound the values of the constant terms
2099 * and increment *n_eq and *n_ineq accordingly.
2101 * In practice, add_bound_constant_constraints only adds inequalities.
2103 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2104 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2106 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2107 return isl_stat_ok;
2109 *n_ineq += graph->n;
2111 return isl_stat_ok;
2114 /* Add constraints to bound the values of the constant terms in the schedule,
2115 * if requested by the user.
2117 * The maximal value of the constant terms is defined by the option
2118 * "schedule_max_constant_term".
2120 * Within each node, the coefficients have the following order:
2121 * - c_i_0
2122 * - c_i_n (if parametric)
2123 * - positive and negative parts of c_i_x
2125 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2126 struct isl_sched_graph *graph)
2128 int i, k;
2129 int max;
2130 int total;
2132 max = isl_options_get_schedule_max_constant_term(ctx);
2133 if (max == -1)
2134 return isl_stat_ok;
2136 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2138 for (i = 0; i < graph->n; ++i) {
2139 struct isl_sched_node *node = &graph->node[i];
2140 k = isl_basic_set_alloc_inequality(graph->lp);
2141 if (k < 0)
2142 return isl_stat_error;
2143 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2144 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2145 isl_int_set_si(graph->lp->ineq[k][0], max);
2148 return isl_stat_ok;
2151 /* Count the number of constraints that will be added by
2152 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2153 * accordingly.
2155 * In practice, add_bound_coefficient_constraints only adds inequalities.
2157 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2158 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2160 int i;
2162 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2163 !isl_options_get_schedule_treat_coalescing(ctx))
2164 return 0;
2166 for (i = 0; i < graph->n; ++i)
2167 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2169 return 0;
2172 /* Add constraints to graph->lp that bound the values of
2173 * the parameter schedule coefficients of "node" to "max" and
2174 * the variable schedule coefficients to the corresponding entry
2175 * in node->max.
2176 * In either case, a negative value means that no bound needs to be imposed.
2178 * For parameter coefficients, this amounts to adding a constraint
2180 * c_n <= max
2182 * i.e.,
2184 * -c_n + max >= 0
2186 * The variables coefficients are, however, not represented directly.
2187 * Instead, the variables coefficients c_x are written as a linear
2188 * combination c_x = cmap c_z of some other coefficients c_z,
2189 * which are in turn encoded as c_z = c_z^+ - c_z^-.
2190 * Let a_j be the elements of row i of node->cmap, then
2192 * -max_i <= c_x_i <= max_i
2194 * is encoded as
2196 * -max_i <= \sum_j a_j (c_z_j^+ - c_z_j^-) <= max_i
2198 * or
2200 * -\sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2201 * \sum_j a_j (c_z_j^+ - c_z_j^-) + max_i >= 0
2203 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2204 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2206 int i, j, k;
2207 int total;
2208 isl_vec *ineq;
2210 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2212 for (j = 0; j < node->nparam; ++j) {
2213 int dim;
2215 if (max < 0)
2216 continue;
2218 k = isl_basic_set_alloc_inequality(graph->lp);
2219 if (k < 0)
2220 return isl_stat_error;
2221 dim = 1 + node->start + 1 + j;
2222 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2223 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2224 isl_int_set_si(graph->lp->ineq[k][0], max);
2227 ineq = isl_vec_alloc(ctx, 1 + total);
2228 ineq = isl_vec_clr(ineq);
2229 if (!ineq)
2230 return isl_stat_error;
2231 for (i = 0; i < node->nvar; ++i) {
2232 int pos = 1 + node_var_coef_offset(node);
2234 if (isl_int_is_neg(node->max->el[i]))
2235 continue;
2237 for (j = 0; j < node->nvar; ++j) {
2238 isl_int_set(ineq->el[pos + 2 * j],
2239 node->cmap->row[i][j]);
2240 isl_int_neg(ineq->el[pos + 2 * j + 1],
2241 node->cmap->row[i][j]);
2243 isl_int_set(ineq->el[0], node->max->el[i]);
2245 k = isl_basic_set_alloc_inequality(graph->lp);
2246 if (k < 0)
2247 goto error;
2248 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2250 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2 * node->nvar);
2251 k = isl_basic_set_alloc_inequality(graph->lp);
2252 if (k < 0)
2253 goto error;
2254 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2256 isl_vec_free(ineq);
2258 return isl_stat_ok;
2259 error:
2260 isl_vec_free(ineq);
2261 return isl_stat_error;
2264 /* Add constraints that bound the values of the variable and parameter
2265 * coefficients of the schedule.
2267 * The maximal value of the coefficients is defined by the option
2268 * 'schedule_max_coefficient' and the entries in node->max.
2269 * These latter entries are only set if either the schedule_max_coefficient
2270 * option or the schedule_treat_coalescing option is set.
2272 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2273 struct isl_sched_graph *graph)
2275 int i;
2276 int max;
2278 max = isl_options_get_schedule_max_coefficient(ctx);
2280 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2281 return isl_stat_ok;
2283 for (i = 0; i < graph->n; ++i) {
2284 struct isl_sched_node *node = &graph->node[i];
2286 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2287 return isl_stat_error;
2290 return isl_stat_ok;
2293 /* Add a constraint to graph->lp that equates the value at position
2294 * "sum_pos" to the sum of the "n" values starting at "first".
2296 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2297 int sum_pos, int first, int n)
2299 int i, k;
2300 int total;
2302 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2304 k = isl_basic_set_alloc_equality(graph->lp);
2305 if (k < 0)
2306 return isl_stat_error;
2307 isl_seq_clr(graph->lp->eq[k], 1 + total);
2308 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2309 for (i = 0; i < n; ++i)
2310 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2312 return isl_stat_ok;
2315 /* Add a constraint to graph->lp that equates the value at position
2316 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2318 * Within each node, the coefficients have the following order:
2319 * - c_i_0
2320 * - c_i_n (if parametric)
2321 * - positive and negative parts of c_i_x
2323 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2324 int sum_pos)
2326 int i, j, k;
2327 int total;
2329 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2331 k = isl_basic_set_alloc_equality(graph->lp);
2332 if (k < 0)
2333 return isl_stat_error;
2334 isl_seq_clr(graph->lp->eq[k], 1 + total);
2335 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2336 for (i = 0; i < graph->n; ++i) {
2337 int pos = 1 + graph->node[i].start + 1;
2339 for (j = 0; j < graph->node[i].nparam; ++j)
2340 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2343 return isl_stat_ok;
2346 /* Add a constraint to graph->lp that equates the value at position
2347 * "sum_pos" to the sum of the variable coefficients of all nodes.
2349 * Within each node, the coefficients have the following order:
2350 * - c_i_0
2351 * - c_i_n (if parametric)
2352 * - positive and negative parts of c_i_x
2354 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2355 int sum_pos)
2357 int i, j, k;
2358 int total;
2360 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2362 k = isl_basic_set_alloc_equality(graph->lp);
2363 if (k < 0)
2364 return isl_stat_error;
2365 isl_seq_clr(graph->lp->eq[k], 1 + total);
2366 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2367 for (i = 0; i < graph->n; ++i) {
2368 struct isl_sched_node *node = &graph->node[i];
2369 int pos = 1 + node_var_coef_offset(node);
2371 for (j = 0; j < 2 * node->nvar; ++j)
2372 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2375 return isl_stat_ok;
2378 /* Construct an ILP problem for finding schedule coefficients
2379 * that result in non-negative, but small dependence distances
2380 * over all dependences.
2381 * In particular, the dependence distances over proximity edges
2382 * are bounded by m_0 + m_n n and we compute schedule coefficients
2383 * with small values (preferably zero) of m_n and m_0.
2385 * All variables of the ILP are non-negative. The actual coefficients
2386 * may be negative, so each coefficient is represented as the difference
2387 * of two non-negative variables. The negative part always appears
2388 * immediately before the positive part.
2389 * Other than that, the variables have the following order
2391 * - sum of positive and negative parts of m_n coefficients
2392 * - m_0
2393 * - sum of all c_n coefficients
2394 * (unconstrained when computing non-parametric schedules)
2395 * - sum of positive and negative parts of all c_x coefficients
2396 * - positive and negative parts of m_n coefficients
2397 * - for each node
2398 * - c_i_0
2399 * - c_i_n (if parametric)
2400 * - positive and negative parts of c_i_x
2402 * The c_i_x are not represented directly, but through the columns of
2403 * node->cmap. That is, the computed values are for variable t_i_x
2404 * such that c_i_x = Q t_i_x with Q equal to node->cmap.
2406 * The constraints are those from the edges plus two or three equalities
2407 * to express the sums.
2409 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2410 * Otherwise, we ignore them.
2412 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2413 int use_coincidence)
2415 int i;
2416 unsigned nparam;
2417 unsigned total;
2418 isl_space *space;
2419 int parametric;
2420 int param_pos;
2421 int n_eq, n_ineq;
2423 parametric = ctx->opt->schedule_parametric;
2424 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2425 param_pos = 4;
2426 total = param_pos + 2 * nparam;
2427 for (i = 0; i < graph->n; ++i) {
2428 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2429 if (node_update_cmap(node) < 0)
2430 return isl_stat_error;
2431 node->start = total;
2432 total += 1 + node->nparam + 2 * node->nvar;
2435 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2436 return isl_stat_error;
2437 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2438 return isl_stat_error;
2439 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2440 return isl_stat_error;
2442 space = isl_space_set_alloc(ctx, 0, total);
2443 isl_basic_set_free(graph->lp);
2444 n_eq += 2 + parametric;
2446 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2448 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2449 return isl_stat_error;
2450 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2451 return isl_stat_error;
2452 if (add_var_sum_constraint(graph, 3) < 0)
2453 return isl_stat_error;
2454 if (add_bound_constant_constraints(ctx, graph) < 0)
2455 return isl_stat_error;
2456 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2457 return isl_stat_error;
2458 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2459 return isl_stat_error;
2460 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2461 return isl_stat_error;
2463 return isl_stat_ok;
2466 /* Analyze the conflicting constraint found by
2467 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2468 * constraint of one of the edges between distinct nodes, living, moreover
2469 * in distinct SCCs, then record the source and sink SCC as this may
2470 * be a good place to cut between SCCs.
2472 static int check_conflict(int con, void *user)
2474 int i;
2475 struct isl_sched_graph *graph = user;
2477 if (graph->src_scc >= 0)
2478 return 0;
2480 con -= graph->lp->n_eq;
2482 if (con >= graph->lp->n_ineq)
2483 return 0;
2485 for (i = 0; i < graph->n_edge; ++i) {
2486 if (!is_validity(&graph->edge[i]))
2487 continue;
2488 if (graph->edge[i].src == graph->edge[i].dst)
2489 continue;
2490 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2491 continue;
2492 if (graph->edge[i].start > con)
2493 continue;
2494 if (graph->edge[i].end <= con)
2495 continue;
2496 graph->src_scc = graph->edge[i].src->scc;
2497 graph->dst_scc = graph->edge[i].dst->scc;
2500 return 0;
2503 /* Check whether the next schedule row of the given node needs to be
2504 * non-trivial. Lower-dimensional domains may have some trivial rows,
2505 * but as soon as the number of remaining required non-trivial rows
2506 * is as large as the number or remaining rows to be computed,
2507 * all remaining rows need to be non-trivial.
2509 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2511 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2514 /* Solve the ILP problem constructed in setup_lp.
2515 * For each node such that all the remaining rows of its schedule
2516 * need to be non-trivial, we construct a non-triviality region.
2517 * This region imposes that the next row is independent of previous rows.
2518 * In particular the coefficients c_i_x are represented by t_i_x
2519 * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
2520 * its first columns span the rows of the previously computed part
2521 * of the schedule. The non-triviality region enforces that at least
2522 * one of the remaining components of t_i_x is non-zero, i.e.,
2523 * that the new schedule row depends on at least one of the remaining
2524 * columns of Q.
2526 static __isl_give isl_vec *solve_lp(struct isl_sched_graph *graph)
2528 int i;
2529 isl_vec *sol;
2530 isl_basic_set *lp;
2532 for (i = 0; i < graph->n; ++i) {
2533 struct isl_sched_node *node = &graph->node[i];
2534 int skip = node->rank;
2535 graph->region[i].pos = node_var_coef_offset(node) + 2 * skip;
2536 if (needs_row(graph, node))
2537 graph->region[i].len = 2 * (node->nvar - skip);
2538 else
2539 graph->region[i].len = 0;
2541 lp = isl_basic_set_copy(graph->lp);
2542 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2543 graph->region, &check_conflict, graph);
2544 return sol;
2547 /* Extract the coefficients for the variables of "node" from "sol".
2549 * Within each node, the coefficients have the following order:
2550 * - c_i_0
2551 * - c_i_n (if parametric)
2552 * - positive and negative parts of c_i_x
2554 * The c_i_x^- appear before their c_i_x^+ counterpart.
2556 * Return c_i_x = c_i_x^+ - c_i_x^-
2558 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2559 __isl_keep isl_vec *sol)
2561 int i;
2562 int pos;
2563 isl_vec *csol;
2565 if (!sol)
2566 return NULL;
2567 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2568 if (!csol)
2569 return NULL;
2571 pos = 1 + node_var_coef_offset(node);
2572 for (i = 0; i < node->nvar; ++i)
2573 isl_int_sub(csol->el[i],
2574 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2576 return csol;
2579 /* Update the schedules of all nodes based on the given solution
2580 * of the LP problem.
2581 * The new row is added to the current band.
2582 * All possibly negative coefficients are encoded as a difference
2583 * of two non-negative variables, so we need to perform the subtraction
2584 * here. Moreover, if use_cmap is set, then the solution does
2585 * not refer to the actual coefficients c_i_x, but instead to variables
2586 * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
2587 * In this case, we then also need to perform this multiplication
2588 * to obtain the values of c_i_x.
2590 * If coincident is set, then the caller guarantees that the new
2591 * row satisfies the coincidence constraints.
2593 static int update_schedule(struct isl_sched_graph *graph,
2594 __isl_take isl_vec *sol, int use_cmap, int coincident)
2596 int i, j;
2597 isl_vec *csol = NULL;
2599 if (!sol)
2600 goto error;
2601 if (sol->size == 0)
2602 isl_die(sol->ctx, isl_error_internal,
2603 "no solution found", goto error);
2604 if (graph->n_total_row >= graph->max_row)
2605 isl_die(sol->ctx, isl_error_internal,
2606 "too many schedule rows", goto error);
2608 for (i = 0; i < graph->n; ++i) {
2609 struct isl_sched_node *node = &graph->node[i];
2610 int pos = node->start;
2611 int row = isl_mat_rows(node->sched);
2613 isl_vec_free(csol);
2614 csol = extract_var_coef(node, sol);
2615 if (!csol)
2616 goto error;
2618 isl_map_free(node->sched_map);
2619 node->sched_map = NULL;
2620 node->sched = isl_mat_add_rows(node->sched, 1);
2621 if (!node->sched)
2622 goto error;
2623 for (j = 0; j < 1 + node->nparam; ++j)
2624 node->sched = isl_mat_set_element(node->sched,
2625 row, j, sol->el[1 + pos + j]);
2626 if (use_cmap)
2627 csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
2628 csol);
2629 if (!csol)
2630 goto error;
2631 for (j = 0; j < node->nvar; ++j)
2632 node->sched = isl_mat_set_element(node->sched,
2633 row, 1 + node->nparam + j, csol->el[j]);
2634 node->coincident[graph->n_total_row] = coincident;
2636 isl_vec_free(sol);
2637 isl_vec_free(csol);
2639 graph->n_row++;
2640 graph->n_total_row++;
2642 return 0;
2643 error:
2644 isl_vec_free(sol);
2645 isl_vec_free(csol);
2646 return -1;
2649 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2650 * and return this isl_aff.
2652 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2653 struct isl_sched_node *node, int row)
2655 int j;
2656 isl_int v;
2657 isl_aff *aff;
2659 isl_int_init(v);
2661 aff = isl_aff_zero_on_domain(ls);
2662 isl_mat_get_element(node->sched, row, 0, &v);
2663 aff = isl_aff_set_constant(aff, v);
2664 for (j = 0; j < node->nparam; ++j) {
2665 isl_mat_get_element(node->sched, row, 1 + j, &v);
2666 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2668 for (j = 0; j < node->nvar; ++j) {
2669 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2670 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2673 isl_int_clear(v);
2675 return aff;
2678 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2679 * and return this multi_aff.
2681 * The result is defined over the uncompressed node domain.
2683 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2684 struct isl_sched_node *node, int first, int n)
2686 int i;
2687 isl_space *space;
2688 isl_local_space *ls;
2689 isl_aff *aff;
2690 isl_multi_aff *ma;
2691 int nrow;
2693 if (!node)
2694 return NULL;
2695 nrow = isl_mat_rows(node->sched);
2696 if (node->compressed)
2697 space = isl_multi_aff_get_domain_space(node->decompress);
2698 else
2699 space = isl_space_copy(node->space);
2700 ls = isl_local_space_from_space(isl_space_copy(space));
2701 space = isl_space_from_domain(space);
2702 space = isl_space_add_dims(space, isl_dim_out, n);
2703 ma = isl_multi_aff_zero(space);
2705 for (i = first; i < first + n; ++i) {
2706 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2707 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2710 isl_local_space_free(ls);
2712 if (node->compressed)
2713 ma = isl_multi_aff_pullback_multi_aff(ma,
2714 isl_multi_aff_copy(node->compress));
2716 return ma;
2719 /* Convert node->sched into a multi_aff and return this multi_aff.
2721 * The result is defined over the uncompressed node domain.
2723 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2724 struct isl_sched_node *node)
2726 int nrow;
2728 nrow = isl_mat_rows(node->sched);
2729 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2732 /* Convert node->sched into a map and return this map.
2734 * The result is cached in node->sched_map, which needs to be released
2735 * whenever node->sched is updated.
2736 * It is defined over the uncompressed node domain.
2738 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2740 if (!node->sched_map) {
2741 isl_multi_aff *ma;
2743 ma = node_extract_schedule_multi_aff(node);
2744 node->sched_map = isl_map_from_multi_aff(ma);
2747 return isl_map_copy(node->sched_map);
2750 /* Construct a map that can be used to update a dependence relation
2751 * based on the current schedule.
2752 * That is, construct a map expressing that source and sink
2753 * are executed within the same iteration of the current schedule.
2754 * This map can then be intersected with the dependence relation.
2755 * This is not the most efficient way, but this shouldn't be a critical
2756 * operation.
2758 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2759 struct isl_sched_node *dst)
2761 isl_map *src_sched, *dst_sched;
2763 src_sched = node_extract_schedule(src);
2764 dst_sched = node_extract_schedule(dst);
2765 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2768 /* Intersect the domains of the nested relations in domain and range
2769 * of "umap" with "map".
2771 static __isl_give isl_union_map *intersect_domains(
2772 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2774 isl_union_set *uset;
2776 umap = isl_union_map_zip(umap);
2777 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2778 umap = isl_union_map_intersect_domain(umap, uset);
2779 umap = isl_union_map_zip(umap);
2780 return umap;
2783 /* Update the dependence relation of the given edge based
2784 * on the current schedule.
2785 * If the dependence is carried completely by the current schedule, then
2786 * it is removed from the edge_tables. It is kept in the list of edges
2787 * as otherwise all edge_tables would have to be recomputed.
2789 static int update_edge(struct isl_sched_graph *graph,
2790 struct isl_sched_edge *edge)
2792 int empty;
2793 isl_map *id;
2795 id = specializer(edge->src, edge->dst);
2796 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2797 if (!edge->map)
2798 goto error;
2800 if (edge->tagged_condition) {
2801 edge->tagged_condition =
2802 intersect_domains(edge->tagged_condition, id);
2803 if (!edge->tagged_condition)
2804 goto error;
2806 if (edge->tagged_validity) {
2807 edge->tagged_validity =
2808 intersect_domains(edge->tagged_validity, id);
2809 if (!edge->tagged_validity)
2810 goto error;
2813 empty = isl_map_plain_is_empty(edge->map);
2814 if (empty < 0)
2815 goto error;
2816 if (empty)
2817 graph_remove_edge(graph, edge);
2819 isl_map_free(id);
2820 return 0;
2821 error:
2822 isl_map_free(id);
2823 return -1;
2826 /* Does the domain of "umap" intersect "uset"?
2828 static int domain_intersects(__isl_keep isl_union_map *umap,
2829 __isl_keep isl_union_set *uset)
2831 int empty;
2833 umap = isl_union_map_copy(umap);
2834 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2835 empty = isl_union_map_is_empty(umap);
2836 isl_union_map_free(umap);
2838 return empty < 0 ? -1 : !empty;
2841 /* Does the range of "umap" intersect "uset"?
2843 static int range_intersects(__isl_keep isl_union_map *umap,
2844 __isl_keep isl_union_set *uset)
2846 int empty;
2848 umap = isl_union_map_copy(umap);
2849 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2850 empty = isl_union_map_is_empty(umap);
2851 isl_union_map_free(umap);
2853 return empty < 0 ? -1 : !empty;
2856 /* Are the condition dependences of "edge" local with respect to
2857 * the current schedule?
2859 * That is, are domain and range of the condition dependences mapped
2860 * to the same point?
2862 * In other words, is the condition false?
2864 static int is_condition_false(struct isl_sched_edge *edge)
2866 isl_union_map *umap;
2867 isl_map *map, *sched, *test;
2868 int empty, local;
2870 empty = isl_union_map_is_empty(edge->tagged_condition);
2871 if (empty < 0 || empty)
2872 return empty;
2874 umap = isl_union_map_copy(edge->tagged_condition);
2875 umap = isl_union_map_zip(umap);
2876 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2877 map = isl_map_from_union_map(umap);
2879 sched = node_extract_schedule(edge->src);
2880 map = isl_map_apply_domain(map, sched);
2881 sched = node_extract_schedule(edge->dst);
2882 map = isl_map_apply_range(map, sched);
2884 test = isl_map_identity(isl_map_get_space(map));
2885 local = isl_map_is_subset(map, test);
2886 isl_map_free(map);
2887 isl_map_free(test);
2889 return local;
2892 /* For each conditional validity constraint that is adjacent
2893 * to a condition with domain in condition_source or range in condition_sink,
2894 * turn it into an unconditional validity constraint.
2896 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2897 __isl_take isl_union_set *condition_source,
2898 __isl_take isl_union_set *condition_sink)
2900 int i;
2902 condition_source = isl_union_set_coalesce(condition_source);
2903 condition_sink = isl_union_set_coalesce(condition_sink);
2905 for (i = 0; i < graph->n_edge; ++i) {
2906 int adjacent;
2907 isl_union_map *validity;
2909 if (!is_conditional_validity(&graph->edge[i]))
2910 continue;
2911 if (is_validity(&graph->edge[i]))
2912 continue;
2914 validity = graph->edge[i].tagged_validity;
2915 adjacent = domain_intersects(validity, condition_sink);
2916 if (adjacent >= 0 && !adjacent)
2917 adjacent = range_intersects(validity, condition_source);
2918 if (adjacent < 0)
2919 goto error;
2920 if (!adjacent)
2921 continue;
2923 set_validity(&graph->edge[i]);
2926 isl_union_set_free(condition_source);
2927 isl_union_set_free(condition_sink);
2928 return 0;
2929 error:
2930 isl_union_set_free(condition_source);
2931 isl_union_set_free(condition_sink);
2932 return -1;
2935 /* Update the dependence relations of all edges based on the current schedule
2936 * and enforce conditional validity constraints that are adjacent
2937 * to satisfied condition constraints.
2939 * First check if any of the condition constraints are satisfied
2940 * (i.e., not local to the outer schedule) and keep track of
2941 * their domain and range.
2942 * Then update all dependence relations (which removes the non-local
2943 * constraints).
2944 * Finally, if any condition constraints turned out to be satisfied,
2945 * then turn all adjacent conditional validity constraints into
2946 * unconditional validity constraints.
2948 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
2950 int i;
2951 int any = 0;
2952 isl_union_set *source, *sink;
2954 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
2955 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
2956 for (i = 0; i < graph->n_edge; ++i) {
2957 int local;
2958 isl_union_set *uset;
2959 isl_union_map *umap;
2961 if (!is_condition(&graph->edge[i]))
2962 continue;
2963 if (is_local(&graph->edge[i]))
2964 continue;
2965 local = is_condition_false(&graph->edge[i]);
2966 if (local < 0)
2967 goto error;
2968 if (local)
2969 continue;
2971 any = 1;
2973 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
2974 uset = isl_union_map_domain(umap);
2975 source = isl_union_set_union(source, uset);
2977 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
2978 uset = isl_union_map_range(umap);
2979 sink = isl_union_set_union(sink, uset);
2982 for (i = graph->n_edge - 1; i >= 0; --i) {
2983 if (update_edge(graph, &graph->edge[i]) < 0)
2984 goto error;
2987 if (any)
2988 return unconditionalize_adjacent_validity(graph, source, sink);
2990 isl_union_set_free(source);
2991 isl_union_set_free(sink);
2992 return 0;
2993 error:
2994 isl_union_set_free(source);
2995 isl_union_set_free(sink);
2996 return -1;
2999 static void next_band(struct isl_sched_graph *graph)
3001 graph->band_start = graph->n_total_row;
3004 /* Return the union of the universe domains of the nodes in "graph"
3005 * that satisfy "pred".
3007 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3008 struct isl_sched_graph *graph,
3009 int (*pred)(struct isl_sched_node *node, int data), int data)
3011 int i;
3012 isl_set *set;
3013 isl_union_set *dom;
3015 for (i = 0; i < graph->n; ++i)
3016 if (pred(&graph->node[i], data))
3017 break;
3019 if (i >= graph->n)
3020 isl_die(ctx, isl_error_internal,
3021 "empty component", return NULL);
3023 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3024 dom = isl_union_set_from_set(set);
3026 for (i = i + 1; i < graph->n; ++i) {
3027 if (!pred(&graph->node[i], data))
3028 continue;
3029 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3030 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3033 return dom;
3036 /* Return a list of unions of universe domains, where each element
3037 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3039 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3040 struct isl_sched_graph *graph)
3042 int i;
3043 isl_union_set_list *filters;
3045 filters = isl_union_set_list_alloc(ctx, graph->scc);
3046 for (i = 0; i < graph->scc; ++i) {
3047 isl_union_set *dom;
3049 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3050 filters = isl_union_set_list_add(filters, dom);
3053 return filters;
3056 /* Return a list of two unions of universe domains, one for the SCCs up
3057 * to and including graph->src_scc and another for the other SCCs.
3059 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3060 struct isl_sched_graph *graph)
3062 isl_union_set *dom;
3063 isl_union_set_list *filters;
3065 filters = isl_union_set_list_alloc(ctx, 2);
3066 dom = isl_sched_graph_domain(ctx, graph,
3067 &node_scc_at_most, graph->src_scc);
3068 filters = isl_union_set_list_add(filters, dom);
3069 dom = isl_sched_graph_domain(ctx, graph,
3070 &node_scc_at_least, graph->src_scc + 1);
3071 filters = isl_union_set_list_add(filters, dom);
3073 return filters;
3076 /* Copy nodes that satisfy node_pred from the src dependence graph
3077 * to the dst dependence graph.
3079 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3080 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3082 int i;
3084 dst->n = 0;
3085 for (i = 0; i < src->n; ++i) {
3086 int j;
3088 if (!node_pred(&src->node[i], data))
3089 continue;
3091 j = dst->n;
3092 dst->node[j].space = isl_space_copy(src->node[i].space);
3093 dst->node[j].compressed = src->node[i].compressed;
3094 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3095 dst->node[j].compress =
3096 isl_multi_aff_copy(src->node[i].compress);
3097 dst->node[j].decompress =
3098 isl_multi_aff_copy(src->node[i].decompress);
3099 dst->node[j].nvar = src->node[i].nvar;
3100 dst->node[j].nparam = src->node[i].nparam;
3101 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3102 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3103 dst->node[j].coincident = src->node[i].coincident;
3104 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3105 dst->node[j].max = isl_vec_copy(src->node[i].max);
3106 dst->n++;
3108 if (!dst->node[j].space || !dst->node[j].sched)
3109 return -1;
3110 if (dst->node[j].compressed &&
3111 (!dst->node[j].hull || !dst->node[j].compress ||
3112 !dst->node[j].decompress))
3113 return -1;
3116 return 0;
3119 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3120 * to the dst dependence graph.
3121 * If the source or destination node of the edge is not in the destination
3122 * graph, then it must be a backward proximity edge and it should simply
3123 * be ignored.
3125 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3126 struct isl_sched_graph *src,
3127 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3129 int i;
3130 enum isl_edge_type t;
3132 dst->n_edge = 0;
3133 for (i = 0; i < src->n_edge; ++i) {
3134 struct isl_sched_edge *edge = &src->edge[i];
3135 isl_map *map;
3136 isl_union_map *tagged_condition;
3137 isl_union_map *tagged_validity;
3138 struct isl_sched_node *dst_src, *dst_dst;
3140 if (!edge_pred(edge, data))
3141 continue;
3143 if (isl_map_plain_is_empty(edge->map))
3144 continue;
3146 dst_src = graph_find_node(ctx, dst, edge->src->space);
3147 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3148 if (!dst_src || !dst_dst) {
3149 if (is_validity(edge) || is_conditional_validity(edge))
3150 isl_die(ctx, isl_error_internal,
3151 "backward (conditional) validity edge",
3152 return -1);
3153 continue;
3156 map = isl_map_copy(edge->map);
3157 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3158 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3160 dst->edge[dst->n_edge].src = dst_src;
3161 dst->edge[dst->n_edge].dst = dst_dst;
3162 dst->edge[dst->n_edge].map = map;
3163 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3164 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3165 dst->edge[dst->n_edge].types = edge->types;
3166 dst->n_edge++;
3168 if (edge->tagged_condition && !tagged_condition)
3169 return -1;
3170 if (edge->tagged_validity && !tagged_validity)
3171 return -1;
3173 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3174 if (edge !=
3175 graph_find_edge(src, t, edge->src, edge->dst))
3176 continue;
3177 if (graph_edge_table_add(ctx, dst, t,
3178 &dst->edge[dst->n_edge - 1]) < 0)
3179 return -1;
3183 return 0;
3186 /* Compute the maximal number of variables over all nodes.
3187 * This is the maximal number of linearly independent schedule
3188 * rows that we need to compute.
3189 * Just in case we end up in a part of the dependence graph
3190 * with only lower-dimensional domains, we make sure we will
3191 * compute the required amount of extra linearly independent rows.
3193 static int compute_maxvar(struct isl_sched_graph *graph)
3195 int i;
3197 graph->maxvar = 0;
3198 for (i = 0; i < graph->n; ++i) {
3199 struct isl_sched_node *node = &graph->node[i];
3200 int nvar;
3202 if (node_update_cmap(node) < 0)
3203 return -1;
3204 nvar = node->nvar + graph->n_row - node->rank;
3205 if (nvar > graph->maxvar)
3206 graph->maxvar = nvar;
3209 return 0;
3212 /* Extract the subgraph of "graph" that consists of the node satisfying
3213 * "node_pred" and the edges satisfying "edge_pred" and store
3214 * the result in "sub".
3216 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3217 int (*node_pred)(struct isl_sched_node *node, int data),
3218 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3219 int data, struct isl_sched_graph *sub)
3221 int i, n = 0, n_edge = 0;
3222 int t;
3224 for (i = 0; i < graph->n; ++i)
3225 if (node_pred(&graph->node[i], data))
3226 ++n;
3227 for (i = 0; i < graph->n_edge; ++i)
3228 if (edge_pred(&graph->edge[i], data))
3229 ++n_edge;
3230 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3231 return -1;
3232 if (copy_nodes(sub, graph, node_pred, data) < 0)
3233 return -1;
3234 if (graph_init_table(ctx, sub) < 0)
3235 return -1;
3236 for (t = 0; t <= isl_edge_last; ++t)
3237 sub->max_edge[t] = graph->max_edge[t];
3238 if (graph_init_edge_tables(ctx, sub) < 0)
3239 return -1;
3240 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3241 return -1;
3242 sub->n_row = graph->n_row;
3243 sub->max_row = graph->max_row;
3244 sub->n_total_row = graph->n_total_row;
3245 sub->band_start = graph->band_start;
3247 return 0;
3250 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3251 struct isl_sched_graph *graph);
3252 static __isl_give isl_schedule_node *compute_schedule_wcc(
3253 isl_schedule_node *node, struct isl_sched_graph *graph);
3255 /* Compute a schedule for a subgraph of "graph". In particular, for
3256 * the graph composed of nodes that satisfy node_pred and edges that
3257 * that satisfy edge_pred.
3258 * If the subgraph is known to consist of a single component, then wcc should
3259 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3260 * Otherwise, we call compute_schedule, which will check whether the subgraph
3261 * is connected.
3263 * The schedule is inserted at "node" and the updated schedule node
3264 * is returned.
3266 static __isl_give isl_schedule_node *compute_sub_schedule(
3267 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3268 struct isl_sched_graph *graph,
3269 int (*node_pred)(struct isl_sched_node *node, int data),
3270 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3271 int data, int wcc)
3273 struct isl_sched_graph split = { 0 };
3275 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3276 &split) < 0)
3277 goto error;
3279 if (wcc)
3280 node = compute_schedule_wcc(node, &split);
3281 else
3282 node = compute_schedule(node, &split);
3284 graph_free(ctx, &split);
3285 return node;
3286 error:
3287 graph_free(ctx, &split);
3288 return isl_schedule_node_free(node);
3291 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3293 return edge->src->scc == scc && edge->dst->scc == scc;
3296 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3298 return edge->dst->scc <= scc;
3301 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3303 return edge->src->scc >= scc;
3306 /* Reset the current band by dropping all its schedule rows.
3308 static int reset_band(struct isl_sched_graph *graph)
3310 int i;
3311 int drop;
3313 drop = graph->n_total_row - graph->band_start;
3314 graph->n_total_row -= drop;
3315 graph->n_row -= drop;
3317 for (i = 0; i < graph->n; ++i) {
3318 struct isl_sched_node *node = &graph->node[i];
3320 isl_map_free(node->sched_map);
3321 node->sched_map = NULL;
3323 node->sched = isl_mat_drop_rows(node->sched,
3324 graph->band_start, drop);
3326 if (!node->sched)
3327 return -1;
3330 return 0;
3333 /* Split the current graph into two parts and compute a schedule for each
3334 * part individually. In particular, one part consists of all SCCs up
3335 * to and including graph->src_scc, while the other part contains the other
3336 * SCCs. The split is enforced by a sequence node inserted at position "node"
3337 * in the schedule tree. Return the updated schedule node.
3338 * If either of these two parts consists of a sequence, then it is spliced
3339 * into the sequence containing the two parts.
3341 * The current band is reset. It would be possible to reuse
3342 * the previously computed rows as the first rows in the next
3343 * band, but recomputing them may result in better rows as we are looking
3344 * at a smaller part of the dependence graph.
3346 static __isl_give isl_schedule_node *compute_split_schedule(
3347 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3349 int is_seq;
3350 isl_ctx *ctx;
3351 isl_union_set_list *filters;
3353 if (!node)
3354 return NULL;
3356 if (reset_band(graph) < 0)
3357 return isl_schedule_node_free(node);
3359 next_band(graph);
3361 ctx = isl_schedule_node_get_ctx(node);
3362 filters = extract_split(ctx, graph);
3363 node = isl_schedule_node_insert_sequence(node, filters);
3364 node = isl_schedule_node_child(node, 1);
3365 node = isl_schedule_node_child(node, 0);
3367 node = compute_sub_schedule(node, ctx, graph,
3368 &node_scc_at_least, &edge_src_scc_at_least,
3369 graph->src_scc + 1, 0);
3370 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3371 node = isl_schedule_node_parent(node);
3372 node = isl_schedule_node_parent(node);
3373 if (is_seq)
3374 node = isl_schedule_node_sequence_splice_child(node, 1);
3375 node = isl_schedule_node_child(node, 0);
3376 node = isl_schedule_node_child(node, 0);
3377 node = compute_sub_schedule(node, ctx, graph,
3378 &node_scc_at_most, &edge_dst_scc_at_most,
3379 graph->src_scc, 0);
3380 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3381 node = isl_schedule_node_parent(node);
3382 node = isl_schedule_node_parent(node);
3383 if (is_seq)
3384 node = isl_schedule_node_sequence_splice_child(node, 0);
3386 return node;
3389 /* Insert a band node at position "node" in the schedule tree corresponding
3390 * to the current band in "graph". Mark the band node permutable
3391 * if "permutable" is set.
3392 * The partial schedules and the coincidence property are extracted
3393 * from the graph nodes.
3394 * Return the updated schedule node.
3396 static __isl_give isl_schedule_node *insert_current_band(
3397 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3398 int permutable)
3400 int i;
3401 int start, end, n;
3402 isl_multi_aff *ma;
3403 isl_multi_pw_aff *mpa;
3404 isl_multi_union_pw_aff *mupa;
3406 if (!node)
3407 return NULL;
3409 if (graph->n < 1)
3410 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3411 "graph should have at least one node",
3412 return isl_schedule_node_free(node));
3414 start = graph->band_start;
3415 end = graph->n_total_row;
3416 n = end - start;
3418 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3419 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3420 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3422 for (i = 1; i < graph->n; ++i) {
3423 isl_multi_union_pw_aff *mupa_i;
3425 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3426 start, n);
3427 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3428 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3429 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3431 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3433 for (i = 0; i < n; ++i)
3434 node = isl_schedule_node_band_member_set_coincident(node, i,
3435 graph->node[0].coincident[start + i]);
3436 node = isl_schedule_node_band_set_permutable(node, permutable);
3438 return node;
3441 /* Update the dependence relations based on the current schedule,
3442 * add the current band to "node" and then continue with the computation
3443 * of the next band.
3444 * Return the updated schedule node.
3446 static __isl_give isl_schedule_node *compute_next_band(
3447 __isl_take isl_schedule_node *node,
3448 struct isl_sched_graph *graph, int permutable)
3450 isl_ctx *ctx;
3452 if (!node)
3453 return NULL;
3455 ctx = isl_schedule_node_get_ctx(node);
3456 if (update_edges(ctx, graph) < 0)
3457 return isl_schedule_node_free(node);
3458 node = insert_current_band(node, graph, permutable);
3459 next_band(graph);
3461 node = isl_schedule_node_child(node, 0);
3462 node = compute_schedule(node, graph);
3463 node = isl_schedule_node_parent(node);
3465 return node;
3468 /* Add constraints to graph->lp that force the dependence "map" (which
3469 * is part of the dependence relation of "edge")
3470 * to be respected and attempt to carry it, where the edge is one from
3471 * a node j to itself. "pos" is the sequence number of the given map.
3472 * That is, add constraints that enforce
3474 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3475 * = c_j_x (y - x) >= e_i
3477 * for each (x,y) in R.
3478 * We obtain general constraints on coefficients (c_0, c_n, c_x)
3479 * of valid constraints for (y - x) and then plug in (-e_i, 0, c_j_x),
3480 * with each coefficient in c_j_x represented as a pair of non-negative
3481 * coefficients.
3483 static int add_intra_constraints(struct isl_sched_graph *graph,
3484 struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
3486 int offset;
3487 isl_ctx *ctx = isl_map_get_ctx(map);
3488 isl_dim_map *dim_map;
3489 isl_basic_set *coef;
3490 struct isl_sched_node *node = edge->src;
3492 coef = intra_coefficients(graph, node, map);
3493 if (!coef)
3494 return -1;
3496 offset = coef_var_offset(coef);
3497 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3498 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3499 graph->lp = isl_basic_set_extend_constraints(graph->lp,
3500 coef->n_eq, coef->n_ineq);
3501 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
3502 coef, dim_map);
3504 return 0;
3507 /* Add constraints to graph->lp that force the dependence "map" (which
3508 * is part of the dependence relation of "edge")
3509 * to be respected and attempt to carry it, where the edge is one from
3510 * node j to node k. "pos" is the sequence number of the given map.
3511 * That is, add constraints that enforce
3513 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3515 * for each (x,y) in R.
3516 * We obtain general constraints on coefficients (c_0, c_n, c_x)
3517 * of valid constraints for R and then plug in
3518 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, c_k_x - c_j_x)
3519 * with each coefficient (except e_i, c_*_0 and c_*_n)
3520 * represented as a pair of non-negative coefficients.
3522 static int add_inter_constraints(struct isl_sched_graph *graph,
3523 struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
3525 int offset;
3526 isl_ctx *ctx = isl_map_get_ctx(map);
3527 isl_dim_map *dim_map;
3528 isl_basic_set *coef;
3529 struct isl_sched_node *src = edge->src;
3530 struct isl_sched_node *dst = edge->dst;
3532 coef = inter_coefficients(graph, edge, map);
3533 if (!coef)
3534 return -1;
3536 offset = coef_var_offset(coef);
3537 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3538 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3539 graph->lp = isl_basic_set_extend_constraints(graph->lp,
3540 coef->n_eq, coef->n_ineq);
3541 graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
3542 coef, dim_map);
3544 return 0;
3547 /* Add constraints to graph->lp that force all (conditional) validity
3548 * dependences to be respected and attempt to carry them.
3550 static int add_all_constraints(struct isl_sched_graph *graph)
3552 int i, j;
3553 int pos;
3555 pos = 0;
3556 for (i = 0; i < graph->n_edge; ++i) {
3557 struct isl_sched_edge *edge= &graph->edge[i];
3559 if (!is_any_validity(edge))
3560 continue;
3562 for (j = 0; j < edge->map->n; ++j) {
3563 isl_basic_map *bmap;
3564 isl_map *map;
3566 bmap = isl_basic_map_copy(edge->map->p[j]);
3567 map = isl_map_from_basic_map(bmap);
3569 if (edge->src == edge->dst &&
3570 add_intra_constraints(graph, edge, map, pos) < 0)
3571 return -1;
3572 if (edge->src != edge->dst &&
3573 add_inter_constraints(graph, edge, map, pos) < 0)
3574 return -1;
3575 ++pos;
3579 return 0;
3582 /* Count the number of equality and inequality constraints
3583 * that will be added to the carry_lp problem.
3584 * We count each edge exactly once.
3586 static int count_all_constraints(struct isl_sched_graph *graph,
3587 int *n_eq, int *n_ineq)
3589 int i, j;
3591 *n_eq = *n_ineq = 0;
3592 for (i = 0; i < graph->n_edge; ++i) {
3593 struct isl_sched_edge *edge= &graph->edge[i];
3595 if (!is_any_validity(edge))
3596 continue;
3598 for (j = 0; j < edge->map->n; ++j) {
3599 isl_basic_map *bmap;
3600 isl_map *map;
3602 bmap = isl_basic_map_copy(edge->map->p[j]);
3603 map = isl_map_from_basic_map(bmap);
3605 if (count_map_constraints(graph, edge, map,
3606 n_eq, n_ineq, 1, 0) < 0)
3607 return -1;
3611 return 0;
3614 /* Construct an LP problem for finding schedule coefficients
3615 * such that the schedule carries as many dependences as possible.
3616 * In particular, for each dependence i, we bound the dependence distance
3617 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3618 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3619 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3620 * Note that if the dependence relation is a union of basic maps,
3621 * then we have to consider each basic map individually as it may only
3622 * be possible to carry the dependences expressed by some of those
3623 * basic maps and not all of them.
3624 * Below, we consider each of those basic maps as a separate "edge".
3626 * All variables of the LP are non-negative. The actual coefficients
3627 * may be negative, so each coefficient is represented as the difference
3628 * of two non-negative variables. The negative part always appears
3629 * immediately before the positive part.
3630 * Other than that, the variables have the following order
3632 * - sum of (1 - e_i) over all edges
3633 * - sum of all c_n coefficients
3634 * (unconstrained when computing non-parametric schedules)
3635 * - sum of positive and negative parts of all c_x coefficients
3636 * - for each edge
3637 * - e_i
3638 * - for each node
3639 * - c_i_0
3640 * - c_i_n (if parametric)
3641 * - positive and negative parts of c_i_x
3643 * The constraints are those from the (validity) edges plus three equalities
3644 * to express the sums and n_edge inequalities to express e_i <= 1.
3646 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
3648 int i;
3649 int k;
3650 isl_space *dim;
3651 unsigned total;
3652 int n_eq, n_ineq;
3653 int n_edge;
3655 n_edge = 0;
3656 for (i = 0; i < graph->n_edge; ++i)
3657 n_edge += graph->edge[i].map->n;
3659 total = 3 + n_edge;
3660 for (i = 0; i < graph->n; ++i) {
3661 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3662 node->start = total;
3663 total += 1 + node->nparam + 2 * node->nvar;
3666 if (count_all_constraints(graph, &n_eq, &n_ineq) < 0)
3667 return isl_stat_error;
3669 dim = isl_space_set_alloc(ctx, 0, total);
3670 isl_basic_set_free(graph->lp);
3671 n_eq += 3;
3672 n_ineq += n_edge;
3673 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3674 graph->lp = isl_basic_set_set_rational(graph->lp);
3676 k = isl_basic_set_alloc_equality(graph->lp);
3677 if (k < 0)
3678 return isl_stat_error;
3679 isl_seq_clr(graph->lp->eq[k], 1 + total);
3680 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3681 isl_int_set_si(graph->lp->eq[k][1], 1);
3682 for (i = 0; i < n_edge; ++i)
3683 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3685 if (add_param_sum_constraint(graph, 1) < 0)
3686 return isl_stat_error;
3687 if (add_var_sum_constraint(graph, 2) < 0)
3688 return isl_stat_error;
3690 for (i = 0; i < n_edge; ++i) {
3691 k = isl_basic_set_alloc_inequality(graph->lp);
3692 if (k < 0)
3693 return isl_stat_error;
3694 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3695 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3696 isl_int_set_si(graph->lp->ineq[k][0], 1);
3699 if (add_all_constraints(graph) < 0)
3700 return isl_stat_error;
3702 return isl_stat_ok;
3705 static __isl_give isl_schedule_node *compute_component_schedule(
3706 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3707 int wcc);
3709 /* Comparison function for sorting the statements based on
3710 * the corresponding value in "r".
3712 static int smaller_value(const void *a, const void *b, void *data)
3714 isl_vec *r = data;
3715 const int *i1 = a;
3716 const int *i2 = b;
3718 return isl_int_cmp(r->el[*i1], r->el[*i2]);
3721 /* If the schedule_split_scaled option is set and if the linear
3722 * parts of the scheduling rows for all nodes in the graphs have
3723 * a non-trivial common divisor, then split off the remainder of the
3724 * constant term modulo this common divisor from the linear part.
3725 * Otherwise, insert a band node directly and continue with
3726 * the construction of the schedule.
3728 * If a non-trivial common divisor is found, then
3729 * the linear part is reduced and the remainder is enforced
3730 * by a sequence node with the children placed in the order
3731 * of this remainder.
3732 * In particular, we assign an scc index based on the remainder and
3733 * then rely on compute_component_schedule to insert the sequence and
3734 * to continue the schedule construction on each part.
3736 static __isl_give isl_schedule_node *split_scaled(
3737 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3739 int i;
3740 int row;
3741 int scc;
3742 isl_ctx *ctx;
3743 isl_int gcd, gcd_i;
3744 isl_vec *r;
3745 int *order;
3747 if (!node)
3748 return NULL;
3750 ctx = isl_schedule_node_get_ctx(node);
3751 if (!ctx->opt->schedule_split_scaled)
3752 return compute_next_band(node, graph, 0);
3753 if (graph->n <= 1)
3754 return compute_next_band(node, graph, 0);
3756 isl_int_init(gcd);
3757 isl_int_init(gcd_i);
3759 isl_int_set_si(gcd, 0);
3761 row = isl_mat_rows(graph->node[0].sched) - 1;
3763 for (i = 0; i < graph->n; ++i) {
3764 struct isl_sched_node *node = &graph->node[i];
3765 int cols = isl_mat_cols(node->sched);
3767 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3768 isl_int_gcd(gcd, gcd, gcd_i);
3771 isl_int_clear(gcd_i);
3773 if (isl_int_cmp_si(gcd, 1) <= 0) {
3774 isl_int_clear(gcd);
3775 return compute_next_band(node, graph, 0);
3778 r = isl_vec_alloc(ctx, graph->n);
3779 order = isl_calloc_array(ctx, int, graph->n);
3780 if (!r || !order)
3781 goto error;
3783 for (i = 0; i < graph->n; ++i) {
3784 struct isl_sched_node *node = &graph->node[i];
3786 order[i] = i;
3787 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
3788 isl_int_fdiv_q(node->sched->row[row][0],
3789 node->sched->row[row][0], gcd);
3790 isl_int_mul(node->sched->row[row][0],
3791 node->sched->row[row][0], gcd);
3792 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3793 if (!node->sched)
3794 goto error;
3797 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
3798 goto error;
3800 scc = 0;
3801 for (i = 0; i < graph->n; ++i) {
3802 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
3803 ++scc;
3804 graph->node[order[i]].scc = scc;
3806 graph->scc = ++scc;
3807 graph->weak = 0;
3809 isl_int_clear(gcd);
3810 isl_vec_free(r);
3811 free(order);
3813 if (update_edges(ctx, graph) < 0)
3814 return isl_schedule_node_free(node);
3815 node = insert_current_band(node, graph, 0);
3816 next_band(graph);
3818 node = isl_schedule_node_child(node, 0);
3819 node = compute_component_schedule(node, graph, 0);
3820 node = isl_schedule_node_parent(node);
3822 return node;
3823 error:
3824 isl_vec_free(r);
3825 free(order);
3826 isl_int_clear(gcd);
3827 return isl_schedule_node_free(node);
3830 /* Is the schedule row "sol" trivial on node "node"?
3831 * That is, is the solution zero on the dimensions orthogonal to
3832 * the previously found solutions?
3833 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
3835 * Each coefficient is represented as the difference between
3836 * two non-negative values in "sol". "sol" has been computed
3837 * in terms of the original iterators (i.e., without use of cmap).
3838 * We construct the schedule row s and write it as a linear
3839 * combination of (linear combinations of) previously computed schedule rows.
3840 * s = Q c or c = U s.
3841 * If the final entries of c are all zero, then the solution is trivial.
3843 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
3845 int trivial;
3846 isl_vec *node_sol;
3848 if (!sol)
3849 return -1;
3850 if (node->nvar == node->rank)
3851 return 0;
3853 node_sol = extract_var_coef(node, sol);
3854 node_sol = isl_mat_vec_product(isl_mat_copy(node->cinv), node_sol);
3855 if (!node_sol)
3856 return -1;
3858 trivial = isl_seq_first_non_zero(node_sol->el + node->rank,
3859 node->nvar - node->rank) == -1;
3861 isl_vec_free(node_sol);
3863 return trivial;
3866 /* Is the schedule row "sol" trivial on any node where it should
3867 * not be trivial?
3868 * "sol" has been computed in terms of the original iterators
3869 * (i.e., without use of cmap).
3870 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
3872 static int is_any_trivial(struct isl_sched_graph *graph,
3873 __isl_keep isl_vec *sol)
3875 int i;
3877 for (i = 0; i < graph->n; ++i) {
3878 struct isl_sched_node *node = &graph->node[i];
3879 int trivial;
3881 if (!needs_row(graph, node))
3882 continue;
3883 trivial = is_trivial(node, sol);
3884 if (trivial < 0 || trivial)
3885 return trivial;
3888 return 0;
3891 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
3892 * If so, return the position of the coalesced dimension.
3893 * Otherwise, return node->nvar or -1 on error.
3895 * In particular, look for pairs of coefficients c_i and c_j such that
3896 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
3897 * If any such pair is found, then return i.
3898 * If size_i is infinity, then no check on c_i needs to be performed.
3900 static int find_node_coalescing(struct isl_sched_node *node,
3901 __isl_keep isl_vec *sol)
3903 int i, j;
3904 isl_int max;
3905 isl_vec *csol;
3907 if (node->nvar <= 1)
3908 return node->nvar;
3910 csol = extract_var_coef(node, sol);
3911 if (!csol)
3912 return -1;
3913 isl_int_init(max);
3914 for (i = 0; i < node->nvar; ++i) {
3915 isl_val *v;
3917 if (isl_int_is_zero(csol->el[i]))
3918 continue;
3919 v = isl_multi_val_get_val(node->sizes, i);
3920 if (!v)
3921 goto error;
3922 if (!isl_val_is_int(v)) {
3923 isl_val_free(v);
3924 continue;
3926 isl_int_mul(max, v->n, csol->el[i]);
3927 isl_val_free(v);
3929 for (j = 0; j < node->nvar; ++j) {
3930 if (j == i)
3931 continue;
3932 if (isl_int_abs_ge(csol->el[j], max))
3933 break;
3935 if (j < node->nvar)
3936 break;
3939 isl_int_clear(max);
3940 isl_vec_free(csol);
3941 return i;
3942 error:
3943 isl_int_clear(max);
3944 isl_vec_free(csol);
3945 return -1;
3948 /* Force the schedule coefficient at position "pos" of "node" to be zero
3949 * in "tl".
3950 * The coefficient is encoded as the difference between two non-negative
3951 * variables. Force these two variables to have the same value.
3953 static __isl_give isl_tab_lexmin *zero_out_node_coef(
3954 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
3956 int dim;
3957 isl_ctx *ctx;
3958 isl_vec *eq;
3960 ctx = isl_space_get_ctx(node->space);
3961 dim = isl_tab_lexmin_dim(tl);
3962 if (dim < 0)
3963 return isl_tab_lexmin_free(tl);
3964 eq = isl_vec_alloc(ctx, 1 + dim);
3965 eq = isl_vec_clr(eq);
3966 if (!eq)
3967 return isl_tab_lexmin_free(tl);
3969 pos = 1 + node_var_coef_offset(node) + 2 * pos;
3970 isl_int_set_si(eq->el[pos], 1);
3971 isl_int_set_si(eq->el[pos + 1], -1);
3972 tl = isl_tab_lexmin_add_eq(tl, eq->el);
3973 isl_vec_free(eq);
3975 return tl;
3978 /* Return the lexicographically smallest rational point in the basic set
3979 * from which "tl" was constructed, double checking that this input set
3980 * was not empty.
3982 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
3984 isl_vec *sol;
3986 sol = isl_tab_lexmin_get_solution(tl);
3987 if (!sol)
3988 return NULL;
3989 if (sol->size == 0)
3990 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
3991 "error in schedule construction",
3992 return isl_vec_free(sol));
3993 return sol;
3996 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
3997 * carry any of the "n_edge" groups of dependences?
3998 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
3999 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4000 * by the edge are carried by the solution.
4001 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4002 * one of those is carried.
4004 * Note that despite the fact that the problem is solved using a rational
4005 * solver, the solution is guaranteed to be integral.
4006 * Specifically, the dependence distance lower bounds e_i (and therefore
4007 * also their sum) are integers. See Lemma 5 of [1].
4009 * Any potential denominator of the sum is cleared by this function.
4010 * The denominator is not relevant for any of the other elements
4011 * in the solution.
4013 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4014 * Problem, Part II: Multi-Dimensional Time.
4015 * In Intl. Journal of Parallel Programming, 1992.
4017 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4019 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4020 isl_int_set_si(sol->el[0], 1);
4021 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4024 /* Return the lexicographically smallest rational point in "lp",
4025 * assuming that all variables are non-negative and performing some
4026 * additional sanity checks.
4027 * In particular, "lp" should not be empty by construction.
4028 * Double check that this is the case.
4029 * Also, check that dependences are carried for at least one of
4030 * the "n_edge" edges.
4032 * If the computed schedule performs loop coalescing on a given node,
4033 * i.e., if it is of the form
4035 * c_i i + c_j j + ...
4037 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4038 * to cut out this solution. Repeat this process until no more loop
4039 * coalescing occurs or until no more dependences can be carried.
4040 * In the latter case, revert to the previously computed solution.
4042 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4043 __isl_take isl_basic_set *lp, int n_edge)
4045 int i, pos;
4046 isl_ctx *ctx;
4047 isl_tab_lexmin *tl;
4048 isl_vec *sol, *prev = NULL;
4049 int treat_coalescing;
4051 if (!lp)
4052 return NULL;
4053 ctx = isl_basic_set_get_ctx(lp);
4054 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4055 tl = isl_tab_lexmin_from_basic_set(lp);
4057 do {
4058 sol = non_empty_solution(tl);
4059 if (!sol)
4060 goto error;
4062 if (!carries_dependences(sol, n_edge)) {
4063 if (!prev)
4064 isl_die(ctx, isl_error_unknown,
4065 "unable to carry dependences",
4066 goto error);
4067 isl_vec_free(sol);
4068 sol = prev;
4069 break;
4071 prev = isl_vec_free(prev);
4072 if (!treat_coalescing)
4073 break;
4074 for (i = 0; i < graph->n; ++i) {
4075 struct isl_sched_node *node = &graph->node[i];
4077 pos = find_node_coalescing(node, sol);
4078 if (pos < 0)
4079 goto error;
4080 if (pos < node->nvar)
4081 break;
4083 if (i < graph->n) {
4084 prev = sol;
4085 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4087 } while (i < graph->n);
4089 isl_tab_lexmin_free(tl);
4091 return sol;
4092 error:
4093 isl_tab_lexmin_free(tl);
4094 isl_vec_free(prev);
4095 isl_vec_free(sol);
4096 return NULL;
4099 /* Construct a schedule row for each node such that as many dependences
4100 * as possible are carried and then continue with the next band.
4102 * If the computed schedule row turns out to be trivial on one or
4103 * more nodes where it should not be trivial, then we throw it away
4104 * and try again on each component separately.
4106 * If there is only one component, then we accept the schedule row anyway,
4107 * but we do not consider it as a complete row and therefore do not
4108 * increment graph->n_row. Note that the ranks of the nodes that
4109 * do get a non-trivial schedule part will get updated regardless and
4110 * graph->maxvar is computed based on these ranks. The test for
4111 * whether more schedule rows are required in compute_schedule_wcc
4112 * is therefore not affected.
4114 * Insert a band corresponding to the schedule row at position "node"
4115 * of the schedule tree and continue with the construction of the schedule.
4116 * This insertion and the continued construction is performed by split_scaled
4117 * after optionally checking for non-trivial common divisors.
4119 static __isl_give isl_schedule_node *carry_dependences(
4120 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4122 int i;
4123 int n_edge;
4124 int trivial;
4125 isl_ctx *ctx;
4126 isl_vec *sol;
4127 isl_basic_set *lp;
4129 if (!node)
4130 return NULL;
4132 n_edge = 0;
4133 for (i = 0; i < graph->n_edge; ++i)
4134 n_edge += graph->edge[i].map->n;
4136 ctx = isl_schedule_node_get_ctx(node);
4137 if (setup_carry_lp(ctx, graph) < 0)
4138 return isl_schedule_node_free(node);
4140 lp = isl_basic_set_copy(graph->lp);
4141 sol = non_neg_lexmin(graph, lp, n_edge);
4142 if (!sol)
4143 return isl_schedule_node_free(node);
4145 trivial = is_any_trivial(graph, sol);
4146 if (trivial < 0) {
4147 sol = isl_vec_free(sol);
4148 } else if (trivial && graph->scc > 1) {
4149 isl_vec_free(sol);
4150 return compute_component_schedule(node, graph, 1);
4153 if (update_schedule(graph, sol, 0, 0) < 0)
4154 return isl_schedule_node_free(node);
4155 if (trivial)
4156 graph->n_row--;
4158 return split_scaled(node, graph);
4161 /* Topologically sort statements mapped to the same schedule iteration
4162 * and add insert a sequence node in front of "node"
4163 * corresponding to this order.
4164 * If "initialized" is set, then it may be assumed that compute_maxvar
4165 * has been called on the current band. Otherwise, call
4166 * compute_maxvar if and before carry_dependences gets called.
4168 * If it turns out to be impossible to sort the statements apart,
4169 * because different dependences impose different orderings
4170 * on the statements, then we extend the schedule such that
4171 * it carries at least one more dependence.
4173 static __isl_give isl_schedule_node *sort_statements(
4174 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4175 int initialized)
4177 isl_ctx *ctx;
4178 isl_union_set_list *filters;
4180 if (!node)
4181 return NULL;
4183 ctx = isl_schedule_node_get_ctx(node);
4184 if (graph->n < 1)
4185 isl_die(ctx, isl_error_internal,
4186 "graph should have at least one node",
4187 return isl_schedule_node_free(node));
4189 if (graph->n == 1)
4190 return node;
4192 if (update_edges(ctx, graph) < 0)
4193 return isl_schedule_node_free(node);
4195 if (graph->n_edge == 0)
4196 return node;
4198 if (detect_sccs(ctx, graph) < 0)
4199 return isl_schedule_node_free(node);
4201 next_band(graph);
4202 if (graph->scc < graph->n) {
4203 if (!initialized && compute_maxvar(graph) < 0)
4204 return isl_schedule_node_free(node);
4205 return carry_dependences(node, graph);
4208 filters = extract_sccs(ctx, graph);
4209 node = isl_schedule_node_insert_sequence(node, filters);
4211 return node;
4214 /* Are there any (non-empty) (conditional) validity edges in the graph?
4216 static int has_validity_edges(struct isl_sched_graph *graph)
4218 int i;
4220 for (i = 0; i < graph->n_edge; ++i) {
4221 int empty;
4223 empty = isl_map_plain_is_empty(graph->edge[i].map);
4224 if (empty < 0)
4225 return -1;
4226 if (empty)
4227 continue;
4228 if (is_any_validity(&graph->edge[i]))
4229 return 1;
4232 return 0;
4235 /* Should we apply a Feautrier step?
4236 * That is, did the user request the Feautrier algorithm and are
4237 * there any validity dependences (left)?
4239 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4241 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4242 return 0;
4244 return has_validity_edges(graph);
4247 /* Compute a schedule for a connected dependence graph using Feautrier's
4248 * multi-dimensional scheduling algorithm and return the updated schedule node.
4250 * The original algorithm is described in [1].
4251 * The main idea is to minimize the number of scheduling dimensions, by
4252 * trying to satisfy as many dependences as possible per scheduling dimension.
4254 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4255 * Problem, Part II: Multi-Dimensional Time.
4256 * In Intl. Journal of Parallel Programming, 1992.
4258 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4259 isl_schedule_node *node, struct isl_sched_graph *graph)
4261 return carry_dependences(node, graph);
4264 /* Turn off the "local" bit on all (condition) edges.
4266 static void clear_local_edges(struct isl_sched_graph *graph)
4268 int i;
4270 for (i = 0; i < graph->n_edge; ++i)
4271 if (is_condition(&graph->edge[i]))
4272 clear_local(&graph->edge[i]);
4275 /* Does "graph" have both condition and conditional validity edges?
4277 static int need_condition_check(struct isl_sched_graph *graph)
4279 int i;
4280 int any_condition = 0;
4281 int any_conditional_validity = 0;
4283 for (i = 0; i < graph->n_edge; ++i) {
4284 if (is_condition(&graph->edge[i]))
4285 any_condition = 1;
4286 if (is_conditional_validity(&graph->edge[i]))
4287 any_conditional_validity = 1;
4290 return any_condition && any_conditional_validity;
4293 /* Does "graph" contain any coincidence edge?
4295 static int has_any_coincidence(struct isl_sched_graph *graph)
4297 int i;
4299 for (i = 0; i < graph->n_edge; ++i)
4300 if (is_coincidence(&graph->edge[i]))
4301 return 1;
4303 return 0;
4306 /* Extract the final schedule row as a map with the iteration domain
4307 * of "node" as domain.
4309 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4311 isl_local_space *ls;
4312 isl_aff *aff;
4313 int row;
4315 row = isl_mat_rows(node->sched) - 1;
4316 ls = isl_local_space_from_space(isl_space_copy(node->space));
4317 aff = extract_schedule_row(ls, node, row);
4318 return isl_map_from_aff(aff);
4321 /* Is the conditional validity dependence in the edge with index "edge_index"
4322 * violated by the latest (i.e., final) row of the schedule?
4323 * That is, is i scheduled after j
4324 * for any conditional validity dependence i -> j?
4326 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4328 isl_map *src_sched, *dst_sched, *map;
4329 struct isl_sched_edge *edge = &graph->edge[edge_index];
4330 int empty;
4332 src_sched = final_row(edge->src);
4333 dst_sched = final_row(edge->dst);
4334 map = isl_map_copy(edge->map);
4335 map = isl_map_apply_domain(map, src_sched);
4336 map = isl_map_apply_range(map, dst_sched);
4337 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4338 empty = isl_map_is_empty(map);
4339 isl_map_free(map);
4341 if (empty < 0)
4342 return -1;
4344 return !empty;
4347 /* Does "graph" have any satisfied condition edges that
4348 * are adjacent to the conditional validity constraint with
4349 * domain "conditional_source" and range "conditional_sink"?
4351 * A satisfied condition is one that is not local.
4352 * If a condition was forced to be local already (i.e., marked as local)
4353 * then there is no need to check if it is in fact local.
4355 * Additionally, mark all adjacent condition edges found as local.
4357 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4358 __isl_keep isl_union_set *conditional_source,
4359 __isl_keep isl_union_set *conditional_sink)
4361 int i;
4362 int any = 0;
4364 for (i = 0; i < graph->n_edge; ++i) {
4365 int adjacent, local;
4366 isl_union_map *condition;
4368 if (!is_condition(&graph->edge[i]))
4369 continue;
4370 if (is_local(&graph->edge[i]))
4371 continue;
4373 condition = graph->edge[i].tagged_condition;
4374 adjacent = domain_intersects(condition, conditional_sink);
4375 if (adjacent >= 0 && !adjacent)
4376 adjacent = range_intersects(condition,
4377 conditional_source);
4378 if (adjacent < 0)
4379 return -1;
4380 if (!adjacent)
4381 continue;
4383 set_local(&graph->edge[i]);
4385 local = is_condition_false(&graph->edge[i]);
4386 if (local < 0)
4387 return -1;
4388 if (!local)
4389 any = 1;
4392 return any;
4395 /* Are there any violated conditional validity dependences with
4396 * adjacent condition dependences that are not local with respect
4397 * to the current schedule?
4398 * That is, is the conditional validity constraint violated?
4400 * Additionally, mark all those adjacent condition dependences as local.
4401 * We also mark those adjacent condition dependences that were not marked
4402 * as local before, but just happened to be local already. This ensures
4403 * that they remain local if the schedule is recomputed.
4405 * We first collect domain and range of all violated conditional validity
4406 * dependences and then check if there are any adjacent non-local
4407 * condition dependences.
4409 static int has_violated_conditional_constraint(isl_ctx *ctx,
4410 struct isl_sched_graph *graph)
4412 int i;
4413 int any = 0;
4414 isl_union_set *source, *sink;
4416 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4417 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4418 for (i = 0; i < graph->n_edge; ++i) {
4419 isl_union_set *uset;
4420 isl_union_map *umap;
4421 int violated;
4423 if (!is_conditional_validity(&graph->edge[i]))
4424 continue;
4426 violated = is_violated(graph, i);
4427 if (violated < 0)
4428 goto error;
4429 if (!violated)
4430 continue;
4432 any = 1;
4434 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4435 uset = isl_union_map_domain(umap);
4436 source = isl_union_set_union(source, uset);
4437 source = isl_union_set_coalesce(source);
4439 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4440 uset = isl_union_map_range(umap);
4441 sink = isl_union_set_union(sink, uset);
4442 sink = isl_union_set_coalesce(sink);
4445 if (any)
4446 any = has_adjacent_true_conditions(graph, source, sink);
4448 isl_union_set_free(source);
4449 isl_union_set_free(sink);
4450 return any;
4451 error:
4452 isl_union_set_free(source);
4453 isl_union_set_free(sink);
4454 return -1;
4457 /* Examine the current band (the rows between graph->band_start and
4458 * graph->n_total_row), deciding whether to drop it or add it to "node"
4459 * and then continue with the computation of the next band, if any.
4460 * If "initialized" is set, then it may be assumed that compute_maxvar
4461 * has been called on the current band. Otherwise, call
4462 * compute_maxvar if and before carry_dependences gets called.
4464 * The caller keeps looking for a new row as long as
4465 * graph->n_row < graph->maxvar. If the latest attempt to find
4466 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4467 * then we either
4468 * - split between SCCs and start over (assuming we found an interesting
4469 * pair of SCCs between which to split)
4470 * - continue with the next band (assuming the current band has at least
4471 * one row)
4472 * - try to carry as many dependences as possible and continue with the next
4473 * band
4474 * In each case, we first insert a band node in the schedule tree
4475 * if any rows have been computed.
4477 * If the caller managed to complete the schedule, we insert a band node
4478 * (if any schedule rows were computed) and we finish off by topologically
4479 * sorting the statements based on the remaining dependences.
4481 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4482 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4483 int initialized)
4485 int insert;
4487 if (!node)
4488 return NULL;
4490 if (graph->n_row < graph->maxvar) {
4491 isl_ctx *ctx;
4492 int empty = graph->n_total_row == graph->band_start;
4494 ctx = isl_schedule_node_get_ctx(node);
4495 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4496 return compute_next_band(node, graph, 1);
4497 if (graph->src_scc >= 0)
4498 return compute_split_schedule(node, graph);
4499 if (!empty)
4500 return compute_next_band(node, graph, 1);
4501 if (!initialized && compute_maxvar(graph) < 0)
4502 return isl_schedule_node_free(node);
4503 return carry_dependences(node, graph);
4506 insert = graph->n_total_row > graph->band_start;
4507 if (insert) {
4508 node = insert_current_band(node, graph, 1);
4509 node = isl_schedule_node_child(node, 0);
4511 node = sort_statements(node, graph, initialized);
4512 if (insert)
4513 node = isl_schedule_node_parent(node);
4515 return node;
4518 /* Construct a band of schedule rows for a connected dependence graph.
4519 * The caller is responsible for determining the strongly connected
4520 * components and calling compute_maxvar first.
4522 * We try to find a sequence of as many schedule rows as possible that result
4523 * in non-negative dependence distances (independent of the previous rows
4524 * in the sequence, i.e., such that the sequence is tilable), with as
4525 * many of the initial rows as possible satisfying the coincidence constraints.
4526 * The computation stops if we can't find any more rows or if we have found
4527 * all the rows we wanted to find.
4529 * If ctx->opt->schedule_outer_coincidence is set, then we force the
4530 * outermost dimension to satisfy the coincidence constraints. If this
4531 * turns out to be impossible, we fall back on the general scheme above
4532 * and try to carry as many dependences as possible.
4534 * If "graph" contains both condition and conditional validity dependences,
4535 * then we need to check that that the conditional schedule constraint
4536 * is satisfied, i.e., there are no violated conditional validity dependences
4537 * that are adjacent to any non-local condition dependences.
4538 * If there are, then we mark all those adjacent condition dependences
4539 * as local and recompute the current band. Those dependences that
4540 * are marked local will then be forced to be local.
4541 * The initial computation is performed with no dependences marked as local.
4542 * If we are lucky, then there will be no violated conditional validity
4543 * dependences adjacent to any non-local condition dependences.
4544 * Otherwise, we mark some additional condition dependences as local and
4545 * recompute. We continue this process until there are no violations left or
4546 * until we are no longer able to compute a schedule.
4547 * Since there are only a finite number of dependences,
4548 * there will only be a finite number of iterations.
4550 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
4551 struct isl_sched_graph *graph)
4553 int has_coincidence;
4554 int use_coincidence;
4555 int force_coincidence = 0;
4556 int check_conditional;
4558 if (sort_sccs(graph) < 0)
4559 return isl_stat_error;
4561 clear_local_edges(graph);
4562 check_conditional = need_condition_check(graph);
4563 has_coincidence = has_any_coincidence(graph);
4565 if (ctx->opt->schedule_outer_coincidence)
4566 force_coincidence = 1;
4568 use_coincidence = has_coincidence;
4569 while (graph->n_row < graph->maxvar) {
4570 isl_vec *sol;
4571 int violated;
4572 int coincident;
4574 graph->src_scc = -1;
4575 graph->dst_scc = -1;
4577 if (setup_lp(ctx, graph, use_coincidence) < 0)
4578 return isl_stat_error;
4579 sol = solve_lp(graph);
4580 if (!sol)
4581 return isl_stat_error;
4582 if (sol->size == 0) {
4583 int empty = graph->n_total_row == graph->band_start;
4585 isl_vec_free(sol);
4586 if (use_coincidence && (!force_coincidence || !empty)) {
4587 use_coincidence = 0;
4588 continue;
4590 return isl_stat_ok;
4592 coincident = !has_coincidence || use_coincidence;
4593 if (update_schedule(graph, sol, 1, coincident) < 0)
4594 return isl_stat_error;
4596 if (!check_conditional)
4597 continue;
4598 violated = has_violated_conditional_constraint(ctx, graph);
4599 if (violated < 0)
4600 return isl_stat_error;
4601 if (!violated)
4602 continue;
4603 if (reset_band(graph) < 0)
4604 return isl_stat_error;
4605 use_coincidence = has_coincidence;
4608 return isl_stat_ok;
4611 /* Compute a schedule for a connected dependence graph by considering
4612 * the graph as a whole and return the updated schedule node.
4614 * The actual schedule rows of the current band are computed by
4615 * compute_schedule_wcc_band. compute_schedule_finish_band takes
4616 * care of integrating the band into "node" and continuing
4617 * the computation.
4619 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
4620 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4622 isl_ctx *ctx;
4624 if (!node)
4625 return NULL;
4627 ctx = isl_schedule_node_get_ctx(node);
4628 if (compute_schedule_wcc_band(ctx, graph) < 0)
4629 return isl_schedule_node_free(node);
4631 return compute_schedule_finish_band(node, graph, 1);
4634 /* Clustering information used by compute_schedule_wcc_clustering.
4636 * "n" is the number of SCCs in the original dependence graph
4637 * "scc" is an array of "n" elements, each representing an SCC
4638 * of the original dependence graph. All entries in the same cluster
4639 * have the same number of schedule rows.
4640 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
4641 * where each cluster is represented by the index of the first SCC
4642 * in the cluster. Initially, each SCC belongs to a cluster containing
4643 * only that SCC.
4645 * "scc_in_merge" is used by merge_clusters_along_edge to keep
4646 * track of which SCCs need to be merged.
4648 * "cluster" contains the merged clusters of SCCs after the clustering
4649 * has completed.
4651 * "scc_node" is a temporary data structure used inside copy_partial.
4652 * For each SCC, it keeps track of the number of nodes in the SCC
4653 * that have already been copied.
4655 struct isl_clustering {
4656 int n;
4657 struct isl_sched_graph *scc;
4658 struct isl_sched_graph *cluster;
4659 int *scc_cluster;
4660 int *scc_node;
4661 int *scc_in_merge;
4664 /* Initialize the clustering data structure "c" from "graph".
4666 * In particular, allocate memory, extract the SCCs from "graph"
4667 * into c->scc, initialize scc_cluster and construct
4668 * a band of schedule rows for each SCC.
4669 * Within each SCC, there is only one SCC by definition.
4670 * Each SCC initially belongs to a cluster containing only that SCC.
4672 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
4673 struct isl_sched_graph *graph)
4675 int i;
4677 c->n = graph->scc;
4678 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
4679 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
4680 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
4681 c->scc_node = isl_calloc_array(ctx, int, c->n);
4682 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
4683 if (!c->scc || !c->cluster ||
4684 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
4685 return isl_stat_error;
4687 for (i = 0; i < c->n; ++i) {
4688 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
4689 &edge_scc_exactly, i, &c->scc[i]) < 0)
4690 return isl_stat_error;
4691 c->scc[i].scc = 1;
4692 if (compute_maxvar(&c->scc[i]) < 0)
4693 return isl_stat_error;
4694 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
4695 return isl_stat_error;
4696 c->scc_cluster[i] = i;
4699 return isl_stat_ok;
4702 /* Free all memory allocated for "c".
4704 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
4706 int i;
4708 if (c->scc)
4709 for (i = 0; i < c->n; ++i)
4710 graph_free(ctx, &c->scc[i]);
4711 free(c->scc);
4712 if (c->cluster)
4713 for (i = 0; i < c->n; ++i)
4714 graph_free(ctx, &c->cluster[i]);
4715 free(c->cluster);
4716 free(c->scc_cluster);
4717 free(c->scc_node);
4718 free(c->scc_in_merge);
4721 /* Should we refrain from merging the cluster in "graph" with
4722 * any other cluster?
4723 * In particular, is its current schedule band empty and incomplete.
4725 static int bad_cluster(struct isl_sched_graph *graph)
4727 return graph->n_row < graph->maxvar &&
4728 graph->n_total_row == graph->band_start;
4731 /* Return the index of an edge in "graph" that can be used to merge
4732 * two clusters in "c".
4733 * Return graph->n_edge if no such edge can be found.
4734 * Return -1 on error.
4736 * In particular, return a proximity edge between two clusters
4737 * that is not marked "no_merge" and such that neither of the
4738 * two clusters has an incomplete, empty band.
4740 * If there are multiple such edges, then try and find the most
4741 * appropriate edge to use for merging. In particular, pick the edge
4742 * with the greatest weight. If there are multiple of those,
4743 * then pick one with the shortest distance between
4744 * the two cluster representatives.
4746 static int find_proximity(struct isl_sched_graph *graph,
4747 struct isl_clustering *c)
4749 int i, best = graph->n_edge, best_dist, best_weight;
4751 for (i = 0; i < graph->n_edge; ++i) {
4752 struct isl_sched_edge *edge = &graph->edge[i];
4753 int dist, weight;
4755 if (!is_proximity(edge))
4756 continue;
4757 if (edge->no_merge)
4758 continue;
4759 if (bad_cluster(&c->scc[edge->src->scc]) ||
4760 bad_cluster(&c->scc[edge->dst->scc]))
4761 continue;
4762 dist = c->scc_cluster[edge->dst->scc] -
4763 c->scc_cluster[edge->src->scc];
4764 if (dist == 0)
4765 continue;
4766 weight = edge->weight;
4767 if (best < graph->n_edge) {
4768 if (best_weight > weight)
4769 continue;
4770 if (best_weight == weight && best_dist <= dist)
4771 continue;
4773 best = i;
4774 best_dist = dist;
4775 best_weight = weight;
4778 return best;
4781 /* Internal data structure used in mark_merge_sccs.
4783 * "graph" is the dependence graph in which a strongly connected
4784 * component is constructed.
4785 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
4786 * "src" and "dst" are the indices of the nodes that are being merged.
4788 struct isl_mark_merge_sccs_data {
4789 struct isl_sched_graph *graph;
4790 int *scc_cluster;
4791 int src;
4792 int dst;
4795 /* Check whether the cluster containing node "i" depends on the cluster
4796 * containing node "j". If "i" and "j" belong to the same cluster,
4797 * then they are taken to depend on each other to ensure that
4798 * the resulting strongly connected component consists of complete
4799 * clusters. Furthermore, if "i" and "j" are the two nodes that
4800 * are being merged, then they are taken to depend on each other as well.
4801 * Otherwise, check if there is a (conditional) validity dependence
4802 * from node[j] to node[i], forcing node[i] to follow node[j].
4804 static isl_bool cluster_follows(int i, int j, void *user)
4806 struct isl_mark_merge_sccs_data *data = user;
4807 struct isl_sched_graph *graph = data->graph;
4808 int *scc_cluster = data->scc_cluster;
4810 if (data->src == i && data->dst == j)
4811 return isl_bool_true;
4812 if (data->src == j && data->dst == i)
4813 return isl_bool_true;
4814 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
4815 return isl_bool_true;
4817 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
4820 /* Mark all SCCs that belong to either of the two clusters in "c"
4821 * connected by the edge in "graph" with index "edge", or to any
4822 * of the intermediate clusters.
4823 * The marking is recorded in c->scc_in_merge.
4825 * The given edge has been selected for merging two clusters,
4826 * meaning that there is at least a proximity edge between the two nodes.
4827 * However, there may also be (indirect) validity dependences
4828 * between the two nodes. When merging the two clusters, all clusters
4829 * containing one or more of the intermediate nodes along the
4830 * indirect validity dependences need to be merged in as well.
4832 * First collect all such nodes by computing the strongly connected
4833 * component (SCC) containing the two nodes connected by the edge, where
4834 * the two nodes are considered to depend on each other to make
4835 * sure they end up in the same SCC. Similarly, each node is considered
4836 * to depend on every other node in the same cluster to ensure
4837 * that the SCC consists of complete clusters.
4839 * Then the original SCCs that contain any of these nodes are marked
4840 * in c->scc_in_merge.
4842 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
4843 int edge, struct isl_clustering *c)
4845 struct isl_mark_merge_sccs_data data;
4846 struct isl_tarjan_graph *g;
4847 int i;
4849 for (i = 0; i < c->n; ++i)
4850 c->scc_in_merge[i] = 0;
4852 data.graph = graph;
4853 data.scc_cluster = c->scc_cluster;
4854 data.src = graph->edge[edge].src - graph->node;
4855 data.dst = graph->edge[edge].dst - graph->node;
4857 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
4858 &cluster_follows, &data);
4859 if (!g)
4860 goto error;
4862 i = g->op;
4863 if (i < 3)
4864 isl_die(ctx, isl_error_internal,
4865 "expecting at least two nodes in component",
4866 goto error);
4867 if (g->order[--i] != -1)
4868 isl_die(ctx, isl_error_internal,
4869 "expecting end of component marker", goto error);
4871 for (--i; i >= 0 && g->order[i] != -1; --i) {
4872 int scc = graph->node[g->order[i]].scc;
4873 c->scc_in_merge[scc] = 1;
4876 isl_tarjan_graph_free(g);
4877 return isl_stat_ok;
4878 error:
4879 isl_tarjan_graph_free(g);
4880 return isl_stat_error;
4883 /* Construct the identifier "cluster_i".
4885 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
4887 char name[40];
4889 snprintf(name, sizeof(name), "cluster_%d", i);
4890 return isl_id_alloc(ctx, name, NULL);
4893 /* Construct the space of the cluster with index "i" containing
4894 * the strongly connected component "scc".
4896 * In particular, construct a space called cluster_i with dimension equal
4897 * to the number of schedule rows in the current band of "scc".
4899 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
4901 int nvar;
4902 isl_space *space;
4903 isl_id *id;
4905 nvar = scc->n_total_row - scc->band_start;
4906 space = isl_space_copy(scc->node[0].space);
4907 space = isl_space_params(space);
4908 space = isl_space_set_from_params(space);
4909 space = isl_space_add_dims(space, isl_dim_set, nvar);
4910 id = cluster_id(isl_space_get_ctx(space), i);
4911 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4913 return space;
4916 /* Collect the domain of the graph for merging clusters.
4918 * In particular, for each cluster with first SCC "i", construct
4919 * a set in the space called cluster_i with dimension equal
4920 * to the number of schedule rows in the current band of the cluster.
4922 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
4923 struct isl_sched_graph *graph, struct isl_clustering *c)
4925 int i;
4926 isl_space *space;
4927 isl_union_set *domain;
4929 space = isl_space_params_alloc(ctx, 0);
4930 domain = isl_union_set_empty(space);
4932 for (i = 0; i < graph->scc; ++i) {
4933 isl_space *space;
4935 if (!c->scc_in_merge[i])
4936 continue;
4937 if (c->scc_cluster[i] != i)
4938 continue;
4939 space = cluster_space(&c->scc[i], i);
4940 domain = isl_union_set_add_set(domain, isl_set_universe(space));
4943 return domain;
4946 /* Construct a map from the original instances to the corresponding
4947 * cluster instance in the current bands of the clusters in "c".
4949 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
4950 struct isl_sched_graph *graph, struct isl_clustering *c)
4952 int i, j;
4953 isl_space *space;
4954 isl_union_map *cluster_map;
4956 space = isl_space_params_alloc(ctx, 0);
4957 cluster_map = isl_union_map_empty(space);
4958 for (i = 0; i < graph->scc; ++i) {
4959 int start, n;
4960 isl_id *id;
4962 if (!c->scc_in_merge[i])
4963 continue;
4965 id = cluster_id(ctx, c->scc_cluster[i]);
4966 start = c->scc[i].band_start;
4967 n = c->scc[i].n_total_row - start;
4968 for (j = 0; j < c->scc[i].n; ++j) {
4969 isl_multi_aff *ma;
4970 isl_map *map;
4971 struct isl_sched_node *node = &c->scc[i].node[j];
4973 ma = node_extract_partial_schedule_multi_aff(node,
4974 start, n);
4975 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
4976 isl_id_copy(id));
4977 map = isl_map_from_multi_aff(ma);
4978 cluster_map = isl_union_map_add_map(cluster_map, map);
4980 isl_id_free(id);
4983 return cluster_map;
4986 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
4987 * that are not isl_edge_condition or isl_edge_conditional_validity.
4989 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
4990 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
4991 __isl_take isl_schedule_constraints *sc)
4993 enum isl_edge_type t;
4995 if (!sc)
4996 return NULL;
4998 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
4999 if (t == isl_edge_condition ||
5000 t == isl_edge_conditional_validity)
5001 continue;
5002 if (!is_type(edge, t))
5003 continue;
5004 sc = isl_schedule_constraints_add(sc, t,
5005 isl_union_map_copy(umap));
5008 return sc;
5011 /* Add schedule constraints of types isl_edge_condition and
5012 * isl_edge_conditional_validity to "sc" by applying "umap" to
5013 * the domains of the wrapped relations in domain and range
5014 * of the corresponding tagged constraints of "edge".
5016 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5017 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5018 __isl_take isl_schedule_constraints *sc)
5020 enum isl_edge_type t;
5021 isl_union_map *tagged;
5023 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5024 if (!is_type(edge, t))
5025 continue;
5026 if (t == isl_edge_condition)
5027 tagged = isl_union_map_copy(edge->tagged_condition);
5028 else
5029 tagged = isl_union_map_copy(edge->tagged_validity);
5030 tagged = isl_union_map_zip(tagged);
5031 tagged = isl_union_map_apply_domain(tagged,
5032 isl_union_map_copy(umap));
5033 tagged = isl_union_map_zip(tagged);
5034 sc = isl_schedule_constraints_add(sc, t, tagged);
5035 if (!sc)
5036 return NULL;
5039 return sc;
5042 /* Given a mapping "cluster_map" from the original instances to
5043 * the cluster instances, add schedule constraints on the clusters
5044 * to "sc" corresponding to the original constraints represented by "edge".
5046 * For non-tagged dependence constraints, the cluster constraints
5047 * are obtained by applying "cluster_map" to the edge->map.
5049 * For tagged dependence constraints, "cluster_map" needs to be applied
5050 * to the domains of the wrapped relations in domain and range
5051 * of the tagged dependence constraints. Pick out the mappings
5052 * from these domains from "cluster_map" and construct their product.
5053 * This mapping can then be applied to the pair of domains.
5055 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5056 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5057 __isl_take isl_schedule_constraints *sc)
5059 isl_union_map *umap;
5060 isl_space *space;
5061 isl_union_set *uset;
5062 isl_union_map *umap1, *umap2;
5064 if (!sc)
5065 return NULL;
5067 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5068 umap = isl_union_map_apply_domain(umap,
5069 isl_union_map_copy(cluster_map));
5070 umap = isl_union_map_apply_range(umap,
5071 isl_union_map_copy(cluster_map));
5072 sc = add_non_conditional_constraints(edge, umap, sc);
5073 isl_union_map_free(umap);
5075 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5076 return sc;
5078 space = isl_space_domain(isl_map_get_space(edge->map));
5079 uset = isl_union_set_from_set(isl_set_universe(space));
5080 umap1 = isl_union_map_copy(cluster_map);
5081 umap1 = isl_union_map_intersect_domain(umap1, uset);
5082 space = isl_space_range(isl_map_get_space(edge->map));
5083 uset = isl_union_set_from_set(isl_set_universe(space));
5084 umap2 = isl_union_map_copy(cluster_map);
5085 umap2 = isl_union_map_intersect_domain(umap2, uset);
5086 umap = isl_union_map_product(umap1, umap2);
5088 sc = add_conditional_constraints(edge, umap, sc);
5090 isl_union_map_free(umap);
5091 return sc;
5094 /* Given a mapping "cluster_map" from the original instances to
5095 * the cluster instances, add schedule constraints on the clusters
5096 * to "sc" corresponding to all edges in "graph" between nodes that
5097 * belong to SCCs that are marked for merging in "scc_in_merge".
5099 static __isl_give isl_schedule_constraints *collect_constraints(
5100 struct isl_sched_graph *graph, int *scc_in_merge,
5101 __isl_keep isl_union_map *cluster_map,
5102 __isl_take isl_schedule_constraints *sc)
5104 int i;
5106 for (i = 0; i < graph->n_edge; ++i) {
5107 struct isl_sched_edge *edge = &graph->edge[i];
5109 if (!scc_in_merge[edge->src->scc])
5110 continue;
5111 if (!scc_in_merge[edge->dst->scc])
5112 continue;
5113 sc = collect_edge_constraints(edge, cluster_map, sc);
5116 return sc;
5119 /* Construct a dependence graph for scheduling clusters with respect
5120 * to each other and store the result in "merge_graph".
5121 * In particular, the nodes of the graph correspond to the schedule
5122 * dimensions of the current bands of those clusters that have been
5123 * marked for merging in "c".
5125 * First construct an isl_schedule_constraints object for this domain
5126 * by transforming the edges in "graph" to the domain.
5127 * Then initialize a dependence graph for scheduling from these
5128 * constraints.
5130 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5131 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5133 isl_union_set *domain;
5134 isl_union_map *cluster_map;
5135 isl_schedule_constraints *sc;
5136 isl_stat r;
5138 domain = collect_domain(ctx, graph, c);
5139 sc = isl_schedule_constraints_on_domain(domain);
5140 if (!sc)
5141 return isl_stat_error;
5142 cluster_map = collect_cluster_map(ctx, graph, c);
5143 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5144 isl_union_map_free(cluster_map);
5146 r = graph_init(merge_graph, sc);
5148 isl_schedule_constraints_free(sc);
5150 return r;
5153 /* Compute the maximal number of remaining schedule rows that still need
5154 * to be computed for the nodes that belong to clusters with the maximal
5155 * dimension for the current band (i.e., the band that is to be merged).
5156 * Only clusters that are about to be merged are considered.
5157 * "maxvar" is the maximal dimension for the current band.
5158 * "c" contains information about the clusters.
5160 * Return the maximal number of remaining schedule rows or -1 on error.
5162 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5164 int i, j;
5165 int max_slack;
5167 max_slack = 0;
5168 for (i = 0; i < c->n; ++i) {
5169 int nvar;
5170 struct isl_sched_graph *scc;
5172 if (!c->scc_in_merge[i])
5173 continue;
5174 scc = &c->scc[i];
5175 nvar = scc->n_total_row - scc->band_start;
5176 if (nvar != maxvar)
5177 continue;
5178 for (j = 0; j < scc->n; ++j) {
5179 struct isl_sched_node *node = &scc->node[j];
5180 int slack;
5182 if (node_update_cmap(node) < 0)
5183 return -1;
5184 slack = node->nvar - node->rank;
5185 if (slack > max_slack)
5186 max_slack = slack;
5190 return max_slack;
5193 /* If there are any clusters where the dimension of the current band
5194 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5195 * if there are any nodes in such a cluster where the number
5196 * of remaining schedule rows that still need to be computed
5197 * is greater than "max_slack", then return the smallest current band
5198 * dimension of all these clusters. Otherwise return the original value
5199 * of "maxvar". Return -1 in case of any error.
5200 * Only clusters that are about to be merged are considered.
5201 * "c" contains information about the clusters.
5203 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5204 struct isl_clustering *c)
5206 int i, j;
5208 for (i = 0; i < c->n; ++i) {
5209 int nvar;
5210 struct isl_sched_graph *scc;
5212 if (!c->scc_in_merge[i])
5213 continue;
5214 scc = &c->scc[i];
5215 nvar = scc->n_total_row - scc->band_start;
5216 if (nvar >= maxvar)
5217 continue;
5218 for (j = 0; j < scc->n; ++j) {
5219 struct isl_sched_node *node = &scc->node[j];
5220 int slack;
5222 if (node_update_cmap(node) < 0)
5223 return -1;
5224 slack = node->nvar - node->rank;
5225 if (slack > max_slack) {
5226 maxvar = nvar;
5227 break;
5232 return maxvar;
5235 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5236 * that still need to be computed. In particular, if there is a node
5237 * in a cluster where the dimension of the current band is smaller
5238 * than merge_graph->maxvar, but the number of remaining schedule rows
5239 * is greater than that of any node in a cluster with the maximal
5240 * dimension for the current band (i.e., merge_graph->maxvar),
5241 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5242 * of those clusters. Without this adjustment, the total number of
5243 * schedule dimensions would be increased, resulting in a skewed view
5244 * of the number of coincident dimensions.
5245 * "c" contains information about the clusters.
5247 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5248 * then there is no point in attempting any merge since it will be rejected
5249 * anyway. Set merge_graph->maxvar to zero in such cases.
5251 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5252 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5254 int max_slack, maxvar;
5256 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5257 if (max_slack < 0)
5258 return isl_stat_error;
5259 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5260 if (maxvar < 0)
5261 return isl_stat_error;
5263 if (maxvar < merge_graph->maxvar) {
5264 if (isl_options_get_schedule_maximize_band_depth(ctx))
5265 merge_graph->maxvar = 0;
5266 else
5267 merge_graph->maxvar = maxvar;
5270 return isl_stat_ok;
5273 /* Return the number of coincident dimensions in the current band of "graph",
5274 * where the nodes of "graph" are assumed to be scheduled by a single band.
5276 static int get_n_coincident(struct isl_sched_graph *graph)
5278 int i;
5280 for (i = graph->band_start; i < graph->n_total_row; ++i)
5281 if (!graph->node[0].coincident[i])
5282 break;
5284 return i - graph->band_start;
5287 /* Should the clusters be merged based on the cluster schedule
5288 * in the current (and only) band of "merge_graph", given that
5289 * coincidence should be maximized?
5291 * If the number of coincident schedule dimensions in the merged band
5292 * would be less than the maximal number of coincident schedule dimensions
5293 * in any of the merged clusters, then the clusters should not be merged.
5295 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5296 struct isl_sched_graph *merge_graph)
5298 int i;
5299 int n_coincident;
5300 int max_coincident;
5302 max_coincident = 0;
5303 for (i = 0; i < c->n; ++i) {
5304 if (!c->scc_in_merge[i])
5305 continue;
5306 n_coincident = get_n_coincident(&c->scc[i]);
5307 if (n_coincident > max_coincident)
5308 max_coincident = n_coincident;
5311 n_coincident = get_n_coincident(merge_graph);
5313 return n_coincident >= max_coincident;
5316 /* Return the transformation on "node" expressed by the current (and only)
5317 * band of "merge_graph" applied to the clusters in "c".
5319 * First find the representation of "node" in its SCC in "c" and
5320 * extract the transformation expressed by the current band.
5321 * Then extract the transformation applied by "merge_graph"
5322 * to the cluster to which this SCC belongs.
5323 * Combine the two to obtain the complete transformation on the node.
5325 * Note that the range of the first transformation is an anonymous space,
5326 * while the domain of the second is named "cluster_X". The range
5327 * of the former therefore needs to be adjusted before the two
5328 * can be combined.
5330 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5331 struct isl_sched_node *node, struct isl_clustering *c,
5332 struct isl_sched_graph *merge_graph)
5334 struct isl_sched_node *scc_node, *cluster_node;
5335 int start, n;
5336 isl_id *id;
5337 isl_space *space;
5338 isl_multi_aff *ma, *ma2;
5340 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5341 start = c->scc[node->scc].band_start;
5342 n = c->scc[node->scc].n_total_row - start;
5343 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5344 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5345 cluster_node = graph_find_node(ctx, merge_graph, space);
5346 if (space && !cluster_node)
5347 isl_die(ctx, isl_error_internal, "unable to find cluster",
5348 space = isl_space_free(space));
5349 id = isl_space_get_tuple_id(space, isl_dim_set);
5350 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5351 isl_space_free(space);
5352 n = merge_graph->n_total_row;
5353 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5354 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5356 return isl_map_from_multi_aff(ma);
5359 /* Give a set of distances "set", are they bounded by a small constant
5360 * in direction "pos"?
5361 * In practice, check if they are bounded by 2 by checking that there
5362 * are no elements with a value greater than or equal to 3 or
5363 * smaller than or equal to -3.
5365 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5367 isl_bool bounded;
5368 isl_set *test;
5370 if (!set)
5371 return isl_bool_error;
5373 test = isl_set_copy(set);
5374 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5375 bounded = isl_set_is_empty(test);
5376 isl_set_free(test);
5378 if (bounded < 0 || !bounded)
5379 return bounded;
5381 test = isl_set_copy(set);
5382 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5383 bounded = isl_set_is_empty(test);
5384 isl_set_free(test);
5386 return bounded;
5389 /* Does the set "set" have a fixed (but possible parametric) value
5390 * at dimension "pos"?
5392 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5394 int n;
5395 isl_bool single;
5397 if (!set)
5398 return isl_bool_error;
5399 set = isl_set_copy(set);
5400 n = isl_set_dim(set, isl_dim_set);
5401 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5402 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5403 single = isl_set_is_singleton(set);
5404 isl_set_free(set);
5406 return single;
5409 /* Does "map" have a fixed (but possible parametric) value
5410 * at dimension "pos" of either its domain or its range?
5412 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5414 isl_set *set;
5415 isl_bool single;
5417 set = isl_map_domain(isl_map_copy(map));
5418 single = has_single_value(set, pos);
5419 isl_set_free(set);
5421 if (single < 0 || single)
5422 return single;
5424 set = isl_map_range(isl_map_copy(map));
5425 single = has_single_value(set, pos);
5426 isl_set_free(set);
5428 return single;
5431 /* Does the edge "edge" from "graph" have bounded dependence distances
5432 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5434 * Extract the complete transformations of the source and destination
5435 * nodes of the edge, apply them to the edge constraints and
5436 * compute the differences. Finally, check if these differences are bounded
5437 * in each direction.
5439 * If the dimension of the band is greater than the number of
5440 * dimensions that can be expected to be optimized by the edge
5441 * (based on its weight), then also allow the differences to be unbounded
5442 * in the remaining dimensions, but only if either the source or
5443 * the destination has a fixed value in that direction.
5444 * This allows a statement that produces values that are used by
5445 * several instances of another statement to be merged with that
5446 * other statement.
5447 * However, merging such clusters will introduce an inherently
5448 * large proximity distance inside the merged cluster, meaning
5449 * that proximity distances will no longer be optimized in
5450 * subsequent merges. These merges are therefore only allowed
5451 * after all other possible merges have been tried.
5452 * The first time such a merge is encountered, the weight of the edge
5453 * is replaced by a negative weight. The second time (i.e., after
5454 * all merges over edges with a non-negative weight have been tried),
5455 * the merge is allowed.
5457 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5458 struct isl_sched_graph *graph, struct isl_clustering *c,
5459 struct isl_sched_graph *merge_graph)
5461 int i, n, n_slack;
5462 isl_bool bounded;
5463 isl_map *map, *t;
5464 isl_set *dist;
5466 map = isl_map_copy(edge->map);
5467 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5468 map = isl_map_apply_domain(map, t);
5469 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5470 map = isl_map_apply_range(map, t);
5471 dist = isl_map_deltas(isl_map_copy(map));
5473 bounded = isl_bool_true;
5474 n = isl_set_dim(dist, isl_dim_set);
5475 n_slack = n - edge->weight;
5476 if (edge->weight < 0)
5477 n_slack -= graph->max_weight + 1;
5478 for (i = 0; i < n; ++i) {
5479 isl_bool bounded_i, singular_i;
5481 bounded_i = distance_is_bounded(dist, i);
5482 if (bounded_i < 0)
5483 goto error;
5484 if (bounded_i)
5485 continue;
5486 if (edge->weight >= 0)
5487 bounded = isl_bool_false;
5488 n_slack--;
5489 if (n_slack < 0)
5490 break;
5491 singular_i = has_singular_src_or_dst(map, i);
5492 if (singular_i < 0)
5493 goto error;
5494 if (singular_i)
5495 continue;
5496 bounded = isl_bool_false;
5497 break;
5499 if (!bounded && i >= n && edge->weight >= 0)
5500 edge->weight -= graph->max_weight + 1;
5501 isl_map_free(map);
5502 isl_set_free(dist);
5504 return bounded;
5505 error:
5506 isl_map_free(map);
5507 isl_set_free(dist);
5508 return isl_bool_error;
5511 /* Should the clusters be merged based on the cluster schedule
5512 * in the current (and only) band of "merge_graph"?
5513 * "graph" is the original dependence graph, while "c" records
5514 * which SCCs are involved in the latest merge.
5516 * In particular, is there at least one proximity constraint
5517 * that is optimized by the merge?
5519 * A proximity constraint is considered to be optimized
5520 * if the dependence distances are small.
5522 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
5523 struct isl_sched_graph *graph, struct isl_clustering *c,
5524 struct isl_sched_graph *merge_graph)
5526 int i;
5528 for (i = 0; i < graph->n_edge; ++i) {
5529 struct isl_sched_edge *edge = &graph->edge[i];
5530 isl_bool bounded;
5532 if (!is_proximity(edge))
5533 continue;
5534 if (!c->scc_in_merge[edge->src->scc])
5535 continue;
5536 if (!c->scc_in_merge[edge->dst->scc])
5537 continue;
5538 if (c->scc_cluster[edge->dst->scc] ==
5539 c->scc_cluster[edge->src->scc])
5540 continue;
5541 bounded = has_bounded_distances(ctx, edge, graph, c,
5542 merge_graph);
5543 if (bounded < 0 || bounded)
5544 return bounded;
5547 return isl_bool_false;
5550 /* Should the clusters be merged based on the cluster schedule
5551 * in the current (and only) band of "merge_graph"?
5552 * "graph" is the original dependence graph, while "c" records
5553 * which SCCs are involved in the latest merge.
5555 * If the current band is empty, then the clusters should not be merged.
5557 * If the band depth should be maximized and the merge schedule
5558 * is incomplete (meaning that the dimension of some of the schedule
5559 * bands in the original schedule will be reduced), then the clusters
5560 * should not be merged.
5562 * If the schedule_maximize_coincidence option is set, then check that
5563 * the number of coincident schedule dimensions is not reduced.
5565 * Finally, only allow the merge if at least one proximity
5566 * constraint is optimized.
5568 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
5569 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5571 if (merge_graph->n_total_row == merge_graph->band_start)
5572 return isl_bool_false;
5574 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
5575 merge_graph->n_total_row < merge_graph->maxvar)
5576 return isl_bool_false;
5578 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
5579 isl_bool ok;
5581 ok = ok_to_merge_coincident(c, merge_graph);
5582 if (ok < 0 || !ok)
5583 return ok;
5586 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
5589 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
5590 * of the schedule in "node" and return the result.
5592 * That is, essentially compute
5594 * T * N(first:first+n-1)
5596 * taking into account the constant term and the parameter coefficients
5597 * in "t_node".
5599 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
5600 struct isl_sched_node *t_node, struct isl_sched_node *node,
5601 int first, int n)
5603 int i, j;
5604 isl_mat *t;
5605 int n_row, n_col, n_param, n_var;
5607 n_param = node->nparam;
5608 n_var = node->nvar;
5609 n_row = isl_mat_rows(t_node->sched);
5610 n_col = isl_mat_cols(node->sched);
5611 t = isl_mat_alloc(ctx, n_row, n_col);
5612 if (!t)
5613 return NULL;
5614 for (i = 0; i < n_row; ++i) {
5615 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
5616 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
5617 for (j = 0; j < n; ++j)
5618 isl_seq_addmul(t->row[i],
5619 t_node->sched->row[i][1 + n_param + j],
5620 node->sched->row[first + j],
5621 1 + n_param + n_var);
5623 return t;
5626 /* Apply the cluster schedule in "t_node" to the current band
5627 * schedule of the nodes in "graph".
5629 * In particular, replace the rows starting at band_start
5630 * by the result of applying the cluster schedule in "t_node"
5631 * to the original rows.
5633 * The coincidence of the schedule is determined by the coincidence
5634 * of the cluster schedule.
5636 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
5637 struct isl_sched_node *t_node)
5639 int i, j;
5640 int n_new;
5641 int start, n;
5643 start = graph->band_start;
5644 n = graph->n_total_row - start;
5646 n_new = isl_mat_rows(t_node->sched);
5647 for (i = 0; i < graph->n; ++i) {
5648 struct isl_sched_node *node = &graph->node[i];
5649 isl_mat *t;
5651 t = node_transformation(ctx, t_node, node, start, n);
5652 node->sched = isl_mat_drop_rows(node->sched, start, n);
5653 node->sched = isl_mat_concat(node->sched, t);
5654 node->sched_map = isl_map_free(node->sched_map);
5655 if (!node->sched)
5656 return isl_stat_error;
5657 for (j = 0; j < n_new; ++j)
5658 node->coincident[start + j] = t_node->coincident[j];
5660 graph->n_total_row -= n;
5661 graph->n_row -= n;
5662 graph->n_total_row += n_new;
5663 graph->n_row += n_new;
5665 return isl_stat_ok;
5668 /* Merge the clusters marked for merging in "c" into a single
5669 * cluster using the cluster schedule in the current band of "merge_graph".
5670 * The representative SCC for the new cluster is the SCC with
5671 * the smallest index.
5673 * The current band schedule of each SCC in the new cluster is obtained
5674 * by applying the schedule of the corresponding original cluster
5675 * to the original band schedule.
5676 * All SCCs in the new cluster have the same number of schedule rows.
5678 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
5679 struct isl_sched_graph *merge_graph)
5681 int i;
5682 int cluster = -1;
5683 isl_space *space;
5685 for (i = 0; i < c->n; ++i) {
5686 struct isl_sched_node *node;
5688 if (!c->scc_in_merge[i])
5689 continue;
5690 if (cluster < 0)
5691 cluster = i;
5692 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
5693 if (!space)
5694 return isl_stat_error;
5695 node = graph_find_node(ctx, merge_graph, space);
5696 isl_space_free(space);
5697 if (!node)
5698 isl_die(ctx, isl_error_internal,
5699 "unable to find cluster",
5700 return isl_stat_error);
5701 if (transform(ctx, &c->scc[i], node) < 0)
5702 return isl_stat_error;
5703 c->scc_cluster[i] = cluster;
5706 return isl_stat_ok;
5709 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
5710 * by scheduling the current cluster bands with respect to each other.
5712 * Construct a dependence graph with a space for each cluster and
5713 * with the coordinates of each space corresponding to the schedule
5714 * dimensions of the current band of that cluster.
5715 * Construct a cluster schedule in this cluster dependence graph and
5716 * apply it to the current cluster bands if it is applicable
5717 * according to ok_to_merge.
5719 * If the number of remaining schedule dimensions in a cluster
5720 * with a non-maximal current schedule dimension is greater than
5721 * the number of remaining schedule dimensions in clusters
5722 * with a maximal current schedule dimension, then restrict
5723 * the number of rows to be computed in the cluster schedule
5724 * to the minimal such non-maximal current schedule dimension.
5725 * Do this by adjusting merge_graph.maxvar.
5727 * Return isl_bool_true if the clusters have effectively been merged
5728 * into a single cluster.
5730 * Note that since the standard scheduling algorithm minimizes the maximal
5731 * distance over proximity constraints, the proximity constraints between
5732 * the merged clusters may not be optimized any further than what is
5733 * sufficient to bring the distances within the limits of the internal
5734 * proximity constraints inside the individual clusters.
5735 * It may therefore make sense to perform an additional translation step
5736 * to bring the clusters closer to each other, while maintaining
5737 * the linear part of the merging schedule found using the standard
5738 * scheduling algorithm.
5740 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
5741 struct isl_clustering *c)
5743 struct isl_sched_graph merge_graph = { 0 };
5744 isl_bool merged;
5746 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
5747 goto error;
5749 if (compute_maxvar(&merge_graph) < 0)
5750 goto error;
5751 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
5752 goto error;
5753 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
5754 goto error;
5755 merged = ok_to_merge(ctx, graph, c, &merge_graph);
5756 if (merged && merge(ctx, c, &merge_graph) < 0)
5757 goto error;
5759 graph_free(ctx, &merge_graph);
5760 return merged;
5761 error:
5762 graph_free(ctx, &merge_graph);
5763 return isl_bool_error;
5766 /* Is there any edge marked "no_merge" between two SCCs that are
5767 * about to be merged (i.e., that are set in "scc_in_merge")?
5768 * "merge_edge" is the proximity edge along which the clusters of SCCs
5769 * are going to be merged.
5771 * If there is any edge between two SCCs with a negative weight,
5772 * while the weight of "merge_edge" is non-negative, then this
5773 * means that the edge was postponed. "merge_edge" should then
5774 * also be postponed since merging along the edge with negative weight should
5775 * be postponed until all edges with non-negative weight have been tried.
5776 * Replace the weight of "merge_edge" by a negative weight as well and
5777 * tell the caller not to attempt a merge.
5779 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
5780 struct isl_sched_edge *merge_edge)
5782 int i;
5784 for (i = 0; i < graph->n_edge; ++i) {
5785 struct isl_sched_edge *edge = &graph->edge[i];
5787 if (!scc_in_merge[edge->src->scc])
5788 continue;
5789 if (!scc_in_merge[edge->dst->scc])
5790 continue;
5791 if (edge->no_merge)
5792 return 1;
5793 if (merge_edge->weight >= 0 && edge->weight < 0) {
5794 merge_edge->weight -= graph->max_weight + 1;
5795 return 1;
5799 return 0;
5802 /* Merge the two clusters in "c" connected by the edge in "graph"
5803 * with index "edge" into a single cluster.
5804 * If it turns out to be impossible to merge these two clusters,
5805 * then mark the edge as "no_merge" such that it will not be
5806 * considered again.
5808 * First mark all SCCs that need to be merged. This includes the SCCs
5809 * in the two clusters, but it may also include the SCCs
5810 * of intermediate clusters.
5811 * If there is already a no_merge edge between any pair of such SCCs,
5812 * then simply mark the current edge as no_merge as well.
5813 * Likewise, if any of those edges was postponed by has_bounded_distances,
5814 * then postpone the current edge as well.
5815 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
5816 * if the clusters did not end up getting merged, unless the non-merge
5817 * is due to the fact that the edge was postponed. This postponement
5818 * can be recognized by a change in weight (from non-negative to negative).
5820 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
5821 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
5823 isl_bool merged;
5824 int edge_weight = graph->edge[edge].weight;
5826 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
5827 return isl_stat_error;
5829 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
5830 merged = isl_bool_false;
5831 else
5832 merged = try_merge(ctx, graph, c);
5833 if (merged < 0)
5834 return isl_stat_error;
5835 if (!merged && edge_weight == graph->edge[edge].weight)
5836 graph->edge[edge].no_merge = 1;
5838 return isl_stat_ok;
5841 /* Does "node" belong to the cluster identified by "cluster"?
5843 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
5845 return node->cluster == cluster;
5848 /* Does "edge" connect two nodes belonging to the cluster
5849 * identified by "cluster"?
5851 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
5853 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
5856 /* Swap the schedule of "node1" and "node2".
5857 * Both nodes have been derived from the same node in a common parent graph.
5858 * Since the "coincident" field is shared with that node
5859 * in the parent graph, there is no need to also swap this field.
5861 static void swap_sched(struct isl_sched_node *node1,
5862 struct isl_sched_node *node2)
5864 isl_mat *sched;
5865 isl_map *sched_map;
5867 sched = node1->sched;
5868 node1->sched = node2->sched;
5869 node2->sched = sched;
5871 sched_map = node1->sched_map;
5872 node1->sched_map = node2->sched_map;
5873 node2->sched_map = sched_map;
5876 /* Copy the current band schedule from the SCCs that form the cluster
5877 * with index "pos" to the actual cluster at position "pos".
5878 * By construction, the index of the first SCC that belongs to the cluster
5879 * is also "pos".
5881 * The order of the nodes inside both the SCCs and the cluster
5882 * is assumed to be same as the order in the original "graph".
5884 * Since the SCC graphs will no longer be used after this function,
5885 * the schedules are actually swapped rather than copied.
5887 static isl_stat copy_partial(struct isl_sched_graph *graph,
5888 struct isl_clustering *c, int pos)
5890 int i, j;
5892 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
5893 c->cluster[pos].n_row = c->scc[pos].n_row;
5894 c->cluster[pos].maxvar = c->scc[pos].maxvar;
5895 j = 0;
5896 for (i = 0; i < graph->n; ++i) {
5897 int k;
5898 int s;
5900 if (graph->node[i].cluster != pos)
5901 continue;
5902 s = graph->node[i].scc;
5903 k = c->scc_node[s]++;
5904 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
5905 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
5906 c->cluster[pos].maxvar = c->scc[s].maxvar;
5907 ++j;
5910 return isl_stat_ok;
5913 /* Is there a (conditional) validity dependence from node[j] to node[i],
5914 * forcing node[i] to follow node[j] or do the nodes belong to the same
5915 * cluster?
5917 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
5919 struct isl_sched_graph *graph = user;
5921 if (graph->node[i].cluster == graph->node[j].cluster)
5922 return isl_bool_true;
5923 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5926 /* Extract the merged clusters of SCCs in "graph", sort them, and
5927 * store them in c->clusters. Update c->scc_cluster accordingly.
5929 * First keep track of the cluster containing the SCC to which a node
5930 * belongs in the node itself.
5931 * Then extract the clusters into c->clusters, copying the current
5932 * band schedule from the SCCs that belong to the cluster.
5933 * Do this only once per cluster.
5935 * Finally, topologically sort the clusters and update c->scc_cluster
5936 * to match the new scc numbering. While the SCCs were originally
5937 * sorted already, some SCCs that depend on some other SCCs may
5938 * have been merged with SCCs that appear before these other SCCs.
5939 * A reordering may therefore be required.
5941 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
5942 struct isl_clustering *c)
5944 int i;
5946 for (i = 0; i < graph->n; ++i)
5947 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
5949 for (i = 0; i < graph->scc; ++i) {
5950 if (c->scc_cluster[i] != i)
5951 continue;
5952 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
5953 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
5954 return isl_stat_error;
5955 c->cluster[i].src_scc = -1;
5956 c->cluster[i].dst_scc = -1;
5957 if (copy_partial(graph, c, i) < 0)
5958 return isl_stat_error;
5961 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
5962 return isl_stat_error;
5963 for (i = 0; i < graph->n; ++i)
5964 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
5966 return isl_stat_ok;
5969 /* Compute weights on the proximity edges of "graph" that can
5970 * be used by find_proximity to find the most appropriate
5971 * proximity edge to use to merge two clusters in "c".
5972 * The weights are also used by has_bounded_distances to determine
5973 * whether the merge should be allowed.
5974 * Store the maximum of the computed weights in graph->max_weight.
5976 * The computed weight is a measure for the number of remaining schedule
5977 * dimensions that can still be completely aligned.
5978 * In particular, compute the number of equalities between
5979 * input dimensions and output dimensions in the proximity constraints.
5980 * The directions that are already handled by outer schedule bands
5981 * are projected out prior to determining this number.
5983 * Edges that will never be considered by find_proximity are ignored.
5985 static isl_stat compute_weights(struct isl_sched_graph *graph,
5986 struct isl_clustering *c)
5988 int i;
5990 graph->max_weight = 0;
5992 for (i = 0; i < graph->n_edge; ++i) {
5993 struct isl_sched_edge *edge = &graph->edge[i];
5994 struct isl_sched_node *src = edge->src;
5995 struct isl_sched_node *dst = edge->dst;
5996 isl_basic_map *hull;
5997 int n_in, n_out;
5999 if (!is_proximity(edge))
6000 continue;
6001 if (bad_cluster(&c->scc[edge->src->scc]) ||
6002 bad_cluster(&c->scc[edge->dst->scc]))
6003 continue;
6004 if (c->scc_cluster[edge->dst->scc] ==
6005 c->scc_cluster[edge->src->scc])
6006 continue;
6008 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6009 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6010 isl_mat_copy(src->ctrans));
6011 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6012 isl_mat_copy(dst->ctrans));
6013 hull = isl_basic_map_project_out(hull,
6014 isl_dim_in, 0, src->rank);
6015 hull = isl_basic_map_project_out(hull,
6016 isl_dim_out, 0, dst->rank);
6017 hull = isl_basic_map_remove_divs(hull);
6018 n_in = isl_basic_map_dim(hull, isl_dim_in);
6019 n_out = isl_basic_map_dim(hull, isl_dim_out);
6020 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6021 isl_dim_in, 0, n_in);
6022 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6023 isl_dim_out, 0, n_out);
6024 if (!hull)
6025 return isl_stat_error;
6026 edge->weight = hull->n_eq;
6027 isl_basic_map_free(hull);
6029 if (edge->weight > graph->max_weight)
6030 graph->max_weight = edge->weight;
6033 return isl_stat_ok;
6036 /* Call compute_schedule_finish_band on each of the clusters in "c"
6037 * in their topological order. This order is determined by the scc
6038 * fields of the nodes in "graph".
6039 * Combine the results in a sequence expressing the topological order.
6041 * If there is only one cluster left, then there is no need to introduce
6042 * a sequence node. Also, in this case, the cluster necessarily contains
6043 * the SCC at position 0 in the original graph and is therefore also
6044 * stored in the first cluster of "c".
6046 static __isl_give isl_schedule_node *finish_bands_clustering(
6047 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6048 struct isl_clustering *c)
6050 int i;
6051 isl_ctx *ctx;
6052 isl_union_set_list *filters;
6054 if (graph->scc == 1)
6055 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6057 ctx = isl_schedule_node_get_ctx(node);
6059 filters = extract_sccs(ctx, graph);
6060 node = isl_schedule_node_insert_sequence(node, filters);
6062 for (i = 0; i < graph->scc; ++i) {
6063 int j = c->scc_cluster[i];
6064 node = isl_schedule_node_child(node, i);
6065 node = isl_schedule_node_child(node, 0);
6066 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6067 node = isl_schedule_node_parent(node);
6068 node = isl_schedule_node_parent(node);
6071 return node;
6074 /* Compute a schedule for a connected dependence graph by first considering
6075 * each strongly connected component (SCC) in the graph separately and then
6076 * incrementally combining them into clusters.
6077 * Return the updated schedule node.
6079 * Initially, each cluster consists of a single SCC, each with its
6080 * own band schedule. The algorithm then tries to merge pairs
6081 * of clusters along a proximity edge until no more suitable
6082 * proximity edges can be found. During this merging, the schedule
6083 * is maintained in the individual SCCs.
6084 * After the merging is completed, the full resulting clusters
6085 * are extracted and in finish_bands_clustering,
6086 * compute_schedule_finish_band is called on each of them to integrate
6087 * the band into "node" and to continue the computation.
6089 * compute_weights initializes the weights that are used by find_proximity.
6091 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6092 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6094 isl_ctx *ctx;
6095 struct isl_clustering c;
6096 int i;
6098 ctx = isl_schedule_node_get_ctx(node);
6100 if (clustering_init(ctx, &c, graph) < 0)
6101 goto error;
6103 if (compute_weights(graph, &c) < 0)
6104 goto error;
6106 for (;;) {
6107 i = find_proximity(graph, &c);
6108 if (i < 0)
6109 goto error;
6110 if (i >= graph->n_edge)
6111 break;
6112 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6113 goto error;
6116 if (extract_clusters(ctx, graph, &c) < 0)
6117 goto error;
6119 node = finish_bands_clustering(node, graph, &c);
6121 clustering_free(ctx, &c);
6122 return node;
6123 error:
6124 clustering_free(ctx, &c);
6125 return isl_schedule_node_free(node);
6128 /* Compute a schedule for a connected dependence graph and return
6129 * the updated schedule node.
6131 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6132 * as many validity dependences as possible. When all validity dependences
6133 * are satisfied we extend the schedule to a full-dimensional schedule.
6135 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6136 * depending on whether the user has selected the option to try and
6137 * compute a schedule for the entire (weakly connected) component first.
6138 * If there is only a single strongly connected component (SCC), then
6139 * there is no point in trying to combine SCCs
6140 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6141 * is called instead.
6143 static __isl_give isl_schedule_node *compute_schedule_wcc(
6144 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6146 isl_ctx *ctx;
6148 if (!node)
6149 return NULL;
6151 ctx = isl_schedule_node_get_ctx(node);
6152 if (detect_sccs(ctx, graph) < 0)
6153 return isl_schedule_node_free(node);
6155 if (compute_maxvar(graph) < 0)
6156 return isl_schedule_node_free(node);
6158 if (need_feautrier_step(ctx, graph))
6159 return compute_schedule_wcc_feautrier(node, graph);
6161 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6162 return compute_schedule_wcc_whole(node, graph);
6163 else
6164 return compute_schedule_wcc_clustering(node, graph);
6167 /* Compute a schedule for each group of nodes identified by node->scc
6168 * separately and then combine them in a sequence node (or as set node
6169 * if graph->weak is set) inserted at position "node" of the schedule tree.
6170 * Return the updated schedule node.
6172 * If "wcc" is set then each of the groups belongs to a single
6173 * weakly connected component in the dependence graph so that
6174 * there is no need for compute_sub_schedule to look for weakly
6175 * connected components.
6177 static __isl_give isl_schedule_node *compute_component_schedule(
6178 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6179 int wcc)
6181 int component;
6182 isl_ctx *ctx;
6183 isl_union_set_list *filters;
6185 if (!node)
6186 return NULL;
6187 ctx = isl_schedule_node_get_ctx(node);
6189 filters = extract_sccs(ctx, graph);
6190 if (graph->weak)
6191 node = isl_schedule_node_insert_set(node, filters);
6192 else
6193 node = isl_schedule_node_insert_sequence(node, filters);
6195 for (component = 0; component < graph->scc; ++component) {
6196 node = isl_schedule_node_child(node, component);
6197 node = isl_schedule_node_child(node, 0);
6198 node = compute_sub_schedule(node, ctx, graph,
6199 &node_scc_exactly,
6200 &edge_scc_exactly, component, wcc);
6201 node = isl_schedule_node_parent(node);
6202 node = isl_schedule_node_parent(node);
6205 return node;
6208 /* Compute a schedule for the given dependence graph and insert it at "node".
6209 * Return the updated schedule node.
6211 * We first check if the graph is connected (through validity and conditional
6212 * validity dependences) and, if not, compute a schedule
6213 * for each component separately.
6214 * If the schedule_serialize_sccs option is set, then we check for strongly
6215 * connected components instead and compute a separate schedule for
6216 * each such strongly connected component.
6218 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6219 struct isl_sched_graph *graph)
6221 isl_ctx *ctx;
6223 if (!node)
6224 return NULL;
6226 ctx = isl_schedule_node_get_ctx(node);
6227 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6228 if (detect_sccs(ctx, graph) < 0)
6229 return isl_schedule_node_free(node);
6230 } else {
6231 if (detect_wccs(ctx, graph) < 0)
6232 return isl_schedule_node_free(node);
6235 if (graph->scc > 1)
6236 return compute_component_schedule(node, graph, 1);
6238 return compute_schedule_wcc(node, graph);
6241 /* Compute a schedule on sc->domain that respects the given schedule
6242 * constraints.
6244 * In particular, the schedule respects all the validity dependences.
6245 * If the default isl scheduling algorithm is used, it tries to minimize
6246 * the dependence distances over the proximity dependences.
6247 * If Feautrier's scheduling algorithm is used, the proximity dependence
6248 * distances are only minimized during the extension to a full-dimensional
6249 * schedule.
6251 * If there are any condition and conditional validity dependences,
6252 * then the conditional validity dependences may be violated inside
6253 * a tilable band, provided they have no adjacent non-local
6254 * condition dependences.
6256 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6257 __isl_take isl_schedule_constraints *sc)
6259 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6260 struct isl_sched_graph graph = { 0 };
6261 isl_schedule *sched;
6262 isl_schedule_node *node;
6263 isl_union_set *domain;
6265 sc = isl_schedule_constraints_align_params(sc);
6267 domain = isl_schedule_constraints_get_domain(sc);
6268 if (isl_union_set_n_set(domain) == 0) {
6269 isl_schedule_constraints_free(sc);
6270 return isl_schedule_from_domain(domain);
6273 if (graph_init(&graph, sc) < 0)
6274 domain = isl_union_set_free(domain);
6276 node = isl_schedule_node_from_domain(domain);
6277 node = isl_schedule_node_child(node, 0);
6278 if (graph.n > 0)
6279 node = compute_schedule(node, &graph);
6280 sched = isl_schedule_node_get_schedule(node);
6281 isl_schedule_node_free(node);
6283 graph_free(ctx, &graph);
6284 isl_schedule_constraints_free(sc);
6286 return sched;
6289 /* Compute a schedule for the given union of domains that respects
6290 * all the validity dependences and minimizes
6291 * the dependence distances over the proximity dependences.
6293 * This function is kept for backward compatibility.
6295 __isl_give isl_schedule *isl_union_set_compute_schedule(
6296 __isl_take isl_union_set *domain,
6297 __isl_take isl_union_map *validity,
6298 __isl_take isl_union_map *proximity)
6300 isl_schedule_constraints *sc;
6302 sc = isl_schedule_constraints_on_domain(domain);
6303 sc = isl_schedule_constraints_set_validity(sc, validity);
6304 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6306 return isl_schedule_constraints_compute_schedule(sc);