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