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