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