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