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