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