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