isl_map_identity: take dimension specification of map as input
[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_private.h>
12 #include <isl/map.h>
13 #include <isl/seq.h>
14 #include <isl_dim_private.h>
15 #include <isl/lp.h>
16 #include <isl/union_map.h>
17 #include <isl_mat_private.h>
18
19 int isl_map_is_transitively_closed(__isl_keep isl_map *map)
20 {
21         isl_map *map2;
22         int closed;
23
24         map2 = isl_map_apply_range(isl_map_copy(map), isl_map_copy(map));
25         closed = isl_map_is_subset(map2, map);
26         isl_map_free(map2);
27
28         return closed;
29 }
30
31 int isl_union_map_is_transitively_closed(__isl_keep isl_union_map *umap)
32 {
33         isl_union_map *umap2;
34         int closed;
35
36         umap2 = isl_union_map_apply_range(isl_union_map_copy(umap),
37                                           isl_union_map_copy(umap));
38         closed = isl_union_map_is_subset(umap2, umap);
39         isl_union_map_free(umap2);
40
41         return closed;
42 }
43  
44 /* Given a map that represents a path with the length of the path
45  * encoded as the difference between the last output coordindate
46  * and the last input coordinate, set this length to either
47  * exactly "length" (if "exactly" is set) or at least "length"
48  * (if "exactly" is not set).
49  */
50 static __isl_give isl_map *set_path_length(__isl_take isl_map *map,
51         int exactly, int length)
52 {
53         struct isl_dim *dim;
54         struct isl_basic_map *bmap;
55         unsigned d;
56         unsigned nparam;
57         int k;
58         isl_int *c;
59
60         if (!map)
61                 return NULL;
62
63         dim = isl_map_get_dim(map);
64         d = isl_dim_size(dim, isl_dim_in);
65         nparam = isl_dim_size(dim, isl_dim_param);
66         bmap = isl_basic_map_alloc_dim(dim, 0, 1, 1);
67         if (exactly) {
68                 k = isl_basic_map_alloc_equality(bmap);
69                 c = bmap->eq[k];
70         } else {
71                 k = isl_basic_map_alloc_inequality(bmap);
72                 c = bmap->ineq[k];
73         }
74         if (k < 0)
75                 goto error;
76         isl_seq_clr(c, 1 + isl_basic_map_total_dim(bmap));
77         isl_int_set_si(c[0], -length);
78         isl_int_set_si(c[1 + nparam + d - 1], -1);
79         isl_int_set_si(c[1 + nparam + d + d - 1], 1);
80
81         bmap = isl_basic_map_finalize(bmap);
82         map = isl_map_intersect(map, isl_map_from_basic_map(bmap));
83
84         return map;
85 error:
86         isl_basic_map_free(bmap);
87         isl_map_free(map);
88         return NULL;
89 }
90
91 /* Check whether the overapproximation of the power of "map" is exactly
92  * the power of "map".  Let R be "map" and A_k the overapproximation.
93  * The approximation is exact if
94  *
95  *      A_1 = R
96  *      A_k = A_{k-1} \circ R                   k >= 2
97  *
98  * Since A_k is known to be an overapproximation, we only need to check
99  *
100  *      A_1 \subset R
101  *      A_k \subset A_{k-1} \circ R             k >= 2
102  *
103  * In practice, "app" has an extra input and output coordinate
104  * to encode the length of the path.  So, we first need to add
105  * this coordinate to "map" and set the length of the path to
106  * one.
107  */
108 static int check_power_exactness(__isl_take isl_map *map,
109         __isl_take isl_map *app)
110 {
111         int exact;
112         isl_map *app_1;
113         isl_map *app_2;
114
115         map = isl_map_add_dims(map, isl_dim_in, 1);
116         map = isl_map_add_dims(map, isl_dim_out, 1);
117         map = set_path_length(map, 1, 1);
118
119         app_1 = set_path_length(isl_map_copy(app), 1, 1);
120
121         exact = isl_map_is_subset(app_1, map);
122         isl_map_free(app_1);
123
124         if (!exact || exact < 0) {
125                 isl_map_free(app);
126                 isl_map_free(map);
127                 return exact;
128         }
129
130         app_1 = set_path_length(isl_map_copy(app), 0, 1);
131         app_2 = set_path_length(app, 0, 2);
132         app_1 = isl_map_apply_range(map, app_1);
133
134         exact = isl_map_is_subset(app_2, app_1);
135
136         isl_map_free(app_1);
137         isl_map_free(app_2);
138
139         return exact;
140 }
141
142 /* Check whether the overapproximation of the power of "map" is exactly
143  * the power of "map", possibly after projecting out the power (if "project"
144  * is set).
145  *
146  * If "project" is set and if "steps" can only result in acyclic paths,
147  * then we check
148  *
149  *      A = R \cup (A \circ R)
150  *
151  * where A is the overapproximation with the power projected out, i.e.,
152  * an overapproximation of the transitive closure.
153  * More specifically, since A is known to be an overapproximation, we check
154  *
155  *      A \subset R \cup (A \circ R)
156  *
157  * Otherwise, we check if the power is exact.
158  *
159  * Note that "app" has an extra input and output coordinate to encode
160  * the length of the part.  If we are only interested in the transitive
161  * closure, then we can simply project out these coordinates first.
162  */
163 static int check_exactness(__isl_take isl_map *map, __isl_take isl_map *app,
164         int project)
165 {
166         isl_map *test;
167         int exact;
168         unsigned d;
169
170         if (!project)
171                 return check_power_exactness(map, app);
172
173         d = isl_map_dim(map, isl_dim_in);
174         app = set_path_length(app, 0, 1);
175         app = isl_map_project_out(app, isl_dim_in, d, 1);
176         app = isl_map_project_out(app, isl_dim_out, d, 1);
177
178         app = isl_map_reset_dim(app, isl_map_get_dim(map));
179
180         test = isl_map_apply_range(isl_map_copy(map), isl_map_copy(app));
181         test = isl_map_union(test, isl_map_copy(map));
182
183         exact = isl_map_is_subset(app, test);
184
185         isl_map_free(app);
186         isl_map_free(test);
187
188         isl_map_free(map);
189
190         return exact;
191 }
192
193 /*
194  * The transitive closure implementation is based on the paper
195  * "Computing the Transitive Closure of a Union of Affine Integer
196  * Tuple Relations" by Anna Beletska, Denis Barthou, Wlodzimierz Bielecki and
197  * Albert Cohen.
198  */
199
200 /* Given a set of n offsets v_i (the rows of "steps"), construct a relation
201  * of the given dimension specification (Z^{n+1} -> Z^{n+1})
202  * that maps an element x to any element that can be reached
203  * by taking a non-negative number of steps along any of
204  * the extended offsets v'_i = [v_i 1].
205  * That is, construct
206  *
207  * { [x] -> [y] : exists k_i >= 0, y = x + \sum_i k_i v'_i }
208  *
209  * For any element in this relation, the number of steps taken
210  * is equal to the difference in the final coordinates.
211  */
212 static __isl_give isl_map *path_along_steps(__isl_take isl_dim *dim,
213         __isl_keep isl_mat *steps)
214 {
215         int i, j, k;
216         struct isl_basic_map *path = NULL;
217         unsigned d;
218         unsigned n;
219         unsigned nparam;
220
221         if (!dim || !steps)
222                 goto error;
223
224         d = isl_dim_size(dim, isl_dim_in);
225         n = steps->n_row;
226         nparam = isl_dim_size(dim, isl_dim_param);
227
228         path = isl_basic_map_alloc_dim(isl_dim_copy(dim), n, d, n);
229
230         for (i = 0; i < n; ++i) {
231                 k = isl_basic_map_alloc_div(path);
232                 if (k < 0)
233                         goto error;
234                 isl_assert(steps->ctx, i == k, goto error);
235                 isl_int_set_si(path->div[k][0], 0);
236         }
237
238         for (i = 0; i < d; ++i) {
239                 k = isl_basic_map_alloc_equality(path);
240                 if (k < 0)
241                         goto error;
242                 isl_seq_clr(path->eq[k], 1 + isl_basic_map_total_dim(path));
243                 isl_int_set_si(path->eq[k][1 + nparam + i], 1);
244                 isl_int_set_si(path->eq[k][1 + nparam + d + i], -1);
245                 if (i == d - 1)
246                         for (j = 0; j < n; ++j)
247                                 isl_int_set_si(path->eq[k][1 + nparam + 2 * d + j], 1);
248                 else
249                         for (j = 0; j < n; ++j)
250                                 isl_int_set(path->eq[k][1 + nparam + 2 * d + j],
251                                             steps->row[j][i]);
252         }
253
254         for (i = 0; i < n; ++i) {
255                 k = isl_basic_map_alloc_inequality(path);
256                 if (k < 0)
257                         goto error;
258                 isl_seq_clr(path->ineq[k], 1 + isl_basic_map_total_dim(path));
259                 isl_int_set_si(path->ineq[k][1 + nparam + 2 * d + i], 1);
260         }
261
262         isl_dim_free(dim);
263
264         path = isl_basic_map_simplify(path);
265         path = isl_basic_map_finalize(path);
266         return isl_map_from_basic_map(path);
267 error:
268         isl_dim_free(dim);
269         isl_basic_map_free(path);
270         return NULL;
271 }
272
273 #define IMPURE          0
274 #define PURE_PARAM      1
275 #define PURE_VAR        2
276 #define MIXED           3
277
278 /* Check whether the parametric constant term of constraint c is never
279  * positive in "bset".
280  */
281 static int parametric_constant_never_positive(__isl_keep isl_basic_set *bset,
282         isl_int *c, int *div_purity)
283 {
284         unsigned d;
285         unsigned n_div;
286         unsigned nparam;
287         int i;
288         int k;
289         int empty;
290
291         n_div = isl_basic_set_dim(bset, isl_dim_div);
292         d = isl_basic_set_dim(bset, isl_dim_set);
293         nparam = isl_basic_set_dim(bset, isl_dim_param);
294
295         bset = isl_basic_set_copy(bset);
296         bset = isl_basic_set_cow(bset);
297         bset = isl_basic_set_extend_constraints(bset, 0, 1);
298         k = isl_basic_set_alloc_inequality(bset);
299         if (k < 0)
300                 goto error;
301         isl_seq_clr(bset->ineq[k], 1 + isl_basic_set_total_dim(bset));
302         isl_seq_cpy(bset->ineq[k], c, 1 + nparam);
303         for (i = 0; i < n_div; ++i) {
304                 if (div_purity[i] != PURE_PARAM)
305                         continue;
306                 isl_int_set(bset->ineq[k][1 + nparam + d + i],
307                             c[1 + nparam + d + i]);
308         }
309         isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
310         empty = isl_basic_set_is_empty(bset);
311         isl_basic_set_free(bset);
312
313         return empty;
314 error:
315         isl_basic_set_free(bset);
316         return -1;
317 }
318
319 /* Return PURE_PARAM if only the coefficients of the parameters are non-zero.
320  * Return PURE_VAR if only the coefficients of the set variables are non-zero.
321  * Return MIXED if only the coefficients of the parameters and the set
322  *      variables are non-zero and if moreover the parametric constant
323  *      can never attain positive values.
324  * Return IMPURE otherwise.
325  *
326  * If div_purity is NULL then we are dealing with a non-parametric set
327  * and so the constraint is obviously PURE_VAR.
328  */
329 static int purity(__isl_keep isl_basic_set *bset, isl_int *c, int *div_purity,
330         int eq)
331 {
332         unsigned d;
333         unsigned n_div;
334         unsigned nparam;
335         int empty;
336         int i;
337         int p = 0, v = 0;
338
339         if (!div_purity)
340                 return PURE_VAR;
341
342         n_div = isl_basic_set_dim(bset, isl_dim_div);
343         d = isl_basic_set_dim(bset, isl_dim_set);
344         nparam = isl_basic_set_dim(bset, isl_dim_param);
345
346         for (i = 0; i < n_div; ++i) {
347                 if (isl_int_is_zero(c[1 + nparam + d + i]))
348                         continue;
349                 switch (div_purity[i]) {
350                 case PURE_PARAM: p = 1; break;
351                 case PURE_VAR: v = 1; break;
352                 default: return IMPURE;
353                 }
354         }
355         if (!p && isl_seq_first_non_zero(c + 1, nparam) == -1)
356                 return PURE_VAR;
357         if (!v && isl_seq_first_non_zero(c + 1 + nparam, d) == -1)
358                 return PURE_PARAM;
359
360         empty = parametric_constant_never_positive(bset, c, div_purity);
361         if (eq && empty >= 0 && !empty) {
362                 isl_seq_neg(c, c, 1 + nparam + d + n_div);
363                 empty = parametric_constant_never_positive(bset, c, div_purity);
364         }
365
366         return empty < 0 ? -1 : empty ? MIXED : IMPURE;
367 }
368
369 /* Return an array of integers indicating the type of each div in bset.
370  * If the div is (recursively) defined in terms of only the parameters,
371  * then the type is PURE_PARAM.
372  * If the div is (recursively) defined in terms of only the set variables,
373  * then the type is PURE_VAR.
374  * Otherwise, the type is IMPURE.
375  */
376 static __isl_give int *get_div_purity(__isl_keep isl_basic_set *bset)
377 {
378         int i, j;
379         int *div_purity;
380         unsigned d;
381         unsigned n_div;
382         unsigned nparam;
383
384         if (!bset)
385                 return NULL;
386
387         n_div = isl_basic_set_dim(bset, isl_dim_div);
388         d = isl_basic_set_dim(bset, isl_dim_set);
389         nparam = isl_basic_set_dim(bset, isl_dim_param);
390
391         div_purity = isl_alloc_array(bset->ctx, int, n_div);
392         if (!div_purity)
393                 return NULL;
394
395         for (i = 0; i < bset->n_div; ++i) {
396                 int p = 0, v = 0;
397                 if (isl_int_is_zero(bset->div[i][0])) {
398                         div_purity[i] = IMPURE;
399                         continue;
400                 }
401                 if (isl_seq_first_non_zero(bset->div[i] + 2, nparam) != -1)
402                         p = 1;
403                 if (isl_seq_first_non_zero(bset->div[i] + 2 + nparam, d) != -1)
404                         v = 1;
405                 for (j = 0; j < i; ++j) {
406                         if (isl_int_is_zero(bset->div[i][2 + nparam + d + j]))
407                                 continue;
408                         switch (div_purity[j]) {
409                         case PURE_PARAM: p = 1; break;
410                         case PURE_VAR: v = 1; break;
411                         default: p = v = 1; break;
412                         }
413                 }
414                 div_purity[i] = v ? p ? IMPURE : PURE_VAR : PURE_PARAM;
415         }
416
417         return div_purity;
418 }
419
420 /* Given a path with the as yet unconstrained length at position "pos",
421  * check if setting the length to zero results in only the identity
422  * mapping.
423  */
424 static int empty_path_is_identity(__isl_keep isl_basic_map *path, unsigned pos)
425 {
426         isl_basic_map *test = NULL;
427         isl_basic_map *id = NULL;
428         int k;
429         int is_id;
430
431         test = isl_basic_map_copy(path);
432         test = isl_basic_map_extend_constraints(test, 1, 0);
433         k = isl_basic_map_alloc_equality(test);
434         if (k < 0)
435                 goto error;
436         isl_seq_clr(test->eq[k], 1 + isl_basic_map_total_dim(test));
437         isl_int_set_si(test->eq[k][pos], 1);
438         id = isl_basic_map_identity(isl_basic_map_get_dim(path));
439         is_id = isl_basic_map_is_equal(test, id);
440         isl_basic_map_free(test);
441         isl_basic_map_free(id);
442         return is_id;
443 error:
444         isl_basic_map_free(test);
445         return -1;
446 }
447
448 /* If any of the constraints is found to be impure then this function
449  * sets *impurity to 1.
450  */
451 static __isl_give isl_basic_map *add_delta_constraints(
452         __isl_take isl_basic_map *path,
453         __isl_keep isl_basic_set *delta, unsigned off, unsigned nparam,
454         unsigned d, int *div_purity, int eq, int *impurity)
455 {
456         int i, k;
457         int n = eq ? delta->n_eq : delta->n_ineq;
458         isl_int **delta_c = eq ? delta->eq : delta->ineq;
459         unsigned n_div;
460
461         n_div = isl_basic_set_dim(delta, isl_dim_div);
462
463         for (i = 0; i < n; ++i) {
464                 isl_int *path_c;
465                 int p = purity(delta, delta_c[i], div_purity, eq);
466                 if (p < 0)
467                         goto error;
468                 if (p != PURE_VAR && p != PURE_PARAM && !*impurity)
469                         *impurity = 1;
470                 if (p == IMPURE)
471                         continue;
472                 if (eq && p != MIXED) {
473                         k = isl_basic_map_alloc_equality(path);
474                         path_c = path->eq[k];
475                 } else {
476                         k = isl_basic_map_alloc_inequality(path);
477                         path_c = path->ineq[k];
478                 }
479                 if (k < 0)
480                         goto error;
481                 isl_seq_clr(path_c, 1 + isl_basic_map_total_dim(path));
482                 if (p == PURE_VAR) {
483                         isl_seq_cpy(path_c + off,
484                                     delta_c[i] + 1 + nparam, d);
485                         isl_int_set(path_c[off + d], delta_c[i][0]);
486                 } else if (p == PURE_PARAM) {
487                         isl_seq_cpy(path_c, delta_c[i], 1 + nparam);
488                 } else {
489                         isl_seq_cpy(path_c + off,
490                                     delta_c[i] + 1 + nparam, d);
491                         isl_seq_cpy(path_c, delta_c[i], 1 + nparam);
492                 }
493                 isl_seq_cpy(path_c + off - n_div,
494                             delta_c[i] + 1 + nparam + d, n_div);
495         }
496
497         return path;
498 error:
499         isl_basic_map_free(path);
500         return NULL;
501 }
502
503 /* Given a set of offsets "delta", construct a relation of the
504  * given dimension specification (Z^{n+1} -> Z^{n+1}) that
505  * is an overapproximation of the relations that
506  * maps an element x to any element that can be reached
507  * by taking a non-negative number of steps along any of
508  * the elements in "delta".
509  * That is, construct an approximation of
510  *
511  *      { [x] -> [y] : exists f \in \delta, k \in Z :
512  *                                      y = x + k [f, 1] and k >= 0 }
513  *
514  * For any element in this relation, the number of steps taken
515  * is equal to the difference in the final coordinates.
516  *
517  * In particular, let delta be defined as
518  *
519  *      \delta = [p] -> { [x] : A x + a >= 0 and B p + b >= 0 and
520  *                              C x + C'p + c >= 0 and
521  *                              D x + D'p + d >= 0 }
522  *
523  * where the constraints C x + C'p + c >= 0 are such that the parametric
524  * constant term of each constraint j, "C_j x + C'_j p + c_j",
525  * can never attain positive values, then the relation is constructed as
526  *
527  *      { [x] -> [y] : exists [f, k] \in Z^{n+1} : y = x + f and
528  *                      A f + k a >= 0 and B p + b >= 0 and
529  *                      C f + C'p + c >= 0 and k >= 1 }
530  *      union { [x] -> [x] }
531  *
532  * If the zero-length paths happen to correspond exactly to the identity
533  * mapping, then we return
534  *
535  *      { [x] -> [y] : exists [f, k] \in Z^{n+1} : y = x + f and
536  *                      A f + k a >= 0 and B p + b >= 0 and
537  *                      C f + C'p + c >= 0 and k >= 0 }
538  *
539  * instead.
540  *
541  * Existentially quantified variables in \delta are handled by
542  * classifying them as independent of the parameters, purely
543  * parameter dependent and others.  Constraints containing
544  * any of the other existentially quantified variables are removed.
545  * This is safe, but leads to an additional overapproximation.
546  *
547  * If there are any impure constraints, then we also eliminate
548  * the parameters from \delta, resulting in a set
549  *
550  *      \delta' = { [x] : E x + e >= 0 }
551  *
552  * and add the constraints
553  *
554  *                      E f + k e >= 0
555  *
556  * to the constructed relation.
557  */
558 static __isl_give isl_map *path_along_delta(__isl_take isl_dim *dim,
559         __isl_take isl_basic_set *delta)
560 {
561         isl_basic_map *path = NULL;
562         unsigned d;
563         unsigned n_div;
564         unsigned nparam;
565         unsigned off;
566         int i, k;
567         int is_id;
568         int *div_purity = NULL;
569         int impurity = 0;
570
571         if (!delta)
572                 goto error;
573         n_div = isl_basic_set_dim(delta, isl_dim_div);
574         d = isl_basic_set_dim(delta, isl_dim_set);
575         nparam = isl_basic_set_dim(delta, isl_dim_param);
576         path = isl_basic_map_alloc_dim(isl_dim_copy(dim), n_div + d + 1,
577                         d + 1 + delta->n_eq, delta->n_eq + delta->n_ineq + 1);
578         off = 1 + nparam + 2 * (d + 1) + n_div;
579
580         for (i = 0; i < n_div + d + 1; ++i) {
581                 k = isl_basic_map_alloc_div(path);
582                 if (k < 0)
583                         goto error;
584                 isl_int_set_si(path->div[k][0], 0);
585         }
586
587         for (i = 0; i < d + 1; ++i) {
588                 k = isl_basic_map_alloc_equality(path);
589                 if (k < 0)
590                         goto error;
591                 isl_seq_clr(path->eq[k], 1 + isl_basic_map_total_dim(path));
592                 isl_int_set_si(path->eq[k][1 + nparam + i], 1);
593                 isl_int_set_si(path->eq[k][1 + nparam + d + 1 + i], -1);
594                 isl_int_set_si(path->eq[k][off + i], 1);
595         }
596
597         div_purity = get_div_purity(delta);
598         if (!div_purity)
599                 goto error;
600
601         path = add_delta_constraints(path, delta, off, nparam, d,
602                                      div_purity, 1, &impurity);
603         path = add_delta_constraints(path, delta, off, nparam, d,
604                                      div_purity, 0, &impurity);
605         if (impurity) {
606                 isl_dim *dim = isl_basic_set_get_dim(delta);
607                 delta = isl_basic_set_project_out(delta,
608                                                   isl_dim_param, 0, nparam);
609                 delta = isl_basic_set_add(delta, isl_dim_param, nparam);
610                 delta = isl_basic_set_reset_dim(delta, dim);
611                 if (!delta)
612                         goto error;
613                 path = isl_basic_map_extend_constraints(path, delta->n_eq,
614                                                         delta->n_ineq + 1);
615                 path = add_delta_constraints(path, delta, off, nparam, d,
616                                              NULL, 1, &impurity);
617                 path = add_delta_constraints(path, delta, off, nparam, d,
618                                              NULL, 0, &impurity);
619                 path = isl_basic_map_gauss(path, NULL);
620         }
621
622         is_id = empty_path_is_identity(path, off + d);
623         if (is_id < 0)
624                 goto error;
625
626         k = isl_basic_map_alloc_inequality(path);
627         if (k < 0)
628                 goto error;
629         isl_seq_clr(path->ineq[k], 1 + isl_basic_map_total_dim(path));
630         if (!is_id)
631                 isl_int_set_si(path->ineq[k][0], -1);
632         isl_int_set_si(path->ineq[k][off + d], 1);
633                         
634         free(div_purity);
635         isl_basic_set_free(delta);
636         path = isl_basic_map_finalize(path);
637         if (is_id) {
638                 isl_dim_free(dim);
639                 return isl_map_from_basic_map(path);
640         }
641         return isl_basic_map_union(path, isl_basic_map_identity(dim));
642 error:
643         free(div_purity);
644         isl_dim_free(dim);
645         isl_basic_set_free(delta);
646         isl_basic_map_free(path);
647         return NULL;
648 }
649
650 /* Given a dimension specification Z^{n+1} -> Z^{n+1} and a parameter "param",
651  * construct a map that equates the parameter to the difference
652  * in the final coordinates and imposes that this difference is positive.
653  * That is, construct
654  *
655  *      { [x,x_s] -> [y,y_s] : k = y_s - x_s > 0 }
656  */
657 static __isl_give isl_map *equate_parameter_to_length(__isl_take isl_dim *dim,
658         unsigned param)
659 {
660         struct isl_basic_map *bmap;
661         unsigned d;
662         unsigned nparam;
663         int k;
664
665         d = isl_dim_size(dim, isl_dim_in);
666         nparam = isl_dim_size(dim, isl_dim_param);
667         bmap = isl_basic_map_alloc_dim(dim, 0, 1, 1);
668         k = isl_basic_map_alloc_equality(bmap);
669         if (k < 0)
670                 goto error;
671         isl_seq_clr(bmap->eq[k], 1 + isl_basic_map_total_dim(bmap));
672         isl_int_set_si(bmap->eq[k][1 + param], -1);
673         isl_int_set_si(bmap->eq[k][1 + nparam + d - 1], -1);
674         isl_int_set_si(bmap->eq[k][1 + nparam + d + d - 1], 1);
675
676         k = isl_basic_map_alloc_inequality(bmap);
677         if (k < 0)
678                 goto error;
679         isl_seq_clr(bmap->ineq[k], 1 + isl_basic_map_total_dim(bmap));
680         isl_int_set_si(bmap->ineq[k][1 + param], 1);
681         isl_int_set_si(bmap->ineq[k][0], -1);
682
683         bmap = isl_basic_map_finalize(bmap);
684         return isl_map_from_basic_map(bmap);
685 error:
686         isl_basic_map_free(bmap);
687         return NULL;
688 }
689
690 /* Check whether "path" is acyclic, where the last coordinates of domain
691  * and range of path encode the number of steps taken.
692  * That is, check whether
693  *
694  *      { d | d = y - x and (x,y) in path }
695  *
696  * does not contain any element with positive last coordinate (positive length)
697  * and zero remaining coordinates (cycle).
698  */
699 static int is_acyclic(__isl_take isl_map *path)
700 {
701         int i;
702         int acyclic;
703         unsigned dim;
704         struct isl_set *delta;
705
706         delta = isl_map_deltas(path);
707         dim = isl_set_dim(delta, isl_dim_set);
708         for (i = 0; i < dim; ++i) {
709                 if (i == dim -1)
710                         delta = isl_set_lower_bound_si(delta, isl_dim_set, i, 1);
711                 else
712                         delta = isl_set_fix_si(delta, isl_dim_set, i, 0);
713         }
714
715         acyclic = isl_set_is_empty(delta);
716         isl_set_free(delta);
717
718         return acyclic;
719 }
720
721 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
722  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
723  * construct a map that is an overapproximation of the map
724  * that takes an element from the space D \times Z to another
725  * element from the same space, such that the first n coordinates of the
726  * difference between them is a sum of differences between images
727  * and pre-images in one of the R_i and such that the last coordinate
728  * is equal to the number of steps taken.
729  * That is, let
730  *
731  *      \Delta_i = { y - x | (x, y) in R_i }
732  *
733  * then the constructed map is an overapproximation of
734  *
735  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
736  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) }
737  *
738  * The elements of the singleton \Delta_i's are collected as the
739  * rows of the steps matrix.  For all these \Delta_i's together,
740  * a single path is constructed.
741  * For each of the other \Delta_i's, we compute an overapproximation
742  * of the paths along elements of \Delta_i.
743  * Since each of these paths performs an addition, composition is
744  * symmetric and we can simply compose all resulting paths in any order.
745  */
746 static __isl_give isl_map *construct_extended_path(__isl_take isl_dim *dim,
747         __isl_keep isl_map *map, int *project)
748 {
749         struct isl_mat *steps = NULL;
750         struct isl_map *path = NULL;
751         unsigned d;
752         int i, j, n;
753
754         d = isl_map_dim(map, isl_dim_in);
755
756         path = isl_map_identity(isl_dim_copy(dim));
757
758         steps = isl_mat_alloc(map->ctx, map->n, d);
759         if (!steps)
760                 goto error;
761
762         n = 0;
763         for (i = 0; i < map->n; ++i) {
764                 struct isl_basic_set *delta;
765
766                 delta = isl_basic_map_deltas(isl_basic_map_copy(map->p[i]));
767
768                 for (j = 0; j < d; ++j) {
769                         int fixed;
770
771                         fixed = isl_basic_set_fast_dim_is_fixed(delta, j,
772                                                             &steps->row[n][j]);
773                         if (fixed < 0) {
774                                 isl_basic_set_free(delta);
775                                 goto error;
776                         }
777                         if (!fixed)
778                                 break;
779                 }
780
781
782                 if (j < d) {
783                         path = isl_map_apply_range(path,
784                                 path_along_delta(isl_dim_copy(dim), delta));
785                         path = isl_map_coalesce(path);
786                 } else {
787                         isl_basic_set_free(delta);
788                         ++n;
789                 }
790         }
791
792         if (n > 0) {
793                 steps->n_row = n;
794                 path = isl_map_apply_range(path,
795                                 path_along_steps(isl_dim_copy(dim), steps));
796         }
797
798         if (project && *project) {
799                 *project = is_acyclic(isl_map_copy(path));
800                 if (*project < 0)
801                         goto error;
802         }
803
804         isl_dim_free(dim);
805         isl_mat_free(steps);
806         return path;
807 error:
808         isl_dim_free(dim);
809         isl_mat_free(steps);
810         isl_map_free(path);
811         return NULL;
812 }
813
814 static int isl_set_overlaps(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
815 {
816         isl_set *i;
817         int no_overlap;
818
819         if (!isl_dim_tuple_match(set1->dim, isl_dim_set, set2->dim, isl_dim_set))
820                 return 0;
821
822         i = isl_set_intersect(isl_set_copy(set1), isl_set_copy(set2));
823         no_overlap = isl_set_is_empty(i);
824         isl_set_free(i);
825
826         return no_overlap < 0 ? -1 : !no_overlap;
827 }
828
829 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
830  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
831  * construct a map that is an overapproximation of the map
832  * that takes an element from the dom R \times Z to an
833  * element from ran R \times Z, such that the first n coordinates of the
834  * difference between them is a sum of differences between images
835  * and pre-images in one of the R_i and such that the last coordinate
836  * is equal to the number of steps taken.
837  * That is, let
838  *
839  *      \Delta_i = { y - x | (x, y) in R_i }
840  *
841  * then the constructed map is an overapproximation of
842  *
843  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
844  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) and
845  *                              x in dom R and x + d in ran R and
846  *                              \sum_i k_i >= 1 }
847  */
848 static __isl_give isl_map *construct_component(__isl_take isl_dim *dim,
849         __isl_keep isl_map *map, int *exact, int project)
850 {
851         struct isl_set *domain = NULL;
852         struct isl_set *range = NULL;
853         struct isl_map *app = NULL;
854         struct isl_map *path = NULL;
855
856         domain = isl_map_domain(isl_map_copy(map));
857         domain = isl_set_coalesce(domain);
858         range = isl_map_range(isl_map_copy(map));
859         range = isl_set_coalesce(range);
860         if (!isl_set_overlaps(domain, range)) {
861                 isl_set_free(domain);
862                 isl_set_free(range);
863                 isl_dim_free(dim);
864
865                 map = isl_map_copy(map);
866                 map = isl_map_add_dims(map, isl_dim_in, 1);
867                 map = isl_map_add_dims(map, isl_dim_out, 1);
868                 map = set_path_length(map, 1, 1);
869                 return map;
870         }
871         app = isl_map_from_domain_and_range(domain, range);
872         app = isl_map_add_dims(app, isl_dim_in, 1);
873         app = isl_map_add_dims(app, isl_dim_out, 1);
874
875         path = construct_extended_path(isl_dim_copy(dim), map,
876                                         exact && *exact ? &project : NULL);
877         app = isl_map_intersect(app, path);
878
879         if (exact && *exact &&
880             (*exact = check_exactness(isl_map_copy(map), isl_map_copy(app),
881                                       project)) < 0)
882                 goto error;
883
884         isl_dim_free(dim);
885         app = set_path_length(app, 0, 1);
886         return app;
887 error:
888         isl_dim_free(dim);
889         isl_map_free(app);
890         return NULL;
891 }
892
893 /* Call construct_component and, if "project" is set, project out
894  * the final coordinates.
895  */
896 static __isl_give isl_map *construct_projected_component(
897         __isl_take isl_dim *dim,
898         __isl_keep isl_map *map, int *exact, int project)
899 {
900         isl_map *app;
901         unsigned d;
902
903         if (!dim)
904                 return NULL;
905         d = isl_dim_size(dim, isl_dim_in);
906
907         app = construct_component(dim, map, exact, project);
908         if (project) {
909                 app = isl_map_project_out(app, isl_dim_in, d - 1, 1);
910                 app = isl_map_project_out(app, isl_dim_out, d - 1, 1);
911         }
912         return app;
913 }
914
915 /* Compute an extended version, i.e., with path lengths, of
916  * an overapproximation of the transitive closure of "bmap"
917  * with path lengths greater than or equal to zero and with
918  * domain and range equal to "dom".
919  */
920 static __isl_give isl_map *q_closure(__isl_take isl_dim *dim,
921         __isl_take isl_set *dom, __isl_keep isl_basic_map *bmap, int *exact)
922 {
923         int project = 1;
924         isl_map *path;
925         isl_map *map;
926         isl_map *app;
927
928         dom = isl_set_add_dims(dom, isl_dim_set, 1);
929         app = isl_map_from_domain_and_range(dom, isl_set_copy(dom));
930         map = isl_map_from_basic_map(isl_basic_map_copy(bmap));
931         path = construct_extended_path(dim, map, &project);
932         app = isl_map_intersect(app, path);
933
934         if ((*exact = check_exactness(map, isl_map_copy(app), project)) < 0)
935                 goto error;
936
937         return app;
938 error:
939         isl_map_free(app);
940         return NULL;
941 }
942
943 /* Check whether qc has any elements of length at least one
944  * with domain and/or range outside of dom and ran.
945  */
946 static int has_spurious_elements(__isl_keep isl_map *qc,
947         __isl_keep isl_set *dom, __isl_keep isl_set *ran)
948 {
949         isl_set *s;
950         int subset;
951         unsigned d;
952
953         if (!qc || !dom || !ran)
954                 return -1;
955
956         d = isl_map_dim(qc, isl_dim_in);
957
958         qc = isl_map_copy(qc);
959         qc = set_path_length(qc, 0, 1);
960         qc = isl_map_project_out(qc, isl_dim_in, d - 1, 1);
961         qc = isl_map_project_out(qc, isl_dim_out, d - 1, 1);
962
963         s = isl_map_domain(isl_map_copy(qc));
964         subset = isl_set_is_subset(s, dom);
965         isl_set_free(s);
966         if (subset < 0)
967                 goto error;
968         if (!subset) {
969                 isl_map_free(qc);
970                 return 1;
971         }
972
973         s = isl_map_range(qc);
974         subset = isl_set_is_subset(s, ran);
975         isl_set_free(s);
976
977         return subset < 0 ? -1 : !subset;
978 error:
979         isl_map_free(qc);
980         return -1;
981 }
982
983 #define LEFT    2
984 #define RIGHT   1
985
986 /* For each basic map in "map", except i, check whether it combines
987  * with the transitive closure that is reflexive on C combines
988  * to the left and to the right.
989  *
990  * In particular, if
991  *
992  *      dom map_j \subseteq C
993  *
994  * then right[j] is set to 1.  Otherwise, if
995  *
996  *      ran map_i \cap dom map_j = \emptyset
997  *
998  * then right[j] is set to 0.  Otherwise, composing to the right
999  * is impossible.
1000  *
1001  * Similar, for composing to the left, we have if
1002  *
1003  *      ran map_j \subseteq C
1004  *
1005  * then left[j] is set to 1.  Otherwise, if
1006  *
1007  *      dom map_i \cap ran map_j = \emptyset
1008  *
1009  * then left[j] is set to 0.  Otherwise, composing to the left
1010  * is impossible.
1011  *
1012  * The return value is or'd with LEFT if composing to the left
1013  * is possible and with RIGHT if composing to the right is possible.
1014  */
1015 static int composability(__isl_keep isl_set *C, int i,
1016         isl_set **dom, isl_set **ran, int *left, int *right,
1017         __isl_keep isl_map *map)
1018 {
1019         int j;
1020         int ok;
1021
1022         ok = LEFT | RIGHT;
1023         for (j = 0; j < map->n && ok; ++j) {
1024                 int overlaps, subset;
1025                 if (j == i)
1026                         continue;
1027
1028                 if (ok & RIGHT) {
1029                         if (!dom[j])
1030                                 dom[j] = isl_set_from_basic_set(
1031                                         isl_basic_map_domain(
1032                                                 isl_basic_map_copy(map->p[j])));
1033                         if (!dom[j])
1034                                 return -1;
1035                         overlaps = isl_set_overlaps(ran[i], dom[j]);
1036                         if (overlaps < 0)
1037                                 return -1;
1038                         if (!overlaps)
1039                                 right[j] = 0;
1040                         else {
1041                                 subset = isl_set_is_subset(dom[j], C);
1042                                 if (subset < 0)
1043                                         return -1;
1044                                 if (subset)
1045                                         right[j] = 1;
1046                                 else
1047                                         ok &= ~RIGHT;
1048                         }
1049                 }
1050
1051                 if (ok & LEFT) {
1052                         if (!ran[j])
1053                                 ran[j] = isl_set_from_basic_set(
1054                                         isl_basic_map_range(
1055                                                 isl_basic_map_copy(map->p[j])));
1056                         if (!ran[j])
1057                                 return -1;
1058                         overlaps = isl_set_overlaps(dom[i], ran[j]);
1059                         if (overlaps < 0)
1060                                 return -1;
1061                         if (!overlaps)
1062                                 left[j] = 0;
1063                         else {
1064                                 subset = isl_set_is_subset(ran[j], C);
1065                                 if (subset < 0)
1066                                         return -1;
1067                                 if (subset)
1068                                         left[j] = 1;
1069                                 else
1070                                         ok &= ~LEFT;
1071                         }
1072                 }
1073         }
1074
1075         return ok;
1076 }
1077
1078 static __isl_give isl_map *anonymize(__isl_take isl_map *map)
1079 {
1080         map = isl_map_reset(map, isl_dim_in);
1081         map = isl_map_reset(map, isl_dim_out);
1082         return map;
1083 }
1084
1085 /* Return a map that is a union of the basic maps in "map", except i,
1086  * composed to left and right with qc based on the entries of "left"
1087  * and "right".
1088  */
1089 static __isl_give isl_map *compose(__isl_keep isl_map *map, int i,
1090         __isl_take isl_map *qc, int *left, int *right)
1091 {
1092         int j;
1093         isl_map *comp;
1094
1095         comp = isl_map_empty(isl_map_get_dim(map));
1096         for (j = 0; j < map->n; ++j) {
1097                 isl_map *map_j;
1098
1099                 if (j == i)
1100                         continue;
1101
1102                 map_j = isl_map_from_basic_map(isl_basic_map_copy(map->p[j]));
1103                 map_j = anonymize(map_j);
1104                 if (left && left[j])
1105                         map_j = isl_map_apply_range(map_j, isl_map_copy(qc));
1106                 if (right && right[j])
1107                         map_j = isl_map_apply_range(isl_map_copy(qc), map_j);
1108                 comp = isl_map_union(comp, map_j);
1109         }
1110
1111         comp = isl_map_compute_divs(comp);
1112         comp = isl_map_coalesce(comp);
1113
1114         isl_map_free(qc);
1115
1116         return comp;
1117 }
1118
1119 /* Compute the transitive closure of "map" incrementally by
1120  * computing
1121  *
1122  *      map_i^+ \cup qc^+
1123  *
1124  * or
1125  *
1126  *      map_i^+ \cup ((id \cup map_i^) \circ qc^+)
1127  *
1128  * or
1129  *
1130  *      map_i^+ \cup (qc^+ \circ (id \cup map_i^))
1131  *
1132  * depending on whether left or right are NULL.
1133  */
1134 static __isl_give isl_map *compute_incremental(
1135         __isl_take isl_dim *dim, __isl_keep isl_map *map,
1136         int i, __isl_take isl_map *qc, int *left, int *right, int *exact)
1137 {
1138         isl_map *map_i;
1139         isl_map *tc;
1140         isl_map *rtc = NULL;
1141
1142         if (!map)
1143                 goto error;
1144         isl_assert(map->ctx, left || right, goto error);
1145
1146         map_i = isl_map_from_basic_map(isl_basic_map_copy(map->p[i]));
1147         tc = construct_projected_component(isl_dim_copy(dim), map_i,
1148                                                 exact, 1);
1149         isl_map_free(map_i);
1150
1151         if (*exact)
1152                 qc = isl_map_transitive_closure(qc, exact);
1153
1154         if (!*exact) {
1155                 isl_dim_free(dim);
1156                 isl_map_free(tc);
1157                 isl_map_free(qc);
1158                 return isl_map_universe(isl_map_get_dim(map));
1159         }
1160
1161         if (!left || !right)
1162                 rtc = isl_map_union(isl_map_copy(tc),
1163                                     isl_map_identity(isl_map_get_dim(tc)));
1164         if (!right)
1165                 qc = isl_map_apply_range(rtc, qc);
1166         if (!left)
1167                 qc = isl_map_apply_range(qc, rtc);
1168         qc = isl_map_union(tc, qc);
1169
1170         isl_dim_free(dim);
1171
1172         return qc;
1173 error:
1174         isl_dim_free(dim);
1175         isl_map_free(qc);
1176         return NULL;
1177 }
1178
1179 /* Given a map "map", try to find a basic map such that
1180  * map^+ can be computed as
1181  *
1182  * map^+ = map_i^+ \cup
1183  *    \bigcup_j ((map_i^+ \cup Id_C)^+ \circ map_j \circ (map_i^+ \cup Id_C))^+
1184  *
1185  * with C the simple hull of the domain and range of the input map.
1186  * map_i^ \cup Id_C is computed by allowing the path lengths to be zero
1187  * and by intersecting domain and range with C.
1188  * Of course, we need to check that this is actually equal to map_i^ \cup Id_C.
1189  * Also, we only use the incremental computation if all the transitive
1190  * closures are exact and if the number of basic maps in the union,
1191  * after computing the integer divisions, is smaller than the number
1192  * of basic maps in the input map.
1193  */
1194 static int incemental_on_entire_domain(__isl_keep isl_dim *dim,
1195         __isl_keep isl_map *map,
1196         isl_set **dom, isl_set **ran, int *left, int *right,
1197         __isl_give isl_map **res)
1198 {
1199         int i;
1200         isl_set *C;
1201         unsigned d;
1202
1203         *res = NULL;
1204
1205         C = isl_set_union(isl_map_domain(isl_map_copy(map)),
1206                           isl_map_range(isl_map_copy(map)));
1207         C = isl_set_from_basic_set(isl_set_simple_hull(C));
1208         if (!C)
1209                 return -1;
1210         if (C->n != 1) {
1211                 isl_set_free(C);
1212                 return 0;
1213         }
1214
1215         d = isl_map_dim(map, isl_dim_in);
1216
1217         for (i = 0; i < map->n; ++i) {
1218                 isl_map *qc;
1219                 int exact_i, spurious;
1220                 int j;
1221                 dom[i] = isl_set_from_basic_set(isl_basic_map_domain(
1222                                         isl_basic_map_copy(map->p[i])));
1223                 ran[i] = isl_set_from_basic_set(isl_basic_map_range(
1224                                         isl_basic_map_copy(map->p[i])));
1225                 qc = q_closure(isl_dim_copy(dim), isl_set_copy(C),
1226                                 map->p[i], &exact_i);
1227                 if (!qc)
1228                         goto error;
1229                 if (!exact_i) {
1230                         isl_map_free(qc);
1231                         continue;
1232                 }
1233                 spurious = has_spurious_elements(qc, dom[i], ran[i]);
1234                 if (spurious) {
1235                         isl_map_free(qc);
1236                         if (spurious < 0)
1237                                 goto error;
1238                         continue;
1239                 }
1240                 qc = isl_map_project_out(qc, isl_dim_in, d, 1);
1241                 qc = isl_map_project_out(qc, isl_dim_out, d, 1);
1242                 qc = isl_map_compute_divs(qc);
1243                 for (j = 0; j < map->n; ++j)
1244                         left[j] = right[j] = 1;
1245                 qc = compose(map, i, qc, left, right);
1246                 if (!qc)
1247                         goto error;
1248                 if (qc->n >= map->n) {
1249                         isl_map_free(qc);
1250                         continue;
1251                 }
1252                 *res = compute_incremental(isl_dim_copy(dim), map, i, qc,
1253                                 left, right, &exact_i);
1254                 if (!*res)
1255                         goto error;
1256                 if (exact_i)
1257                         break;
1258                 isl_map_free(*res);
1259                 *res = NULL;
1260         }
1261
1262         isl_set_free(C);
1263
1264         return *res != NULL;
1265 error:
1266         isl_set_free(C);
1267         return -1;
1268 }
1269
1270 /* Try and compute the transitive closure of "map" as
1271  *
1272  * map^+ = map_i^+ \cup
1273  *    \bigcup_j ((map_i^+ \cup Id_C)^+ \circ map_j \circ (map_i^+ \cup Id_C))^+
1274  *
1275  * with C either the simple hull of the domain and range of the entire
1276  * map or the simple hull of domain and range of map_i.
1277  */
1278 static __isl_give isl_map *incremental_closure(__isl_take isl_dim *dim,
1279         __isl_keep isl_map *map, int *exact, int project)
1280 {
1281         int i;
1282         isl_set **dom = NULL;
1283         isl_set **ran = NULL;
1284         int *left = NULL;
1285         int *right = NULL;
1286         isl_set *C;
1287         unsigned d;
1288         isl_map *res = NULL;
1289
1290         if (!project)
1291                 return construct_projected_component(dim, map, exact, project);
1292
1293         if (!map)
1294                 goto error;
1295         if (map->n <= 1)
1296                 return construct_projected_component(dim, map, exact, project);
1297
1298         d = isl_map_dim(map, isl_dim_in);
1299
1300         dom = isl_calloc_array(map->ctx, isl_set *, map->n);
1301         ran = isl_calloc_array(map->ctx, isl_set *, map->n);
1302         left = isl_calloc_array(map->ctx, int, map->n);
1303         right = isl_calloc_array(map->ctx, int, map->n);
1304         if (!ran || !dom || !left || !right)
1305                 goto error;
1306
1307         if (incemental_on_entire_domain(dim, map, dom, ran, left, right, &res) < 0)
1308                 goto error;
1309
1310         for (i = 0; !res && i < map->n; ++i) {
1311                 isl_map *qc;
1312                 int exact_i, spurious, comp;
1313                 if (!dom[i])
1314                         dom[i] = isl_set_from_basic_set(
1315                                         isl_basic_map_domain(
1316                                                 isl_basic_map_copy(map->p[i])));
1317                 if (!dom[i])
1318                         goto error;
1319                 if (!ran[i])
1320                         ran[i] = isl_set_from_basic_set(
1321                                         isl_basic_map_range(
1322                                                 isl_basic_map_copy(map->p[i])));
1323                 if (!ran[i])
1324                         goto error;
1325                 C = isl_set_union(isl_set_copy(dom[i]),
1326                                       isl_set_copy(ran[i]));
1327                 C = isl_set_from_basic_set(isl_set_simple_hull(C));
1328                 if (!C)
1329                         goto error;
1330                 if (C->n != 1) {
1331                         isl_set_free(C);
1332                         continue;
1333                 }
1334                 comp = composability(C, i, dom, ran, left, right, map);
1335                 if (!comp || comp < 0) {
1336                         isl_set_free(C);
1337                         if (comp < 0)
1338                                 goto error;
1339                         continue;
1340                 }
1341                 qc = q_closure(isl_dim_copy(dim), C, map->p[i], &exact_i);
1342                 if (!qc)
1343                         goto error;
1344                 if (!exact_i) {
1345                         isl_map_free(qc);
1346                         continue;
1347                 }
1348                 spurious = has_spurious_elements(qc, dom[i], ran[i]);
1349                 if (spurious) {
1350                         isl_map_free(qc);
1351                         if (spurious < 0)
1352                                 goto error;
1353                         continue;
1354                 }
1355                 qc = isl_map_project_out(qc, isl_dim_in, d, 1);
1356                 qc = isl_map_project_out(qc, isl_dim_out, d, 1);
1357                 qc = isl_map_compute_divs(qc);
1358                 qc = compose(map, i, qc, (comp & LEFT) ? left : NULL,
1359                                 (comp & RIGHT) ? right : NULL);
1360                 if (!qc)
1361                         goto error;
1362                 if (qc->n >= map->n) {
1363                         isl_map_free(qc);
1364                         continue;
1365                 }
1366                 res = compute_incremental(isl_dim_copy(dim), map, i, qc,
1367                                 (comp & LEFT) ? left : NULL,
1368                                 (comp & RIGHT) ? right : NULL, &exact_i);
1369                 if (!res)
1370                         goto error;
1371                 if (exact_i)
1372                         break;
1373                 isl_map_free(res);
1374                 res = NULL;
1375         }
1376
1377         for (i = 0; i < map->n; ++i) {
1378                 isl_set_free(dom[i]);
1379                 isl_set_free(ran[i]);
1380         }
1381         free(dom);
1382         free(ran);
1383         free(left);
1384         free(right);
1385
1386         if (res) {
1387                 isl_dim_free(dim);
1388                 return res;
1389         }
1390
1391         return construct_projected_component(dim, map, exact, project);
1392 error:
1393         if (dom)
1394                 for (i = 0; i < map->n; ++i)
1395                         isl_set_free(dom[i]);
1396         free(dom);
1397         if (ran)
1398                 for (i = 0; i < map->n; ++i)
1399                         isl_set_free(ran[i]);
1400         free(ran);
1401         free(left);
1402         free(right);
1403         isl_dim_free(dim);
1404         return NULL;
1405 }
1406
1407 /* Given an array of sets "set", add "dom" at position "pos"
1408  * and search for elements at earlier positions that overlap with "dom".
1409  * If any can be found, then merge all of them, together with "dom", into
1410  * a single set and assign the union to the first in the array,
1411  * which becomes the new group leader for all groups involved in the merge.
1412  * During the search, we only consider group leaders, i.e., those with
1413  * group[i] = i, as the other sets have already been combined
1414  * with one of the group leaders.
1415  */
1416 static int merge(isl_set **set, int *group, __isl_take isl_set *dom, int pos)
1417 {
1418         int i;
1419
1420         group[pos] = pos;
1421         set[pos] = isl_set_copy(dom);
1422
1423         for (i = pos - 1; i >= 0; --i) {
1424                 int o;
1425
1426                 if (group[i] != i)
1427                         continue;
1428
1429                 o = isl_set_overlaps(set[i], dom);
1430                 if (o < 0)
1431                         goto error;
1432                 if (!o)
1433                         continue;
1434
1435                 set[i] = isl_set_union(set[i], set[group[pos]]);
1436                 set[group[pos]] = NULL;
1437                 if (!set[i])
1438                         goto error;
1439                 group[group[pos]] = i;
1440                 group[pos] = i;
1441         }
1442
1443         isl_set_free(dom);
1444         return 0;
1445 error:
1446         isl_set_free(dom);
1447         return -1;
1448 }
1449
1450 /* Replace each entry in the n by n grid of maps by the cross product
1451  * with the relation { [i] -> [i + 1] }.
1452  */
1453 static int add_length(__isl_keep isl_map *map, isl_map ***grid, int n)
1454 {
1455         int i, j, k;
1456         isl_dim *dim;
1457         isl_basic_map *bstep;
1458         isl_map *step;
1459         unsigned nparam;
1460
1461         if (!map)
1462                 return -1;
1463
1464         dim = isl_map_get_dim(map);
1465         nparam = isl_dim_size(dim, isl_dim_param);
1466         dim = isl_dim_drop(dim, isl_dim_in, 0, isl_dim_size(dim, isl_dim_in));
1467         dim = isl_dim_drop(dim, isl_dim_out, 0, isl_dim_size(dim, isl_dim_out));
1468         dim = isl_dim_add(dim, isl_dim_in, 1);
1469         dim = isl_dim_add(dim, isl_dim_out, 1);
1470         bstep = isl_basic_map_alloc_dim(dim, 0, 1, 0);
1471         k = isl_basic_map_alloc_equality(bstep);
1472         if (k < 0) {
1473                 isl_basic_map_free(bstep);
1474                 return -1;
1475         }
1476         isl_seq_clr(bstep->eq[k], 1 + isl_basic_map_total_dim(bstep));
1477         isl_int_set_si(bstep->eq[k][0], 1);
1478         isl_int_set_si(bstep->eq[k][1 + nparam], 1);
1479         isl_int_set_si(bstep->eq[k][1 + nparam + 1], -1);
1480         bstep = isl_basic_map_finalize(bstep);
1481         step = isl_map_from_basic_map(bstep);
1482
1483         for (i = 0; i < n; ++i)
1484                 for (j = 0; j < n; ++j)
1485                         grid[i][j] = isl_map_product(grid[i][j],
1486                                                      isl_map_copy(step));
1487
1488         isl_map_free(step);
1489
1490         return 0;
1491 }
1492
1493 /* The core of the Floyd-Warshall algorithm.
1494  * Updates the given n x x matrix of relations in place.
1495  *
1496  * The algorithm iterates over all vertices.  In each step, the whole
1497  * matrix is updated to include all paths that go to the current vertex,
1498  * possibly stay there a while (including passing through earlier vertices)
1499  * and then come back.  At the start of each iteration, the diagonal
1500  * element corresponding to the current vertex is replaced by its
1501  * transitive closure to account for all indirect paths that stay
1502  * in the current vertex.
1503  */
1504 static void floyd_warshall_iterate(isl_map ***grid, int n, int *exact)
1505 {
1506         int r, p, q;
1507
1508         for (r = 0; r < n; ++r) {
1509                 int r_exact;
1510                 grid[r][r] = isl_map_transitive_closure(grid[r][r],
1511                                 (exact && *exact) ? &r_exact : NULL);
1512                 if (exact && *exact && !r_exact)
1513                         *exact = 0;
1514
1515                 for (p = 0; p < n; ++p)
1516                         for (q = 0; q < n; ++q) {
1517                                 isl_map *loop;
1518                                 if (p == r && q == r)
1519                                         continue;
1520                                 loop = isl_map_apply_range(
1521                                                 isl_map_copy(grid[p][r]),
1522                                                 isl_map_copy(grid[r][q]));
1523                                 grid[p][q] = isl_map_union(grid[p][q], loop);
1524                                 loop = isl_map_apply_range(
1525                                                 isl_map_copy(grid[p][r]),
1526                                         isl_map_apply_range(
1527                                                 isl_map_copy(grid[r][r]),
1528                                                 isl_map_copy(grid[r][q])));
1529                                 grid[p][q] = isl_map_union(grid[p][q], loop);
1530                                 grid[p][q] = isl_map_coalesce(grid[p][q]);
1531                         }
1532         }
1533 }
1534
1535 /* Given a partition of the domains and ranges of the basic maps in "map",
1536  * apply the Floyd-Warshall algorithm with the elements in the partition
1537  * as vertices.
1538  *
1539  * In particular, there are "n" elements in the partition and "group" is
1540  * an array of length 2 * map->n with entries in [0,n-1].
1541  *
1542  * We first construct a matrix of relations based on the partition information,
1543  * apply Floyd-Warshall on this matrix of relations and then take the
1544  * union of all entries in the matrix as the final result.
1545  *
1546  * If we are actually computing the power instead of the transitive closure,
1547  * i.e., when "project" is not set, then the result should have the
1548  * path lengths encoded as the difference between an extra pair of
1549  * coordinates.  We therefore apply the nested transitive closures
1550  * to relations that include these lengths.  In particular, we replace
1551  * the input relation by the cross product with the unit length relation
1552  * { [i] -> [i + 1] }.
1553  */
1554 static __isl_give isl_map *floyd_warshall_with_groups(__isl_take isl_dim *dim,
1555         __isl_keep isl_map *map, int *exact, int project, int *group, int n)
1556 {
1557         int i, j, k;
1558         isl_map ***grid = NULL;
1559         isl_map *app;
1560
1561         if (!map)
1562                 goto error;
1563
1564         if (n == 1) {
1565                 free(group);
1566                 return incremental_closure(dim, map, exact, project);
1567         }
1568
1569         grid = isl_calloc_array(map->ctx, isl_map **, n);
1570         if (!grid)
1571                 goto error;
1572         for (i = 0; i < n; ++i) {
1573                 grid[i] = isl_calloc_array(map->ctx, isl_map *, n);
1574                 if (!grid[i])
1575                         goto error;
1576                 for (j = 0; j < n; ++j)
1577                         grid[i][j] = isl_map_empty(isl_map_get_dim(map));
1578         }
1579
1580         for (k = 0; k < map->n; ++k) {
1581                 i = group[2 * k];
1582                 j = group[2 * k + 1];
1583                 grid[i][j] = isl_map_union(grid[i][j],
1584                                 isl_map_from_basic_map(
1585                                         isl_basic_map_copy(map->p[k])));
1586         }
1587
1588         if (!project && add_length(map, grid, n) < 0)
1589                 goto error;
1590
1591         floyd_warshall_iterate(grid, n, exact);
1592
1593         app = isl_map_empty(isl_map_get_dim(map));
1594
1595         for (i = 0; i < n; ++i) {
1596                 for (j = 0; j < n; ++j)
1597                         app = isl_map_union(app, grid[i][j]);
1598                 free(grid[i]);
1599         }
1600         free(grid);
1601
1602         free(group);
1603         isl_dim_free(dim);
1604
1605         return app;
1606 error:
1607         if (grid)
1608                 for (i = 0; i < n; ++i) {
1609                         if (!grid[i])
1610                                 continue;
1611                         for (j = 0; j < n; ++j)
1612                                 isl_map_free(grid[i][j]);
1613                         free(grid[i]);
1614                 }
1615         free(grid);
1616         free(group);
1617         isl_dim_free(dim);
1618         return NULL;
1619 }
1620
1621 /* Partition the domains and ranges of the n basic relations in list
1622  * into disjoint cells.
1623  *
1624  * To find the partition, we simply consider all of the domains
1625  * and ranges in turn and combine those that overlap.
1626  * "set" contains the partition elements and "group" indicates
1627  * to which partition element a given domain or range belongs.
1628  * The domain of basic map i corresponds to element 2 * i in these arrays,
1629  * while the domain corresponds to element 2 * i + 1.
1630  * During the construction group[k] is either equal to k,
1631  * in which case set[k] contains the union of all the domains and
1632  * ranges in the corresponding group, or is equal to some l < k,
1633  * with l another domain or range in the same group.
1634  */
1635 static int *setup_groups(isl_ctx *ctx, __isl_keep isl_basic_map **list, int n,
1636         isl_set ***set, int *n_group)
1637 {
1638         int i;
1639         int *group = NULL;
1640         int g;
1641
1642         *set = isl_calloc_array(ctx, isl_set *, 2 * n);
1643         group = isl_alloc_array(ctx, int, 2 * n);
1644
1645         if (!*set || !group)
1646                 goto error;
1647
1648         for (i = 0; i < n; ++i) {
1649                 isl_set *dom;
1650                 dom = isl_set_from_basic_set(isl_basic_map_domain(
1651                                 isl_basic_map_copy(list[i])));
1652                 if (merge(*set, group, dom, 2 * i) < 0)
1653                         goto error;
1654                 dom = isl_set_from_basic_set(isl_basic_map_range(
1655                                 isl_basic_map_copy(list[i])));
1656                 if (merge(*set, group, dom, 2 * i + 1) < 0)
1657                         goto error;
1658         }
1659
1660         g = 0;
1661         for (i = 0; i < 2 * n; ++i)
1662                 if (group[i] == i) {
1663                         if (g != i) {
1664                                 (*set)[g] = (*set)[i];
1665                                 (*set)[i] = NULL;
1666                         }
1667                         group[i] = g++;
1668                 } else
1669                         group[i] = group[group[i]];
1670
1671         *n_group = g;
1672
1673         return group;
1674 error:
1675         if (*set) {
1676                 for (i = 0; i < 2 * n; ++i)
1677                         isl_set_free((*set)[i]);
1678                 free(*set);
1679                 *set = NULL;
1680         }
1681         free(group);
1682         return NULL;
1683 }
1684
1685 /* Check if the domains and ranges of the basic maps in "map" can
1686  * be partitioned, and if so, apply Floyd-Warshall on the elements
1687  * of the partition.  Note that we also apply this algorithm
1688  * if we want to compute the power, i.e., when "project" is not set.
1689  * However, the results are unlikely to be exact since the recursive
1690  * calls inside the Floyd-Warshall algorithm typically result in
1691  * non-linear path lengths quite quickly.
1692  */
1693 static __isl_give isl_map *floyd_warshall(__isl_take isl_dim *dim,
1694         __isl_keep isl_map *map, int *exact, int project)
1695 {
1696         int i;
1697         isl_set **set = NULL;
1698         int *group = NULL;
1699         int n;
1700
1701         if (!map)
1702                 goto error;
1703         if (map->n <= 1)
1704                 return incremental_closure(dim, map, exact, project);
1705
1706         group = setup_groups(map->ctx, map->p, map->n, &set, &n);
1707         if (!group)
1708                 goto error;
1709
1710         for (i = 0; i < 2 * map->n; ++i)
1711                 isl_set_free(set[i]);
1712
1713         free(set);
1714
1715         return floyd_warshall_with_groups(dim, map, exact, project, group, n);
1716 error:
1717         isl_dim_free(dim);
1718         return NULL;
1719 }
1720
1721 /* Structure for representing the nodes in the graph being traversed
1722  * using Tarjan's algorithm.
1723  * index represents the order in which nodes are visited.
1724  * min_index is the index of the root of a (sub)component.
1725  * on_stack indicates whether the node is currently on the stack.
1726  */
1727 struct basic_map_sort_node {
1728         int index;
1729         int min_index;
1730         int on_stack;
1731 };
1732 /* Structure for representing the graph being traversed
1733  * using Tarjan's algorithm.
1734  * len is the number of nodes
1735  * node is an array of nodes
1736  * stack contains the nodes on the path from the root to the current node
1737  * sp is the stack pointer
1738  * index is the index of the last node visited
1739  * order contains the elements of the components separated by -1
1740  * op represents the current position in order
1741  *
1742  * check_closed is set if we may have used the fact that
1743  * a pair of basic maps can be interchanged
1744  */
1745 struct basic_map_sort {
1746         int len;
1747         struct basic_map_sort_node *node;
1748         int *stack;
1749         int sp;
1750         int index;
1751         int *order;
1752         int op;
1753         int check_closed;
1754 };
1755
1756 static void basic_map_sort_free(struct basic_map_sort *s)
1757 {
1758         if (!s)
1759                 return;
1760         free(s->node);
1761         free(s->stack);
1762         free(s->order);
1763         free(s);
1764 }
1765
1766 static struct basic_map_sort *basic_map_sort_alloc(struct isl_ctx *ctx, int len)
1767 {
1768         struct basic_map_sort *s;
1769         int i;
1770
1771         s = isl_calloc_type(ctx, struct basic_map_sort);
1772         if (!s)
1773                 return NULL;
1774         s->len = len;
1775         s->node = isl_alloc_array(ctx, struct basic_map_sort_node, len);
1776         if (!s->node)
1777                 goto error;
1778         for (i = 0; i < len; ++i)
1779                 s->node[i].index = -1;
1780         s->stack = isl_alloc_array(ctx, int, len);
1781         if (!s->stack)
1782                 goto error;
1783         s->order = isl_alloc_array(ctx, int, 2 * len);
1784         if (!s->order)
1785                 goto error;
1786
1787         s->sp = 0;
1788         s->index = 0;
1789         s->op = 0;
1790
1791         s->check_closed = 0;
1792
1793         return s;
1794 error:
1795         basic_map_sort_free(s);
1796         return NULL;
1797 }
1798
1799 /* Check whether in the computation of the transitive closure
1800  * "bmap1" (R_1) should follow (or be part of the same component as)
1801  * "bmap2" (R_2).
1802  *
1803  * That is check whether
1804  *
1805  *      R_1 \circ R_2
1806  *
1807  * is a subset of
1808  *
1809  *      R_2 \circ R_1
1810  *
1811  * If so, then there is no reason for R_1 to immediately follow R_2
1812  * in any path.
1813  *
1814  * *check_closed is set if the subset relation holds while
1815  * R_1 \circ R_2 is not empty.
1816  */
1817 static int basic_map_follows(__isl_keep isl_basic_map *bmap1,
1818         __isl_keep isl_basic_map *bmap2, int *check_closed)
1819 {
1820         struct isl_map *map12 = NULL;
1821         struct isl_map *map21 = NULL;
1822         int subset;
1823
1824         if (!isl_dim_tuple_match(bmap1->dim, isl_dim_in, bmap2->dim, isl_dim_out))
1825                 return 0;
1826
1827         map21 = isl_map_from_basic_map(
1828                         isl_basic_map_apply_range(
1829                                 isl_basic_map_copy(bmap2),
1830                                 isl_basic_map_copy(bmap1)));
1831         subset = isl_map_is_empty(map21);
1832         if (subset < 0)
1833                 goto error;
1834         if (subset) {
1835                 isl_map_free(map21);
1836                 return 0;
1837         }
1838
1839         if (!isl_dim_tuple_match(bmap1->dim, isl_dim_in, bmap1->dim, isl_dim_out) ||
1840             !isl_dim_tuple_match(bmap2->dim, isl_dim_in, bmap2->dim, isl_dim_out)) {
1841                 isl_map_free(map21);
1842                 return 1;
1843         }
1844
1845         map12 = isl_map_from_basic_map(
1846                         isl_basic_map_apply_range(
1847                                 isl_basic_map_copy(bmap1),
1848                                 isl_basic_map_copy(bmap2)));
1849
1850         subset = isl_map_is_subset(map21, map12);
1851
1852         isl_map_free(map12);
1853         isl_map_free(map21);
1854
1855         if (subset)
1856                 *check_closed = 1;
1857
1858         return subset < 0 ? -1 : !subset;
1859 error:
1860         isl_map_free(map21);
1861         return -1;
1862 }
1863
1864 /* Perform Tarjan's algorithm for computing the strongly connected components
1865  * in the graph with the disjuncts of "map" as vertices and with an
1866  * edge between any pair of disjuncts such that the first has
1867  * to be applied after the second.
1868  */
1869 static int power_components_tarjan(struct basic_map_sort *s,
1870         __isl_keep isl_basic_map **list, int i)
1871 {
1872         int j;
1873
1874         s->node[i].index = s->index;
1875         s->node[i].min_index = s->index;
1876         s->node[i].on_stack = 1;
1877         s->index++;
1878         s->stack[s->sp++] = i;
1879
1880         for (j = s->len - 1; j >= 0; --j) {
1881                 int f;
1882
1883                 if (j == i)
1884                         continue;
1885                 if (s->node[j].index >= 0 &&
1886                         (!s->node[j].on_stack ||
1887                          s->node[j].index > s->node[i].min_index))
1888                         continue;
1889
1890                 f = basic_map_follows(list[i], list[j], &s->check_closed);
1891                 if (f < 0)
1892                         return -1;
1893                 if (!f)
1894                         continue;
1895
1896                 if (s->node[j].index < 0) {
1897                         power_components_tarjan(s, list, j);
1898                         if (s->node[j].min_index < s->node[i].min_index)
1899                                 s->node[i].min_index = s->node[j].min_index;
1900                 } else if (s->node[j].index < s->node[i].min_index)
1901                         s->node[i].min_index = s->node[j].index;
1902         }
1903
1904         if (s->node[i].index != s->node[i].min_index)
1905                 return 0;
1906
1907         do {
1908                 j = s->stack[--s->sp];
1909                 s->node[j].on_stack = 0;
1910                 s->order[s->op++] = j;
1911         } while (j != i);
1912         s->order[s->op++] = -1;
1913
1914         return 0;
1915 }
1916
1917 /* Decompose the "len" basic relations in "list" into strongly connected
1918  * components.
1919  */
1920 static struct basic_map_sort *basic_map_sort_init(isl_ctx *ctx, int len,
1921         __isl_keep isl_basic_map **list)
1922 {
1923         int i;
1924         struct basic_map_sort *s = NULL;
1925
1926         s = basic_map_sort_alloc(ctx, len);
1927         if (!s)
1928                 return NULL;
1929         for (i = len - 1; i >= 0; --i) {
1930                 if (s->node[i].index >= 0)
1931                         continue;
1932                 if (power_components_tarjan(s, list, i) < 0)
1933                         goto error;
1934         }
1935
1936         return s;
1937 error:
1938         basic_map_sort_free(s);
1939         return NULL;
1940 }
1941
1942 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D
1943  * and a dimension specification (Z^{n+1} -> Z^{n+1}),
1944  * construct a map that is an overapproximation of the map
1945  * that takes an element from the dom R \times Z to an
1946  * element from ran R \times Z, such that the first n coordinates of the
1947  * difference between them is a sum of differences between images
1948  * and pre-images in one of the R_i and such that the last coordinate
1949  * is equal to the number of steps taken.
1950  * If "project" is set, then these final coordinates are not included,
1951  * i.e., a relation of type Z^n -> Z^n is returned.
1952  * That is, let
1953  *
1954  *      \Delta_i = { y - x | (x, y) in R_i }
1955  *
1956  * then the constructed map is an overapproximation of
1957  *
1958  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1959  *                              d = (\sum_i k_i \delta_i, \sum_i k_i) and
1960  *                              x in dom R and x + d in ran R }
1961  *
1962  * or
1963  *
1964  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
1965  *                              d = (\sum_i k_i \delta_i) and
1966  *                              x in dom R and x + d in ran R }
1967  *
1968  * if "project" is set.
1969  *
1970  * We first split the map into strongly connected components, perform
1971  * the above on each component and then join the results in the correct
1972  * order, at each join also taking in the union of both arguments
1973  * to allow for paths that do not go through one of the two arguments.
1974  */
1975 static __isl_give isl_map *construct_power_components(__isl_take isl_dim *dim,
1976         __isl_keep isl_map *map, int *exact, int project)
1977 {
1978         int i, n, c;
1979         struct isl_map *path = NULL;
1980         struct basic_map_sort *s = NULL;
1981         int *orig_exact;
1982         int local_exact;
1983
1984         if (!map)
1985                 goto error;
1986         if (map->n <= 1)
1987                 return floyd_warshall(dim, map, exact, project);
1988
1989         s = basic_map_sort_init(map->ctx, map->n, map->p);
1990         if (!s)
1991                 goto error;
1992
1993         orig_exact = exact;
1994         if (s->check_closed && !exact)
1995                 exact = &local_exact;
1996
1997         c = 0;
1998         i = 0;
1999         n = map->n;
2000         if (project)
2001                 path = isl_map_empty(isl_map_get_dim(map));
2002         else
2003                 path = isl_map_empty(isl_dim_copy(dim));
2004         path = anonymize(path);
2005         while (n) {
2006                 struct isl_map *comp;
2007                 isl_map *path_comp, *path_comb;
2008                 comp = isl_map_alloc_dim(isl_map_get_dim(map), n, 0);
2009                 while (s->order[i] != -1) {
2010                         comp = isl_map_add_basic_map(comp,
2011                                     isl_basic_map_copy(map->p[s->order[i]]));
2012                         --n;
2013                         ++i;
2014                 }
2015                 path_comp = floyd_warshall(isl_dim_copy(dim),
2016                                                 comp, exact, project);
2017                 path_comp = anonymize(path_comp);
2018                 path_comb = isl_map_apply_range(isl_map_copy(path),
2019                                                 isl_map_copy(path_comp));
2020                 path = isl_map_union(path, path_comp);
2021                 path = isl_map_union(path, path_comb);
2022                 isl_map_free(comp);
2023                 ++i;
2024                 ++c;
2025         }
2026
2027         if (c > 1 && s->check_closed && !*exact) {
2028                 int closed;
2029
2030                 closed = isl_map_is_transitively_closed(path);
2031                 if (closed < 0)
2032                         goto error;
2033                 if (!closed) {
2034                         basic_map_sort_free(s);
2035                         isl_map_free(path);
2036                         return floyd_warshall(dim, map, orig_exact, project);
2037                 }
2038         }
2039
2040         basic_map_sort_free(s);
2041         isl_dim_free(dim);
2042
2043         return path;
2044 error:
2045         basic_map_sort_free(s);
2046         isl_dim_free(dim);
2047         isl_map_free(path);
2048         return NULL;
2049 }
2050
2051 /* Given a union of basic maps R = \cup_i R_i \subseteq D \times D,
2052  * construct a map that is an overapproximation of the map
2053  * that takes an element from the space D to another
2054  * element from the same space, such that the difference between
2055  * them is a strictly positive sum of differences between images
2056  * and pre-images in one of the R_i.
2057  * The number of differences in the sum is equated to parameter "param".
2058  * That is, let
2059  *
2060  *      \Delta_i = { y - x | (x, y) in R_i }
2061  *
2062  * then the constructed map is an overapproximation of
2063  *
2064  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
2065  *                              d = \sum_i k_i \delta_i and k = \sum_i k_i > 0 }
2066  * or
2067  *
2068  *      { (x) -> (x + d) | \exists k_i >= 0, \delta_i \in \Delta_i :
2069  *                              d = \sum_i k_i \delta_i and \sum_i k_i > 0 }
2070  *
2071  * if "project" is set.
2072  *
2073  * If "project" is not set, then
2074  * we construct an extended mapping with an extra coordinate
2075  * that indicates the number of steps taken.  In particular,
2076  * the difference in the last coordinate is equal to the number
2077  * of steps taken to move from a domain element to the corresponding
2078  * image element(s).
2079  */
2080 static __isl_give isl_map *construct_power(__isl_keep isl_map *map,
2081         int *exact, int project)
2082 {
2083         struct isl_map *app = NULL;
2084         struct isl_dim *dim = NULL;
2085         unsigned d;
2086
2087         if (!map)
2088                 return NULL;
2089
2090         dim = isl_map_get_dim(map);
2091
2092         d = isl_dim_size(dim, isl_dim_in);
2093         dim = isl_dim_add(dim, isl_dim_in, 1);
2094         dim = isl_dim_add(dim, isl_dim_out, 1);
2095
2096         app = construct_power_components(isl_dim_copy(dim), map,
2097                                         exact, project);
2098
2099         isl_dim_free(dim);
2100
2101         return app;
2102 }
2103
2104 /* Compute the positive powers of "map", or an overapproximation.
2105  * If the result is exact, then *exact is set to 1.
2106  *
2107  * If project is set, then we are actually interested in the transitive
2108  * closure, so we can use a more relaxed exactness check.
2109  * The lengths of the paths are also projected out instead of being
2110  * encoded as the difference between an extra pair of final coordinates.
2111  */
2112 static __isl_give isl_map *map_power(__isl_take isl_map *map,
2113         int *exact, int project)
2114 {
2115         struct isl_map *app = NULL;
2116
2117         if (exact)
2118                 *exact = 1;
2119
2120         if (!map)
2121                 return NULL;
2122
2123         isl_assert(map->ctx,
2124                 isl_map_dim(map, isl_dim_in) == isl_map_dim(map, isl_dim_out),
2125                 goto error);
2126
2127         app = construct_power(map, exact, project);
2128
2129         isl_map_free(map);
2130         return app;
2131 error:
2132         isl_map_free(map);
2133         isl_map_free(app);
2134         return NULL;
2135 }
2136
2137 /* Compute the positive powers of "map", or an overapproximation.
2138  * The power is given by parameter "param".  If the result is exact,
2139  * then *exact is set to 1.
2140  * map_power constructs an extended relation with the path lengths
2141  * encoded as the difference between the final coordinates.
2142  * In the final step, this difference is equated to the parameter "param"
2143  * and made positive.  The extra coordinates are subsequently projected out.
2144  */
2145 __isl_give isl_map *isl_map_power(__isl_take isl_map *map, unsigned param,
2146         int *exact)
2147 {
2148         isl_dim *target_dim;
2149         isl_dim *dim;
2150         isl_map *diff;
2151         unsigned d;
2152
2153         if (!map)
2154                 return NULL;
2155
2156         isl_assert(map->ctx, param < isl_map_dim(map, isl_dim_param),
2157                 goto error);
2158
2159         d = isl_map_dim(map, isl_dim_in);
2160
2161         map = isl_map_compute_divs(map);
2162         map = isl_map_coalesce(map);
2163
2164         if (isl_map_fast_is_empty(map))
2165                 return map;
2166
2167         target_dim = isl_map_get_dim(map);
2168         map = map_power(map, exact, 0);
2169
2170         dim = isl_map_get_dim(map);
2171         diff = equate_parameter_to_length(dim, param);
2172         map = isl_map_intersect(map, diff);
2173         map = isl_map_project_out(map, isl_dim_in, d, 1);
2174         map = isl_map_project_out(map, isl_dim_out, d, 1);
2175
2176         map = isl_map_reset_dim(map, target_dim);
2177
2178         return map;
2179 error:
2180         isl_map_free(map);
2181         return NULL;
2182 }
2183
2184 /* Compute a relation that maps each element in the range of the input
2185  * relation to the lengths of all paths composed of edges in the input
2186  * relation that end up in the given range element.
2187  * The result may be an overapproximation, in which case *exact is set to 0.
2188  * The resulting relation is very similar to the power relation.
2189  * The difference are that the domain has been projected out, the
2190  * range has become the domain and the exponent is the range instead
2191  * of a parameter.
2192  */
2193 __isl_give isl_map *isl_map_reaching_path_lengths(__isl_take isl_map *map,
2194         int *exact)
2195 {
2196         isl_dim *dim;
2197         isl_map *diff;
2198         unsigned d;
2199         unsigned param;
2200
2201         if (!map)
2202                 return NULL;
2203
2204         d = isl_map_dim(map, isl_dim_in);
2205         param = isl_map_dim(map, isl_dim_param);
2206
2207         map = isl_map_compute_divs(map);
2208         map = isl_map_coalesce(map);
2209
2210         if (isl_map_fast_is_empty(map)) {
2211                 if (exact)
2212                         *exact = 1;
2213                 map = isl_map_project_out(map, isl_dim_out, 0, d);
2214                 map = isl_map_add_dims(map, isl_dim_out, 1);
2215                 return map;
2216         }
2217
2218         map = map_power(map, exact, 0);
2219
2220         map = isl_map_add_dims(map, isl_dim_param, 1);
2221         dim = isl_map_get_dim(map);
2222         diff = equate_parameter_to_length(dim, param);
2223         map = isl_map_intersect(map, diff);
2224         map = isl_map_project_out(map, isl_dim_in, 0, d + 1);
2225         map = isl_map_project_out(map, isl_dim_out, d, 1);
2226         map = isl_map_reverse(map);
2227         map = isl_map_move_dims(map, isl_dim_out, 0, isl_dim_param, param, 1);
2228
2229         return map;
2230 }
2231
2232 /* Check whether equality i of bset is a pure stride constraint
2233  * on a single dimensions, i.e., of the form
2234  *
2235  *      v = k e
2236  *
2237  * with k a constant and e an existentially quantified variable.
2238  */
2239 static int is_eq_stride(__isl_keep isl_basic_set *bset, int i)
2240 {
2241         int k;
2242         unsigned nparam;
2243         unsigned d;
2244         unsigned n_div;
2245         int pos1;
2246         int pos2;
2247
2248         if (!bset)
2249                 return -1;
2250
2251         if (!isl_int_is_zero(bset->eq[i][0]))
2252                 return 0;
2253
2254         nparam = isl_basic_set_dim(bset, isl_dim_param);
2255         d = isl_basic_set_dim(bset, isl_dim_set);
2256         n_div = isl_basic_set_dim(bset, isl_dim_div);
2257
2258         if (isl_seq_first_non_zero(bset->eq[i] + 1, nparam) != -1)
2259                 return 0;
2260         pos1 = isl_seq_first_non_zero(bset->eq[i] + 1 + nparam, d);
2261         if (pos1 == -1)
2262                 return 0;
2263         if (isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + pos1 + 1, 
2264                                         d - pos1 - 1) != -1)
2265                 return 0;
2266
2267         pos2 = isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + d, n_div);
2268         if (pos2 == -1)
2269                 return 0;
2270         if (isl_seq_first_non_zero(bset->eq[i] + 1 + nparam + d  + pos2 + 1,
2271                                    n_div - pos2 - 1) != -1)
2272                 return 0;
2273         if (!isl_int_is_one(bset->eq[i][1 + nparam + pos1]) &&
2274             !isl_int_is_negone(bset->eq[i][1 + nparam + pos1]))
2275                 return 0;
2276
2277         return 1;
2278 }
2279
2280 /* Given a map, compute the smallest superset of this map that is of the form
2281  *
2282  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
2283  *
2284  * (where p ranges over the (non-parametric) dimensions),
2285  * compute the transitive closure of this map, i.e.,
2286  *
2287  *      { i -> j : exists k > 0:
2288  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2289  *
2290  * and intersect domain and range of this transitive closure with
2291  * the given domain and range.
2292  *
2293  * If with_id is set, then try to include as much of the identity mapping
2294  * as possible, by computing
2295  *
2296  *      { i -> j : exists k >= 0:
2297  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2298  *
2299  * instead (i.e., allow k = 0).
2300  *
2301  * In practice, we compute the difference set
2302  *
2303  *      delta  = { j - i | i -> j in map },
2304  *
2305  * look for stride constraint on the individual dimensions and compute
2306  * (constant) lower and upper bounds for each individual dimension,
2307  * adding a constraint for each bound not equal to infinity.
2308  */
2309 static __isl_give isl_map *box_closure_on_domain(__isl_take isl_map *map,
2310         __isl_take isl_set *dom, __isl_take isl_set *ran, int with_id)
2311 {
2312         int i;
2313         int k;
2314         unsigned d;
2315         unsigned nparam;
2316         unsigned total;
2317         isl_dim *dim;
2318         isl_set *delta;
2319         isl_map *app = NULL;
2320         isl_basic_set *aff = NULL;
2321         isl_basic_map *bmap = NULL;
2322         isl_vec *obj = NULL;
2323         isl_int opt;
2324
2325         isl_int_init(opt);
2326
2327         delta = isl_map_deltas(isl_map_copy(map));
2328
2329         aff = isl_set_affine_hull(isl_set_copy(delta));
2330         if (!aff)
2331                 goto error;
2332         dim = isl_map_get_dim(map);
2333         d = isl_dim_size(dim, isl_dim_in);
2334         nparam = isl_dim_size(dim, isl_dim_param);
2335         total = isl_dim_total(dim);
2336         bmap = isl_basic_map_alloc_dim(dim,
2337                                         aff->n_div + 1, aff->n_div, 2 * d + 1);
2338         for (i = 0; i < aff->n_div + 1; ++i) {
2339                 k = isl_basic_map_alloc_div(bmap);
2340                 if (k < 0)
2341                         goto error;
2342                 isl_int_set_si(bmap->div[k][0], 0);
2343         }
2344         for (i = 0; i < aff->n_eq; ++i) {
2345                 if (!is_eq_stride(aff, i))
2346                         continue;
2347                 k = isl_basic_map_alloc_equality(bmap);
2348                 if (k < 0)
2349                         goto error;
2350                 isl_seq_clr(bmap->eq[k], 1 + nparam);
2351                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + d,
2352                                 aff->eq[i] + 1 + nparam, d);
2353                 isl_seq_neg(bmap->eq[k] + 1 + nparam,
2354                                 aff->eq[i] + 1 + nparam, d);
2355                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + 2 * d,
2356                                 aff->eq[i] + 1 + nparam + d, aff->n_div);
2357                 isl_int_set_si(bmap->eq[k][1 + total + aff->n_div], 0);
2358         }
2359         obj = isl_vec_alloc(map->ctx, 1 + nparam + d);
2360         if (!obj)
2361                 goto error;
2362         isl_seq_clr(obj->el, 1 + nparam + d);
2363         for (i = 0; i < d; ++ i) {
2364                 enum isl_lp_result res;
2365
2366                 isl_int_set_si(obj->el[1 + nparam + i], 1);
2367
2368                 res = isl_set_solve_lp(delta, 0, obj->el, map->ctx->one, &opt,
2369                                         NULL, NULL);
2370                 if (res == isl_lp_error)
2371                         goto error;
2372                 if (res == isl_lp_ok) {
2373                         k = isl_basic_map_alloc_inequality(bmap);
2374                         if (k < 0)
2375                                 goto error;
2376                         isl_seq_clr(bmap->ineq[k],
2377                                         1 + nparam + 2 * d + bmap->n_div);
2378                         isl_int_set_si(bmap->ineq[k][1 + nparam + i], -1);
2379                         isl_int_set_si(bmap->ineq[k][1 + nparam + d + i], 1);
2380                         isl_int_neg(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], opt);
2381                 }
2382
2383                 res = isl_set_solve_lp(delta, 1, obj->el, map->ctx->one, &opt,
2384                                         NULL, NULL);
2385                 if (res == isl_lp_error)
2386                         goto error;
2387                 if (res == isl_lp_ok) {
2388                         k = isl_basic_map_alloc_inequality(bmap);
2389                         if (k < 0)
2390                                 goto error;
2391                         isl_seq_clr(bmap->ineq[k],
2392                                         1 + nparam + 2 * d + bmap->n_div);
2393                         isl_int_set_si(bmap->ineq[k][1 + nparam + i], 1);
2394                         isl_int_set_si(bmap->ineq[k][1 + nparam + d + i], -1);
2395                         isl_int_set(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], opt);
2396                 }
2397
2398                 isl_int_set_si(obj->el[1 + nparam + i], 0);
2399         }
2400         k = isl_basic_map_alloc_inequality(bmap);
2401         if (k < 0)
2402                 goto error;
2403         isl_seq_clr(bmap->ineq[k],
2404                         1 + nparam + 2 * d + bmap->n_div);
2405         if (!with_id)
2406                 isl_int_set_si(bmap->ineq[k][0], -1);
2407         isl_int_set_si(bmap->ineq[k][1 + nparam + 2 * d + aff->n_div], 1);
2408
2409         app = isl_map_from_domain_and_range(dom, ran);
2410
2411         isl_vec_free(obj);
2412         isl_basic_set_free(aff);
2413         isl_map_free(map);
2414         bmap = isl_basic_map_finalize(bmap);
2415         isl_set_free(delta);
2416         isl_int_clear(opt);
2417
2418         map = isl_map_from_basic_map(bmap);
2419         map = isl_map_intersect(map, app);
2420
2421         return map;
2422 error:
2423         isl_vec_free(obj);
2424         isl_basic_map_free(bmap);
2425         isl_basic_set_free(aff);
2426         isl_set_free(dom);
2427         isl_set_free(ran);
2428         isl_map_free(map);
2429         isl_set_free(delta);
2430         isl_int_clear(opt);
2431         return NULL;
2432 }
2433
2434 /* Given a map, compute the smallest superset of this map that is of the form
2435  *
2436  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
2437  *
2438  * (where p ranges over the (non-parametric) dimensions),
2439  * compute the transitive closure of this map, i.e.,
2440  *
2441  *      { i -> j : exists k > 0:
2442  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2443  *
2444  * and intersect domain and range of this transitive closure with
2445  * domain and range of the original map.
2446  */
2447 static __isl_give isl_map *box_closure(__isl_take isl_map *map)
2448 {
2449         isl_set *domain;
2450         isl_set *range;
2451
2452         domain = isl_map_domain(isl_map_copy(map));
2453         domain = isl_set_coalesce(domain);
2454         range = isl_map_range(isl_map_copy(map));
2455         range = isl_set_coalesce(range);
2456
2457         return box_closure_on_domain(map, domain, range, 0);
2458 }
2459
2460 /* Given a map, compute the smallest superset of this map that is of the form
2461  *
2462  *      { i -> j : L <= j - i <= U and exists a_p: j_p - i_p = M_p a_p }
2463  *
2464  * (where p ranges over the (non-parametric) dimensions),
2465  * compute the transitive and partially reflexive closure of this map, i.e.,
2466  *
2467  *      { i -> j : exists k >= 0:
2468  *              k L <= j - i <= k U and exists a: j_p - i_p = M_p a_p }
2469  *
2470  * and intersect domain and range of this transitive closure with
2471  * the given domain.
2472  */
2473 static __isl_give isl_map *box_closure_with_identity(__isl_take isl_map *map,
2474         __isl_take isl_set *dom)
2475 {
2476         return box_closure_on_domain(map, dom, isl_set_copy(dom), 1);
2477 }
2478
2479 /* Check whether app is the transitive closure of map.
2480  * In particular, check that app is acyclic and, if so,
2481  * check that
2482  *
2483  *      app \subset (map \cup (map \circ app))
2484  */
2485 static int check_exactness_omega(__isl_keep isl_map *map,
2486         __isl_keep isl_map *app)
2487 {
2488         isl_set *delta;
2489         int i;
2490         int is_empty, is_exact;
2491         unsigned d;
2492         isl_map *test;
2493
2494         delta = isl_map_deltas(isl_map_copy(app));
2495         d = isl_set_dim(delta, isl_dim_set);
2496         for (i = 0; i < d; ++i)
2497                 delta = isl_set_fix_si(delta, isl_dim_set, i, 0);
2498         is_empty = isl_set_is_empty(delta);
2499         isl_set_free(delta);
2500         if (is_empty < 0)
2501                 return -1;
2502         if (!is_empty)
2503                 return 0;
2504
2505         test = isl_map_apply_range(isl_map_copy(app), isl_map_copy(map));
2506         test = isl_map_union(test, isl_map_copy(map));
2507         is_exact = isl_map_is_subset(app, test);
2508         isl_map_free(test);
2509
2510         return is_exact;
2511 }
2512
2513 /* Check if basic map M_i can be combined with all the other
2514  * basic maps such that
2515  *
2516  *      (\cup_j M_j)^+
2517  *
2518  * can be computed as
2519  *
2520  *      M_i \cup (\cup_{j \ne i} M_i^* \circ M_j \circ M_i^*)^+
2521  *
2522  * In particular, check if we can compute a compact representation
2523  * of
2524  *
2525  *              M_i^* \circ M_j \circ M_i^*
2526  *
2527  * for each j != i.
2528  * Let M_i^? be an extension of M_i^+ that allows paths
2529  * of length zero, i.e., the result of box_closure(., 1).
2530  * The criterion, as proposed by Kelly et al., is that
2531  * id = M_i^? - M_i^+ can be represented as a basic map
2532  * and that
2533  *
2534  *      id \circ M_j \circ id = M_j
2535  *
2536  * for each j != i.
2537  *
2538  * If this function returns 1, then tc and qc are set to
2539  * M_i^+ and M_i^?, respectively.
2540  */
2541 static int can_be_split_off(__isl_keep isl_map *map, int i,
2542         __isl_give isl_map **tc, __isl_give isl_map **qc)
2543 {
2544         isl_map *map_i, *id = NULL;
2545         int j = -1;
2546         isl_set *C;
2547
2548         *tc = NULL;
2549         *qc = NULL;
2550
2551         C = isl_set_union(isl_map_domain(isl_map_copy(map)),
2552                           isl_map_range(isl_map_copy(map)));
2553         C = isl_set_from_basic_set(isl_set_simple_hull(C));
2554         if (!C)
2555                 goto error;
2556
2557         map_i = isl_map_from_basic_map(isl_basic_map_copy(map->p[i]));
2558         *tc = box_closure(isl_map_copy(map_i));
2559         *qc = box_closure_with_identity(map_i, C);
2560         id = isl_map_subtract(isl_map_copy(*qc), isl_map_copy(*tc));
2561
2562         if (!id || !*qc)
2563                 goto error;
2564         if (id->n != 1 || (*qc)->n != 1)
2565                 goto done;
2566
2567         for (j = 0; j < map->n; ++j) {
2568                 isl_map *map_j, *test;
2569                 int is_ok;
2570
2571                 if (i == j)
2572                         continue;
2573                 map_j = isl_map_from_basic_map(
2574                                         isl_basic_map_copy(map->p[j]));
2575                 test = isl_map_apply_range(isl_map_copy(id),
2576                                                 isl_map_copy(map_j));
2577                 test = isl_map_apply_range(test, isl_map_copy(id));
2578                 is_ok = isl_map_is_equal(test, map_j);
2579                 isl_map_free(map_j);
2580                 isl_map_free(test);
2581                 if (is_ok < 0)
2582                         goto error;
2583                 if (!is_ok)
2584                         break;
2585         }
2586
2587 done:
2588         isl_map_free(id);
2589         if (j == map->n)
2590                 return 1;
2591
2592         isl_map_free(*qc);
2593         isl_map_free(*tc);
2594         *qc = NULL;
2595         *tc = NULL;
2596
2597         return 0;
2598 error:
2599         isl_map_free(id);
2600         isl_map_free(*qc);
2601         isl_map_free(*tc);
2602         *qc = NULL;
2603         *tc = NULL;
2604         return -1;
2605 }
2606
2607 static __isl_give isl_map *box_closure_with_check(__isl_take isl_map *map,
2608         int *exact)
2609 {
2610         isl_map *app;
2611
2612         app = box_closure(isl_map_copy(map));
2613         if (exact)
2614                 *exact = check_exactness_omega(map, app);
2615
2616         isl_map_free(map);
2617         return app;
2618 }
2619
2620 /* Compute an overapproximation of the transitive closure of "map"
2621  * using a variation of the algorithm from
2622  * "Transitive Closure of Infinite Graphs and its Applications"
2623  * by Kelly et al.
2624  *
2625  * We first check whether we can can split of any basic map M_i and
2626  * compute
2627  *
2628  *      (\cup_j M_j)^+
2629  *
2630  * as
2631  *
2632  *      M_i \cup (\cup_{j \ne i} M_i^* \circ M_j \circ M_i^*)^+
2633  *
2634  * using a recursive call on the remaining map.
2635  *
2636  * If not, we simply call box_closure on the whole map.
2637  */
2638 static __isl_give isl_map *transitive_closure_omega(__isl_take isl_map *map,
2639         int *exact)
2640 {
2641         int i, j;
2642         int exact_i;
2643         isl_map *app;
2644
2645         if (!map)
2646                 return NULL;
2647         if (map->n == 1)
2648                 return box_closure_with_check(map, exact);
2649
2650         for (i = 0; i < map->n; ++i) {
2651                 int ok;
2652                 isl_map *qc, *tc;
2653                 ok = can_be_split_off(map, i, &tc, &qc);
2654                 if (ok < 0)
2655                         goto error;
2656                 if (!ok)
2657                         continue;
2658
2659                 app = isl_map_alloc_dim(isl_map_get_dim(map), map->n - 1, 0);
2660
2661                 for (j = 0; j < map->n; ++j) {
2662                         if (j == i)
2663                                 continue;
2664                         app = isl_map_add_basic_map(app,
2665                                                 isl_basic_map_copy(map->p[j]));
2666                 }
2667
2668                 app = isl_map_apply_range(isl_map_copy(qc), app);
2669                 app = isl_map_apply_range(app, qc);
2670
2671                 app = isl_map_union(tc, transitive_closure_omega(app, NULL));
2672                 exact_i = check_exactness_omega(map, app);
2673                 if (exact_i == 1) {
2674                         if (exact)
2675                                 *exact = exact_i;
2676                         isl_map_free(map);
2677                         return app;
2678                 }
2679                 isl_map_free(app);
2680                 if (exact_i < 0)
2681                         goto error;
2682         }
2683
2684         return box_closure_with_check(map, exact);
2685 error:
2686         isl_map_free(map);
2687         return NULL;
2688 }
2689
2690 /* Compute the transitive closure  of "map", or an overapproximation.
2691  * If the result is exact, then *exact is set to 1.
2692  * Simply use map_power to compute the powers of map, but tell
2693  * it to project out the lengths of the paths instead of equating
2694  * the length to a parameter.
2695  */
2696 __isl_give isl_map *isl_map_transitive_closure(__isl_take isl_map *map,
2697         int *exact)
2698 {
2699         isl_dim *target_dim;
2700         int closed;
2701
2702         if (!map)
2703                 goto error;
2704
2705         if (map->ctx->opt->closure == ISL_CLOSURE_BOX)
2706                 return transitive_closure_omega(map, exact);
2707
2708         map = isl_map_compute_divs(map);
2709         map = isl_map_coalesce(map);
2710         closed = isl_map_is_transitively_closed(map);
2711         if (closed < 0)
2712                 goto error;
2713         if (closed) {
2714                 if (exact)
2715                         *exact = 1;
2716                 return map;
2717         }
2718
2719         target_dim = isl_map_get_dim(map);
2720         map = map_power(map, exact, 1);
2721         map = isl_map_reset_dim(map, target_dim);
2722
2723         return map;
2724 error:
2725         isl_map_free(map);
2726         return NULL;
2727 }
2728
2729 static int inc_count(__isl_take isl_map *map, void *user)
2730 {
2731         int *n = user;
2732
2733         *n += map->n;
2734
2735         isl_map_free(map);
2736
2737         return 0;
2738 }
2739
2740 static int collect_basic_map(__isl_take isl_map *map, void *user)
2741 {
2742         int i;
2743         isl_basic_map ***next = user;
2744
2745         for (i = 0; i < map->n; ++i) {
2746                 **next = isl_basic_map_copy(map->p[i]);
2747                 if (!**next)
2748                         goto error;
2749                 (*next)++;
2750         }
2751
2752         isl_map_free(map);
2753         return 0;
2754 error:
2755         isl_map_free(map);
2756         return -1;
2757 }
2758
2759 /* Perform Floyd-Warshall on the given list of basic relations.
2760  * The basic relations may live in different dimensions,
2761  * but basic relations that get assigned to the diagonal of the
2762  * grid have domains and ranges of the same dimension and so
2763  * the standard algorithm can be used because the nested transitive
2764  * closures are only applied to diagonal elements and because all
2765  * compositions are peformed on relations with compatible domains and ranges.
2766  */
2767 static __isl_give isl_union_map *union_floyd_warshall_on_list(isl_ctx *ctx,
2768         __isl_keep isl_basic_map **list, int n, int *exact)
2769 {
2770         int i, j, k;
2771         int n_group;
2772         int *group = NULL;
2773         isl_set **set = NULL;
2774         isl_map ***grid = NULL;
2775         isl_union_map *app;
2776
2777         group = setup_groups(ctx, list, n, &set, &n_group);
2778         if (!group)
2779                 goto error;
2780
2781         grid = isl_calloc_array(ctx, isl_map **, n_group);
2782         if (!grid)
2783                 goto error;
2784         for (i = 0; i < n_group; ++i) {
2785                 grid[i] = isl_calloc_array(map->ctx, isl_map *, n_group);
2786                 if (!grid[i])
2787                         goto error;
2788                 for (j = 0; j < n_group; ++j) {
2789                         isl_dim *dim1, *dim2, *dim;
2790                         dim1 = isl_dim_reverse(isl_set_get_dim(set[i]));
2791                         dim2 = isl_set_get_dim(set[j]);
2792                         dim = isl_dim_join(dim1, dim2);
2793                         grid[i][j] = isl_map_empty(dim);
2794                 }
2795         }
2796
2797         for (k = 0; k < n; ++k) {
2798                 i = group[2 * k];
2799                 j = group[2 * k + 1];
2800                 grid[i][j] = isl_map_union(grid[i][j],
2801                                 isl_map_from_basic_map(
2802                                         isl_basic_map_copy(list[k])));
2803         }
2804         
2805         floyd_warshall_iterate(grid, n_group, exact);
2806
2807         app = isl_union_map_empty(isl_map_get_dim(grid[0][0]));
2808
2809         for (i = 0; i < n_group; ++i) {
2810                 for (j = 0; j < n_group; ++j)
2811                         app = isl_union_map_add_map(app, grid[i][j]);
2812                 free(grid[i]);
2813         }
2814         free(grid);
2815
2816         for (i = 0; i < 2 * n; ++i)
2817                 isl_set_free(set[i]);
2818         free(set);
2819
2820         free(group);
2821         return app;
2822 error:
2823         if (grid)
2824                 for (i = 0; i < n_group; ++i) {
2825                         if (!grid[i])
2826                                 continue;
2827                         for (j = 0; j < n_group; ++j)
2828                                 isl_map_free(grid[i][j]);
2829                         free(grid[i]);
2830                 }
2831         free(grid);
2832         if (set) {
2833                 for (i = 0; i < 2 * n; ++i)
2834                         isl_set_free(set[i]);
2835                 free(set);
2836         }
2837         free(group);
2838         return NULL;
2839 }
2840
2841 /* Perform Floyd-Warshall on the given union relation.
2842  * The implementation is very similar to that for non-unions.
2843  * The main difference is that it is applied unconditionally.
2844  * We first extract a list of basic maps from the union map
2845  * and then perform the algorithm on this list.
2846  */
2847 static __isl_give isl_union_map *union_floyd_warshall(
2848         __isl_take isl_union_map *umap, int *exact)
2849 {
2850         int i, n;
2851         isl_ctx *ctx;
2852         isl_basic_map **list;
2853         isl_basic_map **next;
2854         isl_union_map *res;
2855
2856         n = 0;
2857         if (isl_union_map_foreach_map(umap, inc_count, &n) < 0)
2858                 goto error;
2859
2860         ctx = isl_union_map_get_ctx(umap);
2861         list = isl_calloc_array(ctx, isl_basic_map *, n);
2862         if (!list)
2863                 goto error;
2864
2865         next = list;
2866         if (isl_union_map_foreach_map(umap, collect_basic_map, &next) < 0)
2867                 goto error;
2868
2869         res = union_floyd_warshall_on_list(ctx, list, n, exact);
2870
2871         if (list) {
2872                 for (i = 0; i < n; ++i)
2873                         isl_basic_map_free(list[i]);
2874                 free(list);
2875         }
2876
2877         isl_union_map_free(umap);
2878         return res;
2879 error:
2880         if (list) {
2881                 for (i = 0; i < n; ++i)
2882                         isl_basic_map_free(list[i]);
2883                 free(list);
2884         }
2885         isl_union_map_free(umap);
2886         return NULL;
2887 }
2888
2889 /* Decompose the give union relation into strongly connected components.
2890  * The implementation is essentially the same as that of
2891  * construct_power_components with the major difference that all
2892  * operations are performed on union maps.
2893  */
2894 static __isl_give isl_union_map *union_components(
2895         __isl_take isl_union_map *umap, int *exact)
2896 {
2897         int i;
2898         int n;
2899         isl_ctx *ctx;
2900         isl_basic_map **list;
2901         isl_basic_map **next;
2902         isl_union_map *path = NULL;
2903         struct basic_map_sort *s = NULL;
2904         int c, l;
2905         int recheck = 0;
2906
2907         n = 0;
2908         if (isl_union_map_foreach_map(umap, inc_count, &n) < 0)
2909                 goto error;
2910
2911         if (n <= 1)
2912                 return union_floyd_warshall(umap, exact);
2913
2914         ctx = isl_union_map_get_ctx(umap);
2915         list = isl_calloc_array(ctx, isl_basic_map *, n);
2916         if (!list)
2917                 goto error;
2918
2919         next = list;
2920         if (isl_union_map_foreach_map(umap, collect_basic_map, &next) < 0)
2921                 goto error;
2922
2923         s = basic_map_sort_init(ctx, n, list);
2924         if (!s)
2925                 goto error;
2926
2927         c = 0;
2928         i = 0;
2929         l = n;
2930         path = isl_union_map_empty(isl_union_map_get_dim(umap));
2931         while (l) {
2932                 isl_union_map *comp;
2933                 isl_union_map *path_comp, *path_comb;
2934                 comp = isl_union_map_empty(isl_union_map_get_dim(umap));
2935                 while (s->order[i] != -1) {
2936                         comp = isl_union_map_add_map(comp,
2937                                     isl_map_from_basic_map(
2938                                         isl_basic_map_copy(list[s->order[i]])));
2939                         --l;
2940                         ++i;
2941                 }
2942                 path_comp = union_floyd_warshall(comp, exact);
2943                 path_comb = isl_union_map_apply_range(isl_union_map_copy(path),
2944                                                 isl_union_map_copy(path_comp));
2945                 path = isl_union_map_union(path, path_comp);
2946                 path = isl_union_map_union(path, path_comb);
2947                 ++i;
2948                 ++c;
2949         }
2950
2951         if (c > 1 && s->check_closed && !*exact) {
2952                 int closed;
2953
2954                 closed = isl_union_map_is_transitively_closed(path);
2955                 if (closed < 0)
2956                         goto error;
2957                 recheck = !closed;
2958         }
2959
2960         basic_map_sort_free(s);
2961
2962         for (i = 0; i < n; ++i)
2963                 isl_basic_map_free(list[i]);
2964         free(list);
2965
2966         if (recheck) {
2967                 isl_union_map_free(path);
2968                 return union_floyd_warshall(umap, exact);
2969         }
2970
2971         isl_union_map_free(umap);
2972
2973         return path;
2974 error:
2975         basic_map_sort_free(s);
2976         if (list) {
2977                 for (i = 0; i < n; ++i)
2978                         isl_basic_map_free(list[i]);
2979                 free(list);
2980         }
2981         isl_union_map_free(umap);
2982         isl_union_map_free(path);
2983         return NULL;
2984 }
2985
2986 /* Compute the transitive closure  of "umap", or an overapproximation.
2987  * If the result is exact, then *exact is set to 1.
2988  */
2989 __isl_give isl_union_map *isl_union_map_transitive_closure(
2990         __isl_take isl_union_map *umap, int *exact)
2991 {
2992         int closed;
2993
2994         if (!umap)
2995                 return NULL;
2996
2997         if (exact)
2998                 *exact = 1;
2999
3000         umap = isl_union_map_compute_divs(umap);
3001         umap = isl_union_map_coalesce(umap);
3002         closed = isl_union_map_is_transitively_closed(umap);
3003         if (closed < 0)
3004                 goto error;
3005         if (closed)
3006                 return umap;
3007         umap = union_components(umap, exact);
3008         return umap;
3009 error:
3010         isl_union_map_free(umap);
3011         return NULL;
3012 }