Merge branch 'maint'
[platform/upstream/isl.git] / isl_convex_hull.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  *
4  * Use of this software is governed by the GNU LGPLv2.1 license
5  *
6  * Written by Sven Verdoolaege, K.U.Leuven, Departement
7  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8  */
9
10 #include <isl_ctx_private.h>
11 #include <isl_map_private.h>
12 #include <isl/lp.h>
13 #include <isl/map.h>
14 #include <isl_mat_private.h>
15 #include <isl/set.h>
16 #include <isl/seq.h>
17 #include "isl_equalities.h"
18 #include "isl_tab.h"
19
20 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set);
21
22 static void swap_ineq(struct isl_basic_map *bmap, unsigned i, unsigned j)
23 {
24         isl_int *t;
25
26         if (i != j) {
27                 t = bmap->ineq[i];
28                 bmap->ineq[i] = bmap->ineq[j];
29                 bmap->ineq[j] = t;
30         }
31 }
32
33 /* Return 1 if constraint c is redundant with respect to the constraints
34  * in bmap.  If c is a lower [upper] bound in some variable and bmap
35  * does not have a lower [upper] bound in that variable, then c cannot
36  * be redundant and we do not need solve any lp.
37  */
38 int isl_basic_map_constraint_is_redundant(struct isl_basic_map **bmap,
39         isl_int *c, isl_int *opt_n, isl_int *opt_d)
40 {
41         enum isl_lp_result res;
42         unsigned total;
43         int i, j;
44
45         if (!bmap)
46                 return -1;
47
48         total = isl_basic_map_total_dim(*bmap);
49         for (i = 0; i < total; ++i) {
50                 int sign;
51                 if (isl_int_is_zero(c[1+i]))
52                         continue;
53                 sign = isl_int_sgn(c[1+i]);
54                 for (j = 0; j < (*bmap)->n_ineq; ++j)
55                         if (sign == isl_int_sgn((*bmap)->ineq[j][1+i]))
56                                 break;
57                 if (j == (*bmap)->n_ineq)
58                         break;
59         }
60         if (i < total)
61                 return 0;
62
63         res = isl_basic_map_solve_lp(*bmap, 0, c, (*bmap)->ctx->one,
64                                         opt_n, opt_d, NULL);
65         if (res == isl_lp_unbounded)
66                 return 0;
67         if (res == isl_lp_error)
68                 return -1;
69         if (res == isl_lp_empty) {
70                 *bmap = isl_basic_map_set_to_empty(*bmap);
71                 return 0;
72         }
73         return !isl_int_is_neg(*opt_n);
74 }
75
76 int isl_basic_set_constraint_is_redundant(struct isl_basic_set **bset,
77         isl_int *c, isl_int *opt_n, isl_int *opt_d)
78 {
79         return isl_basic_map_constraint_is_redundant(
80                         (struct isl_basic_map **)bset, c, opt_n, opt_d);
81 }
82
83 /* Remove redundant
84  * constraints.  If the minimal value along the normal of a constraint
85  * is the same if the constraint is removed, then the constraint is redundant.
86  *
87  * Alternatively, we could have intersected the basic map with the
88  * corresponding equality and the checked if the dimension was that
89  * of a facet.
90  */
91 __isl_give isl_basic_map *isl_basic_map_remove_redundancies(
92         __isl_take isl_basic_map *bmap)
93 {
94         struct isl_tab *tab;
95
96         if (!bmap)
97                 return NULL;
98
99         bmap = isl_basic_map_gauss(bmap, NULL);
100         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
101                 return bmap;
102         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NO_REDUNDANT))
103                 return bmap;
104         if (bmap->n_ineq <= 1)
105                 return bmap;
106
107         tab = isl_tab_from_basic_map(bmap);
108         if (isl_tab_detect_implicit_equalities(tab) < 0)
109                 goto error;
110         if (isl_tab_detect_redundant(tab) < 0)
111                 goto error;
112         bmap = isl_basic_map_update_from_tab(bmap, tab);
113         isl_tab_free(tab);
114         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_IMPLICIT);
115         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
116         return bmap;
117 error:
118         isl_tab_free(tab);
119         isl_basic_map_free(bmap);
120         return NULL;
121 }
122
123 __isl_give isl_basic_set *isl_basic_set_remove_redundancies(
124         __isl_take isl_basic_set *bset)
125 {
126         return (struct isl_basic_set *)
127                 isl_basic_map_remove_redundancies((struct isl_basic_map *)bset);
128 }
129
130 /* Check if the set set is bound in the direction of the affine
131  * constraint c and if so, set the constant term such that the
132  * resulting constraint is a bounding constraint for the set.
133  */
134 static int uset_is_bound(struct isl_set *set, isl_int *c, unsigned len)
135 {
136         int first;
137         int j;
138         isl_int opt;
139         isl_int opt_denom;
140
141         isl_int_init(opt);
142         isl_int_init(opt_denom);
143         first = 1;
144         for (j = 0; j < set->n; ++j) {
145                 enum isl_lp_result res;
146
147                 if (ISL_F_ISSET(set->p[j], ISL_BASIC_SET_EMPTY))
148                         continue;
149
150                 res = isl_basic_set_solve_lp(set->p[j],
151                                 0, c, set->ctx->one, &opt, &opt_denom, NULL);
152                 if (res == isl_lp_unbounded)
153                         break;
154                 if (res == isl_lp_error)
155                         goto error;
156                 if (res == isl_lp_empty) {
157                         set->p[j] = isl_basic_set_set_to_empty(set->p[j]);
158                         if (!set->p[j])
159                                 goto error;
160                         continue;
161                 }
162                 if (first || isl_int_is_neg(opt)) {
163                         if (!isl_int_is_one(opt_denom))
164                                 isl_seq_scale(c, c, opt_denom, len);
165                         isl_int_sub(c[0], c[0], opt);
166                 }
167                 first = 0;
168         }
169         isl_int_clear(opt);
170         isl_int_clear(opt_denom);
171         return j >= set->n;
172 error:
173         isl_int_clear(opt);
174         isl_int_clear(opt_denom);
175         return -1;
176 }
177
178 __isl_give isl_basic_map *isl_basic_map_set_rational(
179         __isl_take isl_basic_set *bmap)
180 {
181         if (!bmap)
182                 return NULL;
183
184         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
185                 return bmap;
186
187         bmap = isl_basic_map_cow(bmap);
188         if (!bmap)
189                 return NULL;
190
191         ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
192
193         return isl_basic_map_finalize(bmap);
194 }
195
196 __isl_give isl_basic_set *isl_basic_set_set_rational(
197         __isl_take isl_basic_set *bset)
198 {
199         return isl_basic_map_set_rational(bset);
200 }
201
202 static struct isl_set *isl_set_set_rational(struct isl_set *set)
203 {
204         int i;
205
206         set = isl_set_cow(set);
207         if (!set)
208                 return NULL;
209         for (i = 0; i < set->n; ++i) {
210                 set->p[i] = isl_basic_set_set_rational(set->p[i]);
211                 if (!set->p[i])
212                         goto error;
213         }
214         return set;
215 error:
216         isl_set_free(set);
217         return NULL;
218 }
219
220 static struct isl_basic_set *isl_basic_set_add_equality(
221         struct isl_basic_set *bset, isl_int *c)
222 {
223         int i;
224         unsigned dim;
225
226         if (!bset)
227                 return NULL;
228
229         if (ISL_F_ISSET(bset, ISL_BASIC_SET_EMPTY))
230                 return bset;
231
232         isl_assert(bset->ctx, isl_basic_set_n_param(bset) == 0, goto error);
233         isl_assert(bset->ctx, bset->n_div == 0, goto error);
234         dim = isl_basic_set_n_dim(bset);
235         bset = isl_basic_set_cow(bset);
236         bset = isl_basic_set_extend(bset, 0, dim, 0, 1, 0);
237         i = isl_basic_set_alloc_equality(bset);
238         if (i < 0)
239                 goto error;
240         isl_seq_cpy(bset->eq[i], c, 1 + dim);
241         return bset;
242 error:
243         isl_basic_set_free(bset);
244         return NULL;
245 }
246
247 static struct isl_set *isl_set_add_basic_set_equality(struct isl_set *set, isl_int *c)
248 {
249         int i;
250
251         set = isl_set_cow(set);
252         if (!set)
253                 return NULL;
254         for (i = 0; i < set->n; ++i) {
255                 set->p[i] = isl_basic_set_add_equality(set->p[i], c);
256                 if (!set->p[i])
257                         goto error;
258         }
259         return set;
260 error:
261         isl_set_free(set);
262         return NULL;
263 }
264
265 /* Given a union of basic sets, construct the constraints for wrapping
266  * a facet around one of its ridges.
267  * In particular, if each of n the d-dimensional basic sets i in "set"
268  * contains the origin, satisfies the constraints x_1 >= 0 and x_2 >= 0
269  * and is defined by the constraints
270  *                                  [ 1 ]
271  *                              A_i [ x ]  >= 0
272  *
273  * then the resulting set is of dimension n*(1+d) and has as constraints
274  *
275  *                                  [ a_i ]
276  *                              A_i [ x_i ] >= 0
277  *
278  *                                    a_i   >= 0
279  *
280  *                      \sum_i x_{i,1} = 1
281  */
282 static struct isl_basic_set *wrap_constraints(struct isl_set *set)
283 {
284         struct isl_basic_set *lp;
285         unsigned n_eq;
286         unsigned n_ineq;
287         int i, j, k;
288         unsigned dim, lp_dim;
289
290         if (!set)
291                 return NULL;
292
293         dim = 1 + isl_set_n_dim(set);
294         n_eq = 1;
295         n_ineq = set->n;
296         for (i = 0; i < set->n; ++i) {
297                 n_eq += set->p[i]->n_eq;
298                 n_ineq += set->p[i]->n_ineq;
299         }
300         lp = isl_basic_set_alloc(set->ctx, 0, dim * set->n, 0, n_eq, n_ineq);
301         lp = isl_basic_set_set_rational(lp);
302         if (!lp)
303                 return NULL;
304         lp_dim = isl_basic_set_n_dim(lp);
305         k = isl_basic_set_alloc_equality(lp);
306         isl_int_set_si(lp->eq[k][0], -1);
307         for (i = 0; i < set->n; ++i) {
308                 isl_int_set_si(lp->eq[k][1+dim*i], 0);
309                 isl_int_set_si(lp->eq[k][1+dim*i+1], 1);
310                 isl_seq_clr(lp->eq[k]+1+dim*i+2, dim-2);
311         }
312         for (i = 0; i < set->n; ++i) {
313                 k = isl_basic_set_alloc_inequality(lp);
314                 isl_seq_clr(lp->ineq[k], 1+lp_dim);
315                 isl_int_set_si(lp->ineq[k][1+dim*i], 1);
316
317                 for (j = 0; j < set->p[i]->n_eq; ++j) {
318                         k = isl_basic_set_alloc_equality(lp);
319                         isl_seq_clr(lp->eq[k], 1+dim*i);
320                         isl_seq_cpy(lp->eq[k]+1+dim*i, set->p[i]->eq[j], dim);
321                         isl_seq_clr(lp->eq[k]+1+dim*(i+1), dim*(set->n-i-1));
322                 }
323
324                 for (j = 0; j < set->p[i]->n_ineq; ++j) {
325                         k = isl_basic_set_alloc_inequality(lp);
326                         isl_seq_clr(lp->ineq[k], 1+dim*i);
327                         isl_seq_cpy(lp->ineq[k]+1+dim*i, set->p[i]->ineq[j], dim);
328                         isl_seq_clr(lp->ineq[k]+1+dim*(i+1), dim*(set->n-i-1));
329                 }
330         }
331         return lp;
332 }
333
334 /* Given a facet "facet" of the convex hull of "set" and a facet "ridge"
335  * of that facet, compute the other facet of the convex hull that contains
336  * the ridge.
337  *
338  * We first transform the set such that the facet constraint becomes
339  *
340  *                      x_1 >= 0
341  *
342  * I.e., the facet lies in
343  *
344  *                      x_1 = 0
345  *
346  * and on that facet, the constraint that defines the ridge is
347  *
348  *                      x_2 >= 0
349  *
350  * (This transformation is not strictly needed, all that is needed is
351  * that the ridge contains the origin.)
352  *
353  * Since the ridge contains the origin, the cone of the convex hull
354  * will be of the form
355  *
356  *                      x_1 >= 0
357  *                      x_2 >= a x_1
358  *
359  * with this second constraint defining the new facet.
360  * The constant a is obtained by settting x_1 in the cone of the
361  * convex hull to 1 and minimizing x_2.
362  * Now, each element in the cone of the convex hull is the sum
363  * of elements in the cones of the basic sets.
364  * If a_i is the dilation factor of basic set i, then the problem
365  * we need to solve is
366  *
367  *                      min \sum_i x_{i,2}
368  *                      st
369  *                              \sum_i x_{i,1} = 1
370  *                                  a_i   >= 0
371  *                                [ a_i ]
372  *                              A [ x_i ] >= 0
373  *
374  * with
375  *                                  [  1  ]
376  *                              A_i [ x_i ] >= 0
377  *
378  * the constraints of each (transformed) basic set.
379  * If a = n/d, then the constraint defining the new facet (in the transformed
380  * space) is
381  *
382  *                      -n x_1 + d x_2 >= 0
383  *
384  * In the original space, we need to take the same combination of the
385  * corresponding constraints "facet" and "ridge".
386  *
387  * If a = -infty = "-1/0", then we just return the original facet constraint.
388  * This means that the facet is unbounded, but has a bounded intersection
389  * with the union of sets.
390  */
391 isl_int *isl_set_wrap_facet(__isl_keep isl_set *set,
392         isl_int *facet, isl_int *ridge)
393 {
394         int i;
395         isl_ctx *ctx;
396         struct isl_mat *T = NULL;
397         struct isl_basic_set *lp = NULL;
398         struct isl_vec *obj;
399         enum isl_lp_result res;
400         isl_int num, den;
401         unsigned dim;
402
403         if (!set)
404                 return NULL;
405         ctx = set->ctx;
406         set = isl_set_copy(set);
407         set = isl_set_set_rational(set);
408
409         dim = 1 + isl_set_n_dim(set);
410         T = isl_mat_alloc(ctx, 3, dim);
411         if (!T)
412                 goto error;
413         isl_int_set_si(T->row[0][0], 1);
414         isl_seq_clr(T->row[0]+1, dim - 1);
415         isl_seq_cpy(T->row[1], facet, dim);
416         isl_seq_cpy(T->row[2], ridge, dim);
417         T = isl_mat_right_inverse(T);
418         set = isl_set_preimage(set, T);
419         T = NULL;
420         if (!set)
421                 goto error;
422         lp = wrap_constraints(set);
423         obj = isl_vec_alloc(ctx, 1 + dim*set->n);
424         if (!obj)
425                 goto error;
426         isl_int_set_si(obj->block.data[0], 0);
427         for (i = 0; i < set->n; ++i) {
428                 isl_seq_clr(obj->block.data + 1 + dim*i, 2);
429                 isl_int_set_si(obj->block.data[1 + dim*i+2], 1);
430                 isl_seq_clr(obj->block.data + 1 + dim*i+3, dim-3);
431         }
432         isl_int_init(num);
433         isl_int_init(den);
434         res = isl_basic_set_solve_lp(lp, 0,
435                             obj->block.data, ctx->one, &num, &den, NULL);
436         if (res == isl_lp_ok) {
437                 isl_int_neg(num, num);
438                 isl_seq_combine(facet, num, facet, den, ridge, dim);
439                 isl_seq_normalize(ctx, facet, dim);
440         }
441         isl_int_clear(num);
442         isl_int_clear(den);
443         isl_vec_free(obj);
444         isl_basic_set_free(lp);
445         isl_set_free(set);
446         if (res == isl_lp_error)
447                 return NULL;
448         isl_assert(ctx, res == isl_lp_ok || res == isl_lp_unbounded, 
449                    return NULL);
450         return facet;
451 error:
452         isl_basic_set_free(lp);
453         isl_mat_free(T);
454         isl_set_free(set);
455         return NULL;
456 }
457
458 /* Compute the constraint of a facet of "set".
459  *
460  * We first compute the intersection with a bounding constraint
461  * that is orthogonal to one of the coordinate axes.
462  * If the affine hull of this intersection has only one equality,
463  * we have found a facet.
464  * Otherwise, we wrap the current bounding constraint around
465  * one of the equalities of the face (one that is not equal to
466  * the current bounding constraint).
467  * This process continues until we have found a facet.
468  * The dimension of the intersection increases by at least
469  * one on each iteration, so termination is guaranteed.
470  */
471 static __isl_give isl_mat *initial_facet_constraint(__isl_keep isl_set *set)
472 {
473         struct isl_set *slice = NULL;
474         struct isl_basic_set *face = NULL;
475         int i;
476         unsigned dim = isl_set_n_dim(set);
477         int is_bound;
478         isl_mat *bounds;
479
480         isl_assert(set->ctx, set->n > 0, goto error);
481         bounds = isl_mat_alloc(set->ctx, 1, 1 + dim);
482         if (!bounds)
483                 return NULL;
484
485         isl_seq_clr(bounds->row[0], dim);
486         isl_int_set_si(bounds->row[0][1 + dim - 1], 1);
487         is_bound = uset_is_bound(set, bounds->row[0], 1 + dim);
488         if (is_bound < 0)
489                 goto error;
490         isl_assert(set->ctx, is_bound, goto error);
491         isl_seq_normalize(set->ctx, bounds->row[0], 1 + dim);
492         bounds->n_row = 1;
493
494         for (;;) {
495                 slice = isl_set_copy(set);
496                 slice = isl_set_add_basic_set_equality(slice, bounds->row[0]);
497                 face = isl_set_affine_hull(slice);
498                 if (!face)
499                         goto error;
500                 if (face->n_eq == 1) {
501                         isl_basic_set_free(face);
502                         break;
503                 }
504                 for (i = 0; i < face->n_eq; ++i)
505                         if (!isl_seq_eq(bounds->row[0], face->eq[i], 1 + dim) &&
506                             !isl_seq_is_neg(bounds->row[0],
507                                                 face->eq[i], 1 + dim))
508                                 break;
509                 isl_assert(set->ctx, i < face->n_eq, goto error);
510                 if (!isl_set_wrap_facet(set, bounds->row[0], face->eq[i]))
511                         goto error;
512                 isl_seq_normalize(set->ctx, bounds->row[0], bounds->n_col);
513                 isl_basic_set_free(face);
514         }
515
516         return bounds;
517 error:
518         isl_basic_set_free(face);
519         isl_mat_free(bounds);
520         return NULL;
521 }
522
523 /* Given the bounding constraint "c" of a facet of the convex hull of "set",
524  * compute a hyperplane description of the facet, i.e., compute the facets
525  * of the facet.
526  *
527  * We compute an affine transformation that transforms the constraint
528  *
529  *                        [ 1 ]
530  *                      c [ x ] = 0
531  *
532  * to the constraint
533  *
534  *                         z_1  = 0
535  *
536  * by computing the right inverse U of a matrix that starts with the rows
537  *
538  *                      [ 1 0 ]
539  *                      [  c  ]
540  *
541  * Then
542  *                      [ 1 ]     [ 1 ]
543  *                      [ x ] = U [ z ]
544  * and
545  *                      [ 1 ]     [ 1 ]
546  *                      [ z ] = Q [ x ]
547  *
548  * with Q = U^{-1}
549  * Since z_1 is zero, we can drop this variable as well as the corresponding
550  * column of U to obtain
551  *
552  *                      [ 1 ]      [ 1  ]
553  *                      [ x ] = U' [ z' ]
554  * and
555  *                      [ 1  ]      [ 1 ]
556  *                      [ z' ] = Q' [ x ]
557  *
558  * with Q' equal to Q, but without the corresponding row.
559  * After computing the facets of the facet in the z' space,
560  * we convert them back to the x space through Q.
561  */
562 static struct isl_basic_set *compute_facet(struct isl_set *set, isl_int *c)
563 {
564         struct isl_mat *m, *U, *Q;
565         struct isl_basic_set *facet = NULL;
566         struct isl_ctx *ctx;
567         unsigned dim;
568
569         ctx = set->ctx;
570         set = isl_set_copy(set);
571         dim = isl_set_n_dim(set);
572         m = isl_mat_alloc(set->ctx, 2, 1 + dim);
573         if (!m)
574                 goto error;
575         isl_int_set_si(m->row[0][0], 1);
576         isl_seq_clr(m->row[0]+1, dim);
577         isl_seq_cpy(m->row[1], c, 1+dim);
578         U = isl_mat_right_inverse(m);
579         Q = isl_mat_right_inverse(isl_mat_copy(U));
580         U = isl_mat_drop_cols(U, 1, 1);
581         Q = isl_mat_drop_rows(Q, 1, 1);
582         set = isl_set_preimage(set, U);
583         facet = uset_convex_hull_wrap_bounded(set);
584         facet = isl_basic_set_preimage(facet, Q);
585         if (facet)
586                 isl_assert(ctx, facet->n_eq == 0, goto error);
587         return facet;
588 error:
589         isl_basic_set_free(facet);
590         isl_set_free(set);
591         return NULL;
592 }
593
594 /* Given an initial facet constraint, compute the remaining facets.
595  * We do this by running through all facets found so far and computing
596  * the adjacent facets through wrapping, adding those facets that we
597  * hadn't already found before.
598  *
599  * For each facet we have found so far, we first compute its facets
600  * in the resulting convex hull.  That is, we compute the ridges
601  * of the resulting convex hull contained in the facet.
602  * We also compute the corresponding facet in the current approximation
603  * of the convex hull.  There is no need to wrap around the ridges
604  * in this facet since that would result in a facet that is already
605  * present in the current approximation.
606  *
607  * This function can still be significantly optimized by checking which of
608  * the facets of the basic sets are also facets of the convex hull and
609  * using all the facets so far to help in constructing the facets of the
610  * facets
611  * and/or
612  * using the technique in section "3.1 Ridge Generation" of
613  * "Extended Convex Hull" by Fukuda et al.
614  */
615 static struct isl_basic_set *extend(struct isl_basic_set *hull,
616         struct isl_set *set)
617 {
618         int i, j, f;
619         int k;
620         struct isl_basic_set *facet = NULL;
621         struct isl_basic_set *hull_facet = NULL;
622         unsigned dim;
623
624         if (!hull)
625                 return NULL;
626
627         isl_assert(set->ctx, set->n > 0, goto error);
628
629         dim = isl_set_n_dim(set);
630
631         for (i = 0; i < hull->n_ineq; ++i) {
632                 facet = compute_facet(set, hull->ineq[i]);
633                 facet = isl_basic_set_add_equality(facet, hull->ineq[i]);
634                 facet = isl_basic_set_gauss(facet, NULL);
635                 facet = isl_basic_set_normalize_constraints(facet);
636                 hull_facet = isl_basic_set_copy(hull);
637                 hull_facet = isl_basic_set_add_equality(hull_facet, hull->ineq[i]);
638                 hull_facet = isl_basic_set_gauss(hull_facet, NULL);
639                 hull_facet = isl_basic_set_normalize_constraints(hull_facet);
640                 if (!facet || !hull_facet)
641                         goto error;
642                 hull = isl_basic_set_cow(hull);
643                 hull = isl_basic_set_extend_dim(hull,
644                         isl_dim_copy(hull->dim), 0, 0, facet->n_ineq);
645                 if (!hull)
646                         goto error;
647                 for (j = 0; j < facet->n_ineq; ++j) {
648                         for (f = 0; f < hull_facet->n_ineq; ++f)
649                                 if (isl_seq_eq(facet->ineq[j],
650                                                 hull_facet->ineq[f], 1 + dim))
651                                         break;
652                         if (f < hull_facet->n_ineq)
653                                 continue;
654                         k = isl_basic_set_alloc_inequality(hull);
655                         if (k < 0)
656                                 goto error;
657                         isl_seq_cpy(hull->ineq[k], hull->ineq[i], 1+dim);
658                         if (!isl_set_wrap_facet(set, hull->ineq[k], facet->ineq[j]))
659                                 goto error;
660                 }
661                 isl_basic_set_free(hull_facet);
662                 isl_basic_set_free(facet);
663         }
664         hull = isl_basic_set_simplify(hull);
665         hull = isl_basic_set_finalize(hull);
666         return hull;
667 error:
668         isl_basic_set_free(hull_facet);
669         isl_basic_set_free(facet);
670         isl_basic_set_free(hull);
671         return NULL;
672 }
673
674 /* Special case for computing the convex hull of a one dimensional set.
675  * We simply collect the lower and upper bounds of each basic set
676  * and the biggest of those.
677  */
678 static struct isl_basic_set *convex_hull_1d(struct isl_set *set)
679 {
680         struct isl_mat *c = NULL;
681         isl_int *lower = NULL;
682         isl_int *upper = NULL;
683         int i, j, k;
684         isl_int a, b;
685         struct isl_basic_set *hull;
686
687         for (i = 0; i < set->n; ++i) {
688                 set->p[i] = isl_basic_set_simplify(set->p[i]);
689                 if (!set->p[i])
690                         goto error;
691         }
692         set = isl_set_remove_empty_parts(set);
693         if (!set)
694                 goto error;
695         isl_assert(set->ctx, set->n > 0, goto error);
696         c = isl_mat_alloc(set->ctx, 2, 2);
697         if (!c)
698                 goto error;
699
700         if (set->p[0]->n_eq > 0) {
701                 isl_assert(set->ctx, set->p[0]->n_eq == 1, goto error);
702                 lower = c->row[0];
703                 upper = c->row[1];
704                 if (isl_int_is_pos(set->p[0]->eq[0][1])) {
705                         isl_seq_cpy(lower, set->p[0]->eq[0], 2);
706                         isl_seq_neg(upper, set->p[0]->eq[0], 2);
707                 } else {
708                         isl_seq_neg(lower, set->p[0]->eq[0], 2);
709                         isl_seq_cpy(upper, set->p[0]->eq[0], 2);
710                 }
711         } else {
712                 for (j = 0; j < set->p[0]->n_ineq; ++j) {
713                         if (isl_int_is_pos(set->p[0]->ineq[j][1])) {
714                                 lower = c->row[0];
715                                 isl_seq_cpy(lower, set->p[0]->ineq[j], 2);
716                         } else {
717                                 upper = c->row[1];
718                                 isl_seq_cpy(upper, set->p[0]->ineq[j], 2);
719                         }
720                 }
721         }
722
723         isl_int_init(a);
724         isl_int_init(b);
725         for (i = 0; i < set->n; ++i) {
726                 struct isl_basic_set *bset = set->p[i];
727                 int has_lower = 0;
728                 int has_upper = 0;
729
730                 for (j = 0; j < bset->n_eq; ++j) {
731                         has_lower = 1;
732                         has_upper = 1;
733                         if (lower) {
734                                 isl_int_mul(a, lower[0], bset->eq[j][1]);
735                                 isl_int_mul(b, lower[1], bset->eq[j][0]);
736                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
737                                         isl_seq_cpy(lower, bset->eq[j], 2);
738                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
739                                         isl_seq_neg(lower, bset->eq[j], 2);
740                         }
741                         if (upper) {
742                                 isl_int_mul(a, upper[0], bset->eq[j][1]);
743                                 isl_int_mul(b, upper[1], bset->eq[j][0]);
744                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
745                                         isl_seq_neg(upper, bset->eq[j], 2);
746                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
747                                         isl_seq_cpy(upper, bset->eq[j], 2);
748                         }
749                 }
750                 for (j = 0; j < bset->n_ineq; ++j) {
751                         if (isl_int_is_pos(bset->ineq[j][1]))
752                                 has_lower = 1;
753                         if (isl_int_is_neg(bset->ineq[j][1]))
754                                 has_upper = 1;
755                         if (lower && isl_int_is_pos(bset->ineq[j][1])) {
756                                 isl_int_mul(a, lower[0], bset->ineq[j][1]);
757                                 isl_int_mul(b, lower[1], bset->ineq[j][0]);
758                                 if (isl_int_lt(a, b))
759                                         isl_seq_cpy(lower, bset->ineq[j], 2);
760                         }
761                         if (upper && isl_int_is_neg(bset->ineq[j][1])) {
762                                 isl_int_mul(a, upper[0], bset->ineq[j][1]);
763                                 isl_int_mul(b, upper[1], bset->ineq[j][0]);
764                                 if (isl_int_gt(a, b))
765                                         isl_seq_cpy(upper, bset->ineq[j], 2);
766                         }
767                 }
768                 if (!has_lower)
769                         lower = NULL;
770                 if (!has_upper)
771                         upper = NULL;
772         }
773         isl_int_clear(a);
774         isl_int_clear(b);
775
776         hull = isl_basic_set_alloc(set->ctx, 0, 1, 0, 0, 2);
777         hull = isl_basic_set_set_rational(hull);
778         if (!hull)
779                 goto error;
780         if (lower) {
781                 k = isl_basic_set_alloc_inequality(hull);
782                 isl_seq_cpy(hull->ineq[k], lower, 2);
783         }
784         if (upper) {
785                 k = isl_basic_set_alloc_inequality(hull);
786                 isl_seq_cpy(hull->ineq[k], upper, 2);
787         }
788         hull = isl_basic_set_finalize(hull);
789         isl_set_free(set);
790         isl_mat_free(c);
791         return hull;
792 error:
793         isl_set_free(set);
794         isl_mat_free(c);
795         return NULL;
796 }
797
798 /* Project out final n dimensions using Fourier-Motzkin */
799 static struct isl_set *set_project_out(struct isl_ctx *ctx,
800         struct isl_set *set, unsigned n)
801 {
802         return isl_set_remove_dims(set, isl_dim_set, isl_set_n_dim(set) - n, n);
803 }
804
805 static struct isl_basic_set *convex_hull_0d(struct isl_set *set)
806 {
807         struct isl_basic_set *convex_hull;
808
809         if (!set)
810                 return NULL;
811
812         if (isl_set_is_empty(set))
813                 convex_hull = isl_basic_set_empty(isl_dim_copy(set->dim));
814         else
815                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
816         isl_set_free(set);
817         return convex_hull;
818 }
819
820 /* Compute the convex hull of a pair of basic sets without any parameters or
821  * integer divisions using Fourier-Motzkin elimination.
822  * The convex hull is the set of all points that can be written as
823  * the sum of points from both basic sets (in homogeneous coordinates).
824  * We set up the constraints in a space with dimensions for each of
825  * the three sets and then project out the dimensions corresponding
826  * to the two original basic sets, retaining only those corresponding
827  * to the convex hull.
828  */
829 static struct isl_basic_set *convex_hull_pair_elim(struct isl_basic_set *bset1,
830         struct isl_basic_set *bset2)
831 {
832         int i, j, k;
833         struct isl_basic_set *bset[2];
834         struct isl_basic_set *hull = NULL;
835         unsigned dim;
836
837         if (!bset1 || !bset2)
838                 goto error;
839
840         dim = isl_basic_set_n_dim(bset1);
841         hull = isl_basic_set_alloc(bset1->ctx, 0, 2 + 3 * dim, 0,
842                                 1 + dim + bset1->n_eq + bset2->n_eq,
843                                 2 + bset1->n_ineq + bset2->n_ineq);
844         bset[0] = bset1;
845         bset[1] = bset2;
846         for (i = 0; i < 2; ++i) {
847                 for (j = 0; j < bset[i]->n_eq; ++j) {
848                         k = isl_basic_set_alloc_equality(hull);
849                         if (k < 0)
850                                 goto error;
851                         isl_seq_clr(hull->eq[k], (i+1) * (1+dim));
852                         isl_seq_clr(hull->eq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
853                         isl_seq_cpy(hull->eq[k]+(i+1)*(1+dim), bset[i]->eq[j],
854                                         1+dim);
855                 }
856                 for (j = 0; j < bset[i]->n_ineq; ++j) {
857                         k = isl_basic_set_alloc_inequality(hull);
858                         if (k < 0)
859                                 goto error;
860                         isl_seq_clr(hull->ineq[k], (i+1) * (1+dim));
861                         isl_seq_clr(hull->ineq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
862                         isl_seq_cpy(hull->ineq[k]+(i+1)*(1+dim),
863                                         bset[i]->ineq[j], 1+dim);
864                 }
865                 k = isl_basic_set_alloc_inequality(hull);
866                 if (k < 0)
867                         goto error;
868                 isl_seq_clr(hull->ineq[k], 1+2+3*dim);
869                 isl_int_set_si(hull->ineq[k][(i+1)*(1+dim)], 1);
870         }
871         for (j = 0; j < 1+dim; ++j) {
872                 k = isl_basic_set_alloc_equality(hull);
873                 if (k < 0)
874                         goto error;
875                 isl_seq_clr(hull->eq[k], 1+2+3*dim);
876                 isl_int_set_si(hull->eq[k][j], -1);
877                 isl_int_set_si(hull->eq[k][1+dim+j], 1);
878                 isl_int_set_si(hull->eq[k][2*(1+dim)+j], 1);
879         }
880         hull = isl_basic_set_set_rational(hull);
881         hull = isl_basic_set_remove_dims(hull, isl_dim_set, dim, 2*(1+dim));
882         hull = isl_basic_set_remove_redundancies(hull);
883         isl_basic_set_free(bset1);
884         isl_basic_set_free(bset2);
885         return hull;
886 error:
887         isl_basic_set_free(bset1);
888         isl_basic_set_free(bset2);
889         isl_basic_set_free(hull);
890         return NULL;
891 }
892
893 /* Is the set bounded for each value of the parameters?
894  */
895 int isl_basic_set_is_bounded(__isl_keep isl_basic_set *bset)
896 {
897         struct isl_tab *tab;
898         int bounded;
899
900         if (!bset)
901                 return -1;
902         if (isl_basic_set_fast_is_empty(bset))
903                 return 1;
904
905         tab = isl_tab_from_recession_cone(bset, 1);
906         bounded = isl_tab_cone_is_bounded(tab);
907         isl_tab_free(tab);
908         return bounded;
909 }
910
911 /* Is the image bounded for each value of the parameters and
912  * the domain variables?
913  */
914 int isl_basic_map_image_is_bounded(__isl_keep isl_basic_map *bmap)
915 {
916         unsigned nparam = isl_basic_map_dim(bmap, isl_dim_param);
917         unsigned n_in = isl_basic_map_dim(bmap, isl_dim_in);
918         int bounded;
919
920         bmap = isl_basic_map_copy(bmap);
921         bmap = isl_basic_map_cow(bmap);
922         bmap = isl_basic_map_move_dims(bmap, isl_dim_param, nparam,
923                                         isl_dim_in, 0, n_in);
924         bounded = isl_basic_set_is_bounded((isl_basic_set *)bmap);
925         isl_basic_map_free(bmap);
926
927         return bounded;
928 }
929
930 /* Is the set bounded for each value of the parameters?
931  */
932 int isl_set_is_bounded(__isl_keep isl_set *set)
933 {
934         int i;
935
936         if (!set)
937                 return -1;
938
939         for (i = 0; i < set->n; ++i) {
940                 int bounded = isl_basic_set_is_bounded(set->p[i]);
941                 if (!bounded || bounded < 0)
942                         return bounded;
943         }
944         return 1;
945 }
946
947 /* Compute the lineality space of the convex hull of bset1 and bset2.
948  *
949  * We first compute the intersection of the recession cone of bset1
950  * with the negative of the recession cone of bset2 and then compute
951  * the linear hull of the resulting cone.
952  */
953 static struct isl_basic_set *induced_lineality_space(
954         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
955 {
956         int i, k;
957         struct isl_basic_set *lin = NULL;
958         unsigned dim;
959
960         if (!bset1 || !bset2)
961                 goto error;
962
963         dim = isl_basic_set_total_dim(bset1);
964         lin = isl_basic_set_alloc_dim(isl_basic_set_get_dim(bset1), 0,
965                                         bset1->n_eq + bset2->n_eq,
966                                         bset1->n_ineq + bset2->n_ineq);
967         lin = isl_basic_set_set_rational(lin);
968         if (!lin)
969                 goto error;
970         for (i = 0; i < bset1->n_eq; ++i) {
971                 k = isl_basic_set_alloc_equality(lin);
972                 if (k < 0)
973                         goto error;
974                 isl_int_set_si(lin->eq[k][0], 0);
975                 isl_seq_cpy(lin->eq[k] + 1, bset1->eq[i] + 1, dim);
976         }
977         for (i = 0; i < bset1->n_ineq; ++i) {
978                 k = isl_basic_set_alloc_inequality(lin);
979                 if (k < 0)
980                         goto error;
981                 isl_int_set_si(lin->ineq[k][0], 0);
982                 isl_seq_cpy(lin->ineq[k] + 1, bset1->ineq[i] + 1, dim);
983         }
984         for (i = 0; i < bset2->n_eq; ++i) {
985                 k = isl_basic_set_alloc_equality(lin);
986                 if (k < 0)
987                         goto error;
988                 isl_int_set_si(lin->eq[k][0], 0);
989                 isl_seq_neg(lin->eq[k] + 1, bset2->eq[i] + 1, dim);
990         }
991         for (i = 0; i < bset2->n_ineq; ++i) {
992                 k = isl_basic_set_alloc_inequality(lin);
993                 if (k < 0)
994                         goto error;
995                 isl_int_set_si(lin->ineq[k][0], 0);
996                 isl_seq_neg(lin->ineq[k] + 1, bset2->ineq[i] + 1, dim);
997         }
998
999         isl_basic_set_free(bset1);
1000         isl_basic_set_free(bset2);
1001         return isl_basic_set_affine_hull(lin);
1002 error:
1003         isl_basic_set_free(lin);
1004         isl_basic_set_free(bset1);
1005         isl_basic_set_free(bset2);
1006         return NULL;
1007 }
1008
1009 static struct isl_basic_set *uset_convex_hull(struct isl_set *set);
1010
1011 /* Given a set and a linear space "lin" of dimension n > 0,
1012  * project the linear space from the set, compute the convex hull
1013  * and then map the set back to the original space.
1014  *
1015  * Let
1016  *
1017  *      M x = 0
1018  *
1019  * describe the linear space.  We first compute the Hermite normal
1020  * form H = M U of M = H Q, to obtain
1021  *
1022  *      H Q x = 0
1023  *
1024  * The last n rows of H will be zero, so the last n variables of x' = Q x
1025  * are the one we want to project out.  We do this by transforming each
1026  * basic set A x >= b to A U x' >= b and then removing the last n dimensions.
1027  * After computing the convex hull in x'_1, i.e., A' x'_1 >= b',
1028  * we transform the hull back to the original space as A' Q_1 x >= b',
1029  * with Q_1 all but the last n rows of Q.
1030  */
1031 static struct isl_basic_set *modulo_lineality(struct isl_set *set,
1032         struct isl_basic_set *lin)
1033 {
1034         unsigned total = isl_basic_set_total_dim(lin);
1035         unsigned lin_dim;
1036         struct isl_basic_set *hull;
1037         struct isl_mat *M, *U, *Q;
1038
1039         if (!set || !lin)
1040                 goto error;
1041         lin_dim = total - lin->n_eq;
1042         M = isl_mat_sub_alloc6(set->ctx, lin->eq, 0, lin->n_eq, 1, total);
1043         M = isl_mat_left_hermite(M, 0, &U, &Q);
1044         if (!M)
1045                 goto error;
1046         isl_mat_free(M);
1047         isl_basic_set_free(lin);
1048
1049         Q = isl_mat_drop_rows(Q, Q->n_row - lin_dim, lin_dim);
1050
1051         U = isl_mat_lin_to_aff(U);
1052         Q = isl_mat_lin_to_aff(Q);
1053
1054         set = isl_set_preimage(set, U);
1055         set = isl_set_remove_dims(set, isl_dim_set, total - lin_dim, lin_dim);
1056         hull = uset_convex_hull(set);
1057         hull = isl_basic_set_preimage(hull, Q);
1058
1059         return hull;
1060 error:
1061         isl_basic_set_free(lin);
1062         isl_set_free(set);
1063         return NULL;
1064 }
1065
1066 /* Given two polyhedra with as constraints h_{ij} x >= 0 in homegeneous space,
1067  * set up an LP for solving
1068  *
1069  *      \sum_j \alpha_{1j} h_{1j} = \sum_j \alpha_{2j} h_{2j}
1070  *
1071  * \alpha{i0} corresponds to the (implicit) positivity constraint 1 >= 0
1072  * The next \alpha{ij} correspond to the equalities and come in pairs.
1073  * The final \alpha{ij} correspond to the inequalities.
1074  */
1075 static struct isl_basic_set *valid_direction_lp(
1076         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1077 {
1078         struct isl_dim *dim;
1079         struct isl_basic_set *lp;
1080         unsigned d;
1081         int n;
1082         int i, j, k;
1083
1084         if (!bset1 || !bset2)
1085                 goto error;
1086         d = 1 + isl_basic_set_total_dim(bset1);
1087         n = 2 +
1088             2 * bset1->n_eq + bset1->n_ineq + 2 * bset2->n_eq + bset2->n_ineq;
1089         dim = isl_dim_set_alloc(bset1->ctx, 0, n);
1090         lp = isl_basic_set_alloc_dim(dim, 0, d, n);
1091         if (!lp)
1092                 goto error;
1093         for (i = 0; i < n; ++i) {
1094                 k = isl_basic_set_alloc_inequality(lp);
1095                 if (k < 0)
1096                         goto error;
1097                 isl_seq_clr(lp->ineq[k] + 1, n);
1098                 isl_int_set_si(lp->ineq[k][0], -1);
1099                 isl_int_set_si(lp->ineq[k][1 + i], 1);
1100         }
1101         for (i = 0; i < d; ++i) {
1102                 k = isl_basic_set_alloc_equality(lp);
1103                 if (k < 0)
1104                         goto error;
1105                 n = 0;
1106                 isl_int_set_si(lp->eq[k][n], 0); n++;
1107                 /* positivity constraint 1 >= 0 */
1108                 isl_int_set_si(lp->eq[k][n], i == 0); n++;
1109                 for (j = 0; j < bset1->n_eq; ++j) {
1110                         isl_int_set(lp->eq[k][n], bset1->eq[j][i]); n++;
1111                         isl_int_neg(lp->eq[k][n], bset1->eq[j][i]); n++;
1112                 }
1113                 for (j = 0; j < bset1->n_ineq; ++j) {
1114                         isl_int_set(lp->eq[k][n], bset1->ineq[j][i]); n++;
1115                 }
1116                 /* positivity constraint 1 >= 0 */
1117                 isl_int_set_si(lp->eq[k][n], -(i == 0)); n++;
1118                 for (j = 0; j < bset2->n_eq; ++j) {
1119                         isl_int_neg(lp->eq[k][n], bset2->eq[j][i]); n++;
1120                         isl_int_set(lp->eq[k][n], bset2->eq[j][i]); n++;
1121                 }
1122                 for (j = 0; j < bset2->n_ineq; ++j) {
1123                         isl_int_neg(lp->eq[k][n], bset2->ineq[j][i]); n++;
1124                 }
1125         }
1126         lp = isl_basic_set_gauss(lp, NULL);
1127         isl_basic_set_free(bset1);
1128         isl_basic_set_free(bset2);
1129         return lp;
1130 error:
1131         isl_basic_set_free(bset1);
1132         isl_basic_set_free(bset2);
1133         return NULL;
1134 }
1135
1136 /* Compute a vector s in the homogeneous space such that <s, r> > 0
1137  * for all rays in the homogeneous space of the two cones that correspond
1138  * to the input polyhedra bset1 and bset2.
1139  *
1140  * We compute s as a vector that satisfies
1141  *
1142  *      s = \sum_j \alpha_{ij} h_{ij}   for i = 1,2                     (*)
1143  *
1144  * with h_{ij} the normals of the facets of polyhedron i
1145  * (including the "positivity constraint" 1 >= 0) and \alpha_{ij}
1146  * strictly positive numbers.  For simplicity we impose \alpha_{ij} >= 1.
1147  * We first set up an LP with as variables the \alpha{ij}.
1148  * In this formulation, for each polyhedron i,
1149  * the first constraint is the positivity constraint, followed by pairs
1150  * of variables for the equalities, followed by variables for the inequalities.
1151  * We then simply pick a feasible solution and compute s using (*).
1152  *
1153  * Note that we simply pick any valid direction and make no attempt
1154  * to pick a "good" or even the "best" valid direction.
1155  */
1156 static struct isl_vec *valid_direction(
1157         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1158 {
1159         struct isl_basic_set *lp;
1160         struct isl_tab *tab;
1161         struct isl_vec *sample = NULL;
1162         struct isl_vec *dir;
1163         unsigned d;
1164         int i;
1165         int n;
1166
1167         if (!bset1 || !bset2)
1168                 goto error;
1169         lp = valid_direction_lp(isl_basic_set_copy(bset1),
1170                                 isl_basic_set_copy(bset2));
1171         tab = isl_tab_from_basic_set(lp);
1172         sample = isl_tab_get_sample_value(tab);
1173         isl_tab_free(tab);
1174         isl_basic_set_free(lp);
1175         if (!sample)
1176                 goto error;
1177         d = isl_basic_set_total_dim(bset1);
1178         dir = isl_vec_alloc(bset1->ctx, 1 + d);
1179         if (!dir)
1180                 goto error;
1181         isl_seq_clr(dir->block.data + 1, dir->size - 1);
1182         n = 1;
1183         /* positivity constraint 1 >= 0 */
1184         isl_int_set(dir->block.data[0], sample->block.data[n]); n++;
1185         for (i = 0; i < bset1->n_eq; ++i) {
1186                 isl_int_sub(sample->block.data[n],
1187                             sample->block.data[n], sample->block.data[n+1]);
1188                 isl_seq_combine(dir->block.data,
1189                                 bset1->ctx->one, dir->block.data,
1190                                 sample->block.data[n], bset1->eq[i], 1 + d);
1191
1192                 n += 2;
1193         }
1194         for (i = 0; i < bset1->n_ineq; ++i)
1195                 isl_seq_combine(dir->block.data,
1196                                 bset1->ctx->one, dir->block.data,
1197                                 sample->block.data[n++], bset1->ineq[i], 1 + d);
1198         isl_vec_free(sample);
1199         isl_seq_normalize(bset1->ctx, dir->el, dir->size);
1200         isl_basic_set_free(bset1);
1201         isl_basic_set_free(bset2);
1202         return dir;
1203 error:
1204         isl_vec_free(sample);
1205         isl_basic_set_free(bset1);
1206         isl_basic_set_free(bset2);
1207         return NULL;
1208 }
1209
1210 /* Given a polyhedron b_i + A_i x >= 0 and a map T = S^{-1},
1211  * compute b_i' + A_i' x' >= 0, with
1212  *
1213  *      [ b_i A_i ]        [ y' ]                             [ y' ]
1214  *      [  1   0  ] S^{-1} [ x' ] >= 0  or      [ b_i' A_i' ] [ x' ] >= 0
1215  *
1216  * In particular, add the "positivity constraint" and then perform
1217  * the mapping.
1218  */
1219 static struct isl_basic_set *homogeneous_map(struct isl_basic_set *bset,
1220         struct isl_mat *T)
1221 {
1222         int k;
1223
1224         if (!bset)
1225                 goto error;
1226         bset = isl_basic_set_extend_constraints(bset, 0, 1);
1227         k = isl_basic_set_alloc_inequality(bset);
1228         if (k < 0)
1229                 goto error;
1230         isl_seq_clr(bset->ineq[k] + 1, isl_basic_set_total_dim(bset));
1231         isl_int_set_si(bset->ineq[k][0], 1);
1232         bset = isl_basic_set_preimage(bset, T);
1233         return bset;
1234 error:
1235         isl_mat_free(T);
1236         isl_basic_set_free(bset);
1237         return NULL;
1238 }
1239
1240 /* Compute the convex hull of a pair of basic sets without any parameters or
1241  * integer divisions, where the convex hull is known to be pointed,
1242  * but the basic sets may be unbounded.
1243  *
1244  * We turn this problem into the computation of a convex hull of a pair
1245  * _bounded_ polyhedra by "changing the direction of the homogeneous
1246  * dimension".  This idea is due to Matthias Koeppe.
1247  *
1248  * Consider the cones in homogeneous space that correspond to the
1249  * input polyhedra.  The rays of these cones are also rays of the
1250  * polyhedra if the coordinate that corresponds to the homogeneous
1251  * dimension is zero.  That is, if the inner product of the rays
1252  * with the homogeneous direction is zero.
1253  * The cones in the homogeneous space can also be considered to
1254  * correspond to other pairs of polyhedra by chosing a different
1255  * homogeneous direction.  To ensure that both of these polyhedra
1256  * are bounded, we need to make sure that all rays of the cones
1257  * correspond to vertices and not to rays.
1258  * Let s be a direction such that <s, r> > 0 for all rays r of both cones.
1259  * Then using s as a homogeneous direction, we obtain a pair of polytopes.
1260  * The vector s is computed in valid_direction.
1261  *
1262  * Note that we need to consider _all_ rays of the cones and not just
1263  * the rays that correspond to rays in the polyhedra.  If we were to
1264  * only consider those rays and turn them into vertices, then we
1265  * may inadvertently turn some vertices into rays.
1266  *
1267  * The standard homogeneous direction is the unit vector in the 0th coordinate.
1268  * We therefore transform the two polyhedra such that the selected
1269  * direction is mapped onto this standard direction and then proceed
1270  * with the normal computation.
1271  * Let S be a non-singular square matrix with s as its first row,
1272  * then we want to map the polyhedra to the space
1273  *
1274  *      [ y' ]     [ y ]                [ y ]          [ y' ]
1275  *      [ x' ] = S [ x ]        i.e.,   [ x ] = S^{-1} [ x' ]
1276  *
1277  * We take S to be the unimodular completion of s to limit the growth
1278  * of the coefficients in the following computations.
1279  *
1280  * Let b_i + A_i x >= 0 be the constraints of polyhedron i.
1281  * We first move to the homogeneous dimension
1282  *
1283  *      b_i y + A_i x >= 0              [ b_i A_i ] [ y ]    [ 0 ]
1284  *          y         >= 0      or      [  1   0  ] [ x ] >= [ 0 ]
1285  *
1286  * Then we change directoin
1287  *
1288  *      [ b_i A_i ]        [ y' ]                             [ y' ]
1289  *      [  1   0  ] S^{-1} [ x' ] >= 0  or      [ b_i' A_i' ] [ x' ] >= 0
1290  *
1291  * Then we compute the convex hull of the polytopes b_i' + A_i' x' >= 0
1292  * resulting in b' + A' x' >= 0, which we then convert back
1293  *
1294  *                  [ y ]                       [ y ]
1295  *      [ b' A' ] S [ x ] >= 0  or      [ b A ] [ x ] >= 0
1296  *
1297  * The polyhedron b + A x >= 0 is then the convex hull of the input polyhedra.
1298  */
1299 static struct isl_basic_set *convex_hull_pair_pointed(
1300         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1301 {
1302         struct isl_ctx *ctx = NULL;
1303         struct isl_vec *dir = NULL;
1304         struct isl_mat *T = NULL;
1305         struct isl_mat *T2 = NULL;
1306         struct isl_basic_set *hull;
1307         struct isl_set *set;
1308
1309         if (!bset1 || !bset2)
1310                 goto error;
1311         ctx = bset1->ctx;
1312         dir = valid_direction(isl_basic_set_copy(bset1),
1313                                 isl_basic_set_copy(bset2));
1314         if (!dir)
1315                 goto error;
1316         T = isl_mat_alloc(bset1->ctx, dir->size, dir->size);
1317         if (!T)
1318                 goto error;
1319         isl_seq_cpy(T->row[0], dir->block.data, dir->size);
1320         T = isl_mat_unimodular_complete(T, 1);
1321         T2 = isl_mat_right_inverse(isl_mat_copy(T));
1322
1323         bset1 = homogeneous_map(bset1, isl_mat_copy(T2));
1324         bset2 = homogeneous_map(bset2, T2);
1325         set = isl_set_alloc_dim(isl_basic_set_get_dim(bset1), 2, 0);
1326         set = isl_set_add_basic_set(set, bset1);
1327         set = isl_set_add_basic_set(set, bset2);
1328         hull = uset_convex_hull(set);
1329         hull = isl_basic_set_preimage(hull, T);
1330          
1331         isl_vec_free(dir);
1332
1333         return hull;
1334 error:
1335         isl_vec_free(dir);
1336         isl_basic_set_free(bset1);
1337         isl_basic_set_free(bset2);
1338         return NULL;
1339 }
1340
1341 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set);
1342 static struct isl_basic_set *modulo_affine_hull(
1343         struct isl_set *set, struct isl_basic_set *affine_hull);
1344
1345 /* Compute the convex hull of a pair of basic sets without any parameters or
1346  * integer divisions.
1347  *
1348  * This function is called from uset_convex_hull_unbounded, which
1349  * means that the complete convex hull is unbounded.  Some pairs
1350  * of basic sets may still be bounded, though.
1351  * They may even lie inside a lower dimensional space, in which
1352  * case they need to be handled inside their affine hull since
1353  * the main algorithm assumes that the result is full-dimensional.
1354  *
1355  * If the convex hull of the two basic sets would have a non-trivial
1356  * lineality space, we first project out this lineality space.
1357  */
1358 static struct isl_basic_set *convex_hull_pair(struct isl_basic_set *bset1,
1359         struct isl_basic_set *bset2)
1360 {
1361         isl_basic_set *lin, *aff;
1362         int bounded1, bounded2;
1363
1364         if (bset1->ctx->opt->convex == ISL_CONVEX_HULL_FM)
1365                 return convex_hull_pair_elim(bset1, bset2);
1366
1367         aff = isl_set_affine_hull(isl_basic_set_union(isl_basic_set_copy(bset1),
1368                                                     isl_basic_set_copy(bset2)));
1369         if (!aff)
1370                 goto error;
1371         if (aff->n_eq != 0) 
1372                 return modulo_affine_hull(isl_basic_set_union(bset1, bset2), aff);
1373         isl_basic_set_free(aff);
1374
1375         bounded1 = isl_basic_set_is_bounded(bset1);
1376         bounded2 = isl_basic_set_is_bounded(bset2);
1377
1378         if (bounded1 < 0 || bounded2 < 0)
1379                 goto error;
1380
1381         if (bounded1 && bounded2)
1382                 uset_convex_hull_wrap(isl_basic_set_union(bset1, bset2));
1383
1384         if (bounded1 || bounded2)
1385                 return convex_hull_pair_pointed(bset1, bset2);
1386
1387         lin = induced_lineality_space(isl_basic_set_copy(bset1),
1388                                       isl_basic_set_copy(bset2));
1389         if (!lin)
1390                 goto error;
1391         if (isl_basic_set_is_universe(lin)) {
1392                 isl_basic_set_free(bset1);
1393                 isl_basic_set_free(bset2);
1394                 return lin;
1395         }
1396         if (lin->n_eq < isl_basic_set_total_dim(lin)) {
1397                 struct isl_set *set;
1398                 set = isl_set_alloc_dim(isl_basic_set_get_dim(bset1), 2, 0);
1399                 set = isl_set_add_basic_set(set, bset1);
1400                 set = isl_set_add_basic_set(set, bset2);
1401                 return modulo_lineality(set, lin);
1402         }
1403         isl_basic_set_free(lin);
1404
1405         return convex_hull_pair_pointed(bset1, bset2);
1406 error:
1407         isl_basic_set_free(bset1);
1408         isl_basic_set_free(bset2);
1409         return NULL;
1410 }
1411
1412 /* Compute the lineality space of a basic set.
1413  * We currently do not allow the basic set to have any divs.
1414  * We basically just drop the constants and turn every inequality
1415  * into an equality.
1416  */
1417 struct isl_basic_set *isl_basic_set_lineality_space(struct isl_basic_set *bset)
1418 {
1419         int i, k;
1420         struct isl_basic_set *lin = NULL;
1421         unsigned dim;
1422
1423         if (!bset)
1424                 goto error;
1425         isl_assert(bset->ctx, bset->n_div == 0, goto error);
1426         dim = isl_basic_set_total_dim(bset);
1427
1428         lin = isl_basic_set_alloc_dim(isl_basic_set_get_dim(bset), 0, dim, 0);
1429         if (!lin)
1430                 goto error;
1431         for (i = 0; i < bset->n_eq; ++i) {
1432                 k = isl_basic_set_alloc_equality(lin);
1433                 if (k < 0)
1434                         goto error;
1435                 isl_int_set_si(lin->eq[k][0], 0);
1436                 isl_seq_cpy(lin->eq[k] + 1, bset->eq[i] + 1, dim);
1437         }
1438         lin = isl_basic_set_gauss(lin, NULL);
1439         if (!lin)
1440                 goto error;
1441         for (i = 0; i < bset->n_ineq && lin->n_eq < dim; ++i) {
1442                 k = isl_basic_set_alloc_equality(lin);
1443                 if (k < 0)
1444                         goto error;
1445                 isl_int_set_si(lin->eq[k][0], 0);
1446                 isl_seq_cpy(lin->eq[k] + 1, bset->ineq[i] + 1, dim);
1447                 lin = isl_basic_set_gauss(lin, NULL);
1448                 if (!lin)
1449                         goto error;
1450         }
1451         isl_basic_set_free(bset);
1452         return lin;
1453 error:
1454         isl_basic_set_free(lin);
1455         isl_basic_set_free(bset);
1456         return NULL;
1457 }
1458
1459 /* Compute the (linear) hull of the lineality spaces of the basic sets in the
1460  * "underlying" set "set".
1461  */
1462 static struct isl_basic_set *uset_combined_lineality_space(struct isl_set *set)
1463 {
1464         int i;
1465         struct isl_set *lin = NULL;
1466
1467         if (!set)
1468                 return NULL;
1469         if (set->n == 0) {
1470                 struct isl_dim *dim = isl_set_get_dim(set);
1471                 isl_set_free(set);
1472                 return isl_basic_set_empty(dim);
1473         }
1474
1475         lin = isl_set_alloc_dim(isl_set_get_dim(set), set->n, 0);
1476         for (i = 0; i < set->n; ++i)
1477                 lin = isl_set_add_basic_set(lin,
1478                     isl_basic_set_lineality_space(isl_basic_set_copy(set->p[i])));
1479         isl_set_free(set);
1480         return isl_set_affine_hull(lin);
1481 }
1482
1483 /* Compute the convex hull of a set without any parameters or
1484  * integer divisions.
1485  * In each step, we combined two basic sets until only one
1486  * basic set is left.
1487  * The input basic sets are assumed not to have a non-trivial
1488  * lineality space.  If any of the intermediate results has
1489  * a non-trivial lineality space, it is projected out.
1490  */
1491 static struct isl_basic_set *uset_convex_hull_unbounded(struct isl_set *set)
1492 {
1493         struct isl_basic_set *convex_hull = NULL;
1494
1495         convex_hull = isl_set_copy_basic_set(set);
1496         set = isl_set_drop_basic_set(set, convex_hull);
1497         if (!set)
1498                 goto error;
1499         while (set->n > 0) {
1500                 struct isl_basic_set *t;
1501                 t = isl_set_copy_basic_set(set);
1502                 if (!t)
1503                         goto error;
1504                 set = isl_set_drop_basic_set(set, t);
1505                 if (!set)
1506                         goto error;
1507                 convex_hull = convex_hull_pair(convex_hull, t);
1508                 if (set->n == 0)
1509                         break;
1510                 t = isl_basic_set_lineality_space(isl_basic_set_copy(convex_hull));
1511                 if (!t)
1512                         goto error;
1513                 if (isl_basic_set_is_universe(t)) {
1514                         isl_basic_set_free(convex_hull);
1515                         convex_hull = t;
1516                         break;
1517                 }
1518                 if (t->n_eq < isl_basic_set_total_dim(t)) {
1519                         set = isl_set_add_basic_set(set, convex_hull);
1520                         return modulo_lineality(set, t);
1521                 }
1522                 isl_basic_set_free(t);
1523         }
1524         isl_set_free(set);
1525         return convex_hull;
1526 error:
1527         isl_set_free(set);
1528         isl_basic_set_free(convex_hull);
1529         return NULL;
1530 }
1531
1532 /* Compute an initial hull for wrapping containing a single initial
1533  * facet.
1534  * This function assumes that the given set is bounded.
1535  */
1536 static struct isl_basic_set *initial_hull(struct isl_basic_set *hull,
1537         struct isl_set *set)
1538 {
1539         struct isl_mat *bounds = NULL;
1540         unsigned dim;
1541         int k;
1542
1543         if (!hull)
1544                 goto error;
1545         bounds = initial_facet_constraint(set);
1546         if (!bounds)
1547                 goto error;
1548         k = isl_basic_set_alloc_inequality(hull);
1549         if (k < 0)
1550                 goto error;
1551         dim = isl_set_n_dim(set);
1552         isl_assert(set->ctx, 1 + dim == bounds->n_col, goto error);
1553         isl_seq_cpy(hull->ineq[k], bounds->row[0], bounds->n_col);
1554         isl_mat_free(bounds);
1555
1556         return hull;
1557 error:
1558         isl_basic_set_free(hull);
1559         isl_mat_free(bounds);
1560         return NULL;
1561 }
1562
1563 struct max_constraint {
1564         struct isl_mat *c;
1565         int             count;
1566         int             ineq;
1567 };
1568
1569 static int max_constraint_equal(const void *entry, const void *val)
1570 {
1571         struct max_constraint *a = (struct max_constraint *)entry;
1572         isl_int *b = (isl_int *)val;
1573
1574         return isl_seq_eq(a->c->row[0] + 1, b, a->c->n_col - 1);
1575 }
1576
1577 static void update_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1578         isl_int *con, unsigned len, int n, int ineq)
1579 {
1580         struct isl_hash_table_entry *entry;
1581         struct max_constraint *c;
1582         uint32_t c_hash;
1583
1584         c_hash = isl_seq_get_hash(con + 1, len);
1585         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1586                         con + 1, 0);
1587         if (!entry)
1588                 return;
1589         c = entry->data;
1590         if (c->count < n) {
1591                 isl_hash_table_remove(ctx, table, entry);
1592                 return;
1593         }
1594         c->count++;
1595         if (isl_int_gt(c->c->row[0][0], con[0]))
1596                 return;
1597         if (isl_int_eq(c->c->row[0][0], con[0])) {
1598                 if (ineq)
1599                         c->ineq = ineq;
1600                 return;
1601         }
1602         c->c = isl_mat_cow(c->c);
1603         isl_int_set(c->c->row[0][0], con[0]);
1604         c->ineq = ineq;
1605 }
1606
1607 /* Check whether the constraint hash table "table" constains the constraint
1608  * "con".
1609  */
1610 static int has_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1611         isl_int *con, unsigned len, int n)
1612 {
1613         struct isl_hash_table_entry *entry;
1614         struct max_constraint *c;
1615         uint32_t c_hash;
1616
1617         c_hash = isl_seq_get_hash(con + 1, len);
1618         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1619                         con + 1, 0);
1620         if (!entry)
1621                 return 0;
1622         c = entry->data;
1623         if (c->count < n)
1624                 return 0;
1625         return isl_int_eq(c->c->row[0][0], con[0]);
1626 }
1627
1628 /* Check for inequality constraints of a basic set without equalities
1629  * such that the same or more stringent copies of the constraint appear
1630  * in all of the basic sets.  Such constraints are necessarily facet
1631  * constraints of the convex hull.
1632  *
1633  * If the resulting basic set is by chance identical to one of
1634  * the basic sets in "set", then we know that this basic set contains
1635  * all other basic sets and is therefore the convex hull of set.
1636  * In this case we set *is_hull to 1.
1637  */
1638 static struct isl_basic_set *common_constraints(struct isl_basic_set *hull,
1639         struct isl_set *set, int *is_hull)
1640 {
1641         int i, j, s, n;
1642         int min_constraints;
1643         int best;
1644         struct max_constraint *constraints = NULL;
1645         struct isl_hash_table *table = NULL;
1646         unsigned total;
1647
1648         *is_hull = 0;
1649
1650         for (i = 0; i < set->n; ++i)
1651                 if (set->p[i]->n_eq == 0)
1652                         break;
1653         if (i >= set->n)
1654                 return hull;
1655         min_constraints = set->p[i]->n_ineq;
1656         best = i;
1657         for (i = best + 1; i < set->n; ++i) {
1658                 if (set->p[i]->n_eq != 0)
1659                         continue;
1660                 if (set->p[i]->n_ineq >= min_constraints)
1661                         continue;
1662                 min_constraints = set->p[i]->n_ineq;
1663                 best = i;
1664         }
1665         constraints = isl_calloc_array(hull->ctx, struct max_constraint,
1666                                         min_constraints);
1667         if (!constraints)
1668                 return hull;
1669         table = isl_alloc_type(hull->ctx, struct isl_hash_table);
1670         if (isl_hash_table_init(hull->ctx, table, min_constraints))
1671                 goto error;
1672
1673         total = isl_dim_total(set->dim);
1674         for (i = 0; i < set->p[best]->n_ineq; ++i) {
1675                 constraints[i].c = isl_mat_sub_alloc6(hull->ctx,
1676                         set->p[best]->ineq + i, 0, 1, 0, 1 + total);
1677                 if (!constraints[i].c)
1678                         goto error;
1679                 constraints[i].ineq = 1;
1680         }
1681         for (i = 0; i < min_constraints; ++i) {
1682                 struct isl_hash_table_entry *entry;
1683                 uint32_t c_hash;
1684                 c_hash = isl_seq_get_hash(constraints[i].c->row[0] + 1, total);
1685                 entry = isl_hash_table_find(hull->ctx, table, c_hash,
1686                         max_constraint_equal, constraints[i].c->row[0] + 1, 1);
1687                 if (!entry)
1688                         goto error;
1689                 isl_assert(hull->ctx, !entry->data, goto error);
1690                 entry->data = &constraints[i];
1691         }
1692
1693         n = 0;
1694         for (s = 0; s < set->n; ++s) {
1695                 if (s == best)
1696                         continue;
1697
1698                 for (i = 0; i < set->p[s]->n_eq; ++i) {
1699                         isl_int *eq = set->p[s]->eq[i];
1700                         for (j = 0; j < 2; ++j) {
1701                                 isl_seq_neg(eq, eq, 1 + total);
1702                                 update_constraint(hull->ctx, table,
1703                                                             eq, total, n, 0);
1704                         }
1705                 }
1706                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1707                         isl_int *ineq = set->p[s]->ineq[i];
1708                         update_constraint(hull->ctx, table, ineq, total, n,
1709                                 set->p[s]->n_eq == 0);
1710                 }
1711                 ++n;
1712         }
1713
1714         for (i = 0; i < min_constraints; ++i) {
1715                 if (constraints[i].count < n)
1716                         continue;
1717                 if (!constraints[i].ineq)
1718                         continue;
1719                 j = isl_basic_set_alloc_inequality(hull);
1720                 if (j < 0)
1721                         goto error;
1722                 isl_seq_cpy(hull->ineq[j], constraints[i].c->row[0], 1 + total);
1723         }
1724
1725         for (s = 0; s < set->n; ++s) {
1726                 if (set->p[s]->n_eq)
1727                         continue;
1728                 if (set->p[s]->n_ineq != hull->n_ineq)
1729                         continue;
1730                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1731                         isl_int *ineq = set->p[s]->ineq[i];
1732                         if (!has_constraint(hull->ctx, table, ineq, total, n))
1733                                 break;
1734                 }
1735                 if (i == set->p[s]->n_ineq)
1736                         *is_hull = 1;
1737         }
1738
1739         isl_hash_table_clear(table);
1740         for (i = 0; i < min_constraints; ++i)
1741                 isl_mat_free(constraints[i].c);
1742         free(constraints);
1743         free(table);
1744         return hull;
1745 error:
1746         isl_hash_table_clear(table);
1747         free(table);
1748         if (constraints)
1749                 for (i = 0; i < min_constraints; ++i)
1750                         isl_mat_free(constraints[i].c);
1751         free(constraints);
1752         return hull;
1753 }
1754
1755 /* Create a template for the convex hull of "set" and fill it up
1756  * obvious facet constraints, if any.  If the result happens to
1757  * be the convex hull of "set" then *is_hull is set to 1.
1758  */
1759 static struct isl_basic_set *proto_hull(struct isl_set *set, int *is_hull)
1760 {
1761         struct isl_basic_set *hull;
1762         unsigned n_ineq;
1763         int i;
1764
1765         n_ineq = 1;
1766         for (i = 0; i < set->n; ++i) {
1767                 n_ineq += set->p[i]->n_eq;
1768                 n_ineq += set->p[i]->n_ineq;
1769         }
1770         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
1771         hull = isl_basic_set_set_rational(hull);
1772         if (!hull)
1773                 return NULL;
1774         return common_constraints(hull, set, is_hull);
1775 }
1776
1777 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set)
1778 {
1779         struct isl_basic_set *hull;
1780         int is_hull;
1781
1782         hull = proto_hull(set, &is_hull);
1783         if (hull && !is_hull) {
1784                 if (hull->n_ineq == 0)
1785                         hull = initial_hull(hull, set);
1786                 hull = extend(hull, set);
1787         }
1788         isl_set_free(set);
1789
1790         return hull;
1791 }
1792
1793 /* Compute the convex hull of a set without any parameters or
1794  * integer divisions.  Depending on whether the set is bounded,
1795  * we pass control to the wrapping based convex hull or
1796  * the Fourier-Motzkin elimination based convex hull.
1797  * We also handle a few special cases before checking the boundedness.
1798  */
1799 static struct isl_basic_set *uset_convex_hull(struct isl_set *set)
1800 {
1801         struct isl_basic_set *convex_hull = NULL;
1802         struct isl_basic_set *lin;
1803
1804         if (isl_set_n_dim(set) == 0)
1805                 return convex_hull_0d(set);
1806
1807         set = isl_set_coalesce(set);
1808         set = isl_set_set_rational(set);
1809
1810         if (!set)
1811                 goto error;
1812         if (!set)
1813                 return NULL;
1814         if (set->n == 1) {
1815                 convex_hull = isl_basic_set_copy(set->p[0]);
1816                 isl_set_free(set);
1817                 return convex_hull;
1818         }
1819         if (isl_set_n_dim(set) == 1)
1820                 return convex_hull_1d(set);
1821
1822         if (isl_set_is_bounded(set) &&
1823             set->ctx->opt->convex == ISL_CONVEX_HULL_WRAP)
1824                 return uset_convex_hull_wrap(set);
1825
1826         lin = uset_combined_lineality_space(isl_set_copy(set));
1827         if (!lin)
1828                 goto error;
1829         if (isl_basic_set_is_universe(lin)) {
1830                 isl_set_free(set);
1831                 return lin;
1832         }
1833         if (lin->n_eq < isl_basic_set_total_dim(lin))
1834                 return modulo_lineality(set, lin);
1835         isl_basic_set_free(lin);
1836
1837         return uset_convex_hull_unbounded(set);
1838 error:
1839         isl_set_free(set);
1840         isl_basic_set_free(convex_hull);
1841         return NULL;
1842 }
1843
1844 /* This is the core procedure, where "set" is a "pure" set, i.e.,
1845  * without parameters or divs and where the convex hull of set is
1846  * known to be full-dimensional.
1847  */
1848 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set)
1849 {
1850         struct isl_basic_set *convex_hull = NULL;
1851
1852         if (!set)
1853                 goto error;
1854
1855         if (isl_set_n_dim(set) == 0) {
1856                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
1857                 isl_set_free(set);
1858                 convex_hull = isl_basic_set_set_rational(convex_hull);
1859                 return convex_hull;
1860         }
1861
1862         set = isl_set_set_rational(set);
1863         set = isl_set_coalesce(set);
1864         if (!set)
1865                 goto error;
1866         if (set->n == 1) {
1867                 convex_hull = isl_basic_set_copy(set->p[0]);
1868                 isl_set_free(set);
1869                 return convex_hull;
1870         }
1871         if (isl_set_n_dim(set) == 1)
1872                 return convex_hull_1d(set);
1873
1874         return uset_convex_hull_wrap(set);
1875 error:
1876         isl_set_free(set);
1877         return NULL;
1878 }
1879
1880 /* Compute the convex hull of set "set" with affine hull "affine_hull",
1881  * We first remove the equalities (transforming the set), compute the
1882  * convex hull of the transformed set and then add the equalities back
1883  * (after performing the inverse transformation.
1884  */
1885 static struct isl_basic_set *modulo_affine_hull(
1886         struct isl_set *set, struct isl_basic_set *affine_hull)
1887 {
1888         struct isl_mat *T;
1889         struct isl_mat *T2;
1890         struct isl_basic_set *dummy;
1891         struct isl_basic_set *convex_hull;
1892
1893         dummy = isl_basic_set_remove_equalities(
1894                         isl_basic_set_copy(affine_hull), &T, &T2);
1895         if (!dummy)
1896                 goto error;
1897         isl_basic_set_free(dummy);
1898         set = isl_set_preimage(set, T);
1899         convex_hull = uset_convex_hull(set);
1900         convex_hull = isl_basic_set_preimage(convex_hull, T2);
1901         convex_hull = isl_basic_set_intersect(convex_hull, affine_hull);
1902         return convex_hull;
1903 error:
1904         isl_basic_set_free(affine_hull);
1905         isl_set_free(set);
1906         return NULL;
1907 }
1908
1909 /* Compute the convex hull of a map.
1910  *
1911  * The implementation was inspired by "Extended Convex Hull" by Fukuda et al.,
1912  * specifically, the wrapping of facets to obtain new facets.
1913  */
1914 struct isl_basic_map *isl_map_convex_hull(struct isl_map *map)
1915 {
1916         struct isl_basic_set *bset;
1917         struct isl_basic_map *model = NULL;
1918         struct isl_basic_set *affine_hull = NULL;
1919         struct isl_basic_map *convex_hull = NULL;
1920         struct isl_set *set = NULL;
1921         struct isl_ctx *ctx;
1922
1923         if (!map)
1924                 goto error;
1925
1926         ctx = map->ctx;
1927         if (map->n == 0) {
1928                 convex_hull = isl_basic_map_empty_like_map(map);
1929                 isl_map_free(map);
1930                 return convex_hull;
1931         }
1932
1933         map = isl_map_detect_equalities(map);
1934         map = isl_map_align_divs(map);
1935         if (!map)
1936                 goto error;
1937         model = isl_basic_map_copy(map->p[0]);
1938         set = isl_map_underlying_set(map);
1939         if (!set)
1940                 goto error;
1941
1942         affine_hull = isl_set_affine_hull(isl_set_copy(set));
1943         if (!affine_hull)
1944                 goto error;
1945         if (affine_hull->n_eq != 0)
1946                 bset = modulo_affine_hull(set, affine_hull);
1947         else {
1948                 isl_basic_set_free(affine_hull);
1949                 bset = uset_convex_hull(set);
1950         }
1951
1952         convex_hull = isl_basic_map_overlying_set(bset, model);
1953         if (!convex_hull)
1954                 return NULL;
1955
1956         ISL_F_SET(convex_hull, ISL_BASIC_MAP_NO_IMPLICIT);
1957         ISL_F_SET(convex_hull, ISL_BASIC_MAP_ALL_EQUALITIES);
1958         ISL_F_CLR(convex_hull, ISL_BASIC_MAP_RATIONAL);
1959         return convex_hull;
1960 error:
1961         isl_set_free(set);
1962         isl_basic_map_free(model);
1963         return NULL;
1964 }
1965
1966 struct isl_basic_set *isl_set_convex_hull(struct isl_set *set)
1967 {
1968         return (struct isl_basic_set *)
1969                 isl_map_convex_hull((struct isl_map *)set);
1970 }
1971
1972 __isl_give isl_basic_map *isl_map_polyhedral_hull(__isl_take isl_map *map)
1973 {
1974         isl_basic_map *hull;
1975
1976         hull = isl_map_convex_hull(map);
1977         return isl_basic_map_remove_divs(hull);
1978 }
1979
1980 __isl_give isl_basic_set *isl_set_polyhedral_hull(__isl_take isl_set *set)
1981 {
1982         return (isl_basic_set *)isl_map_polyhedral_hull((isl_map *)set);
1983 }
1984
1985 struct sh_data_entry {
1986         struct isl_hash_table   *table;
1987         struct isl_tab          *tab;
1988 };
1989
1990 /* Holds the data needed during the simple hull computation.
1991  * In particular,
1992  *      n               the number of basic sets in the original set
1993  *      hull_table      a hash table of already computed constraints
1994  *                      in the simple hull
1995  *      p               for each basic set,
1996  *              table           a hash table of the constraints
1997  *              tab             the tableau corresponding to the basic set
1998  */
1999 struct sh_data {
2000         struct isl_ctx          *ctx;
2001         unsigned                n;
2002         struct isl_hash_table   *hull_table;
2003         struct sh_data_entry    p[1];
2004 };
2005
2006 static void sh_data_free(struct sh_data *data)
2007 {
2008         int i;
2009
2010         if (!data)
2011                 return;
2012         isl_hash_table_free(data->ctx, data->hull_table);
2013         for (i = 0; i < data->n; ++i) {
2014                 isl_hash_table_free(data->ctx, data->p[i].table);
2015                 isl_tab_free(data->p[i].tab);
2016         }
2017         free(data);
2018 }
2019
2020 struct ineq_cmp_data {
2021         unsigned        len;
2022         isl_int         *p;
2023 };
2024
2025 static int has_ineq(const void *entry, const void *val)
2026 {
2027         isl_int *row = (isl_int *)entry;
2028         struct ineq_cmp_data *v = (struct ineq_cmp_data *)val;
2029
2030         return isl_seq_eq(row + 1, v->p + 1, v->len) ||
2031                isl_seq_is_neg(row + 1, v->p + 1, v->len);
2032 }
2033
2034 static int hash_ineq(struct isl_ctx *ctx, struct isl_hash_table *table,
2035                         isl_int *ineq, unsigned len)
2036 {
2037         uint32_t c_hash;
2038         struct ineq_cmp_data v;
2039         struct isl_hash_table_entry *entry;
2040
2041         v.len = len;
2042         v.p = ineq;
2043         c_hash = isl_seq_get_hash(ineq + 1, len);
2044         entry = isl_hash_table_find(ctx, table, c_hash, has_ineq, &v, 1);
2045         if (!entry)
2046                 return - 1;
2047         entry->data = ineq;
2048         return 0;
2049 }
2050
2051 /* Fill hash table "table" with the constraints of "bset".
2052  * Equalities are added as two inequalities.
2053  * The value in the hash table is a pointer to the (in)equality of "bset".
2054  */
2055 static int hash_basic_set(struct isl_hash_table *table,
2056                                 struct isl_basic_set *bset)
2057 {
2058         int i, j;
2059         unsigned dim = isl_basic_set_total_dim(bset);
2060
2061         for (i = 0; i < bset->n_eq; ++i) {
2062                 for (j = 0; j < 2; ++j) {
2063                         isl_seq_neg(bset->eq[i], bset->eq[i], 1 + dim);
2064                         if (hash_ineq(bset->ctx, table, bset->eq[i], dim) < 0)
2065                                 return -1;
2066                 }
2067         }
2068         for (i = 0; i < bset->n_ineq; ++i) {
2069                 if (hash_ineq(bset->ctx, table, bset->ineq[i], dim) < 0)
2070                         return -1;
2071         }
2072         return 0;
2073 }
2074
2075 static struct sh_data *sh_data_alloc(struct isl_set *set, unsigned n_ineq)
2076 {
2077         struct sh_data *data;
2078         int i;
2079
2080         data = isl_calloc(set->ctx, struct sh_data,
2081                 sizeof(struct sh_data) +
2082                 (set->n - 1) * sizeof(struct sh_data_entry));
2083         if (!data)
2084                 return NULL;
2085         data->ctx = set->ctx;
2086         data->n = set->n;
2087         data->hull_table = isl_hash_table_alloc(set->ctx, n_ineq);
2088         if (!data->hull_table)
2089                 goto error;
2090         for (i = 0; i < set->n; ++i) {
2091                 data->p[i].table = isl_hash_table_alloc(set->ctx,
2092                                     2 * set->p[i]->n_eq + set->p[i]->n_ineq);
2093                 if (!data->p[i].table)
2094                         goto error;
2095                 if (hash_basic_set(data->p[i].table, set->p[i]) < 0)
2096                         goto error;
2097         }
2098         return data;
2099 error:
2100         sh_data_free(data);
2101         return NULL;
2102 }
2103
2104 /* Check if inequality "ineq" is a bound for basic set "j" or if
2105  * it can be relaxed (by increasing the constant term) to become
2106  * a bound for that basic set.  In the latter case, the constant
2107  * term is updated.
2108  * Return 1 if "ineq" is a bound
2109  *        0 if "ineq" may attain arbitrarily small values on basic set "j"
2110  *       -1 if some error occurred
2111  */
2112 static int is_bound(struct sh_data *data, struct isl_set *set, int j,
2113                         isl_int *ineq)
2114 {
2115         enum isl_lp_result res;
2116         isl_int opt;
2117
2118         if (!data->p[j].tab) {
2119                 data->p[j].tab = isl_tab_from_basic_set(set->p[j]);
2120                 if (!data->p[j].tab)
2121                         return -1;
2122         }
2123
2124         isl_int_init(opt);
2125
2126         res = isl_tab_min(data->p[j].tab, ineq, data->ctx->one,
2127                                 &opt, NULL, 0);
2128         if (res == isl_lp_ok && isl_int_is_neg(opt))
2129                 isl_int_sub(ineq[0], ineq[0], opt);
2130
2131         isl_int_clear(opt);
2132
2133         return (res == isl_lp_ok || res == isl_lp_empty) ? 1 :
2134                res == isl_lp_unbounded ? 0 : -1;
2135 }
2136
2137 /* Check if inequality "ineq" from basic set "i" can be relaxed to
2138  * become a bound on the whole set.  If so, add the (relaxed) inequality
2139  * to "hull".
2140  *
2141  * We first check if "hull" already contains a translate of the inequality.
2142  * If so, we are done.
2143  * Then, we check if any of the previous basic sets contains a translate
2144  * of the inequality.  If so, then we have already considered this
2145  * inequality and we are done.
2146  * Otherwise, for each basic set other than "i", we check if the inequality
2147  * is a bound on the basic set.
2148  * For previous basic sets, we know that they do not contain a translate
2149  * of the inequality, so we directly call is_bound.
2150  * For following basic sets, we first check if a translate of the
2151  * inequality appears in its description and if so directly update
2152  * the inequality accordingly.
2153  */
2154 static struct isl_basic_set *add_bound(struct isl_basic_set *hull,
2155         struct sh_data *data, struct isl_set *set, int i, isl_int *ineq)
2156 {
2157         uint32_t c_hash;
2158         struct ineq_cmp_data v;
2159         struct isl_hash_table_entry *entry;
2160         int j, k;
2161
2162         if (!hull)
2163                 return NULL;
2164
2165         v.len = isl_basic_set_total_dim(hull);
2166         v.p = ineq;
2167         c_hash = isl_seq_get_hash(ineq + 1, v.len);
2168
2169         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
2170                                         has_ineq, &v, 0);
2171         if (entry)
2172                 return hull;
2173
2174         for (j = 0; j < i; ++j) {
2175                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
2176                                                 c_hash, has_ineq, &v, 0);
2177                 if (entry)
2178                         break;
2179         }
2180         if (j < i)
2181                 return hull;
2182
2183         k = isl_basic_set_alloc_inequality(hull);
2184         isl_seq_cpy(hull->ineq[k], ineq, 1 + v.len);
2185         if (k < 0)
2186                 goto error;
2187
2188         for (j = 0; j < i; ++j) {
2189                 int bound;
2190                 bound = is_bound(data, set, j, hull->ineq[k]);
2191                 if (bound < 0)
2192                         goto error;
2193                 if (!bound)
2194                         break;
2195         }
2196         if (j < i) {
2197                 isl_basic_set_free_inequality(hull, 1);
2198                 return hull;
2199         }
2200
2201         for (j = i + 1; j < set->n; ++j) {
2202                 int bound, neg;
2203                 isl_int *ineq_j;
2204                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
2205                                                 c_hash, has_ineq, &v, 0);
2206                 if (entry) {
2207                         ineq_j = entry->data;
2208                         neg = isl_seq_is_neg(ineq_j + 1,
2209                                              hull->ineq[k] + 1, v.len);
2210                         if (neg)
2211                                 isl_int_neg(ineq_j[0], ineq_j[0]);
2212                         if (isl_int_gt(ineq_j[0], hull->ineq[k][0]))
2213                                 isl_int_set(hull->ineq[k][0], ineq_j[0]);
2214                         if (neg)
2215                                 isl_int_neg(ineq_j[0], ineq_j[0]);
2216                         continue;
2217                 }
2218                 bound = is_bound(data, set, j, hull->ineq[k]);
2219                 if (bound < 0)
2220                         goto error;
2221                 if (!bound)
2222                         break;
2223         }
2224         if (j < set->n) {
2225                 isl_basic_set_free_inequality(hull, 1);
2226                 return hull;
2227         }
2228
2229         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
2230                                         has_ineq, &v, 1);
2231         if (!entry)
2232                 goto error;
2233         entry->data = hull->ineq[k];
2234
2235         return hull;
2236 error:
2237         isl_basic_set_free(hull);
2238         return NULL;
2239 }
2240
2241 /* Check if any inequality from basic set "i" can be relaxed to
2242  * become a bound on the whole set.  If so, add the (relaxed) inequality
2243  * to "hull".
2244  */
2245 static struct isl_basic_set *add_bounds(struct isl_basic_set *bset,
2246         struct sh_data *data, struct isl_set *set, int i)
2247 {
2248         int j, k;
2249         unsigned dim = isl_basic_set_total_dim(bset);
2250
2251         for (j = 0; j < set->p[i]->n_eq; ++j) {
2252                 for (k = 0; k < 2; ++k) {
2253                         isl_seq_neg(set->p[i]->eq[j], set->p[i]->eq[j], 1+dim);
2254                         bset = add_bound(bset, data, set, i, set->p[i]->eq[j]);
2255                 }
2256         }
2257         for (j = 0; j < set->p[i]->n_ineq; ++j)
2258                 bset = add_bound(bset, data, set, i, set->p[i]->ineq[j]);
2259         return bset;
2260 }
2261
2262 /* Compute a superset of the convex hull of set that is described
2263  * by only translates of the constraints in the constituents of set.
2264  */
2265 static struct isl_basic_set *uset_simple_hull(struct isl_set *set)
2266 {
2267         struct sh_data *data = NULL;
2268         struct isl_basic_set *hull = NULL;
2269         unsigned n_ineq;
2270         int i;
2271
2272         if (!set)
2273                 return NULL;
2274
2275         n_ineq = 0;
2276         for (i = 0; i < set->n; ++i) {
2277                 if (!set->p[i])
2278                         goto error;
2279                 n_ineq += 2 * set->p[i]->n_eq + set->p[i]->n_ineq;
2280         }
2281
2282         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
2283         if (!hull)
2284                 goto error;
2285
2286         data = sh_data_alloc(set, n_ineq);
2287         if (!data)
2288                 goto error;
2289
2290         for (i = 0; i < set->n; ++i)
2291                 hull = add_bounds(hull, data, set, i);
2292
2293         sh_data_free(data);
2294         isl_set_free(set);
2295
2296         return hull;
2297 error:
2298         sh_data_free(data);
2299         isl_basic_set_free(hull);
2300         isl_set_free(set);
2301         return NULL;
2302 }
2303
2304 /* Compute a superset of the convex hull of map that is described
2305  * by only translates of the constraints in the constituents of map.
2306  */
2307 struct isl_basic_map *isl_map_simple_hull(struct isl_map *map)
2308 {
2309         struct isl_set *set = NULL;
2310         struct isl_basic_map *model = NULL;
2311         struct isl_basic_map *hull;
2312         struct isl_basic_map *affine_hull;
2313         struct isl_basic_set *bset = NULL;
2314
2315         if (!map)
2316                 return NULL;
2317         if (map->n == 0) {
2318                 hull = isl_basic_map_empty_like_map(map);
2319                 isl_map_free(map);
2320                 return hull;
2321         }
2322         if (map->n == 1) {
2323                 hull = isl_basic_map_copy(map->p[0]);
2324                 isl_map_free(map);
2325                 return hull;
2326         }
2327
2328         map = isl_map_detect_equalities(map);
2329         affine_hull = isl_map_affine_hull(isl_map_copy(map));
2330         map = isl_map_align_divs(map);
2331         model = isl_basic_map_copy(map->p[0]);
2332
2333         set = isl_map_underlying_set(map);
2334
2335         bset = uset_simple_hull(set);
2336
2337         hull = isl_basic_map_overlying_set(bset, model);
2338
2339         hull = isl_basic_map_intersect(hull, affine_hull);
2340         hull = isl_basic_map_remove_redundancies(hull);
2341         ISL_F_SET(hull, ISL_BASIC_MAP_NO_IMPLICIT);
2342         ISL_F_SET(hull, ISL_BASIC_MAP_ALL_EQUALITIES);
2343
2344         return hull;
2345 }
2346
2347 struct isl_basic_set *isl_set_simple_hull(struct isl_set *set)
2348 {
2349         return (struct isl_basic_set *)
2350                 isl_map_simple_hull((struct isl_map *)set);
2351 }
2352
2353 /* Given a set "set", return parametric bounds on the dimension "dim".
2354  */
2355 static struct isl_basic_set *set_bounds(struct isl_set *set, int dim)
2356 {
2357         unsigned set_dim = isl_set_dim(set, isl_dim_set);
2358         set = isl_set_copy(set);
2359         set = isl_set_eliminate_dims(set, dim + 1, set_dim - (dim + 1));
2360         set = isl_set_eliminate_dims(set, 0, dim);
2361         return isl_set_convex_hull(set);
2362 }
2363
2364 /* Computes a "simple hull" and then check if each dimension in the
2365  * resulting hull is bounded by a symbolic constant.  If not, the
2366  * hull is intersected with the corresponding bounds on the whole set.
2367  */
2368 struct isl_basic_set *isl_set_bounded_simple_hull(struct isl_set *set)
2369 {
2370         int i, j;
2371         struct isl_basic_set *hull;
2372         unsigned nparam, left;
2373         int removed_divs = 0;
2374
2375         hull = isl_set_simple_hull(isl_set_copy(set));
2376         if (!hull)
2377                 goto error;
2378
2379         nparam = isl_basic_set_dim(hull, isl_dim_param);
2380         for (i = 0; i < isl_basic_set_dim(hull, isl_dim_set); ++i) {
2381                 int lower = 0, upper = 0;
2382                 struct isl_basic_set *bounds;
2383
2384                 left = isl_basic_set_total_dim(hull) - nparam - i - 1;
2385                 for (j = 0; j < hull->n_eq; ++j) {
2386                         if (isl_int_is_zero(hull->eq[j][1 + nparam + i]))
2387                                 continue;
2388                         if (isl_seq_first_non_zero(hull->eq[j]+1+nparam+i+1,
2389                                                     left) == -1)
2390                                 break;
2391                 }
2392                 if (j < hull->n_eq)
2393                         continue;
2394
2395                 for (j = 0; j < hull->n_ineq; ++j) {
2396                         if (isl_int_is_zero(hull->ineq[j][1 + nparam + i]))
2397                                 continue;
2398                         if (isl_seq_first_non_zero(hull->ineq[j]+1+nparam+i+1,
2399                                                     left) != -1 ||
2400                             isl_seq_first_non_zero(hull->ineq[j]+1+nparam,
2401                                                     i) != -1)
2402                                 continue;
2403                         if (isl_int_is_pos(hull->ineq[j][1 + nparam + i]))
2404                                 lower = 1;
2405                         else
2406                                 upper = 1;
2407                         if (lower && upper)
2408                                 break;
2409                 }
2410
2411                 if (lower && upper)
2412                         continue;
2413
2414                 if (!removed_divs) {
2415                         set = isl_set_remove_divs(set);
2416                         if (!set)
2417                                 goto error;
2418                         removed_divs = 1;
2419                 }
2420                 bounds = set_bounds(set, i);
2421                 hull = isl_basic_set_intersect(hull, bounds);
2422                 if (!hull)
2423                         goto error;
2424         }
2425
2426         isl_set_free(set);
2427         return hull;
2428 error:
2429         isl_set_free(set);
2430         return NULL;
2431 }