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