isl_scheduler.c: detect_ccs: return isl_stat
[isl.git] / isl_scheduler.c
blobb5e215ec9f57e925f4fffe6f6c8a592c6e037261
1 /*
2 * Copyright 2011 INRIA Saclay
3 * Copyright 2012-2014 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
5 * Copyright 2016 INRIA Paris
6 * Copyright 2017 Sven Verdoolaege
8 * Use of this software is governed by the MIT license
10 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
11 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
12 * 91893 Orsay, France
13 * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
14 * and Centre de Recherche Inria de Paris, 2 rue Simone Iff - Voie DQ12,
15 * CS 42112, 75589 Paris Cedex 12, France
18 #include <isl_ctx_private.h>
19 #include <isl_map_private.h>
20 #include <isl_space_private.h>
21 #include <isl_aff_private.h>
22 #include <isl/hash.h>
23 #include <isl/constraint.h>
24 #include <isl/schedule.h>
25 #include <isl_schedule_constraints.h>
26 #include <isl/schedule_node.h>
27 #include <isl_mat_private.h>
28 #include <isl_vec_private.h>
29 #include <isl/set.h>
30 #include <isl_union_set_private.h>
31 #include <isl_seq.h>
32 #include <isl_tab.h>
33 #include <isl_dim_map.h>
34 #include <isl/map_to_basic_set.h>
35 #include <isl_sort.h>
36 #include <isl_options_private.h>
37 #include <isl_tarjan.h>
38 #include <isl_morph.h>
39 #include <isl/ilp.h>
40 #include <isl_val_private.h>
43 * The scheduling algorithm implemented in this file was inspired by
44 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
45 * Parallelization and Locality Optimization in the Polyhedral Model".
47 * For a detailed description of the variant implemented in isl,
48 * see Verdoolaege and Janssens, "Scheduling for PPCG" (2017).
52 /* Internal information about a node that is used during the construction
53 * of a schedule.
54 * space represents the original space in which the domain lives;
55 * that is, the space is not affected by compression
56 * sched is a matrix representation of the schedule being constructed
57 * for this node; if compressed is set, then this schedule is
58 * defined over the compressed domain space
59 * sched_map is an isl_map representation of the same (partial) schedule
60 * sched_map may be NULL; if compressed is set, then this map
61 * is defined over the uncompressed domain space
62 * rank is the number of linearly independent rows in the linear part
63 * of sched
64 * the rows of "vmap" represent a change of basis for the node
65 * variables; the first rank rows span the linear part of
66 * the schedule rows; the remaining rows are linearly independent
67 * the rows of "indep" represent linear combinations of the schedule
68 * coefficients that are non-zero when the schedule coefficients are
69 * linearly independent of previously computed schedule rows.
70 * start is the first variable in the LP problem in the sequences that
71 * represents the schedule coefficients of this node
72 * nvar is the dimension of the (compressed) domain
73 * nparam is the number of parameters or 0 if we are not constructing
74 * a parametric schedule
76 * If compressed is set, then hull represents the constraints
77 * that were used to derive the compression, while compress and
78 * decompress map the original space to the compressed space and
79 * vice versa.
81 * scc is the index of SCC (or WCC) this node belongs to
83 * "cluster" is only used inside extract_clusters and identifies
84 * the cluster of SCCs that the node belongs to.
86 * coincident contains a boolean for each of the rows of the schedule,
87 * indicating whether the corresponding scheduling dimension satisfies
88 * the coincidence constraints in the sense that the corresponding
89 * dependence distances are zero.
91 * If the schedule_treat_coalescing option is set, then
92 * "sizes" contains the sizes of the (compressed) instance set
93 * in each direction. If there is no fixed size in a given direction,
94 * then the corresponding size value is set to infinity.
95 * If the schedule_treat_coalescing option or the schedule_max_coefficient
96 * option is set, then "max" contains the maximal values for
97 * schedule coefficients of the (compressed) variables. If no bound
98 * needs to be imposed on a particular variable, then the corresponding
99 * value is negative.
100 * If not NULL, then "bounds" contains a non-parametric set
101 * in the compressed space that is bounded by the size in each direction.
103 struct isl_sched_node {
104 isl_space *space;
105 int compressed;
106 isl_set *hull;
107 isl_multi_aff *compress;
108 isl_multi_aff *decompress;
109 isl_mat *sched;
110 isl_map *sched_map;
111 int rank;
112 isl_mat *indep;
113 isl_mat *vmap;
114 int start;
115 int nvar;
116 int nparam;
118 int scc;
119 int cluster;
121 int *coincident;
123 isl_multi_val *sizes;
124 isl_basic_set *bounds;
125 isl_vec *max;
128 static int node_has_tuples(const void *entry, const void *val)
130 struct isl_sched_node *node = (struct isl_sched_node *)entry;
131 isl_space *space = (isl_space *) val;
133 return isl_space_has_equal_tuples(node->space, space);
136 static int node_scc_exactly(struct isl_sched_node *node, int scc)
138 return node->scc == scc;
141 static int node_scc_at_most(struct isl_sched_node *node, int scc)
143 return node->scc <= scc;
146 static int node_scc_at_least(struct isl_sched_node *node, int scc)
148 return node->scc >= scc;
151 /* An edge in the dependence graph. An edge may be used to
152 * ensure validity of the generated schedule, to minimize the dependence
153 * distance or both
155 * map is the dependence relation, with i -> j in the map if j depends on i
156 * tagged_condition and tagged_validity contain the union of all tagged
157 * condition or conditional validity dependence relations that
158 * specialize the dependence relation "map"; that is,
159 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
160 * or "tagged_validity", then i -> j is an element of "map".
161 * If these fields are NULL, then they represent the empty relation.
162 * src is the source node
163 * dst is the sink node
165 * types is a bit vector containing the types of this edge.
166 * validity is set if the edge is used to ensure correctness
167 * coincidence is used to enforce zero dependence distances
168 * proximity is set if the edge is used to minimize dependence distances
169 * condition is set if the edge represents a condition
170 * for a conditional validity schedule constraint
171 * local can only be set for condition edges and indicates that
172 * the dependence distance over the edge should be zero
173 * conditional_validity is set if the edge is used to conditionally
174 * ensure correctness
176 * For validity edges, start and end mark the sequence of inequality
177 * constraints in the LP problem that encode the validity constraint
178 * corresponding to this edge.
180 * During clustering, an edge may be marked "no_merge" if it should
181 * not be used to merge clusters.
182 * The weight is also only used during clustering and it is
183 * an indication of how many schedule dimensions on either side
184 * of the schedule constraints can be aligned.
185 * If the weight is negative, then this means that this edge was postponed
186 * by has_bounded_distances or any_no_merge. The original weight can
187 * be retrieved by adding 1 + graph->max_weight, with "graph"
188 * the graph containing this edge.
190 struct isl_sched_edge {
191 isl_map *map;
192 isl_union_map *tagged_condition;
193 isl_union_map *tagged_validity;
195 struct isl_sched_node *src;
196 struct isl_sched_node *dst;
198 unsigned types;
200 int start;
201 int end;
203 int no_merge;
204 int weight;
207 /* Is "edge" marked as being of type "type"?
209 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
211 return ISL_FL_ISSET(edge->types, 1 << type);
214 /* Mark "edge" as being of type "type".
216 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
218 ISL_FL_SET(edge->types, 1 << type);
221 /* No longer mark "edge" as being of type "type"?
223 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
225 ISL_FL_CLR(edge->types, 1 << type);
228 /* Is "edge" marked as a validity edge?
230 static int is_validity(struct isl_sched_edge *edge)
232 return is_type(edge, isl_edge_validity);
235 /* Mark "edge" as a validity edge.
237 static void set_validity(struct isl_sched_edge *edge)
239 set_type(edge, isl_edge_validity);
242 /* Is "edge" marked as a proximity edge?
244 static int is_proximity(struct isl_sched_edge *edge)
246 return is_type(edge, isl_edge_proximity);
249 /* Is "edge" marked as a local edge?
251 static int is_local(struct isl_sched_edge *edge)
253 return is_type(edge, isl_edge_local);
256 /* Mark "edge" as a local edge.
258 static void set_local(struct isl_sched_edge *edge)
260 set_type(edge, isl_edge_local);
263 /* No longer mark "edge" as a local edge.
265 static void clear_local(struct isl_sched_edge *edge)
267 clear_type(edge, isl_edge_local);
270 /* Is "edge" marked as a coincidence edge?
272 static int is_coincidence(struct isl_sched_edge *edge)
274 return is_type(edge, isl_edge_coincidence);
277 /* Is "edge" marked as a condition edge?
279 static int is_condition(struct isl_sched_edge *edge)
281 return is_type(edge, isl_edge_condition);
284 /* Is "edge" marked as a conditional validity edge?
286 static int is_conditional_validity(struct isl_sched_edge *edge)
288 return is_type(edge, isl_edge_conditional_validity);
291 /* Is "edge" of a type that can appear multiple times between
292 * the same pair of nodes?
294 * Condition edges and conditional validity edges may have tagged
295 * dependence relations, in which case an edge is added for each
296 * pair of tags.
298 static int is_multi_edge_type(struct isl_sched_edge *edge)
300 return is_condition(edge) || is_conditional_validity(edge);
303 /* Internal information about the dependence graph used during
304 * the construction of the schedule.
306 * intra_hmap is a cache, mapping dependence relations to their dual,
307 * for dependences from a node to itself, possibly without
308 * coefficients for the parameters
309 * intra_hmap_param is a cache, mapping dependence relations to their dual,
310 * for dependences from a node to itself, including coefficients
311 * for the parameters
312 * inter_hmap is a cache, mapping dependence relations to their dual,
313 * for dependences between distinct nodes
314 * if compression is involved then the key for these maps
315 * is the original, uncompressed dependence relation, while
316 * the value is the dual of the compressed dependence relation.
318 * n is the number of nodes
319 * node is the list of nodes
320 * maxvar is the maximal number of variables over all nodes
321 * max_row is the allocated number of rows in the schedule
322 * n_row is the current (maximal) number of linearly independent
323 * rows in the node schedules
324 * n_total_row is the current number of rows in the node schedules
325 * band_start is the starting row in the node schedules of the current band
326 * root is set to the the original dependence graph from which this graph
327 * is derived through splitting. If this graph is not the result of
328 * splitting, then the root field points to the graph itself.
330 * sorted contains a list of node indices sorted according to the
331 * SCC to which a node belongs
333 * n_edge is the number of edges
334 * edge is the list of edges
335 * max_edge contains the maximal number of edges of each type;
336 * in particular, it contains the number of edges in the inital graph.
337 * edge_table contains pointers into the edge array, hashed on the source
338 * and sink spaces; there is one such table for each type;
339 * a given edge may be referenced from more than one table
340 * if the corresponding relation appears in more than one of the
341 * sets of dependences; however, for each type there is only
342 * a single edge between a given pair of source and sink space
343 * in the entire graph
345 * node_table contains pointers into the node array, hashed on the space tuples
347 * region contains a list of variable sequences that should be non-trivial
349 * lp contains the (I)LP problem used to obtain new schedule rows
351 * src_scc and dst_scc are the source and sink SCCs of an edge with
352 * conflicting constraints
354 * scc represents the number of components
355 * weak is set if the components are weakly connected
357 * max_weight is used during clustering and represents the maximal
358 * weight of the relevant proximity edges.
360 struct isl_sched_graph {
361 isl_map_to_basic_set *intra_hmap;
362 isl_map_to_basic_set *intra_hmap_param;
363 isl_map_to_basic_set *inter_hmap;
365 struct isl_sched_node *node;
366 int n;
367 int maxvar;
368 int max_row;
369 int n_row;
371 int *sorted;
373 int n_total_row;
374 int band_start;
376 struct isl_sched_graph *root;
378 struct isl_sched_edge *edge;
379 int n_edge;
380 int max_edge[isl_edge_last + 1];
381 struct isl_hash_table *edge_table[isl_edge_last + 1];
383 struct isl_hash_table *node_table;
384 struct isl_trivial_region *region;
386 isl_basic_set *lp;
388 int src_scc;
389 int dst_scc;
391 int scc;
392 int weak;
394 int max_weight;
397 /* Initialize node_table based on the list of nodes.
399 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
401 int i;
403 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
404 if (!graph->node_table)
405 return -1;
407 for (i = 0; i < graph->n; ++i) {
408 struct isl_hash_table_entry *entry;
409 uint32_t hash;
411 hash = isl_space_get_tuple_hash(graph->node[i].space);
412 entry = isl_hash_table_find(ctx, graph->node_table, hash,
413 &node_has_tuples,
414 graph->node[i].space, 1);
415 if (!entry)
416 return -1;
417 entry->data = &graph->node[i];
420 return 0;
423 /* Return a pointer to the node that lives within the given space,
424 * or NULL if there is no such node.
426 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
427 struct isl_sched_graph *graph, __isl_keep isl_space *space)
429 struct isl_hash_table_entry *entry;
430 uint32_t hash;
432 hash = isl_space_get_tuple_hash(space);
433 entry = isl_hash_table_find(ctx, graph->node_table, hash,
434 &node_has_tuples, space, 0);
436 return entry ? entry->data : NULL;
439 /* Is "node" a node in "graph"?
441 static int is_node(struct isl_sched_graph *graph,
442 struct isl_sched_node *node)
444 return node && node >= &graph->node[0] && node < &graph->node[graph->n];
447 static int edge_has_src_and_dst(const void *entry, const void *val)
449 const struct isl_sched_edge *edge = entry;
450 const struct isl_sched_edge *temp = val;
452 return edge->src == temp->src && edge->dst == temp->dst;
455 /* Add the given edge to graph->edge_table[type].
457 static isl_stat graph_edge_table_add(isl_ctx *ctx,
458 struct isl_sched_graph *graph, enum isl_edge_type type,
459 struct isl_sched_edge *edge)
461 struct isl_hash_table_entry *entry;
462 uint32_t hash;
464 hash = isl_hash_init();
465 hash = isl_hash_builtin(hash, edge->src);
466 hash = isl_hash_builtin(hash, edge->dst);
467 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
468 &edge_has_src_and_dst, edge, 1);
469 if (!entry)
470 return isl_stat_error;
471 entry->data = edge;
473 return isl_stat_ok;
476 /* Add "edge" to all relevant edge tables.
477 * That is, for every type of the edge, add it to the corresponding table.
479 static isl_stat graph_edge_tables_add(isl_ctx *ctx,
480 struct isl_sched_graph *graph, struct isl_sched_edge *edge)
482 enum isl_edge_type t;
484 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
485 if (!is_type(edge, t))
486 continue;
487 if (graph_edge_table_add(ctx, graph, t, edge) < 0)
488 return isl_stat_error;
491 return isl_stat_ok;
494 /* Allocate the edge_tables based on the maximal number of edges of
495 * each type.
497 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
499 int i;
501 for (i = 0; i <= isl_edge_last; ++i) {
502 graph->edge_table[i] = isl_hash_table_alloc(ctx,
503 graph->max_edge[i]);
504 if (!graph->edge_table[i])
505 return -1;
508 return 0;
511 /* If graph->edge_table[type] contains an edge from the given source
512 * to the given destination, then return the hash table entry of this edge.
513 * Otherwise, return NULL.
515 static struct isl_hash_table_entry *graph_find_edge_entry(
516 struct isl_sched_graph *graph,
517 enum isl_edge_type type,
518 struct isl_sched_node *src, struct isl_sched_node *dst)
520 isl_ctx *ctx = isl_space_get_ctx(src->space);
521 uint32_t hash;
522 struct isl_sched_edge temp = { .src = src, .dst = dst };
524 hash = isl_hash_init();
525 hash = isl_hash_builtin(hash, temp.src);
526 hash = isl_hash_builtin(hash, temp.dst);
527 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
528 &edge_has_src_and_dst, &temp, 0);
532 /* If graph->edge_table[type] contains an edge from the given source
533 * to the given destination, then return this edge.
534 * Otherwise, return NULL.
536 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
537 enum isl_edge_type type,
538 struct isl_sched_node *src, struct isl_sched_node *dst)
540 struct isl_hash_table_entry *entry;
542 entry = graph_find_edge_entry(graph, type, src, dst);
543 if (!entry)
544 return NULL;
546 return entry->data;
549 /* Check whether the dependence graph has an edge of the given type
550 * between the given two nodes.
552 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
553 enum isl_edge_type type,
554 struct isl_sched_node *src, struct isl_sched_node *dst)
556 struct isl_sched_edge *edge;
557 isl_bool empty;
559 edge = graph_find_edge(graph, type, src, dst);
560 if (!edge)
561 return 0;
563 empty = isl_map_plain_is_empty(edge->map);
564 if (empty < 0)
565 return isl_bool_error;
567 return !empty;
570 /* Look for any edge with the same src, dst and map fields as "model".
572 * Return the matching edge if one can be found.
573 * Return "model" if no matching edge is found.
574 * Return NULL on error.
576 static struct isl_sched_edge *graph_find_matching_edge(
577 struct isl_sched_graph *graph, struct isl_sched_edge *model)
579 enum isl_edge_type i;
580 struct isl_sched_edge *edge;
582 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
583 int is_equal;
585 edge = graph_find_edge(graph, i, model->src, model->dst);
586 if (!edge)
587 continue;
588 is_equal = isl_map_plain_is_equal(model->map, edge->map);
589 if (is_equal < 0)
590 return NULL;
591 if (is_equal)
592 return edge;
595 return model;
598 /* Remove the given edge from all the edge_tables that refer to it.
600 static void graph_remove_edge(struct isl_sched_graph *graph,
601 struct isl_sched_edge *edge)
603 isl_ctx *ctx = isl_map_get_ctx(edge->map);
604 enum isl_edge_type i;
606 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
607 struct isl_hash_table_entry *entry;
609 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
610 if (!entry)
611 continue;
612 if (entry->data != edge)
613 continue;
614 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
618 /* Check whether the dependence graph has any edge
619 * between the given two nodes.
621 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
622 struct isl_sched_node *src, struct isl_sched_node *dst)
624 enum isl_edge_type i;
625 isl_bool r;
627 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
628 r = graph_has_edge(graph, i, src, dst);
629 if (r < 0 || r)
630 return r;
633 return r;
636 /* Check whether the dependence graph has a validity edge
637 * between the given two nodes.
639 * Conditional validity edges are essentially validity edges that
640 * can be ignored if the corresponding condition edges are iteration private.
641 * Here, we are only checking for the presence of validity
642 * edges, so we need to consider the conditional validity edges too.
643 * In particular, this function is used during the detection
644 * of strongly connected components and we cannot ignore
645 * conditional validity edges during this detection.
647 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
648 struct isl_sched_node *src, struct isl_sched_node *dst)
650 isl_bool r;
652 r = graph_has_edge(graph, isl_edge_validity, src, dst);
653 if (r < 0 || r)
654 return r;
656 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
659 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
660 int n_node, int n_edge)
662 int i;
664 graph->n = n_node;
665 graph->n_edge = n_edge;
666 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
667 graph->sorted = isl_calloc_array(ctx, int, graph->n);
668 graph->region = isl_alloc_array(ctx,
669 struct isl_trivial_region, graph->n);
670 graph->edge = isl_calloc_array(ctx,
671 struct isl_sched_edge, graph->n_edge);
673 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
674 graph->intra_hmap_param = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
675 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
677 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
678 !graph->sorted)
679 return -1;
681 for(i = 0; i < graph->n; ++i)
682 graph->sorted[i] = i;
684 return 0;
687 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
689 int i;
691 isl_map_to_basic_set_free(graph->intra_hmap);
692 isl_map_to_basic_set_free(graph->intra_hmap_param);
693 isl_map_to_basic_set_free(graph->inter_hmap);
695 if (graph->node)
696 for (i = 0; i < graph->n; ++i) {
697 isl_space_free(graph->node[i].space);
698 isl_set_free(graph->node[i].hull);
699 isl_multi_aff_free(graph->node[i].compress);
700 isl_multi_aff_free(graph->node[i].decompress);
701 isl_mat_free(graph->node[i].sched);
702 isl_map_free(graph->node[i].sched_map);
703 isl_mat_free(graph->node[i].indep);
704 isl_mat_free(graph->node[i].vmap);
705 if (graph->root == graph)
706 free(graph->node[i].coincident);
707 isl_multi_val_free(graph->node[i].sizes);
708 isl_basic_set_free(graph->node[i].bounds);
709 isl_vec_free(graph->node[i].max);
711 free(graph->node);
712 free(graph->sorted);
713 if (graph->edge)
714 for (i = 0; i < graph->n_edge; ++i) {
715 isl_map_free(graph->edge[i].map);
716 isl_union_map_free(graph->edge[i].tagged_condition);
717 isl_union_map_free(graph->edge[i].tagged_validity);
719 free(graph->edge);
720 free(graph->region);
721 for (i = 0; i <= isl_edge_last; ++i)
722 isl_hash_table_free(ctx, graph->edge_table[i]);
723 isl_hash_table_free(ctx, graph->node_table);
724 isl_basic_set_free(graph->lp);
727 /* For each "set" on which this function is called, increment
728 * graph->n by one and update graph->maxvar.
730 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
732 struct isl_sched_graph *graph = user;
733 int nvar = isl_set_dim(set, isl_dim_set);
735 graph->n++;
736 if (nvar > graph->maxvar)
737 graph->maxvar = nvar;
739 isl_set_free(set);
741 return isl_stat_ok;
744 /* Compute the number of rows that should be allocated for the schedule.
745 * In particular, we need one row for each variable or one row
746 * for each basic map in the dependences.
747 * Note that it is practically impossible to exhaust both
748 * the number of dependences and the number of variables.
750 static isl_stat compute_max_row(struct isl_sched_graph *graph,
751 __isl_keep isl_schedule_constraints *sc)
753 int n_edge;
754 isl_stat r;
755 isl_union_set *domain;
757 graph->n = 0;
758 graph->maxvar = 0;
759 domain = isl_schedule_constraints_get_domain(sc);
760 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
761 isl_union_set_free(domain);
762 if (r < 0)
763 return isl_stat_error;
764 n_edge = isl_schedule_constraints_n_basic_map(sc);
765 if (n_edge < 0)
766 return isl_stat_error;
767 graph->max_row = n_edge + graph->maxvar;
769 return isl_stat_ok;
772 /* Does "bset" have any defining equalities for its set variables?
774 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
776 int i, n;
778 if (!bset)
779 return isl_bool_error;
781 n = isl_basic_set_dim(bset, isl_dim_set);
782 for (i = 0; i < n; ++i) {
783 isl_bool has;
785 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
786 NULL);
787 if (has < 0 || has)
788 return has;
791 return isl_bool_false;
794 /* Set the entries of node->max to the value of the schedule_max_coefficient
795 * option, if set.
797 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
799 int max;
801 max = isl_options_get_schedule_max_coefficient(ctx);
802 if (max == -1)
803 return isl_stat_ok;
805 node->max = isl_vec_alloc(ctx, node->nvar);
806 node->max = isl_vec_set_si(node->max, max);
807 if (!node->max)
808 return isl_stat_error;
810 return isl_stat_ok;
813 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
814 * option (if set) and half of the minimum of the sizes in the other
815 * dimensions. Round up when computing the half such that
816 * if the minimum of the sizes is one, half of the size is taken to be one
817 * rather than zero.
818 * If the global minimum is unbounded (i.e., if both
819 * the schedule_max_coefficient is not set and the sizes in the other
820 * dimensions are unbounded), then store a negative value.
821 * If the schedule coefficient is close to the size of the instance set
822 * in another dimension, then the schedule may represent a loop
823 * coalescing transformation (especially if the coefficient
824 * in that other dimension is one). Forcing the coefficient to be
825 * smaller than or equal to half the minimal size should avoid this
826 * situation.
828 static isl_stat compute_max_coefficient(isl_ctx *ctx,
829 struct isl_sched_node *node)
831 int max;
832 int i, j;
833 isl_vec *v;
835 max = isl_options_get_schedule_max_coefficient(ctx);
836 v = isl_vec_alloc(ctx, node->nvar);
837 if (!v)
838 return isl_stat_error;
840 for (i = 0; i < node->nvar; ++i) {
841 isl_int_set_si(v->el[i], max);
842 isl_int_mul_si(v->el[i], v->el[i], 2);
845 for (i = 0; i < node->nvar; ++i) {
846 isl_val *size;
848 size = isl_multi_val_get_val(node->sizes, i);
849 if (!size)
850 goto error;
851 if (!isl_val_is_int(size)) {
852 isl_val_free(size);
853 continue;
855 for (j = 0; j < node->nvar; ++j) {
856 if (j == i)
857 continue;
858 if (isl_int_is_neg(v->el[j]) ||
859 isl_int_gt(v->el[j], size->n))
860 isl_int_set(v->el[j], size->n);
862 isl_val_free(size);
865 for (i = 0; i < node->nvar; ++i)
866 isl_int_cdiv_q_ui(v->el[i], v->el[i], 2);
868 node->max = v;
869 return isl_stat_ok;
870 error:
871 isl_vec_free(v);
872 return isl_stat_error;
875 /* Compute and return the size of "set" in dimension "dim".
876 * The size is taken to be the difference in values for that variable
877 * for fixed values of the other variables.
878 * This assumes that "set" is convex.
879 * In particular, the variable is first isolated from the other variables
880 * in the range of a map
882 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
884 * and then duplicated
886 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
888 * The shared variables are then projected out and the maximal value
889 * of i_dim' - i_dim is computed.
891 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
893 isl_map *map;
894 isl_local_space *ls;
895 isl_aff *obj;
896 isl_val *v;
898 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
899 map = isl_map_project_out(map, isl_dim_in, dim, 1);
900 map = isl_map_range_product(map, isl_map_copy(map));
901 map = isl_set_unwrap(isl_map_range(map));
902 set = isl_map_deltas(map);
903 ls = isl_local_space_from_space(isl_set_get_space(set));
904 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
905 v = isl_set_max_val(set, obj);
906 isl_aff_free(obj);
907 isl_set_free(set);
909 return v;
912 /* Compute the size of the instance set "set" of "node", after compression,
913 * as well as bounds on the corresponding coefficients, if needed.
915 * The sizes are needed when the schedule_treat_coalescing option is set.
916 * The bounds are needed when the schedule_treat_coalescing option or
917 * the schedule_max_coefficient option is set.
919 * If the schedule_treat_coalescing option is not set, then at most
920 * the bounds need to be set and this is done in set_max_coefficient.
921 * Otherwise, compress the domain if needed, compute the size
922 * in each direction and store the results in node->size.
923 * If the domain is not convex, then the sizes are computed
924 * on a convex superset in order to avoid picking up sizes
925 * that are valid for the individual disjuncts, but not for
926 * the domain as a whole.
927 * Finally, set the bounds on the coefficients based on the sizes
928 * and the schedule_max_coefficient option in compute_max_coefficient.
930 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
931 __isl_take isl_set *set)
933 int j, n;
934 isl_multi_val *mv;
936 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
937 isl_set_free(set);
938 return set_max_coefficient(ctx, node);
941 if (node->compressed)
942 set = isl_set_preimage_multi_aff(set,
943 isl_multi_aff_copy(node->decompress));
944 set = isl_set_from_basic_set(isl_set_simple_hull(set));
945 mv = isl_multi_val_zero(isl_set_get_space(set));
946 n = isl_set_dim(set, isl_dim_set);
947 for (j = 0; j < n; ++j) {
948 isl_val *v;
950 v = compute_size(isl_set_copy(set), j);
951 mv = isl_multi_val_set_val(mv, j, v);
953 node->sizes = mv;
954 isl_set_free(set);
955 if (!node->sizes)
956 return isl_stat_error;
957 return compute_max_coefficient(ctx, node);
960 /* Add a new node to the graph representing the given instance set.
961 * "nvar" is the (possibly compressed) number of variables and
962 * may be smaller than then number of set variables in "set"
963 * if "compressed" is set.
964 * If "compressed" is set, then "hull" represents the constraints
965 * that were used to derive the compression, while "compress" and
966 * "decompress" map the original space to the compressed space and
967 * vice versa.
968 * If "compressed" is not set, then "hull", "compress" and "decompress"
969 * should be NULL.
971 * Compute the size of the instance set and bounds on the coefficients,
972 * if needed.
974 static isl_stat add_node(struct isl_sched_graph *graph,
975 __isl_take isl_set *set, int nvar, int compressed,
976 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
977 __isl_take isl_multi_aff *decompress)
979 int nparam;
980 isl_ctx *ctx;
981 isl_mat *sched;
982 isl_space *space;
983 int *coincident;
984 struct isl_sched_node *node;
986 if (!set)
987 return isl_stat_error;
989 ctx = isl_set_get_ctx(set);
990 nparam = isl_set_dim(set, isl_dim_param);
991 if (!ctx->opt->schedule_parametric)
992 nparam = 0;
993 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
994 node = &graph->node[graph->n];
995 graph->n++;
996 space = isl_set_get_space(set);
997 node->space = space;
998 node->nvar = nvar;
999 node->nparam = nparam;
1000 node->sched = sched;
1001 node->sched_map = NULL;
1002 coincident = isl_calloc_array(ctx, int, graph->max_row);
1003 node->coincident = coincident;
1004 node->compressed = compressed;
1005 node->hull = hull;
1006 node->compress = compress;
1007 node->decompress = decompress;
1008 if (compute_sizes_and_max(ctx, node, set) < 0)
1009 return isl_stat_error;
1011 if (!space || !sched || (graph->max_row && !coincident))
1012 return isl_stat_error;
1013 if (compressed && (!hull || !compress || !decompress))
1014 return isl_stat_error;
1016 return isl_stat_ok;
1019 /* Construct an identifier for node "node", which will represent "set".
1020 * The name of the identifier is either "compressed" or
1021 * "compressed_<name>", with <name> the name of the space of "set".
1022 * The user pointer of the identifier points to "node".
1024 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
1025 struct isl_sched_node *node)
1027 isl_bool has_name;
1028 isl_ctx *ctx;
1029 isl_id *id;
1030 isl_printer *p;
1031 const char *name;
1032 char *id_name;
1034 has_name = isl_set_has_tuple_name(set);
1035 if (has_name < 0)
1036 return NULL;
1038 ctx = isl_set_get_ctx(set);
1039 if (!has_name)
1040 return isl_id_alloc(ctx, "compressed", node);
1042 p = isl_printer_to_str(ctx);
1043 name = isl_set_get_tuple_name(set);
1044 p = isl_printer_print_str(p, "compressed_");
1045 p = isl_printer_print_str(p, name);
1046 id_name = isl_printer_get_str(p);
1047 isl_printer_free(p);
1049 id = isl_id_alloc(ctx, id_name, node);
1050 free(id_name);
1052 return id;
1055 /* Add a new node to the graph representing the given set.
1057 * If any of the set variables is defined by an equality, then
1058 * we perform variable compression such that we can perform
1059 * the scheduling on the compressed domain.
1060 * In this case, an identifier is used that references the new node
1061 * such that each compressed space is unique and
1062 * such that the node can be recovered from the compressed space.
1064 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1066 int nvar;
1067 isl_bool has_equality;
1068 isl_id *id;
1069 isl_basic_set *hull;
1070 isl_set *hull_set;
1071 isl_morph *morph;
1072 isl_multi_aff *compress, *decompress;
1073 struct isl_sched_graph *graph = user;
1075 hull = isl_set_affine_hull(isl_set_copy(set));
1076 hull = isl_basic_set_remove_divs(hull);
1077 nvar = isl_set_dim(set, isl_dim_set);
1078 has_equality = has_any_defining_equality(hull);
1080 if (has_equality < 0)
1081 goto error;
1082 if (!has_equality) {
1083 isl_basic_set_free(hull);
1084 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1087 id = construct_compressed_id(set, &graph->node[graph->n]);
1088 morph = isl_basic_set_variable_compression_with_id(hull,
1089 isl_dim_set, id);
1090 isl_id_free(id);
1091 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1092 compress = isl_morph_get_var_multi_aff(morph);
1093 morph = isl_morph_inverse(morph);
1094 decompress = isl_morph_get_var_multi_aff(morph);
1095 isl_morph_free(morph);
1097 hull_set = isl_set_from_basic_set(hull);
1098 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1099 error:
1100 isl_basic_set_free(hull);
1101 isl_set_free(set);
1102 return isl_stat_error;
1105 struct isl_extract_edge_data {
1106 enum isl_edge_type type;
1107 struct isl_sched_graph *graph;
1110 /* Merge edge2 into edge1, freeing the contents of edge2.
1111 * Return 0 on success and -1 on failure.
1113 * edge1 and edge2 are assumed to have the same value for the map field.
1115 static int merge_edge(struct isl_sched_edge *edge1,
1116 struct isl_sched_edge *edge2)
1118 edge1->types |= edge2->types;
1119 isl_map_free(edge2->map);
1121 if (is_condition(edge2)) {
1122 if (!edge1->tagged_condition)
1123 edge1->tagged_condition = edge2->tagged_condition;
1124 else
1125 edge1->tagged_condition =
1126 isl_union_map_union(edge1->tagged_condition,
1127 edge2->tagged_condition);
1130 if (is_conditional_validity(edge2)) {
1131 if (!edge1->tagged_validity)
1132 edge1->tagged_validity = edge2->tagged_validity;
1133 else
1134 edge1->tagged_validity =
1135 isl_union_map_union(edge1->tagged_validity,
1136 edge2->tagged_validity);
1139 if (is_condition(edge2) && !edge1->tagged_condition)
1140 return -1;
1141 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1142 return -1;
1144 return 0;
1147 /* Insert dummy tags in domain and range of "map".
1149 * In particular, if "map" is of the form
1151 * A -> B
1153 * then return
1155 * [A -> dummy_tag] -> [B -> dummy_tag]
1157 * where the dummy_tags are identical and equal to any dummy tags
1158 * introduced by any other call to this function.
1160 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1162 static char dummy;
1163 isl_ctx *ctx;
1164 isl_id *id;
1165 isl_space *space;
1166 isl_set *domain, *range;
1168 ctx = isl_map_get_ctx(map);
1170 id = isl_id_alloc(ctx, NULL, &dummy);
1171 space = isl_space_params(isl_map_get_space(map));
1172 space = isl_space_set_from_params(space);
1173 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1174 space = isl_space_map_from_set(space);
1176 domain = isl_map_wrap(map);
1177 range = isl_map_wrap(isl_map_universe(space));
1178 map = isl_map_from_domain_and_range(domain, range);
1179 map = isl_map_zip(map);
1181 return map;
1184 /* Given that at least one of "src" or "dst" is compressed, return
1185 * a map between the spaces of these nodes restricted to the affine
1186 * hull that was used in the compression.
1188 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1189 struct isl_sched_node *dst)
1191 isl_set *dom, *ran;
1193 if (src->compressed)
1194 dom = isl_set_copy(src->hull);
1195 else
1196 dom = isl_set_universe(isl_space_copy(src->space));
1197 if (dst->compressed)
1198 ran = isl_set_copy(dst->hull);
1199 else
1200 ran = isl_set_universe(isl_space_copy(dst->space));
1202 return isl_map_from_domain_and_range(dom, ran);
1205 /* Intersect the domains of the nested relations in domain and range
1206 * of "tagged" with "map".
1208 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1209 __isl_keep isl_map *map)
1211 isl_set *set;
1213 tagged = isl_map_zip(tagged);
1214 set = isl_map_wrap(isl_map_copy(map));
1215 tagged = isl_map_intersect_domain(tagged, set);
1216 tagged = isl_map_zip(tagged);
1217 return tagged;
1220 /* Return a pointer to the node that lives in the domain space of "map"
1221 * or NULL if there is no such node.
1223 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1224 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1226 struct isl_sched_node *node;
1227 isl_space *space;
1229 space = isl_space_domain(isl_map_get_space(map));
1230 node = graph_find_node(ctx, graph, space);
1231 isl_space_free(space);
1233 return node;
1236 /* Return a pointer to the node that lives in the range space of "map"
1237 * or NULL if there is no such node.
1239 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1240 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1242 struct isl_sched_node *node;
1243 isl_space *space;
1245 space = isl_space_range(isl_map_get_space(map));
1246 node = graph_find_node(ctx, graph, space);
1247 isl_space_free(space);
1249 return node;
1252 /* Refrain from adding a new edge based on "map".
1253 * Instead, just free the map.
1254 * "tagged" is either a copy of "map" with additional tags or NULL.
1256 static isl_stat skip_edge(__isl_take isl_map *map, __isl_take isl_map *tagged)
1258 isl_map_free(map);
1259 isl_map_free(tagged);
1261 return isl_stat_ok;
1264 /* Add a new edge to the graph based on the given map
1265 * and add it to data->graph->edge_table[data->type].
1266 * If a dependence relation of a given type happens to be identical
1267 * to one of the dependence relations of a type that was added before,
1268 * then we don't create a new edge, but instead mark the original edge
1269 * as also representing a dependence of the current type.
1271 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1272 * may be specified as "tagged" dependence relations. That is, "map"
1273 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1274 * the dependence on iterations and a and b are tags.
1275 * edge->map is set to the relation containing the elements i -> j,
1276 * while edge->tagged_condition and edge->tagged_validity contain
1277 * the union of all the "map" relations
1278 * for which extract_edge is called that result in the same edge->map.
1280 * If the source or the destination node is compressed, then
1281 * intersect both "map" and "tagged" with the constraints that
1282 * were used to construct the compression.
1283 * This ensures that there are no schedule constraints defined
1284 * outside of these domains, while the scheduler no longer has
1285 * any control over those outside parts.
1287 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1289 isl_bool empty;
1290 isl_ctx *ctx = isl_map_get_ctx(map);
1291 struct isl_extract_edge_data *data = user;
1292 struct isl_sched_graph *graph = data->graph;
1293 struct isl_sched_node *src, *dst;
1294 struct isl_sched_edge *edge;
1295 isl_map *tagged = NULL;
1297 if (data->type == isl_edge_condition ||
1298 data->type == isl_edge_conditional_validity) {
1299 if (isl_map_can_zip(map)) {
1300 tagged = isl_map_copy(map);
1301 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1302 } else {
1303 tagged = insert_dummy_tags(isl_map_copy(map));
1307 src = find_domain_node(ctx, graph, map);
1308 dst = find_range_node(ctx, graph, map);
1310 if (!src || !dst)
1311 return skip_edge(map, tagged);
1313 if (src->compressed || dst->compressed) {
1314 isl_map *hull;
1315 hull = extract_hull(src, dst);
1316 if (tagged)
1317 tagged = map_intersect_domains(tagged, hull);
1318 map = isl_map_intersect(map, hull);
1321 empty = isl_map_plain_is_empty(map);
1322 if (empty < 0)
1323 goto error;
1324 if (empty)
1325 return skip_edge(map, tagged);
1327 graph->edge[graph->n_edge].src = src;
1328 graph->edge[graph->n_edge].dst = dst;
1329 graph->edge[graph->n_edge].map = map;
1330 graph->edge[graph->n_edge].types = 0;
1331 graph->edge[graph->n_edge].tagged_condition = NULL;
1332 graph->edge[graph->n_edge].tagged_validity = NULL;
1333 set_type(&graph->edge[graph->n_edge], data->type);
1334 if (data->type == isl_edge_condition)
1335 graph->edge[graph->n_edge].tagged_condition =
1336 isl_union_map_from_map(tagged);
1337 if (data->type == isl_edge_conditional_validity)
1338 graph->edge[graph->n_edge].tagged_validity =
1339 isl_union_map_from_map(tagged);
1341 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1342 if (!edge) {
1343 graph->n_edge++;
1344 return isl_stat_error;
1346 if (edge == &graph->edge[graph->n_edge])
1347 return graph_edge_table_add(ctx, graph, data->type,
1348 &graph->edge[graph->n_edge++]);
1350 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1351 return isl_stat_error;
1353 return graph_edge_table_add(ctx, graph, data->type, edge);
1354 error:
1355 isl_map_free(map);
1356 isl_map_free(tagged);
1357 return isl_stat_error;
1360 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1362 * The context is included in the domain before the nodes of
1363 * the graphs are extracted in order to be able to exploit
1364 * any possible additional equalities.
1365 * Note that this intersection is only performed locally here.
1367 static isl_stat graph_init(struct isl_sched_graph *graph,
1368 __isl_keep isl_schedule_constraints *sc)
1370 isl_ctx *ctx;
1371 isl_union_set *domain;
1372 isl_union_map *c;
1373 struct isl_extract_edge_data data;
1374 enum isl_edge_type i;
1375 isl_stat r;
1377 if (!sc)
1378 return isl_stat_error;
1380 ctx = isl_schedule_constraints_get_ctx(sc);
1382 domain = isl_schedule_constraints_get_domain(sc);
1383 graph->n = isl_union_set_n_set(domain);
1384 isl_union_set_free(domain);
1386 if (graph_alloc(ctx, graph, graph->n,
1387 isl_schedule_constraints_n_map(sc)) < 0)
1388 return isl_stat_error;
1390 if (compute_max_row(graph, sc) < 0)
1391 return isl_stat_error;
1392 graph->root = graph;
1393 graph->n = 0;
1394 domain = isl_schedule_constraints_get_domain(sc);
1395 domain = isl_union_set_intersect_params(domain,
1396 isl_schedule_constraints_get_context(sc));
1397 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1398 isl_union_set_free(domain);
1399 if (r < 0)
1400 return isl_stat_error;
1401 if (graph_init_table(ctx, graph) < 0)
1402 return isl_stat_error;
1403 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1404 c = isl_schedule_constraints_get(sc, i);
1405 graph->max_edge[i] = isl_union_map_n_map(c);
1406 isl_union_map_free(c);
1407 if (!c)
1408 return isl_stat_error;
1410 if (graph_init_edge_tables(ctx, graph) < 0)
1411 return isl_stat_error;
1412 graph->n_edge = 0;
1413 data.graph = graph;
1414 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1415 isl_stat r;
1417 data.type = i;
1418 c = isl_schedule_constraints_get(sc, i);
1419 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1420 isl_union_map_free(c);
1421 if (r < 0)
1422 return isl_stat_error;
1425 return isl_stat_ok;
1428 /* Check whether there is any dependence from node[j] to node[i]
1429 * or from node[i] to node[j].
1431 static isl_bool node_follows_weak(int i, int j, void *user)
1433 isl_bool f;
1434 struct isl_sched_graph *graph = user;
1436 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1437 if (f < 0 || f)
1438 return f;
1439 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1442 /* Check whether there is a (conditional) validity dependence from node[j]
1443 * to node[i], forcing node[i] to follow node[j].
1445 static isl_bool node_follows_strong(int i, int j, void *user)
1447 struct isl_sched_graph *graph = user;
1449 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1452 /* Use Tarjan's algorithm for computing the strongly connected components
1453 * in the dependence graph only considering those edges defined by "follows".
1455 static isl_stat detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1456 isl_bool (*follows)(int i, int j, void *user))
1458 int i, n;
1459 struct isl_tarjan_graph *g = NULL;
1461 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1462 if (!g)
1463 return isl_stat_error;
1465 graph->scc = 0;
1466 i = 0;
1467 n = graph->n;
1468 while (n) {
1469 while (g->order[i] != -1) {
1470 graph->node[g->order[i]].scc = graph->scc;
1471 --n;
1472 ++i;
1474 ++i;
1475 graph->scc++;
1478 isl_tarjan_graph_free(g);
1480 return isl_stat_ok;
1483 /* Apply Tarjan's algorithm to detect the strongly connected components
1484 * in the dependence graph.
1485 * Only consider the (conditional) validity dependences and clear "weak".
1487 static isl_stat detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1489 graph->weak = 0;
1490 return detect_ccs(ctx, graph, &node_follows_strong);
1493 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1494 * in the dependence graph.
1495 * Consider all dependences and set "weak".
1497 static isl_stat detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1499 graph->weak = 1;
1500 return detect_ccs(ctx, graph, &node_follows_weak);
1503 static int cmp_scc(const void *a, const void *b, void *data)
1505 struct isl_sched_graph *graph = data;
1506 const int *i1 = a;
1507 const int *i2 = b;
1509 return graph->node[*i1].scc - graph->node[*i2].scc;
1512 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1514 static int sort_sccs(struct isl_sched_graph *graph)
1516 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1519 /* Return a non-parametric set in the compressed space of "node" that is
1520 * bounded by the size in each direction
1522 * { [x] : -S_i <= x_i <= S_i }
1524 * If S_i is infinity in direction i, then there are no constraints
1525 * in that direction.
1527 * Cache the result in node->bounds.
1529 static __isl_give isl_basic_set *get_size_bounds(struct isl_sched_node *node)
1531 isl_space *space;
1532 isl_basic_set *bounds;
1533 int i;
1534 unsigned nparam;
1536 if (node->bounds)
1537 return isl_basic_set_copy(node->bounds);
1539 if (node->compressed)
1540 space = isl_multi_aff_get_domain_space(node->decompress);
1541 else
1542 space = isl_space_copy(node->space);
1543 nparam = isl_space_dim(space, isl_dim_param);
1544 space = isl_space_drop_dims(space, isl_dim_param, 0, nparam);
1545 bounds = isl_basic_set_universe(space);
1547 for (i = 0; i < node->nvar; ++i) {
1548 isl_val *size;
1550 size = isl_multi_val_get_val(node->sizes, i);
1551 if (!size)
1552 return isl_basic_set_free(bounds);
1553 if (!isl_val_is_int(size)) {
1554 isl_val_free(size);
1555 continue;
1557 bounds = isl_basic_set_upper_bound_val(bounds, isl_dim_set, i,
1558 isl_val_copy(size));
1559 bounds = isl_basic_set_lower_bound_val(bounds, isl_dim_set, i,
1560 isl_val_neg(size));
1563 node->bounds = isl_basic_set_copy(bounds);
1564 return bounds;
1567 /* Drop some constraints from "delta" that could be exploited
1568 * to construct loop coalescing schedules.
1569 * In particular, drop those constraint that bound the difference
1570 * to the size of the domain.
1571 * First project out the parameters to improve the effectiveness.
1573 static __isl_give isl_set *drop_coalescing_constraints(
1574 __isl_take isl_set *delta, struct isl_sched_node *node)
1576 unsigned nparam;
1577 isl_basic_set *bounds;
1579 bounds = get_size_bounds(node);
1581 nparam = isl_set_dim(delta, isl_dim_param);
1582 delta = isl_set_project_out(delta, isl_dim_param, 0, nparam);
1583 delta = isl_set_remove_divs(delta);
1584 delta = isl_set_plain_gist_basic_set(delta, bounds);
1585 return delta;
1588 /* Given a dependence relation R from "node" to itself,
1589 * construct the set of coefficients of valid constraints for elements
1590 * in that dependence relation.
1591 * In particular, the result contains tuples of coefficients
1592 * c_0, c_n, c_x such that
1594 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1596 * or, equivalently,
1598 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1600 * We choose here to compute the dual of delta R.
1601 * Alternatively, we could have computed the dual of R, resulting
1602 * in a set of tuples c_0, c_n, c_x, c_y, and then
1603 * plugged in (c_0, c_n, c_x, -c_x).
1605 * If "need_param" is set, then the resulting coefficients effectively
1606 * include coefficients for the parameters c_n. Otherwise, they may
1607 * have been projected out already.
1608 * Since the constraints may be different for these two cases,
1609 * they are stored in separate caches.
1610 * In particular, if no parameter coefficients are required and
1611 * the schedule_treat_coalescing option is set, then the parameters
1612 * are projected out and some constraints that could be exploited
1613 * to construct coalescing schedules are removed before the dual
1614 * is computed.
1616 * If "node" has been compressed, then the dependence relation
1617 * is also compressed before the set of coefficients is computed.
1619 static __isl_give isl_basic_set *intra_coefficients(
1620 struct isl_sched_graph *graph, struct isl_sched_node *node,
1621 __isl_take isl_map *map, int need_param)
1623 isl_ctx *ctx;
1624 isl_set *delta;
1625 isl_map *key;
1626 isl_basic_set *coef;
1627 isl_maybe_isl_basic_set m;
1628 isl_map_to_basic_set **hmap = &graph->intra_hmap;
1629 int treat;
1631 if (!map)
1632 return NULL;
1634 ctx = isl_map_get_ctx(map);
1635 treat = !need_param && isl_options_get_schedule_treat_coalescing(ctx);
1636 if (!treat)
1637 hmap = &graph->intra_hmap_param;
1638 m = isl_map_to_basic_set_try_get(*hmap, map);
1639 if (m.valid < 0 || m.valid) {
1640 isl_map_free(map);
1641 return m.value;
1644 key = isl_map_copy(map);
1645 if (node->compressed) {
1646 map = isl_map_preimage_domain_multi_aff(map,
1647 isl_multi_aff_copy(node->decompress));
1648 map = isl_map_preimage_range_multi_aff(map,
1649 isl_multi_aff_copy(node->decompress));
1651 delta = isl_map_deltas(map);
1652 if (treat)
1653 delta = drop_coalescing_constraints(delta, node);
1654 delta = isl_set_remove_divs(delta);
1655 coef = isl_set_coefficients(delta);
1656 *hmap = isl_map_to_basic_set_set(*hmap, key, isl_basic_set_copy(coef));
1658 return coef;
1661 /* Given a dependence relation R, construct the set of coefficients
1662 * of valid constraints for elements in that dependence relation.
1663 * In particular, the result contains tuples of coefficients
1664 * c_0, c_n, c_x, c_y such that
1666 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1668 * If the source or destination nodes of "edge" have been compressed,
1669 * then the dependence relation is also compressed before
1670 * the set of coefficients is computed.
1672 static __isl_give isl_basic_set *inter_coefficients(
1673 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1674 __isl_take isl_map *map)
1676 isl_set *set;
1677 isl_map *key;
1678 isl_basic_set *coef;
1679 isl_maybe_isl_basic_set m;
1681 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1682 if (m.valid < 0 || m.valid) {
1683 isl_map_free(map);
1684 return m.value;
1687 key = isl_map_copy(map);
1688 if (edge->src->compressed)
1689 map = isl_map_preimage_domain_multi_aff(map,
1690 isl_multi_aff_copy(edge->src->decompress));
1691 if (edge->dst->compressed)
1692 map = isl_map_preimage_range_multi_aff(map,
1693 isl_multi_aff_copy(edge->dst->decompress));
1694 set = isl_map_wrap(isl_map_remove_divs(map));
1695 coef = isl_set_coefficients(set);
1696 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1697 isl_basic_set_copy(coef));
1699 return coef;
1702 /* Return the position of the coefficients of the variables in
1703 * the coefficients constraints "coef".
1705 * The space of "coef" is of the form
1707 * { coefficients[[cst, params] -> S] }
1709 * Return the position of S.
1711 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1713 int offset;
1714 isl_space *space;
1716 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1717 offset = isl_space_dim(space, isl_dim_in);
1718 isl_space_free(space);
1720 return offset;
1723 /* Return the offset of the coefficient of the constant term of "node"
1724 * within the (I)LP.
1726 * Within each node, the coefficients have the following order:
1727 * - positive and negative parts of c_i_x
1728 * - c_i_n (if parametric)
1729 * - c_i_0
1731 static int node_cst_coef_offset(struct isl_sched_node *node)
1733 return node->start + 2 * node->nvar + node->nparam;
1736 /* Return the offset of the coefficients of the parameters of "node"
1737 * within the (I)LP.
1739 * Within each node, the coefficients have the following order:
1740 * - positive and negative parts of c_i_x
1741 * - c_i_n (if parametric)
1742 * - c_i_0
1744 static int node_par_coef_offset(struct isl_sched_node *node)
1746 return node->start + 2 * node->nvar;
1749 /* Return the offset of the coefficients of the variables of "node"
1750 * within the (I)LP.
1752 * Within each node, the coefficients have the following order:
1753 * - positive and negative parts of c_i_x
1754 * - c_i_n (if parametric)
1755 * - c_i_0
1757 static int node_var_coef_offset(struct isl_sched_node *node)
1759 return node->start;
1762 /* Return the position of the pair of variables encoding
1763 * coefficient "i" of "node".
1765 * The order of these variable pairs is the opposite of
1766 * that of the coefficients, with 2 variables per coefficient.
1768 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1770 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1773 /* Construct an isl_dim_map for mapping constraints on coefficients
1774 * for "node" to the corresponding positions in graph->lp.
1775 * "offset" is the offset of the coefficients for the variables
1776 * in the input constraints.
1777 * "s" is the sign of the mapping.
1779 * The input constraints are given in terms of the coefficients
1780 * (c_0, c_x) or (c_0, c_n, c_x).
1781 * The mapping produced by this function essentially plugs in
1782 * (0, c_i_x^+ - c_i_x^-) if s = 1 and
1783 * (0, -c_i_x^+ + c_i_x^-) if s = -1 or
1784 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1785 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1786 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1787 * Furthermore, the order of these pairs is the opposite of that
1788 * of the corresponding coefficients.
1790 * The caller can extend the mapping to also map the other coefficients
1791 * (and therefore not plug in 0).
1793 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1794 struct isl_sched_graph *graph, struct isl_sched_node *node,
1795 int offset, int s)
1797 int pos;
1798 unsigned total;
1799 isl_dim_map *dim_map;
1801 if (!node || !graph->lp)
1802 return NULL;
1804 total = isl_basic_set_total_dim(graph->lp);
1805 pos = node_var_coef_pos(node, 0);
1806 dim_map = isl_dim_map_alloc(ctx, total);
1807 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1808 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1810 return dim_map;
1813 /* Construct an isl_dim_map for mapping constraints on coefficients
1814 * for "src" (node i) and "dst" (node j) to the corresponding positions
1815 * in graph->lp.
1816 * "offset" is the offset of the coefficients for the variables of "src"
1817 * in the input constraints.
1818 * "s" is the sign of the mapping.
1820 * The input constraints are given in terms of the coefficients
1821 * (c_0, c_n, c_x, c_y).
1822 * The mapping produced by this function essentially plugs in
1823 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1824 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1825 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1826 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1827 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1828 * Furthermore, the order of these pairs is the opposite of that
1829 * of the corresponding coefficients.
1831 * The caller can further extend the mapping.
1833 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1834 struct isl_sched_graph *graph, struct isl_sched_node *src,
1835 struct isl_sched_node *dst, int offset, int s)
1837 int pos;
1838 unsigned total;
1839 isl_dim_map *dim_map;
1841 if (!src || !dst || !graph->lp)
1842 return NULL;
1844 total = isl_basic_set_total_dim(graph->lp);
1845 dim_map = isl_dim_map_alloc(ctx, total);
1847 pos = node_cst_coef_offset(dst);
1848 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1849 pos = node_par_coef_offset(dst);
1850 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1851 pos = node_var_coef_pos(dst, 0);
1852 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1853 dst->nvar, -s);
1854 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1855 dst->nvar, s);
1857 pos = node_cst_coef_offset(src);
1858 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1859 pos = node_par_coef_offset(src);
1860 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1861 pos = node_var_coef_pos(src, 0);
1862 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1863 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1865 return dim_map;
1868 /* Add the constraints from "src" to "dst" using "dim_map",
1869 * after making sure there is enough room in "dst" for the extra constraints.
1871 static __isl_give isl_basic_set *add_constraints_dim_map(
1872 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1873 __isl_take isl_dim_map *dim_map)
1875 int n_eq, n_ineq;
1877 n_eq = isl_basic_set_n_equality(src);
1878 n_ineq = isl_basic_set_n_inequality(src);
1879 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1880 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1881 return dst;
1884 /* Add constraints to graph->lp that force validity for the given
1885 * dependence from a node i to itself.
1886 * That is, add constraints that enforce
1888 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1889 * = c_i_x (y - x) >= 0
1891 * for each (x,y) in R.
1892 * We obtain general constraints on coefficients (c_0, c_x)
1893 * of valid constraints for (y - x) and then plug in (0, c_i_x^+ - c_i_x^-),
1894 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1895 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1896 * Note that the result of intra_coefficients may also contain
1897 * parameter coefficients c_n, in which case 0 is plugged in for them as well.
1899 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1900 struct isl_sched_edge *edge)
1902 int offset;
1903 isl_map *map = isl_map_copy(edge->map);
1904 isl_ctx *ctx = isl_map_get_ctx(map);
1905 isl_dim_map *dim_map;
1906 isl_basic_set *coef;
1907 struct isl_sched_node *node = edge->src;
1909 coef = intra_coefficients(graph, node, map, 0);
1911 offset = coef_var_offset(coef);
1913 if (!coef)
1914 return isl_stat_error;
1916 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1917 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1919 return isl_stat_ok;
1922 /* Add constraints to graph->lp that force validity for the given
1923 * dependence from node i to node j.
1924 * That is, add constraints that enforce
1926 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1928 * for each (x,y) in R.
1929 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1930 * of valid constraints for R and then plug in
1931 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1932 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1933 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1935 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1936 struct isl_sched_edge *edge)
1938 int offset;
1939 isl_map *map;
1940 isl_ctx *ctx;
1941 isl_dim_map *dim_map;
1942 isl_basic_set *coef;
1943 struct isl_sched_node *src = edge->src;
1944 struct isl_sched_node *dst = edge->dst;
1946 if (!graph->lp)
1947 return isl_stat_error;
1949 map = isl_map_copy(edge->map);
1950 ctx = isl_map_get_ctx(map);
1951 coef = inter_coefficients(graph, edge, map);
1953 offset = coef_var_offset(coef);
1955 if (!coef)
1956 return isl_stat_error;
1958 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1960 edge->start = graph->lp->n_ineq;
1961 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1962 if (!graph->lp)
1963 return isl_stat_error;
1964 edge->end = graph->lp->n_ineq;
1966 return isl_stat_ok;
1969 /* Add constraints to graph->lp that bound the dependence distance for the given
1970 * dependence from a node i to itself.
1971 * If s = 1, we add the constraint
1973 * c_i_x (y - x) <= m_0 + m_n n
1975 * or
1977 * -c_i_x (y - x) + m_0 + m_n n >= 0
1979 * for each (x,y) in R.
1980 * If s = -1, we add the constraint
1982 * -c_i_x (y - x) <= m_0 + m_n n
1984 * or
1986 * c_i_x (y - x) + m_0 + m_n n >= 0
1988 * for each (x,y) in R.
1989 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1990 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1991 * with each coefficient (except m_0) represented as a pair of non-negative
1992 * coefficients.
1995 * If "local" is set, then we add constraints
1997 * c_i_x (y - x) <= 0
1999 * or
2001 * -c_i_x (y - x) <= 0
2003 * instead, forcing the dependence distance to be (less than or) equal to 0.
2004 * That is, we plug in (0, 0, -s * c_i_x),
2005 * intra_coefficients is not required to have c_n in its result when
2006 * "local" is set. If they are missing, then (0, -s * c_i_x) is plugged in.
2007 * Note that dependences marked local are treated as validity constraints
2008 * by add_all_validity_constraints and therefore also have
2009 * their distances bounded by 0 from below.
2011 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
2012 struct isl_sched_edge *edge, int s, int local)
2014 int offset;
2015 unsigned nparam;
2016 isl_map *map = isl_map_copy(edge->map);
2017 isl_ctx *ctx = isl_map_get_ctx(map);
2018 isl_dim_map *dim_map;
2019 isl_basic_set *coef;
2020 struct isl_sched_node *node = edge->src;
2022 coef = intra_coefficients(graph, node, map, !local);
2024 offset = coef_var_offset(coef);
2026 if (!coef)
2027 return isl_stat_error;
2029 nparam = isl_space_dim(node->space, isl_dim_param);
2030 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
2032 if (!local) {
2033 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2034 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2035 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2037 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2039 return isl_stat_ok;
2042 /* Add constraints to graph->lp that bound the dependence distance for the given
2043 * dependence from node i to node j.
2044 * If s = 1, we add the constraint
2046 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
2047 * <= m_0 + m_n n
2049 * or
2051 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
2052 * m_0 + m_n n >= 0
2054 * for each (x,y) in R.
2055 * If s = -1, we add the constraint
2057 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
2058 * <= m_0 + m_n n
2060 * or
2062 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
2063 * m_0 + m_n n >= 0
2065 * for each (x,y) in R.
2066 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
2067 * of valid constraints for R and then plug in
2068 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
2069 * s*c_i_x, -s*c_j_x)
2070 * with each coefficient (except m_0, c_*_0 and c_*_n)
2071 * represented as a pair of non-negative coefficients.
2074 * If "local" is set (and s = 1), then we add constraints
2076 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
2078 * or
2080 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
2082 * instead, forcing the dependence distance to be (less than or) equal to 0.
2083 * That is, we plug in
2084 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
2085 * Note that dependences marked local are treated as validity constraints
2086 * by add_all_validity_constraints and therefore also have
2087 * their distances bounded by 0 from below.
2089 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
2090 struct isl_sched_edge *edge, int s, int local)
2092 int offset;
2093 unsigned nparam;
2094 isl_map *map = isl_map_copy(edge->map);
2095 isl_ctx *ctx = isl_map_get_ctx(map);
2096 isl_dim_map *dim_map;
2097 isl_basic_set *coef;
2098 struct isl_sched_node *src = edge->src;
2099 struct isl_sched_node *dst = edge->dst;
2101 coef = inter_coefficients(graph, edge, map);
2103 offset = coef_var_offset(coef);
2105 if (!coef)
2106 return isl_stat_error;
2108 nparam = isl_space_dim(src->space, isl_dim_param);
2109 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
2111 if (!local) {
2112 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2113 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2114 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2117 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2119 return isl_stat_ok;
2122 /* Should the distance over "edge" be forced to zero?
2123 * That is, is it marked as a local edge?
2124 * If "use_coincidence" is set, then coincidence edges are treated
2125 * as local edges.
2127 static int force_zero(struct isl_sched_edge *edge, int use_coincidence)
2129 return is_local(edge) || (use_coincidence && is_coincidence(edge));
2132 /* Add all validity constraints to graph->lp.
2134 * An edge that is forced to be local needs to have its dependence
2135 * distances equal to zero. We take care of bounding them by 0 from below
2136 * here. add_all_proximity_constraints takes care of bounding them by 0
2137 * from above.
2139 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2140 * Otherwise, we ignore them.
2142 static int add_all_validity_constraints(struct isl_sched_graph *graph,
2143 int use_coincidence)
2145 int i;
2147 for (i = 0; i < graph->n_edge; ++i) {
2148 struct isl_sched_edge *edge = &graph->edge[i];
2149 int zero;
2151 zero = force_zero(edge, use_coincidence);
2152 if (!is_validity(edge) && !zero)
2153 continue;
2154 if (edge->src != edge->dst)
2155 continue;
2156 if (add_intra_validity_constraints(graph, edge) < 0)
2157 return -1;
2160 for (i = 0; i < graph->n_edge; ++i) {
2161 struct isl_sched_edge *edge = &graph->edge[i];
2162 int zero;
2164 zero = force_zero(edge, use_coincidence);
2165 if (!is_validity(edge) && !zero)
2166 continue;
2167 if (edge->src == edge->dst)
2168 continue;
2169 if (add_inter_validity_constraints(graph, edge) < 0)
2170 return -1;
2173 return 0;
2176 /* Add constraints to graph->lp that bound the dependence distance
2177 * for all dependence relations.
2178 * If a given proximity dependence is identical to a validity
2179 * dependence, then the dependence distance is already bounded
2180 * from below (by zero), so we only need to bound the distance
2181 * from above. (This includes the case of "local" dependences
2182 * which are treated as validity dependence by add_all_validity_constraints.)
2183 * Otherwise, we need to bound the distance both from above and from below.
2185 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2186 * Otherwise, we ignore them.
2188 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2189 int use_coincidence)
2191 int i;
2193 for (i = 0; i < graph->n_edge; ++i) {
2194 struct isl_sched_edge *edge = &graph->edge[i];
2195 int zero;
2197 zero = force_zero(edge, use_coincidence);
2198 if (!is_proximity(edge) && !zero)
2199 continue;
2200 if (edge->src == edge->dst &&
2201 add_intra_proximity_constraints(graph, edge, 1, zero) < 0)
2202 return -1;
2203 if (edge->src != edge->dst &&
2204 add_inter_proximity_constraints(graph, edge, 1, zero) < 0)
2205 return -1;
2206 if (is_validity(edge) || zero)
2207 continue;
2208 if (edge->src == edge->dst &&
2209 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2210 return -1;
2211 if (edge->src != edge->dst &&
2212 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2213 return -1;
2216 return 0;
2219 /* Normalize the rows of "indep" such that all rows are lexicographically
2220 * positive and such that each row contains as many final zeros as possible,
2221 * given the choice for the previous rows.
2222 * Do this by performing elementary row operations.
2224 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2226 indep = isl_mat_reverse_gauss(indep);
2227 indep = isl_mat_lexnonneg_rows(indep);
2228 return indep;
2231 /* Compute a basis for the rows in the linear part of the schedule
2232 * and extend this basis to a full basis. The remaining rows
2233 * can then be used to force linear independence from the rows
2234 * in the schedule.
2236 * In particular, given the schedule rows S, we compute
2238 * S = H Q
2239 * S U = H
2241 * with H the Hermite normal form of S. That is, all but the
2242 * first rank columns of H are zero and so each row in S is
2243 * a linear combination of the first rank rows of Q.
2244 * The matrix Q can be used as a variable transformation
2245 * that isolates the directions of S in the first rank rows.
2246 * Transposing S U = H yields
2248 * U^T S^T = H^T
2250 * with all but the first rank rows of H^T zero.
2251 * The last rows of U^T are therefore linear combinations
2252 * of schedule coefficients that are all zero on schedule
2253 * coefficients that are linearly dependent on the rows of S.
2254 * At least one of these combinations is non-zero on
2255 * linearly independent schedule coefficients.
2256 * The rows are normalized to involve as few of the last
2257 * coefficients as possible and to have a positive initial value.
2259 static int node_update_vmap(struct isl_sched_node *node)
2261 isl_mat *H, *U, *Q;
2262 int n_row = isl_mat_rows(node->sched);
2264 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2265 1 + node->nparam, node->nvar);
2267 H = isl_mat_left_hermite(H, 0, &U, &Q);
2268 isl_mat_free(node->indep);
2269 isl_mat_free(node->vmap);
2270 node->vmap = Q;
2271 node->indep = isl_mat_transpose(U);
2272 node->rank = isl_mat_initial_non_zero_cols(H);
2273 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2274 node->indep = normalize_independent(node->indep);
2275 isl_mat_free(H);
2277 if (!node->indep || !node->vmap || node->rank < 0)
2278 return -1;
2279 return 0;
2282 /* Is "edge" marked as a validity or a conditional validity edge?
2284 static int is_any_validity(struct isl_sched_edge *edge)
2286 return is_validity(edge) || is_conditional_validity(edge);
2289 /* How many times should we count the constraints in "edge"?
2291 * We count as follows
2292 * validity -> 1 (>= 0)
2293 * validity+proximity -> 2 (>= 0 and upper bound)
2294 * proximity -> 2 (lower and upper bound)
2295 * local(+any) -> 2 (>= 0 and <= 0)
2297 * If an edge is only marked conditional_validity then it counts
2298 * as zero since it is only checked afterwards.
2300 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2301 * Otherwise, we ignore them.
2303 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2305 if (is_proximity(edge) || force_zero(edge, use_coincidence))
2306 return 2;
2307 if (is_validity(edge))
2308 return 1;
2309 return 0;
2312 /* How many times should the constraints in "edge" be counted
2313 * as a parametric intra-node constraint?
2315 * Only proximity edges that are not forced zero need
2316 * coefficient constraints that include coefficients for parameters.
2317 * If the edge is also a validity edge, then only
2318 * an upper bound is introduced. Otherwise, both lower and upper bounds
2319 * are introduced.
2321 static int parametric_intra_edge_multiplicity(struct isl_sched_edge *edge,
2322 int use_coincidence)
2324 if (edge->src != edge->dst)
2325 return 0;
2326 if (!is_proximity(edge))
2327 return 0;
2328 if (force_zero(edge, use_coincidence))
2329 return 0;
2330 if (is_validity(edge))
2331 return 1;
2332 else
2333 return 2;
2336 /* Add "f" times the number of equality and inequality constraints of "bset"
2337 * to "n_eq" and "n_ineq" and free "bset".
2339 static isl_stat update_count(__isl_take isl_basic_set *bset,
2340 int f, int *n_eq, int *n_ineq)
2342 if (!bset)
2343 return isl_stat_error;
2345 *n_eq += isl_basic_set_n_equality(bset);
2346 *n_ineq += isl_basic_set_n_inequality(bset);
2347 isl_basic_set_free(bset);
2349 return isl_stat_ok;
2352 /* Count the number of equality and inequality constraints
2353 * that will be added for the given map.
2355 * The edges that require parameter coefficients are counted separately.
2357 * "use_coincidence" is set if we should take into account coincidence edges.
2359 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2360 struct isl_sched_edge *edge, __isl_take isl_map *map,
2361 int *n_eq, int *n_ineq, int use_coincidence)
2363 isl_map *copy;
2364 isl_basic_set *coef;
2365 int f = edge_multiplicity(edge, use_coincidence);
2366 int fp = parametric_intra_edge_multiplicity(edge, use_coincidence);
2368 if (f == 0) {
2369 isl_map_free(map);
2370 return isl_stat_ok;
2373 if (edge->src != edge->dst) {
2374 coef = inter_coefficients(graph, edge, map);
2375 return update_count(coef, f, n_eq, n_ineq);
2378 if (fp > 0) {
2379 copy = isl_map_copy(map);
2380 coef = intra_coefficients(graph, edge->src, copy, 1);
2381 if (update_count(coef, fp, n_eq, n_ineq) < 0)
2382 goto error;
2385 if (f > fp) {
2386 copy = isl_map_copy(map);
2387 coef = intra_coefficients(graph, edge->src, copy, 0);
2388 if (update_count(coef, f - fp, n_eq, n_ineq) < 0)
2389 goto error;
2392 isl_map_free(map);
2393 return isl_stat_ok;
2394 error:
2395 isl_map_free(map);
2396 return isl_stat_error;
2399 /* Count the number of equality and inequality constraints
2400 * that will be added to the main lp problem.
2401 * We count as follows
2402 * validity -> 1 (>= 0)
2403 * validity+proximity -> 2 (>= 0 and upper bound)
2404 * proximity -> 2 (lower and upper bound)
2405 * local(+any) -> 2 (>= 0 and <= 0)
2407 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2408 * Otherwise, we ignore them.
2410 static int count_constraints(struct isl_sched_graph *graph,
2411 int *n_eq, int *n_ineq, int use_coincidence)
2413 int i;
2415 *n_eq = *n_ineq = 0;
2416 for (i = 0; i < graph->n_edge; ++i) {
2417 struct isl_sched_edge *edge = &graph->edge[i];
2418 isl_map *map = isl_map_copy(edge->map);
2420 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2421 use_coincidence) < 0)
2422 return -1;
2425 return 0;
2428 /* Count the number of constraints that will be added by
2429 * add_bound_constant_constraints to bound the values of the constant terms
2430 * and increment *n_eq and *n_ineq accordingly.
2432 * In practice, add_bound_constant_constraints only adds inequalities.
2434 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2435 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2437 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2438 return isl_stat_ok;
2440 *n_ineq += graph->n;
2442 return isl_stat_ok;
2445 /* Add constraints to bound the values of the constant terms in the schedule,
2446 * if requested by the user.
2448 * The maximal value of the constant terms is defined by the option
2449 * "schedule_max_constant_term".
2451 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2452 struct isl_sched_graph *graph)
2454 int i, k;
2455 int max;
2456 int total;
2458 max = isl_options_get_schedule_max_constant_term(ctx);
2459 if (max == -1)
2460 return isl_stat_ok;
2462 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2464 for (i = 0; i < graph->n; ++i) {
2465 struct isl_sched_node *node = &graph->node[i];
2466 int pos;
2468 k = isl_basic_set_alloc_inequality(graph->lp);
2469 if (k < 0)
2470 return isl_stat_error;
2471 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2472 pos = node_cst_coef_offset(node);
2473 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2474 isl_int_set_si(graph->lp->ineq[k][0], max);
2477 return isl_stat_ok;
2480 /* Count the number of constraints that will be added by
2481 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2482 * accordingly.
2484 * In practice, add_bound_coefficient_constraints only adds inequalities.
2486 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2487 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2489 int i;
2491 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2492 !isl_options_get_schedule_treat_coalescing(ctx))
2493 return 0;
2495 for (i = 0; i < graph->n; ++i)
2496 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2498 return 0;
2501 /* Add constraints to graph->lp that bound the values of
2502 * the parameter schedule coefficients of "node" to "max" and
2503 * the variable schedule coefficients to the corresponding entry
2504 * in node->max.
2505 * In either case, a negative value means that no bound needs to be imposed.
2507 * For parameter coefficients, this amounts to adding a constraint
2509 * c_n <= max
2511 * i.e.,
2513 * -c_n + max >= 0
2515 * The variables coefficients are, however, not represented directly.
2516 * Instead, the variable coefficients c_x are written as differences
2517 * c_x = c_x^+ - c_x^-.
2518 * That is,
2520 * -max_i <= c_x_i <= max_i
2522 * is encoded as
2524 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2526 * or
2528 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2529 * c_x_i^+ - c_x_i^- + max_i >= 0
2531 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2532 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2534 int i, j, k;
2535 int total;
2536 isl_vec *ineq;
2538 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2540 for (j = 0; j < node->nparam; ++j) {
2541 int dim;
2543 if (max < 0)
2544 continue;
2546 k = isl_basic_set_alloc_inequality(graph->lp);
2547 if (k < 0)
2548 return isl_stat_error;
2549 dim = 1 + node_par_coef_offset(node) + j;
2550 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2551 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2552 isl_int_set_si(graph->lp->ineq[k][0], max);
2555 ineq = isl_vec_alloc(ctx, 1 + total);
2556 ineq = isl_vec_clr(ineq);
2557 if (!ineq)
2558 return isl_stat_error;
2559 for (i = 0; i < node->nvar; ++i) {
2560 int pos = 1 + node_var_coef_pos(node, i);
2562 if (isl_int_is_neg(node->max->el[i]))
2563 continue;
2565 isl_int_set_si(ineq->el[pos], 1);
2566 isl_int_set_si(ineq->el[pos + 1], -1);
2567 isl_int_set(ineq->el[0], node->max->el[i]);
2569 k = isl_basic_set_alloc_inequality(graph->lp);
2570 if (k < 0)
2571 goto error;
2572 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2574 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2);
2575 k = isl_basic_set_alloc_inequality(graph->lp);
2576 if (k < 0)
2577 goto error;
2578 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2580 isl_seq_clr(ineq->el + pos, 2);
2582 isl_vec_free(ineq);
2584 return isl_stat_ok;
2585 error:
2586 isl_vec_free(ineq);
2587 return isl_stat_error;
2590 /* Add constraints that bound the values of the variable and parameter
2591 * coefficients of the schedule.
2593 * The maximal value of the coefficients is defined by the option
2594 * 'schedule_max_coefficient' and the entries in node->max.
2595 * These latter entries are only set if either the schedule_max_coefficient
2596 * option or the schedule_treat_coalescing option is set.
2598 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2599 struct isl_sched_graph *graph)
2601 int i;
2602 int max;
2604 max = isl_options_get_schedule_max_coefficient(ctx);
2606 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2607 return isl_stat_ok;
2609 for (i = 0; i < graph->n; ++i) {
2610 struct isl_sched_node *node = &graph->node[i];
2612 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2613 return isl_stat_error;
2616 return isl_stat_ok;
2619 /* Add a constraint to graph->lp that equates the value at position
2620 * "sum_pos" to the sum of the "n" values starting at "first".
2622 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2623 int sum_pos, int first, int n)
2625 int i, k;
2626 int total;
2628 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2630 k = isl_basic_set_alloc_equality(graph->lp);
2631 if (k < 0)
2632 return isl_stat_error;
2633 isl_seq_clr(graph->lp->eq[k], 1 + total);
2634 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2635 for (i = 0; i < n; ++i)
2636 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2638 return isl_stat_ok;
2641 /* Add a constraint to graph->lp that equates the value at position
2642 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2644 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2645 int sum_pos)
2647 int i, j, k;
2648 int total;
2650 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2652 k = isl_basic_set_alloc_equality(graph->lp);
2653 if (k < 0)
2654 return isl_stat_error;
2655 isl_seq_clr(graph->lp->eq[k], 1 + total);
2656 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2657 for (i = 0; i < graph->n; ++i) {
2658 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2660 for (j = 0; j < graph->node[i].nparam; ++j)
2661 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2664 return isl_stat_ok;
2667 /* Add a constraint to graph->lp that equates the value at position
2668 * "sum_pos" to the sum of the variable coefficients of all nodes.
2670 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2671 int sum_pos)
2673 int i, j, k;
2674 int total;
2676 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2678 k = isl_basic_set_alloc_equality(graph->lp);
2679 if (k < 0)
2680 return isl_stat_error;
2681 isl_seq_clr(graph->lp->eq[k], 1 + total);
2682 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2683 for (i = 0; i < graph->n; ++i) {
2684 struct isl_sched_node *node = &graph->node[i];
2685 int pos = 1 + node_var_coef_offset(node);
2687 for (j = 0; j < 2 * node->nvar; ++j)
2688 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2691 return isl_stat_ok;
2694 /* Construct an ILP problem for finding schedule coefficients
2695 * that result in non-negative, but small dependence distances
2696 * over all dependences.
2697 * In particular, the dependence distances over proximity edges
2698 * are bounded by m_0 + m_n n and we compute schedule coefficients
2699 * with small values (preferably zero) of m_n and m_0.
2701 * All variables of the ILP are non-negative. The actual coefficients
2702 * may be negative, so each coefficient is represented as the difference
2703 * of two non-negative variables. The negative part always appears
2704 * immediately before the positive part.
2705 * Other than that, the variables have the following order
2707 * - sum of positive and negative parts of m_n coefficients
2708 * - m_0
2709 * - sum of all c_n coefficients
2710 * (unconstrained when computing non-parametric schedules)
2711 * - sum of positive and negative parts of all c_x coefficients
2712 * - positive and negative parts of m_n coefficients
2713 * - for each node
2714 * - positive and negative parts of c_i_x, in opposite order
2715 * - c_i_n (if parametric)
2716 * - c_i_0
2718 * The constraints are those from the edges plus two or three equalities
2719 * to express the sums.
2721 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2722 * Otherwise, we ignore them.
2724 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2725 int use_coincidence)
2727 int i;
2728 unsigned nparam;
2729 unsigned total;
2730 isl_space *space;
2731 int parametric;
2732 int param_pos;
2733 int n_eq, n_ineq;
2735 parametric = ctx->opt->schedule_parametric;
2736 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2737 param_pos = 4;
2738 total = param_pos + 2 * nparam;
2739 for (i = 0; i < graph->n; ++i) {
2740 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2741 if (node_update_vmap(node) < 0)
2742 return isl_stat_error;
2743 node->start = total;
2744 total += 1 + node->nparam + 2 * node->nvar;
2747 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2748 return isl_stat_error;
2749 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2750 return isl_stat_error;
2751 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2752 return isl_stat_error;
2754 space = isl_space_set_alloc(ctx, 0, total);
2755 isl_basic_set_free(graph->lp);
2756 n_eq += 2 + parametric;
2758 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2760 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2761 return isl_stat_error;
2762 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2763 return isl_stat_error;
2764 if (add_var_sum_constraint(graph, 3) < 0)
2765 return isl_stat_error;
2766 if (add_bound_constant_constraints(ctx, graph) < 0)
2767 return isl_stat_error;
2768 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2769 return isl_stat_error;
2770 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2771 return isl_stat_error;
2772 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2773 return isl_stat_error;
2775 return isl_stat_ok;
2778 /* Analyze the conflicting constraint found by
2779 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2780 * constraint of one of the edges between distinct nodes, living, moreover
2781 * in distinct SCCs, then record the source and sink SCC as this may
2782 * be a good place to cut between SCCs.
2784 static int check_conflict(int con, void *user)
2786 int i;
2787 struct isl_sched_graph *graph = user;
2789 if (graph->src_scc >= 0)
2790 return 0;
2792 con -= graph->lp->n_eq;
2794 if (con >= graph->lp->n_ineq)
2795 return 0;
2797 for (i = 0; i < graph->n_edge; ++i) {
2798 if (!is_validity(&graph->edge[i]))
2799 continue;
2800 if (graph->edge[i].src == graph->edge[i].dst)
2801 continue;
2802 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2803 continue;
2804 if (graph->edge[i].start > con)
2805 continue;
2806 if (graph->edge[i].end <= con)
2807 continue;
2808 graph->src_scc = graph->edge[i].src->scc;
2809 graph->dst_scc = graph->edge[i].dst->scc;
2812 return 0;
2815 /* Check whether the next schedule row of the given node needs to be
2816 * non-trivial. Lower-dimensional domains may have some trivial rows,
2817 * but as soon as the number of remaining required non-trivial rows
2818 * is as large as the number or remaining rows to be computed,
2819 * all remaining rows need to be non-trivial.
2821 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2823 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2826 /* Construct a non-triviality region with triviality directions
2827 * corresponding to the rows of "indep".
2828 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2829 * while the triviality directions are expressed in terms of
2830 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2831 * before c^+_i. Furthermore,
2832 * the pairs of non-negative variables representing the coefficients
2833 * are stored in the opposite order.
2835 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2837 isl_ctx *ctx;
2838 isl_mat *mat;
2839 int i, j, n, n_var;
2841 if (!indep)
2842 return NULL;
2844 ctx = isl_mat_get_ctx(indep);
2845 n = isl_mat_rows(indep);
2846 n_var = isl_mat_cols(indep);
2847 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2848 if (!mat)
2849 return NULL;
2850 for (i = 0; i < n; ++i) {
2851 for (j = 0; j < n_var; ++j) {
2852 int nj = n_var - 1 - j;
2853 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2854 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2858 return mat;
2861 /* Solve the ILP problem constructed in setup_lp.
2862 * For each node such that all the remaining rows of its schedule
2863 * need to be non-trivial, we construct a non-triviality region.
2864 * This region imposes that the next row is independent of previous rows.
2865 * In particular, the non-triviality region enforces that at least
2866 * one of the linear combinations in the rows of node->indep is non-zero.
2868 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2870 int i;
2871 isl_vec *sol;
2872 isl_basic_set *lp;
2874 for (i = 0; i < graph->n; ++i) {
2875 struct isl_sched_node *node = &graph->node[i];
2876 isl_mat *trivial;
2878 graph->region[i].pos = node_var_coef_offset(node);
2879 if (needs_row(graph, node))
2880 trivial = construct_trivial(node->indep);
2881 else
2882 trivial = isl_mat_zero(ctx, 0, 0);
2883 graph->region[i].trivial = trivial;
2885 lp = isl_basic_set_copy(graph->lp);
2886 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2887 graph->region, &check_conflict, graph);
2888 for (i = 0; i < graph->n; ++i)
2889 isl_mat_free(graph->region[i].trivial);
2890 return sol;
2893 /* Extract the coefficients for the variables of "node" from "sol".
2895 * Each schedule coefficient c_i_x is represented as the difference
2896 * between two non-negative variables c_i_x^+ - c_i_x^-.
2897 * The c_i_x^- appear before their c_i_x^+ counterpart.
2898 * Furthermore, the order of these pairs is the opposite of that
2899 * of the corresponding coefficients.
2901 * Return c_i_x = c_i_x^+ - c_i_x^-
2903 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2904 __isl_keep isl_vec *sol)
2906 int i;
2907 int pos;
2908 isl_vec *csol;
2910 if (!sol)
2911 return NULL;
2912 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2913 if (!csol)
2914 return NULL;
2916 pos = 1 + node_var_coef_offset(node);
2917 for (i = 0; i < node->nvar; ++i)
2918 isl_int_sub(csol->el[node->nvar - 1 - i],
2919 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2921 return csol;
2924 /* Update the schedules of all nodes based on the given solution
2925 * of the LP problem.
2926 * The new row is added to the current band.
2927 * All possibly negative coefficients are encoded as a difference
2928 * of two non-negative variables, so we need to perform the subtraction
2929 * here.
2931 * If coincident is set, then the caller guarantees that the new
2932 * row satisfies the coincidence constraints.
2934 static int update_schedule(struct isl_sched_graph *graph,
2935 __isl_take isl_vec *sol, int coincident)
2937 int i, j;
2938 isl_vec *csol = NULL;
2940 if (!sol)
2941 goto error;
2942 if (sol->size == 0)
2943 isl_die(sol->ctx, isl_error_internal,
2944 "no solution found", goto error);
2945 if (graph->n_total_row >= graph->max_row)
2946 isl_die(sol->ctx, isl_error_internal,
2947 "too many schedule rows", goto error);
2949 for (i = 0; i < graph->n; ++i) {
2950 struct isl_sched_node *node = &graph->node[i];
2951 int pos;
2952 int row = isl_mat_rows(node->sched);
2954 isl_vec_free(csol);
2955 csol = extract_var_coef(node, sol);
2956 if (!csol)
2957 goto error;
2959 isl_map_free(node->sched_map);
2960 node->sched_map = NULL;
2961 node->sched = isl_mat_add_rows(node->sched, 1);
2962 if (!node->sched)
2963 goto error;
2964 pos = node_cst_coef_offset(node);
2965 node->sched = isl_mat_set_element(node->sched,
2966 row, 0, sol->el[1 + pos]);
2967 pos = node_par_coef_offset(node);
2968 for (j = 0; j < node->nparam; ++j)
2969 node->sched = isl_mat_set_element(node->sched,
2970 row, 1 + j, sol->el[1 + pos + j]);
2971 for (j = 0; j < node->nvar; ++j)
2972 node->sched = isl_mat_set_element(node->sched,
2973 row, 1 + node->nparam + j, csol->el[j]);
2974 node->coincident[graph->n_total_row] = coincident;
2976 isl_vec_free(sol);
2977 isl_vec_free(csol);
2979 graph->n_row++;
2980 graph->n_total_row++;
2982 return 0;
2983 error:
2984 isl_vec_free(sol);
2985 isl_vec_free(csol);
2986 return -1;
2989 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2990 * and return this isl_aff.
2992 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2993 struct isl_sched_node *node, int row)
2995 int j;
2996 isl_int v;
2997 isl_aff *aff;
2999 isl_int_init(v);
3001 aff = isl_aff_zero_on_domain(ls);
3002 if (isl_mat_get_element(node->sched, row, 0, &v) < 0)
3003 goto error;
3004 aff = isl_aff_set_constant(aff, v);
3005 for (j = 0; j < node->nparam; ++j) {
3006 if (isl_mat_get_element(node->sched, row, 1 + j, &v) < 0)
3007 goto error;
3008 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
3010 for (j = 0; j < node->nvar; ++j) {
3011 if (isl_mat_get_element(node->sched, row,
3012 1 + node->nparam + j, &v) < 0)
3013 goto error;
3014 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
3017 isl_int_clear(v);
3019 return aff;
3020 error:
3021 isl_int_clear(v);
3022 isl_aff_free(aff);
3023 return NULL;
3026 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
3027 * and return this multi_aff.
3029 * The result is defined over the uncompressed node domain.
3031 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
3032 struct isl_sched_node *node, int first, int n)
3034 int i;
3035 isl_space *space;
3036 isl_local_space *ls;
3037 isl_aff *aff;
3038 isl_multi_aff *ma;
3039 int nrow;
3041 if (!node)
3042 return NULL;
3043 nrow = isl_mat_rows(node->sched);
3044 if (node->compressed)
3045 space = isl_multi_aff_get_domain_space(node->decompress);
3046 else
3047 space = isl_space_copy(node->space);
3048 ls = isl_local_space_from_space(isl_space_copy(space));
3049 space = isl_space_from_domain(space);
3050 space = isl_space_add_dims(space, isl_dim_out, n);
3051 ma = isl_multi_aff_zero(space);
3053 for (i = first; i < first + n; ++i) {
3054 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
3055 ma = isl_multi_aff_set_aff(ma, i - first, aff);
3058 isl_local_space_free(ls);
3060 if (node->compressed)
3061 ma = isl_multi_aff_pullback_multi_aff(ma,
3062 isl_multi_aff_copy(node->compress));
3064 return ma;
3067 /* Convert node->sched into a multi_aff and return this multi_aff.
3069 * The result is defined over the uncompressed node domain.
3071 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
3072 struct isl_sched_node *node)
3074 int nrow;
3076 nrow = isl_mat_rows(node->sched);
3077 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
3080 /* Convert node->sched into a map and return this map.
3082 * The result is cached in node->sched_map, which needs to be released
3083 * whenever node->sched is updated.
3084 * It is defined over the uncompressed node domain.
3086 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
3088 if (!node->sched_map) {
3089 isl_multi_aff *ma;
3091 ma = node_extract_schedule_multi_aff(node);
3092 node->sched_map = isl_map_from_multi_aff(ma);
3095 return isl_map_copy(node->sched_map);
3098 /* Construct a map that can be used to update a dependence relation
3099 * based on the current schedule.
3100 * That is, construct a map expressing that source and sink
3101 * are executed within the same iteration of the current schedule.
3102 * This map can then be intersected with the dependence relation.
3103 * This is not the most efficient way, but this shouldn't be a critical
3104 * operation.
3106 static __isl_give isl_map *specializer(struct isl_sched_node *src,
3107 struct isl_sched_node *dst)
3109 isl_map *src_sched, *dst_sched;
3111 src_sched = node_extract_schedule(src);
3112 dst_sched = node_extract_schedule(dst);
3113 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
3116 /* Intersect the domains of the nested relations in domain and range
3117 * of "umap" with "map".
3119 static __isl_give isl_union_map *intersect_domains(
3120 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
3122 isl_union_set *uset;
3124 umap = isl_union_map_zip(umap);
3125 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
3126 umap = isl_union_map_intersect_domain(umap, uset);
3127 umap = isl_union_map_zip(umap);
3128 return umap;
3131 /* Update the dependence relation of the given edge based
3132 * on the current schedule.
3133 * If the dependence is carried completely by the current schedule, then
3134 * it is removed from the edge_tables. It is kept in the list of edges
3135 * as otherwise all edge_tables would have to be recomputed.
3137 * If the edge is of a type that can appear multiple times
3138 * between the same pair of nodes, then it is added to
3139 * the edge table (again). This prevents the situation
3140 * where none of these edges is referenced from the edge table
3141 * because the one that was referenced turned out to be empty and
3142 * was therefore removed from the table.
3144 static int update_edge(isl_ctx *ctx, struct isl_sched_graph *graph,
3145 struct isl_sched_edge *edge)
3147 int empty;
3148 isl_map *id;
3150 id = specializer(edge->src, edge->dst);
3151 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
3152 if (!edge->map)
3153 goto error;
3155 if (edge->tagged_condition) {
3156 edge->tagged_condition =
3157 intersect_domains(edge->tagged_condition, id);
3158 if (!edge->tagged_condition)
3159 goto error;
3161 if (edge->tagged_validity) {
3162 edge->tagged_validity =
3163 intersect_domains(edge->tagged_validity, id);
3164 if (!edge->tagged_validity)
3165 goto error;
3168 empty = isl_map_plain_is_empty(edge->map);
3169 if (empty < 0)
3170 goto error;
3171 if (empty) {
3172 graph_remove_edge(graph, edge);
3173 } else if (is_multi_edge_type(edge)) {
3174 if (graph_edge_tables_add(ctx, graph, edge) < 0)
3175 goto error;
3178 isl_map_free(id);
3179 return 0;
3180 error:
3181 isl_map_free(id);
3182 return -1;
3185 /* Does the domain of "umap" intersect "uset"?
3187 static int domain_intersects(__isl_keep isl_union_map *umap,
3188 __isl_keep isl_union_set *uset)
3190 int empty;
3192 umap = isl_union_map_copy(umap);
3193 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
3194 empty = isl_union_map_is_empty(umap);
3195 isl_union_map_free(umap);
3197 return empty < 0 ? -1 : !empty;
3200 /* Does the range of "umap" intersect "uset"?
3202 static int range_intersects(__isl_keep isl_union_map *umap,
3203 __isl_keep isl_union_set *uset)
3205 int empty;
3207 umap = isl_union_map_copy(umap);
3208 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
3209 empty = isl_union_map_is_empty(umap);
3210 isl_union_map_free(umap);
3212 return empty < 0 ? -1 : !empty;
3215 /* Are the condition dependences of "edge" local with respect to
3216 * the current schedule?
3218 * That is, are domain and range of the condition dependences mapped
3219 * to the same point?
3221 * In other words, is the condition false?
3223 static int is_condition_false(struct isl_sched_edge *edge)
3225 isl_union_map *umap;
3226 isl_map *map, *sched, *test;
3227 int empty, local;
3229 empty = isl_union_map_is_empty(edge->tagged_condition);
3230 if (empty < 0 || empty)
3231 return empty;
3233 umap = isl_union_map_copy(edge->tagged_condition);
3234 umap = isl_union_map_zip(umap);
3235 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3236 map = isl_map_from_union_map(umap);
3238 sched = node_extract_schedule(edge->src);
3239 map = isl_map_apply_domain(map, sched);
3240 sched = node_extract_schedule(edge->dst);
3241 map = isl_map_apply_range(map, sched);
3243 test = isl_map_identity(isl_map_get_space(map));
3244 local = isl_map_is_subset(map, test);
3245 isl_map_free(map);
3246 isl_map_free(test);
3248 return local;
3251 /* For each conditional validity constraint that is adjacent
3252 * to a condition with domain in condition_source or range in condition_sink,
3253 * turn it into an unconditional validity constraint.
3255 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3256 __isl_take isl_union_set *condition_source,
3257 __isl_take isl_union_set *condition_sink)
3259 int i;
3261 condition_source = isl_union_set_coalesce(condition_source);
3262 condition_sink = isl_union_set_coalesce(condition_sink);
3264 for (i = 0; i < graph->n_edge; ++i) {
3265 int adjacent;
3266 isl_union_map *validity;
3268 if (!is_conditional_validity(&graph->edge[i]))
3269 continue;
3270 if (is_validity(&graph->edge[i]))
3271 continue;
3273 validity = graph->edge[i].tagged_validity;
3274 adjacent = domain_intersects(validity, condition_sink);
3275 if (adjacent >= 0 && !adjacent)
3276 adjacent = range_intersects(validity, condition_source);
3277 if (adjacent < 0)
3278 goto error;
3279 if (!adjacent)
3280 continue;
3282 set_validity(&graph->edge[i]);
3285 isl_union_set_free(condition_source);
3286 isl_union_set_free(condition_sink);
3287 return 0;
3288 error:
3289 isl_union_set_free(condition_source);
3290 isl_union_set_free(condition_sink);
3291 return -1;
3294 /* Update the dependence relations of all edges based on the current schedule
3295 * and enforce conditional validity constraints that are adjacent
3296 * to satisfied condition constraints.
3298 * First check if any of the condition constraints are satisfied
3299 * (i.e., not local to the outer schedule) and keep track of
3300 * their domain and range.
3301 * Then update all dependence relations (which removes the non-local
3302 * constraints).
3303 * Finally, if any condition constraints turned out to be satisfied,
3304 * then turn all adjacent conditional validity constraints into
3305 * unconditional validity constraints.
3307 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3309 int i;
3310 int any = 0;
3311 isl_union_set *source, *sink;
3313 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3314 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3315 for (i = 0; i < graph->n_edge; ++i) {
3316 int local;
3317 isl_union_set *uset;
3318 isl_union_map *umap;
3320 if (!is_condition(&graph->edge[i]))
3321 continue;
3322 if (is_local(&graph->edge[i]))
3323 continue;
3324 local = is_condition_false(&graph->edge[i]);
3325 if (local < 0)
3326 goto error;
3327 if (local)
3328 continue;
3330 any = 1;
3332 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3333 uset = isl_union_map_domain(umap);
3334 source = isl_union_set_union(source, uset);
3336 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3337 uset = isl_union_map_range(umap);
3338 sink = isl_union_set_union(sink, uset);
3341 for (i = 0; i < graph->n_edge; ++i) {
3342 if (update_edge(ctx, graph, &graph->edge[i]) < 0)
3343 goto error;
3346 if (any)
3347 return unconditionalize_adjacent_validity(graph, source, sink);
3349 isl_union_set_free(source);
3350 isl_union_set_free(sink);
3351 return 0;
3352 error:
3353 isl_union_set_free(source);
3354 isl_union_set_free(sink);
3355 return -1;
3358 static void next_band(struct isl_sched_graph *graph)
3360 graph->band_start = graph->n_total_row;
3363 /* Return the union of the universe domains of the nodes in "graph"
3364 * that satisfy "pred".
3366 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3367 struct isl_sched_graph *graph,
3368 int (*pred)(struct isl_sched_node *node, int data), int data)
3370 int i;
3371 isl_set *set;
3372 isl_union_set *dom;
3374 for (i = 0; i < graph->n; ++i)
3375 if (pred(&graph->node[i], data))
3376 break;
3378 if (i >= graph->n)
3379 isl_die(ctx, isl_error_internal,
3380 "empty component", return NULL);
3382 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3383 dom = isl_union_set_from_set(set);
3385 for (i = i + 1; i < graph->n; ++i) {
3386 if (!pred(&graph->node[i], data))
3387 continue;
3388 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3389 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3392 return dom;
3395 /* Return a list of unions of universe domains, where each element
3396 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3398 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3399 struct isl_sched_graph *graph)
3401 int i;
3402 isl_union_set_list *filters;
3404 filters = isl_union_set_list_alloc(ctx, graph->scc);
3405 for (i = 0; i < graph->scc; ++i) {
3406 isl_union_set *dom;
3408 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3409 filters = isl_union_set_list_add(filters, dom);
3412 return filters;
3415 /* Return a list of two unions of universe domains, one for the SCCs up
3416 * to and including graph->src_scc and another for the other SCCs.
3418 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3419 struct isl_sched_graph *graph)
3421 isl_union_set *dom;
3422 isl_union_set_list *filters;
3424 filters = isl_union_set_list_alloc(ctx, 2);
3425 dom = isl_sched_graph_domain(ctx, graph,
3426 &node_scc_at_most, graph->src_scc);
3427 filters = isl_union_set_list_add(filters, dom);
3428 dom = isl_sched_graph_domain(ctx, graph,
3429 &node_scc_at_least, graph->src_scc + 1);
3430 filters = isl_union_set_list_add(filters, dom);
3432 return filters;
3435 /* Copy nodes that satisfy node_pred from the src dependence graph
3436 * to the dst dependence graph.
3438 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3439 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3441 int i;
3443 dst->n = 0;
3444 for (i = 0; i < src->n; ++i) {
3445 int j;
3447 if (!node_pred(&src->node[i], data))
3448 continue;
3450 j = dst->n;
3451 dst->node[j].space = isl_space_copy(src->node[i].space);
3452 dst->node[j].compressed = src->node[i].compressed;
3453 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3454 dst->node[j].compress =
3455 isl_multi_aff_copy(src->node[i].compress);
3456 dst->node[j].decompress =
3457 isl_multi_aff_copy(src->node[i].decompress);
3458 dst->node[j].nvar = src->node[i].nvar;
3459 dst->node[j].nparam = src->node[i].nparam;
3460 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3461 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3462 dst->node[j].coincident = src->node[i].coincident;
3463 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3464 dst->node[j].bounds = isl_basic_set_copy(src->node[i].bounds);
3465 dst->node[j].max = isl_vec_copy(src->node[i].max);
3466 dst->n++;
3468 if (!dst->node[j].space || !dst->node[j].sched)
3469 return -1;
3470 if (dst->node[j].compressed &&
3471 (!dst->node[j].hull || !dst->node[j].compress ||
3472 !dst->node[j].decompress))
3473 return -1;
3476 return 0;
3479 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3480 * to the dst dependence graph.
3481 * If the source or destination node of the edge is not in the destination
3482 * graph, then it must be a backward proximity edge and it should simply
3483 * be ignored.
3485 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3486 struct isl_sched_graph *src,
3487 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3489 int i;
3491 dst->n_edge = 0;
3492 for (i = 0; i < src->n_edge; ++i) {
3493 struct isl_sched_edge *edge = &src->edge[i];
3494 isl_map *map;
3495 isl_union_map *tagged_condition;
3496 isl_union_map *tagged_validity;
3497 struct isl_sched_node *dst_src, *dst_dst;
3499 if (!edge_pred(edge, data))
3500 continue;
3502 if (isl_map_plain_is_empty(edge->map))
3503 continue;
3505 dst_src = graph_find_node(ctx, dst, edge->src->space);
3506 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3507 if (!dst_src || !dst_dst) {
3508 if (is_validity(edge) || is_conditional_validity(edge))
3509 isl_die(ctx, isl_error_internal,
3510 "backward (conditional) validity edge",
3511 return -1);
3512 continue;
3515 map = isl_map_copy(edge->map);
3516 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3517 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3519 dst->edge[dst->n_edge].src = dst_src;
3520 dst->edge[dst->n_edge].dst = dst_dst;
3521 dst->edge[dst->n_edge].map = map;
3522 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3523 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3524 dst->edge[dst->n_edge].types = edge->types;
3525 dst->n_edge++;
3527 if (edge->tagged_condition && !tagged_condition)
3528 return -1;
3529 if (edge->tagged_validity && !tagged_validity)
3530 return -1;
3532 if (graph_edge_tables_add(ctx, dst,
3533 &dst->edge[dst->n_edge - 1]) < 0)
3534 return -1;
3537 return 0;
3540 /* Compute the maximal number of variables over all nodes.
3541 * This is the maximal number of linearly independent schedule
3542 * rows that we need to compute.
3543 * Just in case we end up in a part of the dependence graph
3544 * with only lower-dimensional domains, we make sure we will
3545 * compute the required amount of extra linearly independent rows.
3547 static int compute_maxvar(struct isl_sched_graph *graph)
3549 int i;
3551 graph->maxvar = 0;
3552 for (i = 0; i < graph->n; ++i) {
3553 struct isl_sched_node *node = &graph->node[i];
3554 int nvar;
3556 if (node_update_vmap(node) < 0)
3557 return -1;
3558 nvar = node->nvar + graph->n_row - node->rank;
3559 if (nvar > graph->maxvar)
3560 graph->maxvar = nvar;
3563 return 0;
3566 /* Extract the subgraph of "graph" that consists of the nodes satisfying
3567 * "node_pred" and the edges satisfying "edge_pred" and store
3568 * the result in "sub".
3570 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3571 int (*node_pred)(struct isl_sched_node *node, int data),
3572 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3573 int data, struct isl_sched_graph *sub)
3575 int i, n = 0, n_edge = 0;
3576 int t;
3578 for (i = 0; i < graph->n; ++i)
3579 if (node_pred(&graph->node[i], data))
3580 ++n;
3581 for (i = 0; i < graph->n_edge; ++i)
3582 if (edge_pred(&graph->edge[i], data))
3583 ++n_edge;
3584 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3585 return -1;
3586 sub->root = graph->root;
3587 if (copy_nodes(sub, graph, node_pred, data) < 0)
3588 return -1;
3589 if (graph_init_table(ctx, sub) < 0)
3590 return -1;
3591 for (t = 0; t <= isl_edge_last; ++t)
3592 sub->max_edge[t] = graph->max_edge[t];
3593 if (graph_init_edge_tables(ctx, sub) < 0)
3594 return -1;
3595 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3596 return -1;
3597 sub->n_row = graph->n_row;
3598 sub->max_row = graph->max_row;
3599 sub->n_total_row = graph->n_total_row;
3600 sub->band_start = graph->band_start;
3602 return 0;
3605 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3606 struct isl_sched_graph *graph);
3607 static __isl_give isl_schedule_node *compute_schedule_wcc(
3608 isl_schedule_node *node, struct isl_sched_graph *graph);
3610 /* Compute a schedule for a subgraph of "graph". In particular, for
3611 * the graph composed of nodes that satisfy node_pred and edges that
3612 * that satisfy edge_pred.
3613 * If the subgraph is known to consist of a single component, then wcc should
3614 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3615 * Otherwise, we call compute_schedule, which will check whether the subgraph
3616 * is connected.
3618 * The schedule is inserted at "node" and the updated schedule node
3619 * is returned.
3621 static __isl_give isl_schedule_node *compute_sub_schedule(
3622 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3623 struct isl_sched_graph *graph,
3624 int (*node_pred)(struct isl_sched_node *node, int data),
3625 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3626 int data, int wcc)
3628 struct isl_sched_graph split = { 0 };
3630 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3631 &split) < 0)
3632 goto error;
3634 if (wcc)
3635 node = compute_schedule_wcc(node, &split);
3636 else
3637 node = compute_schedule(node, &split);
3639 graph_free(ctx, &split);
3640 return node;
3641 error:
3642 graph_free(ctx, &split);
3643 return isl_schedule_node_free(node);
3646 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3648 return edge->src->scc == scc && edge->dst->scc == scc;
3651 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3653 return edge->dst->scc <= scc;
3656 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3658 return edge->src->scc >= scc;
3661 /* Reset the current band by dropping all its schedule rows.
3663 static int reset_band(struct isl_sched_graph *graph)
3665 int i;
3666 int drop;
3668 drop = graph->n_total_row - graph->band_start;
3669 graph->n_total_row -= drop;
3670 graph->n_row -= drop;
3672 for (i = 0; i < graph->n; ++i) {
3673 struct isl_sched_node *node = &graph->node[i];
3675 isl_map_free(node->sched_map);
3676 node->sched_map = NULL;
3678 node->sched = isl_mat_drop_rows(node->sched,
3679 graph->band_start, drop);
3681 if (!node->sched)
3682 return -1;
3685 return 0;
3688 /* Split the current graph into two parts and compute a schedule for each
3689 * part individually. In particular, one part consists of all SCCs up
3690 * to and including graph->src_scc, while the other part contains the other
3691 * SCCs. The split is enforced by a sequence node inserted at position "node"
3692 * in the schedule tree. Return the updated schedule node.
3693 * If either of these two parts consists of a sequence, then it is spliced
3694 * into the sequence containing the two parts.
3696 * The current band is reset. It would be possible to reuse
3697 * the previously computed rows as the first rows in the next
3698 * band, but recomputing them may result in better rows as we are looking
3699 * at a smaller part of the dependence graph.
3701 static __isl_give isl_schedule_node *compute_split_schedule(
3702 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3704 int is_seq;
3705 isl_ctx *ctx;
3706 isl_union_set_list *filters;
3708 if (!node)
3709 return NULL;
3711 if (reset_band(graph) < 0)
3712 return isl_schedule_node_free(node);
3714 next_band(graph);
3716 ctx = isl_schedule_node_get_ctx(node);
3717 filters = extract_split(ctx, graph);
3718 node = isl_schedule_node_insert_sequence(node, filters);
3719 node = isl_schedule_node_child(node, 1);
3720 node = isl_schedule_node_child(node, 0);
3722 node = compute_sub_schedule(node, ctx, graph,
3723 &node_scc_at_least, &edge_src_scc_at_least,
3724 graph->src_scc + 1, 0);
3725 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3726 node = isl_schedule_node_parent(node);
3727 node = isl_schedule_node_parent(node);
3728 if (is_seq)
3729 node = isl_schedule_node_sequence_splice_child(node, 1);
3730 node = isl_schedule_node_child(node, 0);
3731 node = isl_schedule_node_child(node, 0);
3732 node = compute_sub_schedule(node, ctx, graph,
3733 &node_scc_at_most, &edge_dst_scc_at_most,
3734 graph->src_scc, 0);
3735 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3736 node = isl_schedule_node_parent(node);
3737 node = isl_schedule_node_parent(node);
3738 if (is_seq)
3739 node = isl_schedule_node_sequence_splice_child(node, 0);
3741 return node;
3744 /* Insert a band node at position "node" in the schedule tree corresponding
3745 * to the current band in "graph". Mark the band node permutable
3746 * if "permutable" is set.
3747 * The partial schedules and the coincidence property are extracted
3748 * from the graph nodes.
3749 * Return the updated schedule node.
3751 static __isl_give isl_schedule_node *insert_current_band(
3752 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3753 int permutable)
3755 int i;
3756 int start, end, n;
3757 isl_multi_aff *ma;
3758 isl_multi_pw_aff *mpa;
3759 isl_multi_union_pw_aff *mupa;
3761 if (!node)
3762 return NULL;
3764 if (graph->n < 1)
3765 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3766 "graph should have at least one node",
3767 return isl_schedule_node_free(node));
3769 start = graph->band_start;
3770 end = graph->n_total_row;
3771 n = end - start;
3773 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3774 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3775 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3777 for (i = 1; i < graph->n; ++i) {
3778 isl_multi_union_pw_aff *mupa_i;
3780 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3781 start, n);
3782 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3783 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3784 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3786 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3788 for (i = 0; i < n; ++i)
3789 node = isl_schedule_node_band_member_set_coincident(node, i,
3790 graph->node[0].coincident[start + i]);
3791 node = isl_schedule_node_band_set_permutable(node, permutable);
3793 return node;
3796 /* Update the dependence relations based on the current schedule,
3797 * add the current band to "node" and then continue with the computation
3798 * of the next band.
3799 * Return the updated schedule node.
3801 static __isl_give isl_schedule_node *compute_next_band(
3802 __isl_take isl_schedule_node *node,
3803 struct isl_sched_graph *graph, int permutable)
3805 isl_ctx *ctx;
3807 if (!node)
3808 return NULL;
3810 ctx = isl_schedule_node_get_ctx(node);
3811 if (update_edges(ctx, graph) < 0)
3812 return isl_schedule_node_free(node);
3813 node = insert_current_band(node, graph, permutable);
3814 next_band(graph);
3816 node = isl_schedule_node_child(node, 0);
3817 node = compute_schedule(node, graph);
3818 node = isl_schedule_node_parent(node);
3820 return node;
3823 /* Add the constraints "coef" derived from an edge from "node" to itself
3824 * to graph->lp in order to respect the dependences and to try and carry them.
3825 * "pos" is the sequence number of the edge that needs to be carried.
3826 * "coef" represents general constraints on coefficients (c_0, c_x)
3827 * of valid constraints for (y - x) with x and y instances of the node.
3829 * The constraints added to graph->lp need to enforce
3831 * (c_j_0 + c_j_x y) - (c_j_0 + c_j_x x)
3832 * = c_j_x (y - x) >= e_i
3834 * for each (x,y) in the dependence relation of the edge.
3835 * That is, (-e_i, c_j_x) needs to be plugged in for (c_0, c_x),
3836 * taking into account that each coefficient in c_j_x is represented
3837 * as a pair of non-negative coefficients.
3839 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3840 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3842 int offset;
3843 isl_ctx *ctx;
3844 isl_dim_map *dim_map;
3846 if (!coef)
3847 return isl_stat_error;
3849 ctx = isl_basic_set_get_ctx(coef);
3850 offset = coef_var_offset(coef);
3851 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3852 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3853 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3855 return isl_stat_ok;
3858 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3859 * to graph->lp in order to respect the dependences and to try and carry them.
3860 * "pos" is the sequence number of the edge that needs to be carried or
3861 * -1 if no attempt should be made to carry the dependences.
3862 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3863 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3865 * The constraints added to graph->lp need to enforce
3867 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3869 * for each (x,y) in the dependence relation of the edge or
3871 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= 0
3873 * if pos is -1.
3874 * That is,
3875 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3876 * or
3877 * (c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3878 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3879 * taking into account that each coefficient in c_j_x and c_k_x is represented
3880 * as a pair of non-negative coefficients.
3882 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3883 struct isl_sched_node *src, struct isl_sched_node *dst,
3884 __isl_take isl_basic_set *coef, int pos)
3886 int offset;
3887 isl_ctx *ctx;
3888 isl_dim_map *dim_map;
3890 if (!coef)
3891 return isl_stat_error;
3893 ctx = isl_basic_set_get_ctx(coef);
3894 offset = coef_var_offset(coef);
3895 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3896 if (pos >= 0)
3897 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3898 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3900 return isl_stat_ok;
3903 /* Data structure for keeping track of the data needed
3904 * to exploit non-trivial lineality spaces.
3906 * "any_non_trivial" is true if there are any non-trivial lineality spaces.
3907 * If "any_non_trivial" is not true, then "equivalent" and "mask" may be NULL.
3908 * "equivalent" connects instances to other instances on the same line(s).
3909 * "mask" contains the domain spaces of "equivalent".
3910 * Any instance set not in "mask" does not have a non-trivial lineality space.
3912 struct isl_exploit_lineality_data {
3913 isl_bool any_non_trivial;
3914 isl_union_map *equivalent;
3915 isl_union_set *mask;
3918 /* Data structure collecting information used during the construction
3919 * of an LP for carrying dependences.
3921 * "intra" is a sequence of coefficient constraints for intra-node edges.
3922 * "inter" is a sequence of coefficient constraints for inter-node edges.
3923 * "lineality" contains data used to exploit non-trivial lineality spaces.
3925 struct isl_carry {
3926 isl_basic_set_list *intra;
3927 isl_basic_set_list *inter;
3928 struct isl_exploit_lineality_data lineality;
3931 /* Free all the data stored in "carry".
3933 static void isl_carry_clear(struct isl_carry *carry)
3935 isl_basic_set_list_free(carry->intra);
3936 isl_basic_set_list_free(carry->inter);
3937 isl_union_map_free(carry->lineality.equivalent);
3938 isl_union_set_free(carry->lineality.mask);
3941 /* Return a pointer to the node in "graph" that lives in "space".
3942 * If the requested node has been compressed, then "space"
3943 * corresponds to the compressed space.
3945 * First try and see if "space" is the space of an uncompressed node.
3946 * If so, return that node.
3947 * Otherwise, "space" was constructed by construct_compressed_id and
3948 * contains a user pointer pointing to the node in the tuple id.
3949 * However, this node belongs to the original dependence graph.
3950 * If "graph" is a subgraph of this original dependence graph,
3951 * then the node with the same space still needs to be looked up
3952 * in the current graph.
3954 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3955 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3957 isl_id *id;
3958 struct isl_sched_node *node;
3960 if (!space)
3961 return NULL;
3963 node = graph_find_node(ctx, graph, space);
3964 if (node)
3965 return node;
3967 id = isl_space_get_tuple_id(space, isl_dim_set);
3968 node = isl_id_get_user(id);
3969 isl_id_free(id);
3971 if (!node)
3972 return NULL;
3974 if (!is_node(graph->root, node))
3975 isl_die(ctx, isl_error_internal,
3976 "space points to invalid node", return NULL);
3977 if (graph != graph->root)
3978 node = graph_find_node(ctx, graph, node->space);
3980 return node;
3983 /* Internal data structure for add_all_constraints.
3985 * "graph" is the schedule constraint graph for which an LP problem
3986 * is being constructed.
3987 * "carry_inter" indicates whether inter-node edges should be carried.
3988 * "pos" is the position of the next edge that needs to be carried.
3990 struct isl_add_all_constraints_data {
3991 isl_ctx *ctx;
3992 struct isl_sched_graph *graph;
3993 int carry_inter;
3994 int pos;
3997 /* Add the constraints "coef" derived from an edge from a node to itself
3998 * to data->graph->lp in order to respect the dependences and
3999 * to try and carry them.
4001 * The space of "coef" is of the form
4003 * coefficients[[c_cst] -> S[c_x]]
4005 * with S[c_x] the (compressed) space of the node.
4006 * Extract the node from the space and call add_intra_constraints.
4008 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
4010 struct isl_add_all_constraints_data *data = user;
4011 isl_space *space;
4012 struct isl_sched_node *node;
4014 space = isl_basic_set_get_space(coef);
4015 space = isl_space_range(isl_space_unwrap(space));
4016 node = graph_find_compressed_node(data->ctx, data->graph, space);
4017 isl_space_free(space);
4018 return add_intra_constraints(data->graph, node, coef, data->pos++);
4021 /* Add the constraints "coef" derived from an edge from a node j
4022 * to a node k to data->graph->lp in order to respect the dependences and
4023 * to try and carry them (provided data->carry_inter is set).
4025 * The space of "coef" is of the form
4027 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
4029 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
4030 * Extract the nodes from the space and call add_inter_constraints.
4032 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
4034 struct isl_add_all_constraints_data *data = user;
4035 isl_space *space, *dom;
4036 struct isl_sched_node *src, *dst;
4037 int pos;
4039 space = isl_basic_set_get_space(coef);
4040 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
4041 dom = isl_space_domain(isl_space_copy(space));
4042 src = graph_find_compressed_node(data->ctx, data->graph, dom);
4043 isl_space_free(dom);
4044 space = isl_space_range(space);
4045 dst = graph_find_compressed_node(data->ctx, data->graph, space);
4046 isl_space_free(space);
4048 pos = data->carry_inter ? data->pos++ : -1;
4049 return add_inter_constraints(data->graph, src, dst, coef, pos);
4052 /* Add constraints to graph->lp that force all (conditional) validity
4053 * dependences to be respected and attempt to carry them.
4054 * "intra" is the sequence of coefficient constraints for intra-node edges.
4055 * "inter" is the sequence of coefficient constraints for inter-node edges.
4056 * "carry_inter" indicates whether inter-node edges should be carried or
4057 * only respected.
4059 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
4060 __isl_keep isl_basic_set_list *intra,
4061 __isl_keep isl_basic_set_list *inter, int carry_inter)
4063 struct isl_add_all_constraints_data data = { ctx, graph, carry_inter };
4065 data.pos = 0;
4066 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
4067 return isl_stat_error;
4068 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
4069 return isl_stat_error;
4070 return isl_stat_ok;
4073 /* Internal data structure for count_all_constraints
4074 * for keeping track of the number of equality and inequality constraints.
4076 struct isl_sched_count {
4077 int n_eq;
4078 int n_ineq;
4081 /* Add the number of equality and inequality constraints of "bset"
4082 * to data->n_eq and data->n_ineq.
4084 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
4086 struct isl_sched_count *data = user;
4088 return update_count(bset, 1, &data->n_eq, &data->n_ineq);
4091 /* Count the number of equality and inequality constraints
4092 * that will be added to the carry_lp problem.
4093 * We count each edge exactly once.
4094 * "intra" is the sequence of coefficient constraints for intra-node edges.
4095 * "inter" is the sequence of coefficient constraints for inter-node edges.
4097 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
4098 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
4100 struct isl_sched_count data;
4102 data.n_eq = data.n_ineq = 0;
4103 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
4104 return isl_stat_error;
4105 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
4106 return isl_stat_error;
4108 *n_eq = data.n_eq;
4109 *n_ineq = data.n_ineq;
4111 return isl_stat_ok;
4114 /* Construct an LP problem for finding schedule coefficients
4115 * such that the schedule carries as many validity dependences as possible.
4116 * In particular, for each dependence i, we bound the dependence distance
4117 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
4118 * of all e_i's. Dependences with e_i = 0 in the solution are simply
4119 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
4120 * "intra" is the sequence of coefficient constraints for intra-node edges.
4121 * "inter" is the sequence of coefficient constraints for inter-node edges.
4122 * "n_edge" is the total number of edges.
4123 * "carry_inter" indicates whether inter-node edges should be carried or
4124 * only respected. That is, if "carry_inter" is not set, then
4125 * no e_i variables are introduced for the inter-node edges.
4127 * All variables of the LP are non-negative. The actual coefficients
4128 * may be negative, so each coefficient is represented as the difference
4129 * of two non-negative variables. The negative part always appears
4130 * immediately before the positive part.
4131 * Other than that, the variables have the following order
4133 * - sum of (1 - e_i) over all edges
4134 * - sum of all c_n coefficients
4135 * (unconstrained when computing non-parametric schedules)
4136 * - sum of positive and negative parts of all c_x coefficients
4137 * - for each edge
4138 * - e_i
4139 * - for each node
4140 * - positive and negative parts of c_i_x, in opposite order
4141 * - c_i_n (if parametric)
4142 * - c_i_0
4144 * The constraints are those from the (validity) edges plus three equalities
4145 * to express the sums and n_edge inequalities to express e_i <= 1.
4147 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
4148 int n_edge, __isl_keep isl_basic_set_list *intra,
4149 __isl_keep isl_basic_set_list *inter, int carry_inter)
4151 int i;
4152 int k;
4153 isl_space *dim;
4154 unsigned total;
4155 int n_eq, n_ineq;
4157 total = 3 + n_edge;
4158 for (i = 0; i < graph->n; ++i) {
4159 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
4160 node->start = total;
4161 total += 1 + node->nparam + 2 * node->nvar;
4164 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
4165 return isl_stat_error;
4167 dim = isl_space_set_alloc(ctx, 0, total);
4168 isl_basic_set_free(graph->lp);
4169 n_eq += 3;
4170 n_ineq += n_edge;
4171 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
4172 graph->lp = isl_basic_set_set_rational(graph->lp);
4174 k = isl_basic_set_alloc_equality(graph->lp);
4175 if (k < 0)
4176 return isl_stat_error;
4177 isl_seq_clr(graph->lp->eq[k], 1 + total);
4178 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
4179 isl_int_set_si(graph->lp->eq[k][1], 1);
4180 for (i = 0; i < n_edge; ++i)
4181 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
4183 if (add_param_sum_constraint(graph, 1) < 0)
4184 return isl_stat_error;
4185 if (add_var_sum_constraint(graph, 2) < 0)
4186 return isl_stat_error;
4188 for (i = 0; i < n_edge; ++i) {
4189 k = isl_basic_set_alloc_inequality(graph->lp);
4190 if (k < 0)
4191 return isl_stat_error;
4192 isl_seq_clr(graph->lp->ineq[k], 1 + total);
4193 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
4194 isl_int_set_si(graph->lp->ineq[k][0], 1);
4197 if (add_all_constraints(ctx, graph, intra, inter, carry_inter) < 0)
4198 return isl_stat_error;
4200 return isl_stat_ok;
4203 static __isl_give isl_schedule_node *compute_component_schedule(
4204 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4205 int wcc);
4207 /* If the schedule_split_scaled option is set and if the linear
4208 * parts of the scheduling rows for all nodes in the graphs have
4209 * a non-trivial common divisor, then remove this
4210 * common divisor from the linear part.
4211 * Otherwise, insert a band node directly and continue with
4212 * the construction of the schedule.
4214 * If a non-trivial common divisor is found, then
4215 * the linear part is reduced and the remainder is ignored.
4216 * The pieces of the graph that are assigned different remainders
4217 * form (groups of) strongly connected components within
4218 * the scaled down band. If needed, they can therefore
4219 * be ordered along this remainder in a sequence node.
4220 * However, this ordering is not enforced here in order to allow
4221 * the scheduler to combine some of the strongly connected components.
4223 static __isl_give isl_schedule_node *split_scaled(
4224 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4226 int i;
4227 int row;
4228 isl_ctx *ctx;
4229 isl_int gcd, gcd_i;
4231 if (!node)
4232 return NULL;
4234 ctx = isl_schedule_node_get_ctx(node);
4235 if (!ctx->opt->schedule_split_scaled)
4236 return compute_next_band(node, graph, 0);
4237 if (graph->n <= 1)
4238 return compute_next_band(node, graph, 0);
4240 isl_int_init(gcd);
4241 isl_int_init(gcd_i);
4243 isl_int_set_si(gcd, 0);
4245 row = isl_mat_rows(graph->node[0].sched) - 1;
4247 for (i = 0; i < graph->n; ++i) {
4248 struct isl_sched_node *node = &graph->node[i];
4249 int cols = isl_mat_cols(node->sched);
4251 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4252 isl_int_gcd(gcd, gcd, gcd_i);
4255 isl_int_clear(gcd_i);
4257 if (isl_int_cmp_si(gcd, 1) <= 0) {
4258 isl_int_clear(gcd);
4259 return compute_next_band(node, graph, 0);
4262 for (i = 0; i < graph->n; ++i) {
4263 struct isl_sched_node *node = &graph->node[i];
4265 isl_int_fdiv_q(node->sched->row[row][0],
4266 node->sched->row[row][0], gcd);
4267 isl_int_mul(node->sched->row[row][0],
4268 node->sched->row[row][0], gcd);
4269 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4270 if (!node->sched)
4271 goto error;
4274 isl_int_clear(gcd);
4276 return compute_next_band(node, graph, 0);
4277 error:
4278 isl_int_clear(gcd);
4279 return isl_schedule_node_free(node);
4282 /* Is the schedule row "sol" trivial on node "node"?
4283 * That is, is the solution zero on the dimensions linearly independent of
4284 * the previously found solutions?
4285 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4287 * Each coefficient is represented as the difference between
4288 * two non-negative values in "sol".
4289 * We construct the schedule row s and check if it is linearly
4290 * independent of previously computed schedule rows
4291 * by computing T s, with T the linear combinations that are zero
4292 * on linearly dependent schedule rows.
4293 * If the result consists of all zeros, then the solution is trivial.
4295 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4297 int trivial;
4298 isl_vec *node_sol;
4300 if (!sol)
4301 return -1;
4302 if (node->nvar == node->rank)
4303 return 0;
4305 node_sol = extract_var_coef(node, sol);
4306 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4307 if (!node_sol)
4308 return -1;
4310 trivial = isl_seq_first_non_zero(node_sol->el,
4311 node->nvar - node->rank) == -1;
4313 isl_vec_free(node_sol);
4315 return trivial;
4318 /* Is the schedule row "sol" trivial on any node where it should
4319 * not be trivial?
4320 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4322 static int is_any_trivial(struct isl_sched_graph *graph,
4323 __isl_keep isl_vec *sol)
4325 int i;
4327 for (i = 0; i < graph->n; ++i) {
4328 struct isl_sched_node *node = &graph->node[i];
4329 int trivial;
4331 if (!needs_row(graph, node))
4332 continue;
4333 trivial = is_trivial(node, sol);
4334 if (trivial < 0 || trivial)
4335 return trivial;
4338 return 0;
4341 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4342 * If so, return the position of the coalesced dimension.
4343 * Otherwise, return node->nvar or -1 on error.
4345 * In particular, look for pairs of coefficients c_i and c_j such that
4346 * |c_j/c_i| > ceil(size_i/2), i.e., |c_j| > |c_i * ceil(size_i/2)|.
4347 * If any such pair is found, then return i.
4348 * If size_i is infinity, then no check on c_i needs to be performed.
4350 static int find_node_coalescing(struct isl_sched_node *node,
4351 __isl_keep isl_vec *sol)
4353 int i, j;
4354 isl_int max;
4355 isl_vec *csol;
4357 if (node->nvar <= 1)
4358 return node->nvar;
4360 csol = extract_var_coef(node, sol);
4361 if (!csol)
4362 return -1;
4363 isl_int_init(max);
4364 for (i = 0; i < node->nvar; ++i) {
4365 isl_val *v;
4367 if (isl_int_is_zero(csol->el[i]))
4368 continue;
4369 v = isl_multi_val_get_val(node->sizes, i);
4370 if (!v)
4371 goto error;
4372 if (!isl_val_is_int(v)) {
4373 isl_val_free(v);
4374 continue;
4376 v = isl_val_div_ui(v, 2);
4377 v = isl_val_ceil(v);
4378 if (!v)
4379 goto error;
4380 isl_int_mul(max, v->n, csol->el[i]);
4381 isl_val_free(v);
4383 for (j = 0; j < node->nvar; ++j) {
4384 if (j == i)
4385 continue;
4386 if (isl_int_abs_gt(csol->el[j], max))
4387 break;
4389 if (j < node->nvar)
4390 break;
4393 isl_int_clear(max);
4394 isl_vec_free(csol);
4395 return i;
4396 error:
4397 isl_int_clear(max);
4398 isl_vec_free(csol);
4399 return -1;
4402 /* Force the schedule coefficient at position "pos" of "node" to be zero
4403 * in "tl".
4404 * The coefficient is encoded as the difference between two non-negative
4405 * variables. Force these two variables to have the same value.
4407 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4408 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4410 int dim;
4411 isl_ctx *ctx;
4412 isl_vec *eq;
4414 ctx = isl_space_get_ctx(node->space);
4415 dim = isl_tab_lexmin_dim(tl);
4416 if (dim < 0)
4417 return isl_tab_lexmin_free(tl);
4418 eq = isl_vec_alloc(ctx, 1 + dim);
4419 eq = isl_vec_clr(eq);
4420 if (!eq)
4421 return isl_tab_lexmin_free(tl);
4423 pos = 1 + node_var_coef_pos(node, pos);
4424 isl_int_set_si(eq->el[pos], 1);
4425 isl_int_set_si(eq->el[pos + 1], -1);
4426 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4427 isl_vec_free(eq);
4429 return tl;
4432 /* Return the lexicographically smallest rational point in the basic set
4433 * from which "tl" was constructed, double checking that this input set
4434 * was not empty.
4436 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4438 isl_vec *sol;
4440 sol = isl_tab_lexmin_get_solution(tl);
4441 if (!sol)
4442 return NULL;
4443 if (sol->size == 0)
4444 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4445 "error in schedule construction",
4446 return isl_vec_free(sol));
4447 return sol;
4450 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4451 * carry any of the "n_edge" groups of dependences?
4452 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4453 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4454 * by the edge are carried by the solution.
4455 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4456 * one of those is carried.
4458 * Note that despite the fact that the problem is solved using a rational
4459 * solver, the solution is guaranteed to be integral.
4460 * Specifically, the dependence distance lower bounds e_i (and therefore
4461 * also their sum) are integers. See Lemma 5 of [1].
4463 * Any potential denominator of the sum is cleared by this function.
4464 * The denominator is not relevant for any of the other elements
4465 * in the solution.
4467 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4468 * Problem, Part II: Multi-Dimensional Time.
4469 * In Intl. Journal of Parallel Programming, 1992.
4471 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4473 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4474 isl_int_set_si(sol->el[0], 1);
4475 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4478 /* Return the lexicographically smallest rational point in "lp",
4479 * assuming that all variables are non-negative and performing some
4480 * additional sanity checks.
4481 * If "want_integral" is set, then compute the lexicographically smallest
4482 * integer point instead.
4483 * In particular, "lp" should not be empty by construction.
4484 * Double check that this is the case.
4485 * If dependences are not carried for any of the "n_edge" edges,
4486 * then return an empty vector.
4488 * If the schedule_treat_coalescing option is set and
4489 * if the computed schedule performs loop coalescing on a given node,
4490 * i.e., if it is of the form
4492 * c_i i + c_j j + ...
4494 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4495 * to cut out this solution. Repeat this process until no more loop
4496 * coalescing occurs or until no more dependences can be carried.
4497 * In the latter case, revert to the previously computed solution.
4499 * If the caller requests an integral solution and if coalescing should
4500 * be treated, then perform the coalescing treatment first as
4501 * an integral solution computed before coalescing treatment
4502 * would carry the same number of edges and would therefore probably
4503 * also be coalescing.
4505 * To allow the coalescing treatment to be performed first,
4506 * the initial solution is allowed to be rational and it is only
4507 * cut out (if needed) in the next iteration, if no coalescing measures
4508 * were taken.
4510 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4511 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4513 int i, pos, cut;
4514 isl_ctx *ctx;
4515 isl_tab_lexmin *tl;
4516 isl_vec *sol = NULL, *prev;
4517 int treat_coalescing;
4518 int try_again;
4520 if (!lp)
4521 return NULL;
4522 ctx = isl_basic_set_get_ctx(lp);
4523 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4524 tl = isl_tab_lexmin_from_basic_set(lp);
4526 cut = 0;
4527 do {
4528 int integral;
4530 try_again = 0;
4531 if (cut)
4532 tl = isl_tab_lexmin_cut_to_integer(tl);
4533 prev = sol;
4534 sol = non_empty_solution(tl);
4535 if (!sol)
4536 goto error;
4538 integral = isl_int_is_one(sol->el[0]);
4539 if (!carries_dependences(sol, n_edge)) {
4540 if (!prev)
4541 prev = isl_vec_alloc(ctx, 0);
4542 isl_vec_free(sol);
4543 sol = prev;
4544 break;
4546 prev = isl_vec_free(prev);
4547 cut = want_integral && !integral;
4548 if (cut)
4549 try_again = 1;
4550 if (!treat_coalescing)
4551 continue;
4552 for (i = 0; i < graph->n; ++i) {
4553 struct isl_sched_node *node = &graph->node[i];
4555 pos = find_node_coalescing(node, sol);
4556 if (pos < 0)
4557 goto error;
4558 if (pos < node->nvar)
4559 break;
4561 if (i < graph->n) {
4562 try_again = 1;
4563 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4564 cut = 0;
4566 } while (try_again);
4568 isl_tab_lexmin_free(tl);
4570 return sol;
4571 error:
4572 isl_tab_lexmin_free(tl);
4573 isl_vec_free(prev);
4574 isl_vec_free(sol);
4575 return NULL;
4578 /* If "edge" is an edge from a node to itself, then add the corresponding
4579 * dependence relation to "umap".
4580 * If "node" has been compressed, then the dependence relation
4581 * is also compressed first.
4583 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4584 struct isl_sched_edge *edge)
4586 isl_map *map;
4587 struct isl_sched_node *node = edge->src;
4589 if (edge->src != edge->dst)
4590 return umap;
4592 map = isl_map_copy(edge->map);
4593 if (node->compressed) {
4594 map = isl_map_preimage_domain_multi_aff(map,
4595 isl_multi_aff_copy(node->decompress));
4596 map = isl_map_preimage_range_multi_aff(map,
4597 isl_multi_aff_copy(node->decompress));
4599 umap = isl_union_map_add_map(umap, map);
4600 return umap;
4603 /* If "edge" is an edge from a node to another node, then add the corresponding
4604 * dependence relation to "umap".
4605 * If the source or destination nodes of "edge" have been compressed,
4606 * then the dependence relation is also compressed first.
4608 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4609 struct isl_sched_edge *edge)
4611 isl_map *map;
4613 if (edge->src == edge->dst)
4614 return umap;
4616 map = isl_map_copy(edge->map);
4617 if (edge->src->compressed)
4618 map = isl_map_preimage_domain_multi_aff(map,
4619 isl_multi_aff_copy(edge->src->decompress));
4620 if (edge->dst->compressed)
4621 map = isl_map_preimage_range_multi_aff(map,
4622 isl_multi_aff_copy(edge->dst->decompress));
4623 umap = isl_union_map_add_map(umap, map);
4624 return umap;
4627 /* Internal data structure used by union_drop_coalescing_constraints
4628 * to collect bounds on all relevant statements.
4630 * "graph" is the schedule constraint graph for which an LP problem
4631 * is being constructed.
4632 * "bounds" collects the bounds.
4634 struct isl_collect_bounds_data {
4635 isl_ctx *ctx;
4636 struct isl_sched_graph *graph;
4637 isl_union_set *bounds;
4640 /* Add the size bounds for the node with instance deltas in "set"
4641 * to data->bounds.
4643 static isl_stat collect_bounds(__isl_take isl_set *set, void *user)
4645 struct isl_collect_bounds_data *data = user;
4646 struct isl_sched_node *node;
4647 isl_space *space;
4648 isl_set *bounds;
4650 space = isl_set_get_space(set);
4651 isl_set_free(set);
4653 node = graph_find_compressed_node(data->ctx, data->graph, space);
4654 isl_space_free(space);
4656 bounds = isl_set_from_basic_set(get_size_bounds(node));
4657 data->bounds = isl_union_set_add_set(data->bounds, bounds);
4659 return isl_stat_ok;
4662 /* Drop some constraints from "delta" that could be exploited
4663 * to construct loop coalescing schedules.
4664 * In particular, drop those constraint that bound the difference
4665 * to the size of the domain.
4666 * Do this for each set/node in "delta" separately.
4667 * The parameters are assumed to have been projected out by the caller.
4669 static __isl_give isl_union_set *union_drop_coalescing_constraints(isl_ctx *ctx,
4670 struct isl_sched_graph *graph, __isl_take isl_union_set *delta)
4672 struct isl_collect_bounds_data data = { ctx, graph };
4674 data.bounds = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4675 if (isl_union_set_foreach_set(delta, &collect_bounds, &data) < 0)
4676 data.bounds = isl_union_set_free(data.bounds);
4677 delta = isl_union_set_plain_gist(delta, data.bounds);
4679 return delta;
4682 /* Given a non-trivial lineality space "lineality", add the corresponding
4683 * universe set to data->mask and add a map from elements to
4684 * other elements along the lines in "lineality" to data->equivalent.
4685 * If this is the first time this function gets called
4686 * (data->any_non_trivial is still false), then set data->any_non_trivial and
4687 * initialize data->mask and data->equivalent.
4689 * In particular, if the lineality space is defined by equality constraints
4691 * E x = 0
4693 * then construct an affine mapping
4695 * f : x -> E x
4697 * and compute the equivalence relation of having the same image under f:
4699 * { x -> x' : E x = E x' }
4701 static isl_stat add_non_trivial_lineality(__isl_take isl_basic_set *lineality,
4702 struct isl_exploit_lineality_data *data)
4704 isl_mat *eq;
4705 isl_space *space;
4706 isl_set *univ;
4707 isl_multi_aff *ma;
4708 isl_multi_pw_aff *mpa;
4709 isl_map *map;
4710 int n;
4712 if (!lineality)
4713 return isl_stat_error;
4714 if (isl_basic_set_dim(lineality, isl_dim_div) != 0)
4715 isl_die(isl_basic_set_get_ctx(lineality), isl_error_internal,
4716 "local variables not allowed", goto error);
4718 space = isl_basic_set_get_space(lineality);
4719 if (!data->any_non_trivial) {
4720 data->equivalent = isl_union_map_empty(isl_space_copy(space));
4721 data->mask = isl_union_set_empty(isl_space_copy(space));
4723 data->any_non_trivial = isl_bool_true;
4725 univ = isl_set_universe(isl_space_copy(space));
4726 data->mask = isl_union_set_add_set(data->mask, univ);
4728 eq = isl_basic_set_extract_equalities(lineality);
4729 n = isl_mat_rows(eq);
4730 eq = isl_mat_insert_zero_rows(eq, 0, 1);
4731 eq = isl_mat_set_element_si(eq, 0, 0, 1);
4732 space = isl_space_from_domain(space);
4733 space = isl_space_add_dims(space, isl_dim_out, n);
4734 ma = isl_multi_aff_from_aff_mat(space, eq);
4735 mpa = isl_multi_pw_aff_from_multi_aff(ma);
4736 map = isl_multi_pw_aff_eq_map(mpa, isl_multi_pw_aff_copy(mpa));
4737 data->equivalent = isl_union_map_add_map(data->equivalent, map);
4739 isl_basic_set_free(lineality);
4740 return isl_stat_ok;
4741 error:
4742 isl_basic_set_free(lineality);
4743 return isl_stat_error;
4746 /* Check if the lineality space "set" is non-trivial (i.e., is not just
4747 * the origin or, in other words, satisfies a number of equality constraints
4748 * that is smaller than the dimension of the set).
4749 * If so, extend data->mask and data->equivalent accordingly.
4751 * The input should not have any local variables already, but
4752 * isl_set_remove_divs is called to make sure it does not.
4754 static isl_stat add_lineality(__isl_take isl_set *set, void *user)
4756 struct isl_exploit_lineality_data *data = user;
4757 isl_basic_set *hull;
4758 int dim, n_eq;
4760 set = isl_set_remove_divs(set);
4761 hull = isl_set_unshifted_simple_hull(set);
4762 dim = isl_basic_set_dim(hull, isl_dim_set);
4763 n_eq = isl_basic_set_n_equality(hull);
4764 if (!hull)
4765 return isl_stat_error;
4766 if (dim != n_eq)
4767 return add_non_trivial_lineality(hull, data);
4768 isl_basic_set_free(hull);
4769 return isl_stat_ok;
4772 /* Check if the difference set on intra-node schedule constraints "intra"
4773 * has any non-trivial lineality space.
4774 * If so, then extend the difference set to a difference set
4775 * on equivalent elements. That is, if "intra" is
4777 * { y - x : (x,y) \in V }
4779 * and elements are equivalent if they have the same image under f,
4780 * then return
4782 * { y' - x' : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4784 * or, since f is linear,
4786 * { y' - x' : (x,y) \in V and f(y - x) = f(y' - x') }
4788 * The results of the search for non-trivial lineality spaces is stored
4789 * in "data".
4791 static __isl_give isl_union_set *exploit_intra_lineality(
4792 __isl_take isl_union_set *intra,
4793 struct isl_exploit_lineality_data *data)
4795 isl_union_set *lineality;
4796 isl_union_set *uset;
4798 data->any_non_trivial = isl_bool_false;
4799 lineality = isl_union_set_copy(intra);
4800 lineality = isl_union_set_combined_lineality_space(lineality);
4801 if (isl_union_set_foreach_set(lineality, &add_lineality, data) < 0)
4802 data->any_non_trivial = isl_bool_error;
4803 isl_union_set_free(lineality);
4805 if (data->any_non_trivial < 0)
4806 return isl_union_set_free(intra);
4807 if (!data->any_non_trivial)
4808 return intra;
4810 uset = isl_union_set_copy(intra);
4811 intra = isl_union_set_subtract(intra, isl_union_set_copy(data->mask));
4812 uset = isl_union_set_apply(uset, isl_union_map_copy(data->equivalent));
4813 intra = isl_union_set_union(intra, uset);
4815 intra = isl_union_set_remove_divs(intra);
4817 return intra;
4820 /* If the difference set on intra-node schedule constraints was found to have
4821 * any non-trivial lineality space by exploit_intra_lineality,
4822 * as recorded in "data", then extend the inter-node
4823 * schedule constraints "inter" to schedule constraints on equivalent elements.
4824 * That is, if "inter" is V and
4825 * elements are equivalent if they have the same image under f, then return
4827 * { (x', y') : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4829 static __isl_give isl_union_map *exploit_inter_lineality(
4830 __isl_take isl_union_map *inter,
4831 struct isl_exploit_lineality_data *data)
4833 isl_union_map *umap;
4835 if (data->any_non_trivial < 0)
4836 return isl_union_map_free(inter);
4837 if (!data->any_non_trivial)
4838 return inter;
4840 umap = isl_union_map_copy(inter);
4841 inter = isl_union_map_subtract_range(inter,
4842 isl_union_set_copy(data->mask));
4843 umap = isl_union_map_apply_range(umap,
4844 isl_union_map_copy(data->equivalent));
4845 inter = isl_union_map_union(inter, umap);
4846 umap = isl_union_map_copy(inter);
4847 inter = isl_union_map_subtract_domain(inter,
4848 isl_union_set_copy(data->mask));
4849 umap = isl_union_map_apply_range(isl_union_map_copy(data->equivalent),
4850 umap);
4851 inter = isl_union_map_union(inter, umap);
4853 inter = isl_union_map_remove_divs(inter);
4855 return inter;
4858 /* For each (conditional) validity edge in "graph",
4859 * add the corresponding dependence relation using "add"
4860 * to a collection of dependence relations and return the result.
4861 * If "coincidence" is set, then coincidence edges are considered as well.
4863 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4864 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4865 struct isl_sched_edge *edge), int coincidence)
4867 int i;
4868 isl_space *space;
4869 isl_union_map *umap;
4871 space = isl_space_copy(graph->node[0].space);
4872 umap = isl_union_map_empty(space);
4874 for (i = 0; i < graph->n_edge; ++i) {
4875 struct isl_sched_edge *edge = &graph->edge[i];
4877 if (!is_any_validity(edge) &&
4878 (!coincidence || !is_coincidence(edge)))
4879 continue;
4881 umap = add(umap, edge);
4884 return umap;
4887 /* Project out all parameters from "uset" and return the result.
4889 static __isl_give isl_union_set *union_set_drop_parameters(
4890 __isl_take isl_union_set *uset)
4892 unsigned nparam;
4894 nparam = isl_union_set_dim(uset, isl_dim_param);
4895 return isl_union_set_project_out(uset, isl_dim_param, 0, nparam);
4898 /* For each dependence relation on a (conditional) validity edge
4899 * from a node to itself,
4900 * construct the set of coefficients of valid constraints for elements
4901 * in that dependence relation and collect the results.
4902 * If "coincidence" is set, then coincidence edges are considered as well.
4904 * In particular, for each dependence relation R, constraints
4905 * on coefficients (c_0, c_x) are constructed such that
4907 * c_0 + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4909 * If the schedule_treat_coalescing option is set, then some constraints
4910 * that could be exploited to construct coalescing schedules
4911 * are removed before the dual is computed, but after the parameters
4912 * have been projected out.
4913 * The entire computation is essentially the same as that performed
4914 * by intra_coefficients, except that it operates on multiple
4915 * edges together and that the parameters are always projected out.
4917 * Additionally, exploit any non-trivial lineality space
4918 * in the difference set after removing coalescing constraints and
4919 * store the results of the non-trivial lineality space detection in "data".
4920 * The procedure is currently run unconditionally, but it is unlikely
4921 * to find any non-trivial lineality spaces if no coalescing constraints
4922 * have been removed.
4924 * Note that if a dependence relation is a union of basic maps,
4925 * then each basic map needs to be treated individually as it may only
4926 * be possible to carry the dependences expressed by some of those
4927 * basic maps and not all of them.
4928 * The collected validity constraints are therefore not coalesced and
4929 * it is assumed that they are not coalesced automatically.
4930 * Duplicate basic maps can be removed, however.
4931 * In particular, if the same basic map appears as a disjunct
4932 * in multiple edges, then it only needs to be carried once.
4934 static __isl_give isl_basic_set_list *collect_intra_validity(isl_ctx *ctx,
4935 struct isl_sched_graph *graph, int coincidence,
4936 struct isl_exploit_lineality_data *data)
4938 isl_union_map *intra;
4939 isl_union_set *delta;
4940 isl_basic_set_list *list;
4942 intra = collect_validity(graph, &add_intra, coincidence);
4943 delta = isl_union_map_deltas(intra);
4944 delta = union_set_drop_parameters(delta);
4945 delta = isl_union_set_remove_divs(delta);
4946 if (isl_options_get_schedule_treat_coalescing(ctx))
4947 delta = union_drop_coalescing_constraints(ctx, graph, delta);
4948 delta = exploit_intra_lineality(delta, data);
4949 list = isl_union_set_get_basic_set_list(delta);
4950 isl_union_set_free(delta);
4952 return isl_basic_set_list_coefficients(list);
4955 /* For each dependence relation on a (conditional) validity edge
4956 * from a node to some other node,
4957 * construct the set of coefficients of valid constraints for elements
4958 * in that dependence relation and collect the results.
4959 * If "coincidence" is set, then coincidence edges are considered as well.
4961 * In particular, for each dependence relation R, constraints
4962 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4964 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4966 * This computation is essentially the same as that performed
4967 * by inter_coefficients, except that it operates on multiple
4968 * edges together.
4970 * Additionally, exploit any non-trivial lineality space
4971 * that may have been discovered by collect_intra_validity
4972 * (as stored in "data").
4974 * Note that if a dependence relation is a union of basic maps,
4975 * then each basic map needs to be treated individually as it may only
4976 * be possible to carry the dependences expressed by some of those
4977 * basic maps and not all of them.
4978 * The collected validity constraints are therefore not coalesced and
4979 * it is assumed that they are not coalesced automatically.
4980 * Duplicate basic maps can be removed, however.
4981 * In particular, if the same basic map appears as a disjunct
4982 * in multiple edges, then it only needs to be carried once.
4984 static __isl_give isl_basic_set_list *collect_inter_validity(
4985 struct isl_sched_graph *graph, int coincidence,
4986 struct isl_exploit_lineality_data *data)
4988 isl_union_map *inter;
4989 isl_union_set *wrap;
4990 isl_basic_set_list *list;
4992 inter = collect_validity(graph, &add_inter, coincidence);
4993 inter = exploit_inter_lineality(inter, data);
4994 inter = isl_union_map_remove_divs(inter);
4995 wrap = isl_union_map_wrap(inter);
4996 list = isl_union_set_get_basic_set_list(wrap);
4997 isl_union_set_free(wrap);
4998 return isl_basic_set_list_coefficients(list);
5001 /* Construct an LP problem for finding schedule coefficients
5002 * such that the schedule carries as many of the "n_edge" groups of
5003 * dependences as possible based on the corresponding coefficient
5004 * constraints and return the lexicographically smallest non-trivial solution.
5005 * "intra" is the sequence of coefficient constraints for intra-node edges.
5006 * "inter" is the sequence of coefficient constraints for inter-node edges.
5007 * If "want_integral" is set, then compute an integral solution
5008 * for the coefficients rather than using the numerators
5009 * of a rational solution.
5010 * "carry_inter" indicates whether inter-node edges should be carried or
5011 * only respected.
5013 * If none of the "n_edge" groups can be carried
5014 * then return an empty vector.
5016 static __isl_give isl_vec *compute_carrying_sol_coef(isl_ctx *ctx,
5017 struct isl_sched_graph *graph, int n_edge,
5018 __isl_keep isl_basic_set_list *intra,
5019 __isl_keep isl_basic_set_list *inter, int want_integral,
5020 int carry_inter)
5022 isl_basic_set *lp;
5024 if (setup_carry_lp(ctx, graph, n_edge, intra, inter, carry_inter) < 0)
5025 return NULL;
5027 lp = isl_basic_set_copy(graph->lp);
5028 return non_neg_lexmin(graph, lp, n_edge, want_integral);
5031 /* Construct an LP problem for finding schedule coefficients
5032 * such that the schedule carries as many of the validity dependences
5033 * as possible and
5034 * return the lexicographically smallest non-trivial solution.
5035 * If "fallback" is set, then the carrying is performed as a fallback
5036 * for the Pluto-like scheduler.
5037 * If "coincidence" is set, then try and carry coincidence edges as well.
5039 * The variable "n_edge" stores the number of groups that should be carried.
5040 * If none of the "n_edge" groups can be carried
5041 * then return an empty vector.
5042 * If, moreover, "n_edge" is zero, then the LP problem does not even
5043 * need to be constructed.
5045 * If a fallback solution is being computed, then compute an integral solution
5046 * for the coefficients rather than using the numerators
5047 * of a rational solution.
5049 * If a fallback solution is being computed, if there are any intra-node
5050 * dependences, and if requested by the user, then first try
5051 * to only carry those intra-node dependences.
5052 * If this fails to carry any dependences, then try again
5053 * with the inter-node dependences included.
5055 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
5056 struct isl_sched_graph *graph, int fallback, int coincidence)
5058 int n_intra, n_inter;
5059 int n_edge;
5060 struct isl_carry carry = { 0 };
5061 isl_vec *sol;
5063 carry.intra = collect_intra_validity(ctx, graph, coincidence,
5064 &carry.lineality);
5065 carry.inter = collect_inter_validity(graph, coincidence,
5066 &carry.lineality);
5067 if (!carry.intra || !carry.inter)
5068 goto error;
5069 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
5070 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
5072 if (fallback && n_intra > 0 &&
5073 isl_options_get_schedule_carry_self_first(ctx)) {
5074 sol = compute_carrying_sol_coef(ctx, graph, n_intra,
5075 carry.intra, carry.inter, fallback, 0);
5076 if (!sol || sol->size != 0 || n_inter == 0) {
5077 isl_carry_clear(&carry);
5078 return sol;
5080 isl_vec_free(sol);
5083 n_edge = n_intra + n_inter;
5084 if (n_edge == 0) {
5085 isl_carry_clear(&carry);
5086 return isl_vec_alloc(ctx, 0);
5089 sol = compute_carrying_sol_coef(ctx, graph, n_edge,
5090 carry.intra, carry.inter, fallback, 1);
5091 isl_carry_clear(&carry);
5092 return sol;
5093 error:
5094 isl_carry_clear(&carry);
5095 return NULL;
5098 /* Construct a schedule row for each node such that as many validity dependences
5099 * as possible are carried and then continue with the next band.
5100 * If "fallback" is set, then the carrying is performed as a fallback
5101 * for the Pluto-like scheduler.
5102 * If "coincidence" is set, then try and carry coincidence edges as well.
5104 * If there are no validity dependences, then no dependence can be carried and
5105 * the procedure is guaranteed to fail. If there is more than one component,
5106 * then try computing a schedule on each component separately
5107 * to prevent or at least postpone this failure.
5109 * If a schedule row is computed, then check that dependences are carried
5110 * for at least one of the edges.
5112 * If the computed schedule row turns out to be trivial on one or
5113 * more nodes where it should not be trivial, then we throw it away
5114 * and try again on each component separately.
5116 * If there is only one component, then we accept the schedule row anyway,
5117 * but we do not consider it as a complete row and therefore do not
5118 * increment graph->n_row. Note that the ranks of the nodes that
5119 * do get a non-trivial schedule part will get updated regardless and
5120 * graph->maxvar is computed based on these ranks. The test for
5121 * whether more schedule rows are required in compute_schedule_wcc
5122 * is therefore not affected.
5124 * Insert a band corresponding to the schedule row at position "node"
5125 * of the schedule tree and continue with the construction of the schedule.
5126 * This insertion and the continued construction is performed by split_scaled
5127 * after optionally checking for non-trivial common divisors.
5129 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
5130 struct isl_sched_graph *graph, int fallback, int coincidence)
5132 int trivial;
5133 isl_ctx *ctx;
5134 isl_vec *sol;
5136 if (!node)
5137 return NULL;
5139 ctx = isl_schedule_node_get_ctx(node);
5140 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
5141 if (!sol)
5142 return isl_schedule_node_free(node);
5143 if (sol->size == 0) {
5144 isl_vec_free(sol);
5145 if (graph->scc > 1)
5146 return compute_component_schedule(node, graph, 1);
5147 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
5148 return isl_schedule_node_free(node));
5151 trivial = is_any_trivial(graph, sol);
5152 if (trivial < 0) {
5153 sol = isl_vec_free(sol);
5154 } else if (trivial && graph->scc > 1) {
5155 isl_vec_free(sol);
5156 return compute_component_schedule(node, graph, 1);
5159 if (update_schedule(graph, sol, 0) < 0)
5160 return isl_schedule_node_free(node);
5161 if (trivial)
5162 graph->n_row--;
5164 return split_scaled(node, graph);
5167 /* Construct a schedule row for each node such that as many validity dependences
5168 * as possible are carried and then continue with the next band.
5169 * Do so as a fallback for the Pluto-like scheduler.
5170 * If "coincidence" is set, then try and carry coincidence edges as well.
5172 static __isl_give isl_schedule_node *carry_fallback(
5173 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5174 int coincidence)
5176 return carry(node, graph, 1, coincidence);
5179 /* Construct a schedule row for each node such that as many validity dependences
5180 * as possible are carried and then continue with the next band.
5181 * Do so for the case where the Feautrier scheduler was selected
5182 * by the user.
5184 static __isl_give isl_schedule_node *carry_feautrier(
5185 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5187 return carry(node, graph, 0, 0);
5190 /* Construct a schedule row for each node such that as many validity dependences
5191 * as possible are carried and then continue with the next band.
5192 * Do so as a fallback for the Pluto-like scheduler.
5194 static __isl_give isl_schedule_node *carry_dependences(
5195 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5197 return carry_fallback(node, graph, 0);
5200 /* Construct a schedule row for each node such that as many validity or
5201 * coincidence dependences as possible are carried and
5202 * then continue with the next band.
5203 * Do so as a fallback for the Pluto-like scheduler.
5205 static __isl_give isl_schedule_node *carry_coincidence(
5206 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5208 return carry_fallback(node, graph, 1);
5211 /* Topologically sort statements mapped to the same schedule iteration
5212 * and add insert a sequence node in front of "node"
5213 * corresponding to this order.
5214 * If "initialized" is set, then it may be assumed that compute_maxvar
5215 * has been called on the current band. Otherwise, call
5216 * compute_maxvar if and before carry_dependences gets called.
5218 * If it turns out to be impossible to sort the statements apart,
5219 * because different dependences impose different orderings
5220 * on the statements, then we extend the schedule such that
5221 * it carries at least one more dependence.
5223 static __isl_give isl_schedule_node *sort_statements(
5224 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5225 int initialized)
5227 isl_ctx *ctx;
5228 isl_union_set_list *filters;
5230 if (!node)
5231 return NULL;
5233 ctx = isl_schedule_node_get_ctx(node);
5234 if (graph->n < 1)
5235 isl_die(ctx, isl_error_internal,
5236 "graph should have at least one node",
5237 return isl_schedule_node_free(node));
5239 if (graph->n == 1)
5240 return node;
5242 if (update_edges(ctx, graph) < 0)
5243 return isl_schedule_node_free(node);
5245 if (graph->n_edge == 0)
5246 return node;
5248 if (detect_sccs(ctx, graph) < 0)
5249 return isl_schedule_node_free(node);
5251 next_band(graph);
5252 if (graph->scc < graph->n) {
5253 if (!initialized && compute_maxvar(graph) < 0)
5254 return isl_schedule_node_free(node);
5255 return carry_dependences(node, graph);
5258 filters = extract_sccs(ctx, graph);
5259 node = isl_schedule_node_insert_sequence(node, filters);
5261 return node;
5264 /* Are there any (non-empty) (conditional) validity edges in the graph?
5266 static int has_validity_edges(struct isl_sched_graph *graph)
5268 int i;
5270 for (i = 0; i < graph->n_edge; ++i) {
5271 int empty;
5273 empty = isl_map_plain_is_empty(graph->edge[i].map);
5274 if (empty < 0)
5275 return -1;
5276 if (empty)
5277 continue;
5278 if (is_any_validity(&graph->edge[i]))
5279 return 1;
5282 return 0;
5285 /* Should we apply a Feautrier step?
5286 * That is, did the user request the Feautrier algorithm and are
5287 * there any validity dependences (left)?
5289 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
5291 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
5292 return 0;
5294 return has_validity_edges(graph);
5297 /* Compute a schedule for a connected dependence graph using Feautrier's
5298 * multi-dimensional scheduling algorithm and return the updated schedule node.
5300 * The original algorithm is described in [1].
5301 * The main idea is to minimize the number of scheduling dimensions, by
5302 * trying to satisfy as many dependences as possible per scheduling dimension.
5304 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
5305 * Problem, Part II: Multi-Dimensional Time.
5306 * In Intl. Journal of Parallel Programming, 1992.
5308 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
5309 isl_schedule_node *node, struct isl_sched_graph *graph)
5311 return carry_feautrier(node, graph);
5314 /* Turn off the "local" bit on all (condition) edges.
5316 static void clear_local_edges(struct isl_sched_graph *graph)
5318 int i;
5320 for (i = 0; i < graph->n_edge; ++i)
5321 if (is_condition(&graph->edge[i]))
5322 clear_local(&graph->edge[i]);
5325 /* Does "graph" have both condition and conditional validity edges?
5327 static int need_condition_check(struct isl_sched_graph *graph)
5329 int i;
5330 int any_condition = 0;
5331 int any_conditional_validity = 0;
5333 for (i = 0; i < graph->n_edge; ++i) {
5334 if (is_condition(&graph->edge[i]))
5335 any_condition = 1;
5336 if (is_conditional_validity(&graph->edge[i]))
5337 any_conditional_validity = 1;
5340 return any_condition && any_conditional_validity;
5343 /* Does "graph" contain any coincidence edge?
5345 static int has_any_coincidence(struct isl_sched_graph *graph)
5347 int i;
5349 for (i = 0; i < graph->n_edge; ++i)
5350 if (is_coincidence(&graph->edge[i]))
5351 return 1;
5353 return 0;
5356 /* Extract the final schedule row as a map with the iteration domain
5357 * of "node" as domain.
5359 static __isl_give isl_map *final_row(struct isl_sched_node *node)
5361 isl_multi_aff *ma;
5362 int row;
5364 row = isl_mat_rows(node->sched) - 1;
5365 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
5366 return isl_map_from_multi_aff(ma);
5369 /* Is the conditional validity dependence in the edge with index "edge_index"
5370 * violated by the latest (i.e., final) row of the schedule?
5371 * That is, is i scheduled after j
5372 * for any conditional validity dependence i -> j?
5374 static int is_violated(struct isl_sched_graph *graph, int edge_index)
5376 isl_map *src_sched, *dst_sched, *map;
5377 struct isl_sched_edge *edge = &graph->edge[edge_index];
5378 int empty;
5380 src_sched = final_row(edge->src);
5381 dst_sched = final_row(edge->dst);
5382 map = isl_map_copy(edge->map);
5383 map = isl_map_apply_domain(map, src_sched);
5384 map = isl_map_apply_range(map, dst_sched);
5385 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
5386 empty = isl_map_is_empty(map);
5387 isl_map_free(map);
5389 if (empty < 0)
5390 return -1;
5392 return !empty;
5395 /* Does "graph" have any satisfied condition edges that
5396 * are adjacent to the conditional validity constraint with
5397 * domain "conditional_source" and range "conditional_sink"?
5399 * A satisfied condition is one that is not local.
5400 * If a condition was forced to be local already (i.e., marked as local)
5401 * then there is no need to check if it is in fact local.
5403 * Additionally, mark all adjacent condition edges found as local.
5405 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
5406 __isl_keep isl_union_set *conditional_source,
5407 __isl_keep isl_union_set *conditional_sink)
5409 int i;
5410 int any = 0;
5412 for (i = 0; i < graph->n_edge; ++i) {
5413 int adjacent, local;
5414 isl_union_map *condition;
5416 if (!is_condition(&graph->edge[i]))
5417 continue;
5418 if (is_local(&graph->edge[i]))
5419 continue;
5421 condition = graph->edge[i].tagged_condition;
5422 adjacent = domain_intersects(condition, conditional_sink);
5423 if (adjacent >= 0 && !adjacent)
5424 adjacent = range_intersects(condition,
5425 conditional_source);
5426 if (adjacent < 0)
5427 return -1;
5428 if (!adjacent)
5429 continue;
5431 set_local(&graph->edge[i]);
5433 local = is_condition_false(&graph->edge[i]);
5434 if (local < 0)
5435 return -1;
5436 if (!local)
5437 any = 1;
5440 return any;
5443 /* Are there any violated conditional validity dependences with
5444 * adjacent condition dependences that are not local with respect
5445 * to the current schedule?
5446 * That is, is the conditional validity constraint violated?
5448 * Additionally, mark all those adjacent condition dependences as local.
5449 * We also mark those adjacent condition dependences that were not marked
5450 * as local before, but just happened to be local already. This ensures
5451 * that they remain local if the schedule is recomputed.
5453 * We first collect domain and range of all violated conditional validity
5454 * dependences and then check if there are any adjacent non-local
5455 * condition dependences.
5457 static int has_violated_conditional_constraint(isl_ctx *ctx,
5458 struct isl_sched_graph *graph)
5460 int i;
5461 int any = 0;
5462 isl_union_set *source, *sink;
5464 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5465 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5466 for (i = 0; i < graph->n_edge; ++i) {
5467 isl_union_set *uset;
5468 isl_union_map *umap;
5469 int violated;
5471 if (!is_conditional_validity(&graph->edge[i]))
5472 continue;
5474 violated = is_violated(graph, i);
5475 if (violated < 0)
5476 goto error;
5477 if (!violated)
5478 continue;
5480 any = 1;
5482 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5483 uset = isl_union_map_domain(umap);
5484 source = isl_union_set_union(source, uset);
5485 source = isl_union_set_coalesce(source);
5487 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5488 uset = isl_union_map_range(umap);
5489 sink = isl_union_set_union(sink, uset);
5490 sink = isl_union_set_coalesce(sink);
5493 if (any)
5494 any = has_adjacent_true_conditions(graph, source, sink);
5496 isl_union_set_free(source);
5497 isl_union_set_free(sink);
5498 return any;
5499 error:
5500 isl_union_set_free(source);
5501 isl_union_set_free(sink);
5502 return -1;
5505 /* Examine the current band (the rows between graph->band_start and
5506 * graph->n_total_row), deciding whether to drop it or add it to "node"
5507 * and then continue with the computation of the next band, if any.
5508 * If "initialized" is set, then it may be assumed that compute_maxvar
5509 * has been called on the current band. Otherwise, call
5510 * compute_maxvar if and before carry_dependences gets called.
5512 * The caller keeps looking for a new row as long as
5513 * graph->n_row < graph->maxvar. If the latest attempt to find
5514 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
5515 * then we either
5516 * - split between SCCs and start over (assuming we found an interesting
5517 * pair of SCCs between which to split)
5518 * - continue with the next band (assuming the current band has at least
5519 * one row)
5520 * - if there is more than one SCC left, then split along all SCCs
5521 * - if outer coincidence needs to be enforced, then try to carry as many
5522 * validity or coincidence dependences as possible and
5523 * continue with the next band
5524 * - try to carry as many validity dependences as possible and
5525 * continue with the next band
5526 * In each case, we first insert a band node in the schedule tree
5527 * if any rows have been computed.
5529 * If the caller managed to complete the schedule and the current band
5530 * is empty, then finish off by topologically
5531 * sorting the statements based on the remaining dependences.
5532 * If, on the other hand, the current band has at least one row,
5533 * then continue with the next band. Note that this next band
5534 * will necessarily be empty, but the graph may still be split up
5535 * into weakly connected components before arriving back here.
5537 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5538 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5539 int initialized)
5541 int empty;
5543 if (!node)
5544 return NULL;
5546 empty = graph->n_total_row == graph->band_start;
5547 if (graph->n_row < graph->maxvar) {
5548 isl_ctx *ctx;
5550 ctx = isl_schedule_node_get_ctx(node);
5551 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5552 return compute_next_band(node, graph, 1);
5553 if (graph->src_scc >= 0)
5554 return compute_split_schedule(node, graph);
5555 if (!empty)
5556 return compute_next_band(node, graph, 1);
5557 if (graph->scc > 1)
5558 return compute_component_schedule(node, graph, 1);
5559 if (!initialized && compute_maxvar(graph) < 0)
5560 return isl_schedule_node_free(node);
5561 if (isl_options_get_schedule_outer_coincidence(ctx))
5562 return carry_coincidence(node, graph);
5563 return carry_dependences(node, graph);
5566 if (!empty)
5567 return compute_next_band(node, graph, 1);
5568 return sort_statements(node, graph, initialized);
5571 /* Construct a band of schedule rows for a connected dependence graph.
5572 * The caller is responsible for determining the strongly connected
5573 * components and calling compute_maxvar first.
5575 * We try to find a sequence of as many schedule rows as possible that result
5576 * in non-negative dependence distances (independent of the previous rows
5577 * in the sequence, i.e., such that the sequence is tilable), with as
5578 * many of the initial rows as possible satisfying the coincidence constraints.
5579 * The computation stops if we can't find any more rows or if we have found
5580 * all the rows we wanted to find.
5582 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5583 * outermost dimension to satisfy the coincidence constraints. If this
5584 * turns out to be impossible, we fall back on the general scheme above
5585 * and try to carry as many dependences as possible.
5587 * If "graph" contains both condition and conditional validity dependences,
5588 * then we need to check that that the conditional schedule constraint
5589 * is satisfied, i.e., there are no violated conditional validity dependences
5590 * that are adjacent to any non-local condition dependences.
5591 * If there are, then we mark all those adjacent condition dependences
5592 * as local and recompute the current band. Those dependences that
5593 * are marked local will then be forced to be local.
5594 * The initial computation is performed with no dependences marked as local.
5595 * If we are lucky, then there will be no violated conditional validity
5596 * dependences adjacent to any non-local condition dependences.
5597 * Otherwise, we mark some additional condition dependences as local and
5598 * recompute. We continue this process until there are no violations left or
5599 * until we are no longer able to compute a schedule.
5600 * Since there are only a finite number of dependences,
5601 * there will only be a finite number of iterations.
5603 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5604 struct isl_sched_graph *graph)
5606 int has_coincidence;
5607 int use_coincidence;
5608 int force_coincidence = 0;
5609 int check_conditional;
5611 if (sort_sccs(graph) < 0)
5612 return isl_stat_error;
5614 clear_local_edges(graph);
5615 check_conditional = need_condition_check(graph);
5616 has_coincidence = has_any_coincidence(graph);
5618 if (ctx->opt->schedule_outer_coincidence)
5619 force_coincidence = 1;
5621 use_coincidence = has_coincidence;
5622 while (graph->n_row < graph->maxvar) {
5623 isl_vec *sol;
5624 int violated;
5625 int coincident;
5627 graph->src_scc = -1;
5628 graph->dst_scc = -1;
5630 if (setup_lp(ctx, graph, use_coincidence) < 0)
5631 return isl_stat_error;
5632 sol = solve_lp(ctx, graph);
5633 if (!sol)
5634 return isl_stat_error;
5635 if (sol->size == 0) {
5636 int empty = graph->n_total_row == graph->band_start;
5638 isl_vec_free(sol);
5639 if (use_coincidence && (!force_coincidence || !empty)) {
5640 use_coincidence = 0;
5641 continue;
5643 return isl_stat_ok;
5645 coincident = !has_coincidence || use_coincidence;
5646 if (update_schedule(graph, sol, coincident) < 0)
5647 return isl_stat_error;
5649 if (!check_conditional)
5650 continue;
5651 violated = has_violated_conditional_constraint(ctx, graph);
5652 if (violated < 0)
5653 return isl_stat_error;
5654 if (!violated)
5655 continue;
5656 if (reset_band(graph) < 0)
5657 return isl_stat_error;
5658 use_coincidence = has_coincidence;
5661 return isl_stat_ok;
5664 /* Compute a schedule for a connected dependence graph by considering
5665 * the graph as a whole and return the updated schedule node.
5667 * The actual schedule rows of the current band are computed by
5668 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5669 * care of integrating the band into "node" and continuing
5670 * the computation.
5672 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5673 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5675 isl_ctx *ctx;
5677 if (!node)
5678 return NULL;
5680 ctx = isl_schedule_node_get_ctx(node);
5681 if (compute_schedule_wcc_band(ctx, graph) < 0)
5682 return isl_schedule_node_free(node);
5684 return compute_schedule_finish_band(node, graph, 1);
5687 /* Clustering information used by compute_schedule_wcc_clustering.
5689 * "n" is the number of SCCs in the original dependence graph
5690 * "scc" is an array of "n" elements, each representing an SCC
5691 * of the original dependence graph. All entries in the same cluster
5692 * have the same number of schedule rows.
5693 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5694 * where each cluster is represented by the index of the first SCC
5695 * in the cluster. Initially, each SCC belongs to a cluster containing
5696 * only that SCC.
5698 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5699 * track of which SCCs need to be merged.
5701 * "cluster" contains the merged clusters of SCCs after the clustering
5702 * has completed.
5704 * "scc_node" is a temporary data structure used inside copy_partial.
5705 * For each SCC, it keeps track of the number of nodes in the SCC
5706 * that have already been copied.
5708 struct isl_clustering {
5709 int n;
5710 struct isl_sched_graph *scc;
5711 struct isl_sched_graph *cluster;
5712 int *scc_cluster;
5713 int *scc_node;
5714 int *scc_in_merge;
5717 /* Initialize the clustering data structure "c" from "graph".
5719 * In particular, allocate memory, extract the SCCs from "graph"
5720 * into c->scc, initialize scc_cluster and construct
5721 * a band of schedule rows for each SCC.
5722 * Within each SCC, there is only one SCC by definition.
5723 * Each SCC initially belongs to a cluster containing only that SCC.
5725 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5726 struct isl_sched_graph *graph)
5728 int i;
5730 c->n = graph->scc;
5731 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5732 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5733 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5734 c->scc_node = isl_calloc_array(ctx, int, c->n);
5735 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5736 if (!c->scc || !c->cluster ||
5737 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5738 return isl_stat_error;
5740 for (i = 0; i < c->n; ++i) {
5741 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5742 &edge_scc_exactly, i, &c->scc[i]) < 0)
5743 return isl_stat_error;
5744 c->scc[i].scc = 1;
5745 if (compute_maxvar(&c->scc[i]) < 0)
5746 return isl_stat_error;
5747 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5748 return isl_stat_error;
5749 c->scc_cluster[i] = i;
5752 return isl_stat_ok;
5755 /* Free all memory allocated for "c".
5757 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5759 int i;
5761 if (c->scc)
5762 for (i = 0; i < c->n; ++i)
5763 graph_free(ctx, &c->scc[i]);
5764 free(c->scc);
5765 if (c->cluster)
5766 for (i = 0; i < c->n; ++i)
5767 graph_free(ctx, &c->cluster[i]);
5768 free(c->cluster);
5769 free(c->scc_cluster);
5770 free(c->scc_node);
5771 free(c->scc_in_merge);
5774 /* Should we refrain from merging the cluster in "graph" with
5775 * any other cluster?
5776 * In particular, is its current schedule band empty and incomplete.
5778 static int bad_cluster(struct isl_sched_graph *graph)
5780 return graph->n_row < graph->maxvar &&
5781 graph->n_total_row == graph->band_start;
5784 /* Is "edge" a proximity edge with a non-empty dependence relation?
5786 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5788 if (!is_proximity(edge))
5789 return isl_bool_false;
5790 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5793 /* Return the index of an edge in "graph" that can be used to merge
5794 * two clusters in "c".
5795 * Return graph->n_edge if no such edge can be found.
5796 * Return -1 on error.
5798 * In particular, return a proximity edge between two clusters
5799 * that is not marked "no_merge" and such that neither of the
5800 * two clusters has an incomplete, empty band.
5802 * If there are multiple such edges, then try and find the most
5803 * appropriate edge to use for merging. In particular, pick the edge
5804 * with the greatest weight. If there are multiple of those,
5805 * then pick one with the shortest distance between
5806 * the two cluster representatives.
5808 static int find_proximity(struct isl_sched_graph *graph,
5809 struct isl_clustering *c)
5811 int i, best = graph->n_edge, best_dist, best_weight;
5813 for (i = 0; i < graph->n_edge; ++i) {
5814 struct isl_sched_edge *edge = &graph->edge[i];
5815 int dist, weight;
5816 isl_bool prox;
5818 prox = is_non_empty_proximity(edge);
5819 if (prox < 0)
5820 return -1;
5821 if (!prox)
5822 continue;
5823 if (edge->no_merge)
5824 continue;
5825 if (bad_cluster(&c->scc[edge->src->scc]) ||
5826 bad_cluster(&c->scc[edge->dst->scc]))
5827 continue;
5828 dist = c->scc_cluster[edge->dst->scc] -
5829 c->scc_cluster[edge->src->scc];
5830 if (dist == 0)
5831 continue;
5832 weight = edge->weight;
5833 if (best < graph->n_edge) {
5834 if (best_weight > weight)
5835 continue;
5836 if (best_weight == weight && best_dist <= dist)
5837 continue;
5839 best = i;
5840 best_dist = dist;
5841 best_weight = weight;
5844 return best;
5847 /* Internal data structure used in mark_merge_sccs.
5849 * "graph" is the dependence graph in which a strongly connected
5850 * component is constructed.
5851 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5852 * "src" and "dst" are the indices of the nodes that are being merged.
5854 struct isl_mark_merge_sccs_data {
5855 struct isl_sched_graph *graph;
5856 int *scc_cluster;
5857 int src;
5858 int dst;
5861 /* Check whether the cluster containing node "i" depends on the cluster
5862 * containing node "j". If "i" and "j" belong to the same cluster,
5863 * then they are taken to depend on each other to ensure that
5864 * the resulting strongly connected component consists of complete
5865 * clusters. Furthermore, if "i" and "j" are the two nodes that
5866 * are being merged, then they are taken to depend on each other as well.
5867 * Otherwise, check if there is a (conditional) validity dependence
5868 * from node[j] to node[i], forcing node[i] to follow node[j].
5870 static isl_bool cluster_follows(int i, int j, void *user)
5872 struct isl_mark_merge_sccs_data *data = user;
5873 struct isl_sched_graph *graph = data->graph;
5874 int *scc_cluster = data->scc_cluster;
5876 if (data->src == i && data->dst == j)
5877 return isl_bool_true;
5878 if (data->src == j && data->dst == i)
5879 return isl_bool_true;
5880 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5881 return isl_bool_true;
5883 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5886 /* Mark all SCCs that belong to either of the two clusters in "c"
5887 * connected by the edge in "graph" with index "edge", or to any
5888 * of the intermediate clusters.
5889 * The marking is recorded in c->scc_in_merge.
5891 * The given edge has been selected for merging two clusters,
5892 * meaning that there is at least a proximity edge between the two nodes.
5893 * However, there may also be (indirect) validity dependences
5894 * between the two nodes. When merging the two clusters, all clusters
5895 * containing one or more of the intermediate nodes along the
5896 * indirect validity dependences need to be merged in as well.
5898 * First collect all such nodes by computing the strongly connected
5899 * component (SCC) containing the two nodes connected by the edge, where
5900 * the two nodes are considered to depend on each other to make
5901 * sure they end up in the same SCC. Similarly, each node is considered
5902 * to depend on every other node in the same cluster to ensure
5903 * that the SCC consists of complete clusters.
5905 * Then the original SCCs that contain any of these nodes are marked
5906 * in c->scc_in_merge.
5908 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5909 int edge, struct isl_clustering *c)
5911 struct isl_mark_merge_sccs_data data;
5912 struct isl_tarjan_graph *g;
5913 int i;
5915 for (i = 0; i < c->n; ++i)
5916 c->scc_in_merge[i] = 0;
5918 data.graph = graph;
5919 data.scc_cluster = c->scc_cluster;
5920 data.src = graph->edge[edge].src - graph->node;
5921 data.dst = graph->edge[edge].dst - graph->node;
5923 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5924 &cluster_follows, &data);
5925 if (!g)
5926 goto error;
5928 i = g->op;
5929 if (i < 3)
5930 isl_die(ctx, isl_error_internal,
5931 "expecting at least two nodes in component",
5932 goto error);
5933 if (g->order[--i] != -1)
5934 isl_die(ctx, isl_error_internal,
5935 "expecting end of component marker", goto error);
5937 for (--i; i >= 0 && g->order[i] != -1; --i) {
5938 int scc = graph->node[g->order[i]].scc;
5939 c->scc_in_merge[scc] = 1;
5942 isl_tarjan_graph_free(g);
5943 return isl_stat_ok;
5944 error:
5945 isl_tarjan_graph_free(g);
5946 return isl_stat_error;
5949 /* Construct the identifier "cluster_i".
5951 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5953 char name[40];
5955 snprintf(name, sizeof(name), "cluster_%d", i);
5956 return isl_id_alloc(ctx, name, NULL);
5959 /* Construct the space of the cluster with index "i" containing
5960 * the strongly connected component "scc".
5962 * In particular, construct a space called cluster_i with dimension equal
5963 * to the number of schedule rows in the current band of "scc".
5965 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5967 int nvar;
5968 isl_space *space;
5969 isl_id *id;
5971 nvar = scc->n_total_row - scc->band_start;
5972 space = isl_space_copy(scc->node[0].space);
5973 space = isl_space_params(space);
5974 space = isl_space_set_from_params(space);
5975 space = isl_space_add_dims(space, isl_dim_set, nvar);
5976 id = cluster_id(isl_space_get_ctx(space), i);
5977 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5979 return space;
5982 /* Collect the domain of the graph for merging clusters.
5984 * In particular, for each cluster with first SCC "i", construct
5985 * a set in the space called cluster_i with dimension equal
5986 * to the number of schedule rows in the current band of the cluster.
5988 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5989 struct isl_sched_graph *graph, struct isl_clustering *c)
5991 int i;
5992 isl_space *space;
5993 isl_union_set *domain;
5995 space = isl_space_params_alloc(ctx, 0);
5996 domain = isl_union_set_empty(space);
5998 for (i = 0; i < graph->scc; ++i) {
5999 isl_space *space;
6001 if (!c->scc_in_merge[i])
6002 continue;
6003 if (c->scc_cluster[i] != i)
6004 continue;
6005 space = cluster_space(&c->scc[i], i);
6006 domain = isl_union_set_add_set(domain, isl_set_universe(space));
6009 return domain;
6012 /* Construct a map from the original instances to the corresponding
6013 * cluster instance in the current bands of the clusters in "c".
6015 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
6016 struct isl_sched_graph *graph, struct isl_clustering *c)
6018 int i, j;
6019 isl_space *space;
6020 isl_union_map *cluster_map;
6022 space = isl_space_params_alloc(ctx, 0);
6023 cluster_map = isl_union_map_empty(space);
6024 for (i = 0; i < graph->scc; ++i) {
6025 int start, n;
6026 isl_id *id;
6028 if (!c->scc_in_merge[i])
6029 continue;
6031 id = cluster_id(ctx, c->scc_cluster[i]);
6032 start = c->scc[i].band_start;
6033 n = c->scc[i].n_total_row - start;
6034 for (j = 0; j < c->scc[i].n; ++j) {
6035 isl_multi_aff *ma;
6036 isl_map *map;
6037 struct isl_sched_node *node = &c->scc[i].node[j];
6039 ma = node_extract_partial_schedule_multi_aff(node,
6040 start, n);
6041 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
6042 isl_id_copy(id));
6043 map = isl_map_from_multi_aff(ma);
6044 cluster_map = isl_union_map_add_map(cluster_map, map);
6046 isl_id_free(id);
6049 return cluster_map;
6052 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
6053 * that are not isl_edge_condition or isl_edge_conditional_validity.
6055 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
6056 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6057 __isl_take isl_schedule_constraints *sc)
6059 enum isl_edge_type t;
6061 if (!sc)
6062 return NULL;
6064 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
6065 if (t == isl_edge_condition ||
6066 t == isl_edge_conditional_validity)
6067 continue;
6068 if (!is_type(edge, t))
6069 continue;
6070 sc = isl_schedule_constraints_add(sc, t,
6071 isl_union_map_copy(umap));
6074 return sc;
6077 /* Add schedule constraints of types isl_edge_condition and
6078 * isl_edge_conditional_validity to "sc" by applying "umap" to
6079 * the domains of the wrapped relations in domain and range
6080 * of the corresponding tagged constraints of "edge".
6082 static __isl_give isl_schedule_constraints *add_conditional_constraints(
6083 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6084 __isl_take isl_schedule_constraints *sc)
6086 enum isl_edge_type t;
6087 isl_union_map *tagged;
6089 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
6090 if (!is_type(edge, t))
6091 continue;
6092 if (t == isl_edge_condition)
6093 tagged = isl_union_map_copy(edge->tagged_condition);
6094 else
6095 tagged = isl_union_map_copy(edge->tagged_validity);
6096 tagged = isl_union_map_zip(tagged);
6097 tagged = isl_union_map_apply_domain(tagged,
6098 isl_union_map_copy(umap));
6099 tagged = isl_union_map_zip(tagged);
6100 sc = isl_schedule_constraints_add(sc, t, tagged);
6101 if (!sc)
6102 return NULL;
6105 return sc;
6108 /* Given a mapping "cluster_map" from the original instances to
6109 * the cluster instances, add schedule constraints on the clusters
6110 * to "sc" corresponding to the original constraints represented by "edge".
6112 * For non-tagged dependence constraints, the cluster constraints
6113 * are obtained by applying "cluster_map" to the edge->map.
6115 * For tagged dependence constraints, "cluster_map" needs to be applied
6116 * to the domains of the wrapped relations in domain and range
6117 * of the tagged dependence constraints. Pick out the mappings
6118 * from these domains from "cluster_map" and construct their product.
6119 * This mapping can then be applied to the pair of domains.
6121 static __isl_give isl_schedule_constraints *collect_edge_constraints(
6122 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
6123 __isl_take isl_schedule_constraints *sc)
6125 isl_union_map *umap;
6126 isl_space *space;
6127 isl_union_set *uset;
6128 isl_union_map *umap1, *umap2;
6130 if (!sc)
6131 return NULL;
6133 umap = isl_union_map_from_map(isl_map_copy(edge->map));
6134 umap = isl_union_map_apply_domain(umap,
6135 isl_union_map_copy(cluster_map));
6136 umap = isl_union_map_apply_range(umap,
6137 isl_union_map_copy(cluster_map));
6138 sc = add_non_conditional_constraints(edge, umap, sc);
6139 isl_union_map_free(umap);
6141 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
6142 return sc;
6144 space = isl_space_domain(isl_map_get_space(edge->map));
6145 uset = isl_union_set_from_set(isl_set_universe(space));
6146 umap1 = isl_union_map_copy(cluster_map);
6147 umap1 = isl_union_map_intersect_domain(umap1, uset);
6148 space = isl_space_range(isl_map_get_space(edge->map));
6149 uset = isl_union_set_from_set(isl_set_universe(space));
6150 umap2 = isl_union_map_copy(cluster_map);
6151 umap2 = isl_union_map_intersect_domain(umap2, uset);
6152 umap = isl_union_map_product(umap1, umap2);
6154 sc = add_conditional_constraints(edge, umap, sc);
6156 isl_union_map_free(umap);
6157 return sc;
6160 /* Given a mapping "cluster_map" from the original instances to
6161 * the cluster instances, add schedule constraints on the clusters
6162 * to "sc" corresponding to all edges in "graph" between nodes that
6163 * belong to SCCs that are marked for merging in "scc_in_merge".
6165 static __isl_give isl_schedule_constraints *collect_constraints(
6166 struct isl_sched_graph *graph, int *scc_in_merge,
6167 __isl_keep isl_union_map *cluster_map,
6168 __isl_take isl_schedule_constraints *sc)
6170 int i;
6172 for (i = 0; i < graph->n_edge; ++i) {
6173 struct isl_sched_edge *edge = &graph->edge[i];
6175 if (!scc_in_merge[edge->src->scc])
6176 continue;
6177 if (!scc_in_merge[edge->dst->scc])
6178 continue;
6179 sc = collect_edge_constraints(edge, cluster_map, sc);
6182 return sc;
6185 /* Construct a dependence graph for scheduling clusters with respect
6186 * to each other and store the result in "merge_graph".
6187 * In particular, the nodes of the graph correspond to the schedule
6188 * dimensions of the current bands of those clusters that have been
6189 * marked for merging in "c".
6191 * First construct an isl_schedule_constraints object for this domain
6192 * by transforming the edges in "graph" to the domain.
6193 * Then initialize a dependence graph for scheduling from these
6194 * constraints.
6196 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
6197 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6199 isl_union_set *domain;
6200 isl_union_map *cluster_map;
6201 isl_schedule_constraints *sc;
6202 isl_stat r;
6204 domain = collect_domain(ctx, graph, c);
6205 sc = isl_schedule_constraints_on_domain(domain);
6206 if (!sc)
6207 return isl_stat_error;
6208 cluster_map = collect_cluster_map(ctx, graph, c);
6209 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
6210 isl_union_map_free(cluster_map);
6212 r = graph_init(merge_graph, sc);
6214 isl_schedule_constraints_free(sc);
6216 return r;
6219 /* Compute the maximal number of remaining schedule rows that still need
6220 * to be computed for the nodes that belong to clusters with the maximal
6221 * dimension for the current band (i.e., the band that is to be merged).
6222 * Only clusters that are about to be merged are considered.
6223 * "maxvar" is the maximal dimension for the current band.
6224 * "c" contains information about the clusters.
6226 * Return the maximal number of remaining schedule rows or -1 on error.
6228 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
6230 int i, j;
6231 int max_slack;
6233 max_slack = 0;
6234 for (i = 0; i < c->n; ++i) {
6235 int nvar;
6236 struct isl_sched_graph *scc;
6238 if (!c->scc_in_merge[i])
6239 continue;
6240 scc = &c->scc[i];
6241 nvar = scc->n_total_row - scc->band_start;
6242 if (nvar != maxvar)
6243 continue;
6244 for (j = 0; j < scc->n; ++j) {
6245 struct isl_sched_node *node = &scc->node[j];
6246 int slack;
6248 if (node_update_vmap(node) < 0)
6249 return -1;
6250 slack = node->nvar - node->rank;
6251 if (slack > max_slack)
6252 max_slack = slack;
6256 return max_slack;
6259 /* If there are any clusters where the dimension of the current band
6260 * (i.e., the band that is to be merged) is smaller than "maxvar" and
6261 * if there are any nodes in such a cluster where the number
6262 * of remaining schedule rows that still need to be computed
6263 * is greater than "max_slack", then return the smallest current band
6264 * dimension of all these clusters. Otherwise return the original value
6265 * of "maxvar". Return -1 in case of any error.
6266 * Only clusters that are about to be merged are considered.
6267 * "c" contains information about the clusters.
6269 static int limit_maxvar_to_slack(int maxvar, int max_slack,
6270 struct isl_clustering *c)
6272 int i, j;
6274 for (i = 0; i < c->n; ++i) {
6275 int nvar;
6276 struct isl_sched_graph *scc;
6278 if (!c->scc_in_merge[i])
6279 continue;
6280 scc = &c->scc[i];
6281 nvar = scc->n_total_row - scc->band_start;
6282 if (nvar >= maxvar)
6283 continue;
6284 for (j = 0; j < scc->n; ++j) {
6285 struct isl_sched_node *node = &scc->node[j];
6286 int slack;
6288 if (node_update_vmap(node) < 0)
6289 return -1;
6290 slack = node->nvar - node->rank;
6291 if (slack > max_slack) {
6292 maxvar = nvar;
6293 break;
6298 return maxvar;
6301 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
6302 * that still need to be computed. In particular, if there is a node
6303 * in a cluster where the dimension of the current band is smaller
6304 * than merge_graph->maxvar, but the number of remaining schedule rows
6305 * is greater than that of any node in a cluster with the maximal
6306 * dimension for the current band (i.e., merge_graph->maxvar),
6307 * then adjust merge_graph->maxvar to the (smallest) current band dimension
6308 * of those clusters. Without this adjustment, the total number of
6309 * schedule dimensions would be increased, resulting in a skewed view
6310 * of the number of coincident dimensions.
6311 * "c" contains information about the clusters.
6313 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
6314 * then there is no point in attempting any merge since it will be rejected
6315 * anyway. Set merge_graph->maxvar to zero in such cases.
6317 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
6318 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
6320 int max_slack, maxvar;
6322 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
6323 if (max_slack < 0)
6324 return isl_stat_error;
6325 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
6326 if (maxvar < 0)
6327 return isl_stat_error;
6329 if (maxvar < merge_graph->maxvar) {
6330 if (isl_options_get_schedule_maximize_band_depth(ctx))
6331 merge_graph->maxvar = 0;
6332 else
6333 merge_graph->maxvar = maxvar;
6336 return isl_stat_ok;
6339 /* Return the number of coincident dimensions in the current band of "graph",
6340 * where the nodes of "graph" are assumed to be scheduled by a single band.
6342 static int get_n_coincident(struct isl_sched_graph *graph)
6344 int i;
6346 for (i = graph->band_start; i < graph->n_total_row; ++i)
6347 if (!graph->node[0].coincident[i])
6348 break;
6350 return i - graph->band_start;
6353 /* Should the clusters be merged based on the cluster schedule
6354 * in the current (and only) band of "merge_graph", given that
6355 * coincidence should be maximized?
6357 * If the number of coincident schedule dimensions in the merged band
6358 * would be less than the maximal number of coincident schedule dimensions
6359 * in any of the merged clusters, then the clusters should not be merged.
6361 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
6362 struct isl_sched_graph *merge_graph)
6364 int i;
6365 int n_coincident;
6366 int max_coincident;
6368 max_coincident = 0;
6369 for (i = 0; i < c->n; ++i) {
6370 if (!c->scc_in_merge[i])
6371 continue;
6372 n_coincident = get_n_coincident(&c->scc[i]);
6373 if (n_coincident > max_coincident)
6374 max_coincident = n_coincident;
6377 n_coincident = get_n_coincident(merge_graph);
6379 return n_coincident >= max_coincident;
6382 /* Return the transformation on "node" expressed by the current (and only)
6383 * band of "merge_graph" applied to the clusters in "c".
6385 * First find the representation of "node" in its SCC in "c" and
6386 * extract the transformation expressed by the current band.
6387 * Then extract the transformation applied by "merge_graph"
6388 * to the cluster to which this SCC belongs.
6389 * Combine the two to obtain the complete transformation on the node.
6391 * Note that the range of the first transformation is an anonymous space,
6392 * while the domain of the second is named "cluster_X". The range
6393 * of the former therefore needs to be adjusted before the two
6394 * can be combined.
6396 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
6397 struct isl_sched_node *node, struct isl_clustering *c,
6398 struct isl_sched_graph *merge_graph)
6400 struct isl_sched_node *scc_node, *cluster_node;
6401 int start, n;
6402 isl_id *id;
6403 isl_space *space;
6404 isl_multi_aff *ma, *ma2;
6406 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
6407 start = c->scc[node->scc].band_start;
6408 n = c->scc[node->scc].n_total_row - start;
6409 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
6410 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
6411 cluster_node = graph_find_node(ctx, merge_graph, space);
6412 if (space && !cluster_node)
6413 isl_die(ctx, isl_error_internal, "unable to find cluster",
6414 space = isl_space_free(space));
6415 id = isl_space_get_tuple_id(space, isl_dim_set);
6416 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
6417 isl_space_free(space);
6418 n = merge_graph->n_total_row;
6419 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
6420 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
6422 return isl_map_from_multi_aff(ma);
6425 /* Give a set of distances "set", are they bounded by a small constant
6426 * in direction "pos"?
6427 * In practice, check if they are bounded by 2 by checking that there
6428 * are no elements with a value greater than or equal to 3 or
6429 * smaller than or equal to -3.
6431 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
6433 isl_bool bounded;
6434 isl_set *test;
6436 if (!set)
6437 return isl_bool_error;
6439 test = isl_set_copy(set);
6440 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
6441 bounded = isl_set_is_empty(test);
6442 isl_set_free(test);
6444 if (bounded < 0 || !bounded)
6445 return bounded;
6447 test = isl_set_copy(set);
6448 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
6449 bounded = isl_set_is_empty(test);
6450 isl_set_free(test);
6452 return bounded;
6455 /* Does the set "set" have a fixed (but possible parametric) value
6456 * at dimension "pos"?
6458 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
6460 int n;
6461 isl_bool single;
6463 if (!set)
6464 return isl_bool_error;
6465 set = isl_set_copy(set);
6466 n = isl_set_dim(set, isl_dim_set);
6467 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
6468 set = isl_set_project_out(set, isl_dim_set, 0, pos);
6469 single = isl_set_is_singleton(set);
6470 isl_set_free(set);
6472 return single;
6475 /* Does "map" have a fixed (but possible parametric) value
6476 * at dimension "pos" of either its domain or its range?
6478 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
6480 isl_set *set;
6481 isl_bool single;
6483 set = isl_map_domain(isl_map_copy(map));
6484 single = has_single_value(set, pos);
6485 isl_set_free(set);
6487 if (single < 0 || single)
6488 return single;
6490 set = isl_map_range(isl_map_copy(map));
6491 single = has_single_value(set, pos);
6492 isl_set_free(set);
6494 return single;
6497 /* Does the edge "edge" from "graph" have bounded dependence distances
6498 * in the merged graph "merge_graph" of a selection of clusters in "c"?
6500 * Extract the complete transformations of the source and destination
6501 * nodes of the edge, apply them to the edge constraints and
6502 * compute the differences. Finally, check if these differences are bounded
6503 * in each direction.
6505 * If the dimension of the band is greater than the number of
6506 * dimensions that can be expected to be optimized by the edge
6507 * (based on its weight), then also allow the differences to be unbounded
6508 * in the remaining dimensions, but only if either the source or
6509 * the destination has a fixed value in that direction.
6510 * This allows a statement that produces values that are used by
6511 * several instances of another statement to be merged with that
6512 * other statement.
6513 * However, merging such clusters will introduce an inherently
6514 * large proximity distance inside the merged cluster, meaning
6515 * that proximity distances will no longer be optimized in
6516 * subsequent merges. These merges are therefore only allowed
6517 * after all other possible merges have been tried.
6518 * The first time such a merge is encountered, the weight of the edge
6519 * is replaced by a negative weight. The second time (i.e., after
6520 * all merges over edges with a non-negative weight have been tried),
6521 * the merge is allowed.
6523 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
6524 struct isl_sched_graph *graph, struct isl_clustering *c,
6525 struct isl_sched_graph *merge_graph)
6527 int i, n, n_slack;
6528 isl_bool bounded;
6529 isl_map *map, *t;
6530 isl_set *dist;
6532 map = isl_map_copy(edge->map);
6533 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6534 map = isl_map_apply_domain(map, t);
6535 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6536 map = isl_map_apply_range(map, t);
6537 dist = isl_map_deltas(isl_map_copy(map));
6539 bounded = isl_bool_true;
6540 n = isl_set_dim(dist, isl_dim_set);
6541 n_slack = n - edge->weight;
6542 if (edge->weight < 0)
6543 n_slack -= graph->max_weight + 1;
6544 for (i = 0; i < n; ++i) {
6545 isl_bool bounded_i, singular_i;
6547 bounded_i = distance_is_bounded(dist, i);
6548 if (bounded_i < 0)
6549 goto error;
6550 if (bounded_i)
6551 continue;
6552 if (edge->weight >= 0)
6553 bounded = isl_bool_false;
6554 n_slack--;
6555 if (n_slack < 0)
6556 break;
6557 singular_i = has_singular_src_or_dst(map, i);
6558 if (singular_i < 0)
6559 goto error;
6560 if (singular_i)
6561 continue;
6562 bounded = isl_bool_false;
6563 break;
6565 if (!bounded && i >= n && edge->weight >= 0)
6566 edge->weight -= graph->max_weight + 1;
6567 isl_map_free(map);
6568 isl_set_free(dist);
6570 return bounded;
6571 error:
6572 isl_map_free(map);
6573 isl_set_free(dist);
6574 return isl_bool_error;
6577 /* Should the clusters be merged based on the cluster schedule
6578 * in the current (and only) band of "merge_graph"?
6579 * "graph" is the original dependence graph, while "c" records
6580 * which SCCs are involved in the latest merge.
6582 * In particular, is there at least one proximity constraint
6583 * that is optimized by the merge?
6585 * A proximity constraint is considered to be optimized
6586 * if the dependence distances are small.
6588 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6589 struct isl_sched_graph *graph, struct isl_clustering *c,
6590 struct isl_sched_graph *merge_graph)
6592 int i;
6594 for (i = 0; i < graph->n_edge; ++i) {
6595 struct isl_sched_edge *edge = &graph->edge[i];
6596 isl_bool bounded;
6598 if (!is_proximity(edge))
6599 continue;
6600 if (!c->scc_in_merge[edge->src->scc])
6601 continue;
6602 if (!c->scc_in_merge[edge->dst->scc])
6603 continue;
6604 if (c->scc_cluster[edge->dst->scc] ==
6605 c->scc_cluster[edge->src->scc])
6606 continue;
6607 bounded = has_bounded_distances(ctx, edge, graph, c,
6608 merge_graph);
6609 if (bounded < 0 || bounded)
6610 return bounded;
6613 return isl_bool_false;
6616 /* Should the clusters be merged based on the cluster schedule
6617 * in the current (and only) band of "merge_graph"?
6618 * "graph" is the original dependence graph, while "c" records
6619 * which SCCs are involved in the latest merge.
6621 * If the current band is empty, then the clusters should not be merged.
6623 * If the band depth should be maximized and the merge schedule
6624 * is incomplete (meaning that the dimension of some of the schedule
6625 * bands in the original schedule will be reduced), then the clusters
6626 * should not be merged.
6628 * If the schedule_maximize_coincidence option is set, then check that
6629 * the number of coincident schedule dimensions is not reduced.
6631 * Finally, only allow the merge if at least one proximity
6632 * constraint is optimized.
6634 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6635 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6637 if (merge_graph->n_total_row == merge_graph->band_start)
6638 return isl_bool_false;
6640 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6641 merge_graph->n_total_row < merge_graph->maxvar)
6642 return isl_bool_false;
6644 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6645 isl_bool ok;
6647 ok = ok_to_merge_coincident(c, merge_graph);
6648 if (ok < 0 || !ok)
6649 return ok;
6652 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6655 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6656 * of the schedule in "node" and return the result.
6658 * That is, essentially compute
6660 * T * N(first:first+n-1)
6662 * taking into account the constant term and the parameter coefficients
6663 * in "t_node".
6665 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6666 struct isl_sched_node *t_node, struct isl_sched_node *node,
6667 int first, int n)
6669 int i, j;
6670 isl_mat *t;
6671 int n_row, n_col, n_param, n_var;
6673 n_param = node->nparam;
6674 n_var = node->nvar;
6675 n_row = isl_mat_rows(t_node->sched);
6676 n_col = isl_mat_cols(node->sched);
6677 t = isl_mat_alloc(ctx, n_row, n_col);
6678 if (!t)
6679 return NULL;
6680 for (i = 0; i < n_row; ++i) {
6681 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6682 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6683 for (j = 0; j < n; ++j)
6684 isl_seq_addmul(t->row[i],
6685 t_node->sched->row[i][1 + n_param + j],
6686 node->sched->row[first + j],
6687 1 + n_param + n_var);
6689 return t;
6692 /* Apply the cluster schedule in "t_node" to the current band
6693 * schedule of the nodes in "graph".
6695 * In particular, replace the rows starting at band_start
6696 * by the result of applying the cluster schedule in "t_node"
6697 * to the original rows.
6699 * The coincidence of the schedule is determined by the coincidence
6700 * of the cluster schedule.
6702 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6703 struct isl_sched_node *t_node)
6705 int i, j;
6706 int n_new;
6707 int start, n;
6709 start = graph->band_start;
6710 n = graph->n_total_row - start;
6712 n_new = isl_mat_rows(t_node->sched);
6713 for (i = 0; i < graph->n; ++i) {
6714 struct isl_sched_node *node = &graph->node[i];
6715 isl_mat *t;
6717 t = node_transformation(ctx, t_node, node, start, n);
6718 node->sched = isl_mat_drop_rows(node->sched, start, n);
6719 node->sched = isl_mat_concat(node->sched, t);
6720 node->sched_map = isl_map_free(node->sched_map);
6721 if (!node->sched)
6722 return isl_stat_error;
6723 for (j = 0; j < n_new; ++j)
6724 node->coincident[start + j] = t_node->coincident[j];
6726 graph->n_total_row -= n;
6727 graph->n_row -= n;
6728 graph->n_total_row += n_new;
6729 graph->n_row += n_new;
6731 return isl_stat_ok;
6734 /* Merge the clusters marked for merging in "c" into a single
6735 * cluster using the cluster schedule in the current band of "merge_graph".
6736 * The representative SCC for the new cluster is the SCC with
6737 * the smallest index.
6739 * The current band schedule of each SCC in the new cluster is obtained
6740 * by applying the schedule of the corresponding original cluster
6741 * to the original band schedule.
6742 * All SCCs in the new cluster have the same number of schedule rows.
6744 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6745 struct isl_sched_graph *merge_graph)
6747 int i;
6748 int cluster = -1;
6749 isl_space *space;
6751 for (i = 0; i < c->n; ++i) {
6752 struct isl_sched_node *node;
6754 if (!c->scc_in_merge[i])
6755 continue;
6756 if (cluster < 0)
6757 cluster = i;
6758 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6759 if (!space)
6760 return isl_stat_error;
6761 node = graph_find_node(ctx, merge_graph, space);
6762 isl_space_free(space);
6763 if (!node)
6764 isl_die(ctx, isl_error_internal,
6765 "unable to find cluster",
6766 return isl_stat_error);
6767 if (transform(ctx, &c->scc[i], node) < 0)
6768 return isl_stat_error;
6769 c->scc_cluster[i] = cluster;
6772 return isl_stat_ok;
6775 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6776 * by scheduling the current cluster bands with respect to each other.
6778 * Construct a dependence graph with a space for each cluster and
6779 * with the coordinates of each space corresponding to the schedule
6780 * dimensions of the current band of that cluster.
6781 * Construct a cluster schedule in this cluster dependence graph and
6782 * apply it to the current cluster bands if it is applicable
6783 * according to ok_to_merge.
6785 * If the number of remaining schedule dimensions in a cluster
6786 * with a non-maximal current schedule dimension is greater than
6787 * the number of remaining schedule dimensions in clusters
6788 * with a maximal current schedule dimension, then restrict
6789 * the number of rows to be computed in the cluster schedule
6790 * to the minimal such non-maximal current schedule dimension.
6791 * Do this by adjusting merge_graph.maxvar.
6793 * Return isl_bool_true if the clusters have effectively been merged
6794 * into a single cluster.
6796 * Note that since the standard scheduling algorithm minimizes the maximal
6797 * distance over proximity constraints, the proximity constraints between
6798 * the merged clusters may not be optimized any further than what is
6799 * sufficient to bring the distances within the limits of the internal
6800 * proximity constraints inside the individual clusters.
6801 * It may therefore make sense to perform an additional translation step
6802 * to bring the clusters closer to each other, while maintaining
6803 * the linear part of the merging schedule found using the standard
6804 * scheduling algorithm.
6806 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6807 struct isl_clustering *c)
6809 struct isl_sched_graph merge_graph = { 0 };
6810 isl_bool merged;
6812 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6813 goto error;
6815 if (compute_maxvar(&merge_graph) < 0)
6816 goto error;
6817 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6818 goto error;
6819 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6820 goto error;
6821 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6822 if (merged && merge(ctx, c, &merge_graph) < 0)
6823 goto error;
6825 graph_free(ctx, &merge_graph);
6826 return merged;
6827 error:
6828 graph_free(ctx, &merge_graph);
6829 return isl_bool_error;
6832 /* Is there any edge marked "no_merge" between two SCCs that are
6833 * about to be merged (i.e., that are set in "scc_in_merge")?
6834 * "merge_edge" is the proximity edge along which the clusters of SCCs
6835 * are going to be merged.
6837 * If there is any edge between two SCCs with a negative weight,
6838 * while the weight of "merge_edge" is non-negative, then this
6839 * means that the edge was postponed. "merge_edge" should then
6840 * also be postponed since merging along the edge with negative weight should
6841 * be postponed until all edges with non-negative weight have been tried.
6842 * Replace the weight of "merge_edge" by a negative weight as well and
6843 * tell the caller not to attempt a merge.
6845 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6846 struct isl_sched_edge *merge_edge)
6848 int i;
6850 for (i = 0; i < graph->n_edge; ++i) {
6851 struct isl_sched_edge *edge = &graph->edge[i];
6853 if (!scc_in_merge[edge->src->scc])
6854 continue;
6855 if (!scc_in_merge[edge->dst->scc])
6856 continue;
6857 if (edge->no_merge)
6858 return 1;
6859 if (merge_edge->weight >= 0 && edge->weight < 0) {
6860 merge_edge->weight -= graph->max_weight + 1;
6861 return 1;
6865 return 0;
6868 /* Merge the two clusters in "c" connected by the edge in "graph"
6869 * with index "edge" into a single cluster.
6870 * If it turns out to be impossible to merge these two clusters,
6871 * then mark the edge as "no_merge" such that it will not be
6872 * considered again.
6874 * First mark all SCCs that need to be merged. This includes the SCCs
6875 * in the two clusters, but it may also include the SCCs
6876 * of intermediate clusters.
6877 * If there is already a no_merge edge between any pair of such SCCs,
6878 * then simply mark the current edge as no_merge as well.
6879 * Likewise, if any of those edges was postponed by has_bounded_distances,
6880 * then postpone the current edge as well.
6881 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6882 * if the clusters did not end up getting merged, unless the non-merge
6883 * is due to the fact that the edge was postponed. This postponement
6884 * can be recognized by a change in weight (from non-negative to negative).
6886 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6887 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6889 isl_bool merged;
6890 int edge_weight = graph->edge[edge].weight;
6892 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6893 return isl_stat_error;
6895 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6896 merged = isl_bool_false;
6897 else
6898 merged = try_merge(ctx, graph, c);
6899 if (merged < 0)
6900 return isl_stat_error;
6901 if (!merged && edge_weight == graph->edge[edge].weight)
6902 graph->edge[edge].no_merge = 1;
6904 return isl_stat_ok;
6907 /* Does "node" belong to the cluster identified by "cluster"?
6909 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6911 return node->cluster == cluster;
6914 /* Does "edge" connect two nodes belonging to the cluster
6915 * identified by "cluster"?
6917 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6919 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6922 /* Swap the schedule of "node1" and "node2".
6923 * Both nodes have been derived from the same node in a common parent graph.
6924 * Since the "coincident" field is shared with that node
6925 * in the parent graph, there is no need to also swap this field.
6927 static void swap_sched(struct isl_sched_node *node1,
6928 struct isl_sched_node *node2)
6930 isl_mat *sched;
6931 isl_map *sched_map;
6933 sched = node1->sched;
6934 node1->sched = node2->sched;
6935 node2->sched = sched;
6937 sched_map = node1->sched_map;
6938 node1->sched_map = node2->sched_map;
6939 node2->sched_map = sched_map;
6942 /* Copy the current band schedule from the SCCs that form the cluster
6943 * with index "pos" to the actual cluster at position "pos".
6944 * By construction, the index of the first SCC that belongs to the cluster
6945 * is also "pos".
6947 * The order of the nodes inside both the SCCs and the cluster
6948 * is assumed to be same as the order in the original "graph".
6950 * Since the SCC graphs will no longer be used after this function,
6951 * the schedules are actually swapped rather than copied.
6953 static isl_stat copy_partial(struct isl_sched_graph *graph,
6954 struct isl_clustering *c, int pos)
6956 int i, j;
6958 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6959 c->cluster[pos].n_row = c->scc[pos].n_row;
6960 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6961 j = 0;
6962 for (i = 0; i < graph->n; ++i) {
6963 int k;
6964 int s;
6966 if (graph->node[i].cluster != pos)
6967 continue;
6968 s = graph->node[i].scc;
6969 k = c->scc_node[s]++;
6970 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6971 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6972 c->cluster[pos].maxvar = c->scc[s].maxvar;
6973 ++j;
6976 return isl_stat_ok;
6979 /* Is there a (conditional) validity dependence from node[j] to node[i],
6980 * forcing node[i] to follow node[j] or do the nodes belong to the same
6981 * cluster?
6983 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6985 struct isl_sched_graph *graph = user;
6987 if (graph->node[i].cluster == graph->node[j].cluster)
6988 return isl_bool_true;
6989 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6992 /* Extract the merged clusters of SCCs in "graph", sort them, and
6993 * store them in c->clusters. Update c->scc_cluster accordingly.
6995 * First keep track of the cluster containing the SCC to which a node
6996 * belongs in the node itself.
6997 * Then extract the clusters into c->clusters, copying the current
6998 * band schedule from the SCCs that belong to the cluster.
6999 * Do this only once per cluster.
7001 * Finally, topologically sort the clusters and update c->scc_cluster
7002 * to match the new scc numbering. While the SCCs were originally
7003 * sorted already, some SCCs that depend on some other SCCs may
7004 * have been merged with SCCs that appear before these other SCCs.
7005 * A reordering may therefore be required.
7007 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
7008 struct isl_clustering *c)
7010 int i;
7012 for (i = 0; i < graph->n; ++i)
7013 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
7015 for (i = 0; i < graph->scc; ++i) {
7016 if (c->scc_cluster[i] != i)
7017 continue;
7018 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
7019 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
7020 return isl_stat_error;
7021 c->cluster[i].src_scc = -1;
7022 c->cluster[i].dst_scc = -1;
7023 if (copy_partial(graph, c, i) < 0)
7024 return isl_stat_error;
7027 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
7028 return isl_stat_error;
7029 for (i = 0; i < graph->n; ++i)
7030 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
7032 return isl_stat_ok;
7035 /* Compute weights on the proximity edges of "graph" that can
7036 * be used by find_proximity to find the most appropriate
7037 * proximity edge to use to merge two clusters in "c".
7038 * The weights are also used by has_bounded_distances to determine
7039 * whether the merge should be allowed.
7040 * Store the maximum of the computed weights in graph->max_weight.
7042 * The computed weight is a measure for the number of remaining schedule
7043 * dimensions that can still be completely aligned.
7044 * In particular, compute the number of equalities between
7045 * input dimensions and output dimensions in the proximity constraints.
7046 * The directions that are already handled by outer schedule bands
7047 * are projected out prior to determining this number.
7049 * Edges that will never be considered by find_proximity are ignored.
7051 static isl_stat compute_weights(struct isl_sched_graph *graph,
7052 struct isl_clustering *c)
7054 int i;
7056 graph->max_weight = 0;
7058 for (i = 0; i < graph->n_edge; ++i) {
7059 struct isl_sched_edge *edge = &graph->edge[i];
7060 struct isl_sched_node *src = edge->src;
7061 struct isl_sched_node *dst = edge->dst;
7062 isl_basic_map *hull;
7063 isl_bool prox;
7064 int n_in, n_out;
7066 prox = is_non_empty_proximity(edge);
7067 if (prox < 0)
7068 return isl_stat_error;
7069 if (!prox)
7070 continue;
7071 if (bad_cluster(&c->scc[edge->src->scc]) ||
7072 bad_cluster(&c->scc[edge->dst->scc]))
7073 continue;
7074 if (c->scc_cluster[edge->dst->scc] ==
7075 c->scc_cluster[edge->src->scc])
7076 continue;
7078 hull = isl_map_affine_hull(isl_map_copy(edge->map));
7079 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
7080 isl_mat_copy(src->vmap));
7081 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
7082 isl_mat_copy(dst->vmap));
7083 hull = isl_basic_map_project_out(hull,
7084 isl_dim_in, 0, src->rank);
7085 hull = isl_basic_map_project_out(hull,
7086 isl_dim_out, 0, dst->rank);
7087 hull = isl_basic_map_remove_divs(hull);
7088 n_in = isl_basic_map_dim(hull, isl_dim_in);
7089 n_out = isl_basic_map_dim(hull, isl_dim_out);
7090 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7091 isl_dim_in, 0, n_in);
7092 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7093 isl_dim_out, 0, n_out);
7094 if (!hull)
7095 return isl_stat_error;
7096 edge->weight = isl_basic_map_n_equality(hull);
7097 isl_basic_map_free(hull);
7099 if (edge->weight > graph->max_weight)
7100 graph->max_weight = edge->weight;
7103 return isl_stat_ok;
7106 /* Call compute_schedule_finish_band on each of the clusters in "c"
7107 * in their topological order. This order is determined by the scc
7108 * fields of the nodes in "graph".
7109 * Combine the results in a sequence expressing the topological order.
7111 * If there is only one cluster left, then there is no need to introduce
7112 * a sequence node. Also, in this case, the cluster necessarily contains
7113 * the SCC at position 0 in the original graph and is therefore also
7114 * stored in the first cluster of "c".
7116 static __isl_give isl_schedule_node *finish_bands_clustering(
7117 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7118 struct isl_clustering *c)
7120 int i;
7121 isl_ctx *ctx;
7122 isl_union_set_list *filters;
7124 if (graph->scc == 1)
7125 return compute_schedule_finish_band(node, &c->cluster[0], 0);
7127 ctx = isl_schedule_node_get_ctx(node);
7129 filters = extract_sccs(ctx, graph);
7130 node = isl_schedule_node_insert_sequence(node, filters);
7132 for (i = 0; i < graph->scc; ++i) {
7133 int j = c->scc_cluster[i];
7134 node = isl_schedule_node_child(node, i);
7135 node = isl_schedule_node_child(node, 0);
7136 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
7137 node = isl_schedule_node_parent(node);
7138 node = isl_schedule_node_parent(node);
7141 return node;
7144 /* Compute a schedule for a connected dependence graph by first considering
7145 * each strongly connected component (SCC) in the graph separately and then
7146 * incrementally combining them into clusters.
7147 * Return the updated schedule node.
7149 * Initially, each cluster consists of a single SCC, each with its
7150 * own band schedule. The algorithm then tries to merge pairs
7151 * of clusters along a proximity edge until no more suitable
7152 * proximity edges can be found. During this merging, the schedule
7153 * is maintained in the individual SCCs.
7154 * After the merging is completed, the full resulting clusters
7155 * are extracted and in finish_bands_clustering,
7156 * compute_schedule_finish_band is called on each of them to integrate
7157 * the band into "node" and to continue the computation.
7159 * compute_weights initializes the weights that are used by find_proximity.
7161 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
7162 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7164 isl_ctx *ctx;
7165 struct isl_clustering c;
7166 int i;
7168 ctx = isl_schedule_node_get_ctx(node);
7170 if (clustering_init(ctx, &c, graph) < 0)
7171 goto error;
7173 if (compute_weights(graph, &c) < 0)
7174 goto error;
7176 for (;;) {
7177 i = find_proximity(graph, &c);
7178 if (i < 0)
7179 goto error;
7180 if (i >= graph->n_edge)
7181 break;
7182 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
7183 goto error;
7186 if (extract_clusters(ctx, graph, &c) < 0)
7187 goto error;
7189 node = finish_bands_clustering(node, graph, &c);
7191 clustering_free(ctx, &c);
7192 return node;
7193 error:
7194 clustering_free(ctx, &c);
7195 return isl_schedule_node_free(node);
7198 /* Compute a schedule for a connected dependence graph and return
7199 * the updated schedule node.
7201 * If Feautrier's algorithm is selected, we first recursively try to satisfy
7202 * as many validity dependences as possible. When all validity dependences
7203 * are satisfied we extend the schedule to a full-dimensional schedule.
7205 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
7206 * depending on whether the user has selected the option to try and
7207 * compute a schedule for the entire (weakly connected) component first.
7208 * If there is only a single strongly connected component (SCC), then
7209 * there is no point in trying to combine SCCs
7210 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
7211 * is called instead.
7213 static __isl_give isl_schedule_node *compute_schedule_wcc(
7214 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7216 isl_ctx *ctx;
7218 if (!node)
7219 return NULL;
7221 ctx = isl_schedule_node_get_ctx(node);
7222 if (detect_sccs(ctx, graph) < 0)
7223 return isl_schedule_node_free(node);
7225 if (compute_maxvar(graph) < 0)
7226 return isl_schedule_node_free(node);
7228 if (need_feautrier_step(ctx, graph))
7229 return compute_schedule_wcc_feautrier(node, graph);
7231 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
7232 return compute_schedule_wcc_whole(node, graph);
7233 else
7234 return compute_schedule_wcc_clustering(node, graph);
7237 /* Compute a schedule for each group of nodes identified by node->scc
7238 * separately and then combine them in a sequence node (or as set node
7239 * if graph->weak is set) inserted at position "node" of the schedule tree.
7240 * Return the updated schedule node.
7242 * If "wcc" is set then each of the groups belongs to a single
7243 * weakly connected component in the dependence graph so that
7244 * there is no need for compute_sub_schedule to look for weakly
7245 * connected components.
7247 * If a set node would be introduced and if the number of components
7248 * is equal to the number of nodes, then check if the schedule
7249 * is already complete. If so, a redundant set node would be introduced
7250 * (without any further descendants) stating that the statements
7251 * can be executed in arbitrary order, which is also expressed
7252 * by the absence of any node. Refrain from inserting any nodes
7253 * in this case and simply return.
7255 static __isl_give isl_schedule_node *compute_component_schedule(
7256 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7257 int wcc)
7259 int component;
7260 isl_ctx *ctx;
7261 isl_union_set_list *filters;
7263 if (!node)
7264 return NULL;
7266 if (graph->weak && graph->scc == graph->n) {
7267 if (compute_maxvar(graph) < 0)
7268 return isl_schedule_node_free(node);
7269 if (graph->n_row >= graph->maxvar)
7270 return node;
7273 ctx = isl_schedule_node_get_ctx(node);
7274 filters = extract_sccs(ctx, graph);
7275 if (graph->weak)
7276 node = isl_schedule_node_insert_set(node, filters);
7277 else
7278 node = isl_schedule_node_insert_sequence(node, filters);
7280 for (component = 0; component < graph->scc; ++component) {
7281 node = isl_schedule_node_child(node, component);
7282 node = isl_schedule_node_child(node, 0);
7283 node = compute_sub_schedule(node, ctx, graph,
7284 &node_scc_exactly,
7285 &edge_scc_exactly, component, wcc);
7286 node = isl_schedule_node_parent(node);
7287 node = isl_schedule_node_parent(node);
7290 return node;
7293 /* Compute a schedule for the given dependence graph and insert it at "node".
7294 * Return the updated schedule node.
7296 * We first check if the graph is connected (through validity and conditional
7297 * validity dependences) and, if not, compute a schedule
7298 * for each component separately.
7299 * If the schedule_serialize_sccs option is set, then we check for strongly
7300 * connected components instead and compute a separate schedule for
7301 * each such strongly connected component.
7303 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
7304 struct isl_sched_graph *graph)
7306 isl_ctx *ctx;
7308 if (!node)
7309 return NULL;
7311 ctx = isl_schedule_node_get_ctx(node);
7312 if (isl_options_get_schedule_serialize_sccs(ctx)) {
7313 if (detect_sccs(ctx, graph) < 0)
7314 return isl_schedule_node_free(node);
7315 } else {
7316 if (detect_wccs(ctx, graph) < 0)
7317 return isl_schedule_node_free(node);
7320 if (graph->scc > 1)
7321 return compute_component_schedule(node, graph, 1);
7323 return compute_schedule_wcc(node, graph);
7326 /* Compute a schedule on sc->domain that respects the given schedule
7327 * constraints.
7329 * In particular, the schedule respects all the validity dependences.
7330 * If the default isl scheduling algorithm is used, it tries to minimize
7331 * the dependence distances over the proximity dependences.
7332 * If Feautrier's scheduling algorithm is used, the proximity dependence
7333 * distances are only minimized during the extension to a full-dimensional
7334 * schedule.
7336 * If there are any condition and conditional validity dependences,
7337 * then the conditional validity dependences may be violated inside
7338 * a tilable band, provided they have no adjacent non-local
7339 * condition dependences.
7341 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
7342 __isl_take isl_schedule_constraints *sc)
7344 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
7345 struct isl_sched_graph graph = { 0 };
7346 isl_schedule *sched;
7347 isl_schedule_node *node;
7348 isl_union_set *domain;
7350 sc = isl_schedule_constraints_align_params(sc);
7352 domain = isl_schedule_constraints_get_domain(sc);
7353 if (isl_union_set_n_set(domain) == 0) {
7354 isl_schedule_constraints_free(sc);
7355 return isl_schedule_from_domain(domain);
7358 if (graph_init(&graph, sc) < 0)
7359 domain = isl_union_set_free(domain);
7361 node = isl_schedule_node_from_domain(domain);
7362 node = isl_schedule_node_child(node, 0);
7363 if (graph.n > 0)
7364 node = compute_schedule(node, &graph);
7365 sched = isl_schedule_node_get_schedule(node);
7366 isl_schedule_node_free(node);
7368 graph_free(ctx, &graph);
7369 isl_schedule_constraints_free(sc);
7371 return sched;
7374 /* Compute a schedule for the given union of domains that respects
7375 * all the validity dependences and minimizes
7376 * the dependence distances over the proximity dependences.
7378 * This function is kept for backward compatibility.
7380 __isl_give isl_schedule *isl_union_set_compute_schedule(
7381 __isl_take isl_union_set *domain,
7382 __isl_take isl_union_map *validity,
7383 __isl_take isl_union_map *proximity)
7385 isl_schedule_constraints *sc;
7387 sc = isl_schedule_constraints_on_domain(domain);
7388 sc = isl_schedule_constraints_set_validity(sc, validity);
7389 sc = isl_schedule_constraints_set_proximity(sc, proximity);
7391 return isl_schedule_constraints_compute_schedule(sc);