relicense isl under the MIT license
[platform/upstream/isl.git] / isl_schedule.c
1 /*
2  * Copyright 2011      INRIA Saclay
3  *
4  * Use of this software is governed by the MIT 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_space_private.h>
14 #include <isl/aff.h>
15 #include <isl/hash.h>
16 #include <isl/constraint.h>
17 #include <isl/schedule.h>
18 #include <isl_mat_private.h>
19 #include <isl/set.h>
20 #include <isl/seq.h>
21 #include <isl_tab.h>
22 #include <isl_dim_map.h>
23 #include <isl_hmap_map_basic_set.h>
24 #include <isl_sort.h>
25 #include <isl_schedule_private.h>
26 #include <isl_band_private.h>
27 #include <isl_list_private.h>
28 #include <isl_options_private.h>
29 #include <isl_tarjan.h>
30
31 /*
32  * The scheduling algorithm implemented in this file was inspired by
33  * Bondhugula et al., "Automatic Transformations for Communication-Minimized
34  * Parallelization and Locality Optimization in the Polyhedral Model".
35  */
36
37
38 /* Internal information about a node that is used during the construction
39  * of a schedule.
40  * dim represents the space in which the domain lives
41  * sched is a matrix representation of the schedule being constructed
42  *      for this node
43  * sched_map is an isl_map representation of the same (partial) schedule
44  *      sched_map may be NULL
45  * rank is the number of linearly independent rows in the linear part
46  *      of sched
47  * the columns of cmap represent a change of basis for the schedule
48  *      coefficients; the first rank columns span the linear part of
49  *      the schedule rows
50  * start is the first variable in the LP problem in the sequences that
51  *      represents the schedule coefficients of this node
52  * nvar is the dimension of the domain
53  * nparam is the number of parameters or 0 if we are not constructing
54  *      a parametric schedule
55  *
56  * scc is the index of SCC (or WCC) this node belongs to
57  *
58  * band contains the band index for each of the rows of the schedule.
59  * band_id is used to differentiate between separate bands at the same
60  * level within the same parent band, i.e., bands that are separated
61  * by the parent band or bands that are independent of each other.
62  * zero contains a boolean for each of the rows of the schedule,
63  * indicating whether the corresponding scheduling dimension results
64  * in zero dependence distances within its band and with respect
65  * to the proximity edges.
66  */
67 struct isl_sched_node {
68         isl_space *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     *zero;
82 };
83
84 static int node_has_dim(const void *entry, const void *val)
85 {
86         struct isl_sched_node *node = (struct isl_sched_node *)entry;
87         isl_space *dim = (isl_space *)val;
88
89         return isl_space_is_equal(node->dim, dim);
90 }
91
92 /* An edge in the dependence graph.  An edge may be used to
93  * ensure validity of the generated schedule, to minimize the dependence
94  * distance or both
95  *
96  * map is the dependence relation
97  * src is the source node
98  * dst is the sink node
99  * validity is set if the edge is used to ensure correctness
100  * proximity is set if the edge is used to minimize dependence distances
101  *
102  * For validity edges, start and end mark the sequence of inequality
103  * constraints in the LP problem that encode the validity constraint
104  * corresponding to this edge.
105  */
106 struct isl_sched_edge {
107         isl_map *map;
108
109         struct isl_sched_node *src;
110         struct isl_sched_node *dst;
111
112         int validity;
113         int proximity;
114
115         int start;
116         int end;
117 };
118
119 enum isl_edge_type {
120         isl_edge_validity = 0,
121         isl_edge_first = isl_edge_validity,
122         isl_edge_proximity,
123         isl_edge_last = isl_edge_proximity
124 };
125
126 /* Internal information about the dependence graph used during
127  * the construction of the schedule.
128  *
129  * intra_hmap is a cache, mapping dependence relations to their dual,
130  *      for dependences from a node to itself
131  * inter_hmap is a cache, mapping dependence relations to their dual,
132  *      for dependences between distinct nodes
133  *
134  * n is the number of nodes
135  * node is the list of nodes
136  * maxvar is the maximal number of variables over all nodes
137  * max_row is the allocated number of rows in the schedule
138  * n_row is the current (maximal) number of linearly independent
139  *      rows in the node schedules
140  * n_total_row is the current number of rows in the node schedules
141  * n_band is the current number of completed bands
142  * band_start is the starting row in the node schedules of the current band
143  * root is set if this graph is the original dependence graph,
144  *      without any splitting
145  *
146  * sorted contains a list of node indices sorted according to the
147  *      SCC to which a node belongs
148  *
149  * n_edge is the number of edges
150  * edge is the list of edges
151  * max_edge contains the maximal number of edges of each type;
152  *      in particular, it contains the number of edges in the inital graph.
153  * edge_table contains pointers into the edge array, hashed on the source
154  *      and sink spaces; there is one such table for each type;
155  *      a given edge may be referenced from more than one table
156  *      if the corresponding relation appears in more than of the
157  *      sets of dependences
158  *
159  * node_table contains pointers into the node array, hashed on the space
160  *
161  * region contains a list of variable sequences that should be non-trivial
162  *
163  * lp contains the (I)LP problem used to obtain new schedule rows
164  *
165  * src_scc and dst_scc are the source and sink SCCs of an edge with
166  *      conflicting constraints
167  *
168  * scc represents the number of components
169  */
170 struct isl_sched_graph {
171         isl_hmap_map_basic_set *intra_hmap;
172         isl_hmap_map_basic_set *inter_hmap;
173
174         struct isl_sched_node *node;
175         int n;
176         int maxvar;
177         int max_row;
178         int n_row;
179
180         int *sorted;
181
182         int n_band;
183         int n_total_row;
184         int band_start;
185
186         int root;
187
188         struct isl_sched_edge *edge;
189         int n_edge;
190         int max_edge[isl_edge_last + 1];
191         struct isl_hash_table *edge_table[isl_edge_last + 1];
192
193         struct isl_hash_table *node_table;
194         struct isl_region *region;
195
196         isl_basic_set *lp;
197
198         int src_scc;
199         int dst_scc;
200
201         int scc;
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_space_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_space *dim)
235 {
236         struct isl_hash_table_entry *entry;
237         uint32_t hash;
238
239         hash = isl_space_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 /* Add the given edge to graph->edge_table[type].
255  */
256 static int graph_edge_table_add(isl_ctx *ctx, struct isl_sched_graph *graph,
257         enum isl_edge_type type, struct isl_sched_edge *edge)
258 {
259         struct isl_hash_table_entry *entry;
260         uint32_t hash;
261
262         hash = isl_hash_init();
263         hash = isl_hash_builtin(hash, edge->src);
264         hash = isl_hash_builtin(hash, edge->dst);
265         entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
266                                     &edge_has_src_and_dst, edge, 1);
267         if (!entry)
268                 return -1;
269         entry->data = edge;
270
271         return 0;
272 }
273
274 /* Allocate the edge_tables based on the maximal number of edges of
275  * each type.
276  */
277 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
278 {
279         int i;
280
281         for (i = 0; i <= isl_edge_last; ++i) {
282                 graph->edge_table[i] = isl_hash_table_alloc(ctx,
283                                                             graph->max_edge[i]);
284                 if (!graph->edge_table[i])
285                         return -1;
286         }
287
288         return 0;
289 }
290
291 /* If graph->edge_table[type] contains an edge from the given source
292  * to the given destination, then return the hash table entry of this edge.
293  * Otherwise, return NULL.
294  */
295 static struct isl_hash_table_entry *graph_find_edge_entry(
296         struct isl_sched_graph *graph,
297         enum isl_edge_type type,
298         struct isl_sched_node *src, struct isl_sched_node *dst)
299 {
300         isl_ctx *ctx = isl_space_get_ctx(src->dim);
301         uint32_t hash;
302         struct isl_sched_edge temp = { .src = src, .dst = dst };
303
304         hash = isl_hash_init();
305         hash = isl_hash_builtin(hash, temp.src);
306         hash = isl_hash_builtin(hash, temp.dst);
307         return isl_hash_table_find(ctx, graph->edge_table[type], hash,
308                                     &edge_has_src_and_dst, &temp, 0);
309 }
310
311
312 /* If graph->edge_table[type] contains an edge from the given source
313  * to the given destination, then return this edge.
314  * Otherwise, return NULL.
315  */
316 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
317         enum isl_edge_type type,
318         struct isl_sched_node *src, struct isl_sched_node *dst)
319 {
320         struct isl_hash_table_entry *entry;
321
322         entry = graph_find_edge_entry(graph, type, src, dst);
323         if (!entry)
324                 return NULL;
325
326         return entry->data;
327 }
328
329 /* Check whether the dependence graph has an edge of the give type
330  * between the given two nodes.
331  */
332 static int graph_has_edge(struct isl_sched_graph *graph,
333         enum isl_edge_type type,
334         struct isl_sched_node *src, struct isl_sched_node *dst)
335 {
336         struct isl_sched_edge *edge;
337         int empty;
338
339         edge = graph_find_edge(graph, type, src, dst);
340         if (!edge)
341                 return 0;
342
343         empty = isl_map_plain_is_empty(edge->map);
344         if (empty < 0)
345                 return -1;
346
347         return !empty;
348 }
349
350 /* If there is an edge from the given source to the given destination
351  * of any type then return this edge.
352  * Otherwise, return NULL.
353  */
354 static struct isl_sched_edge *graph_find_any_edge(struct isl_sched_graph *graph,
355         struct isl_sched_node *src, struct isl_sched_node *dst)
356 {
357         enum isl_edge_type i;
358         struct isl_sched_edge *edge;
359
360         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
361                 edge = graph_find_edge(graph, i, src, dst);
362                 if (edge)
363                         return edge;
364         }
365
366         return NULL;
367 }
368
369 /* Remove the given edge from all the edge_tables that refer to it.
370  */
371 static void graph_remove_edge(struct isl_sched_graph *graph,
372         struct isl_sched_edge *edge)
373 {
374         isl_ctx *ctx = isl_map_get_ctx(edge->map);
375         enum isl_edge_type i;
376
377         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
378                 struct isl_hash_table_entry *entry;
379
380                 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
381                 if (!entry)
382                         continue;
383                 if (entry->data != edge)
384                         continue;
385                 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
386         }
387 }
388
389 /* Check whether the dependence graph has any edge
390  * between the given two nodes.
391  */
392 static int graph_has_any_edge(struct isl_sched_graph *graph,
393         struct isl_sched_node *src, struct isl_sched_node *dst)
394 {
395         enum isl_edge_type i;
396         int r;
397
398         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
399                 r = graph_has_edge(graph, i, src, dst);
400                 if (r < 0 || r)
401                         return r;
402         }
403
404         return r;
405 }
406
407 /* Check whether the dependence graph has a validity edge
408  * between the given two nodes.
409  */
410 static int graph_has_validity_edge(struct isl_sched_graph *graph,
411         struct isl_sched_node *src, struct isl_sched_node *dst)
412 {
413         return graph_has_edge(graph, isl_edge_validity, src, dst);
414 }
415
416 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
417         int n_node, int n_edge)
418 {
419         int i;
420
421         graph->n = n_node;
422         graph->n_edge = n_edge;
423         graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
424         graph->sorted = isl_calloc_array(ctx, int, graph->n);
425         graph->region = isl_alloc_array(ctx, struct isl_region, graph->n);
426         graph->edge = isl_calloc_array(ctx,
427                                         struct isl_sched_edge, graph->n_edge);
428
429         graph->intra_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
430         graph->inter_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
431
432         if (!graph->node || !graph->region || !graph->edge || !graph->sorted)
433                 return -1;
434
435         for(i = 0; i < graph->n; ++i)
436                 graph->sorted[i] = i;
437
438         return 0;
439 }
440
441 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
442 {
443         int i;
444
445         isl_hmap_map_basic_set_free(ctx, graph->intra_hmap);
446         isl_hmap_map_basic_set_free(ctx, graph->inter_hmap);
447
448         for (i = 0; i < graph->n; ++i) {
449                 isl_space_free(graph->node[i].dim);
450                 isl_mat_free(graph->node[i].sched);
451                 isl_map_free(graph->node[i].sched_map);
452                 isl_mat_free(graph->node[i].cmap);
453                 if (graph->root) {
454                         free(graph->node[i].band);
455                         free(graph->node[i].band_id);
456                         free(graph->node[i].zero);
457                 }
458         }
459         free(graph->node);
460         free(graph->sorted);
461         for (i = 0; i < graph->n_edge; ++i)
462                 isl_map_free(graph->edge[i].map);
463         free(graph->edge);
464         free(graph->region);
465         for (i = 0; i <= isl_edge_last; ++i)
466                 isl_hash_table_free(ctx, graph->edge_table[i]);
467         isl_hash_table_free(ctx, graph->node_table);
468         isl_basic_set_free(graph->lp);
469 }
470
471 /* For each "set" on which this function is called, increment
472  * graph->n by one and update graph->maxvar.
473  */
474 static int init_n_maxvar(__isl_take isl_set *set, void *user)
475 {
476         struct isl_sched_graph *graph = user;
477         int nvar = isl_set_dim(set, isl_dim_set);
478
479         graph->n++;
480         if (nvar > graph->maxvar)
481                 graph->maxvar = nvar;
482
483         isl_set_free(set);
484
485         return 0;
486 }
487
488 /* Compute the number of rows that should be allocated for the schedule.
489  * The graph can be split at most "n - 1" times, there can be at most
490  * two rows for each dimension in the iteration domains (in particular,
491  * we usually have one row, but it may be split by split_scaled),
492  * and there can be one extra row for ordering the statements.
493  * Note that if we have actually split "n - 1" times, then no ordering
494  * is needed, so in principle we could use "graph->n + 2 * graph->maxvar - 1".
495  */
496 static int compute_max_row(struct isl_sched_graph *graph,
497         __isl_keep isl_union_set *domain)
498 {
499         graph->n = 0;
500         graph->maxvar = 0;
501         if (isl_union_set_foreach_set(domain, &init_n_maxvar, graph) < 0)
502                 return -1;
503         graph->max_row = graph->n + 2 * graph->maxvar;
504
505         return 0;
506 }
507
508 /* Add a new node to the graph representing the given set.
509  */
510 static int extract_node(__isl_take isl_set *set, void *user)
511 {
512         int nvar, nparam;
513         isl_ctx *ctx;
514         isl_space *dim;
515         isl_mat *sched;
516         struct isl_sched_graph *graph = user;
517         int *band, *band_id, *zero;
518
519         ctx = isl_set_get_ctx(set);
520         dim = isl_set_get_space(set);
521         isl_set_free(set);
522         nvar = isl_space_dim(dim, isl_dim_set);
523         nparam = isl_space_dim(dim, isl_dim_param);
524         if (!ctx->opt->schedule_parametric)
525                 nparam = 0;
526         sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
527         graph->node[graph->n].dim = dim;
528         graph->node[graph->n].nvar = nvar;
529         graph->node[graph->n].nparam = nparam;
530         graph->node[graph->n].sched = sched;
531         graph->node[graph->n].sched_map = NULL;
532         band = isl_alloc_array(ctx, int, graph->max_row);
533         graph->node[graph->n].band = band;
534         band_id = isl_calloc_array(ctx, int, graph->max_row);
535         graph->node[graph->n].band_id = band_id;
536         zero = isl_calloc_array(ctx, int, graph->max_row);
537         graph->node[graph->n].zero = zero;
538         graph->n++;
539
540         if (!sched || !band || !band_id || !zero)
541                 return -1;
542
543         return 0;
544 }
545
546 struct isl_extract_edge_data {
547         enum isl_edge_type type;
548         struct isl_sched_graph *graph;
549 };
550
551 /* Add a new edge to the graph based on the given map
552  * and add it to data->graph->edge_table[data->type].
553  * If a dependence relation of a given type happens to be identical
554  * to one of the dependence relations of a type that was added before,
555  * then we don't create a new edge, but instead mark the original edge
556  * as also representing a dependence of the current type.
557  */
558 static int extract_edge(__isl_take isl_map *map, void *user)
559 {
560         isl_ctx *ctx = isl_map_get_ctx(map);
561         struct isl_extract_edge_data *data = user;
562         struct isl_sched_graph *graph = data->graph;
563         struct isl_sched_node *src, *dst;
564         isl_space *dim;
565         struct isl_sched_edge *edge;
566         int is_equal;
567
568         dim = isl_space_domain(isl_map_get_space(map));
569         src = graph_find_node(ctx, graph, dim);
570         isl_space_free(dim);
571         dim = isl_space_range(isl_map_get_space(map));
572         dst = graph_find_node(ctx, graph, dim);
573         isl_space_free(dim);
574
575         if (!src || !dst) {
576                 isl_map_free(map);
577                 return 0;
578         }
579
580         graph->edge[graph->n_edge].src = src;
581         graph->edge[graph->n_edge].dst = dst;
582         graph->edge[graph->n_edge].map = map;
583         if (data->type == isl_edge_validity) {
584                 graph->edge[graph->n_edge].validity = 1;
585                 graph->edge[graph->n_edge].proximity = 0;
586         }
587         if (data->type == isl_edge_proximity) {
588                 graph->edge[graph->n_edge].validity = 0;
589                 graph->edge[graph->n_edge].proximity = 1;
590         }
591         graph->n_edge++;
592
593         edge = graph_find_any_edge(graph, src, dst);
594         if (!edge)
595                 return graph_edge_table_add(ctx, graph, data->type,
596                                     &graph->edge[graph->n_edge - 1]);
597         is_equal = isl_map_plain_is_equal(map, edge->map);
598         if (is_equal < 0)
599                 return -1;
600         if (!is_equal)
601                 return graph_edge_table_add(ctx, graph, data->type,
602                                     &graph->edge[graph->n_edge - 1]);
603
604         graph->n_edge--;
605         edge->validity |= graph->edge[graph->n_edge].validity;
606         edge->proximity |= graph->edge[graph->n_edge].proximity;
607         isl_map_free(map);
608
609         return graph_edge_table_add(ctx, graph, data->type, edge);
610 }
611
612 /* Check whether there is any dependence from node[j] to node[i]
613  * or from node[i] to node[j].
614  */
615 static int node_follows_weak(int i, int j, void *user)
616 {
617         int f;
618         struct isl_sched_graph *graph = user;
619
620         f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
621         if (f < 0 || f)
622                 return f;
623         return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
624 }
625
626 /* Check whether there is a validity dependence from node[j] to node[i],
627  * forcing node[i] to follow node[j].
628  */
629 static int node_follows_strong(int i, int j, void *user)
630 {
631         struct isl_sched_graph *graph = user;
632
633         return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
634 }
635
636 /* Use Tarjan's algorithm for computing the strongly connected components
637  * in the dependence graph (only validity edges).
638  * If weak is set, we consider the graph to be undirected and
639  * we effectively compute the (weakly) connected components.
640  * Additionally, we also consider other edges when weak is set.
641  */
642 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph, int weak)
643 {
644         int i, n;
645         struct isl_tarjan_graph *g = NULL;
646
647         g = isl_tarjan_graph_init(ctx, graph->n,
648                 weak ? &node_follows_weak : &node_follows_strong, graph);
649         if (!g)
650                 return -1;
651
652         graph->scc = 0;
653         i = 0;
654         n = graph->n;
655         while (n) {
656                 while (g->order[i] != -1) {
657                         graph->node[g->order[i]].scc = graph->scc;
658                         --n;
659                         ++i;
660                 }
661                 ++i;
662                 graph->scc++;
663         }
664
665         isl_tarjan_graph_free(g);
666
667         return 0;
668 }
669
670 /* Apply Tarjan's algorithm to detect the strongly connected components
671  * in the dependence graph.
672  */
673 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
674 {
675         return detect_ccs(ctx, graph, 0);
676 }
677
678 /* Apply Tarjan's algorithm to detect the (weakly) connected components
679  * in the dependence graph.
680  */
681 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
682 {
683         return detect_ccs(ctx, graph, 1);
684 }
685
686 static int cmp_scc(const void *a, const void *b, void *data)
687 {
688         struct isl_sched_graph *graph = data;
689         const int *i1 = a;
690         const int *i2 = b;
691
692         return graph->node[*i1].scc - graph->node[*i2].scc;
693 }
694
695 /* Sort the elements of graph->sorted according to the corresponding SCCs.
696  */
697 static int sort_sccs(struct isl_sched_graph *graph)
698 {
699         return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
700 }
701
702 /* Given a dependence relation R from a node to itself,
703  * construct the set of coefficients of valid constraints for elements
704  * in that dependence relation.
705  * In particular, the result contains tuples of coefficients
706  * c_0, c_n, c_x such that
707  *
708  *      c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
709  *
710  * or, equivalently,
711  *
712  *      c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
713  *
714  * We choose here to compute the dual of delta R.
715  * Alternatively, we could have computed the dual of R, resulting
716  * in a set of tuples c_0, c_n, c_x, c_y, and then
717  * plugged in (c_0, c_n, c_x, -c_x).
718  */
719 static __isl_give isl_basic_set *intra_coefficients(
720         struct isl_sched_graph *graph, __isl_take isl_map *map)
721 {
722         isl_ctx *ctx = isl_map_get_ctx(map);
723         isl_set *delta;
724         isl_basic_set *coef;
725
726         if (isl_hmap_map_basic_set_has(ctx, graph->intra_hmap, map))
727                 return isl_hmap_map_basic_set_get(ctx, graph->intra_hmap, map);
728
729         delta = isl_set_remove_divs(isl_map_deltas(isl_map_copy(map)));
730         coef = isl_set_coefficients(delta);
731         isl_hmap_map_basic_set_set(ctx, graph->intra_hmap, map,
732                                         isl_basic_set_copy(coef));
733
734         return coef;
735 }
736
737 /* Given a dependence relation R, * construct the set of coefficients
738  * of valid constraints for elements in that dependence relation.
739  * In particular, the result contains tuples of coefficients
740  * c_0, c_n, c_x, c_y such that
741  *
742  *      c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
743  *
744  */
745 static __isl_give isl_basic_set *inter_coefficients(
746         struct isl_sched_graph *graph, __isl_take isl_map *map)
747 {
748         isl_ctx *ctx = isl_map_get_ctx(map);
749         isl_set *set;
750         isl_basic_set *coef;
751
752         if (isl_hmap_map_basic_set_has(ctx, graph->inter_hmap, map))
753                 return isl_hmap_map_basic_set_get(ctx, graph->inter_hmap, map);
754
755         set = isl_map_wrap(isl_map_remove_divs(isl_map_copy(map)));
756         coef = isl_set_coefficients(set);
757         isl_hmap_map_basic_set_set(ctx, graph->inter_hmap, map,
758                                         isl_basic_set_copy(coef));
759
760         return coef;
761 }
762
763 /* Add constraints to graph->lp that force validity for the given
764  * dependence from a node i to itself.
765  * That is, add constraints that enforce
766  *
767  *      (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
768  *      = c_i_x (y - x) >= 0
769  *
770  * for each (x,y) in R.
771  * We obtain general constraints on coefficients (c_0, c_n, c_x)
772  * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
773  * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
774  * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
775  *
776  * Actually, we do not construct constraints for the c_i_x themselves,
777  * but for the coefficients of c_i_x written as a linear combination
778  * of the columns in node->cmap.
779  */
780 static int add_intra_validity_constraints(struct isl_sched_graph *graph,
781         struct isl_sched_edge *edge)
782 {
783         unsigned total;
784         isl_map *map = isl_map_copy(edge->map);
785         isl_ctx *ctx = isl_map_get_ctx(map);
786         isl_space *dim;
787         isl_dim_map *dim_map;
788         isl_basic_set *coef;
789         struct isl_sched_node *node = edge->src;
790
791         coef = intra_coefficients(graph, map);
792
793         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
794
795         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
796                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(node->cmap));
797
798         total = isl_basic_set_total_dim(graph->lp);
799         dim_map = isl_dim_map_alloc(ctx, total);
800         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
801                           isl_space_dim(dim, isl_dim_set), 1,
802                           node->nvar, -1);
803         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
804                           isl_space_dim(dim, isl_dim_set), 1,
805                           node->nvar, 1);
806         graph->lp = isl_basic_set_extend_constraints(graph->lp,
807                         coef->n_eq, coef->n_ineq);
808         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
809                                                            coef, dim_map);
810         isl_space_free(dim);
811
812         return 0;
813 }
814
815 /* Add constraints to graph->lp that force validity for the given
816  * dependence from node i to node j.
817  * That is, add constraints that enforce
818  *
819  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
820  *
821  * for each (x,y) in R.
822  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
823  * of valid constraints for R and then plug in
824  * (c_j_0 - c_i_0, c_j_n^+ - c_j_n^- - (c_i_n^+ - c_i_n^-),
825  *  c_j_x^+ - c_j_x^- - (c_i_x^+ - c_i_x^-)),
826  * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
827  * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
828  *
829  * Actually, we do not construct constraints for the c_*_x themselves,
830  * but for the coefficients of c_*_x written as a linear combination
831  * of the columns in node->cmap.
832  */
833 static int add_inter_validity_constraints(struct isl_sched_graph *graph,
834         struct isl_sched_edge *edge)
835 {
836         unsigned total;
837         isl_map *map = isl_map_copy(edge->map);
838         isl_ctx *ctx = isl_map_get_ctx(map);
839         isl_space *dim;
840         isl_dim_map *dim_map;
841         isl_basic_set *coef;
842         struct isl_sched_node *src = edge->src;
843         struct isl_sched_node *dst = edge->dst;
844
845         coef = inter_coefficients(graph, map);
846
847         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
848
849         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
850                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(src->cmap));
851         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
852                     isl_space_dim(dim, isl_dim_set) + src->nvar,
853                     isl_mat_copy(dst->cmap));
854
855         total = isl_basic_set_total_dim(graph->lp);
856         dim_map = isl_dim_map_alloc(ctx, total);
857
858         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
859         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
860         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
861         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
862                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
863                           dst->nvar, -1);
864         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
865                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
866                           dst->nvar, 1);
867
868         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
869         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
870         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
871         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
872                           isl_space_dim(dim, isl_dim_set), 1,
873                           src->nvar, 1);
874         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
875                           isl_space_dim(dim, isl_dim_set), 1,
876                           src->nvar, -1);
877
878         edge->start = graph->lp->n_ineq;
879         graph->lp = isl_basic_set_extend_constraints(graph->lp,
880                         coef->n_eq, coef->n_ineq);
881         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
882                                                            coef, dim_map);
883         isl_space_free(dim);
884         edge->end = graph->lp->n_ineq;
885
886         return 0;
887 }
888
889 /* Add constraints to graph->lp that bound the dependence distance for the given
890  * dependence from a node i to itself.
891  * If s = 1, we add the constraint
892  *
893  *      c_i_x (y - x) <= m_0 + m_n n
894  *
895  * or
896  *
897  *      -c_i_x (y - x) + m_0 + m_n n >= 0
898  *
899  * for each (x,y) in R.
900  * If s = -1, we add the constraint
901  *
902  *      -c_i_x (y - x) <= m_0 + m_n n
903  *
904  * or
905  *
906  *      c_i_x (y - x) + m_0 + m_n n >= 0
907  *
908  * for each (x,y) in R.
909  * We obtain general constraints on coefficients (c_0, c_n, c_x)
910  * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
911  * with each coefficient (except m_0) represented as a pair of non-negative
912  * coefficients.
913  *
914  * Actually, we do not construct constraints for the c_i_x themselves,
915  * but for the coefficients of c_i_x written as a linear combination
916  * of the columns in node->cmap.
917  */
918 static int add_intra_proximity_constraints(struct isl_sched_graph *graph,
919         struct isl_sched_edge *edge, int s)
920 {
921         unsigned total;
922         unsigned nparam;
923         isl_map *map = isl_map_copy(edge->map);
924         isl_ctx *ctx = isl_map_get_ctx(map);
925         isl_space *dim;
926         isl_dim_map *dim_map;
927         isl_basic_set *coef;
928         struct isl_sched_node *node = edge->src;
929
930         coef = intra_coefficients(graph, map);
931
932         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
933
934         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
935                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(node->cmap));
936
937         nparam = isl_space_dim(node->dim, isl_dim_param);
938         total = isl_basic_set_total_dim(graph->lp);
939         dim_map = isl_dim_map_alloc(ctx, total);
940         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
941         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
942         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
943         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
944                           isl_space_dim(dim, isl_dim_set), 1,
945                           node->nvar, s);
946         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
947                           isl_space_dim(dim, isl_dim_set), 1,
948                           node->nvar, -s);
949         graph->lp = isl_basic_set_extend_constraints(graph->lp,
950                         coef->n_eq, coef->n_ineq);
951         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
952                                                            coef, dim_map);
953         isl_space_free(dim);
954
955         return 0;
956 }
957
958 /* Add constraints to graph->lp that bound the dependence distance for the given
959  * dependence from node i to node j.
960  * If s = 1, we add the constraint
961  *
962  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
963  *              <= m_0 + m_n n
964  *
965  * or
966  *
967  *      -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
968  *              m_0 + m_n n >= 0
969  *
970  * for each (x,y) in R.
971  * If s = -1, we add the constraint
972  *
973  *      -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
974  *              <= m_0 + m_n n
975  *
976  * or
977  *
978  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
979  *              m_0 + m_n n >= 0
980  *
981  * for each (x,y) in R.
982  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
983  * of valid constraints for R and then plug in
984  * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
985  *  -s*c_j_x+s*c_i_x)
986  * with each coefficient (except m_0, c_j_0 and c_i_0)
987  * represented as a pair of non-negative coefficients.
988  *
989  * Actually, we do not construct constraints for the c_*_x themselves,
990  * but for the coefficients of c_*_x written as a linear combination
991  * of the columns in node->cmap.
992  */
993 static int add_inter_proximity_constraints(struct isl_sched_graph *graph,
994         struct isl_sched_edge *edge, int s)
995 {
996         unsigned total;
997         unsigned nparam;
998         isl_map *map = isl_map_copy(edge->map);
999         isl_ctx *ctx = isl_map_get_ctx(map);
1000         isl_space *dim;
1001         isl_dim_map *dim_map;
1002         isl_basic_set *coef;
1003         struct isl_sched_node *src = edge->src;
1004         struct isl_sched_node *dst = edge->dst;
1005
1006         coef = inter_coefficients(graph, map);
1007
1008         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
1009
1010         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1011                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(src->cmap));
1012         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1013                     isl_space_dim(dim, isl_dim_set) + src->nvar,
1014                     isl_mat_copy(dst->cmap));
1015
1016         nparam = isl_space_dim(src->dim, isl_dim_param);
1017         total = isl_basic_set_total_dim(graph->lp);
1018         dim_map = isl_dim_map_alloc(ctx, total);
1019
1020         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1021         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1022         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1023
1024         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, -s);
1025         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, s);
1026         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, -s);
1027         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
1028                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
1029                           dst->nvar, s);
1030         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
1031                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
1032                           dst->nvar, -s);
1033
1034         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, s);
1035         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, -s);
1036         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, s);
1037         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
1038                           isl_space_dim(dim, isl_dim_set), 1,
1039                           src->nvar, -s);
1040         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
1041                           isl_space_dim(dim, isl_dim_set), 1,
1042                           src->nvar, s);
1043
1044         graph->lp = isl_basic_set_extend_constraints(graph->lp,
1045                         coef->n_eq, coef->n_ineq);
1046         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1047                                                            coef, dim_map);
1048         isl_space_free(dim);
1049
1050         return 0;
1051 }
1052
1053 static int add_all_validity_constraints(struct isl_sched_graph *graph)
1054 {
1055         int i;
1056
1057         for (i = 0; i < graph->n_edge; ++i) {
1058                 struct isl_sched_edge *edge= &graph->edge[i];
1059                 if (!edge->validity)
1060                         continue;
1061                 if (edge->src != edge->dst)
1062                         continue;
1063                 if (add_intra_validity_constraints(graph, edge) < 0)
1064                         return -1;
1065         }
1066
1067         for (i = 0; i < graph->n_edge; ++i) {
1068                 struct isl_sched_edge *edge = &graph->edge[i];
1069                 if (!edge->validity)
1070                         continue;
1071                 if (edge->src == edge->dst)
1072                         continue;
1073                 if (add_inter_validity_constraints(graph, edge) < 0)
1074                         return -1;
1075         }
1076
1077         return 0;
1078 }
1079
1080 /* Add constraints to graph->lp that bound the dependence distance
1081  * for all dependence relations.
1082  * If a given proximity dependence is identical to a validity
1083  * dependence, then the dependence distance is already bounded
1084  * from below (by zero), so we only need to bound the distance
1085  * from above.
1086  * Otherwise, we need to bound the distance both from above and from below.
1087  */
1088 static int add_all_proximity_constraints(struct isl_sched_graph *graph)
1089 {
1090         int i;
1091
1092         for (i = 0; i < graph->n_edge; ++i) {
1093                 struct isl_sched_edge *edge= &graph->edge[i];
1094                 if (!edge->proximity)
1095                         continue;
1096                 if (edge->src == edge->dst &&
1097                     add_intra_proximity_constraints(graph, edge, 1) < 0)
1098                         return -1;
1099                 if (edge->src != edge->dst &&
1100                     add_inter_proximity_constraints(graph, edge, 1) < 0)
1101                         return -1;
1102                 if (edge->validity)
1103                         continue;
1104                 if (edge->src == edge->dst &&
1105                     add_intra_proximity_constraints(graph, edge, -1) < 0)
1106                         return -1;
1107                 if (edge->src != edge->dst &&
1108                     add_inter_proximity_constraints(graph, edge, -1) < 0)
1109                         return -1;
1110         }
1111
1112         return 0;
1113 }
1114
1115 /* Compute a basis for the rows in the linear part of the schedule
1116  * and extend this basis to a full basis.  The remaining rows
1117  * can then be used to force linear independence from the rows
1118  * in the schedule.
1119  *
1120  * In particular, given the schedule rows S, we compute
1121  *
1122  *      S = H Q
1123  *
1124  * with H the Hermite normal form of S.  That is, all but the
1125  * first rank columns of Q are zero and so each row in S is
1126  * a linear combination of the first rank rows of Q.
1127  * The matrix Q is then transposed because we will write the
1128  * coefficients of the next schedule row as a column vector s
1129  * and express this s as a linear combination s = Q c of the
1130  * computed basis.
1131  */
1132 static int node_update_cmap(struct isl_sched_node *node)
1133 {
1134         isl_mat *H, *Q;
1135         int n_row = isl_mat_rows(node->sched);
1136
1137         H = isl_mat_sub_alloc(node->sched, 0, n_row,
1138                               1 + node->nparam, node->nvar);
1139
1140         H = isl_mat_left_hermite(H, 0, NULL, &Q);
1141         isl_mat_free(node->cmap);
1142         node->cmap = isl_mat_transpose(Q);
1143         node->rank = isl_mat_initial_non_zero_cols(H);
1144         isl_mat_free(H);
1145
1146         if (!node->cmap || node->rank < 0)
1147                 return -1;
1148         return 0;
1149 }
1150
1151 /* Count the number of equality and inequality constraints
1152  * that will be added for the given map.
1153  * If carry is set, then we are counting the number of (validity)
1154  * constraints that will be added in setup_carry_lp and we count
1155  * each edge exactly once.  Otherwise, we count as follows
1156  * validity             -> 1 (>= 0)
1157  * validity+proximity   -> 2 (>= 0 and upper bound)
1158  * proximity            -> 2 (lower and upper bound)
1159  */
1160 static int count_map_constraints(struct isl_sched_graph *graph,
1161         struct isl_sched_edge *edge, __isl_take isl_map *map,
1162         int *n_eq, int *n_ineq, int carry)
1163 {
1164         isl_basic_set *coef;
1165         int f = carry ? 1 : edge->proximity ? 2 : 1;
1166
1167         if (carry && !edge->validity) {
1168                 isl_map_free(map);
1169                 return 0;
1170         }
1171
1172         if (edge->src == edge->dst)
1173                 coef = intra_coefficients(graph, map);
1174         else
1175                 coef = inter_coefficients(graph, map);
1176         if (!coef)
1177                 return -1;
1178         *n_eq += f * coef->n_eq;
1179         *n_ineq += f * coef->n_ineq;
1180         isl_basic_set_free(coef);
1181
1182         return 0;
1183 }
1184
1185 /* Count the number of equality and inequality constraints
1186  * that will be added to the main lp problem.
1187  * We count as follows
1188  * validity             -> 1 (>= 0)
1189  * validity+proximity   -> 2 (>= 0 and upper bound)
1190  * proximity            -> 2 (lower and upper bound)
1191  */
1192 static int count_constraints(struct isl_sched_graph *graph,
1193         int *n_eq, int *n_ineq)
1194 {
1195         int i;
1196
1197         *n_eq = *n_ineq = 0;
1198         for (i = 0; i < graph->n_edge; ++i) {
1199                 struct isl_sched_edge *edge= &graph->edge[i];
1200                 isl_map *map = isl_map_copy(edge->map);
1201
1202                 if (count_map_constraints(graph, edge, map,
1203                                           n_eq, n_ineq, 0) < 0)
1204                         return -1;
1205         }
1206
1207         return 0;
1208 }
1209
1210 /* Add constraints that bound the values of the variable and parameter
1211  * coefficients of the schedule.
1212  *
1213  * The maximal value of the coefficients is defined by the option
1214  * 'schedule_max_coefficient'.
1215  */
1216 static int add_bound_coefficient_constraints(isl_ctx *ctx,
1217         struct isl_sched_graph *graph)
1218 {
1219         int i, j, k;
1220         int max_coefficient;
1221         int total;
1222
1223         max_coefficient = ctx->opt->schedule_max_coefficient;
1224
1225         if (max_coefficient == -1)
1226                 return 0;
1227
1228         total = isl_basic_set_total_dim(graph->lp);
1229
1230         for (i = 0; i < graph->n; ++i) {
1231                 struct isl_sched_node *node = &graph->node[i];
1232                 for (j = 0; j < 2 * node->nparam + 2 * node->nvar; ++j) {
1233                         int dim;
1234                         k = isl_basic_set_alloc_inequality(graph->lp);
1235                         if (k < 0)
1236                                 return -1;
1237                         dim = 1 + node->start + 1 + j;
1238                         isl_seq_clr(graph->lp->ineq[k], 1 +  total);
1239                         isl_int_set_si(graph->lp->ineq[k][dim], -1);
1240                         isl_int_set_si(graph->lp->ineq[k][0], max_coefficient);
1241                 }
1242         }
1243
1244         return 0;
1245 }
1246
1247 /* Construct an ILP problem for finding schedule coefficients
1248  * that result in non-negative, but small dependence distances
1249  * over all dependences.
1250  * In particular, the dependence distances over proximity edges
1251  * are bounded by m_0 + m_n n and we compute schedule coefficients
1252  * with small values (preferably zero) of m_n and m_0.
1253  *
1254  * All variables of the ILP are non-negative.  The actual coefficients
1255  * may be negative, so each coefficient is represented as the difference
1256  * of two non-negative variables.  The negative part always appears
1257  * immediately before the positive part.
1258  * Other than that, the variables have the following order
1259  *
1260  *      - sum of positive and negative parts of m_n coefficients
1261  *      - m_0
1262  *      - sum of positive and negative parts of all c_n coefficients
1263  *              (unconstrained when computing non-parametric schedules)
1264  *      - sum of positive and negative parts of all c_x coefficients
1265  *      - positive and negative parts of m_n coefficients
1266  *      - for each node
1267  *              - c_i_0
1268  *              - positive and negative parts of c_i_n (if parametric)
1269  *              - positive and negative parts of c_i_x
1270  *
1271  * The c_i_x are not represented directly, but through the columns of
1272  * node->cmap.  That is, the computed values are for variable t_i_x
1273  * such that c_i_x = Q t_i_x with Q equal to node->cmap.
1274  *
1275  * The constraints are those from the edges plus two or three equalities
1276  * to express the sums.
1277  *
1278  * If force_zero is set, then we add equalities to ensure that
1279  * the sum of the m_n coefficients and m_0 are both zero.
1280  */
1281 static int setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
1282         int force_zero)
1283 {
1284         int i, j;
1285         int k;
1286         unsigned nparam;
1287         unsigned total;
1288         isl_space *dim;
1289         int parametric;
1290         int param_pos;
1291         int n_eq, n_ineq;
1292         int max_constant_term;
1293         int max_coefficient;
1294
1295         max_constant_term = ctx->opt->schedule_max_constant_term;
1296         max_coefficient = ctx->opt->schedule_max_coefficient;
1297
1298         parametric = ctx->opt->schedule_parametric;
1299         nparam = isl_space_dim(graph->node[0].dim, isl_dim_param);
1300         param_pos = 4;
1301         total = param_pos + 2 * nparam;
1302         for (i = 0; i < graph->n; ++i) {
1303                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
1304                 if (node_update_cmap(node) < 0)
1305                         return -1;
1306                 node->start = total;
1307                 total += 1 + 2 * (node->nparam + node->nvar);
1308         }
1309
1310         if (count_constraints(graph, &n_eq, &n_ineq) < 0)
1311                 return -1;
1312
1313         dim = isl_space_set_alloc(ctx, 0, total);
1314         isl_basic_set_free(graph->lp);
1315         n_eq += 2 + parametric + force_zero;
1316         if (max_constant_term != -1)
1317                 n_ineq += graph->n;
1318         if (max_coefficient != -1)
1319                 for (i = 0; i < graph->n; ++i)
1320                         n_ineq += 2 * graph->node[i].nparam +
1321                                   2 * graph->node[i].nvar;
1322
1323         graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
1324
1325         k = isl_basic_set_alloc_equality(graph->lp);
1326         if (k < 0)
1327                 return -1;
1328         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1329         if (!force_zero)
1330                 isl_int_set_si(graph->lp->eq[k][1], -1);
1331         for (i = 0; i < 2 * nparam; ++i)
1332                 isl_int_set_si(graph->lp->eq[k][1 + param_pos + i], 1);
1333
1334         if (force_zero) {
1335                 k = isl_basic_set_alloc_equality(graph->lp);
1336                 if (k < 0)
1337                         return -1;
1338                 isl_seq_clr(graph->lp->eq[k], 1 +  total);
1339                 isl_int_set_si(graph->lp->eq[k][2], -1);
1340         }
1341
1342         if (parametric) {
1343                 k = isl_basic_set_alloc_equality(graph->lp);
1344                 if (k < 0)
1345                         return -1;
1346                 isl_seq_clr(graph->lp->eq[k], 1 +  total);
1347                 isl_int_set_si(graph->lp->eq[k][3], -1);
1348                 for (i = 0; i < graph->n; ++i) {
1349                         int pos = 1 + graph->node[i].start + 1;
1350
1351                         for (j = 0; j < 2 * graph->node[i].nparam; ++j)
1352                                 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1353                 }
1354         }
1355
1356         k = isl_basic_set_alloc_equality(graph->lp);
1357         if (k < 0)
1358                 return -1;
1359         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1360         isl_int_set_si(graph->lp->eq[k][4], -1);
1361         for (i = 0; i < graph->n; ++i) {
1362                 struct isl_sched_node *node = &graph->node[i];
1363                 int pos = 1 + node->start + 1 + 2 * node->nparam;
1364
1365                 for (j = 0; j < 2 * node->nvar; ++j)
1366                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1367         }
1368
1369         if (max_constant_term != -1)
1370                 for (i = 0; i < graph->n; ++i) {
1371                         struct isl_sched_node *node = &graph->node[i];
1372                         k = isl_basic_set_alloc_inequality(graph->lp);
1373                         if (k < 0)
1374                                 return -1;
1375                         isl_seq_clr(graph->lp->ineq[k], 1 +  total);
1376                         isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
1377                         isl_int_set_si(graph->lp->ineq[k][0], max_constant_term);
1378                 }
1379
1380         if (add_bound_coefficient_constraints(ctx, graph) < 0)
1381                 return -1;
1382         if (add_all_validity_constraints(graph) < 0)
1383                 return -1;
1384         if (add_all_proximity_constraints(graph) < 0)
1385                 return -1;
1386
1387         return 0;
1388 }
1389
1390 /* Analyze the conflicting constraint found by
1391  * isl_tab_basic_set_non_trivial_lexmin.  If it corresponds to the validity
1392  * constraint of one of the edges between distinct nodes, living, moreover
1393  * in distinct SCCs, then record the source and sink SCC as this may
1394  * be a good place to cut between SCCs.
1395  */
1396 static int check_conflict(int con, void *user)
1397 {
1398         int i;
1399         struct isl_sched_graph *graph = user;
1400
1401         if (graph->src_scc >= 0)
1402                 return 0;
1403
1404         con -= graph->lp->n_eq;
1405
1406         if (con >= graph->lp->n_ineq)
1407                 return 0;
1408
1409         for (i = 0; i < graph->n_edge; ++i) {
1410                 if (!graph->edge[i].validity)
1411                         continue;
1412                 if (graph->edge[i].src == graph->edge[i].dst)
1413                         continue;
1414                 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
1415                         continue;
1416                 if (graph->edge[i].start > con)
1417                         continue;
1418                 if (graph->edge[i].end <= con)
1419                         continue;
1420                 graph->src_scc = graph->edge[i].src->scc;
1421                 graph->dst_scc = graph->edge[i].dst->scc;
1422         }
1423
1424         return 0;
1425 }
1426
1427 /* Check whether the next schedule row of the given node needs to be
1428  * non-trivial.  Lower-dimensional domains may have some trivial rows,
1429  * but as soon as the number of remaining required non-trivial rows
1430  * is as large as the number or remaining rows to be computed,
1431  * all remaining rows need to be non-trivial.
1432  */
1433 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
1434 {
1435         return node->nvar - node->rank >= graph->maxvar - graph->n_row;
1436 }
1437
1438 /* Solve the ILP problem constructed in setup_lp.
1439  * For each node such that all the remaining rows of its schedule
1440  * need to be non-trivial, we construct a non-triviality region.
1441  * This region imposes that the next row is independent of previous rows.
1442  * In particular the coefficients c_i_x are represented by t_i_x
1443  * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
1444  * its first columns span the rows of the previously computed part
1445  * of the schedule.  The non-triviality region enforces that at least
1446  * one of the remaining components of t_i_x is non-zero, i.e.,
1447  * that the new schedule row depends on at least one of the remaining
1448  * columns of Q.
1449  */
1450 static __isl_give isl_vec *solve_lp(struct isl_sched_graph *graph)
1451 {
1452         int i;
1453         isl_vec *sol;
1454         isl_basic_set *lp;
1455
1456         for (i = 0; i < graph->n; ++i) {
1457                 struct isl_sched_node *node = &graph->node[i];
1458                 int skip = node->rank;
1459                 graph->region[i].pos = node->start + 1 + 2*(node->nparam+skip);
1460                 if (needs_row(graph, node))
1461                         graph->region[i].len = 2 * (node->nvar - skip);
1462                 else
1463                         graph->region[i].len = 0;
1464         }
1465         lp = isl_basic_set_copy(graph->lp);
1466         sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
1467                                        graph->region, &check_conflict, graph);
1468         return sol;
1469 }
1470
1471 /* Update the schedules of all nodes based on the given solution
1472  * of the LP problem.
1473  * The new row is added to the current band.
1474  * All possibly negative coefficients are encoded as a difference
1475  * of two non-negative variables, so we need to perform the subtraction
1476  * here.  Moreover, if use_cmap is set, then the solution does
1477  * not refer to the actual coefficients c_i_x, but instead to variables
1478  * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
1479  * In this case, we then also need to perform this multiplication
1480  * to obtain the values of c_i_x.
1481  *
1482  * If check_zero is set, then the first two coordinates of sol are
1483  * assumed to correspond to the dependence distance.  If these two
1484  * coordinates are zero, then the corresponding scheduling dimension
1485  * is marked as being zero distance.
1486  */
1487 static int update_schedule(struct isl_sched_graph *graph,
1488         __isl_take isl_vec *sol, int use_cmap, int check_zero)
1489 {
1490         int i, j;
1491         int zero = 0;
1492         isl_vec *csol = NULL;
1493
1494         if (!sol)
1495                 goto error;
1496         if (sol->size == 0)
1497                 isl_die(sol->ctx, isl_error_internal,
1498                         "no solution found", goto error);
1499
1500         if (check_zero)
1501                 zero = isl_int_is_zero(sol->el[1]) &&
1502                            isl_int_is_zero(sol->el[2]);
1503
1504         for (i = 0; i < graph->n; ++i) {
1505                 struct isl_sched_node *node = &graph->node[i];
1506                 int pos = node->start;
1507                 int row = isl_mat_rows(node->sched);
1508
1509                 isl_vec_free(csol);
1510                 csol = isl_vec_alloc(sol->ctx, node->nvar);
1511                 if (!csol)
1512                         goto error;
1513
1514                 isl_map_free(node->sched_map);
1515                 node->sched_map = NULL;
1516                 node->sched = isl_mat_add_rows(node->sched, 1);
1517                 if (!node->sched)
1518                         goto error;
1519                 node->sched = isl_mat_set_element(node->sched, row, 0,
1520                                                   sol->el[1 + pos]);
1521                 for (j = 0; j < node->nparam + node->nvar; ++j)
1522                         isl_int_sub(sol->el[1 + pos + 1 + 2 * j + 1],
1523                                     sol->el[1 + pos + 1 + 2 * j + 1],
1524                                     sol->el[1 + pos + 1 + 2 * j]);
1525                 for (j = 0; j < node->nparam; ++j)
1526                         node->sched = isl_mat_set_element(node->sched,
1527                                         row, 1 + j, sol->el[1+pos+1+2*j+1]);
1528                 for (j = 0; j < node->nvar; ++j)
1529                         isl_int_set(csol->el[j],
1530                                     sol->el[1+pos+1+2*(node->nparam+j)+1]);
1531                 if (use_cmap)
1532                         csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
1533                                                    csol);
1534                 if (!csol)
1535                         goto error;
1536                 for (j = 0; j < node->nvar; ++j)
1537                         node->sched = isl_mat_set_element(node->sched,
1538                                         row, 1 + node->nparam + j, csol->el[j]);
1539                 node->band[graph->n_total_row] = graph->n_band;
1540                 node->zero[graph->n_total_row] = zero;
1541         }
1542         isl_vec_free(sol);
1543         isl_vec_free(csol);
1544
1545         graph->n_row++;
1546         graph->n_total_row++;
1547
1548         return 0;
1549 error:
1550         isl_vec_free(sol);
1551         isl_vec_free(csol);
1552         return -1;
1553 }
1554
1555 /* Convert node->sched into a multi_aff and return this multi_aff.
1556  */
1557 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
1558         struct isl_sched_node *node)
1559 {
1560         int i, j;
1561         isl_space *space;
1562         isl_local_space *ls;
1563         isl_aff *aff;
1564         isl_multi_aff *ma;
1565         int nrow, ncol;
1566         isl_int v;
1567
1568         nrow = isl_mat_rows(node->sched);
1569         ncol = isl_mat_cols(node->sched) - 1;
1570         space = isl_space_from_domain(isl_space_copy(node->dim));
1571         space = isl_space_add_dims(space, isl_dim_out, nrow);
1572         ma = isl_multi_aff_zero(space);
1573         ls = isl_local_space_from_space(isl_space_copy(node->dim));
1574
1575         isl_int_init(v);
1576
1577         for (i = 0; i < nrow; ++i) {
1578                 aff = isl_aff_zero_on_domain(isl_local_space_copy(ls));
1579                 isl_mat_get_element(node->sched, i, 0, &v);
1580                 aff = isl_aff_set_constant(aff, v);
1581                 for (j = 0; j < node->nparam; ++j) {
1582                         isl_mat_get_element(node->sched, i, 1 + j, &v);
1583                         aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
1584                 }
1585                 for (j = 0; j < node->nvar; ++j) {
1586                         isl_mat_get_element(node->sched,
1587                                             i, 1 + node->nparam + j, &v);
1588                         aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
1589                 }
1590                 ma = isl_multi_aff_set_aff(ma, i, aff);
1591         }
1592
1593         isl_int_clear(v);
1594
1595         isl_local_space_free(ls);
1596
1597         return ma;
1598 }
1599
1600 /* Convert node->sched into a map and return this map.
1601  *
1602  * The result is cached in node->sched_map, which needs to be released
1603  * whenever node->sched is updated.
1604  */
1605 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
1606 {
1607         if (!node->sched_map) {
1608                 isl_multi_aff *ma;
1609
1610                 ma = node_extract_schedule_multi_aff(node);
1611                 node->sched_map = isl_map_from_multi_aff(ma);
1612         }
1613
1614         return isl_map_copy(node->sched_map);
1615 }
1616
1617 /* Update the given dependence relation based on the current schedule.
1618  * That is, intersect the dependence relation with a map expressing
1619  * that source and sink are executed within the same iteration of
1620  * the current schedule.
1621  * This is not the most efficient way, but this shouldn't be a critical
1622  * operation.
1623  */
1624 static __isl_give isl_map *specialize(__isl_take isl_map *map,
1625         struct isl_sched_node *src, struct isl_sched_node *dst)
1626 {
1627         isl_map *src_sched, *dst_sched, *id;
1628
1629         src_sched = node_extract_schedule(src);
1630         dst_sched = node_extract_schedule(dst);
1631         id = isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
1632         return isl_map_intersect(map, id);
1633 }
1634
1635 /* Update the dependence relations of all edges based on the current schedule.
1636  * If a dependence is carried completely by the current schedule, then
1637  * it is removed from the edge_tables.  It is kept in the list of edges
1638  * as otherwise all edge_tables would have to be recomputed.
1639  */
1640 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
1641 {
1642         int i;
1643
1644         for (i = graph->n_edge - 1; i >= 0; --i) {
1645                 struct isl_sched_edge *edge = &graph->edge[i];
1646                 edge->map = specialize(edge->map, edge->src, edge->dst);
1647                 if (!edge->map)
1648                         return -1;
1649
1650                 if (isl_map_plain_is_empty(edge->map))
1651                         graph_remove_edge(graph, edge);
1652         }
1653
1654         return 0;
1655 }
1656
1657 static void next_band(struct isl_sched_graph *graph)
1658 {
1659         graph->band_start = graph->n_total_row;
1660         graph->n_band++;
1661 }
1662
1663 /* Topologically sort statements mapped to the same schedule iteration
1664  * and add a row to the schedule corresponding to this order.
1665  */
1666 static int sort_statements(isl_ctx *ctx, struct isl_sched_graph *graph)
1667 {
1668         int i, j;
1669
1670         if (graph->n <= 1)
1671                 return 0;
1672
1673         if (update_edges(ctx, graph) < 0)
1674                 return -1;
1675
1676         if (graph->n_edge == 0)
1677                 return 0;
1678
1679         if (detect_sccs(ctx, graph) < 0)
1680                 return -1;
1681
1682         for (i = 0; i < graph->n; ++i) {
1683                 struct isl_sched_node *node = &graph->node[i];
1684                 int row = isl_mat_rows(node->sched);
1685                 int cols = isl_mat_cols(node->sched);
1686
1687                 isl_map_free(node->sched_map);
1688                 node->sched_map = NULL;
1689                 node->sched = isl_mat_add_rows(node->sched, 1);
1690                 if (!node->sched)
1691                         return -1;
1692                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
1693                                                      node->scc);
1694                 for (j = 1; j < cols; ++j)
1695                         node->sched = isl_mat_set_element_si(node->sched,
1696                                                              row, j, 0);
1697                 node->band[graph->n_total_row] = graph->n_band;
1698         }
1699
1700         graph->n_total_row++;
1701         next_band(graph);
1702
1703         return 0;
1704 }
1705
1706 /* Construct an isl_schedule based on the computed schedule stored
1707  * in graph and with parameters specified by dim.
1708  */
1709 static __isl_give isl_schedule *extract_schedule(struct isl_sched_graph *graph,
1710         __isl_take isl_space *dim)
1711 {
1712         int i;
1713         isl_ctx *ctx;
1714         isl_schedule *sched = NULL;
1715                 
1716         if (!dim)
1717                 return NULL;
1718
1719         ctx = isl_space_get_ctx(dim);
1720         sched = isl_calloc(ctx, struct isl_schedule,
1721                            sizeof(struct isl_schedule) +
1722                            (graph->n - 1) * sizeof(struct isl_schedule_node));
1723         if (!sched)
1724                 goto error;
1725
1726         sched->ref = 1;
1727         sched->n = graph->n;
1728         sched->n_band = graph->n_band;
1729         sched->n_total_row = graph->n_total_row;
1730
1731         for (i = 0; i < sched->n; ++i) {
1732                 int r, b;
1733                 int *band_end, *band_id, *zero;
1734
1735                 band_end = isl_alloc_array(ctx, int, graph->n_band);
1736                 band_id = isl_alloc_array(ctx, int, graph->n_band);
1737                 zero = isl_alloc_array(ctx, int, graph->n_total_row);
1738                 sched->node[i].sched =
1739                         node_extract_schedule_multi_aff(&graph->node[i]);
1740                 sched->node[i].band_end = band_end;
1741                 sched->node[i].band_id = band_id;
1742                 sched->node[i].zero = zero;
1743                 if (!band_end || !band_id || !zero)
1744                         goto error;
1745
1746                 for (r = 0; r < graph->n_total_row; ++r)
1747                         zero[r] = graph->node[i].zero[r];
1748                 for (r = b = 0; r < graph->n_total_row; ++r) {
1749                         if (graph->node[i].band[r] == b)
1750                                 continue;
1751                         band_end[b++] = r;
1752                         if (graph->node[i].band[r] == -1)
1753                                 break;
1754                 }
1755                 if (r == graph->n_total_row)
1756                         band_end[b++] = r;
1757                 sched->node[i].n_band = b;
1758                 for (--b; b >= 0; --b)
1759                         band_id[b] = graph->node[i].band_id[b];
1760         }
1761
1762         sched->dim = dim;
1763
1764         return sched;
1765 error:
1766         isl_space_free(dim);
1767         isl_schedule_free(sched);
1768         return NULL;
1769 }
1770
1771 /* Copy nodes that satisfy node_pred from the src dependence graph
1772  * to the dst dependence graph.
1773  */
1774 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
1775         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1776 {
1777         int i;
1778
1779         dst->n = 0;
1780         for (i = 0; i < src->n; ++i) {
1781                 if (!node_pred(&src->node[i], data))
1782                         continue;
1783                 dst->node[dst->n].dim = isl_space_copy(src->node[i].dim);
1784                 dst->node[dst->n].nvar = src->node[i].nvar;
1785                 dst->node[dst->n].nparam = src->node[i].nparam;
1786                 dst->node[dst->n].sched = isl_mat_copy(src->node[i].sched);
1787                 dst->node[dst->n].sched_map =
1788                         isl_map_copy(src->node[i].sched_map);
1789                 dst->node[dst->n].band = src->node[i].band;
1790                 dst->node[dst->n].band_id = src->node[i].band_id;
1791                 dst->node[dst->n].zero = src->node[i].zero;
1792                 dst->n++;
1793         }
1794
1795         return 0;
1796 }
1797
1798 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
1799  * to the dst dependence graph.
1800  * If the source or destination node of the edge is not in the destination
1801  * graph, then it must be a backward proximity edge and it should simply
1802  * be ignored.
1803  */
1804 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
1805         struct isl_sched_graph *src,
1806         int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
1807 {
1808         int i;
1809         enum isl_edge_type t;
1810
1811         dst->n_edge = 0;
1812         for (i = 0; i < src->n_edge; ++i) {
1813                 struct isl_sched_edge *edge = &src->edge[i];
1814                 isl_map *map;
1815                 struct isl_sched_node *dst_src, *dst_dst;
1816
1817                 if (!edge_pred(edge, data))
1818                         continue;
1819
1820                 if (isl_map_plain_is_empty(edge->map))
1821                         continue;
1822
1823                 dst_src = graph_find_node(ctx, dst, edge->src->dim);
1824                 dst_dst = graph_find_node(ctx, dst, edge->dst->dim);
1825                 if (!dst_src || !dst_dst) {
1826                         if (edge->validity)
1827                                 isl_die(ctx, isl_error_internal,
1828                                         "backward validity edge", return -1);
1829                         continue;
1830                 }
1831
1832                 map = isl_map_copy(edge->map);
1833
1834                 dst->edge[dst->n_edge].src = dst_src;
1835                 dst->edge[dst->n_edge].dst = dst_dst;
1836                 dst->edge[dst->n_edge].map = map;
1837                 dst->edge[dst->n_edge].validity = edge->validity;
1838                 dst->edge[dst->n_edge].proximity = edge->proximity;
1839                 dst->n_edge++;
1840
1841                 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
1842                         if (edge !=
1843                             graph_find_edge(src, t, edge->src, edge->dst))
1844                                 continue;
1845                         if (graph_edge_table_add(ctx, dst, t,
1846                                             &dst->edge[dst->n_edge - 1]) < 0)
1847                                 return -1;
1848                 }
1849         }
1850
1851         return 0;
1852 }
1853
1854 /* Given a "src" dependence graph that contains the nodes from "dst"
1855  * that satisfy node_pred, copy the schedule computed in "src"
1856  * for those nodes back to "dst".
1857  */
1858 static int copy_schedule(struct isl_sched_graph *dst,
1859         struct isl_sched_graph *src,
1860         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1861 {
1862         int i;
1863
1864         src->n = 0;
1865         for (i = 0; i < dst->n; ++i) {
1866                 if (!node_pred(&dst->node[i], data))
1867                         continue;
1868                 isl_mat_free(dst->node[i].sched);
1869                 isl_map_free(dst->node[i].sched_map);
1870                 dst->node[i].sched = isl_mat_copy(src->node[src->n].sched);
1871                 dst->node[i].sched_map =
1872                         isl_map_copy(src->node[src->n].sched_map);
1873                 src->n++;
1874         }
1875
1876         dst->n_total_row = src->n_total_row;
1877         dst->n_band = src->n_band;
1878
1879         return 0;
1880 }
1881
1882 /* Compute the maximal number of variables over all nodes.
1883  * This is the maximal number of linearly independent schedule
1884  * rows that we need to compute.
1885  * Just in case we end up in a part of the dependence graph
1886  * with only lower-dimensional domains, we make sure we will
1887  * compute the required amount of extra linearly independent rows.
1888  */
1889 static int compute_maxvar(struct isl_sched_graph *graph)
1890 {
1891         int i;
1892
1893         graph->maxvar = 0;
1894         for (i = 0; i < graph->n; ++i) {
1895                 struct isl_sched_node *node = &graph->node[i];
1896                 int nvar;
1897
1898                 if (node_update_cmap(node) < 0)
1899                         return -1;
1900                 nvar = node->nvar + graph->n_row - node->rank;
1901                 if (nvar > graph->maxvar)
1902                         graph->maxvar = nvar;
1903         }
1904
1905         return 0;
1906 }
1907
1908 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph);
1909 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph);
1910
1911 /* Compute a schedule for a subgraph of "graph".  In particular, for
1912  * the graph composed of nodes that satisfy node_pred and edges that
1913  * that satisfy edge_pred.  The caller should precompute the number
1914  * of nodes and edges that satisfy these predicates and pass them along
1915  * as "n" and "n_edge".
1916  * If the subgraph is known to consist of a single component, then wcc should
1917  * be set and then we call compute_schedule_wcc on the constructed subgraph.
1918  * Otherwise, we call compute_schedule, which will check whether the subgraph
1919  * is connected.
1920  */
1921 static int compute_sub_schedule(isl_ctx *ctx,
1922         struct isl_sched_graph *graph, int n, int n_edge,
1923         int (*node_pred)(struct isl_sched_node *node, int data),
1924         int (*edge_pred)(struct isl_sched_edge *edge, int data),
1925         int data, int wcc)
1926 {
1927         struct isl_sched_graph split = { 0 };
1928         int t;
1929
1930         if (graph_alloc(ctx, &split, n, n_edge) < 0)
1931                 goto error;
1932         if (copy_nodes(&split, graph, node_pred, data) < 0)
1933                 goto error;
1934         if (graph_init_table(ctx, &split) < 0)
1935                 goto error;
1936         for (t = 0; t <= isl_edge_last; ++t)
1937                 split.max_edge[t] = graph->max_edge[t];
1938         if (graph_init_edge_tables(ctx, &split) < 0)
1939                 goto error;
1940         if (copy_edges(ctx, &split, graph, edge_pred, data) < 0)
1941                 goto error;
1942         split.n_row = graph->n_row;
1943         split.n_total_row = graph->n_total_row;
1944         split.n_band = graph->n_band;
1945         split.band_start = graph->band_start;
1946
1947         if (wcc && compute_schedule_wcc(ctx, &split) < 0)
1948                 goto error;
1949         if (!wcc && compute_schedule(ctx, &split) < 0)
1950                 goto error;
1951
1952         copy_schedule(graph, &split, node_pred, data);
1953
1954         graph_free(ctx, &split);
1955         return 0;
1956 error:
1957         graph_free(ctx, &split);
1958         return -1;
1959 }
1960
1961 static int node_scc_exactly(struct isl_sched_node *node, int scc)
1962 {
1963         return node->scc == scc;
1964 }
1965
1966 static int node_scc_at_most(struct isl_sched_node *node, int scc)
1967 {
1968         return node->scc <= scc;
1969 }
1970
1971 static int node_scc_at_least(struct isl_sched_node *node, int scc)
1972 {
1973         return node->scc >= scc;
1974 }
1975
1976 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
1977 {
1978         return edge->src->scc == scc && edge->dst->scc == scc;
1979 }
1980
1981 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
1982 {
1983         return edge->dst->scc <= scc;
1984 }
1985
1986 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
1987 {
1988         return edge->src->scc >= scc;
1989 }
1990
1991 /* Pad the schedules of all nodes with zero rows such that in the end
1992  * they all have graph->n_total_row rows.
1993  * The extra rows don't belong to any band, so they get assigned band number -1.
1994  */
1995 static int pad_schedule(struct isl_sched_graph *graph)
1996 {
1997         int i, j;
1998
1999         for (i = 0; i < graph->n; ++i) {
2000                 struct isl_sched_node *node = &graph->node[i];
2001                 int row = isl_mat_rows(node->sched);
2002                 if (graph->n_total_row > row) {
2003                         isl_map_free(node->sched_map);
2004                         node->sched_map = NULL;
2005                 }
2006                 node->sched = isl_mat_add_zero_rows(node->sched,
2007                                                     graph->n_total_row - row);
2008                 if (!node->sched)
2009                         return -1;
2010                 for (j = row; j < graph->n_total_row; ++j)
2011                         node->band[j] = -1;
2012         }
2013
2014         return 0;
2015 }
2016
2017 /* Split the current graph into two parts and compute a schedule for each
2018  * part individually.  In particular, one part consists of all SCCs up
2019  * to and including graph->src_scc, while the other part contains the other
2020  * SCCS.
2021  *
2022  * The split is enforced in the schedule by constant rows with two different
2023  * values (0 and 1).  These constant rows replace the previously computed rows
2024  * in the current band.
2025  * It would be possible to reuse them as the first rows in the next
2026  * band, but recomputing them may result in better rows as we are looking
2027  * at a smaller part of the dependence graph.
2028  * compute_split_schedule is only called when no zero-distance schedule row
2029  * could be found on the entire graph, so we wark the splitting row as
2030  * non zero-distance.
2031  *
2032  * The band_id of the second group is set to n, where n is the number
2033  * of nodes in the first group.  This ensures that the band_ids over
2034  * the two groups remain disjoint, even if either or both of the two
2035  * groups contain independent components.
2036  */
2037 static int compute_split_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
2038 {
2039         int i, j, n, e1, e2;
2040         int n_total_row, orig_total_row;
2041         int n_band, orig_band;
2042         int drop;
2043
2044         drop = graph->n_total_row - graph->band_start;
2045         graph->n_total_row -= drop;
2046         graph->n_row -= drop;
2047
2048         n = 0;
2049         for (i = 0; i < graph->n; ++i) {
2050                 struct isl_sched_node *node = &graph->node[i];
2051                 int row = isl_mat_rows(node->sched) - drop;
2052                 int cols = isl_mat_cols(node->sched);
2053                 int before = node->scc <= graph->src_scc;
2054
2055                 if (before)
2056                         n++;
2057
2058                 isl_map_free(node->sched_map);
2059                 node->sched_map = NULL;
2060                 node->sched = isl_mat_drop_rows(node->sched,
2061                                                 graph->band_start, drop);
2062                 node->sched = isl_mat_add_rows(node->sched, 1);
2063                 if (!node->sched)
2064                         return -1;
2065                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
2066                                                      !before);
2067                 for (j = 1; j < cols; ++j)
2068                         node->sched = isl_mat_set_element_si(node->sched,
2069                                                              row, j, 0);
2070                 node->band[graph->n_total_row] = graph->n_band;
2071                 node->zero[graph->n_total_row] = 0;
2072         }
2073
2074         e1 = e2 = 0;
2075         for (i = 0; i < graph->n_edge; ++i) {
2076                 if (graph->edge[i].dst->scc <= graph->src_scc)
2077                         e1++;
2078                 if (graph->edge[i].src->scc > graph->src_scc)
2079                         e2++;
2080         }
2081
2082         graph->n_total_row++;
2083         next_band(graph);
2084
2085         for (i = 0; i < graph->n; ++i) {
2086                 struct isl_sched_node *node = &graph->node[i];
2087                 if (node->scc > graph->src_scc)
2088                         node->band_id[graph->n_band] = n;
2089         }
2090
2091         orig_total_row = graph->n_total_row;
2092         orig_band = graph->n_band;
2093         if (compute_sub_schedule(ctx, graph, n, e1,
2094                                 &node_scc_at_most, &edge_dst_scc_at_most,
2095                                 graph->src_scc, 0) < 0)
2096                 return -1;
2097         n_total_row = graph->n_total_row;
2098         graph->n_total_row = orig_total_row;
2099         n_band = graph->n_band;
2100         graph->n_band = orig_band;
2101         if (compute_sub_schedule(ctx, graph, graph->n - n, e2,
2102                                 &node_scc_at_least, &edge_src_scc_at_least,
2103                                 graph->src_scc + 1, 0) < 0)
2104                 return -1;
2105         if (n_total_row > graph->n_total_row)
2106                 graph->n_total_row = n_total_row;
2107         if (n_band > graph->n_band)
2108                 graph->n_band = n_band;
2109
2110         return pad_schedule(graph);
2111 }
2112
2113 /* Compute the next band of the schedule after updating the dependence
2114  * relations based on the the current schedule.
2115  */
2116 static int compute_next_band(isl_ctx *ctx, struct isl_sched_graph *graph)
2117 {
2118         if (update_edges(ctx, graph) < 0)
2119                 return -1;
2120         next_band(graph);
2121                 
2122         return compute_schedule(ctx, graph);
2123 }
2124
2125 /* Add constraints to graph->lp that force the dependence "map" (which
2126  * is part of the dependence relation of "edge")
2127  * to be respected and attempt to carry it, where the edge is one from
2128  * a node j to itself.  "pos" is the sequence number of the given map.
2129  * That is, add constraints that enforce
2130  *
2131  *      (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
2132  *      = c_j_x (y - x) >= e_i
2133  *
2134  * for each (x,y) in R.
2135  * We obtain general constraints on coefficients (c_0, c_n, c_x)
2136  * of valid constraints for (y - x) and then plug in (-e_i, 0, c_j_x),
2137  * with each coefficient in c_j_x represented as a pair of non-negative
2138  * coefficients.
2139  */
2140 static int add_intra_constraints(struct isl_sched_graph *graph,
2141         struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
2142 {
2143         unsigned total;
2144         isl_ctx *ctx = isl_map_get_ctx(map);
2145         isl_space *dim;
2146         isl_dim_map *dim_map;
2147         isl_basic_set *coef;
2148         struct isl_sched_node *node = edge->src;
2149
2150         coef = intra_coefficients(graph, map);
2151
2152         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
2153
2154         total = isl_basic_set_total_dim(graph->lp);
2155         dim_map = isl_dim_map_alloc(ctx, total);
2156         isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
2157         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
2158                           isl_space_dim(dim, isl_dim_set), 1,
2159                           node->nvar, -1);
2160         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
2161                           isl_space_dim(dim, isl_dim_set), 1,
2162                           node->nvar, 1);
2163         graph->lp = isl_basic_set_extend_constraints(graph->lp,
2164                         coef->n_eq, coef->n_ineq);
2165         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
2166                                                            coef, dim_map);
2167         isl_space_free(dim);
2168
2169         return 0;
2170 }
2171
2172 /* Add constraints to graph->lp that force the dependence "map" (which
2173  * is part of the dependence relation of "edge")
2174  * to be respected and attempt to carry it, where the edge is one from
2175  * node j to node k.  "pos" is the sequence number of the given map.
2176  * That is, add constraints that enforce
2177  *
2178  *      (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
2179  *
2180  * for each (x,y) in R.
2181  * We obtain general constraints on coefficients (c_0, c_n, c_x)
2182  * of valid constraints for R and then plug in
2183  * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, c_k_x - c_j_x)
2184  * with each coefficient (except e_i, c_k_0 and c_j_0)
2185  * represented as a pair of non-negative coefficients.
2186  */
2187 static int add_inter_constraints(struct isl_sched_graph *graph,
2188         struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
2189 {
2190         unsigned total;
2191         isl_ctx *ctx = isl_map_get_ctx(map);
2192         isl_space *dim;
2193         isl_dim_map *dim_map;
2194         isl_basic_set *coef;
2195         struct isl_sched_node *src = edge->src;
2196         struct isl_sched_node *dst = edge->dst;
2197
2198         coef = inter_coefficients(graph, map);
2199
2200         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
2201
2202         total = isl_basic_set_total_dim(graph->lp);
2203         dim_map = isl_dim_map_alloc(ctx, total);
2204
2205         isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
2206
2207         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
2208         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
2209         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
2210         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
2211                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
2212                           dst->nvar, -1);
2213         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
2214                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
2215                           dst->nvar, 1);
2216
2217         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
2218         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
2219         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
2220         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
2221                           isl_space_dim(dim, isl_dim_set), 1,
2222                           src->nvar, 1);
2223         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
2224                           isl_space_dim(dim, isl_dim_set), 1,
2225                           src->nvar, -1);
2226
2227         graph->lp = isl_basic_set_extend_constraints(graph->lp,
2228                         coef->n_eq, coef->n_ineq);
2229         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
2230                                                            coef, dim_map);
2231         isl_space_free(dim);
2232
2233         return 0;
2234 }
2235
2236 /* Add constraints to graph->lp that force all validity dependences
2237  * to be respected and attempt to carry them.
2238  */
2239 static int add_all_constraints(struct isl_sched_graph *graph)
2240 {
2241         int i, j;
2242         int pos;
2243
2244         pos = 0;
2245         for (i = 0; i < graph->n_edge; ++i) {
2246                 struct isl_sched_edge *edge= &graph->edge[i];
2247
2248                 if (!edge->validity)
2249                         continue;
2250
2251                 for (j = 0; j < edge->map->n; ++j) {
2252                         isl_basic_map *bmap;
2253                         isl_map *map;
2254
2255                         bmap = isl_basic_map_copy(edge->map->p[j]);
2256                         map = isl_map_from_basic_map(bmap);
2257
2258                         if (edge->src == edge->dst &&
2259                             add_intra_constraints(graph, edge, map, pos) < 0)
2260                                 return -1;
2261                         if (edge->src != edge->dst &&
2262                             add_inter_constraints(graph, edge, map, pos) < 0)
2263                                 return -1;
2264                         ++pos;
2265                 }
2266         }
2267
2268         return 0;
2269 }
2270
2271 /* Count the number of equality and inequality constraints
2272  * that will be added to the carry_lp problem.
2273  * We count each edge exactly once.
2274  */
2275 static int count_all_constraints(struct isl_sched_graph *graph,
2276         int *n_eq, int *n_ineq)
2277 {
2278         int i, j;
2279
2280         *n_eq = *n_ineq = 0;
2281         for (i = 0; i < graph->n_edge; ++i) {
2282                 struct isl_sched_edge *edge= &graph->edge[i];
2283                 for (j = 0; j < edge->map->n; ++j) {
2284                         isl_basic_map *bmap;
2285                         isl_map *map;
2286
2287                         bmap = isl_basic_map_copy(edge->map->p[j]);
2288                         map = isl_map_from_basic_map(bmap);
2289
2290                         if (count_map_constraints(graph, edge, map,
2291                                                   n_eq, n_ineq, 1) < 0)
2292                                     return -1;
2293                 }
2294         }
2295
2296         return 0;
2297 }
2298
2299 /* Construct an LP problem for finding schedule coefficients
2300  * such that the schedule carries as many dependences as possible.
2301  * In particular, for each dependence i, we bound the dependence distance
2302  * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
2303  * of all e_i's.  Dependence with e_i = 0 in the solution are simply
2304  * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
2305  * Note that if the dependence relation is a union of basic maps,
2306  * then we have to consider each basic map individually as it may only
2307  * be possible to carry the dependences expressed by some of those
2308  * basic maps and not all off them.
2309  * Below, we consider each of those basic maps as a separate "edge".
2310  *
2311  * All variables of the LP are non-negative.  The actual coefficients
2312  * may be negative, so each coefficient is represented as the difference
2313  * of two non-negative variables.  The negative part always appears
2314  * immediately before the positive part.
2315  * Other than that, the variables have the following order
2316  *
2317  *      - sum of (1 - e_i) over all edges
2318  *      - sum of positive and negative parts of all c_n coefficients
2319  *              (unconstrained when computing non-parametric schedules)
2320  *      - sum of positive and negative parts of all c_x coefficients
2321  *      - for each edge
2322  *              - e_i
2323  *      - for each node
2324  *              - c_i_0
2325  *              - positive and negative parts of c_i_n (if parametric)
2326  *              - positive and negative parts of c_i_x
2327  *
2328  * The constraints are those from the (validity) edges plus three equalities
2329  * to express the sums and n_edge inequalities to express e_i <= 1.
2330  */
2331 static int setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2332 {
2333         int i, j;
2334         int k;
2335         isl_space *dim;
2336         unsigned total;
2337         int n_eq, n_ineq;
2338         int n_edge;
2339
2340         n_edge = 0;
2341         for (i = 0; i < graph->n_edge; ++i)
2342                 n_edge += graph->edge[i].map->n;
2343
2344         total = 3 + n_edge;
2345         for (i = 0; i < graph->n; ++i) {
2346                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2347                 node->start = total;
2348                 total += 1 + 2 * (node->nparam + node->nvar);
2349         }
2350
2351         if (count_all_constraints(graph, &n_eq, &n_ineq) < 0)
2352                 return -1;
2353
2354         dim = isl_space_set_alloc(ctx, 0, total);
2355         isl_basic_set_free(graph->lp);
2356         n_eq += 3;
2357         n_ineq += n_edge;
2358         graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
2359         graph->lp = isl_basic_set_set_rational(graph->lp);
2360
2361         k = isl_basic_set_alloc_equality(graph->lp);
2362         if (k < 0)
2363                 return -1;
2364         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2365         isl_int_set_si(graph->lp->eq[k][0], -n_edge);
2366         isl_int_set_si(graph->lp->eq[k][1], 1);
2367         for (i = 0; i < n_edge; ++i)
2368                 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
2369
2370         k = isl_basic_set_alloc_equality(graph->lp);
2371         if (k < 0)
2372                 return -1;
2373         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2374         isl_int_set_si(graph->lp->eq[k][2], -1);
2375         for (i = 0; i < graph->n; ++i) {
2376                 int pos = 1 + graph->node[i].start + 1;
2377
2378                 for (j = 0; j < 2 * graph->node[i].nparam; ++j)
2379                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2380         }
2381
2382         k = isl_basic_set_alloc_equality(graph->lp);
2383         if (k < 0)
2384                 return -1;
2385         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2386         isl_int_set_si(graph->lp->eq[k][3], -1);
2387         for (i = 0; i < graph->n; ++i) {
2388                 struct isl_sched_node *node = &graph->node[i];
2389                 int pos = 1 + node->start + 1 + 2 * node->nparam;
2390
2391                 for (j = 0; j < 2 * node->nvar; ++j)
2392                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2393         }
2394
2395         for (i = 0; i < n_edge; ++i) {
2396                 k = isl_basic_set_alloc_inequality(graph->lp);
2397                 if (k < 0)
2398                         return -1;
2399                 isl_seq_clr(graph->lp->ineq[k], 1 +  total);
2400                 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
2401                 isl_int_set_si(graph->lp->ineq[k][0], 1);
2402         }
2403
2404         if (add_all_constraints(graph) < 0)
2405                 return -1;
2406
2407         return 0;
2408 }
2409
2410 /* If the schedule_split_scaled option is set and if the linear
2411  * parts of the scheduling rows for all nodes in the graphs have
2412  * non-trivial common divisor, then split off the constant term
2413  * from the linear part.
2414  * The constant term is then placed in a separate band and
2415  * the linear part is reduced.
2416  */
2417 static int split_scaled(isl_ctx *ctx, struct isl_sched_graph *graph)
2418 {
2419         int i;
2420         int row;
2421         isl_int gcd, gcd_i;
2422
2423         if (!ctx->opt->schedule_split_scaled)
2424                 return 0;
2425         if (graph->n <= 1)
2426                 return 0;
2427
2428         isl_int_init(gcd);
2429         isl_int_init(gcd_i);
2430
2431         isl_int_set_si(gcd, 0);
2432
2433         row = isl_mat_rows(graph->node[0].sched) - 1;
2434
2435         for (i = 0; i < graph->n; ++i) {
2436                 struct isl_sched_node *node = &graph->node[i];
2437                 int cols = isl_mat_cols(node->sched);
2438
2439                 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
2440                 isl_int_gcd(gcd, gcd, gcd_i);
2441         }
2442
2443         isl_int_clear(gcd_i);
2444
2445         if (isl_int_cmp_si(gcd, 1) <= 0) {
2446                 isl_int_clear(gcd);
2447                 return 0;
2448         }
2449
2450         next_band(graph);
2451
2452         for (i = 0; i < graph->n; ++i) {
2453                 struct isl_sched_node *node = &graph->node[i];
2454
2455                 isl_map_free(node->sched_map);
2456                 node->sched_map = NULL;
2457                 node->sched = isl_mat_add_zero_rows(node->sched, 1);
2458                 if (!node->sched)
2459                         goto error;
2460                 isl_int_fdiv_r(node->sched->row[row + 1][0],
2461                                node->sched->row[row][0], gcd);
2462                 isl_int_fdiv_q(node->sched->row[row][0],
2463                                node->sched->row[row][0], gcd);
2464                 isl_int_mul(node->sched->row[row][0],
2465                             node->sched->row[row][0], gcd);
2466                 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
2467                 if (!node->sched)
2468                         goto error;
2469                 node->band[graph->n_total_row] = graph->n_band;
2470         }
2471
2472         graph->n_total_row++;
2473
2474         isl_int_clear(gcd);
2475         return 0;
2476 error:
2477         isl_int_clear(gcd);
2478         return -1;
2479 }
2480
2481 /* Construct a schedule row for each node such that as many dependences
2482  * as possible are carried and then continue with the next band.
2483  */
2484 static int carry_dependences(isl_ctx *ctx, struct isl_sched_graph *graph)
2485 {
2486         int i;
2487         int n_edge;
2488         isl_vec *sol;
2489         isl_basic_set *lp;
2490
2491         n_edge = 0;
2492         for (i = 0; i < graph->n_edge; ++i)
2493                 n_edge += graph->edge[i].map->n;
2494
2495         if (setup_carry_lp(ctx, graph) < 0)
2496                 return -1;
2497
2498         lp = isl_basic_set_copy(graph->lp);
2499         sol = isl_tab_basic_set_non_neg_lexmin(lp);
2500         if (!sol)
2501                 return -1;
2502
2503         if (sol->size == 0) {
2504                 isl_vec_free(sol);
2505                 isl_die(ctx, isl_error_internal,
2506                         "error in schedule construction", return -1);
2507         }
2508
2509         if (isl_int_cmp_si(sol->el[1], n_edge) >= 0) {
2510                 isl_vec_free(sol);
2511                 isl_die(ctx, isl_error_unknown,
2512                         "unable to carry dependences", return -1);
2513         }
2514
2515         if (update_schedule(graph, sol, 0, 0) < 0)
2516                 return -1;
2517
2518         if (split_scaled(ctx, graph) < 0)
2519                 return -1;
2520
2521         return compute_next_band(ctx, graph);
2522 }
2523
2524 /* Are there any (non-empty) validity edges in the graph?
2525  */
2526 static int has_validity_edges(struct isl_sched_graph *graph)
2527 {
2528         int i;
2529
2530         for (i = 0; i < graph->n_edge; ++i) {
2531                 int empty;
2532
2533                 empty = isl_map_plain_is_empty(graph->edge[i].map);
2534                 if (empty < 0)
2535                         return -1;
2536                 if (empty)
2537                         continue;
2538                 if (graph->edge[i].validity)
2539                         return 1;
2540         }
2541
2542         return 0;
2543 }
2544
2545 /* Should we apply a Feautrier step?
2546  * That is, did the user request the Feautrier algorithm and are
2547  * there any validity dependences (left)?
2548  */
2549 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
2550 {
2551         if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
2552                 return 0;
2553
2554         return has_validity_edges(graph);
2555 }
2556
2557 /* Compute a schedule for a connected dependence graph using Feautrier's
2558  * multi-dimensional scheduling algorithm.
2559  * The original algorithm is described in [1].
2560  * The main idea is to minimize the number of scheduling dimensions, by
2561  * trying to satisfy as many dependences as possible per scheduling dimension.
2562  *
2563  * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
2564  *     Problem, Part II: Multi-Dimensional Time.
2565  *     In Intl. Journal of Parallel Programming, 1992.
2566  */
2567 static int compute_schedule_wcc_feautrier(isl_ctx *ctx,
2568         struct isl_sched_graph *graph)
2569 {
2570         return carry_dependences(ctx, graph);
2571 }
2572
2573 /* Compute a schedule for a connected dependence graph.
2574  * We try to find a sequence of as many schedule rows as possible that result
2575  * in non-negative dependence distances (independent of the previous rows
2576  * in the sequence, i.e., such that the sequence is tilable).
2577  * If we can't find any more rows we either
2578  * - split between SCCs and start over (assuming we found an interesting
2579  *      pair of SCCs between which to split)
2580  * - continue with the next band (assuming the current band has at least
2581  *      one row)
2582  * - try to carry as many dependences as possible and continue with the next
2583  *      band
2584  *
2585  * If Feautrier's algorithm is selected, we first recursively try to satisfy
2586  * as many validity dependences as possible. When all validity dependences
2587  * are satisfied we extend the schedule to a full-dimensional schedule.
2588  *
2589  * If we manage to complete the schedule, we finish off by topologically
2590  * sorting the statements based on the remaining dependences.
2591  *
2592  * If ctx->opt->schedule_outer_zero_distance is set, then we force the
2593  * outermost dimension in the current band to be zero distance.  If this
2594  * turns out to be impossible, we fall back on the general scheme above
2595  * and try to carry as many dependences as possible.
2596  */
2597 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph)
2598 {
2599         int force_zero = 0;
2600
2601         if (detect_sccs(ctx, graph) < 0)
2602                 return -1;
2603         if (sort_sccs(graph) < 0)
2604                 return -1;
2605
2606         if (compute_maxvar(graph) < 0)
2607                 return -1;
2608
2609         if (need_feautrier_step(ctx, graph))
2610                 return compute_schedule_wcc_feautrier(ctx, graph);
2611
2612         if (ctx->opt->schedule_outer_zero_distance)
2613                 force_zero = 1;
2614
2615         while (graph->n_row < graph->maxvar) {
2616                 isl_vec *sol;
2617
2618                 graph->src_scc = -1;
2619                 graph->dst_scc = -1;
2620
2621                 if (setup_lp(ctx, graph, force_zero) < 0)
2622                         return -1;
2623                 sol = solve_lp(graph);
2624                 if (!sol)
2625                         return -1;
2626                 if (sol->size == 0) {
2627                         isl_vec_free(sol);
2628                         if (!ctx->opt->schedule_maximize_band_depth &&
2629                             graph->n_total_row > graph->band_start)
2630                                 return compute_next_band(ctx, graph);
2631                         if (graph->src_scc >= 0)
2632                                 return compute_split_schedule(ctx, graph);
2633                         if (graph->n_total_row > graph->band_start)
2634                                 return compute_next_band(ctx, graph);
2635                         return carry_dependences(ctx, graph);
2636                 }
2637                 if (update_schedule(graph, sol, 1, 1) < 0)
2638                         return -1;
2639                 force_zero = 0;
2640         }
2641
2642         if (graph->n_total_row > graph->band_start)
2643                 next_band(graph);
2644         return sort_statements(ctx, graph);
2645 }
2646
2647 /* Add a row to the schedules that separates the SCCs and move
2648  * to the next band.
2649  */
2650 static int split_on_scc(struct isl_sched_graph *graph)
2651 {
2652         int i;
2653
2654         for (i = 0; i < graph->n; ++i) {
2655                 struct isl_sched_node *node = &graph->node[i];
2656                 int row = isl_mat_rows(node->sched);
2657
2658                 isl_map_free(node->sched_map);
2659                 node->sched_map = NULL;
2660                 node->sched = isl_mat_add_zero_rows(node->sched, 1);
2661                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
2662                                                      node->scc);
2663                 if (!node->sched)
2664                         return -1;
2665                 node->band[graph->n_total_row] = graph->n_band;
2666         }
2667
2668         graph->n_total_row++;
2669         next_band(graph);
2670
2671         return 0;
2672 }
2673
2674 /* Compute a schedule for each component (identified by node->scc)
2675  * of the dependence graph separately and then combine the results.
2676  * Depending on the setting of schedule_fuse, a component may be
2677  * either weakly or strongly connected.
2678  *
2679  * The band_id is adjusted such that each component has a separate id.
2680  * Note that the band_id may have already been set to a value different
2681  * from zero by compute_split_schedule.
2682  */
2683 static int compute_component_schedule(isl_ctx *ctx,
2684         struct isl_sched_graph *graph)
2685 {
2686         int wcc, i;
2687         int n, n_edge;
2688         int n_total_row, orig_total_row;
2689         int n_band, orig_band;
2690
2691         if (ctx->opt->schedule_fuse == ISL_SCHEDULE_FUSE_MIN ||
2692             ctx->opt->schedule_separate_components)
2693                 split_on_scc(graph);
2694
2695         n_total_row = 0;
2696         orig_total_row = graph->n_total_row;
2697         n_band = 0;
2698         orig_band = graph->n_band;
2699         for (i = 0; i < graph->n; ++i)
2700                 graph->node[i].band_id[graph->n_band] += graph->node[i].scc;
2701         for (wcc = 0; wcc < graph->scc; ++wcc) {
2702                 n = 0;
2703                 for (i = 0; i < graph->n; ++i)
2704                         if (graph->node[i].scc == wcc)
2705                                 n++;
2706                 n_edge = 0;
2707                 for (i = 0; i < graph->n_edge; ++i)
2708                         if (graph->edge[i].src->scc == wcc &&
2709                             graph->edge[i].dst->scc == wcc)
2710                                 n_edge++;
2711
2712                 if (compute_sub_schedule(ctx, graph, n, n_edge,
2713                                     &node_scc_exactly,
2714                                     &edge_scc_exactly, wcc, 1) < 0)
2715                         return -1;
2716                 if (graph->n_total_row > n_total_row)
2717                         n_total_row = graph->n_total_row;
2718                 graph->n_total_row = orig_total_row;
2719                 if (graph->n_band > n_band)
2720                         n_band = graph->n_band;
2721                 graph->n_band = orig_band;
2722         }
2723
2724         graph->n_total_row = n_total_row;
2725         graph->n_band = n_band;
2726
2727         return pad_schedule(graph);
2728 }
2729
2730 /* Compute a schedule for the given dependence graph.
2731  * We first check if the graph is connected (through validity dependences)
2732  * and, if not, compute a schedule for each component separately.
2733  * If schedule_fuse is set to minimal fusion, then we check for strongly
2734  * connected components instead and compute a separate schedule for
2735  * each such strongly connected component.
2736  */
2737 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
2738 {
2739         if (ctx->opt->schedule_fuse == ISL_SCHEDULE_FUSE_MIN) {
2740                 if (detect_sccs(ctx, graph) < 0)
2741                         return -1;
2742         } else {
2743                 if (detect_wccs(ctx, graph) < 0)
2744                         return -1;
2745         }
2746
2747         if (graph->scc > 1)
2748                 return compute_component_schedule(ctx, graph);
2749
2750         return compute_schedule_wcc(ctx, graph);
2751 }
2752
2753 /* Compute a schedule for the given union of domains that respects
2754  * all the validity dependences.
2755  * If the default isl scheduling algorithm is used, it tries to minimize
2756  * the dependence distances over the proximity dependences.
2757  * If Feautrier's scheduling algorithm is used, the proximity dependence
2758  * distances are only minimized during the extension to a full-dimensional
2759  * schedule.
2760  */
2761 __isl_give isl_schedule *isl_union_set_compute_schedule(
2762         __isl_take isl_union_set *domain,
2763         __isl_take isl_union_map *validity,
2764         __isl_take isl_union_map *proximity)
2765 {
2766         isl_ctx *ctx = isl_union_set_get_ctx(domain);
2767         isl_space *dim;
2768         struct isl_sched_graph graph = { 0 };
2769         isl_schedule *sched;
2770         struct isl_extract_edge_data data;
2771
2772         domain = isl_union_set_align_params(domain,
2773                                             isl_union_map_get_space(validity));
2774         domain = isl_union_set_align_params(domain,
2775                                             isl_union_map_get_space(proximity));
2776         dim = isl_union_set_get_space(domain);
2777         validity = isl_union_map_align_params(validity, isl_space_copy(dim));
2778         proximity = isl_union_map_align_params(proximity, dim);
2779
2780         if (!domain)
2781                 goto error;
2782
2783         graph.n = isl_union_set_n_set(domain);
2784         if (graph.n == 0)
2785                 goto empty;
2786         if (graph_alloc(ctx, &graph, graph.n,
2787             isl_union_map_n_map(validity) + isl_union_map_n_map(proximity)) < 0)
2788                 goto error;
2789         if (compute_max_row(&graph, domain) < 0)
2790                 goto error;
2791         graph.root = 1;
2792         graph.n = 0;
2793         if (isl_union_set_foreach_set(domain, &extract_node, &graph) < 0)
2794                 goto error;
2795         if (graph_init_table(ctx, &graph) < 0)
2796                 goto error;
2797         graph.max_edge[isl_edge_validity] = isl_union_map_n_map(validity);
2798         graph.max_edge[isl_edge_proximity] = isl_union_map_n_map(proximity);
2799         if (graph_init_edge_tables(ctx, &graph) < 0)
2800                 goto error;
2801         graph.n_edge = 0;
2802         data.graph = &graph;
2803         data.type = isl_edge_validity;
2804         if (isl_union_map_foreach_map(validity, &extract_edge, &data) < 0)
2805                 goto error;
2806         data.type = isl_edge_proximity;
2807         if (isl_union_map_foreach_map(proximity, &extract_edge, &data) < 0)
2808                 goto error;
2809
2810         if (compute_schedule(ctx, &graph) < 0)
2811                 goto error;
2812
2813 empty:
2814         sched = extract_schedule(&graph, isl_union_set_get_space(domain));
2815
2816         graph_free(ctx, &graph);
2817         isl_union_set_free(domain);
2818         isl_union_map_free(validity);
2819         isl_union_map_free(proximity);
2820
2821         return sched;
2822 error:
2823         graph_free(ctx, &graph);
2824         isl_union_set_free(domain);
2825         isl_union_map_free(validity);
2826         isl_union_map_free(proximity);
2827         return NULL;
2828 }
2829
2830 void *isl_schedule_free(__isl_take isl_schedule *sched)
2831 {
2832         int i;
2833         if (!sched)
2834                 return NULL;
2835
2836         if (--sched->ref > 0)
2837                 return NULL;
2838
2839         for (i = 0; i < sched->n; ++i) {
2840                 isl_multi_aff_free(sched->node[i].sched);
2841                 free(sched->node[i].band_end);
2842                 free(sched->node[i].band_id);
2843                 free(sched->node[i].zero);
2844         }
2845         isl_space_free(sched->dim);
2846         isl_band_list_free(sched->band_forest);
2847         free(sched);
2848         return NULL;
2849 }
2850
2851 isl_ctx *isl_schedule_get_ctx(__isl_keep isl_schedule *schedule)
2852 {
2853         return schedule ? isl_space_get_ctx(schedule->dim) : NULL;
2854 }
2855
2856 /* Return an isl_union_map of the schedule.  If we have already constructed
2857  * a band forest, then this band forest may have been modified so we need
2858  * to extract the isl_union_map from the forest rather than from
2859  * the originally computed schedule.
2860  */
2861 __isl_give isl_union_map *isl_schedule_get_map(__isl_keep isl_schedule *sched)
2862 {
2863         int i;
2864         isl_union_map *umap;
2865
2866         if (!sched)
2867                 return NULL;
2868
2869         if (sched->band_forest)
2870                 return isl_band_list_get_suffix_schedule(sched->band_forest);
2871
2872         umap = isl_union_map_empty(isl_space_copy(sched->dim));
2873         for (i = 0; i < sched->n; ++i) {
2874                 isl_multi_aff *ma;
2875
2876                 ma = isl_multi_aff_copy(sched->node[i].sched);
2877                 umap = isl_union_map_add_map(umap, isl_map_from_multi_aff(ma));
2878         }
2879
2880         return umap;
2881 }
2882
2883 static __isl_give isl_band_list *construct_band_list(
2884         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
2885         int band_nr, int *parent_active, int n_active);
2886
2887 /* Construct an isl_band structure for the band in the given schedule
2888  * with sequence number band_nr for the n_active nodes marked by active.
2889  * If the nodes don't have a band with the given sequence number,
2890  * then a band without members is created.
2891  *
2892  * Because of the way the schedule is constructed, we know that
2893  * the position of the band inside the schedule of a node is the same
2894  * for all active nodes.
2895  */
2896 static __isl_give isl_band *construct_band(__isl_keep isl_schedule *schedule,
2897         __isl_keep isl_band *parent,
2898         int band_nr, int *active, int n_active)
2899 {
2900         int i, j;
2901         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2902         isl_band *band;
2903         unsigned start, end;
2904
2905         band = isl_band_alloc(ctx);
2906         if (!band)
2907                 return NULL;
2908
2909         band->schedule = schedule;
2910         band->parent = parent;
2911
2912         for (i = 0; i < schedule->n; ++i)
2913                 if (active[i] && schedule->node[i].n_band > band_nr + 1)
2914                         break;
2915
2916         if (i < schedule->n) {
2917                 band->children = construct_band_list(schedule, band,
2918                                                 band_nr + 1, active, n_active);
2919                 if (!band->children)
2920                         goto error;
2921         }
2922
2923         for (i = 0; i < schedule->n; ++i)
2924                 if (active[i])
2925                         break;
2926
2927         if (i >= schedule->n)
2928                 isl_die(ctx, isl_error_internal,
2929                         "band without active statements", goto error);
2930
2931         start = band_nr ? schedule->node[i].band_end[band_nr - 1] : 0;
2932         end = band_nr < schedule->node[i].n_band ?
2933                 schedule->node[i].band_end[band_nr] : start;
2934         band->n = end - start;
2935
2936         band->zero = isl_alloc_array(ctx, int, band->n);
2937         if (!band->zero)
2938                 goto error;
2939
2940         for (j = 0; j < band->n; ++j)
2941                 band->zero[j] = schedule->node[i].zero[start + j];
2942
2943         band->pma = isl_union_pw_multi_aff_empty(isl_space_copy(schedule->dim));
2944         for (i = 0; i < schedule->n; ++i) {
2945                 isl_multi_aff *ma;
2946                 isl_pw_multi_aff *pma;
2947                 unsigned n_out;
2948
2949                 if (!active[i])
2950                         continue;
2951
2952                 ma = isl_multi_aff_copy(schedule->node[i].sched);
2953                 n_out = isl_multi_aff_dim(ma, isl_dim_out);
2954                 ma = isl_multi_aff_drop_dims(ma, isl_dim_out, end, n_out - end);
2955                 ma = isl_multi_aff_drop_dims(ma, isl_dim_out, 0, start);
2956                 pma = isl_pw_multi_aff_from_multi_aff(ma);
2957                 band->pma = isl_union_pw_multi_aff_add_pw_multi_aff(band->pma,
2958                                                                     pma);
2959         }
2960         if (!band->pma)
2961                 goto error;
2962
2963         return band;
2964 error:
2965         isl_band_free(band);
2966         return NULL;
2967 }
2968
2969 /* Construct a list of bands that start at the same position (with
2970  * sequence number band_nr) in the schedules of the nodes that
2971  * were active in the parent band.
2972  *
2973  * A separate isl_band structure is created for each band_id
2974  * and for each node that does not have a band with sequence
2975  * number band_nr.  In the latter case, a band without members
2976  * is created.
2977  * This ensures that if a band has any children, then each node
2978  * that was active in the band is active in exactly one of the children.
2979  */
2980 static __isl_give isl_band_list *construct_band_list(
2981         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
2982         int band_nr, int *parent_active, int n_active)
2983 {
2984         int i, j;
2985         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2986         int *active;
2987         int n_band;
2988         isl_band_list *list;
2989
2990         n_band = 0;
2991         for (i = 0; i < n_active; ++i) {
2992                 for (j = 0; j < schedule->n; ++j) {
2993                         if (!parent_active[j])
2994                                 continue;
2995                         if (schedule->node[j].n_band <= band_nr)
2996                                 continue;
2997                         if (schedule->node[j].band_id[band_nr] == i) {
2998                                 n_band++;
2999                                 break;
3000                         }
3001                 }
3002         }
3003         for (j = 0; j < schedule->n; ++j)
3004                 if (schedule->node[j].n_band <= band_nr)
3005                         n_band++;
3006
3007         if (n_band == 1) {
3008                 isl_band *band;
3009                 list = isl_band_list_alloc(ctx, n_band);
3010                 band = construct_band(schedule, parent, band_nr,
3011                                         parent_active, n_active);
3012                 return isl_band_list_add(list, band);
3013         }
3014
3015         active = isl_alloc_array(ctx, int, schedule->n);
3016         if (!active)
3017                 return NULL;
3018
3019         list = isl_band_list_alloc(ctx, n_band);
3020
3021         for (i = 0; i < n_active; ++i) {
3022                 int n = 0;
3023                 isl_band *band;
3024
3025                 for (j = 0; j < schedule->n; ++j) {
3026                         active[j] = parent_active[j] &&
3027                                         schedule->node[j].n_band > band_nr &&
3028                                         schedule->node[j].band_id[band_nr] == i;
3029                         if (active[j])
3030                                 n++;
3031                 }
3032                 if (n == 0)
3033                         continue;
3034
3035                 band = construct_band(schedule, parent, band_nr, active, n);
3036
3037                 list = isl_band_list_add(list, band);
3038         }
3039         for (i = 0; i < schedule->n; ++i) {
3040                 isl_band *band;
3041                 if (!parent_active[i])
3042                         continue;
3043                 if (schedule->node[i].n_band > band_nr)
3044                         continue;
3045                 for (j = 0; j < schedule->n; ++j)
3046                         active[j] = j == i;
3047                 band = construct_band(schedule, parent, band_nr, active, 1);
3048                 list = isl_band_list_add(list, band);
3049         }
3050
3051         free(active);
3052
3053         return list;
3054 }
3055
3056 /* Construct a band forest representation of the schedule and
3057  * return the list of roots.
3058  */
3059 static __isl_give isl_band_list *construct_forest(
3060         __isl_keep isl_schedule *schedule)
3061 {
3062         int i;
3063         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
3064         isl_band_list *forest;
3065         int *active;
3066
3067         active = isl_alloc_array(ctx, int, schedule->n);
3068         if (!active)
3069                 return NULL;
3070
3071         for (i = 0; i < schedule->n; ++i)
3072                 active[i] = 1;
3073
3074         forest = construct_band_list(schedule, NULL, 0, active, schedule->n);
3075
3076         free(active);
3077
3078         return forest;
3079 }
3080
3081 /* Return the roots of a band forest representation of the schedule.
3082  */
3083 __isl_give isl_band_list *isl_schedule_get_band_forest(
3084         __isl_keep isl_schedule *schedule)
3085 {
3086         if (!schedule)
3087                 return NULL;
3088         if (!schedule->band_forest)
3089                 schedule->band_forest = construct_forest(schedule);
3090         return isl_band_list_dup(schedule->band_forest);
3091 }
3092
3093 /* Call "fn" on each band in the schedule in depth-first post-order.
3094  */
3095 int isl_schedule_foreach_band(__isl_keep isl_schedule *sched,
3096         int (*fn)(__isl_keep isl_band *band, void *user), void *user)
3097 {
3098         int r;
3099         isl_band_list *forest;
3100
3101         if (!sched)
3102                 return -1;
3103
3104         forest = isl_schedule_get_band_forest(sched);
3105         r = isl_band_list_foreach_band(forest, fn, user);
3106         isl_band_list_free(forest);
3107
3108         return r;
3109 }
3110
3111 static __isl_give isl_printer *print_band_list(__isl_take isl_printer *p,
3112         __isl_keep isl_band_list *list);
3113
3114 static __isl_give isl_printer *print_band(__isl_take isl_printer *p,
3115         __isl_keep isl_band *band)
3116 {
3117         isl_band_list *children;
3118
3119         p = isl_printer_start_line(p);
3120         p = isl_printer_print_union_pw_multi_aff(p, band->pma);
3121         p = isl_printer_end_line(p);
3122
3123         if (!isl_band_has_children(band))
3124                 return p;
3125
3126         children = isl_band_get_children(band);
3127
3128         p = isl_printer_indent(p, 4);
3129         p = print_band_list(p, children);
3130         p = isl_printer_indent(p, -4);
3131
3132         isl_band_list_free(children);
3133
3134         return p;
3135 }
3136
3137 static __isl_give isl_printer *print_band_list(__isl_take isl_printer *p,
3138         __isl_keep isl_band_list *list)
3139 {
3140         int i, n;
3141
3142         n = isl_band_list_n_band(list);
3143         for (i = 0; i < n; ++i) {
3144                 isl_band *band;
3145                 band = isl_band_list_get_band(list, i);
3146                 p = print_band(p, band);
3147                 isl_band_free(band);
3148         }
3149
3150         return p;
3151 }
3152
3153 __isl_give isl_printer *isl_printer_print_schedule(__isl_take isl_printer *p,
3154         __isl_keep isl_schedule *schedule)
3155 {
3156         isl_band_list *forest;
3157
3158         forest = isl_schedule_get_band_forest(schedule);
3159
3160         p = print_band_list(p, forest);
3161
3162         isl_band_list_free(forest);
3163
3164         return p;
3165 }
3166
3167 void isl_schedule_dump(__isl_keep isl_schedule *schedule)
3168 {
3169         isl_printer *printer;
3170
3171         if (!schedule)
3172                 return;
3173
3174         printer = isl_printer_to_file(isl_schedule_get_ctx(schedule), stderr);
3175         printer = isl_printer_print_schedule(printer, schedule);
3176
3177         isl_printer_free(printer);
3178 }