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