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