isl_map_transitive_closure, omega-like: only use ?-closure if result is exact
[platform/upstream/isl.git] / isl_transitive_closure.c
1 /*
2  * Copyright 2010      INRIA Saclay
3  *
4  * Use of this software is governed by the GNU LGPLv2.1 license
5  *
6  * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
7  * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
8  * 91893 Orsay, France 
9  */
10
11 #include "isl_map.h"
12 #include "isl_map_private.h"
13 #include "isl_seq.h"
14 #include <isl_lp.h>
15  
16 /* Given a map that represents a path with the length of the path
17  * encoded as the difference between the last output coordindate
18  * and the last input coordinate, set this length to either
19  * exactly "length" (if "exactly" is set) or at least "length"
20  * (if "exactly" is not set).
21  */
22 static __isl_give isl_map *set_path_length(__isl_take isl_map *map,
23         int exactly, int length)
24 {
25         struct isl_dim *dim;
26         struct isl_basic_map *bmap;
27         unsigned d;
28         unsigned nparam;
29         int k;
30         isl_int *c;
31
32         if (!map)
33                 return NULL;
34
35         dim = isl_map_get_dim(map);
36         d = isl_dim_size(dim, isl_dim_in);
37         nparam = isl_dim_size(dim, isl_dim_param);
38         bmap = isl_basic_map_alloc_dim(dim, 0, 1, 1);
39         if (exactly) {
40                 k = isl_basic_map_alloc_equality(bmap);
41                 c = bmap->eq[k];
42         } else {
43                 k = isl_basic_map_alloc_inequality(bmap);
44                 c = bmap->ineq[k];
45         }
46         if (k < 0)
47                 goto error;
48         isl_seq_clr(c, 1 + isl_basic_map_total_dim(bmap));
49         isl_int_set_si(c[0], -length);
50         isl_int_set_si(c[1 + nparam + d - 1], -1);
51         isl_int_set_si(c[1 + nparam + d + d - 1], 1);
52
53         bmap = isl_basic_map_finalize(bmap);
54         map = isl_map_intersect(map, isl_map_from_basic_map(bmap));
55
56         return map;
57 error:
58         isl_basic_map_free(bmap);
59         isl_map_free(map);
60         return NULL;
61 }
62
63 /* Check whether the overapproximation of the power of "map" is exactly
64  * the power of "map".  Let R be "map" and A_k the overapproximation.
65  * The approximation is exact if
66  *
67  *      A_1 = R
68  *      A_k = A_{k-1} \circ R                   k >= 2
69  *
70  * Since A_k is known to be an overapproximation, we only need to check
71  *
72  *      A_1 \subset R
73  *      A_k \subset A_{k-1} \circ R             k >= 2
74  *
75  * In practice, "app" has an extra input and output coordinate
76  * to encode the length of the path.  So, we first need to add
77  * this coordinate to "map" and set the length of the path to
78  * one.
79  */
80 static int check_power_exactness(__isl_take isl_map *map,
81         __isl_take isl_map *app)
82 {
83         int exact;
84         isl_map *app_1;
85         isl_map *app_2;
86
87         map = isl_map_add(map, isl_dim_in, 1);
88         map = isl_map_add(map, isl_dim_out, 1);
89         map = set_path_length(map, 1, 1);
90
91         app_1 = set_path_length(isl_map_copy(app), 1, 1);
92
93         exact = isl_map_is_subset(app_1, map);
94         isl_map_free(app_1);
95
96         if (!exact || exact < 0) {
97                 isl_map_free(app);
98                 isl_map_free(map);
99                 return exact;
100         }
101
102         app_1 = set_path_length(isl_map_copy(app), 0, 1);
103         app_2 = set_path_length(app, 0, 2);
104         app_1 = isl_map_apply_range(map, app_1);
105
106         exact = isl_map_is_subset(app_2, app_1);
107
108         isl_map_free(app_1);
109         isl_map_free(app_2);
110
111         return exact;
112 }
113
114 /* Check whether the overapproximation of the power of "map" is exactly
115  * the power of "map", possibly after projecting out the power (if "project"
116  * is set).
117  *
118  * If "project" is set and if "steps" can only result in acyclic paths,
119  * then we check
120  *
121  *      A = R \cup (A \circ R)
122  *
123  * where A is the overapproximation with the power projected out, i.e.,
124  * an overapproximation of the transitive closure.
125  * More specifically, since A is known to be an overapproximation, we check
126  *
127  *      A \subset R \cup (A \circ R)
128  *
129  * Otherwise, we check if the power is exact.
130  *
131  * Note that "app" has an extra input and output coordinate to encode
132  * the length of the part.  If we are only interested in the transitive
133  * closure, then we can simply project out these coordinates first.
134  */
135 static int check_exactness(__isl_take isl_map *map, __isl_take isl_map *app,
136         int project)
137 {
138         isl_map *test;
139         int exact;
140         unsigned d;
141
142         if (!project)
143                 return check_power_exactness(map, app);
144
145         d = isl_map_dim(map, isl_dim_in);
146         app = set_path_length(app, 0, 1);
147         app = isl_map_project_out(app, isl_dim_in, d, 1);
148         app = isl_map_project_out(app, isl_dim_out, d, 1);
149
150         test = isl_map_apply_range(isl_map_copy(map), isl_map_copy(app));
151         test = isl_map_union(test, isl_map_copy(map));
152
153         exact = isl_map_is_subset(app, test);
154
155         isl_map_free(app);
156         isl_map_free(test);
157
158         isl_map_free(map);
159
160         return exact;
161 error:
162         isl_map_free(app);
163         isl_map_free(map);
164         return -1;
165 }
166
167 /*
168  * The transitive closure implementation is based on the paper
169  * "Computing the Transitive Closure of a Union of Affine Integer
170  * Tuple Relations" by Anna Beletska, Denis Barthou, Wlodzimierz Bielecki and
171  * Albert Cohen.
172  */
173
174 /* Given a set of n offsets v_i (the rows of "steps"), construct a relation
175  * of the given dimension specification (Z^{n+1} -> Z^{n+1})
176  * that maps an element x to any element that can be reached
177  * by taking a non-negative number of steps along any of
178  * the extended offsets v'_i = [v_i 1].
179  * That is, construct
180  *
181  * { [x] -> [y] : exists k_i >= 0, y = x + \sum_i k_i v'_i }
182  *
183  * For any element in this relation, the number of steps taken
184  * is equal to the difference in the final coordinates.
185  */
186 static __isl_give isl_map *path_along_steps(__isl_take isl_dim *dim,
187         __isl_keep isl_mat *steps)
188 {
189         int i, j, k;
190         struct isl_basic_map *path = NULL;
191         unsigned d;
192         unsigned n;
193         unsigned nparam;
194
195         if (!dim || !steps)
196                 goto error;
197
198         d = isl_dim_size(dim, isl_dim_in);
199         n = steps->n_row;
200         nparam = isl_dim_size(dim, isl_dim_param);
201
202         path = isl_basic_map_alloc_dim(isl_dim_copy(dim), n, d, n);
203
204         for (i = 0; i < n; ++i) {
205                 k = isl_basic_map_alloc_div(path);
206                 if (k < 0)
207                         goto error;
208                 isl_assert(steps->ctx, i == k, goto error);
209                 isl_int_set_si(path->div[k][0], 0);
210         }
211
212         for (i = 0; i < d; ++i) {
213                 k = isl_basic_map_alloc_equality(path);
214                 if (k < 0)
215                         goto error;
216                 isl_seq_clr(path->eq[k], 1 + isl_basic_map_total_dim(path));
217                 isl_int_set_si(path->eq[k][1 + nparam + i], 1);
218                 isl_int_set_si(path->eq[k][1 + nparam + d + i], -1);
219                 if (i == d - 1)
220                         for (j = 0; j < n; ++j)
221                                 isl_int_set_si(path->eq[k][1 + nparam + 2 * d + j], 1);
222                 else
223                         for (j = 0; j < n; ++j)
224                                 isl_int_set(path->eq[k][1 + nparam + 2 * d + j],
225                                             steps->row[j][i]);
226         }
227
228         for (i = 0; i < n; ++i) {
229                 k = isl_basic_map_alloc_inequality(path);
230                 if (k < 0)
231                         goto error;
232                 isl_seq_clr(path->ineq[k], 1 + isl_basic_map_total_dim(path));
233                 isl_int_set_si(path->ineq[k][1 + nparam + 2 * d + i], 1);
234         }
235
236         isl_dim_free(dim);
237
238         path = isl_basic_map_simplify(path);
239         path = isl_basic_map_finalize(path);
240         return isl_map_from_basic_map(path);
241 error:
242         isl_dim_free(dim);
243         isl_basic_map_free(path);
244         return NULL;
245 }
246
247 #define IMPURE          0
248 #define PURE_PARAM      1
249 #define PURE_VAR        2
250 #define MIXED           3
251
252 /* Return PURE_PARAM if only the coefficients of the parameters are non-zero.
253  * Return PURE_VAR if only the coefficients of the set variables are non-zero.
254  * Return MIXED if only the coefficients of the parameters and the set
255  *      variables are non-zero and if moreover the parametric constant
256  *      can never attain positive values.
257  * Return IMPURE otherwise.
258  */
259 static int purity(__isl_keep isl_basic_set *bset, isl_int *c, int *div_purity,
260         int eq)
261 {
262         unsigned d;
263         unsigned n_div;
264         unsigned nparam;
265         int k;
266         int empty;
267         int i;
268         int p = 0, v = 0;
269
270         n_div = isl_basic_set_dim(bset, isl_dim_div);
271         d = isl_basic_set_dim(bset, isl_dim_set);
272         nparam = isl_basic_set_dim(bset, isl_dim_param);
273
274         for (i = 0; i < n_div; ++i) {
275                 if (isl_int_is_zero(c[1 + nparam + d + i]))
276                         continue;
277                 switch (div_purity[i]) {
278                 case PURE_PARAM: p = 1; break;
279                 case PURE_VAR: v = 1; break;
280                 default: return IMPURE;
281                 }
282         }
283         if (!p && isl_seq_first_non_zero(c + 1, nparam) == -1)
284                 return PURE_VAR;
285         if (!v && isl_seq_first_non_zero(c + 1 + nparam, d) == -1)
286                 return PURE_PARAM;
287         if (eq)
288                 return IMPURE;
289
290         bset = isl_basic_set_copy(bset);
291         bset = isl_basic_set_cow(bset);
292         bset = isl_basic_set_extend_constraints(bset, 0, 1);
293         k = isl_basic_set_alloc_inequality(bset);
294         if (k < 0)
295                 goto error;
296         isl_seq_clr(bset->ineq[k], 1 + isl_basic_set_total_dim(bset));
297         isl_seq_cpy(bset->ineq[k], c, 1 + nparam);
298         for (i = 0; i < n_div; ++i) {
299                 if (div_purity[i] != PURE_PARAM)
300                         continue;
301                 isl_int_set(bset->ineq[k][1 + nparam + d + i],
302                             c[1 + nparam + d + i]);
303         }
304         isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
305         empty = isl_basic_set_is_empty(bset);
306         isl_basic_set_free(bset);
307
308         return empty < 0 ? -1 : empty ? MIXED : IMPURE;
309 error:
310         isl_basic_set_free(bset);
311         return -1;
312 }
313
314 /* Return an array of integers indicating the type of each div in bset.
315  * If the div is (recursively) defined in terms of only the parameters,
316  * then the type is PURE_PARAM.
317  * If the div is (recursively) defined in terms of only the set variables,
318  * then the type is PURE_VAR.
319  * Otherwise, the type is IMPURE.
320  */
321 static __isl_give int *get_div_purity(__isl_keep isl_basic_set *bset)
322 {
323         int i, j;
324         int *div_purity;
325         unsigned d;
326         unsigned n_div;
327         unsigned nparam;
328
329         if (!bset)
330                 return NULL;
331
332         n_div = isl_basic_set_dim(bset, isl_dim_div);
333         d = isl_basic_set_dim(bset, isl_dim_set);
334         nparam = isl_basic_set_dim(bset, isl_dim_param);
335
336         div_purity = isl_alloc_array(bset->ctx, int, n_div);
337         if (!div_purity)
338                 return NULL;
339
340         for (i = 0; i < bset->n_div; ++i) {
341                 int p = 0, v = 0;
342                 if (isl_int_is_zero(bset->div[i][0])) {
343                         div_purity[i] = IMPURE;
344                         continue;
345                 }
346                 if (isl_seq_first_non_zero(bset->div[i] + 2, nparam) != -1)
347                         p = 1;
348                 if (isl_seq_first_non_zero(bset->div[i] + 2 + nparam, d) != -1)
349                         v = 1;
350                 for (j = 0; j < i; ++j) {
351                         if (isl_int_is_zero(bset->div[i][2 + nparam + d + j]))
352                                 continue;
353                         switch (div_purity[j]) {
354                         case PURE_PARAM: p = 1; break;
355                         case PURE_VAR: v = 1; break;
356                         default: p = v = 1; break;
357                         }
358                 }
359                 div_purity[i] = v ? p ? IMPURE : PURE_VAR : PURE_PARAM;
360         }
361
362         return div_purity;
363 }
364
365 /* Given a path with the as yet unconstrained length at position "pos",
366  * check if setting the length to zero results in only the identity
367  * mapping.
368  */
369 int empty_path_is_identity(__isl_keep isl_basic_map *path, unsigned pos)
370 {
371         isl_basic_map *test = NULL;
372         isl_basic_map *id = NULL;
373         int k;
374         int is_id;
375
376         test = isl_basic_map_copy(path);
377         test = isl_basic_map_extend_constraints(test, 1, 0);
378         k = isl_basic_map_alloc_equality(test);
379         if (k < 0)
380                 goto error;
381         isl_seq_clr(test->eq[k], 1 + isl_basic_map_total_dim(test));
382         isl_int_set_si(test->eq[k][pos], 1);
383         id = isl_basic_map_identity(isl_dim_domain(isl_basic_map_get_dim(path)));
384         is_id = isl_basic_map_is_equal(test, id);
385         isl_basic_map_free(test);
386         isl_basic_map_free(id);
387         return is_id;
388 error:
389         isl_basic_map_free(test);
390         return -1;
391 }
392
393 __isl_give isl_basic_map *add_delta_constraints(__isl_take isl_basic_map *path,
394         __isl_keep isl_basic_set *delta, unsigned off, unsigned nparam,
395         unsigned d, int *div_purity, int eq)
396 {
397         int i, k;
398         int n = eq ? delta->n_eq : delta->n_ineq;
399         isl_int **delta_c = eq ? delta->eq : delta->ineq;
400         isl_int **path_c = eq ? path->eq : path->ineq;
401         unsigned n_div;
402
403         n_div = isl_basic_set_dim(delta, isl_dim_div);
404
405         for (i = 0; i < n; ++i) {
406                 int p = purity(delta, delta_c[i], div_purity, eq);
407                 if (p < 0)
408                         goto error;
409                 if (p == IMPURE)
410                         continue;
411                 if (eq)
412                         k = isl_basic_map_alloc_equality(path);
413                 else
414                         k = isl_basic_map_alloc_inequality(path);
415                 if (k < 0)
416                         goto error;
417                 isl_seq_clr(path_c[k], 1 + isl_basic_map_total_dim(path));
418                 if (p == PURE_VAR) {
419                         isl_seq_cpy(path_c[k] + off,
420                                     delta_c[i] + 1 + nparam, d);
421                         isl_int_set(path_c[k][off + d], delta_c[i][0]);
422                 } else if (p == PURE_PARAM) {
423                         isl_seq_cpy(path_c[k], delta_c[i], 1 + nparam);
424                 } else {
425                         isl_seq_cpy(path_c[k] + off,
426                                     delta_c[i] + 1 + nparam, d);
427                         isl_seq_cpy(path_c[k], delta_c[i], 1 + nparam);
428                 }
429                 isl_seq_cpy(path_c[k] + off - n_div,
430                             delta_c[i] + 1 + nparam + d, n_div);
431         }
432
433         return path;
434 error:
435         isl_basic_map_free(path);
436         return NULL;
437 }
438
439 /* Given a set of offsets "delta", construct a relation of the
440  * given dimension specification (Z^{n+1} -> Z^{n+1}) that
441  * is an overapproximation of the relations that
442  * maps an element x to any element that can be reached
443  * by taking a non-negative number of steps along any of
444  * the elements in "delta".
445  * That is, construct an approximation of
446  *
447  *      { [x] -> [y] : exists f \in \delta, k \in Z :
448  *                                      y = x + k [f, 1] and k >= 0 }
449  *
450  * For any element in this relation, the number of steps taken
451  * is equal to the difference in the final coordinates.
452  *
453  * In particular, let delta be defined as
454  *
455  *      \delta = [p] -> { [x] : A x + a >= and B p + b >= 0 and
456  *                              C x + C'p + c >= 0 and
457  *                              D x + D'p + d >= 0 }
458  *
459  * where the constraints C x + C'p + c >= 0 are such that the parametric
460  * constant term of each constraint j, "C_j x + C'_j p + c_j",
461  * can never attain positive values, then the relation is constructed as
462  *
463  *      { [x] -> [y] : exists [f, k] \in Z^{n+1} : y = x + f and
464  *                      A f + k a >= 0 and B p + b >= 0 and
465  *                      C f + C'p + c >= 0 and k >= 1 }
466  *      union { [x] -> [x] }
467  *
468  * If the zero-length paths happen to correspond exactly to the identity
469  * mapping, then we return
470  *
471  *      { [x] -> [y] : exists [f, k] \in Z^{n+1} : y = x + f and
472  *                      A f + k a >= 0 and B p + b >= 0 and
473  *                      C f + C'p + c >= 0 and k >= 0 }
474  *
475  * instead.
476  *
477  * Existentially quantified variables in \delta are handled by
478  * classifying them as independent of the parameters, purely
479  * parameter dependent and others.  Constraints containing
480  * any of the other existentially quantified variables are removed.
481  * This is safe, but leads to an additional overapproximation.
482  */
483 static __isl_give isl_map *path_along_delta(__isl_take isl_dim *dim,
484         __isl_take isl_basic_set *delta)
485 {
486         isl_basic_map *path = NULL;
487         unsigned d;
488         unsigned n_div;
489         unsigned nparam;
490         unsigned off;
491         int i, k;
492         int is_id;
493         int *div_purity = NULL;
494
495         if (!delta)
496                 goto error;
497         n_div = isl_basic_set_dim(delta, isl_dim_div);
498         d = isl_basic_set_dim(delta, isl_dim_set);
499         nparam = isl_basic_set_dim(delta, isl_dim_param);
500         path = isl_basic_map_alloc_dim(isl_dim_copy(dim), n_div + d + 1,
501                         d + 1 + delta->n_eq, delta->n_ineq + 1);
502         off = 1 + nparam + 2 * (d + 1) + n_div;
503
504         for (i = 0; i < n_div + d + 1; ++i) {
505                 k = isl_basic_map_alloc_div(path);
506                 if (k < 0)
507                         goto error;
508                 isl_int_set_si(path->div[k][0], 0);
509         }
510
511         for (i = 0; i < d + 1; ++i) {
512                 k = isl_basic_map_alloc_equality(path);
513                 if (k < 0)
514                         goto error;
515                 isl_seq_clr(path->eq[k], 1 + isl_basic_map_total_dim(path));
516                 isl_int_set_si(path->eq[k][1 + nparam + i], 1);
517                 isl_int_set_si(path->eq[k][1 + nparam + d + 1 + i], -1);
518                 isl_int_set_si(path->eq[k][off + i], 1);
519         }
520
521         div_purity = get_div_purity(delta);
522         if (!div_purity)
523                 goto error;
524
525         path = add_delta_constraints(path, delta, off, nparam, d, div_purity, 1);
526         path = add_delta_constraints(path, delta, off, nparam, d, div_purity, 0);
527
528         is_id = empty_path_is_identity(path, off + d);
529         if (is_id < 0)
530                 goto error;
531
532         k = isl_basic_map_alloc_inequality(path);
533         if (k < 0)
534                 goto error;
535         isl_seq_clr(path->ineq[k], 1 + isl_basic_map_total_dim(path));
536         if (!is_id)
537                 isl_int_set_si(path->ineq[k][0], -1);
538         isl_int_set_si(path->ineq[k][off + d], 1);
539                         
540         free(div_purity);
541         isl_basic_set_free(delta);
542         path = isl_basic_map_finalize(path);
543         if (is_id) {
544                 isl_dim_free(dim);
545                 return isl_map_from_basic_map(path);
546         }
547         return isl_basic_map_union(path,
548                                 isl_basic_map_identity(isl_dim_domain(dim)));
549 error:
550         free(div_purity);
551         isl_dim_free(dim);
552         isl_basic_set_free(delta);
553         isl_basic_map_free(path);
554         return NULL;
555 }
556
557 /* Given a dimenion specification Z^{n+1} -> Z^{n+1} and a parameter "param",
558  * construct a map that equates the parameter to the difference
559  * in the final coordinates and imposes that this difference is positive.
560  * That is, construct
561  *
562  *      { [x,x_s] -> [y,y_s] : k = y_s - x_s > 0 }
563  */
564 static __isl_give isl_map *equate_parameter_to_length(__isl_take isl_dim *dim,
565         unsigned param)
566 {
567         struct isl_basic_map *bmap;
568         unsigned d;
569         unsigned nparam;
570         int k;
571
572         d = isl_dim_size(dim, isl_dim_in);
573         nparam = isl_dim_size(dim, isl_dim_param);
574         bmap = isl_basic_map_alloc_dim(dim, 0, 1, 1);
575         k = isl_basic_map_alloc_equality(bmap);
576         if (k < 0)
577                 goto error;
578         isl_seq_clr(bmap->eq[k], 1 + isl_basic_map_total_dim(bmap));
579         isl_int_set_si(bmap->eq[k][1 + param], -1);
580         isl_int_set_si(bmap->eq[k][1 + nparam + d - 1], -1);
581         isl_int_set_si(bmap->eq[k][1 + nparam + d + d - 1], 1);
582
583         k = isl_basic_map_alloc_inequality(bmap);
584         if (k < 0)
585                 goto error;
586         isl_seq_clr(bmap->ineq[k], 1 + isl_basic_map_total_dim(bmap));
587         isl_int_set_si(bmap->ineq[k][1 + param], 1);
588         isl_int_set_si(bmap->ineq[k][0], -1);
589
590         bmap = isl_basic_map_finalize(bmap);
591         return isl_map_from_basic_map(bmap);
592 error:
593         isl_basic_map_free(bmap);
594         return NULL;
595 }
596
597 /* Check whether "path" is acyclic, where the last coordinates of domain
598  * and range of path encode the number of steps taken.
599  * That is, check whether
600  *
601  *      { d | d = y - x and (x,y) in path }
602  *
603  * does not contain any element with positive last coordinate (positive length)
604  * and zero remaining coordinates (cycle).
605  */
606 static int is_acyclic(__isl_take isl_map *path)
607 {
608         int i;
609         int acyclic;
610         unsigned dim;
611         struct isl_set *delta;
612
613         delta = isl_map_deltas(path);
614         dim = isl_set_dim(delta, isl_dim_set);
615         for (i = 0; i < dim; ++i) {
616                 if (i == dim -1)
617                         delta = isl_set_lower_bound_si(delta, isl_dim_set, i, 1);
618                 else
619                         delta = isl_set_fix_si(delta, isl_dim_set, i, 0);
620         }
621
622         acyclic = isl_set_is_empty(delta);
623         isl_set_free(delta);
624
625         return acyclic;
626 }
627
628 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
629  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
630  * construct a map that is an overapproximation of the map
631  * that takes an element from the space D \times Z to another
632  * element from the same space, such that the first n coordinates of the
633  * difference between them is a sum of differences between images
634  * and pre-images in one of the R_i and such that the last coordinate
635  * is equal to the number of steps taken.
636  * That is, let
637  *
638  *      \Delta_i = { y - x | (x, y) in R_i }
639  *
640  * then the constructed map is an overapproximation of
641  *
642  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
643  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) }
644  *
645  * The elements of the singleton \Delta_i's are collected as the
646  * rows of the steps matrix.  For all these \Delta_i's together,
647  * a single path is constructed.
648  * For each of the other \Delta_i's, we compute an overapproximation
649  * of the paths along elements of \Delta_i.
650  * Since each of these paths performs an addition, composition is
651  * symmetric and we can simply compose all resulting paths in any order.
652  */
653 static __isl_give isl_map *construct_extended_path(__isl_take isl_dim *dim,
654         __isl_keep isl_map *map, int *project)
655 {
656         struct isl_mat *steps = NULL;
657         struct isl_map *path = NULL;
658         unsigned d;
659         int i, j, n;
660
661         d = isl_map_dim(map, isl_dim_in);
662
663         path = isl_map_identity(isl_dim_domain(isl_dim_copy(dim)));
664
665         steps = isl_mat_alloc(map->ctx, map->n, d);
666         if (!steps)
667                 goto error;
668
669         n = 0;
670         for (i = 0; i < map->n; ++i) {
671                 struct isl_basic_set *delta;
672
673                 delta = isl_basic_map_deltas(isl_basic_map_copy(map->p[i]));
674
675                 for (j = 0; j < d; ++j) {
676                         int fixed;
677
678                         fixed = isl_basic_set_fast_dim_is_fixed(delta, j,
679                                                             &steps->row[n][j]);
680                         if (fixed < 0) {
681                                 isl_basic_set_free(delta);
682                                 goto error;
683                         }
684                         if (!fixed)
685                                 break;
686                 }
687
688
689                 if (j < d) {
690                         path = isl_map_apply_range(path,
691                                 path_along_delta(isl_dim_copy(dim), delta));
692                         path = isl_map_coalesce(path);
693                 } else {
694                         isl_basic_set_free(delta);
695                         ++n;
696                 }
697         }
698
699         if (n > 0) {
700                 steps->n_row = n;
701                 path = isl_map_apply_range(path,
702                                 path_along_steps(isl_dim_copy(dim), steps));
703         }
704
705         if (project && *project) {
706                 *project = is_acyclic(isl_map_copy(path));
707                 if (*project < 0)
708                         goto error;
709         }
710
711         isl_dim_free(dim);
712         isl_mat_free(steps);
713         return path;
714 error:
715         isl_dim_free(dim);
716         isl_mat_free(steps);
717         isl_map_free(path);
718         return NULL;
719 }
720
721 static int isl_set_overlaps(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
722 {
723         isl_set *i;
724         int no_overlap;
725
726         i = isl_set_intersect(isl_set_copy(set1), isl_set_copy(set2));
727         no_overlap = isl_set_is_empty(i);
728         isl_set_free(i);
729
730         return no_overlap < 0 ? -1 : !no_overlap;
731 }
732
733 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
734  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
735  * construct a map that is an overapproximation of the map
736  * that takes an element from the dom R \times Z to an
737  * element from ran R \times Z, such that the first n coordinates of the
738  * difference between them is a sum of differences between images
739  * and pre-images in one of the R_i and such that the last coordinate
740  * is equal to the number of steps taken.
741  * That is, let
742  *
743  *      \Delta_i = { y - x | (x, y) in R_i }
744  *
745  * then the constructed map is an overapproximation of
746  *
747  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
748  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) and
749  *                              x in dom R and x + d in ran R and
750  *                              \sum_i k_i >= 1 }
751  */
752 static __isl_give isl_map *construct_component(__isl_take isl_dim *dim,
753         __isl_keep isl_map *map, int *exact, int project)
754 {
755         struct isl_set *domain = NULL;
756         struct isl_set *range = NULL;
757         struct isl_map *app = NULL;
758         struct isl_map *path = NULL;
759
760         domain = isl_map_domain(isl_map_copy(map));
761         domain = isl_set_coalesce(domain);
762         range = isl_map_range(isl_map_copy(map));
763         range = isl_set_coalesce(range);
764         if (!isl_set_overlaps(domain, range)) {
765                 isl_set_free(domain);
766                 isl_set_free(range);
767                 isl_dim_free(dim);
768
769                 map = isl_map_copy(map);
770                 map = isl_map_add(map, isl_dim_in, 1);
771                 map = isl_map_add(map, isl_dim_out, 1);
772                 map = set_path_length(map, 1, 1);
773                 return map;
774         }
775         app = isl_map_from_domain_and_range(domain, range);
776         app = isl_map_add(app, isl_dim_in, 1);
777         app = isl_map_add(app, isl_dim_out, 1);
778
779         path = construct_extended_path(isl_dim_copy(dim), map,
780                                         exact && *exact ? &project : NULL);
781         app = isl_map_intersect(app, path);
782
783         if (exact && *exact &&
784             (*exact = check_exactness(isl_map_copy(map), isl_map_copy(app),
785                                       project)) < 0)
786                 goto error;
787
788         isl_dim_free(dim);
789         app = set_path_length(app, 0, 1);
790         return app;
791 error:
792         isl_dim_free(dim);
793         isl_map_free(app);
794         return NULL;
795 }
796
797 /* Call construct_component and, if "project" is set, project out
798  * the final coordinates.
799  */
800 static __isl_give isl_map *construct_projected_component(
801         __isl_take isl_dim *dim,
802         __isl_keep isl_map *map, int *exact, int project)
803 {
804         isl_map *app;
805         unsigned d;
806
807         if (!dim)
808                 return NULL;
809         d = isl_dim_size(dim, isl_dim_in);
810
811         app = construct_component(dim, map, exact, project);
812         if (project) {
813                 app = isl_map_project_out(app, isl_dim_in, d - 1, 1);
814                 app = isl_map_project_out(app, isl_dim_out, d - 1, 1);
815         }
816         return app;
817 }
818
819 /* Compute an extended version, i.e., with path lengths, of
820  * an overapproximation of the transitive closure of "bmap"
821  * with path lengths greater than or equal to zero and with
822  * domain and range equal to "dom".
823  */
824 static __isl_give isl_map *q_closure(__isl_take isl_dim *dim,
825         __isl_take isl_set *dom, __isl_keep isl_basic_map *bmap, int *exact)
826 {
827         int project = 1;
828         isl_map *path;
829         isl_map *map;
830         isl_map *app;
831
832         dom = isl_set_add(dom, isl_dim_set, 1);
833         app = isl_map_from_domain_and_range(dom, isl_set_copy(dom));
834         map = isl_map_from_basic_map(isl_basic_map_copy(bmap));
835         path = construct_extended_path(dim, map, &project);
836         app = isl_map_intersect(app, path);
837
838         if ((*exact = check_exactness(map, isl_map_copy(app), project)) < 0)
839                 goto error;
840
841         return app;
842 error:
843         isl_map_free(app);
844         return NULL;
845 }
846
847 /* Check whether qc has any elements of length at least one
848  * with domain and/or range outside of dom and ran.
849  */
850 static int has_spurious_elements(__isl_keep isl_map *qc,
851         __isl_keep isl_set *dom, __isl_keep isl_set *ran)
852 {
853         isl_set *s;
854         int subset;
855         unsigned d;
856
857         if (!qc || !dom || !ran)
858                 return -1;
859
860         d = isl_map_dim(qc, isl_dim_in);
861
862         qc = isl_map_copy(qc);
863         qc = set_path_length(qc, 0, 1);
864         qc = isl_map_project_out(qc, isl_dim_in, d - 1, 1);
865         qc = isl_map_project_out(qc, isl_dim_out, d - 1, 1);
866
867         s = isl_map_domain(isl_map_copy(qc));
868         subset = isl_set_is_subset(s, dom);
869         isl_set_free(s);
870         if (subset < 0)
871                 goto error;
872         if (!subset) {
873                 isl_map_free(qc);
874                 return 1;
875         }
876
877         s = isl_map_range(qc);
878         subset = isl_set_is_subset(s, ran);
879         isl_set_free(s);
880
881         return subset < 0 ? -1 : !subset;
882 error:
883         isl_map_free(qc);
884         return -1;
885 }
886
887 #define LEFT    2
888 #define RIGHT   1
889
890 /* For each basic map in "map", except i, check whether it combines
891  * with the transitive closure that is reflexive on C combines
892  * to the left and to the right.
893  *
894  * In particular, if
895  *
896  *      dom map_j \subseteq C
897  *
898  * then right[j] is set to 1.  Otherwise, if
899  *
900  *      ran map_i \cap dom map_j = \emptyset
901  *
902  * then right[j] is set to 0.  Otherwise, composing to the right
903  * is impossible.
904  *
905  * Similar, for composing to the left, we have if
906  *
907  *      ran map_j \subseteq C
908  *
909  * then left[j] is set to 1.  Otherwise, if
910  *
911  *      dom map_i \cap ran map_j = \emptyset
912  *
913  * then left[j] is set to 0.  Otherwise, composing to the left
914  * is impossible.
915  *
916  * The return value is or'd with LEFT if composing to the left
917  * is possible and with RIGHT if composing to the right is possible.
918  */
919 static int composability(__isl_keep isl_set *C, int i,
920         isl_set **dom, isl_set **ran, int *left, int *right,
921         __isl_keep isl_map *map)
922 {
923         int j;
924         int ok;
925
926         ok = LEFT | RIGHT;
927         for (j = 0; j < map->n && ok; ++j) {
928                 int overlaps, subset;
929                 if (j == i)
930                         continue;
931
932                 if (ok & RIGHT) {
933                         if (!dom[j])
934                                 dom[j] = isl_set_from_basic_set(
935                                         isl_basic_map_domain(
936                                                 isl_basic_map_copy(map->p[j])));
937                         if (!dom[j])
938                                 return -1;
939                         overlaps = isl_set_overlaps(ran[i], dom[j]);
940                         if (overlaps < 0)
941                                 return -1;
942                         if (!overlaps)
943                                 right[j] = 0;
944                         else {
945                                 subset = isl_set_is_subset(dom[j], C);
946                                 if (subset < 0)
947                                         return -1;
948                                 if (subset)
949                                         right[j] = 1;
950                                 else
951                                         ok &= ~RIGHT;
952                         }
953                 }
954
955                 if (ok & LEFT) {
956                         if (!ran[j])
957                                 ran[j] = isl_set_from_basic_set(
958                                         isl_basic_map_range(
959                                                 isl_basic_map_copy(map->p[j])));
960                         if (!ran[j])
961                                 return -1;
962                         overlaps = isl_set_overlaps(dom[i], ran[j]);
963                         if (overlaps < 0)
964                                 return -1;
965                         if (!overlaps)
966                                 left[j] = 0;
967                         else {
968                                 subset = isl_set_is_subset(ran[j], C);
969                                 if (subset < 0)
970                                         return -1;
971                                 if (subset)
972                                         left[j] = 1;
973                                 else
974                                         ok &= ~LEFT;
975                         }
976                 }
977         }
978
979         return ok;
980 }
981
982 /* Return a map that is a union of the basic maps in "map", except i,
983  * composed to left and right with qc based on the entries of "left"
984  * and "right".
985  */
986 static __isl_give isl_map *compose(__isl_keep isl_map *map, int i,
987         __isl_take isl_map *qc, int *left, int *right)
988 {
989         int j;
990         isl_map *comp;
991
992         comp = isl_map_empty(isl_map_get_dim(map));
993         for (j = 0; j < map->n; ++j) {
994                 isl_map *map_j;
995
996                 if (j == i)
997                         continue;
998
999                 map_j = isl_map_from_basic_map(isl_basic_map_copy(map->p[j]));
1000                 if (left && left[j])
1001                         map_j = isl_map_apply_range(map_j, isl_map_copy(qc));
1002                 if (right && right[j])
1003                         map_j = isl_map_apply_range(isl_map_copy(qc), map_j);
1004                 comp = isl_map_union(comp, map_j);
1005         }
1006
1007         comp = isl_map_compute_divs(comp);
1008         comp = isl_map_coalesce(comp);
1009
1010         isl_map_free(qc);
1011
1012         return comp;
1013 }
1014
1015 /* Compute the transitive closure of "map" incrementally by
1016  * computing
1017  *
1018  *      map_i^+ \cup qc^+
1019  *
1020  * or
1021  *
1022  *      map_i^+ \cup ((id \cup map_i^) \circ qc^+)
1023  *
1024  * or
1025  *
1026  *      map_i^+ \cup (qc^+ \circ (id \cup map_i^))
1027  *
1028  * depending on whether left or right are NULL.
1029  */
1030 static __isl_give isl_map *compute_incremental(
1031         __isl_take isl_dim *dim, __isl_keep isl_map *map,
1032         int i, __isl_take isl_map *qc, int *left, int *right, int *exact)
1033 {
1034         isl_map *map_i;
1035         isl_map *tc;
1036         isl_map *rtc = NULL;
1037
1038         if (!map)
1039                 goto error;
1040         isl_assert(map->ctx, left || right, goto error);
1041
1042         map_i = isl_map_from_basic_map(isl_basic_map_copy(map->p[i]));
1043         tc = construct_projected_component(isl_dim_copy(dim), map_i,
1044                                                 exact, 1);
1045         isl_map_free(map_i);
1046
1047         if (*exact)
1048                 qc = isl_map_transitive_closure(qc, exact);
1049
1050         if (!*exact) {
1051                 isl_dim_free(dim);
1052                 isl_map_free(tc);
1053                 isl_map_free(qc);
1054                 return isl_map_universe(isl_map_get_dim(map));
1055         }
1056
1057         if (!left || !right)
1058                 rtc = isl_map_union(isl_map_copy(tc),
1059                         isl_map_identity(isl_dim_domain(isl_map_get_dim(tc))));
1060         if (!right)
1061                 qc = isl_map_apply_range(rtc, qc);
1062         if (!left)
1063                 qc = isl_map_apply_range(qc, rtc);
1064         qc = isl_map_union(tc, qc);
1065
1066         isl_dim_free(dim);
1067
1068         return qc;
1069 error:
1070         isl_dim_free(dim);
1071         isl_map_free(qc);
1072         return NULL;
1073 }
1074
1075 /* Given a map "map", try to find a basic map such that
1076  * map^+ can be computed as
1077  *
1078  * map^+ = map_i^+ \cup
1079  *    \bigcup_j ((map_i^+ \cup Id_C)^+ \circ map_j \circ (map_i^+ \cup Id_C))^+
1080  *
1081  * with C the simple hull of the domain and range of the input map.
1082  * map_i^ \cup Id_C is computed by allowing the path lengths to be zero
1083  * and by intersecting domain and range with C.
1084  * Of course, we need to check that this is actually equal to map_i^ \cup Id_C.
1085  * Also, we only use the incremental computation if all the transitive
1086  * closures are exact and if the number of basic maps in the union,
1087  * after computing the integer divisions, is smaller than the number
1088  * of basic maps in the input map.
1089  */
1090 static int incemental_on_entire_domain(__isl_keep isl_dim *dim,
1091         __isl_keep isl_map *map,
1092         isl_set **dom, isl_set **ran, int *left, int *right,
1093         __isl_give isl_map **res)
1094 {
1095         int i;
1096         isl_set *C;
1097         unsigned d;
1098
1099         *res = NULL;
1100
1101         C = isl_set_union(isl_map_domain(isl_map_copy(map)),
1102                           isl_map_range(isl_map_copy(map)));
1103         C = isl_set_from_basic_set(isl_set_simple_hull(C));
1104         if (!C)
1105                 return -1;
1106         if (C->n != 1) {
1107                 isl_set_free(C);
1108                 return 0;
1109         }
1110
1111         d = isl_map_dim(map, isl_dim_in);
1112
1113         for (i = 0; i < map->n; ++i) {
1114                 isl_map *qc;
1115                 int exact_i, spurious;
1116                 int j;
1117                 dom[i] = isl_set_from_basic_set(isl_basic_map_domain(
1118                                         isl_basic_map_copy(map->p[i])));
1119                 ran[i] = isl_set_from_basic_set(isl_basic_map_range(
1120                                         isl_basic_map_copy(map->p[i])));
1121                 qc = q_closure(isl_dim_copy(dim), isl_set_copy(C),
1122                                 map->p[i], &exact_i);
1123                 if (!qc)
1124                         goto error;
1125                 if (!exact_i) {
1126                         isl_map_free(qc);
1127                         continue;
1128                 }
1129                 spurious = has_spurious_elements(qc, dom[i], ran[i]);
1130                 if (spurious) {
1131                         isl_map_free(qc);
1132                         if (spurious < 0)
1133                                 goto error;
1134                         continue;
1135                 }
1136                 qc = isl_map_project_out(qc, isl_dim_in, d, 1);
1137                 qc = isl_map_project_out(qc, isl_dim_out, d, 1);
1138                 qc = isl_map_compute_divs(qc);
1139                 for (j = 0; j < map->n; ++j)
1140                         left[j] = right[j] = 1;
1141                 qc = compose(map, i, qc, left, right);
1142                 if (!qc)
1143                         goto error;
1144                 if (qc->n >= map->n) {
1145                         isl_map_free(qc);
1146                         continue;
1147                 }
1148                 *res = compute_incremental(isl_dim_copy(dim), map, i, qc,
1149                                 left, right, &exact_i);
1150                 if (!*res)
1151                         goto error;
1152                 if (exact_i)
1153                         break;
1154                 isl_map_free(*res);
1155                 *res = NULL;
1156         }
1157
1158         isl_set_free(C);
1159
1160         return *res != NULL;
1161 error:
1162         isl_set_free(C);
1163         return -1;
1164 }
1165
1166 /* Try and compute the transitive closure of "map" as
1167  *
1168  * map^+ = map_i^+ \cup
1169  *    \bigcup_j ((map_i^+ \cup Id_C)^+ \circ map_j \circ (map_i^+ \cup Id_C))^+
1170  *
1171  * with C either the simple hull of the domain and range of the entire
1172  * map or the simple hull of domain and range of map_i.
1173  */
1174 static __isl_give isl_map *incremental_closure(__isl_take isl_dim *dim,
1175         __isl_keep isl_map *map, int *exact, int project)
1176 {
1177         int i;
1178         isl_set **dom = NULL;
1179         isl_set **ran = NULL;
1180         int *left = NULL;
1181         int *right = NULL;
1182         isl_set *C;
1183         unsigned d;
1184         isl_map *res = NULL;
1185
1186         if (!project)
1187                 return construct_projected_component(dim, map, exact, project);
1188
1189         if (!map)
1190                 goto error;
1191         if (map->n <= 1)
1192                 return construct_projected_component(dim, map, exact, project);
1193
1194         d = isl_map_dim(map, isl_dim_in);
1195
1196         dom = isl_calloc_array(map->ctx, isl_set *, map->n);
1197         ran = isl_calloc_array(map->ctx, isl_set *, map->n);
1198         left = isl_calloc_array(map->ctx, int, map->n);
1199         right = isl_calloc_array(map->ctx, int, map->n);
1200         if (!ran || !dom || !left || !right)
1201                 goto error;
1202
1203         if (incemental_on_entire_domain(dim, map, dom, ran, left, right, &res) < 0)
1204                 goto error;
1205
1206         for (i = 0; !res && i < map->n; ++i) {
1207                 isl_map *qc;
1208                 int exact_i, spurious, comp;
1209                 if (!dom[i])
1210                         dom[i] = isl_set_from_basic_set(
1211                                         isl_basic_map_domain(
1212                                                 isl_basic_map_copy(map->p[i])));
1213                 if (!dom[i])
1214                         goto error;
1215                 if (!ran[i])
1216                         ran[i] = isl_set_from_basic_set(
1217                                         isl_basic_map_range(
1218                                                 isl_basic_map_copy(map->p[i])));
1219                 if (!ran[i])
1220                         goto error;
1221                 C = isl_set_union(isl_set_copy(dom[i]),
1222                                       isl_set_copy(ran[i]));
1223                 C = isl_set_from_basic_set(isl_set_simple_hull(C));
1224                 if (!C)
1225                         goto error;
1226                 if (C->n != 1) {
1227                         isl_set_free(C);
1228                         continue;
1229                 }
1230                 comp = composability(C, i, dom, ran, left, right, map);
1231                 if (!comp || comp < 0) {
1232                         isl_set_free(C);
1233                         if (comp < 0)
1234                                 goto error;
1235                         continue;
1236                 }
1237                 qc = q_closure(isl_dim_copy(dim), C, map->p[i], &exact_i);
1238                 if (!qc)
1239                         goto error;
1240                 if (!exact_i) {
1241                         isl_map_free(qc);
1242                         continue;
1243                 }
1244                 spurious = has_spurious_elements(qc, dom[i], ran[i]);
1245                 if (spurious) {
1246                         isl_map_free(qc);
1247                         if (spurious < 0)
1248                                 goto error;
1249                         continue;
1250                 }
1251                 qc = isl_map_project_out(qc, isl_dim_in, d, 1);
1252                 qc = isl_map_project_out(qc, isl_dim_out, d, 1);
1253                 qc = isl_map_compute_divs(qc);
1254                 qc = compose(map, i, qc, (comp & LEFT) ? left : NULL,
1255                                 (comp & RIGHT) ? right : NULL);
1256                 if (!qc)
1257                         goto error;
1258                 if (qc->n >= map->n) {
1259                         isl_map_free(qc);
1260                         continue;
1261                 }
1262                 res = compute_incremental(isl_dim_copy(dim), map, i, qc,
1263                                 (comp & LEFT) ? left : NULL,
1264                                 (comp & RIGHT) ? right : NULL, &exact_i);
1265                 if (!res)
1266                         goto error;
1267                 if (exact_i)
1268                         break;
1269                 isl_map_free(res);
1270                 res = NULL;
1271         }
1272
1273         for (i = 0; i < map->n; ++i) {
1274                 isl_set_free(dom[i]);
1275                 isl_set_free(ran[i]);
1276         }
1277         free(dom);
1278         free(ran);
1279         free(left);
1280         free(right);
1281
1282         if (res) {
1283                 isl_dim_free(dim);
1284                 return res;
1285         }
1286
1287         return construct_projected_component(dim, map, exact, project);
1288 error:
1289         if (dom)
1290                 for (i = 0; i < map->n; ++i)
1291                         isl_set_free(dom[i]);
1292         free(dom);
1293         if (ran)
1294                 for (i = 0; i < map->n; ++i)
1295                         isl_set_free(ran[i]);
1296         free(ran);
1297         free(left);
1298         free(right);
1299         isl_dim_free(dim);
1300         return NULL;
1301 }
1302
1303 /* Given an array of sets "set", add "dom" at position "pos"
1304  * and search for elements at earlier positions that overlap with "dom".
1305  * If any can be found, then merge all of them, together with "dom", into
1306  * a single set and assign the union to the first in the array,
1307  * which becomes the new group leader for all groups involved in the merge.
1308  * During the search, we only consider group leaders, i.e., those with
1309  * group[i] = i, as the other sets have already been combined
1310  * with one of the group leaders.
1311  */
1312 static int merge(isl_set **set, int *group, __isl_take isl_set *dom, int pos)
1313 {
1314         int i;
1315
1316         group[pos] = pos;
1317         set[pos] = isl_set_copy(dom);
1318
1319         for (i = pos - 1; i >= 0; --i) {
1320                 int o;
1321
1322                 if (group[i] != i)
1323                         continue;
1324
1325                 o = isl_set_overlaps(set[i], dom);
1326                 if (o < 0)
1327                         goto error;
1328                 if (!o)
1329                         continue;
1330
1331                 set[i] = isl_set_union(set[i], set[group[pos]]);
1332                 if (!set[i])
1333                         goto error;
1334                 set[group[pos]] = NULL;
1335                 group[group[pos]] = i;
1336                 group[pos] = i;
1337         }
1338
1339         isl_set_free(dom);
1340         return 0;
1341 error:
1342         isl_set_free(dom);
1343         return -1;
1344 }
1345
1346 /* Given a partition of the domains and ranges of the basic maps in "map",
1347  * apply the Floyd-Warshall algorithm with the elements in the partition
1348  * as vertices.
1349  *
1350  * In particular, there are "n" elements in the partition and "group" is
1351  * an array of length 2 * map->n with entries in [0,n-1].
1352  *
1353  * We first construct a matrix of relations based on the partition information,
1354  * apply Floyd-Warshall on this matrix of relations and then take the
1355  * union of all entries in the matrix as the final result.
1356  *
1357  * The algorithm iterates over all vertices.  In each step, the whole
1358  * matrix is updated to include all paths that go to the current vertex,
1359  * possibly stay there a while (including passing through earlier vertices)
1360  * and then come back.  At the start of each iteration, the diagonal
1361  * element corresponding to the current vertex is replaced by its
1362  * transitive closure to account for all indirect paths that stay
1363  * in the current vertex.
1364  */
1365 static __isl_give isl_map *floyd_warshall_with_groups(__isl_take isl_dim *dim,
1366         __isl_keep isl_map *map, int *exact, int project, int *group, int n)
1367 {
1368         int i, j, k;
1369         int r, p, q;
1370         isl_map ***grid = NULL;
1371         isl_map *app;
1372
1373         if (!map)
1374                 goto error;
1375
1376         if (n == 1) {
1377                 free(group);
1378                 return incremental_closure(dim, map, exact, project);
1379         }
1380
1381         grid = isl_calloc_array(map->ctx, isl_map **, n);
1382         if (!grid)
1383                 goto error;
1384         for (i = 0; i < n; ++i) {
1385                 grid[i] = isl_calloc_array(map->ctx, isl_map *, n);
1386                 if (!grid[i])
1387                         goto error;
1388                 for (j = 0; j < n; ++j)
1389                         grid[i][j] = isl_map_empty(isl_map_get_dim(map));
1390         }
1391
1392         for (k = 0; k < map->n; ++k) {
1393                 i = group[2 * k];
1394                 j = group[2 * k + 1];
1395                 grid[i][j] = isl_map_union(grid[i][j],
1396                                 isl_map_from_basic_map(
1397                                         isl_basic_map_copy(map->p[k])));
1398         }
1399
1400         for (r = 0; r < n; ++r) {
1401                 int r_exact;
1402                 grid[r][r] = isl_map_transitive_closure(grid[r][r],
1403                                 (exact && *exact) ? &r_exact : NULL);
1404                 if (exact && *exact && !r_exact)
1405                         *exact = 0;
1406
1407                 for (p = 0; p < n; ++p)
1408                         for (q = 0; q < n; ++q) {
1409                                 isl_map *loop;
1410                                 if (p == r && q == r)
1411                                         continue;
1412                                 loop = isl_map_apply_range(
1413                                                 isl_map_copy(grid[p][r]),
1414                                                 isl_map_copy(grid[r][q]));
1415                                 grid[p][q] = isl_map_union(grid[p][q], loop);
1416                                 loop = isl_map_apply_range(
1417                                                 isl_map_copy(grid[p][r]),
1418                                         isl_map_apply_range(
1419                                                 isl_map_copy(grid[r][r]),
1420                                                 isl_map_copy(grid[r][q])));
1421                                 grid[p][q] = isl_map_union(grid[p][q], loop);
1422                                 grid[p][q] = isl_map_coalesce(grid[p][q]);
1423                         }
1424         }
1425
1426         app = isl_map_empty(isl_map_get_dim(map));
1427
1428         for (i = 0; i < n; ++i) {
1429                 for (j = 0; j < n; ++j)
1430                         app = isl_map_union(app, grid[i][j]);
1431                 free(grid[i]);
1432         }
1433         free(grid);
1434
1435         free(group);
1436         isl_dim_free(dim);
1437
1438         return app;
1439 error:
1440         if (grid)
1441                 for (i = 0; i < n; ++i) {
1442                         if (!grid[i])
1443                                 continue;
1444                         for (j = 0; j < n; ++j)
1445                                 isl_map_free(grid[i][j]);
1446                         free(grid[i]);
1447                 }
1448         free(grid);
1449         free(group);
1450         isl_dim_free(dim);
1451         return NULL;
1452 }
1453
1454 /* Check if the domains and ranges of the basic maps in "map" can
1455  * be partitioned, and if so, apply Floyd-Warshall on the elements
1456  * of the partition.  Note that we can only apply this algorithm
1457  * if we want to compute the transitive closure, i.e., when "project"
1458  * is set.  If we want to compute the power, we need to keep track
1459  * of the lengths and the recursive calls inside the Floyd-Warshall
1460  * would result in non-linear lengths.
1461  *
1462  * To find the partition, we simply consider all of the domains
1463  * and ranges in turn and combine those that overlap.
1464  * "set" contains the partition elements and "group" indicates
1465  * to which partition element a given domain or range belongs.
1466  * The domain of basic map i corresponds to element 2 * i in these arrays,
1467  * while the domain corresponds to element 2 * i + 1.
1468  * During the construction group[k] is either equal to k,
1469  * in which case set[k] contains the union of all the domains and
1470  * ranges in the corresponding group, or is equal to some l < k,
1471  * with l another domain or range in the same group.
1472  */
1473 static __isl_give isl_map *floyd_warshall(__isl_take isl_dim *dim,
1474         __isl_keep isl_map *map, int *exact, int project)
1475 {
1476         int i;
1477         isl_set **set = NULL;
1478         int *group = NULL;
1479         int n;
1480
1481         if (!map)
1482                 goto error;
1483         if (!project || map->n <= 1)
1484                 return incremental_closure(dim, map, exact, project);
1485
1486         set = isl_calloc_array(map->ctx, isl_set *, 2 * map->n);
1487         group = isl_alloc_array(map->ctx, int, 2 * map->n);
1488
1489         if (!set || !group)
1490                 goto error;
1491
1492         for (i = 0; i < map->n; ++i) {
1493                 isl_set *dom;
1494                 dom = isl_set_from_basic_set(isl_basic_map_domain(
1495                                 isl_basic_map_copy(map->p[i])));
1496                 if (merge(set, group, dom, 2 * i) < 0)
1497                         goto error;
1498                 dom = isl_set_from_basic_set(isl_basic_map_range(
1499                                 isl_basic_map_copy(map->p[i])));
1500                 if (merge(set, group, dom, 2 * i + 1) < 0)
1501                         goto error;
1502         }
1503
1504         n = 0;
1505         for (i = 0; i < 2 * map->n; ++i)
1506                 if (group[i] == i)
1507                         group[i] = n++;
1508                 else
1509                         group[i] = group[group[i]];
1510
1511         for (i = 0; i < 2 * map->n; ++i)
1512                 isl_set_free(set[i]);
1513
1514         free(set);
1515
1516         return floyd_warshall_with_groups(dim, map, exact, project, group, n);
1517 error:
1518         for (i = 0; i < 2 * map->n; ++i)
1519                 isl_set_free(set[i]);
1520         free(set);
1521         free(group);
1522         isl_dim_free(dim);
1523         return NULL;
1524 }
1525
1526 /* Structure for representing the nodes in the graph being traversed
1527  * using Tarjan's algorithm.
1528  * index represents the order in which nodes are visited.
1529  * min_index is the index of the root of a (sub)component.
1530  * on_stack indicates whether the node is currently on the stack.
1531  */
1532 struct basic_map_sort_node {
1533         int index;
1534         int min_index;
1535         int on_stack;
1536 };
1537 /* Structure for representing the graph being traversed
1538  * using Tarjan's algorithm.
1539  * len is the number of nodes
1540  * node is an array of nodes
1541  * stack contains the nodes on the path from the root to the current node
1542  * sp is the stack pointer
1543  * index is the index of the last node visited
1544  * order contains the elements of the components separated by -1
1545  * op represents the current position in order
1546  */
1547 struct basic_map_sort {
1548         int len;
1549         struct basic_map_sort_node *node;
1550         int *stack;
1551         int sp;
1552         int index;
1553         int *order;
1554         int op;
1555 };
1556
1557 static void basic_map_sort_free(struct basic_map_sort *s)
1558 {
1559         if (!s)
1560                 return;
1561         free(s->node);
1562         free(s->stack);
1563         free(s->order);
1564         free(s);
1565 }
1566
1567 static struct basic_map_sort *basic_map_sort_alloc(struct isl_ctx *ctx, int len)
1568 {
1569         struct basic_map_sort *s;
1570         int i;
1571
1572         s = isl_calloc_type(ctx, struct basic_map_sort);
1573         if (!s)
1574                 return NULL;
1575         s->len = len;
1576         s->node = isl_alloc_array(ctx, struct basic_map_sort_node, len);
1577         if (!s->node)
1578                 goto error;
1579         for (i = 0; i < len; ++i)
1580                 s->node[i].index = -1;
1581         s->stack = isl_alloc_array(ctx, int, len);
1582         if (!s->stack)
1583                 goto error;
1584         s->order = isl_alloc_array(ctx, int, 2 * len);
1585         if (!s->order)
1586                 goto error;
1587
1588         s->sp = 0;
1589         s->index = 0;
1590         s->op = 0;
1591
1592         return s;
1593 error:
1594         basic_map_sort_free(s);
1595         return NULL;
1596 }
1597
1598 /* Check whether in the computation of the transitive closure
1599  * "bmap1" (R_1) should follow (or be part of the same component as)
1600  * "bmap2" (R_2).
1601  *
1602  * That is check whether
1603  *
1604  *      R_1 \circ R_2
1605  *
1606  * is a subset of
1607  *
1608  *      R_2 \circ R_1
1609  *
1610  * If so, then there is no reason for R_1 to immediately follow R_2
1611  * in any path.
1612  */
1613 static int basic_map_follows(__isl_keep isl_basic_map *bmap1,
1614         __isl_keep isl_basic_map *bmap2)
1615 {
1616         struct isl_map *map12 = NULL;
1617         struct isl_map *map21 = NULL;
1618         int subset;
1619
1620         map21 = isl_map_from_basic_map(
1621                         isl_basic_map_apply_range(
1622                                 isl_basic_map_copy(bmap2),
1623                                 isl_basic_map_copy(bmap1)));
1624         subset = isl_map_is_empty(map21);
1625         if (subset < 0)
1626                 goto error;
1627         if (subset) {
1628                 isl_map_free(map21);
1629                 return 0;
1630         }
1631
1632         map12 = isl_map_from_basic_map(
1633                         isl_basic_map_apply_range(
1634                                 isl_basic_map_copy(bmap1),
1635                                 isl_basic_map_copy(bmap2)));
1636
1637         subset = isl_map_is_subset(map21, map12);
1638
1639         isl_map_free(map12);
1640         isl_map_free(map21);
1641
1642         return subset < 0 ? -1 : !subset;
1643 error:
1644         isl_map_free(map21);
1645         return -1;
1646 }
1647
1648 /* Perform Tarjan's algorithm for computing the strongly connected components
1649  * in the graph with the disjuncts of "map" as vertices and with an
1650  * edge between any pair of disjuncts such that the first has
1651  * to be applied after the second.
1652  */
1653 static int power_components_tarjan(struct basic_map_sort *s,
1654         __isl_keep isl_map *map, int i)
1655 {
1656         int j;
1657
1658         s->node[i].index = s->index;
1659         s->node[i].min_index = s->index;
1660         s->node[i].on_stack = 1;
1661         s->index++;
1662         s->stack[s->sp++] = i;
1663
1664         for (j = s->len - 1; j >= 0; --j) {
1665                 int f;
1666
1667                 if (j == i)
1668                         continue;
1669                 if (s->node[j].index >= 0 &&
1670                         (!s->node[j].on_stack ||
1671                          s->node[j].index > s->node[i].min_index))
1672                         continue;
1673
1674                 f = basic_map_follows(map->p[i], map->p[j]);
1675                 if (f < 0)
1676                         return -1;
1677                 if (!f)
1678                         continue;
1679
1680                 if (s->node[j].index < 0) {
1681                         power_components_tarjan(s, map, j);
1682                         if (s->node[j].min_index < s->node[i].min_index)
1683                                 s->node[i].min_index = s->node[j].min_index;
1684                 } else if (s->node[j].index < s->node[i].min_index)
1685                         s->node[i].min_index = s->node[j].index;
1686         }
1687
1688         if (s->node[i].index != s->node[i].min_index)
1689                 return 0;
1690
1691         do {
1692                 j = s->stack[--s->sp];
1693                 s->node[j].on_stack = 0;
1694                 s->order[s->op++] = j;
1695         } while (j != i);
1696         s->order[s->op++] = -1;
1697
1698         return 0;
1699 }
1700
1701 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
1702  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
1703  * construct a map that is an overapproximation of the map
1704  * that takes an element from the dom R \times Z to an
1705  * element from ran R \times Z, such that the first n coordinates of the
1706  * difference between them is a sum of differences between images
1707  * and pre-images in one of the R_i and such that the last coordinate
1708  * is equal to the number of steps taken.
1709  * If "project" is set, then these final coordinates are not included,
1710  * i.e., a relation of type Z^n -> Z^n is returned.
1711  * That is, let
1712  *
1713  *      \Delta_i = { y - x | (x, y) in R_i }
1714  *
1715  * then the constructed map is an overapproximation of
1716  *
1717  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1718  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) and
1719  *                              x in dom R and x + d in ran R }
1720  *
1721  * or
1722  *
1723  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1724  *                              d = (\sum_i k_i \delta_i) and
1725  *                              x in dom R and x + d in ran R }
1726  *
1727  * if "project" is set.
1728  *
1729  * We first split the map into strongly connected components, perform
1730  * the above on each component and then join the results in the correct
1731  * order, at each join also taking in the union of both arguments
1732  * to allow for paths that do not go through one of the two arguments.
1733  */
1734 static __isl_give isl_map *construct_power_components(__isl_take isl_dim *dim,
1735         __isl_keep isl_map *map, int *exact, int project)
1736 {
1737         int i, n;
1738         struct isl_map *path = NULL;
1739         struct basic_map_sort *s = NULL;
1740
1741         if (!map)
1742                 goto error;
1743         if (map->n <= 1)
1744                 return floyd_warshall(dim, map, exact, project);
1745
1746         s = basic_map_sort_alloc(map->ctx, map->n);
1747         if (!s)
1748                 goto error;
1749         for (i = map->n - 1; i >= 0; --i) {
1750                 if (s->node[i].index >= 0)
1751                         continue;
1752                 if (power_components_tarjan(s, map, i) < 0)
1753                         goto error;
1754         }
1755
1756         i = 0;
1757         n = map->n;
1758         if (project)
1759                 path = isl_map_empty(isl_map_get_dim(map));
1760         else
1761                 path = isl_map_empty(isl_dim_copy(dim));
1762         while (n) {
1763                 struct isl_map *comp;
1764                 isl_map *path_comp, *path_comb;
1765                 comp = isl_map_alloc_dim(isl_map_get_dim(map), n, 0);
1766                 while (s->order[i] != -1) {
1767                         comp = isl_map_add_basic_map(comp,
1768                                     isl_basic_map_copy(map->p[s->order[i]]));
1769                         --n;
1770                         ++i;
1771                 }
1772                 path_comp = floyd_warshall(isl_dim_copy(dim),
1773                                                 comp, exact, project);
1774                 path_comb = isl_map_apply_range(isl_map_copy(path),
1775                                                 isl_map_copy(path_comp));
1776                 path = isl_map_union(path, path_comp);
1777                 path = isl_map_union(path, path_comb);
1778                 isl_map_free(comp);
1779                 ++i;
1780         }
1781
1782         basic_map_sort_free(s);
1783         isl_dim_free(dim);
1784
1785         return path;
1786 error:
1787         basic_map_sort_free(s);
1788         isl_dim_free(dim);
1789         return NULL;
1790 }
1791
1792 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D,
1793  * construct a map that is an overapproximation of the map
1794  * that takes an element from the space D to another
1795  * element from the same space, such that the difference between
1796  * them is a strictly positive sum of differences between images
1797  * and pre-images in one of the R_i.
1798  * The number of differences in the sum is equated to parameter "param".
1799  * That is, let
1800  *
1801  *      \Delta_i = { y - x | (x, y) in R_i }
1802  *
1803  * then the constructed map is an overapproximation of
1804  *
1805  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1806  *                              d = \sum_i k_i \delta_i and k = \sum_i k_i > 0 }
1807  * or
1808  *
1809  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1810  *                              d = \sum_i k_i \delta_i and \sum_i k_i > 0 }
1811  *
1812  * if "project" is set.
1813  *
1814  * If "project" is not set, then
1815  * we first construct an extended mapping with an extra coordinate
1816  * that indicates the number of steps taken.  In particular,
1817  * the difference in the last coordinate is equal to the number
1818  * of steps taken to move from a domain element to the corresponding
1819  * image element(s).
1820  * In the final step, this difference is equated to the parameter "param"
1821  * and made positive.  The extra coordinates are subsequently projected out.
1822  */
1823 static __isl_give isl_map *construct_power(__isl_keep isl_map *map,
1824         unsigned param, int *exact, int project)
1825 {
1826         struct isl_map *app = NULL;
1827         struct isl_map *diff;
1828         struct isl_dim *dim = NULL;
1829         unsigned d;
1830
1831         if (!map)
1832                 return NULL;
1833
1834         dim = isl_map_get_dim(map);
1835
1836         d = isl_dim_size(dim, isl_dim_in);
1837         dim = isl_dim_add(dim, isl_dim_in, 1);
1838         dim = isl_dim_add(dim, isl_dim_out, 1);
1839
1840         app = construct_power_components(isl_dim_copy(dim), map,
1841                                         exact, project);
1842
1843         if (project) {
1844                 isl_dim_free(dim);
1845         } else {
1846                 diff = equate_parameter_to_length(dim, param);
1847                 app = isl_map_intersect(app, diff);
1848                 app = isl_map_project_out(app, isl_dim_in, d, 1);
1849                 app = isl_map_project_out(app, isl_dim_out, d, 1);
1850         }
1851
1852         return app;
1853 }
1854
1855 /* Compute the positive powers of "map", or an overapproximation.
1856  * The power is given by parameter "param".  If the result is exact,
1857  * then *exact is set to 1.
1858  *
1859  * If project is set, then we are actually interested in the transitive
1860  * closure, so we can use a more relaxed exactness check.
1861  * The lengths of the paths are also projected out instead of being
1862  * equated to "param" (which is then ignored in this case).
1863  */
1864 static __isl_give isl_map *map_power(__isl_take isl_map *map, unsigned param,
1865         int *exact, int project)
1866 {
1867         struct isl_map *app = NULL;
1868
1869         if (exact)
1870                 *exact = 1;
1871
1872         map = isl_map_compute_divs(map);
1873         map = isl_map_coalesce(map);
1874         if (!map)
1875                 return NULL;
1876
1877         if (isl_map_fast_is_empty(map))
1878                 return map;
1879
1880         isl_assert(map->ctx, project || param < isl_map_dim(map, isl_dim_param),
1881                 goto error);
1882         isl_assert(map->ctx,
1883                 isl_map_dim(map, isl_dim_in) == isl_map_dim(map, isl_dim_out),
1884                 goto error);
1885
1886         app = construct_power(map, param, exact, project);
1887
1888         isl_map_free(map);
1889         return app;
1890 error:
1891         isl_map_free(map);
1892         isl_map_free(app);
1893         return NULL;
1894 }
1895
1896 /* Compute the positive powers of "map", or an overapproximation.
1897  * The power is given by parameter "param".  If the result is exact,
1898  * then *exact is set to 1.
1899  */
1900 __isl_give isl_map *isl_map_power(__isl_take isl_map *map, unsigned param,
1901         int *exact)
1902 {
1903         return map_power(map, param, exact, 0);
1904 }
1905
1906 /* Check whether equality i of bset is a pure stride constraint
1907  * on a single dimensions, i.e., of the form
1908  *
1909  *      v = k e
1910  *
1911  * with k a constant and e an existentially quantified variable.
1912  */
1913 static int is_eq_stride(__isl_keep isl_basic_set *bset, int i)
1914 {
1915         int k;
1916         unsigned nparam;
1917         unsigned d;
1918         unsigned n_div;
1919         int pos1;
1920         int pos2;
1921
1922         if (!bset)
1923                 return -1;
1924
1925         if (!isl_int_is_zero(bset->eq[i][0]))
1926                 return 0;
1927
1928         nparam = isl_basic_set_dim(bset, isl_dim_param);
1929         d = isl_basic_set_dim(bset, isl_dim_set);
1930         n_div = isl_basic_set_dim(bset, isl_dim_div);
1931
1932         if (isl_seq_first_non_zero(bset->eq[i] + 1, nparam) != -1)
1933                 return 0;
1934         pos1 = isl_seq_first_non_zero(bset->eq[i] + 1 + nparam, d);
1935         if (pos1 == -1)
1936                 return 0;
1937         if (isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + pos1 + 1, 
1938                                         d - pos1 - 1) != -1)
1939                 return 0;
1940
1941         pos2 = isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + d, n_div);
1942         if (pos2 == -1)
1943                 return 0;
1944         if (isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + d  + pos2 + 1,
1945                                    n_div - pos2 - 1) != -1)
1946                 return 0;
1947         if (!isl_int_is_one(bset->eq[i][1 + nparam + pos1]) &&
1948             !isl_int_is_negone(bset->eq[i][1 + nparam + pos1]))
1949                 return 0;
1950
1951         return 1;
1952 }
1953
1954 /* Given a map, compute the smallest superset of this map that is of the form
1955  *
1956  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
1957  *
1958  * (where p ranges over the (non-parametric) dimensions),
1959  * compute the transitive closure of this map, i.e.,
1960  *
1961  *      { i -> j : exists k > 0:
1962  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
1963  *
1964  * and intersect domain and range of this transitive closure with
1965  * the given domain and range.
1966  *
1967  * If with_id is set, then try to include as much of the identity mapping
1968  * as possible, by computing
1969  *
1970  *      { i -> j : exists k >= 0:
1971  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
1972  *
1973  * instead (i.e., allow k = 0).
1974  *
1975  * In practice, we compute the difference set
1976  *
1977  *      delta  = { j - i | i -> j in map },
1978  *
1979  * look for stride constraint on the individual dimensions and compute
1980  * (constant) lower and upper bounds for each individual dimension,
1981  * adding a constraint for each bound not equal to infinity.
1982  */
1983 static __isl_give isl_map *box_closure_on_domain(__isl_take isl_map *map,
1984         __isl_take isl_set *dom, __isl_take isl_set *ran, int with_id)
1985 {
1986         int i;
1987         int k;
1988         unsigned d;
1989         unsigned nparam;
1990         unsigned total;
1991         isl_dim *dim;
1992         isl_set *delta;
1993         isl_map *app = NULL;
1994         isl_basic_set *aff = NULL;
1995         isl_basic_map *bmap = NULL;
1996         isl_vec *obj = NULL;
1997         isl_int opt;
1998
1999         isl_int_init(opt);
2000
2001         delta = isl_map_deltas(isl_map_copy(map));
2002
2003         aff = isl_set_affine_hull(isl_set_copy(delta));
2004         if (!aff)
2005                 goto error;
2006         dim = isl_map_get_dim(map);
2007         d = isl_dim_size(dim, isl_dim_in);
2008         nparam = isl_dim_size(dim, isl_dim_param);
2009         total = isl_dim_total(dim);
2010         bmap = isl_basic_map_alloc_dim(dim,
2011                                         aff->n_div + 1, aff->n_div, 2 * d + 1);
2012         for (i = 0; i < aff->n_div + 1; ++i) {
2013                 k = isl_basic_map_alloc_div(bmap);
2014                 if (k < 0)
2015                         goto error;
2016                 isl_int_set_si(bmap->div[k][0], 0);
2017         }
2018         for (i = 0; i < aff->n_eq; ++i) {
2019                 if (!is_eq_stride(aff, i))
2020                         continue;
2021                 k = isl_basic_map_alloc_equality(bmap);
2022                 if (k < 0)
2023                         goto error;
2024                 isl_seq_clr(bmap->eq[k], 1 + nparam);
2025                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + d,
2026                                 aff->eq[i] + 1 + nparam, d);
2027                 isl_seq_neg(bmap->eq[k] + 1 + nparam,
2028                                 aff->eq[i] + 1 + nparam, d);
2029                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + 2 * d,
2030                                 aff->eq[i] + 1 + nparam + d, aff->n_div);
2031                 isl_int_set_si(bmap->eq[k][1 + total + aff->n_div], 0);
2032         }
2033         obj = isl_vec_alloc(map->ctx, 1 + nparam + d);
2034         if (!obj)
2035                 goto error;
2036         isl_seq_clr(obj->el, 1 + nparam + d);
2037         for (i = 0; i < d; ++ i) {
2038                 enum isl_lp_result res;
2039
2040                 isl_int_set_si(obj->el[1 + nparam + i], 1);
2041
2042                 res = isl_set_solve_lp(delta, 0, obj->el, map->ctx->one, &opt,
2043                                         NULL, NULL);
2044                 if (res == isl_lp_error)
2045                         goto error;
2046                 if (res == isl_lp_ok) {
2047                         k = isl_basic_map_alloc_inequality(bmap);
2048                         if (k < 0)
2049                                 goto error;
2050                         isl_seq_clr(bmap->ineq[k],
2051                                         1 + nparam + 2 * d + bmap->n_div);
2052                         isl_int_set_si(bmap->ineq[k][1 + nparam + i], -1);
2053                         isl_int_set_si(bmap->ineq[k][1 + nparam + d + i], 1);
2054                         isl_int_neg(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], opt);
2055                 }
2056
2057                 res = isl_set_solve_lp(delta, 1, obj->el, map->ctx->one, &opt,
2058                                         NULL, NULL);
2059                 if (res == isl_lp_error)
2060                         goto error;
2061                 if (res == isl_lp_ok) {
2062                         k = isl_basic_map_alloc_inequality(bmap);
2063                         if (k < 0)
2064                                 goto error;
2065                         isl_seq_clr(bmap->ineq[k],
2066                                         1 + nparam + 2 * d + bmap->n_div);
2067                         isl_int_set_si(bmap->ineq[k][1 + nparam + i], 1);
2068                         isl_int_set_si(bmap->ineq[k][1 + nparam + d + i], -1);
2069                         isl_int_set(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], opt);
2070                 }
2071
2072                 isl_int_set_si(obj->el[1 + nparam + i], 0);
2073         }
2074         k = isl_basic_map_alloc_inequality(bmap);
2075         if (k < 0)
2076                 goto error;
2077         isl_seq_clr(bmap->ineq[k],
2078                         1 + nparam + 2 * d + bmap->n_div);
2079         if (!with_id)
2080                 isl_int_set_si(bmap->ineq[k][0], -1);
2081         isl_int_set_si(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], 1);
2082
2083         app = isl_map_from_domain_and_range(dom, ran);
2084
2085         isl_vec_free(obj);
2086         isl_basic_set_free(aff);
2087         isl_map_free(map);
2088         bmap = isl_basic_map_finalize(bmap);
2089         isl_set_free(delta);
2090         isl_int_clear(opt);
2091
2092         map = isl_map_from_basic_map(bmap);
2093         map = isl_map_intersect(map, app);
2094
2095         return map;
2096 error:
2097         isl_vec_free(obj);
2098         isl_basic_map_free(bmap);
2099         isl_basic_set_free(aff);
2100         isl_set_free(dom);
2101         isl_set_free(ran);
2102         isl_map_free(map);
2103         isl_set_free(delta);
2104         isl_int_clear(opt);
2105         return NULL;
2106 }
2107
2108 /* Given a map, compute the smallest superset of this map that is of the form
2109  *
2110  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
2111  *
2112  * (where p ranges over the (non-parametric) dimensions),
2113  * compute the transitive closure of this map, i.e.,
2114  *
2115  *      { i -> j : exists k > 0:
2116  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2117  *
2118  * and intersect domain and range of this transitive closure with
2119  * domain and range of the original map.
2120  */
2121 static __isl_give isl_map *box_closure(__isl_take isl_map *map)
2122 {
2123         isl_set *domain;
2124         isl_set *range;
2125
2126         domain = isl_map_domain(isl_map_copy(map));
2127         domain = isl_set_coalesce(domain);
2128         range = isl_map_range(isl_map_copy(map));
2129         range = isl_set_coalesce(range);
2130
2131         return box_closure_on_domain(map, domain, range, 0);
2132 }
2133
2134 /* Given a map, compute the smallest superset of this map that is of the form
2135  *
2136  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
2137  *
2138  * (where p ranges over the (non-parametric) dimensions),
2139  * compute the transitive and partially reflexive closure of this map, i.e.,
2140  *
2141  *      { i -> j : exists k >= 0:
2142  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2143  *
2144  * and intersect domain and range of this transitive closure with
2145  * the given domain.
2146  */
2147 static __isl_give isl_map *box_closure_with_identity(__isl_take isl_map *map,
2148         __isl_take isl_set *dom)
2149 {
2150         return box_closure_on_domain(map, dom, isl_set_copy(dom), 1);
2151 }
2152
2153 /* Check whether app is the transitive closure of map.
2154  * In particular, check that app is acyclic and, if so,
2155  * check that
2156  *
2157  *      app \subset (map \cup (map \circ app))
2158  */
2159 static int check_exactness_omega(__isl_keep isl_map *map,
2160         __isl_keep isl_map *app)
2161 {
2162         isl_set *delta;
2163         int i;
2164         int is_empty, is_exact;
2165         unsigned d;
2166         isl_map *test;
2167
2168         delta = isl_map_deltas(isl_map_copy(app));
2169         d = isl_set_dim(delta, isl_dim_set);
2170         for (i = 0; i < d; ++i)
2171                 delta = isl_set_fix_si(delta, isl_dim_set, i, 0);
2172         is_empty = isl_set_is_empty(delta);
2173         isl_set_free(delta);
2174         if (is_empty < 0)
2175                 return -1;
2176         if (!is_empty)
2177                 return 0;
2178
2179         test = isl_map_apply_range(isl_map_copy(app), isl_map_copy(map));
2180         test = isl_map_union(test, isl_map_copy(map));
2181         is_exact = isl_map_is_subset(app, test);
2182         isl_map_free(test);
2183
2184         return is_exact;
2185 }
2186
2187 /* Check if basic map M_i can be combined with all the other
2188  * basic maps such that
2189  *
2190  *      (\cup_j M_j)^+
2191  *
2192  * can be computed as
2193  *
2194  *      M_i \cup (\cup_{j \ne i} M_i^* \circ M_j \circ M_i^*)^+
2195  *
2196  * In particular, check if we can compute a compact representation
2197  * of
2198  *
2199  *              M_i^* \circ M_j \circ M_i^*
2200  *
2201  * for each j != i.
2202  * Let M_i^? be an extension of M_i^+ that allows paths
2203  * of length zero, i.e., the result of box_closure(., 1).
2204  * The criterion, as proposed by Kelly et al., is that
2205  * id = M_i^? - M_i^+ can be represented as a basic map
2206  * and that
2207  *
2208  *      id \circ M_j \circ id = M_j
2209  *
2210  * for each j != i.
2211  *
2212  * If this function returns 1, then tc and qc are set to
2213  * M_i^+ and M_i^?, respectively.
2214  */
2215 static int can_be_split_off(__isl_keep isl_map *map, int i,
2216         __isl_give isl_map **tc, __isl_give isl_map **qc)
2217 {
2218         isl_map *map_i, *id = NULL;
2219         int j = -1;
2220         isl_set *C;
2221
2222         *tc = NULL;
2223         *qc = NULL;
2224
2225         C = isl_set_union(isl_map_domain(isl_map_copy(map)),
2226                           isl_map_range(isl_map_copy(map)));
2227         C = isl_set_from_basic_set(isl_set_simple_hull(C));
2228         if (!C)
2229                 goto error;
2230
2231         map_i = isl_map_from_basic_map(isl_basic_map_copy(map->p[i]));
2232         *tc = box_closure(isl_map_copy(map_i));
2233         *qc = box_closure_with_identity(map_i, C);
2234         id = isl_map_subtract(isl_map_copy(*qc), isl_map_copy(*tc));
2235
2236         if (!id || !*qc)
2237                 goto error;
2238         if (id->n != 1 || (*qc)->n != 1)
2239                 goto done;
2240
2241         for (j = 0; j < map->n; ++j) {
2242                 isl_map *map_j, *test;
2243                 int is_ok;
2244
2245                 if (i == j)
2246                         continue;
2247                 map_j = isl_map_from_basic_map(
2248                                         isl_basic_map_copy(map->p[j]));
2249                 test = isl_map_apply_range(isl_map_copy(id),
2250                                                 isl_map_copy(map_j));
2251                 test = isl_map_apply_range(test, isl_map_copy(id));
2252                 is_ok = isl_map_is_equal(test, map_j);
2253                 isl_map_free(map_j);
2254                 isl_map_free(test);
2255                 if (is_ok < 0)
2256                         goto error;
2257                 if (!is_ok)
2258                         break;
2259         }
2260
2261 done:
2262         isl_map_free(id);
2263         if (j == map->n)
2264                 return 1;
2265
2266         isl_map_free(*qc);
2267         isl_map_free(*tc);
2268         *qc = NULL;
2269         *tc = NULL;
2270
2271         return 0;
2272 error:
2273         isl_map_free(id);
2274         isl_map_free(*qc);
2275         isl_map_free(*tc);
2276         *qc = NULL;
2277         *tc = NULL;
2278         return -1;
2279 }
2280
2281 static __isl_give isl_map *box_closure_with_check(__isl_take isl_map *map,
2282         int *exact)
2283 {
2284         isl_map *app;
2285
2286         app = box_closure(isl_map_copy(map));
2287         if (exact)
2288                 *exact = check_exactness_omega(map, app);
2289
2290         isl_map_free(map);
2291         return app;
2292 }
2293
2294 /* Compute an overapproximation of the transitive closure of "map"
2295  * using a variation of the algorithm from
2296  * "Transitive Closure of Infinite Graphs and its Applications"
2297  * by Kelly et al.
2298  *
2299  * We first check whether we can can split of any basic map M_i and
2300  * compute
2301  *
2302  *      (\cup_j M_j)^+
2303  *
2304  * as
2305  *
2306  *      M_i \cup (\cup_{j \ne i} M_i^* \circ M_j \circ M_i^*)^+
2307  *
2308  * using a recursive call on the remaining map.
2309  *
2310  * If not, we simply call box_closure on the whole map.
2311  */
2312 static __isl_give isl_map *transitive_closure_omega(__isl_take isl_map *map,
2313         int *exact)
2314 {
2315         int i, j;
2316         int exact_i;
2317         isl_map *app;
2318
2319         if (!map)
2320                 return NULL;
2321         if (map->n == 1)
2322                 return box_closure_with_check(map, exact);
2323
2324         for (i = 0; i < map->n; ++i) {
2325                 int ok;
2326                 isl_map *qc, *tc;
2327                 ok = can_be_split_off(map, i, &tc, &qc);
2328                 if (ok < 0)
2329                         goto error;
2330                 if (!ok)
2331                         continue;
2332
2333                 app = isl_map_alloc_dim(isl_map_get_dim(map), map->n - 1, 0);
2334
2335                 for (j = 0; j < map->n; ++j) {
2336                         if (j == i)
2337                                 continue;
2338                         app = isl_map_add_basic_map(app,
2339                                                 isl_basic_map_copy(map->p[j]));
2340                 }
2341
2342                 app = isl_map_apply_range(isl_map_copy(qc), app);
2343                 app = isl_map_apply_range(app, qc);
2344
2345                 app = isl_map_union(tc, transitive_closure_omega(app, NULL));
2346                 exact_i = check_exactness_omega(map, app);
2347                 if (exact_i == 1) {
2348                         if (exact)
2349                                 *exact = exact_i;
2350                         isl_map_free(map);
2351                         return app;
2352                 }
2353                 isl_map_free(app);
2354                 if (exact_i < 0)
2355                         goto error;
2356         }
2357
2358         return box_closure_with_check(map, exact);
2359 error:
2360         isl_map_free(map);
2361         return NULL;
2362 }
2363
2364 /* Compute the transitive closure  of "map", or an overapproximation.
2365  * If the result is exact, then *exact is set to 1.
2366  * Simply use map_power to compute the powers of map, but tell
2367  * it to project out the lengths of the paths instead of equating
2368  * the length to a parameter.
2369  */
2370 __isl_give isl_map *isl_map_transitive_closure(__isl_take isl_map *map,
2371         int *exact)
2372 {
2373         unsigned param;
2374
2375         if (!map)
2376                 goto error;
2377
2378         if (map->ctx->opt->closure == ISL_CLOSURE_OMEGA)
2379                 return transitive_closure_omega(map, exact);
2380
2381         param = isl_map_dim(map, isl_dim_param);
2382         map = map_power(map, param, exact, 1);
2383
2384         return map;
2385 error:
2386         isl_map_free(map);
2387         return NULL;
2388 }