scheduling: introduce band forest interface
[platform/upstream/isl.git] / isl_schedule.c
1 /*
2  * Copyright 2011      INRIA Saclay
3  *
4  * Use of this software is governed by the GNU LGPLv2.1 license
5  *
6  * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
7  * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
8  * 91893 Orsay, France
9  */
10
11 #include <isl_ctx_private.h>
12 #include <isl_map_private.h>
13 #include <isl_dim_private.h>
14 #include <isl/hash.h>
15 #include <isl/constraint.h>
16 #include <isl/schedule.h>
17 #include <isl_mat_private.h>
18 #include <isl/set.h>
19 #include <isl/seq.h>
20 #include <isl_tab.h>
21 #include <isl_dim_map.h>
22 #include <isl_hmap_map_basic_set.h>
23 #include <isl_qsort.h>
24 #include <isl_schedule_private.h>
25 #include <isl_band_private.h>
26
27 /*
28  * The scheduling algorithm implemented in this file was inspired by
29  * Bondhugula et al., "Automatic Transformations for Communication-Minimized
30  * Parallelization and Locality Optimization in the Polyhedral Model".
31  */
32
33
34 /* Internal information about a node that is used during the construction
35  * of a schedule.
36  * dim represents the space in which the domain lives
37  * sched is a matrix representation of the schedule being constructed
38  *      for this node
39  * sched_map is an isl_map representation of the same (partial) schedule
40  *      sched_map may be NULL
41  * rank is the number of linearly independent rows in the linear part
42  *      of sched
43  * the columns of cmap represent a change of basis for the schedule
44  *      coefficients; the first rank columns span the linear part of
45  *      the schedule rows
46  * start is the first variable in the LP problem in the sequences that
47  *      represents the schedule coefficients of this node
48  * nvar is the dimension of the domain
49  * nparam is the number of parameters or 0 if we are not constructing
50  *      a parametric schedule
51  *
52  * scc is the index of SCC (or WCC) this node belongs to
53  *
54  * band contains the band index for each of the rows of the schedule.
55  * band_id is used to differentiate between separate bands at the same
56  * level within the same parent band, i.e., bands that are separated
57  * by the parent band or bands that are independent of each other.
58  * parallel contains a boolean for each of the rows of the schedule,
59  * indicating whether the corresponding scheduling dimension is parallel
60  * within its band and with respect to the proximity edges.
61  *
62  * index, min_index and on_stack are used during the SCC detection
63  * index represents the order in which nodes are visited.
64  * min_index is the index of the root of a (sub)component.
65  * on_stack indicates whether the node is currently on the stack.
66  */
67 struct isl_sched_node {
68         isl_dim *dim;
69         isl_mat *sched;
70         isl_map *sched_map;
71         int      rank;
72         isl_mat *cmap;
73         int      start;
74         int      nvar;
75         int      nparam;
76
77         int      scc;
78
79         int     *band;
80         int     *band_id;
81         int     *parallel;
82
83         /* scc detection */
84         int      index;
85         int      min_index;
86         int      on_stack;
87 };
88
89 static int node_has_dim(const void *entry, const void *val)
90 {
91         struct isl_sched_node *node = (struct isl_sched_node *)entry;
92         isl_dim *dim = (isl_dim *)val;
93
94         return isl_dim_equal(node->dim, dim);
95 }
96
97 /* An edge in the dependence graph.  An edge may be used to
98  * ensure validity of the generated schedule, to minimize the dependence
99  * distance or both
100  *
101  * map is the dependence relation
102  * src is the source node
103  * dst is the sink node
104  * validity is set if the edge is used to ensure correctness
105  * proximity is set if the edge is used to minimize dependence distances
106  *
107  * For validity edges, start and end mark the sequence of inequality
108  * constraints in the LP problem that encode the validity constraint
109  * corresponding to this edge.
110  */
111 struct isl_sched_edge {
112         isl_map *map;
113
114         struct isl_sched_node *src;
115         struct isl_sched_node *dst;
116
117         int validity;
118         int proximity;
119
120         int start;
121         int end;
122 };
123
124 /* Internal information about the dependence graph used during
125  * the construction of the schedule.
126  *
127  * intra_hmap is a cache, mapping dependence relations to their dual,
128  *      for dependences from a node to itself
129  * inter_hmap is a cache, mapping dependence relations to their dual,
130  *      for dependences between distinct nodes
131  *
132  * n is the number of nodes
133  * node is the list of nodes
134  * maxvar is the maximal number of variables over all nodes
135  * n_row is the current (maximal) number of linearly independent
136  *      rows in the node schedules
137  * n_total_row is the current number of rows in the node schedules
138  * n_band is the current number of completed bands
139  * band_start is the starting row in the node schedules of the current band
140  * root is set if this graph is the original dependence graph,
141  *      without any splitting
142  *
143  * sorted contains a list of node indices sorted according to the
144  *      SCC to which a node belongs
145  *
146  * n_edge is the number of edges
147  * edge is the list of edges
148  * edge_table contains pointers into the edge array, hashed on the source
149  *      and sink spaces; the table only contains edges that represent
150  *      validity constraints (and that may or may not also represent proximity
151  *      constraints)
152  *
153  * node_table contains pointers into the node array, hashed on the space
154  *
155  * region contains a list of variable sequences that should be non-trivial
156  *
157  * lp contains the (I)LP problem used to obtain new schedule rows
158  *
159  * src_scc and dst_scc are the source and sink SCCs of an edge with
160  *      conflicting constraints
161  *
162  * scc, sp, index and stack are used during the detection of SCCs
163  * scc is the number of the next SCC
164  * stack contains the nodes on the path from the root to the current node
165  * sp is the stack pointer
166  * index is the index of the last node visited
167  */
168 struct isl_sched_graph {
169         isl_hmap_map_basic_set *intra_hmap;
170         isl_hmap_map_basic_set *inter_hmap;
171
172         struct isl_sched_node *node;
173         int n;
174         int maxvar;
175         int n_row;
176
177         int *sorted;
178
179         int n_band;
180         int n_total_row;
181         int band_start;
182
183         int root;
184
185         struct isl_sched_edge *edge;
186         int n_edge;
187         struct isl_hash_table *edge_table;
188
189         struct isl_hash_table *node_table;
190         struct isl_region *region;
191
192         isl_basic_set *lp;
193
194         int src_scc;
195         int dst_scc;
196
197         /* scc detection */
198         int scc;
199         int sp;
200         int index;
201         int *stack;
202 };
203
204 /* Initialize node_table based on the list of nodes.
205  */
206 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
207 {
208         int i;
209
210         graph->node_table = isl_hash_table_alloc(ctx, graph->n);
211         if (!graph->node_table)
212                 return -1;
213
214         for (i = 0; i < graph->n; ++i) {
215                 struct isl_hash_table_entry *entry;
216                 uint32_t hash;
217
218                 hash = isl_dim_get_hash(graph->node[i].dim);
219                 entry = isl_hash_table_find(ctx, graph->node_table, hash,
220                                             &node_has_dim,
221                                             graph->node[i].dim, 1);
222                 if (!entry)
223                         return -1;
224                 entry->data = &graph->node[i];
225         }
226
227         return 0;
228 }
229
230 /* Return a pointer to the node that lives within the given space,
231  * or NULL if there is no such node.
232  */
233 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
234         struct isl_sched_graph *graph, __isl_keep isl_dim *dim)
235 {
236         struct isl_hash_table_entry *entry;
237         uint32_t hash;
238
239         hash = isl_dim_get_hash(dim);
240         entry = isl_hash_table_find(ctx, graph->node_table, hash,
241                                     &node_has_dim, dim, 0);
242
243         return entry ? entry->data : NULL;
244 }
245
246 static int edge_has_src_and_dst(const void *entry, const void *val)
247 {
248         const struct isl_sched_edge *edge = entry;
249         const struct isl_sched_edge *temp = val;
250
251         return edge->src == temp->src && edge->dst == temp->dst;
252 }
253
254 /* Initialize edge_table based on the list of edges.
255  * Only edges with validity set are added to the table.
256  */
257 static int graph_init_edge_table(isl_ctx *ctx, struct isl_sched_graph *graph)
258 {
259         int i;
260
261         graph->edge_table = isl_hash_table_alloc(ctx, graph->n_edge);
262         if (!graph->edge_table)
263                 return -1;
264
265         for (i = 0; i < graph->n_edge; ++i) {
266                 struct isl_hash_table_entry *entry;
267                 uint32_t hash;
268
269                 if (!graph->edge[i].validity)
270                         continue;
271
272                 hash = isl_hash_init();
273                 hash = isl_hash_builtin(hash, graph->edge[i].src);
274                 hash = isl_hash_builtin(hash, graph->edge[i].dst);
275                 entry = isl_hash_table_find(ctx, graph->edge_table, hash,
276                                             &edge_has_src_and_dst,
277                                             &graph->edge[i], 1);
278                 if (!entry)
279                         return -1;
280                 entry->data = &graph->edge[i];
281         }
282
283         return 0;
284 }
285
286 /* Check whether the dependence graph has a (validity) edge
287  * between the given two nodes.
288  */
289 static int graph_has_edge(struct isl_sched_graph *graph,
290         struct isl_sched_node *src, struct isl_sched_node *dst)
291 {
292         isl_ctx *ctx = isl_dim_get_ctx(src->dim);
293         struct isl_hash_table_entry *entry;
294         uint32_t hash;
295         struct isl_sched_edge temp = { .src = src, .dst = dst };
296         struct isl_sched_edge *edge;
297         int empty;
298
299         hash = isl_hash_init();
300         hash = isl_hash_builtin(hash, temp.src);
301         hash = isl_hash_builtin(hash, temp.dst);
302         entry = isl_hash_table_find(ctx, graph->edge_table, hash,
303                                     &edge_has_src_and_dst, &temp, 0);
304         if (!entry)
305                 return 0;
306
307         edge = entry->data;
308         empty = isl_map_plain_is_empty(edge->map);
309         if (empty < 0)
310                 return -1;
311
312         return !empty;
313 }
314
315 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
316         int n_node, int n_edge)
317 {
318         int i;
319
320         graph->n = n_node;
321         graph->n_edge = n_edge;
322         graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
323         graph->sorted = isl_calloc_array(ctx, int, graph->n);
324         graph->region = isl_alloc_array(ctx, struct isl_region, graph->n);
325         graph->stack = isl_alloc_array(ctx, int, graph->n);
326         graph->edge = isl_calloc_array(ctx,
327                                         struct isl_sched_edge, graph->n_edge);
328
329         graph->intra_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
330         graph->inter_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
331
332         if (!graph->node || !graph->region || !graph->stack || !graph->edge ||
333             !graph->sorted)
334                 return -1;
335
336         for(i = 0; i < graph->n; ++i)
337                 graph->sorted[i] = i;
338
339         return 0;
340 }
341
342 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
343 {
344         int i;
345
346         isl_hmap_map_basic_set_free(ctx, graph->intra_hmap);
347         isl_hmap_map_basic_set_free(ctx, graph->inter_hmap);
348
349         for (i = 0; i < graph->n; ++i) {
350                 isl_dim_free(graph->node[i].dim);
351                 isl_mat_free(graph->node[i].sched);
352                 isl_map_free(graph->node[i].sched_map);
353                 isl_mat_free(graph->node[i].cmap);
354                 if (graph->root) {
355                         free(graph->node[i].band);
356                         free(graph->node[i].band_id);
357                         free(graph->node[i].parallel);
358                 }
359         }
360         free(graph->node);
361         free(graph->sorted);
362         for (i = 0; i < graph->n_edge; ++i)
363                 isl_map_free(graph->edge[i].map);
364         free(graph->edge);
365         free(graph->region);
366         free(graph->stack);
367         isl_hash_table_free(ctx, graph->edge_table);
368         isl_hash_table_free(ctx, graph->node_table);
369         isl_basic_set_free(graph->lp);
370 }
371
372 /* Add a new node to the graph representing the given set.
373  */
374 static int extract_node(__isl_take isl_set *set, void *user)
375 {
376         int nvar, nparam;
377         isl_ctx *ctx;
378         isl_dim *dim;
379         isl_mat *sched;
380         struct isl_sched_graph *graph = user;
381         int *band, *band_id, *parallel;
382
383         ctx = isl_set_get_ctx(set);
384         dim = isl_set_get_dim(set);
385         isl_set_free(set);
386         nvar = isl_dim_size(dim, isl_dim_set);
387         nparam = isl_dim_size(dim, isl_dim_param);
388         if (!ctx->opt->schedule_parametric)
389                 nparam = 0;
390         sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
391         graph->node[graph->n].dim = dim;
392         graph->node[graph->n].nvar = nvar;
393         graph->node[graph->n].nparam = nparam;
394         graph->node[graph->n].sched = sched;
395         graph->node[graph->n].sched_map = NULL;
396         band = isl_alloc_array(ctx, int, graph->n_edge + nvar);
397         graph->node[graph->n].band = band;
398         band_id = isl_calloc_array(ctx, int, graph->n_edge + nvar);
399         graph->node[graph->n].band_id = band_id;
400         parallel = isl_calloc_array(ctx, int, graph->n_edge + nvar);
401         graph->node[graph->n].parallel = parallel;
402         graph->n++;
403
404         if (!sched || !band || !band_id || !parallel)
405                 return -1;
406
407         return 0;
408 }
409
410 /* Add a new edge to the graph based on the given map.
411  * Edges are first extracted from the validity dependences,
412  * from which the edge_table is constructed.
413  * Afterwards, the proximity dependences are added.  If a proximity
414  * dependence relation happens to be identical to one of the
415  * validity dependence relations added before, then we don't create
416  * a new edge, but instead mark the original edge as also representing
417  * a proximity dependence.
418  */
419 static int extract_edge(__isl_take isl_map *map, void *user)
420 {
421         isl_ctx *ctx = isl_map_get_ctx(map);
422         struct isl_sched_graph *graph = user;
423         struct isl_sched_node *src, *dst;
424         isl_dim *dim;
425
426         dim = isl_dim_domain(isl_map_get_dim(map));
427         src = graph_find_node(ctx, graph, dim);
428         isl_dim_free(dim);
429         dim = isl_dim_range(isl_map_get_dim(map));
430         dst = graph_find_node(ctx, graph, dim);
431         isl_dim_free(dim);
432
433         if (!src || !dst) {
434                 isl_map_free(map);
435                 return 0;
436         }
437
438         graph->edge[graph->n_edge].src = src;
439         graph->edge[graph->n_edge].dst = dst;
440         graph->edge[graph->n_edge].map = map;
441         graph->edge[graph->n_edge].validity = !graph->edge_table;
442         graph->edge[graph->n_edge].proximity = !!graph->edge_table;
443         graph->n_edge++;
444
445         if (graph->edge_table) {
446                 uint32_t hash;
447                 struct isl_hash_table_entry *entry;
448                 struct isl_sched_edge *edge;
449                 int is_equal;
450
451                 hash = isl_hash_init();
452                 hash = isl_hash_builtin(hash, src);
453                 hash = isl_hash_builtin(hash, dst);
454                 entry = isl_hash_table_find(ctx, graph->edge_table, hash,
455                                             &edge_has_src_and_dst,
456                                             &graph->edge[graph->n_edge - 1], 0);
457                 if (!entry)
458                         return 0;
459                 edge = entry->data;
460                 is_equal = isl_map_plain_is_equal(map, edge->map);
461                 if (is_equal < 0)
462                         return -1;
463                 if (!is_equal)
464                         return 0;
465
466                 graph->n_edge--;
467                 edge->proximity = 1;
468                 isl_map_free(map);
469         }
470
471         return 0;
472 }
473
474 /* Check whether there is a validity dependence from src to dst,
475  * forcing dst to follow src.
476  */
477 static int node_follows(struct isl_sched_graph *graph, 
478         struct isl_sched_node *dst, struct isl_sched_node *src)
479 {
480         return graph_has_edge(graph, src, dst);
481 }
482
483 /* Perform Tarjan's algorithm for computing the strongly connected components
484  * in the dependence graph (only validity edges).
485  * If directed is not set, we consider the graph to be undirected and
486  * we effectively compute the (weakly) connected components.
487  */
488 static int detect_sccs_tarjan(struct isl_sched_graph *g, int i, int directed)
489 {
490         int j;
491
492         g->node[i].index = g->index;
493         g->node[i].min_index = g->index;
494         g->node[i].on_stack = 1;
495         g->index++;
496         g->stack[g->sp++] = i;
497
498         for (j = g->n - 1; j >= 0; --j) {
499                 int f;
500
501                 if (j == i)
502                         continue;
503                 if (g->node[j].index >= 0 &&
504                         (!g->node[j].on_stack ||
505                          g->node[j].index > g->node[i].min_index))
506                         continue;
507                 
508                 f = node_follows(g, &g->node[i], &g->node[j]);
509                 if (f < 0)
510                         return -1;
511                 if (!f && !directed) {
512                         f = node_follows(g, &g->node[j], &g->node[i]);
513                         if (f < 0)
514                                 return -1;
515                 }
516                 if (!f)
517                         continue;
518                 if (g->node[j].index < 0) {
519                         detect_sccs_tarjan(g, j, directed);
520                         if (g->node[j].min_index < g->node[i].min_index)
521                                 g->node[i].min_index = g->node[j].min_index;
522                 } else if (g->node[j].index < g->node[i].min_index)
523                         g->node[i].min_index = g->node[j].index;
524         }
525
526         if (g->node[i].index != g->node[i].min_index)
527                 return 0;
528
529         do {
530                 j = g->stack[--g->sp];
531                 g->node[j].on_stack = 0;
532                 g->node[j].scc = g->scc;
533         } while (j != i);
534         g->scc++;
535
536         return 0;
537 }
538
539 static int detect_ccs(struct isl_sched_graph *graph, int directed)
540 {
541         int i;
542
543         graph->index = 0;
544         graph->sp = 0;
545         graph->scc = 0;
546         for (i = graph->n - 1; i >= 0; --i)
547                 graph->node[i].index = -1;
548
549         for (i = graph->n - 1; i >= 0; --i) {
550                 if (graph->node[i].index >= 0)
551                         continue;
552                 if (detect_sccs_tarjan(graph, i, directed) < 0)
553                         return -1;
554         }
555
556         return 0;
557 }
558
559 /* Apply Tarjan's algorithm to detect the strongly connected components
560  * in the dependence graph.
561  */
562 static int detect_sccs(struct isl_sched_graph *graph)
563 {
564         return detect_ccs(graph, 1);
565 }
566
567 /* Apply Tarjan's algorithm to detect the (weakly) connected components
568  * in the dependence graph.
569  */
570 static int detect_wccs(struct isl_sched_graph *graph)
571 {
572         return detect_ccs(graph, 0);
573 }
574
575 static int cmp_scc(const void *a, const void *b, void *data)
576 {
577         struct isl_sched_graph *graph = data;
578         const int *i1 = a;
579         const int *i2 = b;
580
581         return graph->node[*i1].scc - graph->node[*i2].scc;
582 }
583
584 /* Sort the elements of graph->sorted according to the corresponding SCCs.
585  */
586 static void sort_sccs(struct isl_sched_graph *graph)
587 {
588         isl_quicksort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
589 }
590
591 /* Given a dependence relation R from a node to itself,
592  * construct the set of coefficients of valid constraints for elements
593  * in that dependence relation.
594  * In particular, the result contains tuples of coefficients
595  * c_0, c_n, c_x such that
596  *
597  *      c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
598  *
599  * or, equivalently,
600  *
601  *      c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
602  *
603  * We choose here to compute the dual of delta R.
604  * Alternatively, we could have computed the dual of R, resulting
605  * in a set of tuples c_0, c_n, c_x, c_y, and then
606  * plugged in (c_0, c_n, c_x, -c_x).
607  */
608 static __isl_give isl_basic_set *intra_coefficients(
609         struct isl_sched_graph *graph, __isl_take isl_map *map)
610 {
611         isl_ctx *ctx = isl_map_get_ctx(map);
612         isl_set *delta;
613         isl_basic_set *coef;
614
615         if (isl_hmap_map_basic_set_has(ctx, graph->intra_hmap, map))
616                 return isl_hmap_map_basic_set_get(ctx, graph->intra_hmap, map);
617
618         delta = isl_set_remove_divs(isl_map_deltas(isl_map_copy(map)));
619         coef = isl_set_coefficients(delta);
620         isl_hmap_map_basic_set_set(ctx, graph->intra_hmap, map,
621                                         isl_basic_set_copy(coef));
622
623         return coef;
624 }
625
626 /* Given a dependence relation R, * construct the set of coefficients
627  * of valid constraints for elements in that dependence relation.
628  * In particular, the result contains tuples of coefficients
629  * c_0, c_n, c_x, c_y such that
630  *
631  *      c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
632  *
633  */
634 static __isl_give isl_basic_set *inter_coefficients(
635         struct isl_sched_graph *graph, __isl_take isl_map *map)
636 {
637         isl_ctx *ctx = isl_map_get_ctx(map);
638         isl_set *set;
639         isl_basic_set *coef;
640
641         if (isl_hmap_map_basic_set_has(ctx, graph->inter_hmap, map))
642                 return isl_hmap_map_basic_set_get(ctx, graph->inter_hmap, map);
643
644         set = isl_map_wrap(isl_map_remove_divs(isl_map_copy(map)));
645         coef = isl_set_coefficients(set);
646         isl_hmap_map_basic_set_set(ctx, graph->inter_hmap, map,
647                                         isl_basic_set_copy(coef));
648
649         return coef;
650 }
651
652 /* Add constraints to graph->lp that force validity for the given
653  * dependence from a node i to itself.
654  * That is, add constraints that enforce
655  *
656  *      (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
657  *      = c_i_x (y - x) >= 0
658  *
659  * for each (x,y) in R.
660  * We obtain general constraints on coefficients (c_0, c_n, c_x)
661  * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
662  * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
663  * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
664  *
665  * Actually, we do not construct constraints for the c_i_x themselves,
666  * but for the coefficients of c_i_x written as a linear combination
667  * of the columns in node->cmap.
668  */
669 static int add_intra_validity_constraints(struct isl_sched_graph *graph,
670         struct isl_sched_edge *edge)
671 {
672         unsigned total;
673         isl_map *map = isl_map_copy(edge->map);
674         isl_ctx *ctx = isl_map_get_ctx(map);
675         isl_dim *dim;
676         isl_dim_map *dim_map;
677         isl_basic_set *coef;
678         struct isl_sched_node *node = edge->src;
679
680         coef = intra_coefficients(graph, map);
681
682         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
683
684         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
685                     isl_dim_size(dim, isl_dim_set), isl_mat_copy(node->cmap));
686
687         total = isl_basic_set_total_dim(graph->lp);
688         dim_map = isl_dim_map_alloc(ctx, total);
689         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
690                           isl_dim_size(dim, isl_dim_set), 1,
691                           node->nvar, -1);
692         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
693                           isl_dim_size(dim, isl_dim_set), 1,
694                           node->nvar, 1);
695         graph->lp = isl_basic_set_extend_constraints(graph->lp,
696                         coef->n_eq, coef->n_ineq);
697         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
698                                                            coef, dim_map);
699         isl_dim_free(dim);
700
701         return 0;
702 }
703
704 /* Add constraints to graph->lp that force validity for the given
705  * dependence from node i to node j.
706  * That is, add constraints that enforce
707  *
708  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
709  *
710  * for each (x,y) in R.
711  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
712  * of valid constraints for R and then plug in
713  * (c_j_0 - c_i_0, c_j_n^+ - c_j_n^- - (c_i_n^+ - c_i_n^-),
714  *  c_j_x^+ - c_j_x^- - (c_i_x^+ - c_i_x^-)),
715  * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
716  * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
717  *
718  * Actually, we do not construct constraints for the c_*_x themselves,
719  * but for the coefficients of c_*_x written as a linear combination
720  * of the columns in node->cmap.
721  */
722 static int add_inter_validity_constraints(struct isl_sched_graph *graph,
723         struct isl_sched_edge *edge)
724 {
725         unsigned total;
726         isl_map *map = isl_map_copy(edge->map);
727         isl_ctx *ctx = isl_map_get_ctx(map);
728         isl_dim *dim;
729         isl_dim_map *dim_map;
730         isl_basic_set *coef;
731         struct isl_sched_node *src = edge->src;
732         struct isl_sched_node *dst = edge->dst;
733
734         coef = inter_coefficients(graph, map);
735
736         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
737
738         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
739                     isl_dim_size(dim, isl_dim_set), isl_mat_copy(src->cmap));
740         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
741                     isl_dim_size(dim, isl_dim_set) + src->nvar,
742                     isl_mat_copy(dst->cmap));
743
744         total = isl_basic_set_total_dim(graph->lp);
745         dim_map = isl_dim_map_alloc(ctx, total);
746
747         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
748         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
749         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
750         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
751                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
752                           dst->nvar, -1);
753         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
754                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
755                           dst->nvar, 1);
756
757         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
758         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
759         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
760         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
761                           isl_dim_size(dim, isl_dim_set), 1,
762                           src->nvar, 1);
763         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
764                           isl_dim_size(dim, isl_dim_set), 1,
765                           src->nvar, -1);
766
767         edge->start = graph->lp->n_ineq;
768         graph->lp = isl_basic_set_extend_constraints(graph->lp,
769                         coef->n_eq, coef->n_ineq);
770         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
771                                                            coef, dim_map);
772         isl_dim_free(dim);
773         edge->end = graph->lp->n_ineq;
774
775         return 0;
776 }
777
778 /* Add constraints to graph->lp that bound the dependence distance for the given
779  * dependence from a node i to itself.
780  * If s = 1, we add the constraint
781  *
782  *      c_i_x (y - x) <= m_0 + m_n n
783  *
784  * or
785  *
786  *      -c_i_x (y - x) + m_0 + m_n n >= 0
787  *
788  * for each (x,y) in R.
789  * If s = -1, we add the constraint
790  *
791  *      -c_i_x (y - x) <= m_0 + m_n n
792  *
793  * or
794  *
795  *      c_i_x (y - x) + m_0 + m_n n >= 0
796  *
797  * for each (x,y) in R.
798  * We obtain general constraints on coefficients (c_0, c_n, c_x)
799  * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
800  * with each coefficient (except m_0) represented as a pair of non-negative
801  * coefficients.
802  *
803  * Actually, we do not construct constraints for the c_i_x themselves,
804  * but for the coefficients of c_i_x written as a linear combination
805  * of the columns in node->cmap.
806  */
807 static int add_intra_proximity_constraints(struct isl_sched_graph *graph,
808         struct isl_sched_edge *edge, int s)
809 {
810         unsigned total;
811         unsigned nparam;
812         isl_map *map = isl_map_copy(edge->map);
813         isl_ctx *ctx = isl_map_get_ctx(map);
814         isl_dim *dim;
815         isl_dim_map *dim_map;
816         isl_basic_set *coef;
817         struct isl_sched_node *node = edge->src;
818
819         coef = intra_coefficients(graph, map);
820
821         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
822
823         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
824                     isl_dim_size(dim, isl_dim_set), isl_mat_copy(node->cmap));
825
826         nparam = isl_dim_size(node->dim, isl_dim_param);
827         total = isl_basic_set_total_dim(graph->lp);
828         dim_map = isl_dim_map_alloc(ctx, total);
829         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
830         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
831         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
832         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
833                           isl_dim_size(dim, isl_dim_set), 1,
834                           node->nvar, s);
835         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
836                           isl_dim_size(dim, isl_dim_set), 1,
837                           node->nvar, -s);
838         graph->lp = isl_basic_set_extend_constraints(graph->lp,
839                         coef->n_eq, coef->n_ineq);
840         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
841                                                            coef, dim_map);
842         isl_dim_free(dim);
843
844         return 0;
845 }
846
847 /* Add constraints to graph->lp that bound the dependence distance for the given
848  * dependence from node i to node j.
849  * If s = 1, we add the constraint
850  *
851  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
852  *              <= m_0 + m_n n
853  *
854  * or
855  *
856  *      -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
857  *              m_0 + m_n n >= 0
858  *
859  * for each (x,y) in R.
860  * If s = -1, we add the constraint
861  *
862  *      -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
863  *              <= m_0 + m_n n
864  *
865  * or
866  *
867  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
868  *              m_0 + m_n n >= 0
869  *
870  * for each (x,y) in R.
871  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
872  * of valid constraints for R and then plug in
873  * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
874  *  -s*c_j_x+s*c_i_x)
875  * with each coefficient (except m_0, c_j_0 and c_i_0)
876  * represented as a pair of non-negative coefficients.
877  *
878  * Actually, we do not construct constraints for the c_*_x themselves,
879  * but for the coefficients of c_*_x written as a linear combination
880  * of the columns in node->cmap.
881  */
882 static int add_inter_proximity_constraints(struct isl_sched_graph *graph,
883         struct isl_sched_edge *edge, int s)
884 {
885         unsigned total;
886         unsigned nparam;
887         isl_map *map = isl_map_copy(edge->map);
888         isl_ctx *ctx = isl_map_get_ctx(map);
889         isl_dim *dim;
890         isl_dim_map *dim_map;
891         isl_basic_set *coef;
892         struct isl_sched_node *src = edge->src;
893         struct isl_sched_node *dst = edge->dst;
894
895         coef = inter_coefficients(graph, map);
896
897         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
898
899         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
900                     isl_dim_size(dim, isl_dim_set), isl_mat_copy(src->cmap));
901         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
902                     isl_dim_size(dim, isl_dim_set) + src->nvar,
903                     isl_mat_copy(dst->cmap));
904
905         nparam = isl_dim_size(src->dim, isl_dim_param);
906         total = isl_basic_set_total_dim(graph->lp);
907         dim_map = isl_dim_map_alloc(ctx, total);
908
909         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
910         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
911         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
912
913         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, -s);
914         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, s);
915         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, -s);
916         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
917                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
918                           dst->nvar, s);
919         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
920                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
921                           dst->nvar, -s);
922
923         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, s);
924         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, -s);
925         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, s);
926         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
927                           isl_dim_size(dim, isl_dim_set), 1,
928                           src->nvar, -s);
929         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
930                           isl_dim_size(dim, isl_dim_set), 1,
931                           src->nvar, s);
932
933         graph->lp = isl_basic_set_extend_constraints(graph->lp,
934                         coef->n_eq, coef->n_ineq);
935         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
936                                                            coef, dim_map);
937         isl_dim_free(dim);
938
939         return 0;
940 }
941
942 static int add_all_validity_constraints(struct isl_sched_graph *graph)
943 {
944         int i;
945
946         for (i = 0; i < graph->n_edge; ++i) {
947                 struct isl_sched_edge *edge= &graph->edge[i];
948                 if (!edge->validity)
949                         continue;
950                 if (edge->src != edge->dst)
951                         continue;
952                 if (add_intra_validity_constraints(graph, edge) < 0)
953                         return -1;
954         }
955
956         for (i = 0; i < graph->n_edge; ++i) {
957                 struct isl_sched_edge *edge = &graph->edge[i];
958                 if (!edge->validity)
959                         continue;
960                 if (edge->src == edge->dst)
961                         continue;
962                 if (add_inter_validity_constraints(graph, edge) < 0)
963                         return -1;
964         }
965
966         return 0;
967 }
968
969 /* Add constraints to graph->lp that bound the dependence distance
970  * for all dependence relations.
971  * If a given proximity dependence is identical to a validity
972  * dependence, then the dependence distance is already bounded
973  * from below (by zero), so we only need to bound the distance
974  * from above.
975  * Otherwise, we need to bound the distance both from above and from below.
976  */
977 static int add_all_proximity_constraints(struct isl_sched_graph *graph)
978 {
979         int i;
980
981         for (i = 0; i < graph->n_edge; ++i) {
982                 struct isl_sched_edge *edge= &graph->edge[i];
983                 if (!edge->proximity)
984                         continue;
985                 if (edge->src == edge->dst &&
986                     add_intra_proximity_constraints(graph, edge, 1) < 0)
987                         return -1;
988                 if (edge->src != edge->dst &&
989                     add_inter_proximity_constraints(graph, edge, 1) < 0)
990                         return -1;
991                 if (edge->validity)
992                         continue;
993                 if (edge->src == edge->dst &&
994                     add_intra_proximity_constraints(graph, edge, -1) < 0)
995                         return -1;
996                 if (edge->src != edge->dst &&
997                     add_inter_proximity_constraints(graph, edge, -1) < 0)
998                         return -1;
999         }
1000
1001         return 0;
1002 }
1003
1004 /* Compute a basis for the rows in the linear part of the schedule
1005  * and extend this basis to a full basis.  The remaining rows
1006  * can then be used to force linear independence from the rows
1007  * in the schedule.
1008  *
1009  * In particular, given the schedule rows S, we compute
1010  *
1011  *      S = H Q
1012  *
1013  * with H the Hermite normal form of S.  That is, all but the
1014  * first rank columns of Q are zero and so each row in S is
1015  * a linear combination of the first rank rows of Q.
1016  * The matrix Q is then transposed because we will write the
1017  * coefficients of the next schedule row as a column vector s
1018  * and express this s as a linear combination s = Q c of the
1019  * computed basis.
1020  */
1021 static int node_update_cmap(struct isl_sched_node *node)
1022 {
1023         isl_mat *H, *Q;
1024         int n_row = isl_mat_rows(node->sched);
1025
1026         H = isl_mat_sub_alloc(node->sched, 0, n_row,
1027                               1 + node->nparam, node->nvar);
1028
1029         H = isl_mat_left_hermite(H, 0, NULL, &Q);
1030         isl_mat_free(node->cmap);
1031         node->cmap = isl_mat_transpose(Q);
1032         node->rank = isl_mat_initial_non_zero_cols(H);
1033         isl_mat_free(H);
1034
1035         if (!node->cmap || node->rank < 0)
1036                 return -1;
1037         return 0;
1038 }
1039
1040 /* Count the number of equality and inequality constraints
1041  * that will be added.  If once is set, then we count
1042  * each edge exactly once.  Otherwise, we count as follows
1043  * validity             -> 1 (>= 0)
1044  * validity+proximity   -> 2 (>= 0 and upper bound)
1045  * proximity            -> 2 (lower and upper bound)
1046  */
1047 static int count_constraints(struct isl_sched_graph *graph,
1048         int *n_eq, int *n_ineq, int once)
1049 {
1050         int i;
1051         isl_basic_set *coef;
1052
1053         *n_eq = *n_ineq = 0;
1054         for (i = 0; i < graph->n_edge; ++i) {
1055                 struct isl_sched_edge *edge= &graph->edge[i];
1056                 isl_map *map = isl_map_copy(edge->map);
1057                 int f = once ? 1 : edge->proximity ? 2 : 1;
1058
1059                 if (edge->src == edge->dst)
1060                         coef = intra_coefficients(graph, map);
1061                 else
1062                         coef = inter_coefficients(graph, map);
1063                 if (!coef)
1064                         return -1;
1065                 *n_eq += f * coef->n_eq;
1066                 *n_ineq += f * coef->n_ineq;
1067                 isl_basic_set_free(coef);
1068         }
1069
1070         return 0;
1071 }
1072
1073 /* Construct an ILP problem for finding schedule coefficients
1074  * that result in non-negative, but small dependence distances
1075  * over all dependences.
1076  * In particular, the dependence distances over proximity edges
1077  * are bounded by m_0 + m_n n and we compute schedule coefficients
1078  * with small values (preferably zero) of m_n and m_0.
1079  *
1080  * All variables of the ILP are non-negative.  The actual coefficients
1081  * may be negative, so each coefficient is represented as the difference
1082  * of two non-negative variables.  The negative part always appears
1083  * immediately before the positive part.
1084  * Other than that, the variables have the following order
1085  *
1086  *      - sum of positive and negative parts of m_n coefficients
1087  *      - m_0
1088  *      - sum of positive and negative parts of all c_n coefficients
1089  *              (unconstrained when computing non-parametric schedules)
1090  *      - sum of positive and negative parts of all c_x coefficients
1091  *      - positive and negative parts of m_n coefficients
1092  *      - for each node
1093  *              - c_i_0
1094  *              - positive and negative parts of c_i_n (if parametric)
1095  *              - positive and negative parts of c_i_x
1096  *
1097  * The c_i_x are not represented directly, but through the columns of
1098  * node->cmap.  That is, the computed values are for variable t_i_x
1099  * such that c_i_x = Q t_i_x with Q equal to node->cmap.
1100  *
1101  * The constraints are those from the edges plus two or three equalities
1102  * to express the sums.
1103  */
1104 static int setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
1105 {
1106         int i, j;
1107         int k;
1108         unsigned nparam;
1109         unsigned total;
1110         isl_dim *dim;
1111         int parametric;
1112         int param_pos;
1113         int n_eq, n_ineq;
1114
1115         parametric = ctx->opt->schedule_parametric;
1116         nparam = isl_dim_size(graph->node[0].dim, isl_dim_param);
1117         param_pos = 4;
1118         total = param_pos + 2 * nparam;
1119         for (i = 0; i < graph->n; ++i) {
1120                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
1121                 if (node_update_cmap(node) < 0)
1122                         return -1;
1123                 node->start = total;
1124                 total += 1 + 2 * (node->nparam + node->nvar);
1125         }
1126
1127         if (count_constraints(graph, &n_eq, &n_ineq, 0) < 0)
1128                 return -1;
1129
1130         dim = isl_dim_set_alloc(ctx, 0, total);
1131         isl_basic_set_free(graph->lp);
1132         n_eq += 2 + parametric;
1133         graph->lp = isl_basic_set_alloc_dim(dim, 0, n_eq, n_ineq);
1134
1135         k = isl_basic_set_alloc_equality(graph->lp);
1136         if (k < 0)
1137                 return -1;
1138         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1139         isl_int_set_si(graph->lp->eq[k][1], -1);
1140         for (i = 0; i < 2 * nparam; ++i)
1141                 isl_int_set_si(graph->lp->eq[k][1 + param_pos + i], 1);
1142
1143         if (parametric) {
1144                 k = isl_basic_set_alloc_equality(graph->lp);
1145                 if (k < 0)
1146                         return -1;
1147                 isl_seq_clr(graph->lp->eq[k], 1 +  total);
1148                 isl_int_set_si(graph->lp->eq[k][3], -1);
1149                 for (i = 0; i < graph->n; ++i) {
1150                         int pos = 1 + graph->node[i].start + 1;
1151
1152                         for (j = 0; j < 2 * graph->node[i].nparam; ++j)
1153                                 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1154                 }
1155         }
1156
1157         k = isl_basic_set_alloc_equality(graph->lp);
1158         if (k < 0)
1159                 return -1;
1160         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1161         isl_int_set_si(graph->lp->eq[k][4], -1);
1162         for (i = 0; i < graph->n; ++i) {
1163                 struct isl_sched_node *node = &graph->node[i];
1164                 int pos = 1 + node->start + 1 + 2 * node->nparam;
1165
1166                 for (j = 0; j < 2 * node->nvar; ++j)
1167                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1168         }
1169
1170         if (add_all_validity_constraints(graph) < 0)
1171                 return -1;
1172         if (add_all_proximity_constraints(graph) < 0)
1173                 return -1;
1174
1175         return 0;
1176 }
1177
1178 /* Analyze the conflicting constraint found by
1179  * isl_tab_basic_set_non_trivial_lexmin.  If it corresponds to the validity
1180  * constraint of one of the edges between distinct nodes, living, moreover
1181  * in distinct SCCs, then record the source and sink SCC as this may
1182  * be a good place to cut between SCCs.
1183  */
1184 static int check_conflict(int con, void *user)
1185 {
1186         int i;
1187         struct isl_sched_graph *graph = user;
1188
1189         if (graph->src_scc >= 0)
1190                 return 0;
1191
1192         con -= graph->lp->n_eq;
1193
1194         if (con >= graph->lp->n_ineq)
1195                 return 0;
1196
1197         for (i = 0; i < graph->n_edge; ++i) {
1198                 if (!graph->edge[i].validity)
1199                         continue;
1200                 if (graph->edge[i].src == graph->edge[i].dst)
1201                         continue;
1202                 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
1203                         continue;
1204                 if (graph->edge[i].start > con)
1205                         continue;
1206                 if (graph->edge[i].end <= con)
1207                         continue;
1208                 graph->src_scc = graph->edge[i].src->scc;
1209                 graph->dst_scc = graph->edge[i].dst->scc;
1210         }
1211
1212         return 0;
1213 }
1214
1215 /* Check whether the next schedule row of the given node needs to be
1216  * non-trivial.  Lower-dimensional domains may have some trivial rows,
1217  * but as soon as the number of remaining required non-trivial rows
1218  * is as large as the number or remaining rows to be computed,
1219  * all remaining rows need to be non-trivial.
1220  */
1221 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
1222 {
1223         return node->nvar - node->rank >= graph->maxvar - graph->n_row;
1224 }
1225
1226 /* Solve the ILP problem constructed in setup_lp.
1227  * For each node such that all the remaining rows of its schedule
1228  * need to be non-trivial, we construct a non-triviality region.
1229  * This region imposes that the next row is independent of previous rows.
1230  * In particular the coefficients c_i_x are represented by t_i_x
1231  * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
1232  * its first columns span the rows of the previously computed part
1233  * of the schedule.  The non-triviality region enforces that at least
1234  * one of the remaining components of t_i_x is non-zero, i.e.,
1235  * that the new schedule row depends on at least one of the remaining
1236  * columns of Q.
1237  */
1238 static __isl_give isl_vec *solve_lp(struct isl_sched_graph *graph)
1239 {
1240         int i;
1241         isl_vec *sol;
1242         isl_basic_set *lp;
1243
1244         for (i = 0; i < graph->n; ++i) {
1245                 struct isl_sched_node *node = &graph->node[i];
1246                 int skip = node->rank;
1247                 graph->region[i].pos = node->start + 1 + 2*(node->nparam+skip);
1248                 if (needs_row(graph, node))
1249                         graph->region[i].len = 2 * (node->nvar - skip);
1250                 else
1251                         graph->region[i].len = 0;
1252         }
1253         lp = isl_basic_set_copy(graph->lp);
1254         sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
1255                                        graph->region, &check_conflict, graph);
1256         return sol;
1257 }
1258
1259 /* Update the schedules of all nodes based on the given solution
1260  * of the LP problem.
1261  * The new row is added to the current band.
1262  * All possibly negative coefficients are encoded as a difference
1263  * of two non-negative variables, so we need to perform the subtraction
1264  * here.  Moreover, if use_cmap is set, then the solution does
1265  * not refer to the actual coefficients c_i_x, but instead to variables
1266  * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
1267  * In this case, we then also need to perform this multiplication
1268  * to obtain the values of c_i_x.
1269  *
1270  * If check_parallel is set, then the first two coordinates of sol are
1271  * assumed to correspond to the dependence distance.  If these two
1272  * coordinates are zero, then the corresponding scheduling dimension
1273  * is marked as being parallel.
1274  */
1275 static int update_schedule(struct isl_sched_graph *graph,
1276         __isl_take isl_vec *sol, int use_cmap, int check_parallel)
1277 {
1278         int i, j;
1279         int parallel = 0;
1280         isl_vec *csol = NULL;
1281
1282         if (!sol)
1283                 goto error;
1284         if (sol->size == 0)
1285                 isl_die(sol->ctx, isl_error_internal,
1286                         "no solution found", goto error);
1287
1288         if (check_parallel)
1289                 parallel = isl_int_is_zero(sol->el[1]) &&
1290                            isl_int_is_zero(sol->el[2]);
1291
1292         for (i = 0; i < graph->n; ++i) {
1293                 struct isl_sched_node *node = &graph->node[i];
1294                 int pos = node->start;
1295                 int row = isl_mat_rows(node->sched);
1296
1297                 isl_vec_free(csol);
1298                 csol = isl_vec_alloc(sol->ctx, node->nvar);
1299                 if (!csol)
1300                         goto error;
1301
1302                 isl_map_free(node->sched_map);
1303                 node->sched_map = NULL;
1304                 node->sched = isl_mat_add_rows(node->sched, 1);
1305                 if (!node->sched)
1306                         goto error;
1307                 node->sched = isl_mat_set_element(node->sched, row, 0,
1308                                                   sol->el[1 + pos]);
1309                 for (j = 0; j < node->nparam + node->nvar; ++j)
1310                         isl_int_sub(sol->el[1 + pos + 1 + 2 * j + 1],
1311                                     sol->el[1 + pos + 1 + 2 * j + 1],
1312                                     sol->el[1 + pos + 1 + 2 * j]);
1313                 for (j = 0; j < node->nparam; ++j)
1314                         node->sched = isl_mat_set_element(node->sched,
1315                                         row, 1 + j, sol->el[1+pos+1+2*j+1]);
1316                 for (j = 0; j < node->nvar; ++j)
1317                         isl_int_set(csol->el[j],
1318                                     sol->el[1+pos+1+2*(node->nparam+j)+1]);
1319                 if (use_cmap)
1320                         csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
1321                                                    csol);
1322                 if (!csol)
1323                         goto error;
1324                 for (j = 0; j < node->nvar; ++j)
1325                         node->sched = isl_mat_set_element(node->sched,
1326                                         row, 1 + node->nparam + j, csol->el[j]);
1327                 node->band[graph->n_total_row] = graph->n_band;
1328                 node->parallel[graph->n_total_row] = parallel;
1329         }
1330         isl_vec_free(sol);
1331         isl_vec_free(csol);
1332
1333         graph->n_row++;
1334         graph->n_total_row++;
1335
1336         return 0;
1337 error:
1338         isl_vec_free(sol);
1339         isl_vec_free(csol);
1340         return -1;
1341 }
1342
1343 /* Convert node->sched into a map and return this map.
1344  * We simply add equality constraints that express each output variable
1345  * as the affine combination of parameters and input variables specified
1346  * by the schedule matrix.
1347  *
1348  * The result is cached in node->sched_map, which needs to be released
1349  * whenever node->sched is updated.
1350  */
1351 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
1352 {
1353         int i, j;
1354         isl_dim *dim;
1355         isl_basic_map *bmap;
1356         isl_constraint *c;
1357         int nrow, ncol;
1358         isl_int v;
1359
1360         if (node->sched_map)
1361                 return isl_map_copy(node->sched_map);
1362
1363         nrow = isl_mat_rows(node->sched);
1364         ncol = isl_mat_cols(node->sched) - 1;
1365         dim = isl_dim_from_domain(isl_dim_copy(node->dim));
1366         dim = isl_dim_add(dim, isl_dim_out, nrow);
1367         bmap = isl_basic_map_universe(isl_dim_copy(dim));
1368
1369         isl_int_init(v);
1370
1371         for (i = 0; i < nrow; ++i) {
1372                 c = isl_equality_alloc(isl_dim_copy(dim));
1373                 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1374                 isl_mat_get_element(node->sched, i, 0, &v);
1375                 isl_constraint_set_constant(c, v);
1376                 for (j = 0; j < node->nparam; ++j) {
1377                         isl_mat_get_element(node->sched, i, 1 + j, &v);
1378                         isl_constraint_set_coefficient(c, isl_dim_param, j, v);
1379                 }
1380                 for (j = 0; j < node->nvar; ++j) {
1381                         isl_mat_get_element(node->sched,
1382                                             i, 1 + node->nparam + j, &v);
1383                         isl_constraint_set_coefficient(c, isl_dim_in, j, v);
1384                 }
1385                 bmap = isl_basic_map_add_constraint(bmap, c);
1386         }
1387
1388         isl_int_clear(v);
1389
1390         isl_dim_free(dim);
1391
1392         node->sched_map = isl_map_from_basic_map(bmap);
1393         return isl_map_copy(node->sched_map);
1394 }
1395
1396 /* Update the given dependence relation based on the current schedule.
1397  * That is, intersect the dependence relation with a map expressing
1398  * that source and sink are executed within the same iteration of
1399  * the current schedule.
1400  * This is not the most efficient way, but this shouldn't be a critical
1401  * operation.
1402  */
1403 static __isl_give isl_map *specialize(__isl_take isl_map *map,
1404         struct isl_sched_node *src, struct isl_sched_node *dst)
1405 {
1406         isl_map *src_sched, *dst_sched, *id;
1407
1408         src_sched = node_extract_schedule(src);
1409         dst_sched = node_extract_schedule(dst);
1410         id = isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
1411         return isl_map_intersect(map, id);
1412 }
1413
1414 /* Update the dependence relations of all edges based on the current schedule.
1415  * If a dependence is carried completely by the current schedule, then
1416  * it is removed and edge_table is updated accordingly.
1417  */
1418 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
1419 {
1420         int i;
1421         int reset_table = 0;
1422
1423         for (i = graph->n_edge - 1; i >= 0; --i) {
1424                 struct isl_sched_edge *edge = &graph->edge[i];
1425                 edge->map = specialize(edge->map, edge->src, edge->dst);
1426                 if (!edge->map)
1427                         return -1;
1428
1429                 if (isl_map_plain_is_empty(edge->map)) {
1430                         reset_table = 1;
1431                         isl_map_free(edge->map);
1432                         if (i != graph->n_edge - 1)
1433                                 graph->edge[i] = graph->edge[graph->n_edge - 1];
1434                         graph->n_edge--;
1435                 }
1436         }
1437
1438         if (reset_table) {
1439                 isl_hash_table_free(ctx, graph->edge_table);
1440                 graph->edge_table = NULL;
1441                 return graph_init_edge_table(ctx, graph);
1442         }
1443
1444         return 0;
1445 }
1446
1447 static void next_band(struct isl_sched_graph *graph)
1448 {
1449         graph->band_start = graph->n_total_row;
1450         graph->n_band++;
1451 }
1452
1453 /* Topologically sort statements mapped to same schedule iteration
1454  * and add a row to the schedule corresponding to this order.
1455  */
1456 static int sort_statements(isl_ctx *ctx, struct isl_sched_graph *graph)
1457 {
1458         int i, j;
1459
1460         if (graph->n <= 1)
1461                 return 0;
1462
1463         if (update_edges(ctx, graph) < 0)
1464                 return -1;
1465
1466         if (graph->n_edge == 0)
1467                 return 0;
1468
1469         if (detect_sccs(graph) < 0)
1470                 return -1;
1471
1472         for (i = 0; i < graph->n; ++i) {
1473                 struct isl_sched_node *node = &graph->node[i];
1474                 int row = isl_mat_rows(node->sched);
1475                 int cols = isl_mat_cols(node->sched);
1476
1477                 isl_map_free(node->sched_map);
1478                 node->sched_map = NULL;
1479                 node->sched = isl_mat_add_rows(node->sched, 1);
1480                 if (!node->sched)
1481                         return -1;
1482                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
1483                                                      node->scc);
1484                 for (j = 1; j < cols; ++j)
1485                         node->sched = isl_mat_set_element_si(node->sched,
1486                                                              row, j, 0);
1487                 node->band[graph->n_total_row] = graph->n_band;
1488         }
1489
1490         graph->n_total_row++;
1491         next_band(graph);
1492
1493         return 0;
1494 }
1495
1496 /* Construct an isl_schedule based on the computed schedule stored
1497  * in graph and with parameters specified by dim.
1498  */
1499 static __isl_give isl_schedule *extract_schedule(struct isl_sched_graph *graph,
1500         __isl_take isl_dim *dim)
1501 {
1502         int i;
1503         isl_ctx *ctx;
1504         isl_schedule *sched = NULL;
1505                 
1506         if (!dim)
1507                 return NULL;
1508
1509         ctx = isl_dim_get_ctx(dim);
1510         sched = isl_calloc(ctx, struct isl_schedule,
1511                            sizeof(struct isl_schedule) +
1512                            (graph->n - 1) * sizeof(struct isl_schedule_node));
1513         if (!sched)
1514                 goto error;
1515
1516         sched->ref = 1;
1517         sched->n = graph->n;
1518         sched->n_band = graph->n_band;
1519         sched->n_total_row = graph->n_total_row;
1520
1521         for (i = 0; i < sched->n; ++i) {
1522                 int r, b;
1523                 int *band_end, *band_id, *parallel;
1524
1525                 band_end = isl_alloc_array(ctx, int, graph->n_band);
1526                 band_id = isl_alloc_array(ctx, int, graph->n_band);
1527                 parallel = isl_alloc_array(ctx, int, graph->n_total_row);
1528                 sched->node[i].sched = node_extract_schedule(&graph->node[i]);
1529                 sched->node[i].band_end = band_end;
1530                 sched->node[i].band_id = band_id;
1531                 sched->node[i].parallel = parallel;
1532                 if (!band_end || !band_id || !parallel)
1533                         goto error;
1534
1535                 for (r = 0; r < graph->n_total_row; ++r)
1536                         parallel[r] = graph->node[i].parallel[r];
1537                 for (r = b = 0; r < graph->n_total_row; ++r) {
1538                         if (graph->node[i].band[r] == b)
1539                                 continue;
1540                         band_end[b++] = r;
1541                         if (graph->node[i].band[r] == -1)
1542                                 break;
1543                 }
1544                 if (r == graph->n_total_row)
1545                         band_end[b++] = r;
1546                 sched->node[i].n_band = b;
1547                 for (--b; b >= 0; --b)
1548                         band_id[b] = graph->node[i].band_id[b];
1549         }
1550
1551         sched->dim = dim;
1552
1553         return sched;
1554 error:
1555         isl_dim_free(dim);
1556         isl_schedule_free(sched);
1557         return NULL;
1558 }
1559
1560 /* Copy nodes that satisfy node_pred from the src dependence graph
1561  * to the dst dependence graph.
1562  */
1563 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
1564         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1565 {
1566         int i;
1567
1568         dst->n = 0;
1569         for (i = 0; i < src->n; ++i) {
1570                 if (!node_pred(&src->node[i], data))
1571                         continue;
1572                 dst->node[dst->n].dim = isl_dim_copy(src->node[i].dim);
1573                 dst->node[dst->n].nvar = src->node[i].nvar;
1574                 dst->node[dst->n].nparam = src->node[i].nparam;
1575                 dst->node[dst->n].sched = isl_mat_copy(src->node[i].sched);
1576                 dst->node[dst->n].sched_map =
1577                         isl_map_copy(src->node[i].sched_map);
1578                 dst->node[dst->n].band = src->node[i].band;
1579                 dst->node[dst->n].band_id = src->node[i].band_id;
1580                 dst->node[dst->n].parallel = src->node[i].parallel;
1581                 dst->n++;
1582         }
1583
1584         return 0;
1585 }
1586
1587 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
1588  * to the dst dependence graph.
1589  */
1590 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
1591         struct isl_sched_graph *src,
1592         int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
1593 {
1594         int i;
1595
1596         dst->n_edge = 0;
1597         for (i = 0; i < src->n_edge; ++i) {
1598                 struct isl_sched_edge *edge = &src->edge[i];
1599                 isl_map *map;
1600
1601                 if (!edge_pred(edge, data))
1602                         continue;
1603
1604                 if (isl_map_plain_is_empty(edge->map))
1605                         continue;
1606
1607                 map = isl_map_copy(edge->map);
1608
1609                 dst->edge[dst->n_edge].src =
1610                         graph_find_node(ctx, dst, edge->src->dim);
1611                 dst->edge[dst->n_edge].dst =
1612                         graph_find_node(ctx, dst, edge->dst->dim);
1613                 dst->edge[dst->n_edge].map = map;
1614                 dst->edge[dst->n_edge].validity = edge->validity;
1615                 dst->edge[dst->n_edge].proximity = edge->proximity;
1616                 dst->n_edge++;
1617         }
1618
1619         return 0;
1620 }
1621
1622 /* Given a "src" dependence graph that contains the nodes from "dst"
1623  * that satisfy node_pred, copy the schedule computed in "src"
1624  * for those nodes back to "dst".
1625  */
1626 static int copy_schedule(struct isl_sched_graph *dst,
1627         struct isl_sched_graph *src,
1628         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1629 {
1630         int i;
1631
1632         src->n = 0;
1633         for (i = 0; i < dst->n; ++i) {
1634                 if (!node_pred(&dst->node[i], data))
1635                         continue;
1636                 isl_mat_free(dst->node[i].sched);
1637                 isl_map_free(dst->node[i].sched_map);
1638                 dst->node[i].sched = isl_mat_copy(src->node[src->n].sched);
1639                 dst->node[i].sched_map =
1640                         isl_map_copy(src->node[src->n].sched_map);
1641                 src->n++;
1642         }
1643
1644         dst->n_total_row = src->n_total_row;
1645         dst->n_band = src->n_band;
1646
1647         return 0;
1648 }
1649
1650 /* Compute the maximal number of variables over all nodes.
1651  * This is the maximal number of linearly independent schedule
1652  * rows that we need to compute.
1653  * Just in case we end up in a part of the dependence graph
1654  * with only lower-dimensional domains, we make sure we will
1655  * compute the required amount of extra linearly independent rows.
1656  */
1657 static int compute_maxvar(struct isl_sched_graph *graph)
1658 {
1659         int i;
1660
1661         graph->maxvar = 0;
1662         for (i = 0; i < graph->n; ++i) {
1663                 struct isl_sched_node *node = &graph->node[i];
1664                 int nvar;
1665
1666                 if (node_update_cmap(node) < 0)
1667                         return -1;
1668                 nvar = node->nvar + graph->n_row - node->rank;
1669                 if (nvar > graph->maxvar)
1670                         graph->maxvar = nvar;
1671         }
1672
1673         return 0;
1674 }
1675
1676 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph);
1677 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph);
1678
1679 /* Compute a schedule for a subgraph of "graph".  In particular, for
1680  * the graph composed of nodes that satisfy node_pred and edges that
1681  * that satisfy edge_pred.  The caller should precompute the number
1682  * of nodes and edges that satisfy these predicates and pass them along
1683  * as "n" and "n_edge".
1684  * If the subgraph is known to consist of a single component, then wcc should
1685  * be set and then we call compute_schedule_wcc on the constructed subgraph.
1686  * Otherwise, we call compute_schedule, which will check whether the subgraph
1687  * is connected.
1688  */
1689 static int compute_sub_schedule(isl_ctx *ctx,
1690         struct isl_sched_graph *graph, int n, int n_edge,
1691         int (*node_pred)(struct isl_sched_node *node, int data),
1692         int (*edge_pred)(struct isl_sched_edge *edge, int data),
1693         int data, int wcc)
1694 {
1695         struct isl_sched_graph split = { 0 };
1696
1697         if (graph_alloc(ctx, &split, n, n_edge) < 0)
1698                 goto error;
1699         if (copy_nodes(&split, graph, node_pred, data) < 0)
1700                 goto error;
1701         if (graph_init_table(ctx, &split) < 0)
1702                 goto error;
1703         if (copy_edges(ctx, &split, graph, edge_pred, data) < 0)
1704                 goto error;
1705         if (graph_init_edge_table(ctx, &split) < 0)
1706                 goto error;
1707         split.n_row = graph->n_row;
1708         split.n_total_row = graph->n_total_row;
1709         split.n_band = graph->n_band;
1710         split.band_start = graph->band_start;
1711
1712         if (wcc && compute_schedule_wcc(ctx, &split) < 0)
1713                 goto error;
1714         if (!wcc && compute_schedule(ctx, &split) < 0)
1715                 goto error;
1716
1717         copy_schedule(graph, &split, node_pred, data);
1718
1719         graph_free(ctx, &split);
1720         return 0;
1721 error:
1722         graph_free(ctx, &split);
1723         return -1;
1724 }
1725
1726 static int node_scc_exactly(struct isl_sched_node *node, int scc)
1727 {
1728         return node->scc == scc;
1729 }
1730
1731 static int node_scc_at_most(struct isl_sched_node *node, int scc)
1732 {
1733         return node->scc <= scc;
1734 }
1735
1736 static int node_scc_at_least(struct isl_sched_node *node, int scc)
1737 {
1738         return node->scc >= scc;
1739 }
1740
1741 static int edge_src_scc_exactly(struct isl_sched_edge *edge, int scc)
1742 {
1743         return edge->src->scc == scc;
1744 }
1745
1746 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
1747 {
1748         return edge->dst->scc <= scc;
1749 }
1750
1751 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
1752 {
1753         return edge->src->scc >= scc;
1754 }
1755
1756 /* Pad the schedules of all nodes with zero rows such that in the end
1757  * they all have graph->n_total_row rows.
1758  * The extra rows don't belong to any band, so they get assigned band number -1.
1759  */
1760 static int pad_schedule(struct isl_sched_graph *graph)
1761 {
1762         int i, j;
1763
1764         for (i = 0; i < graph->n; ++i) {
1765                 struct isl_sched_node *node = &graph->node[i];
1766                 int row = isl_mat_rows(node->sched);
1767                 if (graph->n_total_row > row) {
1768                         isl_map_free(node->sched_map);
1769                         node->sched_map = NULL;
1770                 }
1771                 node->sched = isl_mat_add_zero_rows(node->sched,
1772                                                     graph->n_total_row - row);
1773                 if (!node->sched)
1774                         return -1;
1775                 for (j = row; j < graph->n_total_row; ++j)
1776                         node->band[j] = -1;
1777         }
1778
1779         return 0;
1780 }
1781
1782 /* Split the current graph into two parts and compute a schedule for each
1783  * part individually.  In particular, one part consists of all SCCs up
1784  * to and including graph->src_scc, while the other part contains the other
1785  * SCCS.
1786  *
1787  * The split is enforced in the schedule by constant rows with two different
1788  * values (0 and 1).  These constant rows replace the previously computed rows
1789  * in the current band.
1790  * It would be possible to reuse them as the first rows in the next
1791  * band, but recomputing them may result in better rows as we are looking
1792  * at a smaller part of the dependence graph.
1793  *
1794  * The band_id of the second group is set to n, where n is the number
1795  * of nodes in the first group.  This ensures that the band_ids over
1796  * the two groups remain disjoint, even if either or both of the two
1797  * groups contain independent components.
1798  */
1799 static int compute_split_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
1800 {
1801         int i, j, n, e1, e2;
1802         int n_total_row, orig_total_row;
1803         int n_band, orig_band;
1804         int drop;
1805
1806         drop = graph->n_total_row - graph->band_start;
1807         graph->n_total_row -= drop;
1808         graph->n_row -= drop;
1809
1810         n = 0;
1811         for (i = 0; i < graph->n; ++i) {
1812                 struct isl_sched_node *node = &graph->node[i];
1813                 int row = isl_mat_rows(node->sched) - drop;
1814                 int cols = isl_mat_cols(node->sched);
1815                 int before = node->scc <= graph->src_scc;
1816
1817                 if (before)
1818                         n++;
1819
1820                 isl_map_free(node->sched_map);
1821                 node->sched_map = NULL;
1822                 node->sched = isl_mat_drop_rows(node->sched,
1823                                                 graph->band_start, drop);
1824                 node->sched = isl_mat_add_rows(node->sched, 1);
1825                 if (!node->sched)
1826                         return -1;
1827                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
1828                                                      !before);
1829                 for (j = 1; j < cols; ++j)
1830                         node->sched = isl_mat_set_element_si(node->sched,
1831                                                              row, j, 0);
1832                 node->band[graph->n_total_row] = graph->n_band;
1833         }
1834
1835         e1 = e2 = 0;
1836         for (i = 0; i < graph->n_edge; ++i) {
1837                 if (graph->edge[i].dst->scc <= graph->src_scc)
1838                         e1++;
1839                 if (graph->edge[i].src->scc > graph->src_scc)
1840                         e2++;
1841         }
1842
1843         graph->n_total_row++;
1844         next_band(graph);
1845
1846         for (i = 0; i < graph->n; ++i) {
1847                 struct isl_sched_node *node = &graph->node[i];
1848                 if (node->scc > graph->src_scc)
1849                         node->band_id[graph->n_band] = n;
1850         }
1851
1852         orig_total_row = graph->n_total_row;
1853         orig_band = graph->n_band;
1854         if (compute_sub_schedule(ctx, graph, n, e1,
1855                                 &node_scc_at_most, &edge_dst_scc_at_most,
1856                                 graph->src_scc, 0) < 0)
1857                 return -1;
1858         n_total_row = graph->n_total_row;
1859         graph->n_total_row = orig_total_row;
1860         n_band = graph->n_band;
1861         graph->n_band = orig_band;
1862         if (compute_sub_schedule(ctx, graph, graph->n - n, e2,
1863                                 &node_scc_at_least, &edge_src_scc_at_least,
1864                                 graph->src_scc + 1, 0) < 0)
1865                 return -1;
1866         if (n_total_row > graph->n_total_row)
1867                 graph->n_total_row = n_total_row;
1868         if (n_band > graph->n_band)
1869                 graph->n_band = n_band;
1870
1871         return pad_schedule(graph);
1872 }
1873
1874 /* Compute the next band of the schedule after updating the dependence
1875  * relations based on the the current schedule.
1876  */
1877 static int compute_next_band(isl_ctx *ctx, struct isl_sched_graph *graph)
1878 {
1879         if (update_edges(ctx, graph) < 0)
1880                 return -1;
1881         next_band(graph);
1882                 
1883         return compute_schedule(ctx, graph);
1884 }
1885
1886 /* Add constraints to graph->lp that force the dependence of edge i
1887  * to be respected and attempt to carry it, where edge i is one from
1888  * a node j to itself.
1889  * That is, add constraints that enforce
1890  *
1891  *      (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
1892  *      = c_j_x (y - x) >= e_i
1893  *
1894  * for each (x,y) in R.
1895  * We obtain general constraints on coefficients (c_0, c_n, c_x)
1896  * of valid constraints for (y - x) and then plug in (-e_i, 0, c_j_x),
1897  * with each coefficient in c_j_x represented as a pair of non-negative
1898  * coefficients.
1899  */
1900 static int add_intra_constraints(struct isl_sched_graph *graph, int i)
1901 {
1902         unsigned total;
1903         struct isl_sched_edge *edge= &graph->edge[i];
1904         isl_map *map = isl_map_copy(edge->map);
1905         isl_ctx *ctx = isl_map_get_ctx(map);
1906         isl_dim *dim;
1907         isl_dim_map *dim_map;
1908         isl_basic_set *coef;
1909         struct isl_sched_node *node = edge->src;
1910
1911         coef = intra_coefficients(graph, map);
1912
1913         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
1914
1915         total = isl_basic_set_total_dim(graph->lp);
1916         dim_map = isl_dim_map_alloc(ctx, total);
1917         isl_dim_map_range(dim_map, 3 + i, 0, 0, 0, 1, -1);
1918         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
1919                           isl_dim_size(dim, isl_dim_set), 1,
1920                           node->nvar, -1);
1921         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
1922                           isl_dim_size(dim, isl_dim_set), 1,
1923                           node->nvar, 1);
1924         graph->lp = isl_basic_set_extend_constraints(graph->lp,
1925                         coef->n_eq, coef->n_ineq);
1926         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1927                                                            coef, dim_map);
1928         isl_dim_free(dim);
1929
1930         return 0;
1931 }
1932
1933 /* Add constraints to graph->lp that force the dependence of edge i
1934  * to be respected and attempt to carry it, where edge i is one from
1935  * node j to node k.
1936  * That is, add constraints that enforce
1937  *
1938  *      (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
1939  *
1940  * for each (x,y) in R.
1941  * We obtain general constraints on coefficients (c_0, c_n, c_x)
1942  * of valid constraints for R and then plug in
1943  * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, c_k_x - c_j_x)
1944  * with each coefficient (except e_i, c_k_0 and c_j_0)
1945  * represented as a pair of non-negative coefficients.
1946  */
1947 static int add_inter_constraints(struct isl_sched_graph *graph, int i)
1948 {
1949         unsigned total;
1950         struct isl_sched_edge *edge= &graph->edge[i];
1951         isl_map *map = isl_map_copy(edge->map);
1952         isl_ctx *ctx = isl_map_get_ctx(map);
1953         isl_dim *dim;
1954         isl_dim_map *dim_map;
1955         isl_basic_set *coef;
1956         struct isl_sched_node *src = edge->src;
1957         struct isl_sched_node *dst = edge->dst;
1958
1959         coef = inter_coefficients(graph, map);
1960
1961         dim = isl_dim_domain(isl_dim_unwrap(isl_basic_set_get_dim(coef)));
1962
1963         total = isl_basic_set_total_dim(graph->lp);
1964         dim_map = isl_dim_map_alloc(ctx, total);
1965
1966         isl_dim_map_range(dim_map, 3 + i, 0, 0, 0, 1, -1);
1967
1968         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
1969         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
1970         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
1971         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
1972                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
1973                           dst->nvar, -1);
1974         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
1975                           isl_dim_size(dim, isl_dim_set) + src->nvar, 1,
1976                           dst->nvar, 1);
1977
1978         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
1979         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
1980         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
1981         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
1982                           isl_dim_size(dim, isl_dim_set), 1,
1983                           src->nvar, 1);
1984         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
1985                           isl_dim_size(dim, isl_dim_set), 1,
1986                           src->nvar, -1);
1987
1988         graph->lp = isl_basic_set_extend_constraints(graph->lp,
1989                         coef->n_eq, coef->n_ineq);
1990         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1991                                                            coef, dim_map);
1992         isl_dim_free(dim);
1993
1994         return 0;
1995 }
1996
1997 /* Add constraints to graph->lp that force all dependence
1998  * to be respected and attempt to carry it.
1999  */
2000 static int add_all_constraints(struct isl_sched_graph *graph)
2001 {
2002         int i;
2003
2004         for (i = 0; i < graph->n_edge; ++i) {
2005                 struct isl_sched_edge *edge= &graph->edge[i];
2006                 if (edge->src == edge->dst &&
2007                     add_intra_constraints(graph, i) < 0)
2008                         return -1;
2009                 if (edge->src != edge->dst &&
2010                     add_inter_constraints(graph, i) < 0)
2011                         return -1;
2012         }
2013
2014         return 0;
2015 }
2016
2017 /* Construct an LP problem for finding schedule coefficients
2018  * such that the schedule carries as many dependences as possible.
2019  * In particular, for each dependence i, we bound the dependence distance
2020  * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
2021  * of all e_i's.  Dependence with e_i = 0 in the solution are simply
2022  * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
2023  *
2024  * All variables of the LP are non-negative.  The actual coefficients
2025  * may be negative, so each coefficient is represented as the difference
2026  * of two non-negative variables.  The negative part always appears
2027  * immediately before the positive part.
2028  * Other than that, the variables have the following order
2029  *
2030  *      - sum of (1 - e_i) over all edges
2031  *      - sum of positive and negative parts of all c_n coefficients
2032  *              (unconstrained when computing non-parametric schedules)
2033  *      - sum of positive and negative parts of all c_x coefficients
2034  *      - for each edge
2035  *              - e_i
2036  *      - for each node
2037  *              - c_i_0
2038  *              - positive and negative parts of c_i_n (if parametric)
2039  *              - positive and negative parts of c_i_x
2040  *
2041  * The constraints are those from the edges plus three equalities
2042  * to express the sums and n_edge inequalities to express e_i <= 1.
2043  */
2044 static int setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2045 {
2046         int i, j;
2047         int k;
2048         isl_dim *dim;
2049         unsigned total;
2050         int n_eq, n_ineq;
2051
2052         total = 3 + graph->n_edge;
2053         for (i = 0; i < graph->n; ++i) {
2054                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2055                 node->start = total;
2056                 total += 1 + 2 * (node->nparam + node->nvar);
2057         }
2058
2059         if (count_constraints(graph, &n_eq, &n_ineq, 1) < 0)
2060                 return -1;
2061
2062         dim = isl_dim_set_alloc(ctx, 0, total);
2063         isl_basic_set_free(graph->lp);
2064         n_eq += 3;
2065         n_ineq += graph->n_edge;
2066         graph->lp = isl_basic_set_alloc_dim(dim, 0, n_eq, n_ineq);
2067         graph->lp = isl_basic_set_set_rational(graph->lp);
2068
2069         k = isl_basic_set_alloc_equality(graph->lp);
2070         if (k < 0)
2071                 return -1;
2072         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2073         isl_int_set_si(graph->lp->eq[k][0], -graph->n_edge);
2074         isl_int_set_si(graph->lp->eq[k][1], 1);
2075         for (i = 0; i < graph->n_edge; ++i)
2076                 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
2077
2078         k = isl_basic_set_alloc_equality(graph->lp);
2079         if (k < 0)
2080                 return -1;
2081         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2082         isl_int_set_si(graph->lp->eq[k][2], -1);
2083         for (i = 0; i < graph->n; ++i) {
2084                 int pos = 1 + graph->node[i].start + 1;
2085
2086                 for (j = 0; j < 2 * graph->node[i].nparam; ++j)
2087                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2088         }
2089
2090         k = isl_basic_set_alloc_equality(graph->lp);
2091         if (k < 0)
2092                 return -1;
2093         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2094         isl_int_set_si(graph->lp->eq[k][3], -1);
2095         for (i = 0; i < graph->n; ++i) {
2096                 struct isl_sched_node *node = &graph->node[i];
2097                 int pos = 1 + node->start + 1 + 2 * node->nparam;
2098
2099                 for (j = 0; j < 2 * node->nvar; ++j)
2100                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2101         }
2102
2103         for (i = 0; i < graph->n_edge; ++i) {
2104                 k = isl_basic_set_alloc_inequality(graph->lp);
2105                 if (k < 0)
2106                         return -1;
2107                 isl_seq_clr(graph->lp->ineq[k], 1 +  total);
2108                 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
2109                 isl_int_set_si(graph->lp->ineq[k][0], 1);
2110         }
2111
2112         if (add_all_constraints(graph) < 0)
2113                 return -1;
2114
2115         return 0;
2116 }
2117
2118 /* Construct a schedule row for each node such that as many dependences
2119  * as possible are carried and then continue with the next band.
2120  */
2121 static int carry_dependences(isl_ctx *ctx, struct isl_sched_graph *graph)
2122 {
2123         isl_vec *sol;
2124         isl_basic_set *lp;
2125
2126         if (setup_carry_lp(ctx, graph) < 0)
2127                 return -1;
2128
2129         lp = isl_basic_set_copy(graph->lp);
2130         sol = isl_tab_basic_set_non_neg_lexmin(lp);
2131         if (!sol)
2132                 return -1;
2133
2134         if (sol->size == 0) {
2135                 isl_vec_free(sol);
2136                 isl_die(ctx, isl_error_internal,
2137                         "error in schedule construction", return -1);
2138         }
2139
2140         if (isl_int_cmp_si(sol->el[1], graph->n_edge) >= 0) {
2141                 isl_vec_free(sol);
2142                 isl_die(ctx, isl_error_unknown,
2143                         "unable to carry dependences", return -1);
2144         }
2145
2146         if (update_schedule(graph, sol, 0, 0) < 0)
2147                 return -1;
2148
2149         return compute_next_band(ctx, graph);
2150 }
2151
2152 /* Compute a schedule for a connected dependence graph.
2153  * We try to find a sequence of as many schedule rows as possible that result
2154  * in non-negative dependence distances (independent of the previous rows
2155  * in the sequence, i.e., such that the sequence is tilable).
2156  * If we can't find any more rows we either
2157  * - split between SCCs and start over (assuming we found an interesting
2158  *      pair of SCCs between which to split)
2159  * - continue with the next band (assuming the current band has at least
2160  *      one row)
2161  * - try to carry as many dependences as possible and continue with the next
2162  *      band
2163  *
2164  * If we manage to complete the schedule, we finish off by topologically
2165  * sorting the statements based on the remaining dependences.
2166  */
2167 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph)
2168 {
2169         if (detect_sccs(graph) < 0)
2170                 return -1;
2171         sort_sccs(graph);
2172
2173         if (compute_maxvar(graph) < 0)
2174                 return -1;
2175
2176         while (graph->n_row < graph->maxvar) {
2177                 isl_vec *sol;
2178
2179                 graph->src_scc = -1;
2180                 graph->dst_scc = -1;
2181
2182                 if (setup_lp(ctx, graph) < 0)
2183                         return -1;
2184                 sol = solve_lp(graph);
2185                 if (!sol)
2186                         return -1;
2187                 if (sol->size == 0) {
2188                         isl_vec_free(sol);
2189                         if (graph->src_scc >= 0)
2190                                 return compute_split_schedule(ctx, graph);
2191                         if (graph->n_total_row > graph->band_start)
2192                                 return compute_next_band(ctx, graph);
2193                         return carry_dependences(ctx, graph);
2194                 }
2195                 if (update_schedule(graph, sol, 1, 1) < 0)
2196                         return -1;
2197         }
2198
2199         if (graph->n_total_row > graph->band_start)
2200                 next_band(graph);
2201         return sort_statements(ctx, graph);
2202 }
2203
2204 /* Compute a schedule for each component (identified by node->scc)
2205  * of the dependence graph separately and then combine the results.
2206  *
2207  * The band_id is adjusted such that each component has a separate id.
2208  * Note that the band_id may have already been set to a value different
2209  * from zero by compute_split_schedule.
2210  */
2211 static int compute_component_schedule(isl_ctx *ctx,
2212         struct isl_sched_graph *graph)
2213 {
2214         int wcc, i;
2215         int n, n_edge;
2216         int n_total_row, orig_total_row;
2217         int n_band, orig_band;
2218
2219         n_total_row = 0;
2220         orig_total_row = graph->n_total_row;
2221         n_band = 0;
2222         orig_band = graph->n_band;
2223         for (i = 0; i < graph->n; ++i)
2224                 graph->node[i].band_id[graph->n_band] += graph->node[i].scc;
2225         for (wcc = 0; wcc < graph->scc; ++wcc) {
2226                 n = 0;
2227                 for (i = 0; i < graph->n; ++i)
2228                         if (graph->node[i].scc == wcc)
2229                                 n++;
2230                 n_edge = 0;
2231                 for (i = 0; i < graph->n_edge; ++i)
2232                         if (graph->edge[i].src->scc == wcc)
2233                                 n_edge++;
2234
2235                 if (compute_sub_schedule(ctx, graph, n, n_edge,
2236                                     &node_scc_exactly,
2237                                     &edge_src_scc_exactly, wcc, 1) < 0)
2238                         return -1;
2239                 if (graph->n_total_row > n_total_row)
2240                         n_total_row = graph->n_total_row;
2241                 graph->n_total_row = orig_total_row;
2242                 if (graph->n_band > n_band)
2243                         n_band = graph->n_band;
2244                 graph->n_band = orig_band;
2245         }
2246
2247         graph->n_total_row = n_total_row;
2248         graph->n_band = n_band;
2249
2250         return pad_schedule(graph);
2251 }
2252
2253 /* Compute a schedule for the given dependence graph.
2254  * We first check if the graph is connected (through validity dependences)
2255  * and if so compute a schedule for each component separately.
2256  */
2257 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
2258 {
2259         if (detect_wccs(graph) < 0)
2260                 return -1;
2261
2262         if (graph->scc > 1)
2263                 return compute_component_schedule(ctx, graph);
2264
2265         return compute_schedule_wcc(ctx, graph);
2266 }
2267
2268 /* Compute a schedule for the given union of domains that respects
2269  * all the validity dependences and tries to minimize the dependence
2270  * distances over the proximity dependences.
2271  */
2272 __isl_give isl_schedule *isl_union_set_compute_schedule(
2273         __isl_take isl_union_set *domain,
2274         __isl_take isl_union_map *validity,
2275         __isl_take isl_union_map *proximity)
2276 {
2277         isl_ctx *ctx = isl_union_set_get_ctx(domain);
2278         isl_dim *dim;
2279         struct isl_sched_graph graph = { 0 };
2280         isl_schedule *sched;
2281
2282         domain = isl_union_set_align_params(domain,
2283                                             isl_union_map_get_dim(validity));
2284         domain = isl_union_set_align_params(domain,
2285                                             isl_union_map_get_dim(proximity));
2286         dim = isl_union_set_get_dim(domain);
2287         validity = isl_union_map_align_params(validity, isl_dim_copy(dim));
2288         proximity = isl_union_map_align_params(proximity, dim);
2289
2290         if (!domain)
2291                 goto error;
2292
2293         graph.n = isl_union_set_n_set(domain);
2294         if (graph.n == 0)
2295                 goto empty;
2296         if (graph_alloc(ctx, &graph, graph.n,
2297             isl_union_map_n_map(validity) + isl_union_map_n_map(proximity)) < 0)
2298                 goto error;
2299         graph.root = 1;
2300         graph.n = 0;
2301         if (isl_union_set_foreach_set(domain, &extract_node, &graph) < 0)
2302                 goto error;
2303         if (graph_init_table(ctx, &graph) < 0)
2304                 goto error;
2305         graph.n_edge = 0;
2306         if (isl_union_map_foreach_map(validity, &extract_edge, &graph) < 0)
2307                 goto error;
2308         if (graph_init_edge_table(ctx, &graph) < 0)
2309                 goto error;
2310         if (isl_union_map_foreach_map(proximity, &extract_edge, &graph) < 0)
2311                 goto error;
2312
2313         if (compute_schedule(ctx, &graph) < 0)
2314                 goto error;
2315
2316 empty:
2317         sched = extract_schedule(&graph, isl_union_set_get_dim(domain));
2318
2319         graph_free(ctx, &graph);
2320         isl_union_set_free(domain);
2321         isl_union_map_free(validity);
2322         isl_union_map_free(proximity);
2323
2324         return sched;
2325 error:
2326         graph_free(ctx, &graph);
2327         isl_union_set_free(domain);
2328         isl_union_map_free(validity);
2329         isl_union_map_free(proximity);
2330         return NULL;
2331 }
2332
2333 void *isl_schedule_free(__isl_take isl_schedule *sched)
2334 {
2335         int i;
2336         if (!sched)
2337                 return NULL;
2338
2339         if (--sched->ref > 0)
2340                 return NULL;
2341
2342         for (i = 0; i < sched->n; ++i) {
2343                 isl_map_free(sched->node[i].sched);
2344                 free(sched->node[i].band_end);
2345                 free(sched->node[i].band_id);
2346                 free(sched->node[i].parallel);
2347         }
2348         isl_dim_free(sched->dim);
2349         isl_band_list_free(sched->band_forest);
2350         free(sched);
2351         return NULL;
2352 }
2353
2354 isl_ctx *isl_schedule_get_ctx(__isl_keep isl_schedule *schedule)
2355 {
2356         return schedule ? isl_dim_get_ctx(schedule->dim) : NULL;
2357 }
2358
2359 __isl_give isl_union_map *isl_schedule_get_map(__isl_keep isl_schedule *sched)
2360 {
2361         int i;
2362         isl_union_map *umap;
2363
2364         if (!sched)
2365                 return NULL;
2366
2367         umap = isl_union_map_empty(isl_dim_copy(sched->dim));
2368         for (i = 0; i < sched->n; ++i)
2369                 umap = isl_union_map_add_map(umap,
2370                                             isl_map_copy(sched->node[i].sched));
2371
2372         return umap;
2373 }
2374
2375 int isl_schedule_n_band(__isl_keep isl_schedule *sched)
2376 {
2377         return sched ? sched->n_band : 0;
2378 }
2379
2380 /* Construct a mapping that maps each domain to the band in its schedule
2381  * with the specified band index.  Note that bands with the same index
2382  * but for different domains do not need to be related.
2383  */
2384 __isl_give isl_union_map *isl_schedule_get_band(__isl_keep isl_schedule *sched,
2385         unsigned band)
2386 {
2387         int i;
2388         isl_union_map *umap;
2389
2390         if (!sched)
2391                 return NULL;
2392
2393         umap = isl_union_map_empty(isl_dim_copy(sched->dim));
2394         for (i = 0; i < sched->n; ++i) {
2395                 int start, end;
2396                 isl_map *map;
2397
2398                 if (band >= sched->node[i].n_band)
2399                         continue;
2400
2401                 start = band > 0 ? sched->node[i].band_end[band - 1] : 0;
2402                 end = sched->node[i].band_end[band];
2403
2404                 map = isl_map_copy(sched->node[i].sched);
2405
2406                 map = isl_map_project_out(map, isl_dim_out, end,
2407                                           sched->n_total_row - end);
2408                 map = isl_map_project_out(map, isl_dim_out, 0, start);
2409
2410                 umap = isl_union_map_add_map(umap, map);
2411         }
2412
2413         return umap;
2414 }
2415
2416 static __isl_give isl_band_list *construct_band_list(
2417         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
2418         int band_nr, int *parent_active, int n_active);
2419
2420 /* Construct an isl_band structure for the band in the given schedule
2421  * with sequence number band_nr for the n_active nodes marked by active.
2422  * If the nodes don't have a band with the given sequence number,
2423  * then a band without members is created.
2424  *
2425  * Because of the way the schedule is constructed, we know that
2426  * the position of the band inside the schedule of a node is the same
2427  * for all active nodes.
2428  */
2429 static __isl_give isl_band *construct_band(__isl_keep isl_schedule *schedule,
2430         __isl_keep isl_band *parent,
2431         int band_nr, int *active, int n_active)
2432 {
2433         int i, j;
2434         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2435         isl_band *band;
2436         unsigned start, end;
2437
2438         band = isl_calloc_type(ctx, isl_band);
2439         if (!band)
2440                 return NULL;
2441
2442         band->ref = 1;
2443         band->schedule = schedule;
2444         band->parent = parent;
2445
2446         for (i = 0; i < schedule->n; ++i)
2447                 if (active[i] && schedule->node[i].n_band > band_nr + 1)
2448                         break;
2449
2450         if (i < schedule->n) {
2451                 band->children = construct_band_list(schedule, band,
2452                                                 band_nr + 1, active, n_active);
2453                 if (!band->children)
2454                         goto error;
2455         }
2456
2457         for (i = 0; i < schedule->n; ++i)
2458                 if (active[i])
2459                         break;
2460
2461         if (i >= schedule->n)
2462                 isl_die(ctx, isl_error_internal,
2463                         "band without active statements", goto error);
2464
2465         start = band_nr ? schedule->node[i].band_end[band_nr - 1] : 0;
2466         end = band_nr < schedule->node[i].n_band ?
2467                 schedule->node[i].band_end[band_nr] : start;
2468         band->n = end - start;
2469
2470         band->parallel = isl_alloc_array(ctx, int, band->n);
2471         if (!band->parallel)
2472                 goto error;
2473
2474         for (j = 0; j < band->n; ++j)
2475                 band->parallel[j] = schedule->node[i].parallel[start + j];
2476
2477         band->map = isl_union_map_empty(isl_dim_copy(schedule->dim));
2478         for (i = 0; i < schedule->n; ++i) {
2479                 isl_map *map;
2480                 unsigned n_out;
2481
2482                 if (!active[i])
2483                         continue;
2484
2485                 map = isl_map_copy(schedule->node[i].sched);
2486                 n_out = isl_map_dim(map, isl_dim_out);
2487                 map = isl_map_project_out(map, isl_dim_out, end, n_out - end);
2488                 map = isl_map_project_out(map, isl_dim_out, 0, start);
2489                 band->map = isl_union_map_union(band->map,
2490                                                 isl_union_map_from_map(map));
2491         }
2492         if (!band->map)
2493                 goto error;
2494
2495         return band;
2496 error:
2497         isl_band_free(band);
2498         return NULL;
2499 }
2500
2501 /* Construct a list of bands that start at the same position (with
2502  * sequence number band_nr) in the schedules of the nodes that
2503  * were active in the parent band.
2504  *
2505  * A separate isl_band structure is created for each band_id
2506  * and for each node that does not have a band with sequence
2507  * number band_nr.  In the latter case, a band without members
2508  * is created.
2509  * This ensures that if a band has any children, then each node
2510  * that was active in the band is active in exactly one of the children.
2511  */
2512 static __isl_give isl_band_list *construct_band_list(
2513         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
2514         int band_nr, int *parent_active, int n_active)
2515 {
2516         int i, j;
2517         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2518         int *active;
2519         int n_band;
2520         isl_band_list *list;
2521
2522         n_band = 0;
2523         for (i = 0; i < n_active; ++i) {
2524                 for (j = 0; j < schedule->n; ++j) {
2525                         if (!parent_active[j])
2526                                 continue;
2527                         if (schedule->node[j].n_band <= band_nr)
2528                                 continue;
2529                         if (schedule->node[j].band_id[band_nr] == i) {
2530                                 n_band++;
2531                                 break;
2532                         }
2533                 }
2534         }
2535         for (j = 0; j < schedule->n; ++j)
2536                 if (schedule->node[j].n_band <= band_nr)
2537                         n_band++;
2538
2539         if (n_band == 1) {
2540                 isl_band *band;
2541                 list = isl_band_list_alloc(ctx, n_band);
2542                 band = construct_band(schedule, parent, band_nr,
2543                                         parent_active, n_active);
2544                 return isl_band_list_add(list, band);
2545         }
2546
2547         active = isl_alloc_array(ctx, int, schedule->n);
2548         if (!active)
2549                 return NULL;
2550
2551         list = isl_band_list_alloc(ctx, n_band);
2552
2553         for (i = 0; i < n_active; ++i) {
2554                 int n = 0;
2555                 isl_band *band;
2556
2557                 for (j = 0; j < schedule->n; ++j) {
2558                         active[j] = parent_active[j] &&
2559                                         schedule->node[j].n_band > band_nr &&
2560                                         schedule->node[j].band_id[band_nr] == i;
2561                         if (active[j])
2562                                 n++;
2563                 }
2564                 if (n == 0)
2565                         continue;
2566
2567                 band = construct_band(schedule, parent, band_nr, active, n);
2568
2569                 list = isl_band_list_add(list, band);
2570         }
2571         for (i = 0; i < schedule->n; ++i) {
2572                 isl_band *band;
2573                 if (!parent_active[i])
2574                         continue;
2575                 if (schedule->node[i].n_band > band_nr)
2576                         continue;
2577                 for (j = 0; j < schedule->n; ++j)
2578                         active[j] = j == i;
2579                 band = construct_band(schedule, parent, band_nr, active, 1);
2580                 list = isl_band_list_add(list, band);
2581         }
2582
2583         free(active);
2584
2585         return list;
2586 }
2587
2588 /* Construct a band forest representation of the schedule and
2589  * return the list of roots.
2590  */
2591 static __isl_give isl_band_list *construct_forest(
2592         __isl_keep isl_schedule *schedule)
2593 {
2594         int i;
2595         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2596         isl_band_list *forest;
2597         int *active;
2598
2599         active = isl_alloc_array(ctx, int, schedule->n);
2600         if (!active)
2601                 return NULL;
2602
2603         for (i = 0; i < schedule->n; ++i)
2604                 active[i] = 1;
2605
2606         forest = construct_band_list(schedule, NULL, 0, active, schedule->n);
2607
2608         free(active);
2609
2610         return forest;
2611 }
2612
2613 /* Return the roots of a band forest representation of the schedule.
2614  */
2615 __isl_give isl_band_list *isl_schedule_get_band_forest(
2616         __isl_keep isl_schedule *schedule)
2617 {
2618         if (!schedule)
2619                 return NULL;
2620         if (!schedule->band_forest)
2621                 schedule->band_forest = construct_forest(schedule);
2622         return isl_band_list_copy(schedule->band_forest);
2623 }