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