sample: remove lineality and skew into positive orthant
[platform/upstream/isl.git] / isl_convex_hull.c
1 #include "isl_lp.h"
2 #include "isl_map.h"
3 #include "isl_map_private.h"
4 #include "isl_mat.h"
5 #include "isl_set.h"
6 #include "isl_seq.h"
7 #include "isl_equalities.h"
8
9 static struct isl_basic_set *uset_convex_hull(struct isl_ctx *ctx,
10         struct isl_set *set);
11
12 static swap_ineq(struct isl_basic_map *bmap, unsigned i, unsigned j)
13 {
14         isl_int *t;
15
16         if (i != j) {
17                 t = bmap->ineq[i];
18                 bmap->ineq[i] = bmap->ineq[j];
19                 bmap->ineq[j] = t;
20         }
21 }
22
23 /* Compute the convex hull of a basic map, by removing the redundant
24  * constraints.  If the minimal value along the normal of a constraint
25  * is the same if the constraint is removed, then the constraint is redundant.
26  *
27  * Alternatively, we could have intersected the basic map with the
28  * corresponding equality and the checked if the dimension was that
29  * of a facet.
30  */
31 struct isl_basic_map *isl_basic_map_convex_hull(struct isl_ctx *ctx,
32                                                 struct isl_basic_map *bmap)
33 {
34         int i;
35         isl_int opt_n;
36         isl_int opt_d;
37
38         bmap = isl_basic_map_implicit_equalities(ctx, bmap);
39         if (!bmap)
40                 return NULL;
41
42         if (F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
43                 return bmap;
44         if (F_ISSET(bmap, ISL_BASIC_MAP_NO_REDUNDANT))
45                 return bmap;
46
47         isl_int_init(opt_n);
48         isl_int_init(opt_d);
49         for (i = bmap->n_ineq-1; i >= 0; --i) {
50                 enum isl_lp_result res;
51                 swap_ineq(bmap, i, bmap->n_ineq-1);
52                 bmap->n_ineq--;
53                 res = isl_solve_lp(bmap, 0,
54                         bmap->ineq[bmap->n_ineq]+1, ctx->one, &opt_n, &opt_d);
55                 bmap->n_ineq++;
56                 swap_ineq(bmap, i, bmap->n_ineq-1);
57                 if (res == isl_lp_unbounded)
58                         continue;
59                 if (res == isl_lp_error)
60                         goto error;
61                 if (res == isl_lp_empty) {
62                         bmap = isl_basic_map_set_to_empty(ctx, bmap);
63                         break;
64                 }
65                 isl_int_addmul(opt_n, opt_d, bmap->ineq[i][0]);
66                 if (!isl_int_is_neg(opt_n))
67                         isl_basic_map_drop_inequality(ctx, bmap, i);
68         }
69         isl_int_clear(opt_n);
70         isl_int_clear(opt_d);
71
72         F_SET(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
73         return bmap;
74 error:
75         isl_int_clear(opt_n);
76         isl_int_clear(opt_d);
77         isl_basic_map_free(ctx, bmap);
78         return NULL;
79 }
80
81 struct isl_basic_set *isl_basic_set_convex_hull(struct isl_ctx *ctx,
82                                                 struct isl_basic_set *bset)
83 {
84         return (struct isl_basic_set *)isl_basic_map_convex_hull(ctx,
85                                                 (struct isl_basic_map *)bset);
86 }
87
88 /* Check if "c" is a direction with a lower bound in "set" that is independent
89  * of the previously found "n" bounds in "dirs".
90  * If so, add it to the list, with the negative of the lower bound
91  * in the constant position, i.e., such that c correspond to a bounding
92  * hyperplane (but not necessarily a facet).
93  */
94 static int is_independent_bound(struct isl_ctx *ctx,
95         struct isl_set *set, isl_int *c,
96         struct isl_mat *dirs, int n)
97 {
98         int first;
99         int i = 0, j;
100         isl_int opt;
101         isl_int opt_denom;
102
103         isl_seq_cpy(dirs->row[n]+1, c+1, dirs->n_col-1);
104         if (n != 0) {
105                 int pos = isl_seq_first_non_zero(dirs->row[n]+1, dirs->n_col-1);
106                 if (pos < 0)
107                         return 0;
108                 for (i = 0; i < n; ++i) {
109                         int pos_i;
110                         pos_i = isl_seq_first_non_zero(dirs->row[i]+1, dirs->n_col-1);
111                         if (pos_i < pos)
112                                 continue;
113                         if (pos_i > pos)
114                                 break;
115                         isl_seq_elim(dirs->row[n]+1, dirs->row[i]+1, pos,
116                                         dirs->n_col-1, NULL);
117                         pos = isl_seq_first_non_zero(dirs->row[n]+1, dirs->n_col-1);
118                         if (pos < 0)
119                                 return 0;
120                 }
121         }
122
123         isl_int_init(opt);
124         isl_int_init(opt_denom);
125         first = 1;
126         for (j = 0; j < set->n; ++j) {
127                 enum isl_lp_result res;
128
129                 if (F_ISSET(set->p[j], ISL_BASIC_MAP_EMPTY))
130                         continue;
131
132                 res = isl_solve_lp((struct isl_basic_map*)set->p[j],
133                                 0, dirs->row[n]+1, ctx->one, &opt, &opt_denom);
134                 if (res == isl_lp_unbounded)
135                         break;
136                 if (res == isl_lp_error)
137                         goto error;
138                 if (res == isl_lp_empty) {
139                         set->p[j] = isl_basic_set_set_to_empty(ctx, set->p[j]);
140                         if (!set->p[j])
141                                 goto error;
142                         continue;
143                 }
144                 if (!isl_int_is_one(opt_denom))
145                         isl_seq_scale(dirs->row[n], dirs->row[n], opt_denom,
146                                         dirs->n_col);
147                 if (first || isl_int_lt(opt, dirs->row[n][0]))
148                         isl_int_set(dirs->row[n][0], opt);
149                 first = 0;
150         }
151         isl_int_clear(opt);
152         isl_int_clear(opt_denom);
153         if (j < set->n)
154                 return 0;
155         isl_int_neg(dirs->row[n][0], dirs->row[n][0]);
156         if (i < n) {
157                 int k;
158                 isl_int *t = dirs->row[n];
159                 for (k = n; k > i; --k)
160                         dirs->row[k] = dirs->row[k-1];
161                 dirs->row[i] = t;
162         }
163         return 1;
164 error:
165         isl_int_clear(opt);
166         isl_int_clear(opt_denom);
167         return -1;
168 }
169
170 /* Compute and return a maximal set of linearly independent bounds
171  * on the set "set", based on the constraints of the basic sets
172  * in "set".
173  */
174 static struct isl_mat *independent_bounds(struct isl_ctx *ctx,
175         struct isl_set *set)
176 {
177         int i, j, n;
178         struct isl_mat *dirs = NULL;
179
180         dirs = isl_mat_alloc(ctx, set->dim, 1+set->dim);
181         if (!dirs)
182                 goto error;
183
184         n = 0;
185         for (i = 0; n < set->dim && i < set->n; ++i) {
186                 int f;
187                 struct isl_basic_set *bset = set->p[i];
188
189                 for (j = 0; n < set->dim && j < bset->n_eq; ++j) {
190                         f = is_independent_bound(ctx, set, bset->eq[j],
191                                                 dirs, n);
192                         if (f < 0)
193                                 goto error;
194                         if (f) {
195                                 ++n;
196                                 continue;
197                         }
198                         isl_seq_neg(bset->eq[j], bset->eq[j], 1+set->dim);
199                         f = is_independent_bound(ctx, set, bset->eq[j],
200                                                 dirs, n);
201                         isl_seq_neg(bset->eq[j], bset->eq[j], 1+set->dim);
202                         if (f < 0)
203                                 goto error;
204                         if (f)
205                                 ++n;
206                 }
207                 for (j = 0; n < set->dim && j < bset->n_ineq; ++j) {
208                         f = is_independent_bound(ctx, set, bset->ineq[j],
209                                                 dirs, n);
210                         if (f < 0)
211                                 goto error;
212                         if (f)
213                                 ++n;
214                 }
215         }
216         dirs->n_row = n;
217         return dirs;
218 error:
219         isl_mat_free(ctx, dirs);
220         return NULL;
221 }
222
223 static struct isl_basic_set *isl_basic_set_set_rational(struct isl_ctx *ctx,
224         struct isl_basic_set *bset)
225 {
226         if (!bset)
227                 return NULL;
228
229         if (F_ISSET(bset, ISL_BASIC_MAP_RATIONAL))
230                 return bset;
231
232         bset = isl_basic_set_cow(ctx, bset);
233         if (!bset)
234                 return NULL;
235
236         F_SET(bset, ISL_BASIC_MAP_RATIONAL);
237
238         return bset;
239 }
240
241 static struct isl_set *isl_set_set_rational(struct isl_ctx *ctx,
242         struct isl_set *set)
243 {
244         int i;
245
246         set = isl_set_cow(ctx, set);
247         if (!set)
248                 return NULL;
249         for (i = 0; i < set->n; ++i) {
250                 set->p[i] = isl_basic_set_set_rational(ctx, set->p[i]);
251                 if (!set->p[i])
252                         goto error;
253         }
254         return set;
255 error:
256         isl_set_free(ctx, set);
257         return NULL;
258 }
259
260 static struct isl_basic_set *isl_basic_set_add_equality(struct isl_ctx *ctx,
261         struct isl_basic_set *bset, isl_int *c)
262 {
263         int i;
264         unsigned total;
265
266         isl_assert(ctx, bset->nparam == 0, goto error);
267         isl_assert(ctx, bset->n_div == 0, goto error);
268         bset = isl_basic_set_extend(ctx, bset, 0, bset->dim, 0, 1, 0);
269         i = isl_basic_set_alloc_equality(ctx, bset);
270         if (i < 0)
271                 goto error;
272         isl_seq_cpy(bset->eq[i], c, 1 + bset->dim);
273         return bset;
274 error:
275         isl_basic_set_free(ctx, bset);
276         return NULL;
277 }
278
279 static struct isl_set *isl_set_add_equality(struct isl_ctx *ctx,
280         struct isl_set *set, isl_int *c)
281 {
282         int i;
283
284         set = isl_set_cow(ctx, set);
285         if (!set)
286                 return NULL;
287         for (i = 0; i < set->n; ++i) {
288                 set->p[i] = isl_basic_set_add_equality(ctx, set->p[i], c);
289                 if (!set->p[i])
290                         goto error;
291         }
292         return set;
293 error:
294         isl_set_free(ctx, set);
295         return NULL;
296 }
297
298 /* Given a union of basic sets, construct the constraints for wrapping
299  * a facet around one of its ridges.
300  * In particular, if each of n the d-dimensional basic sets i in "set"
301  * contains the origin, satisfies the constraints x_1 >= 0 and x_2 >= 0
302  * and is defined by the constraints
303  *                                  [ 1 ]
304  *                              A_i [ x ]  >= 0
305  *
306  * then the resulting set is of dimension n*(1+d) and has as contraints
307  *
308  *                                  [ a_i ]
309  *                              A_i [ x_i ] >= 0
310  *
311  *                                    a_i   >= 0
312  *
313  *                      \sum_i x_{i,1} = 1
314  */
315 static struct isl_basic_set *wrap_constraints(struct isl_ctx *ctx,
316                                                         struct isl_set *set)
317 {
318         struct isl_basic_set *lp;
319         unsigned n_eq;
320         unsigned n_ineq;
321         int i, j, k;
322         unsigned dim;
323
324         if (!set)
325                 return NULL;
326
327         dim = 1 + set->dim;
328         n_eq = 1;
329         n_ineq = set->n;
330         for (i = 0; i < set->n; ++i) {
331                 n_eq += set->p[i]->n_eq;
332                 n_ineq += set->p[i]->n_ineq;
333         }
334         lp = isl_basic_set_alloc(ctx, 0, dim * set->n, 0, n_eq, n_ineq);
335         if (!lp)
336                 return NULL;
337         k = isl_basic_set_alloc_equality(ctx, lp);
338         isl_int_set_si(lp->eq[k][0], -1);
339         for (i = 0; i < set->n; ++i) {
340                 isl_int_set_si(lp->eq[k][1+dim*i], 0);
341                 isl_int_set_si(lp->eq[k][1+dim*i+1], 1);
342                 isl_seq_clr(lp->eq[k]+1+dim*i+2, dim-2);
343         }
344         for (i = 0; i < set->n; ++i) {
345                 k = isl_basic_set_alloc_inequality(ctx, lp);
346                 isl_seq_clr(lp->ineq[k], 1+lp->dim);
347                 isl_int_set_si(lp->ineq[k][1+dim*i], 1);
348
349                 for (j = 0; j < set->p[i]->n_eq; ++j) {
350                         k = isl_basic_set_alloc_equality(ctx, lp);
351                         isl_seq_clr(lp->eq[k], 1+dim*i);
352                         isl_seq_cpy(lp->eq[k]+1+dim*i, set->p[i]->eq[j], dim);
353                         isl_seq_clr(lp->eq[k]+1+dim*(i+1), dim*(set->n-i-1));
354                 }
355
356                 for (j = 0; j < set->p[i]->n_ineq; ++j) {
357                         k = isl_basic_set_alloc_inequality(ctx, lp);
358                         isl_seq_clr(lp->ineq[k], 1+dim*i);
359                         isl_seq_cpy(lp->ineq[k]+1+dim*i, set->p[i]->ineq[j], dim);
360                         isl_seq_clr(lp->ineq[k]+1+dim*(i+1), dim*(set->n-i-1));
361                 }
362         }
363         return lp;
364 }
365
366 /* Given a facet "facet" of the convex hull of "set" and a facet "ridge"
367  * of that facet, compute the other facet of the convex hull that contains
368  * the ridge.
369  *
370  * We first transform the set such that the facet constraint becomes
371  *
372  *                      x_1 >= 0
373  *
374  * I.e., the facet is
375  *
376  *                      x_1 = 0
377  *
378  * and on that facet, the constraint that defines the ridge is
379  *
380  *                      x_2 >= 0
381  *
382  * (This transformation is not strictly needed, all that is needed is
383  * that the ridge contains the origin.)
384  *
385  * Since the ridge contains the origin, the cone of the convex hull
386  * will be of the form
387  *
388  *                      x_1 >= 0
389  *                      x_2 >= a x_1
390  *
391  * with this second constraint defining the new facet.
392  * The constant a is obtained by settting x_1 in the cone of the
393  * convex hull to 1 and minimizing x_2.
394  * Now, each element in the cone of the convex hull is the sum
395  * of elements in the cones of the basic sets.
396  * If a_i is the dilation factor of basic set i, then the problem
397  * we need to solve is
398  *
399  *                      min \sum_i x_{i,2}
400  *                      st
401  *                              \sum_i x_{i,1} = 1
402  *                                  a_i   >= 0
403  *                                [ a_i ]
404  *                              A [ x_i ] >= 0
405  *
406  * with
407  *                                  [  1  ]
408  *                              A_i [ x_i ] >= 0
409  *
410  * the constraints of each (transformed) basic set.
411  * If a = n/d, then the consstraint defining the new facet (in the transformed
412  * space) is
413  *
414  *                      -n x_1 + d x_2 >= 0
415  *
416  * In the original space, we need to take the same combination of the
417  * corresponding constraints "facet" and "ridge".
418  */
419 static isl_int *wrap_facet(struct isl_ctx *ctx, struct isl_set *set,
420         isl_int *facet, isl_int *ridge)
421 {
422         int i;
423         struct isl_mat *T = NULL;
424         struct isl_basic_set *lp = NULL;
425         struct isl_vec *obj;
426         enum isl_lp_result res;
427         isl_int num, den;
428         unsigned dim;
429
430         set = isl_set_copy(ctx, set);
431
432         dim = 1 + set->dim;
433         T = isl_mat_alloc(ctx, 3, 1 + set->dim);
434         if (!T)
435                 goto error;
436         isl_int_set_si(T->row[0][0], 1);
437         isl_seq_clr(T->row[0]+1, set->dim);
438         isl_seq_cpy(T->row[1], facet, 1+set->dim);
439         isl_seq_cpy(T->row[2], ridge, 1+set->dim);
440         T = isl_mat_right_inverse(ctx, T);
441         set = isl_set_preimage(ctx, set, T);
442         T = NULL;
443         lp = wrap_constraints(ctx, set);
444         obj = isl_vec_alloc(ctx, dim*set->n);
445         if (!obj)
446                 goto error;
447         for (i = 0; i < set->n; ++i) {
448                 isl_seq_clr(obj->block.data+dim*i, 2);
449                 isl_int_set_si(obj->block.data[dim*i+2], 1);
450                 isl_seq_clr(obj->block.data+dim*i+3, dim-3);
451         }
452         isl_int_init(num);
453         isl_int_init(den);
454         res = isl_solve_lp((struct isl_basic_map *)lp, 0,
455                                         obj->block.data, ctx->one, &num, &den);
456         if (res == isl_lp_ok) {
457                 isl_int_neg(num, num);
458                 isl_seq_combine(facet, num, facet, den, ridge, dim);
459         }
460         isl_int_clear(num);
461         isl_int_clear(den);
462         isl_vec_free(ctx, obj);
463         isl_basic_set_free(ctx, lp);
464         isl_set_free(ctx, set);
465         return (res == isl_lp_ok) ? facet : NULL;
466 error:
467         isl_basic_set_free(ctx, lp);
468         isl_mat_free(ctx, T);
469         isl_set_free(ctx, set);
470         return NULL;
471 }
472
473 /* Given a direction of a constraint, compute the constant term
474  * such that the resulting constraint is a bounding constraint
475  * of the set "set" (which just happens to be a face of the
476  * original set).
477  */
478 static int compute_bound_on_face(struct isl_ctx *ctx,
479         struct isl_set *set, isl_int *c)
480 {
481         int first = 1;
482         int j;
483         isl_int opt;
484         isl_int opt_denom;
485
486         isl_int_init(opt);
487         isl_int_init(opt_denom);
488         for (j = 0; j < set->n; ++j) {
489                 enum isl_lp_result res;
490
491                 if (F_ISSET(set->p[j], ISL_BASIC_MAP_EMPTY))
492                         continue;
493
494                 res = isl_solve_lp((struct isl_basic_map*)set->p[j],
495                                         0, c+1, ctx->one, &opt, &opt_denom);
496                 if (res == isl_lp_unbounded)
497                         goto error;
498                 if (res == isl_lp_error)
499                         goto error;
500                 if (res == isl_lp_empty) {
501                         set->p[j] = isl_basic_set_set_to_empty(ctx, set->p[j]);
502                         if (!set->p[j])
503                                 goto error;
504                         continue;
505                 }
506                 if (!isl_int_is_one(opt_denom))
507                         isl_seq_scale(c, c, opt_denom, 1+set->dim);
508                 if (first || isl_int_lt(opt, c[0]))
509                         isl_int_set(c[0], opt);
510                 first = 0;
511         }
512         isl_assert(ctx, !first, goto error);
513         isl_int_clear(opt);
514         isl_int_clear(opt_denom);
515         isl_int_neg(c[0], c[0]);
516         return 0;
517 error:
518         isl_int_clear(opt);
519         isl_int_clear(opt_denom);
520         return -1;
521 }
522
523 /* Given a set of d linearly independent bounding constraints of the
524  * convex hull of "set", compute the constraint of a facet of "set".
525  *
526  * We first compute the intersection with the first bounding hyperplane
527  * and shift the second bounding constraint to be a bounding constraint
528  * of the resulting face.  We then wrap around the next bounding constraint
529  * and continue the process until all bounding constraints have been
530  * taken into account.
531  * The resulting linear combination of the bounding constraints will
532  * correspond to a facet of the convex hull.
533  */
534 static struct isl_mat *initial_facet_constraint(struct isl_ctx *ctx,
535         struct isl_set *set, struct isl_mat *bounds)
536 {
537         struct isl_set *face = NULL;
538         int i;
539
540         isl_assert(ctx, set->n > 0, goto error);
541         isl_assert(ctx, bounds->n_row == set->dim, goto error);
542
543         face = isl_set_copy(ctx, set);
544         if (!face)
545                 goto error;
546         for (i = 1; i < set->dim; ++i) {
547                 face = isl_set_add_equality(ctx, face, bounds->row[i-1]);
548                 if (compute_bound_on_face(ctx, face, bounds->row[i]) < 0)
549                         goto error;
550                 if (!wrap_facet(ctx, set, bounds->row[0], bounds->row[i]))
551                         goto error;
552         }
553         isl_set_free(ctx, face);
554         return bounds;
555 error:
556         isl_set_free(ctx, face);
557         isl_mat_free(ctx, bounds);
558         return NULL;
559 }
560
561 /* Given the bounding constraint "c" of a facet of the convex hull of "set",
562  * compute a hyperplane description of the facet, i.e., compute the facets
563  * of the facet.
564  *
565  * We compute an affine transformation that transforms the constraint
566  *
567  *                        [ 1 ]
568  *                      c [ x ] = 0
569  *
570  * to the constraint
571  *
572  *                         z_1  = 0
573  *
574  * by computing the right inverse U of a matrix that starts with the rows
575  *
576  *                      [ 1 0 ]
577  *                      [  c  ]
578  *
579  * Then
580  *                      [ 1 ]     [ 1 ]
581  *                      [ x ] = U [ z ]
582  * and
583  *                      [ 1 ]     [ 1 ]
584  *                      [ z ] = Q [ x ]
585  *
586  * with Q = U^{-1}
587  * Since z_1 is zero, we can drop this variable as well as the corresponding
588  * column of U to obtain
589  *
590  *                      [ 1 ]      [ 1  ]
591  *                      [ x ] = U' [ z' ]
592  * and
593  *                      [ 1  ]      [ 1 ]
594  *                      [ z' ] = Q' [ x ]
595  *
596  * with Q' equal to Q, but without the corresponding row.
597  * After computing the facets of the facet in the z' space,
598  * we convert them back to the x space through Q.
599  */
600 static struct isl_basic_set *compute_facet(struct isl_ctx *ctx,
601         struct isl_set *set, isl_int *c)
602 {
603         struct isl_mat *m, *U, *Q;
604         struct isl_basic_set *facet;
605
606         set = isl_set_copy(ctx, set);
607         m = isl_mat_alloc(ctx, 2, 1 + set->dim);
608         if (!m)
609                 goto error;
610         isl_int_set_si(m->row[0][0], 1);
611         isl_seq_clr(m->row[0]+1, set->dim);
612         isl_seq_cpy(m->row[1], c, 1+set->dim);
613         m = isl_mat_left_hermite(ctx, m, 0, &U, &Q);
614         if (!m)
615                 goto error;
616         U = isl_mat_drop_cols(ctx, U, 1, 1);
617         Q = isl_mat_drop_rows(ctx, Q, 1, 1);
618         set = isl_set_preimage(ctx, set, U);
619         facet = uset_convex_hull(ctx, set);
620         facet = isl_basic_set_preimage(ctx, facet, Q);
621         isl_mat_free(ctx, m);
622         return facet;
623 error:
624         isl_set_free(ctx, set);
625         return NULL;
626 }
627
628 /* Given an initial facet constraint, compute the remaining facets.
629  * We do this by running through all facets found so far and computing
630  * the adjacent facets through wrapping, adding those facets that we
631  * hadn't already found before.
632  *
633  * This function can still be significantly optimized by checking which of
634  * the facets of the basic sets are also facets of the convex hull and
635  * using all the facets so far to help in constructing the facets of the
636  * facets
637  * and/or
638  * using the technique in section "3.1 Ridge Generation" of
639  * "Extended Convex Hull" by Fukuda et al.
640  */
641 static struct isl_basic_set *extend(struct isl_ctx *ctx, struct isl_set *set,
642         struct isl_mat *initial)
643 {
644         int i, j, f;
645         int k;
646         struct isl_basic_set *hull = NULL;
647         struct isl_basic_set *facet = NULL;
648         unsigned n_ineq;
649         unsigned total;
650
651         isl_assert(ctx, set->n > 0, goto error);
652
653         n_ineq = 1;
654         for (i = 0; i < set->n; ++i) {
655                 n_ineq += set->p[i]->n_eq;
656                 n_ineq += set->p[i]->n_ineq;
657         }
658         isl_assert(ctx, 1 + set->dim == initial->n_col, goto error);
659         hull = isl_basic_set_alloc(ctx, 0, set->dim, 0,
660                     0, n_ineq + 2 * set->p[0]->n_div);
661         if (!hull)
662                 goto error;
663         k = isl_basic_set_alloc_inequality(ctx, hull);
664         if (k < 0)
665                 goto error;
666         isl_seq_cpy(hull->ineq[k], initial->row[0], initial->n_col);
667         for (i = 0; i < hull->n_ineq; ++i) {
668                 facet = compute_facet(ctx, set, hull->ineq[i]);
669                 if (!facet)
670                         goto error;
671                 for (j = 0; j < facet->n_ineq; ++j) {
672                         k = isl_basic_set_alloc_inequality(ctx, hull);
673                         if (k < 0)
674                                 goto error;
675                         isl_seq_cpy(hull->ineq[k], hull->ineq[i], 1+hull->dim);
676                         if (!wrap_facet(ctx, set, hull->ineq[k], facet->ineq[j]))
677                                 goto error;
678                         for (f = 0; f < k; ++f)
679                                 if (isl_seq_eq(hull->ineq[f], hull->ineq[k],
680                                                 1+hull->dim))
681                                         break;
682                         if (f < k)
683                                 isl_basic_set_free_inequality(ctx, hull, 1);
684                 }
685                 isl_basic_set_free(ctx, facet);
686         }
687         hull = isl_basic_set_simplify(ctx, hull);
688         hull = isl_basic_set_finalize(ctx, hull);
689         return hull;
690 error:
691         isl_basic_set_free(ctx, hull);
692         return NULL;
693 }
694
695 /* Special case for computing the convex hull of a one dimensional set.
696  * We simply collect the lower and upper bounds of each basic set
697  * and the biggest of those.
698  */
699 static struct isl_basic_set *convex_hull_1d(struct isl_ctx *ctx,
700         struct isl_set *set)
701 {
702         struct isl_mat *c = NULL;
703         isl_int *lower = NULL;
704         isl_int *upper = NULL;
705         int i, j, k;
706         isl_int a, b;
707         struct isl_basic_set *hull;
708
709         for (i = 0; i < set->n; ++i) {
710                 set->p[i] = isl_basic_set_simplify(ctx, set->p[i]);
711                 if (!set->p[i])
712                         goto error;
713         }
714         set = isl_set_remove_empty_parts(ctx, set);
715         if (!set)
716                 goto error;
717         isl_assert(ctx, set->n > 0, goto error);
718         c = isl_mat_alloc(ctx, 2, 2);
719         if (!c)
720                 goto error;
721
722         if (set->p[0]->n_eq > 0) {
723                 isl_assert(ctx, set->p[0]->n_eq == 1, goto error);
724                 lower = c->row[0];
725                 upper = c->row[1];
726                 if (isl_int_is_pos(set->p[0]->eq[0][1])) {
727                         isl_seq_cpy(lower, set->p[0]->eq[0], 2);
728                         isl_seq_neg(upper, set->p[0]->eq[0], 2);
729                 } else {
730                         isl_seq_neg(lower, set->p[0]->eq[0], 2);
731                         isl_seq_cpy(upper, set->p[0]->eq[0], 2);
732                 }
733         } else {
734                 for (j = 0; j < set->p[0]->n_ineq; ++j) {
735                         if (isl_int_is_pos(set->p[0]->ineq[j][1])) {
736                                 lower = c->row[0];
737                                 isl_seq_cpy(lower, set->p[0]->ineq[j], 2);
738                         } else {
739                                 upper = c->row[1];
740                                 isl_seq_cpy(upper, set->p[0]->ineq[j], 2);
741                         }
742                 }
743         }
744
745         isl_int_init(a);
746         isl_int_init(b);
747         for (i = 0; i < set->n; ++i) {
748                 struct isl_basic_set *bset = set->p[i];
749                 int has_lower = 0;
750                 int has_upper = 0;
751
752                 for (j = 0; j < bset->n_eq; ++j) {
753                         has_lower = 1;
754                         has_upper = 1;
755                         if (lower) {
756                                 isl_int_mul(a, lower[0], bset->eq[j][1]);
757                                 isl_int_mul(b, lower[1], bset->eq[j][0]);
758                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
759                                         isl_seq_cpy(lower, bset->eq[j], 2);
760                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
761                                         isl_seq_neg(lower, bset->eq[j], 2);
762                         }
763                         if (upper) {
764                                 isl_int_mul(a, upper[0], bset->eq[j][1]);
765                                 isl_int_mul(b, upper[1], bset->eq[j][0]);
766                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
767                                         isl_seq_neg(upper, bset->eq[j], 2);
768                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
769                                         isl_seq_cpy(upper, bset->eq[j], 2);
770                         }
771                 }
772                 for (j = 0; j < bset->n_ineq; ++j) {
773                         if (isl_int_is_pos(bset->ineq[j][1]))
774                                 has_lower = 1;
775                         if (isl_int_is_neg(bset->ineq[j][1]))
776                                 has_upper = 1;
777                         if (lower && isl_int_is_pos(bset->ineq[j][1])) {
778                                 isl_int_mul(a, lower[0], bset->ineq[j][1]);
779                                 isl_int_mul(b, lower[1], bset->ineq[j][0]);
780                                 if (isl_int_lt(a, b))
781                                         isl_seq_cpy(lower, bset->ineq[j], 2);
782                         }
783                         if (upper && isl_int_is_neg(bset->ineq[j][1])) {
784                                 isl_int_mul(a, upper[0], bset->ineq[j][1]);
785                                 isl_int_mul(b, upper[1], bset->ineq[j][0]);
786                                 if (isl_int_gt(a, b))
787                                         isl_seq_cpy(upper, bset->ineq[j], 2);
788                         }
789                 }
790                 if (!has_lower)
791                         lower = NULL;
792                 if (!has_upper)
793                         upper = NULL;
794         }
795         isl_int_clear(a);
796         isl_int_clear(b);
797
798         hull = isl_basic_set_alloc(ctx, 0, 1, 0, 0, 2);
799         if (!hull)
800                 goto error;
801         if (lower) {
802                 k = isl_basic_set_alloc_inequality(ctx, hull);
803                 isl_seq_cpy(hull->ineq[k], lower, 2);
804         }
805         if (upper) {
806                 k = isl_basic_set_alloc_inequality(ctx, hull);
807                 isl_seq_cpy(hull->ineq[k], upper, 2);
808         }
809         hull = isl_basic_set_finalize(ctx, hull);
810         isl_set_free(ctx, set);
811         isl_mat_free(ctx, c);
812         return hull;
813 error:
814         isl_set_free(ctx, set);
815         isl_mat_free(ctx, c);
816         return NULL;
817 }
818
819 /* Project out final n dimensions using Fourier-Motzkin */
820 static struct isl_set *set_project_out(struct isl_ctx *ctx,
821         struct isl_set *set, unsigned n)
822 {
823         int i;
824
825         set = isl_set_cow(ctx, set);
826         if (!set)
827                 return NULL;
828         
829         for (i = 0; i < set->n; ++i) {
830                 set->p[i] = isl_basic_set_eliminate_vars(ctx, set->p[i],
831                                                             set->dim - n, n);
832                 if (!set->p[i])
833                         goto error;
834         }
835         set = isl_set_drop_vars(ctx, set, set->dim - n, n);
836         return set;
837 error:
838         isl_set_free(ctx, set);
839         return NULL;
840 }
841
842 /* If the number of linearly independent bounds we found is smaller
843  * than the dimension, then the convex hull will have a lineality space,
844  * so we may as well project out this lineality space.
845  * We first transform the set such that the first variables correspond
846  * to the directions of the linearly independent bounds and then
847  * project out the remaining variables.
848  */
849 static struct isl_basic_set *modulo_lineality(struct isl_ctx *ctx,
850         struct isl_set *set, struct isl_mat *bounds)
851 {
852         int i, j;
853         unsigned old_dim, new_dim;
854         struct isl_mat *H = NULL, *U = NULL, *Q = NULL;
855         struct isl_basic_set *hull;
856
857         old_dim = set->dim;
858         new_dim = bounds->n_row;
859         H = isl_mat_sub_alloc(ctx, bounds->row, 0, bounds->n_row, 1, set->dim);
860         H = isl_mat_left_hermite(ctx, H, 0, &U, &Q);
861         if (!H)
862                 goto error;
863         U = isl_mat_lin_to_aff(ctx, U);
864         Q = isl_mat_lin_to_aff(ctx, Q);
865         Q->n_row = 1 + new_dim;
866         isl_mat_free(ctx, H);
867         set = isl_set_preimage(ctx, set, U);
868         set = set_project_out(ctx, set, old_dim - new_dim);
869         hull = uset_convex_hull(ctx, set);
870         hull = isl_basic_set_preimage(ctx, hull, Q);
871         isl_mat_free(ctx, bounds);
872         return hull;
873 error:
874         isl_mat_free(ctx, bounds);
875         isl_mat_free(ctx, Q);
876         isl_set_free(ctx, set);
877         return NULL;
878 }
879
880 /* This is the core procedure, where "set" is a "pure" set, i.e.,
881  * without parameters or divs and where the convex hull of set is
882  * known to be full-dimensional.
883  */
884 static struct isl_basic_set *uset_convex_hull(struct isl_ctx *ctx,
885         struct isl_set *set)
886 {
887         int i;
888         struct isl_basic_set *convex_hull = NULL;
889         struct isl_mat *bounds;
890
891         if (set->dim == 0) {
892                 convex_hull = isl_basic_set_universe(ctx, 0, 0);
893                 isl_set_free(ctx, set);
894                 return convex_hull;
895         }
896
897         set = isl_set_set_rational(ctx, set);
898
899         if (!set)
900                 goto error;
901         for (i = 0; i < set->n; ++i) {
902                 set->p[i] = isl_basic_set_convex_hull(ctx, set->p[i]);
903                 if (!set->p[i])
904                         goto error;
905         }
906         set = isl_set_remove_empty_parts(ctx, set);
907         if (!set)
908                 goto error;
909         if (set->n == 1) {
910                 convex_hull = isl_basic_set_copy(ctx, set->p[0]);
911                 isl_set_free(ctx, set);
912                 return convex_hull;
913         }
914         if (set->dim == 1)
915                 return convex_hull_1d(ctx, set);
916
917         bounds = independent_bounds(ctx, set);
918         if (!bounds)
919                 goto error;
920         if (bounds->n_row < set->dim)
921                 return modulo_lineality(ctx, set, bounds);
922         bounds = initial_facet_constraint(ctx, set, bounds);
923         if (!bounds)
924                 goto error;
925         convex_hull = extend(ctx, set, bounds);
926         isl_mat_free(ctx, bounds);
927         isl_set_free(ctx, set);
928
929         return convex_hull;
930 error:
931         isl_set_free(ctx, set);
932         return NULL;
933 }
934
935 /* Compute the convex hull of set "set" with affine hull "affine_hull",
936  * We first remove the equalities (transforming the set), compute the
937  * convex hull of the transformed set and then add the equalities back
938  * (after performing the inverse transformation.
939  */
940 static struct isl_basic_set *modulo_affine_hull(struct isl_ctx *ctx,
941         struct isl_set *set, struct isl_basic_set *affine_hull)
942 {
943         struct isl_mat *T;
944         struct isl_mat *T2;
945         struct isl_basic_set *dummy;
946         struct isl_basic_set *convex_hull;
947
948         dummy = isl_basic_set_remove_equalities(ctx,
949                         isl_basic_set_copy(ctx, affine_hull), &T, &T2);
950         if (!dummy)
951                 goto error;
952         isl_basic_set_free(ctx, dummy);
953         set = isl_set_preimage(ctx, set, T);
954         convex_hull = uset_convex_hull(ctx, set);
955         convex_hull = isl_basic_set_preimage(ctx, convex_hull, T2);
956         convex_hull = isl_basic_set_intersect(ctx, convex_hull, affine_hull);
957         return convex_hull;
958 error:
959         isl_basic_set_free(ctx, affine_hull);
960         isl_set_free(ctx, set);
961         return NULL;
962 }
963
964 /* Compute the convex hull of a map.
965  *
966  * The implementation was inspired by "Extended Convex Hull" by Fukuda et al.,
967  * specifically, the wrapping of facets to obtain new facets.
968  */
969 struct isl_basic_map *isl_map_convex_hull(struct isl_ctx *ctx,
970                                                 struct isl_map *map)
971 {
972         struct isl_basic_set *bset;
973         struct isl_basic_set *affine_hull = NULL;
974         struct isl_basic_map *convex_hull = NULL;
975         struct isl_set *set = NULL;
976
977         if (!map)
978                 goto error;
979
980         if (map->n == 0) {
981                 convex_hull = isl_basic_map_empty(ctx,
982                                             map->nparam, map->n_in, map->n_out);
983                 isl_map_free(ctx, map);
984                 return convex_hull;
985         }
986
987         set = isl_map_underlying_set(ctx, isl_map_copy(ctx, map));
988         if (!set)
989                 goto error;
990
991         affine_hull = isl_set_affine_hull(ctx, isl_set_copy(ctx, set));
992         if (!affine_hull)
993                 goto error;
994         if (affine_hull->n_eq != 0)
995                 bset = modulo_affine_hull(ctx, set, affine_hull);
996         else {
997                 isl_basic_set_free(ctx, affine_hull);
998                 bset = uset_convex_hull(ctx, set);
999         }
1000
1001         convex_hull = isl_basic_map_overlying_set(ctx, bset,
1002                         isl_basic_map_copy(ctx, map->p[0]));
1003
1004         isl_map_free(ctx, map);
1005         return convex_hull;
1006 error:
1007         isl_set_free(ctx, set);
1008         isl_map_free(ctx, map);
1009         return NULL;
1010 }
1011
1012 struct isl_basic_set *isl_set_convex_hull(struct isl_ctx *ctx,
1013                                                 struct isl_set *set)
1014 {
1015         return (struct isl_basic_set *)
1016                 isl_map_convex_hull(ctx, (struct isl_map *)set);
1017 }