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