Merge commit 'isl-0.05.1'
[platform/upstream/isl.git] / isl_tab_pip.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  * Copyright 2010      INRIA Saclay
4  *
5  * Use of this software is governed by the GNU LGPLv2.1 license
6  *
7  * Written by Sven Verdoolaege, K.U.Leuven, Departement
8  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
9  * and INRIA Saclay - Ile-de-France, Parc Club Orsay Universite,
10  * ZAC des vignes, 4 rue Jacques Monod, 91893 Orsay, France 
11  */
12
13 #include "isl_map_private.h"
14 #include <isl/seq.h>
15 #include "isl_tab.h"
16 #include "isl_sample.h"
17 #include <isl_mat_private.h>
18
19 /*
20  * The implementation of parametric integer linear programming in this file
21  * was inspired by the paper "Parametric Integer Programming" and the
22  * report "Solving systems of affine (in)equalities" by Paul Feautrier
23  * (and others).
24  *
25  * The strategy used for obtaining a feasible solution is different
26  * from the one used in isl_tab.c.  In particular, in isl_tab.c,
27  * upon finding a constraint that is not yet satisfied, we pivot
28  * in a row that increases the constant term of row holding the
29  * constraint, making sure the sample solution remains feasible
30  * for all the constraints it already satisfied.
31  * Here, we always pivot in the row holding the constraint,
32  * choosing a column that induces the lexicographically smallest
33  * increment to the sample solution.
34  *
35  * By starting out from a sample value that is lexicographically
36  * smaller than any integer point in the problem space, the first
37  * feasible integer sample point we find will also be the lexicographically
38  * smallest.  If all variables can be assumed to be non-negative,
39  * then the initial sample value may be chosen equal to zero.
40  * However, we will not make this assumption.  Instead, we apply
41  * the "big parameter" trick.  Any variable x is then not directly
42  * used in the tableau, but instead it its represented by another
43  * variable x' = M + x, where M is an arbitrarily large (positive)
44  * value.  x' is therefore always non-negative, whatever the value of x.
45  * Taking as initial sample value x' = 0 corresponds to x = -M,
46  * which is always smaller than any possible value of x.
47  *
48  * The big parameter trick is used in the main tableau and
49  * also in the context tableau if isl_context_lex is used.
50  * In this case, each tableaus has its own big parameter.
51  * Before doing any real work, we check if all the parameters
52  * happen to be non-negative.  If so, we drop the column corresponding
53  * to M from the initial context tableau.
54  * If isl_context_gbr is used, then the big parameter trick is only
55  * used in the main tableau.
56  */
57
58 struct isl_context;
59 struct isl_context_op {
60         /* detect nonnegative parameters in context and mark them in tab */
61         struct isl_tab *(*detect_nonnegative_parameters)(
62                         struct isl_context *context, struct isl_tab *tab);
63         /* return temporary reference to basic set representation of context */
64         struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
65         /* return temporary reference to tableau representation of context */
66         struct isl_tab *(*peek_tab)(struct isl_context *context);
67         /* add equality; check is 1 if eq may not be valid;
68          * update is 1 if we may want to call ineq_sign on context later.
69          */
70         void (*add_eq)(struct isl_context *context, isl_int *eq,
71                         int check, int update);
72         /* add inequality; check is 1 if ineq may not be valid;
73          * update is 1 if we may want to call ineq_sign on context later.
74          */
75         void (*add_ineq)(struct isl_context *context, isl_int *ineq,
76                         int check, int update);
77         /* check sign of ineq based on previous information.
78          * strict is 1 if saturation should be treated as a positive sign.
79          */
80         enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
81                         isl_int *ineq, int strict);
82         /* check if inequality maintains feasibility */
83         int (*test_ineq)(struct isl_context *context, isl_int *ineq);
84         /* return index of a div that corresponds to "div" */
85         int (*get_div)(struct isl_context *context, struct isl_tab *tab,
86                         struct isl_vec *div);
87         /* add div "div" to context and return non-negativity */
88         int (*add_div)(struct isl_context *context, struct isl_vec *div);
89         int (*detect_equalities)(struct isl_context *context,
90                         struct isl_tab *tab);
91         /* return row index of "best" split */
92         int (*best_split)(struct isl_context *context, struct isl_tab *tab);
93         /* check if context has already been determined to be empty */
94         int (*is_empty)(struct isl_context *context);
95         /* check if context is still usable */
96         int (*is_ok)(struct isl_context *context);
97         /* save a copy/snapshot of context */
98         void *(*save)(struct isl_context *context);
99         /* restore saved context */
100         void (*restore)(struct isl_context *context, void *);
101         /* invalidate context */
102         void (*invalidate)(struct isl_context *context);
103         /* free context */
104         void (*free)(struct isl_context *context);
105 };
106
107 struct isl_context {
108         struct isl_context_op *op;
109 };
110
111 struct isl_context_lex {
112         struct isl_context context;
113         struct isl_tab *tab;
114 };
115
116 struct isl_partial_sol {
117         int level;
118         struct isl_basic_set *dom;
119         struct isl_mat *M;
120
121         struct isl_partial_sol *next;
122 };
123
124 struct isl_sol;
125 struct isl_sol_callback {
126         struct isl_tab_callback callback;
127         struct isl_sol *sol;
128 };
129
130 /* isl_sol is an interface for constructing a solution to
131  * a parametric integer linear programming problem.
132  * Every time the algorithm reaches a state where a solution
133  * can be read off from the tableau (including cases where the tableau
134  * is empty), the function "add" is called on the isl_sol passed
135  * to find_solutions_main.
136  *
137  * The context tableau is owned by isl_sol and is updated incrementally.
138  *
139  * There are currently two implementations of this interface,
140  * isl_sol_map, which simply collects the solutions in an isl_map
141  * and (optionally) the parts of the context where there is no solution
142  * in an isl_set, and
143  * isl_sol_for, which calls a user-defined function for each part of
144  * the solution.
145  */
146 struct isl_sol {
147         int error;
148         int rational;
149         int level;
150         int max;
151         int n_out;
152         struct isl_context *context;
153         struct isl_partial_sol *partial;
154         void (*add)(struct isl_sol *sol,
155                             struct isl_basic_set *dom, struct isl_mat *M);
156         void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
157         void (*free)(struct isl_sol *sol);
158         struct isl_sol_callback dec_level;
159 };
160
161 static void sol_free(struct isl_sol *sol)
162 {
163         struct isl_partial_sol *partial, *next;
164         if (!sol)
165                 return;
166         for (partial = sol->partial; partial; partial = next) {
167                 next = partial->next;
168                 isl_basic_set_free(partial->dom);
169                 isl_mat_free(partial->M);
170                 free(partial);
171         }
172         sol->free(sol);
173 }
174
175 /* Push a partial solution represented by a domain and mapping M
176  * onto the stack of partial solutions.
177  */
178 static void sol_push_sol(struct isl_sol *sol,
179         struct isl_basic_set *dom, struct isl_mat *M)
180 {
181         struct isl_partial_sol *partial;
182
183         if (sol->error || !dom)
184                 goto error;
185
186         partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
187         if (!partial)
188                 goto error;
189
190         partial->level = sol->level;
191         partial->dom = dom;
192         partial->M = M;
193         partial->next = sol->partial;
194
195         sol->partial = partial;
196
197         return;
198 error:
199         isl_basic_set_free(dom);
200         sol->error = 1;
201 }
202
203 /* Pop one partial solution from the partial solution stack and
204  * pass it on to sol->add or sol->add_empty.
205  */
206 static void sol_pop_one(struct isl_sol *sol)
207 {
208         struct isl_partial_sol *partial;
209
210         partial = sol->partial;
211         sol->partial = partial->next;
212
213         if (partial->M)
214                 sol->add(sol, partial->dom, partial->M);
215         else
216                 sol->add_empty(sol, partial->dom);
217         free(partial);
218 }
219
220 /* Return a fresh copy of the domain represented by the context tableau.
221  */
222 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
223 {
224         struct isl_basic_set *bset;
225
226         if (sol->error)
227                 return NULL;
228
229         bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
230         bset = isl_basic_set_update_from_tab(bset,
231                         sol->context->op->peek_tab(sol->context));
232
233         return bset;
234 }
235
236 /* Check whether two partial solutions have the same mapping, where n_div
237  * is the number of divs that the two partial solutions have in common.
238  */
239 static int same_solution(struct isl_partial_sol *s1, struct isl_partial_sol *s2,
240         unsigned n_div)
241 {
242         int i;
243         unsigned dim;
244
245         if (!s1->M != !s2->M)
246                 return 0;
247         if (!s1->M)
248                 return 1;
249
250         dim = isl_basic_set_total_dim(s1->dom) - s1->dom->n_div;
251
252         for (i = 0; i < s1->M->n_row; ++i) {
253                 if (isl_seq_first_non_zero(s1->M->row[i]+1+dim+n_div,
254                                             s1->M->n_col-1-dim-n_div) != -1)
255                         return 0;
256                 if (isl_seq_first_non_zero(s2->M->row[i]+1+dim+n_div,
257                                             s2->M->n_col-1-dim-n_div) != -1)
258                         return 0;
259                 if (!isl_seq_eq(s1->M->row[i], s2->M->row[i], 1+dim+n_div))
260                         return 0;
261         }
262         return 1;
263 }
264
265 /* Pop all solutions from the partial solution stack that were pushed onto
266  * the stack at levels that are deeper than the current level.
267  * If the two topmost elements on the stack have the same level
268  * and represent the same solution, then their domains are combined.
269  * This combined domain is the same as the current context domain
270  * as sol_pop is called each time we move back to a higher level.
271  */
272 static void sol_pop(struct isl_sol *sol)
273 {
274         struct isl_partial_sol *partial;
275         unsigned n_div;
276
277         if (sol->error)
278                 return;
279
280         if (sol->level == 0) {
281                 for (partial = sol->partial; partial; partial = sol->partial)
282                         sol_pop_one(sol);
283                 return;
284         }
285
286         partial = sol->partial;
287         if (!partial)
288                 return;
289
290         if (partial->level <= sol->level)
291                 return;
292
293         if (partial->next && partial->next->level == partial->level) {
294                 n_div = isl_basic_set_dim(
295                                 sol->context->op->peek_basic_set(sol->context),
296                                 isl_dim_div);
297
298                 if (!same_solution(partial, partial->next, n_div)) {
299                         sol_pop_one(sol);
300                         sol_pop_one(sol);
301                 } else {
302                         struct isl_basic_set *bset;
303
304                         bset = sol_domain(sol);
305
306                         isl_basic_set_free(partial->next->dom);
307                         partial->next->dom = bset;
308                         partial->next->level = sol->level;
309
310                         sol->partial = partial->next;
311                         isl_basic_set_free(partial->dom);
312                         isl_mat_free(partial->M);
313                         free(partial);
314                 }
315         } else
316                 sol_pop_one(sol);
317 }
318
319 static void sol_dec_level(struct isl_sol *sol)
320 {
321         if (sol->error)
322                 return;
323
324         sol->level--;
325
326         sol_pop(sol);
327 }
328
329 static int sol_dec_level_wrap(struct isl_tab_callback *cb)
330 {
331         struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
332
333         sol_dec_level(callback->sol);
334
335         return callback->sol->error ? -1 : 0;
336 }
337
338 /* Move down to next level and push callback onto context tableau
339  * to decrease the level again when it gets rolled back across
340  * the current state.  That is, dec_level will be called with
341  * the context tableau in the same state as it is when inc_level
342  * is called.
343  */
344 static void sol_inc_level(struct isl_sol *sol)
345 {
346         struct isl_tab *tab;
347
348         if (sol->error)
349                 return;
350
351         sol->level++;
352         tab = sol->context->op->peek_tab(sol->context);
353         if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
354                 sol->error = 1;
355 }
356
357 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
358 {
359         int i;
360
361         if (isl_int_is_one(m))
362                 return;
363
364         for (i = 0; i < n_row; ++i)
365                 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
366 }
367
368 /* Add the solution identified by the tableau and the context tableau.
369  *
370  * The layout of the variables is as follows.
371  *      tab->n_var is equal to the total number of variables in the input
372  *                      map (including divs that were copied from the context)
373  *                      + the number of extra divs constructed
374  *      Of these, the first tab->n_param and the last tab->n_div variables
375  *      correspond to the variables in the context, i.e.,
376  *              tab->n_param + tab->n_div = context_tab->n_var
377  *      tab->n_param is equal to the number of parameters and input
378  *                      dimensions in the input map
379  *      tab->n_div is equal to the number of divs in the context
380  *
381  * If there is no solution, then call add_empty with a basic set
382  * that corresponds to the context tableau.  (If add_empty is NULL,
383  * then do nothing).
384  *
385  * If there is a solution, then first construct a matrix that maps
386  * all dimensions of the context to the output variables, i.e.,
387  * the output dimensions in the input map.
388  * The divs in the input map (if any) that do not correspond to any
389  * div in the context do not appear in the solution.
390  * The algorithm will make sure that they have an integer value,
391  * but these values themselves are of no interest.
392  * We have to be careful not to drop or rearrange any divs in the
393  * context because that would change the meaning of the matrix.
394  *
395  * To extract the value of the output variables, it should be noted
396  * that we always use a big parameter M in the main tableau and so
397  * the variable stored in this tableau is not an output variable x itself, but
398  *      x' = M + x (in case of minimization)
399  * or
400  *      x' = M - x (in case of maximization)
401  * If x' appears in a column, then its optimal value is zero,
402  * which means that the optimal value of x is an unbounded number
403  * (-M for minimization and M for maximization).
404  * We currently assume that the output dimensions in the original map
405  * are bounded, so this cannot occur.
406  * Similarly, when x' appears in a row, then the coefficient of M in that
407  * row is necessarily 1.
408  * If the row in the tableau represents
409  *      d x' = c + d M + e(y)
410  * then, in case of minimization, the corresponding row in the matrix
411  * will be
412  *      a c + a e(y)
413  * with a d = m, the (updated) common denominator of the matrix.
414  * In case of maximization, the row will be
415  *      -a c - a e(y)
416  */
417 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
418 {
419         struct isl_basic_set *bset = NULL;
420         struct isl_mat *mat = NULL;
421         unsigned off;
422         int row, i;
423         isl_int m;
424
425         if (sol->error || !tab)
426                 goto error;
427
428         if (tab->empty && !sol->add_empty)
429                 return;
430
431         bset = sol_domain(sol);
432
433         if (tab->empty) {
434                 sol_push_sol(sol, bset, NULL);
435                 return;
436         }
437
438         off = 2 + tab->M;
439
440         mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
441                                             1 + tab->n_param + tab->n_div);
442         if (!mat)
443                 goto error;
444
445         isl_int_init(m);
446
447         isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
448         isl_int_set_si(mat->row[0][0], 1);
449         for (row = 0; row < sol->n_out; ++row) {
450                 int i = tab->n_param + row;
451                 int r, j;
452
453                 isl_seq_clr(mat->row[1 + row], mat->n_col);
454                 if (!tab->var[i].is_row) {
455                         if (tab->M)
456                                 isl_die(mat->ctx, isl_error_invalid,
457                                         "unbounded optimum", goto error2);
458                         continue;
459                 }
460
461                 r = tab->var[i].index;
462                 if (tab->M &&
463                     isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
464                         isl_die(mat->ctx, isl_error_invalid,
465                                 "unbounded optimum", goto error2);
466                 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
467                 isl_int_divexact(m, tab->mat->row[r][0], m);
468                 scale_rows(mat, m, 1 + row);
469                 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
470                 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
471                 for (j = 0; j < tab->n_param; ++j) {
472                         int col;
473                         if (tab->var[j].is_row)
474                                 continue;
475                         col = tab->var[j].index;
476                         isl_int_mul(mat->row[1 + row][1 + j], m,
477                                     tab->mat->row[r][off + col]);
478                 }
479                 for (j = 0; j < tab->n_div; ++j) {
480                         int col;
481                         if (tab->var[tab->n_var - tab->n_div+j].is_row)
482                                 continue;
483                         col = tab->var[tab->n_var - tab->n_div+j].index;
484                         isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
485                                     tab->mat->row[r][off + col]);
486                 }
487                 if (sol->max)
488                         isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
489                                     mat->n_col);
490         }
491
492         isl_int_clear(m);
493
494         sol_push_sol(sol, bset, mat);
495         return;
496 error2:
497         isl_int_clear(m);
498 error:
499         isl_basic_set_free(bset);
500         isl_mat_free(mat);
501         sol->error = 1;
502 }
503
504 struct isl_sol_map {
505         struct isl_sol  sol;
506         struct isl_map  *map;
507         struct isl_set  *empty;
508 };
509
510 static void sol_map_free(struct isl_sol_map *sol_map)
511 {
512         if (!sol_map)
513                 return;
514         if (sol_map->sol.context)
515                 sol_map->sol.context->op->free(sol_map->sol.context);
516         isl_map_free(sol_map->map);
517         isl_set_free(sol_map->empty);
518         free(sol_map);
519 }
520
521 static void sol_map_free_wrap(struct isl_sol *sol)
522 {
523         sol_map_free((struct isl_sol_map *)sol);
524 }
525
526 /* This function is called for parts of the context where there is
527  * no solution, with "bset" corresponding to the context tableau.
528  * Simply add the basic set to the set "empty".
529  */
530 static void sol_map_add_empty(struct isl_sol_map *sol,
531         struct isl_basic_set *bset)
532 {
533         if (!bset)
534                 goto error;
535         isl_assert(bset->ctx, sol->empty, goto error);
536
537         sol->empty = isl_set_grow(sol->empty, 1);
538         bset = isl_basic_set_simplify(bset);
539         bset = isl_basic_set_finalize(bset);
540         sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
541         if (!sol->empty)
542                 goto error;
543         isl_basic_set_free(bset);
544         return;
545 error:
546         isl_basic_set_free(bset);
547         sol->sol.error = 1;
548 }
549
550 static void sol_map_add_empty_wrap(struct isl_sol *sol,
551         struct isl_basic_set *bset)
552 {
553         sol_map_add_empty((struct isl_sol_map *)sol, bset);
554 }
555
556 /* Add bset to sol's empty, but only if we are actually collecting
557  * the empty set.
558  */
559 static void sol_map_add_empty_if_needed(struct isl_sol_map *sol,
560         struct isl_basic_set *bset)
561 {
562         if (sol->empty)
563                 sol_map_add_empty(sol, bset);
564         else
565                 isl_basic_set_free(bset);
566 }
567
568 /* Given a basic map "dom" that represents the context and an affine
569  * matrix "M" that maps the dimensions of the context to the
570  * output variables, construct a basic map with the same parameters
571  * and divs as the context, the dimensions of the context as input
572  * dimensions and a number of output dimensions that is equal to
573  * the number of output dimensions in the input map.
574  *
575  * The constraints and divs of the context are simply copied
576  * from "dom".  For each row
577  *      x = c + e(y)
578  * an equality
579  *      c + e(y) - d x = 0
580  * is added, with d the common denominator of M.
581  */
582 static void sol_map_add(struct isl_sol_map *sol,
583         struct isl_basic_set *dom, struct isl_mat *M)
584 {
585         int i;
586         struct isl_basic_map *bmap = NULL;
587         isl_basic_set *context_bset;
588         unsigned n_eq;
589         unsigned n_ineq;
590         unsigned nparam;
591         unsigned total;
592         unsigned n_div;
593         unsigned n_out;
594
595         if (sol->sol.error || !dom || !M)
596                 goto error;
597
598         n_out = sol->sol.n_out;
599         n_eq = dom->n_eq + n_out;
600         n_ineq = dom->n_ineq;
601         n_div = dom->n_div;
602         nparam = isl_basic_set_total_dim(dom) - n_div;
603         total = isl_map_dim(sol->map, isl_dim_all);
604         bmap = isl_basic_map_alloc_dim(isl_map_get_dim(sol->map),
605                                         n_div, n_eq, 2 * n_div + n_ineq);
606         if (!bmap)
607                 goto error;
608         if (sol->sol.rational)
609                 ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
610         for (i = 0; i < dom->n_div; ++i) {
611                 int k = isl_basic_map_alloc_div(bmap);
612                 if (k < 0)
613                         goto error;
614                 isl_seq_cpy(bmap->div[k], dom->div[i], 1 + 1 + nparam);
615                 isl_seq_clr(bmap->div[k] + 1 + 1 + nparam, total - nparam);
616                 isl_seq_cpy(bmap->div[k] + 1 + 1 + total,
617                             dom->div[i] + 1 + 1 + nparam, i);
618         }
619         for (i = 0; i < dom->n_eq; ++i) {
620                 int k = isl_basic_map_alloc_equality(bmap);
621                 if (k < 0)
622                         goto error;
623                 isl_seq_cpy(bmap->eq[k], dom->eq[i], 1 + nparam);
624                 isl_seq_clr(bmap->eq[k] + 1 + nparam, total - nparam);
625                 isl_seq_cpy(bmap->eq[k] + 1 + total,
626                             dom->eq[i] + 1 + nparam, n_div);
627         }
628         for (i = 0; i < dom->n_ineq; ++i) {
629                 int k = isl_basic_map_alloc_inequality(bmap);
630                 if (k < 0)
631                         goto error;
632                 isl_seq_cpy(bmap->ineq[k], dom->ineq[i], 1 + nparam);
633                 isl_seq_clr(bmap->ineq[k] + 1 + nparam, total - nparam);
634                 isl_seq_cpy(bmap->ineq[k] + 1 + total,
635                         dom->ineq[i] + 1 + nparam, n_div);
636         }
637         for (i = 0; i < M->n_row - 1; ++i) {
638                 int k = isl_basic_map_alloc_equality(bmap);
639                 if (k < 0)
640                         goto error;
641                 isl_seq_cpy(bmap->eq[k], M->row[1 + i], 1 + nparam);
642                 isl_seq_clr(bmap->eq[k] + 1 + nparam, n_out);
643                 isl_int_neg(bmap->eq[k][1 + nparam + i], M->row[0][0]);
644                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + n_out,
645                             M->row[1 + i] + 1 + nparam, n_div);
646         }
647         bmap = isl_basic_map_simplify(bmap);
648         bmap = isl_basic_map_finalize(bmap);
649         sol->map = isl_map_grow(sol->map, 1);
650         sol->map = isl_map_add_basic_map(sol->map, bmap);
651         if (!sol->map)
652                 goto error;
653         isl_basic_set_free(dom);
654         isl_mat_free(M);
655         return;
656 error:
657         isl_basic_set_free(dom);
658         isl_mat_free(M);
659         isl_basic_map_free(bmap);
660         sol->sol.error = 1;
661 }
662
663 static void sol_map_add_wrap(struct isl_sol *sol,
664         struct isl_basic_set *dom, struct isl_mat *M)
665 {
666         sol_map_add((struct isl_sol_map *)sol, dom, M);
667 }
668
669
670 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
671  * i.e., the constant term and the coefficients of all variables that
672  * appear in the context tableau.
673  * Note that the coefficient of the big parameter M is NOT copied.
674  * The context tableau may not have a big parameter and even when it
675  * does, it is a different big parameter.
676  */
677 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
678 {
679         int i;
680         unsigned off = 2 + tab->M;
681
682         isl_int_set(line[0], tab->mat->row[row][1]);
683         for (i = 0; i < tab->n_param; ++i) {
684                 if (tab->var[i].is_row)
685                         isl_int_set_si(line[1 + i], 0);
686                 else {
687                         int col = tab->var[i].index;
688                         isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
689                 }
690         }
691         for (i = 0; i < tab->n_div; ++i) {
692                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
693                         isl_int_set_si(line[1 + tab->n_param + i], 0);
694                 else {
695                         int col = tab->var[tab->n_var - tab->n_div + i].index;
696                         isl_int_set(line[1 + tab->n_param + i],
697                                     tab->mat->row[row][off + col]);
698                 }
699         }
700 }
701
702 /* Check if rows "row1" and "row2" have identical "parametric constants",
703  * as explained above.
704  * In this case, we also insist that the coefficients of the big parameter
705  * be the same as the values of the constants will only be the same
706  * if these coefficients are also the same.
707  */
708 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
709 {
710         int i;
711         unsigned off = 2 + tab->M;
712
713         if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
714                 return 0;
715
716         if (tab->M && isl_int_ne(tab->mat->row[row1][2],
717                                  tab->mat->row[row2][2]))
718                 return 0;
719
720         for (i = 0; i < tab->n_param + tab->n_div; ++i) {
721                 int pos = i < tab->n_param ? i :
722                         tab->n_var - tab->n_div + i - tab->n_param;
723                 int col;
724
725                 if (tab->var[pos].is_row)
726                         continue;
727                 col = tab->var[pos].index;
728                 if (isl_int_ne(tab->mat->row[row1][off + col],
729                                tab->mat->row[row2][off + col]))
730                         return 0;
731         }
732         return 1;
733 }
734
735 /* Return an inequality that expresses that the "parametric constant"
736  * should be non-negative.
737  * This function is only called when the coefficient of the big parameter
738  * is equal to zero.
739  */
740 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
741 {
742         struct isl_vec *ineq;
743
744         ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
745         if (!ineq)
746                 return NULL;
747
748         get_row_parameter_line(tab, row, ineq->el);
749         if (ineq)
750                 ineq = isl_vec_normalize(ineq);
751
752         return ineq;
753 }
754
755 /* Return a integer division for use in a parametric cut based on the given row.
756  * In particular, let the parametric constant of the row be
757  *
758  *              \sum_i a_i y_i
759  *
760  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
761  * The div returned is equal to
762  *
763  *              floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
764  */
765 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
766 {
767         struct isl_vec *div;
768
769         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
770         if (!div)
771                 return NULL;
772
773         isl_int_set(div->el[0], tab->mat->row[row][0]);
774         get_row_parameter_line(tab, row, div->el + 1);
775         div = isl_vec_normalize(div);
776         isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
777         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
778
779         return div;
780 }
781
782 /* Return a integer division for use in transferring an integrality constraint
783  * to the context.
784  * In particular, let the parametric constant of the row be
785  *
786  *              \sum_i a_i y_i
787  *
788  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
789  * The the returned div is equal to
790  *
791  *              floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
792  */
793 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
794 {
795         struct isl_vec *div;
796
797         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
798         if (!div)
799                 return NULL;
800
801         isl_int_set(div->el[0], tab->mat->row[row][0]);
802         get_row_parameter_line(tab, row, div->el + 1);
803         div = isl_vec_normalize(div);
804         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
805
806         return div;
807 }
808
809 /* Construct and return an inequality that expresses an upper bound
810  * on the given div.
811  * In particular, if the div is given by
812  *
813  *      d = floor(e/m)
814  *
815  * then the inequality expresses
816  *
817  *      m d <= e
818  */
819 static struct isl_vec *ineq_for_div(struct isl_basic_set *bset, unsigned div)
820 {
821         unsigned total;
822         unsigned div_pos;
823         struct isl_vec *ineq;
824
825         if (!bset)
826                 return NULL;
827
828         total = isl_basic_set_total_dim(bset);
829         div_pos = 1 + total - bset->n_div + div;
830
831         ineq = isl_vec_alloc(bset->ctx, 1 + total);
832         if (!ineq)
833                 return NULL;
834
835         isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
836         isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
837         return ineq;
838 }
839
840 /* Given a row in the tableau and a div that was created
841  * using get_row_split_div and that been constrained to equality, i.e.,
842  *
843  *              d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
844  *
845  * replace the expression "\sum_i {a_i} y_i" in the row by d,
846  * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
847  * The coefficients of the non-parameters in the tableau have been
848  * verified to be integral.  We can therefore simply replace coefficient b
849  * by floor(b).  For the coefficients of the parameters we have
850  * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
851  * floor(b) = b.
852  */
853 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
854 {
855         isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
856                         tab->mat->row[row][0], 1 + tab->M + tab->n_col);
857
858         isl_int_set_si(tab->mat->row[row][0], 1);
859
860         if (tab->var[tab->n_var - tab->n_div + div].is_row) {
861                 int drow = tab->var[tab->n_var - tab->n_div + div].index;
862
863                 isl_assert(tab->mat->ctx,
864                         isl_int_is_one(tab->mat->row[drow][0]), goto error);
865                 isl_seq_combine(tab->mat->row[row] + 1,
866                         tab->mat->ctx->one, tab->mat->row[row] + 1,
867                         tab->mat->ctx->one, tab->mat->row[drow] + 1,
868                         1 + tab->M + tab->n_col);
869         } else {
870                 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
871
872                 isl_int_set_si(tab->mat->row[row][2 + tab->M + dcol], 1);
873         }
874
875         return tab;
876 error:
877         isl_tab_free(tab);
878         return NULL;
879 }
880
881 /* Check if the (parametric) constant of the given row is obviously
882  * negative, meaning that we don't need to consult the context tableau.
883  * If there is a big parameter and its coefficient is non-zero,
884  * then this coefficient determines the outcome.
885  * Otherwise, we check whether the constant is negative and
886  * all non-zero coefficients of parameters are negative and
887  * belong to non-negative parameters.
888  */
889 static int is_obviously_neg(struct isl_tab *tab, int row)
890 {
891         int i;
892         int col;
893         unsigned off = 2 + tab->M;
894
895         if (tab->M) {
896                 if (isl_int_is_pos(tab->mat->row[row][2]))
897                         return 0;
898                 if (isl_int_is_neg(tab->mat->row[row][2]))
899                         return 1;
900         }
901
902         if (isl_int_is_nonneg(tab->mat->row[row][1]))
903                 return 0;
904         for (i = 0; i < tab->n_param; ++i) {
905                 /* Eliminated parameter */
906                 if (tab->var[i].is_row)
907                         continue;
908                 col = tab->var[i].index;
909                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
910                         continue;
911                 if (!tab->var[i].is_nonneg)
912                         return 0;
913                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
914                         return 0;
915         }
916         for (i = 0; i < tab->n_div; ++i) {
917                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
918                         continue;
919                 col = tab->var[tab->n_var - tab->n_div + i].index;
920                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
921                         continue;
922                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
923                         return 0;
924                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
925                         return 0;
926         }
927         return 1;
928 }
929
930 /* Check if the (parametric) constant of the given row is obviously
931  * non-negative, meaning that we don't need to consult the context tableau.
932  * If there is a big parameter and its coefficient is non-zero,
933  * then this coefficient determines the outcome.
934  * Otherwise, we check whether the constant is non-negative and
935  * all non-zero coefficients of parameters are positive and
936  * belong to non-negative parameters.
937  */
938 static int is_obviously_nonneg(struct isl_tab *tab, int row)
939 {
940         int i;
941         int col;
942         unsigned off = 2 + tab->M;
943
944         if (tab->M) {
945                 if (isl_int_is_pos(tab->mat->row[row][2]))
946                         return 1;
947                 if (isl_int_is_neg(tab->mat->row[row][2]))
948                         return 0;
949         }
950
951         if (isl_int_is_neg(tab->mat->row[row][1]))
952                 return 0;
953         for (i = 0; i < tab->n_param; ++i) {
954                 /* Eliminated parameter */
955                 if (tab->var[i].is_row)
956                         continue;
957                 col = tab->var[i].index;
958                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
959                         continue;
960                 if (!tab->var[i].is_nonneg)
961                         return 0;
962                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
963                         return 0;
964         }
965         for (i = 0; i < tab->n_div; ++i) {
966                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
967                         continue;
968                 col = tab->var[tab->n_var - tab->n_div + i].index;
969                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
970                         continue;
971                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
972                         return 0;
973                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
974                         return 0;
975         }
976         return 1;
977 }
978
979 /* Given a row r and two columns, return the column that would
980  * lead to the lexicographically smallest increment in the sample
981  * solution when leaving the basis in favor of the row.
982  * Pivoting with column c will increment the sample value by a non-negative
983  * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
984  * corresponding to the non-parametric variables.
985  * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
986  * with all other entries in this virtual row equal to zero.
987  * If variable v appears in a row, then a_{v,c} is the element in column c
988  * of that row.
989  *
990  * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
991  * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
992  * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
993  * increment.  Otherwise, it's c2.
994  */
995 static int lexmin_col_pair(struct isl_tab *tab,
996         int row, int col1, int col2, isl_int tmp)
997 {
998         int i;
999         isl_int *tr;
1000
1001         tr = tab->mat->row[row] + 2 + tab->M;
1002
1003         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1004                 int s1, s2;
1005                 isl_int *r;
1006
1007                 if (!tab->var[i].is_row) {
1008                         if (tab->var[i].index == col1)
1009                                 return col2;
1010                         if (tab->var[i].index == col2)
1011                                 return col1;
1012                         continue;
1013                 }
1014
1015                 if (tab->var[i].index == row)
1016                         continue;
1017
1018                 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1019                 s1 = isl_int_sgn(r[col1]);
1020                 s2 = isl_int_sgn(r[col2]);
1021                 if (s1 == 0 && s2 == 0)
1022                         continue;
1023                 if (s1 < s2)
1024                         return col1;
1025                 if (s2 < s1)
1026                         return col2;
1027
1028                 isl_int_mul(tmp, r[col2], tr[col1]);
1029                 isl_int_submul(tmp, r[col1], tr[col2]);
1030                 if (isl_int_is_pos(tmp))
1031                         return col1;
1032                 if (isl_int_is_neg(tmp))
1033                         return col2;
1034         }
1035         return -1;
1036 }
1037
1038 /* Given a row in the tableau, find and return the column that would
1039  * result in the lexicographically smallest, but positive, increment
1040  * in the sample point.
1041  * If there is no such column, then return tab->n_col.
1042  * If anything goes wrong, return -1.
1043  */
1044 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1045 {
1046         int j;
1047         int col = tab->n_col;
1048         isl_int *tr;
1049         isl_int tmp;
1050
1051         tr = tab->mat->row[row] + 2 + tab->M;
1052
1053         isl_int_init(tmp);
1054
1055         for (j = tab->n_dead; j < tab->n_col; ++j) {
1056                 if (tab->col_var[j] >= 0 &&
1057                     (tab->col_var[j] < tab->n_param  ||
1058                     tab->col_var[j] >= tab->n_var - tab->n_div))
1059                         continue;
1060
1061                 if (!isl_int_is_pos(tr[j]))
1062                         continue;
1063
1064                 if (col == tab->n_col)
1065                         col = j;
1066                 else
1067                         col = lexmin_col_pair(tab, row, col, j, tmp);
1068                 isl_assert(tab->mat->ctx, col >= 0, goto error);
1069         }
1070
1071         isl_int_clear(tmp);
1072         return col;
1073 error:
1074         isl_int_clear(tmp);
1075         return -1;
1076 }
1077
1078 /* Return the first known violated constraint, i.e., a non-negative
1079  * constraint that currently has an either obviously negative value
1080  * or a previously determined to be negative value.
1081  *
1082  * If any constraint has a negative coefficient for the big parameter,
1083  * if any, then we return one of these first.
1084  */
1085 static int first_neg(struct isl_tab *tab)
1086 {
1087         int row;
1088
1089         if (tab->M)
1090                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1091                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1092                                 continue;
1093                         if (!isl_int_is_neg(tab->mat->row[row][2]))
1094                                 continue;
1095                         if (tab->row_sign)
1096                                 tab->row_sign[row] = isl_tab_row_neg;
1097                         return row;
1098                 }
1099         for (row = tab->n_redundant; row < tab->n_row; ++row) {
1100                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1101                         continue;
1102                 if (tab->row_sign) {
1103                         if (tab->row_sign[row] == 0 &&
1104                             is_obviously_neg(tab, row))
1105                                 tab->row_sign[row] = isl_tab_row_neg;
1106                         if (tab->row_sign[row] != isl_tab_row_neg)
1107                                 continue;
1108                 } else if (!is_obviously_neg(tab, row))
1109                         continue;
1110                 return row;
1111         }
1112         return -1;
1113 }
1114
1115 /* Resolve all known or obviously violated constraints through pivoting.
1116  * In particular, as long as we can find any violated constraint, we
1117  * look for a pivoting column that would result in the lexicographically
1118  * smallest increment in the sample point.  If there is no such column
1119  * then the tableau is infeasible.
1120  */
1121 static struct isl_tab *restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1122 static struct isl_tab *restore_lexmin(struct isl_tab *tab)
1123 {
1124         int row, col;
1125
1126         if (!tab)
1127                 return NULL;
1128         if (tab->empty)
1129                 return tab;
1130         while ((row = first_neg(tab)) != -1) {
1131                 col = lexmin_pivot_col(tab, row);
1132                 if (col >= tab->n_col) {
1133                         if (isl_tab_mark_empty(tab) < 0)
1134                                 goto error;
1135                         return tab;
1136                 }
1137                 if (col < 0)
1138                         goto error;
1139                 if (isl_tab_pivot(tab, row, col) < 0)
1140                         goto error;
1141         }
1142         return tab;
1143 error:
1144         isl_tab_free(tab);
1145         return NULL;
1146 }
1147
1148 /* Given a row that represents an equality, look for an appropriate
1149  * pivoting column.
1150  * In particular, if there are any non-zero coefficients among
1151  * the non-parameter variables, then we take the last of these
1152  * variables.  Eliminating this variable in terms of the other
1153  * variables and/or parameters does not influence the property
1154  * that all column in the initial tableau are lexicographically
1155  * positive.  The row corresponding to the eliminated variable
1156  * will only have non-zero entries below the diagonal of the
1157  * initial tableau.  That is, we transform
1158  *
1159  *              I                               I
1160  *                1             into            a
1161  *                  I                             I
1162  *
1163  * If there is no such non-parameter variable, then we are dealing with
1164  * pure parameter equality and we pick any parameter with coefficient 1 or -1
1165  * for elimination.  This will ensure that the eliminated parameter
1166  * always has an integer value whenever all the other parameters are integral.
1167  * If there is no such parameter then we return -1.
1168  */
1169 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1170 {
1171         unsigned off = 2 + tab->M;
1172         int i;
1173
1174         for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1175                 int col;
1176                 if (tab->var[i].is_row)
1177                         continue;
1178                 col = tab->var[i].index;
1179                 if (col <= tab->n_dead)
1180                         continue;
1181                 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1182                         return col;
1183         }
1184         for (i = tab->n_dead; i < tab->n_col; ++i) {
1185                 if (isl_int_is_one(tab->mat->row[row][off + i]))
1186                         return i;
1187                 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1188                         return i;
1189         }
1190         return -1;
1191 }
1192
1193 /* Add an equality that is known to be valid to the tableau.
1194  * We first check if we can eliminate a variable or a parameter.
1195  * If not, we add the equality as two inequalities.
1196  * In this case, the equality was a pure parameter equality and there
1197  * is no need to resolve any constraint violations.
1198  */
1199 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1200 {
1201         int i;
1202         int r;
1203
1204         if (!tab)
1205                 return NULL;
1206         r = isl_tab_add_row(tab, eq);
1207         if (r < 0)
1208                 goto error;
1209
1210         r = tab->con[r].index;
1211         i = last_var_col_or_int_par_col(tab, r);
1212         if (i < 0) {
1213                 tab->con[r].is_nonneg = 1;
1214                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1215                         goto error;
1216                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1217                 r = isl_tab_add_row(tab, eq);
1218                 if (r < 0)
1219                         goto error;
1220                 tab->con[r].is_nonneg = 1;
1221                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1222                         goto error;
1223         } else {
1224                 if (isl_tab_pivot(tab, r, i) < 0)
1225                         goto error;
1226                 if (isl_tab_kill_col(tab, i) < 0)
1227                         goto error;
1228                 tab->n_eq++;
1229         }
1230
1231         return tab;
1232 error:
1233         isl_tab_free(tab);
1234         return NULL;
1235 }
1236
1237 /* Check if the given row is a pure constant.
1238  */
1239 static int is_constant(struct isl_tab *tab, int row)
1240 {
1241         unsigned off = 2 + tab->M;
1242
1243         return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1244                                         tab->n_col - tab->n_dead) == -1;
1245 }
1246
1247 /* Add an equality that may or may not be valid to the tableau.
1248  * If the resulting row is a pure constant, then it must be zero.
1249  * Otherwise, the resulting tableau is empty.
1250  *
1251  * If the row is not a pure constant, then we add two inequalities,
1252  * each time checking that they can be satisfied.
1253  * In the end we try to use one of the two constraints to eliminate
1254  * a column.
1255  */
1256 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1257 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1258 {
1259         int r1, r2;
1260         int row;
1261         struct isl_tab_undo *snap;
1262
1263         if (!tab)
1264                 return NULL;
1265         snap = isl_tab_snap(tab);
1266         r1 = isl_tab_add_row(tab, eq);
1267         if (r1 < 0)
1268                 goto error;
1269         tab->con[r1].is_nonneg = 1;
1270         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1271                 goto error;
1272
1273         row = tab->con[r1].index;
1274         if (is_constant(tab, row)) {
1275                 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1276                     (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1277                         if (isl_tab_mark_empty(tab) < 0)
1278                                 goto error;
1279                         return tab;
1280                 }
1281                 if (isl_tab_rollback(tab, snap) < 0)
1282                         goto error;
1283                 return tab;
1284         }
1285
1286         tab = restore_lexmin(tab);
1287         if (!tab || tab->empty)
1288                 return tab;
1289
1290         isl_seq_neg(eq, eq, 1 + tab->n_var);
1291
1292         r2 = isl_tab_add_row(tab, eq);
1293         if (r2 < 0)
1294                 goto error;
1295         tab->con[r2].is_nonneg = 1;
1296         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1297                 goto error;
1298
1299         tab = restore_lexmin(tab);
1300         if (!tab || tab->empty)
1301                 return tab;
1302
1303         if (!tab->con[r1].is_row) {
1304                 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1305                         goto error;
1306         } else if (!tab->con[r2].is_row) {
1307                 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1308                         goto error;
1309         } else if (isl_int_is_zero(tab->mat->row[tab->con[r1].index][1])) {
1310                 unsigned off = 2 + tab->M;
1311                 int i;
1312                 int row = tab->con[r1].index;
1313                 i = isl_seq_first_non_zero(tab->mat->row[row]+off+tab->n_dead,
1314                                                 tab->n_col - tab->n_dead);
1315                 if (i != -1) {
1316                         if (isl_tab_pivot(tab, row, tab->n_dead + i) < 0)
1317                                 goto error;
1318                         if (isl_tab_kill_col(tab, tab->n_dead + i) < 0)
1319                                 goto error;
1320                 }
1321         }
1322
1323         if (tab->bmap) {
1324                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1325                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1326                         goto error;
1327                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1328                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1329                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1330                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1331                         goto error;
1332                 if (!tab->bmap)
1333                         goto error;
1334         }
1335
1336         return tab;
1337 error:
1338         isl_tab_free(tab);
1339         return NULL;
1340 }
1341
1342 /* Add an inequality to the tableau, resolving violations using
1343  * restore_lexmin.
1344  */
1345 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1346 {
1347         int r;
1348
1349         if (!tab)
1350                 return NULL;
1351         if (tab->bmap) {
1352                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1353                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1354                         goto error;
1355                 if (!tab->bmap)
1356                         goto error;
1357         }
1358         r = isl_tab_add_row(tab, ineq);
1359         if (r < 0)
1360                 goto error;
1361         tab->con[r].is_nonneg = 1;
1362         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1363                 goto error;
1364         if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1365                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1366                         goto error;
1367                 return tab;
1368         }
1369
1370         tab = restore_lexmin(tab);
1371         if (tab && !tab->empty && tab->con[r].is_row &&
1372                  isl_tab_row_is_redundant(tab, tab->con[r].index))
1373                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1374                         goto error;
1375         return tab;
1376 error:
1377         isl_tab_free(tab);
1378         return NULL;
1379 }
1380
1381 /* Check if the coefficients of the parameters are all integral.
1382  */
1383 static int integer_parameter(struct isl_tab *tab, int row)
1384 {
1385         int i;
1386         int col;
1387         unsigned off = 2 + tab->M;
1388
1389         for (i = 0; i < tab->n_param; ++i) {
1390                 /* Eliminated parameter */
1391                 if (tab->var[i].is_row)
1392                         continue;
1393                 col = tab->var[i].index;
1394                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1395                                                 tab->mat->row[row][0]))
1396                         return 0;
1397         }
1398         for (i = 0; i < tab->n_div; ++i) {
1399                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1400                         continue;
1401                 col = tab->var[tab->n_var - tab->n_div + i].index;
1402                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1403                                                 tab->mat->row[row][0]))
1404                         return 0;
1405         }
1406         return 1;
1407 }
1408
1409 /* Check if the coefficients of the non-parameter variables are all integral.
1410  */
1411 static int integer_variable(struct isl_tab *tab, int row)
1412 {
1413         int i;
1414         unsigned off = 2 + tab->M;
1415
1416         for (i = tab->n_dead; i < tab->n_col; ++i) {
1417                 if (tab->col_var[i] >= 0 &&
1418                     (tab->col_var[i] < tab->n_param ||
1419                      tab->col_var[i] >= tab->n_var - tab->n_div))
1420                         continue;
1421                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1422                                                 tab->mat->row[row][0]))
1423                         return 0;
1424         }
1425         return 1;
1426 }
1427
1428 /* Check if the constant term is integral.
1429  */
1430 static int integer_constant(struct isl_tab *tab, int row)
1431 {
1432         return isl_int_is_divisible_by(tab->mat->row[row][1],
1433                                         tab->mat->row[row][0]);
1434 }
1435
1436 #define I_CST   1 << 0
1437 #define I_PAR   1 << 1
1438 #define I_VAR   1 << 2
1439
1440 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1441  * that is non-integer and therefore requires a cut and return
1442  * the index of the variable.
1443  * For parametric tableaus, there are three parts in a row,
1444  * the constant, the coefficients of the parameters and the rest.
1445  * For each part, we check whether the coefficients in that part
1446  * are all integral and if so, set the corresponding flag in *f.
1447  * If the constant and the parameter part are integral, then the
1448  * current sample value is integral and no cut is required
1449  * (irrespective of whether the variable part is integral).
1450  */
1451 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1452 {
1453         var = var < 0 ? tab->n_param : var + 1;
1454
1455         for (; var < tab->n_var - tab->n_div; ++var) {
1456                 int flags = 0;
1457                 int row;
1458                 if (!tab->var[var].is_row)
1459                         continue;
1460                 row = tab->var[var].index;
1461                 if (integer_constant(tab, row))
1462                         ISL_FL_SET(flags, I_CST);
1463                 if (integer_parameter(tab, row))
1464                         ISL_FL_SET(flags, I_PAR);
1465                 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1466                         continue;
1467                 if (integer_variable(tab, row))
1468                         ISL_FL_SET(flags, I_VAR);
1469                 *f = flags;
1470                 return var;
1471         }
1472         return -1;
1473 }
1474
1475 /* Check for first (non-parameter) variable that is non-integer and
1476  * therefore requires a cut and return the corresponding row.
1477  * For parametric tableaus, there are three parts in a row,
1478  * the constant, the coefficients of the parameters and the rest.
1479  * For each part, we check whether the coefficients in that part
1480  * are all integral and if so, set the corresponding flag in *f.
1481  * If the constant and the parameter part are integral, then the
1482  * current sample value is integral and no cut is required
1483  * (irrespective of whether the variable part is integral).
1484  */
1485 static int first_non_integer_row(struct isl_tab *tab, int *f)
1486 {
1487         int var = next_non_integer_var(tab, -1, f);
1488
1489         return var < 0 ? -1 : tab->var[var].index;
1490 }
1491
1492 /* Add a (non-parametric) cut to cut away the non-integral sample
1493  * value of the given row.
1494  *
1495  * If the row is given by
1496  *
1497  *      m r = f + \sum_i a_i y_i
1498  *
1499  * then the cut is
1500  *
1501  *      c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1502  *
1503  * The big parameter, if any, is ignored, since it is assumed to be big
1504  * enough to be divisible by any integer.
1505  * If the tableau is actually a parametric tableau, then this function
1506  * is only called when all coefficients of the parameters are integral.
1507  * The cut therefore has zero coefficients for the parameters.
1508  *
1509  * The current value is known to be negative, so row_sign, if it
1510  * exists, is set accordingly.
1511  *
1512  * Return the row of the cut or -1.
1513  */
1514 static int add_cut(struct isl_tab *tab, int row)
1515 {
1516         int i;
1517         int r;
1518         isl_int *r_row;
1519         unsigned off = 2 + tab->M;
1520
1521         if (isl_tab_extend_cons(tab, 1) < 0)
1522                 return -1;
1523         r = isl_tab_allocate_con(tab);
1524         if (r < 0)
1525                 return -1;
1526
1527         r_row = tab->mat->row[tab->con[r].index];
1528         isl_int_set(r_row[0], tab->mat->row[row][0]);
1529         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1530         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1531         isl_int_neg(r_row[1], r_row[1]);
1532         if (tab->M)
1533                 isl_int_set_si(r_row[2], 0);
1534         for (i = 0; i < tab->n_col; ++i)
1535                 isl_int_fdiv_r(r_row[off + i],
1536                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1537
1538         tab->con[r].is_nonneg = 1;
1539         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1540                 return -1;
1541         if (tab->row_sign)
1542                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1543
1544         return tab->con[r].index;
1545 }
1546
1547 /* Given a non-parametric tableau, add cuts until an integer
1548  * sample point is obtained or until the tableau is determined
1549  * to be integer infeasible.
1550  * As long as there is any non-integer value in the sample point,
1551  * we add appropriate cuts, if possible, for each of these
1552  * non-integer values and then resolve the violated
1553  * cut constraints using restore_lexmin.
1554  * If one of the corresponding rows is equal to an integral
1555  * combination of variables/constraints plus a non-integral constant,
1556  * then there is no way to obtain an integer point and we return
1557  * a tableau that is marked empty.
1558  */
1559 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab)
1560 {
1561         int var;
1562         int row;
1563         int flags;
1564
1565         if (!tab)
1566                 return NULL;
1567         if (tab->empty)
1568                 return tab;
1569
1570         while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1571                 do {
1572                         if (ISL_FL_ISSET(flags, I_VAR)) {
1573                                 if (isl_tab_mark_empty(tab) < 0)
1574                                         goto error;
1575                                 return tab;
1576                         }
1577                         row = tab->var[var].index;
1578                         row = add_cut(tab, row);
1579                         if (row < 0)
1580                                 goto error;
1581                 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1582                 tab = restore_lexmin(tab);
1583                 if (!tab || tab->empty)
1584                         break;
1585         }
1586         return tab;
1587 error:
1588         isl_tab_free(tab);
1589         return NULL;
1590 }
1591
1592 /* Check whether all the currently active samples also satisfy the inequality
1593  * "ineq" (treated as an equality if eq is set).
1594  * Remove those samples that do not.
1595  */
1596 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1597 {
1598         int i;
1599         isl_int v;
1600
1601         if (!tab)
1602                 return NULL;
1603
1604         isl_assert(tab->mat->ctx, tab->bmap, goto error);
1605         isl_assert(tab->mat->ctx, tab->samples, goto error);
1606         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1607
1608         isl_int_init(v);
1609         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1610                 int sgn;
1611                 isl_seq_inner_product(ineq, tab->samples->row[i],
1612                                         1 + tab->n_var, &v);
1613                 sgn = isl_int_sgn(v);
1614                 if (eq ? (sgn == 0) : (sgn >= 0))
1615                         continue;
1616                 tab = isl_tab_drop_sample(tab, i);
1617                 if (!tab)
1618                         break;
1619         }
1620         isl_int_clear(v);
1621
1622         return tab;
1623 error:
1624         isl_tab_free(tab);
1625         return NULL;
1626 }
1627
1628 /* Check whether the sample value of the tableau is finite,
1629  * i.e., either the tableau does not use a big parameter, or
1630  * all values of the variables are equal to the big parameter plus
1631  * some constant.  This constant is the actual sample value.
1632  */
1633 static int sample_is_finite(struct isl_tab *tab)
1634 {
1635         int i;
1636
1637         if (!tab->M)
1638                 return 1;
1639
1640         for (i = 0; i < tab->n_var; ++i) {
1641                 int row;
1642                 if (!tab->var[i].is_row)
1643                         return 0;
1644                 row = tab->var[i].index;
1645                 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1646                         return 0;
1647         }
1648         return 1;
1649 }
1650
1651 /* Check if the context tableau of sol has any integer points.
1652  * Leave tab in empty state if no integer point can be found.
1653  * If an integer point can be found and if moreover it is finite,
1654  * then it is added to the list of sample values.
1655  *
1656  * This function is only called when none of the currently active sample
1657  * values satisfies the most recently added constraint.
1658  */
1659 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1660 {
1661         struct isl_tab_undo *snap;
1662         int feasible;
1663
1664         if (!tab)
1665                 return NULL;
1666
1667         snap = isl_tab_snap(tab);
1668         if (isl_tab_push_basis(tab) < 0)
1669                 goto error;
1670
1671         tab = cut_to_integer_lexmin(tab);
1672         if (!tab)
1673                 goto error;
1674
1675         if (!tab->empty && sample_is_finite(tab)) {
1676                 struct isl_vec *sample;
1677
1678                 sample = isl_tab_get_sample_value(tab);
1679
1680                 tab = isl_tab_add_sample(tab, sample);
1681         }
1682
1683         if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1684                 goto error;
1685
1686         return tab;
1687 error:
1688         isl_tab_free(tab);
1689         return NULL;
1690 }
1691
1692 /* Check if any of the currently active sample values satisfies
1693  * the inequality "ineq" (an equality if eq is set).
1694  */
1695 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1696 {
1697         int i;
1698         isl_int v;
1699
1700         if (!tab)
1701                 return -1;
1702
1703         isl_assert(tab->mat->ctx, tab->bmap, return -1);
1704         isl_assert(tab->mat->ctx, tab->samples, return -1);
1705         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1706
1707         isl_int_init(v);
1708         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1709                 int sgn;
1710                 isl_seq_inner_product(ineq, tab->samples->row[i],
1711                                         1 + tab->n_var, &v);
1712                 sgn = isl_int_sgn(v);
1713                 if (eq ? (sgn == 0) : (sgn >= 0))
1714                         break;
1715         }
1716         isl_int_clear(v);
1717
1718         return i < tab->n_sample;
1719 }
1720
1721 /* Add a div specified by "div" to the tableau "tab" and return
1722  * 1 if the div is obviously non-negative.
1723  */
1724 static int context_tab_add_div(struct isl_tab *tab, struct isl_vec *div,
1725         int (*add_ineq)(void *user, isl_int *), void *user)
1726 {
1727         int i;
1728         int r;
1729         struct isl_mat *samples;
1730         int nonneg;
1731
1732         r = isl_tab_add_div(tab, div, add_ineq, user);
1733         if (r < 0)
1734                 return -1;
1735         nonneg = tab->var[r].is_nonneg;
1736         tab->var[r].frozen = 1;
1737
1738         samples = isl_mat_extend(tab->samples,
1739                         tab->n_sample, 1 + tab->n_var);
1740         tab->samples = samples;
1741         if (!samples)
1742                 return -1;
1743         for (i = tab->n_outside; i < samples->n_row; ++i) {
1744                 isl_seq_inner_product(div->el + 1, samples->row[i],
1745                         div->size - 1, &samples->row[i][samples->n_col - 1]);
1746                 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1747                                samples->row[i][samples->n_col - 1], div->el[0]);
1748         }
1749
1750         return nonneg;
1751 }
1752
1753 /* Add a div specified by "div" to both the main tableau and
1754  * the context tableau.  In case of the main tableau, we only
1755  * need to add an extra div.  In the context tableau, we also
1756  * need to express the meaning of the div.
1757  * Return the index of the div or -1 if anything went wrong.
1758  */
1759 static int add_div(struct isl_tab *tab, struct isl_context *context,
1760         struct isl_vec *div)
1761 {
1762         int r;
1763         int nonneg;
1764
1765         if ((nonneg = context->op->add_div(context, div)) < 0)
1766                 goto error;
1767
1768         if (!context->op->is_ok(context))
1769                 goto error;
1770
1771         if (isl_tab_extend_vars(tab, 1) < 0)
1772                 goto error;
1773         r = isl_tab_allocate_var(tab);
1774         if (r < 0)
1775                 goto error;
1776         if (nonneg)
1777                 tab->var[r].is_nonneg = 1;
1778         tab->var[r].frozen = 1;
1779         tab->n_div++;
1780
1781         return tab->n_div - 1;
1782 error:
1783         context->op->invalidate(context);
1784         return -1;
1785 }
1786
1787 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1788 {
1789         int i;
1790         unsigned total = isl_basic_map_total_dim(tab->bmap);
1791
1792         for (i = 0; i < tab->bmap->n_div; ++i) {
1793                 if (isl_int_ne(tab->bmap->div[i][0], denom))
1794                         continue;
1795                 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
1796                         continue;
1797                 return i;
1798         }
1799         return -1;
1800 }
1801
1802 /* Return the index of a div that corresponds to "div".
1803  * We first check if we already have such a div and if not, we create one.
1804  */
1805 static int get_div(struct isl_tab *tab, struct isl_context *context,
1806         struct isl_vec *div)
1807 {
1808         int d;
1809         struct isl_tab *context_tab = context->op->peek_tab(context);
1810
1811         if (!context_tab)
1812                 return -1;
1813
1814         d = find_div(context_tab, div->el + 1, div->el[0]);
1815         if (d != -1)
1816                 return d;
1817
1818         return add_div(tab, context, div);
1819 }
1820
1821 /* Add a parametric cut to cut away the non-integral sample value
1822  * of the give row.
1823  * Let a_i be the coefficients of the constant term and the parameters
1824  * and let b_i be the coefficients of the variables or constraints
1825  * in basis of the tableau.
1826  * Let q be the div q = floor(\sum_i {-a_i} y_i).
1827  *
1828  * The cut is expressed as
1829  *
1830  *      c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1831  *
1832  * If q did not already exist in the context tableau, then it is added first.
1833  * If q is in a column of the main tableau then the "+ q" can be accomplished
1834  * by setting the corresponding entry to the denominator of the constraint.
1835  * If q happens to be in a row of the main tableau, then the corresponding
1836  * row needs to be added instead (taking care of the denominators).
1837  * Note that this is very unlikely, but perhaps not entirely impossible.
1838  *
1839  * The current value of the cut is known to be negative (or at least
1840  * non-positive), so row_sign is set accordingly.
1841  *
1842  * Return the row of the cut or -1.
1843  */
1844 static int add_parametric_cut(struct isl_tab *tab, int row,
1845         struct isl_context *context)
1846 {
1847         struct isl_vec *div;
1848         int d;
1849         int i;
1850         int r;
1851         isl_int *r_row;
1852         int col;
1853         int n;
1854         unsigned off = 2 + tab->M;
1855
1856         if (!context)
1857                 return -1;
1858
1859         div = get_row_parameter_div(tab, row);
1860         if (!div)
1861                 return -1;
1862
1863         n = tab->n_div;
1864         d = context->op->get_div(context, tab, div);
1865         if (d < 0)
1866                 return -1;
1867
1868         if (isl_tab_extend_cons(tab, 1) < 0)
1869                 return -1;
1870         r = isl_tab_allocate_con(tab);
1871         if (r < 0)
1872                 return -1;
1873
1874         r_row = tab->mat->row[tab->con[r].index];
1875         isl_int_set(r_row[0], tab->mat->row[row][0]);
1876         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1877         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1878         isl_int_neg(r_row[1], r_row[1]);
1879         if (tab->M)
1880                 isl_int_set_si(r_row[2], 0);
1881         for (i = 0; i < tab->n_param; ++i) {
1882                 if (tab->var[i].is_row)
1883                         continue;
1884                 col = tab->var[i].index;
1885                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1886                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1887                                 tab->mat->row[row][0]);
1888                 isl_int_neg(r_row[off + col], r_row[off + col]);
1889         }
1890         for (i = 0; i < tab->n_div; ++i) {
1891                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1892                         continue;
1893                 col = tab->var[tab->n_var - tab->n_div + i].index;
1894                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1895                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1896                                 tab->mat->row[row][0]);
1897                 isl_int_neg(r_row[off + col], r_row[off + col]);
1898         }
1899         for (i = 0; i < tab->n_col; ++i) {
1900                 if (tab->col_var[i] >= 0 &&
1901                     (tab->col_var[i] < tab->n_param ||
1902                      tab->col_var[i] >= tab->n_var - tab->n_div))
1903                         continue;
1904                 isl_int_fdiv_r(r_row[off + i],
1905                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1906         }
1907         if (tab->var[tab->n_var - tab->n_div + d].is_row) {
1908                 isl_int gcd;
1909                 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
1910                 isl_int_init(gcd);
1911                 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
1912                 isl_int_divexact(r_row[0], r_row[0], gcd);
1913                 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
1914                 isl_seq_combine(r_row + 1, gcd, r_row + 1,
1915                                 r_row[0], tab->mat->row[d_row] + 1,
1916                                 off - 1 + tab->n_col);
1917                 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
1918                 isl_int_clear(gcd);
1919         } else {
1920                 col = tab->var[tab->n_var - tab->n_div + d].index;
1921                 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
1922         }
1923
1924         tab->con[r].is_nonneg = 1;
1925         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1926                 return -1;
1927         if (tab->row_sign)
1928                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1929
1930         isl_vec_free(div);
1931
1932         row = tab->con[r].index;
1933
1934         if (d >= n && context->op->detect_equalities(context, tab) < 0)
1935                 return -1;
1936
1937         return row;
1938 }
1939
1940 /* Construct a tableau for bmap that can be used for computing
1941  * the lexicographic minimum (or maximum) of bmap.
1942  * If not NULL, then dom is the domain where the minimum
1943  * should be computed.  In this case, we set up a parametric
1944  * tableau with row signs (initialized to "unknown").
1945  * If M is set, then the tableau will use a big parameter.
1946  * If max is set, then a maximum should be computed instead of a minimum.
1947  * This means that for each variable x, the tableau will contain the variable
1948  * x' = M - x, rather than x' = M + x.  This in turn means that the coefficient
1949  * of the variables in all constraints are negated prior to adding them
1950  * to the tableau.
1951  */
1952 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
1953         struct isl_basic_set *dom, unsigned M, int max)
1954 {
1955         int i;
1956         struct isl_tab *tab;
1957
1958         tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
1959                             isl_basic_map_total_dim(bmap), M);
1960         if (!tab)
1961                 return NULL;
1962
1963         tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
1964         if (dom) {
1965                 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
1966                 tab->n_div = dom->n_div;
1967                 tab->row_sign = isl_calloc_array(bmap->ctx,
1968                                         enum isl_tab_row_sign, tab->mat->n_row);
1969                 if (!tab->row_sign)
1970                         goto error;
1971         }
1972         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
1973                 if (isl_tab_mark_empty(tab) < 0)
1974                         goto error;
1975                 return tab;
1976         }
1977
1978         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1979                 tab->var[i].is_nonneg = 1;
1980                 tab->var[i].frozen = 1;
1981         }
1982         for (i = 0; i < bmap->n_eq; ++i) {
1983                 if (max)
1984                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1985                                     bmap->eq[i] + 1 + tab->n_param,
1986                                     tab->n_var - tab->n_param - tab->n_div);
1987                 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
1988                 if (max)
1989                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1990                                     bmap->eq[i] + 1 + tab->n_param,
1991                                     tab->n_var - tab->n_param - tab->n_div);
1992                 if (!tab || tab->empty)
1993                         return tab;
1994         }
1995         if (bmap->n_eq)
1996                 tab = restore_lexmin(tab);
1997         for (i = 0; i < bmap->n_ineq; ++i) {
1998                 if (max)
1999                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2000                                     bmap->ineq[i] + 1 + tab->n_param,
2001                                     tab->n_var - tab->n_param - tab->n_div);
2002                 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2003                 if (max)
2004                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2005                                     bmap->ineq[i] + 1 + tab->n_param,
2006                                     tab->n_var - tab->n_param - tab->n_div);
2007                 if (!tab || tab->empty)
2008                         return tab;
2009         }
2010         return tab;
2011 error:
2012         isl_tab_free(tab);
2013         return NULL;
2014 }
2015
2016 /* Given a main tableau where more than one row requires a split,
2017  * determine and return the "best" row to split on.
2018  *
2019  * Given two rows in the main tableau, if the inequality corresponding
2020  * to the first row is redundant with respect to that of the second row
2021  * in the current tableau, then it is better to split on the second row,
2022  * since in the positive part, both row will be positive.
2023  * (In the negative part a pivot will have to be performed and just about
2024  * anything can happen to the sign of the other row.)
2025  *
2026  * As a simple heuristic, we therefore select the row that makes the most
2027  * of the other rows redundant.
2028  *
2029  * Perhaps it would also be useful to look at the number of constraints
2030  * that conflict with any given constraint.
2031  */
2032 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2033 {
2034         struct isl_tab_undo *snap;
2035         int split;
2036         int row;
2037         int best = -1;
2038         int best_r;
2039
2040         if (isl_tab_extend_cons(context_tab, 2) < 0)
2041                 return -1;
2042
2043         snap = isl_tab_snap(context_tab);
2044
2045         for (split = tab->n_redundant; split < tab->n_row; ++split) {
2046                 struct isl_tab_undo *snap2;
2047                 struct isl_vec *ineq = NULL;
2048                 int r = 0;
2049                 int ok;
2050
2051                 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2052                         continue;
2053                 if (tab->row_sign[split] != isl_tab_row_any)
2054                         continue;
2055
2056                 ineq = get_row_parameter_ineq(tab, split);
2057                 if (!ineq)
2058                         return -1;
2059                 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2060                 isl_vec_free(ineq);
2061                 if (!ok)
2062                         return -1;
2063
2064                 snap2 = isl_tab_snap(context_tab);
2065
2066                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2067                         struct isl_tab_var *var;
2068
2069                         if (row == split)
2070                                 continue;
2071                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2072                                 continue;
2073                         if (tab->row_sign[row] != isl_tab_row_any)
2074                                 continue;
2075
2076                         ineq = get_row_parameter_ineq(tab, row);
2077                         if (!ineq)
2078                                 return -1;
2079                         ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2080                         isl_vec_free(ineq);
2081                         if (!ok)
2082                                 return -1;
2083                         var = &context_tab->con[context_tab->n_con - 1];
2084                         if (!context_tab->empty &&
2085                             !isl_tab_min_at_most_neg_one(context_tab, var))
2086                                 r++;
2087                         if (isl_tab_rollback(context_tab, snap2) < 0)
2088                                 return -1;
2089                 }
2090                 if (best == -1 || r > best_r) {
2091                         best = split;
2092                         best_r = r;
2093                 }
2094                 if (isl_tab_rollback(context_tab, snap) < 0)
2095                         return -1;
2096         }
2097
2098         return best;
2099 }
2100
2101 static struct isl_basic_set *context_lex_peek_basic_set(
2102         struct isl_context *context)
2103 {
2104         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2105         if (!clex->tab)
2106                 return NULL;
2107         return isl_tab_peek_bset(clex->tab);
2108 }
2109
2110 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2111 {
2112         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2113         return clex->tab;
2114 }
2115
2116 static void context_lex_extend(struct isl_context *context, int n)
2117 {
2118         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2119         if (!clex->tab)
2120                 return;
2121         if (isl_tab_extend_cons(clex->tab, n) >= 0)
2122                 return;
2123         isl_tab_free(clex->tab);
2124         clex->tab = NULL;
2125 }
2126
2127 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2128                 int check, int update)
2129 {
2130         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2131         if (isl_tab_extend_cons(clex->tab, 2) < 0)
2132                 goto error;
2133         clex->tab = add_lexmin_eq(clex->tab, eq);
2134         if (check) {
2135                 int v = tab_has_valid_sample(clex->tab, eq, 1);
2136                 if (v < 0)
2137                         goto error;
2138                 if (!v)
2139                         clex->tab = check_integer_feasible(clex->tab);
2140         }
2141         if (update)
2142                 clex->tab = check_samples(clex->tab, eq, 1);
2143         return;
2144 error:
2145         isl_tab_free(clex->tab);
2146         clex->tab = NULL;
2147 }
2148
2149 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2150                 int check, int update)
2151 {
2152         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2153         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2154                 goto error;
2155         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2156         if (check) {
2157                 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2158                 if (v < 0)
2159                         goto error;
2160                 if (!v)
2161                         clex->tab = check_integer_feasible(clex->tab);
2162         }
2163         if (update)
2164                 clex->tab = check_samples(clex->tab, ineq, 0);
2165         return;
2166 error:
2167         isl_tab_free(clex->tab);
2168         clex->tab = NULL;
2169 }
2170
2171 static int context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2172 {
2173         struct isl_context *context = (struct isl_context *)user;
2174         context_lex_add_ineq(context, ineq, 0, 0);
2175         return context->op->is_ok(context) ? 0 : -1;
2176 }
2177
2178 /* Check which signs can be obtained by "ineq" on all the currently
2179  * active sample values.  See row_sign for more information.
2180  */
2181 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2182         int strict)
2183 {
2184         int i;
2185         int sgn;
2186         isl_int tmp;
2187         enum isl_tab_row_sign res = isl_tab_row_unknown;
2188
2189         isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2190         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2191                         return isl_tab_row_unknown);
2192
2193         isl_int_init(tmp);
2194         for (i = tab->n_outside; i < tab->n_sample; ++i) {
2195                 isl_seq_inner_product(tab->samples->row[i], ineq,
2196                                         1 + tab->n_var, &tmp);
2197                 sgn = isl_int_sgn(tmp);
2198                 if (sgn > 0 || (sgn == 0 && strict)) {
2199                         if (res == isl_tab_row_unknown)
2200                                 res = isl_tab_row_pos;
2201                         if (res == isl_tab_row_neg)
2202                                 res = isl_tab_row_any;
2203                 }
2204                 if (sgn < 0) {
2205                         if (res == isl_tab_row_unknown)
2206                                 res = isl_tab_row_neg;
2207                         if (res == isl_tab_row_pos)
2208                                 res = isl_tab_row_any;
2209                 }
2210                 if (res == isl_tab_row_any)
2211                         break;
2212         }
2213         isl_int_clear(tmp);
2214
2215         return res;
2216 }
2217
2218 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2219                         isl_int *ineq, int strict)
2220 {
2221         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2222         return tab_ineq_sign(clex->tab, ineq, strict);
2223 }
2224
2225 /* Check whether "ineq" can be added to the tableau without rendering
2226  * it infeasible.
2227  */
2228 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2229 {
2230         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2231         struct isl_tab_undo *snap;
2232         int feasible;
2233
2234         if (!clex->tab)
2235                 return -1;
2236
2237         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2238                 return -1;
2239
2240         snap = isl_tab_snap(clex->tab);
2241         if (isl_tab_push_basis(clex->tab) < 0)
2242                 return -1;
2243         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2244         clex->tab = check_integer_feasible(clex->tab);
2245         if (!clex->tab)
2246                 return -1;
2247         feasible = !clex->tab->empty;
2248         if (isl_tab_rollback(clex->tab, snap) < 0)
2249                 return -1;
2250
2251         return feasible;
2252 }
2253
2254 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2255                 struct isl_vec *div)
2256 {
2257         return get_div(tab, context, div);
2258 }
2259
2260 static int context_lex_add_div(struct isl_context *context, struct isl_vec *div)
2261 {
2262         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2263         return context_tab_add_div(clex->tab, div,
2264                                         context_lex_add_ineq_wrap, context);
2265 }
2266
2267 static int context_lex_detect_equalities(struct isl_context *context,
2268                 struct isl_tab *tab)
2269 {
2270         return 0;
2271 }
2272
2273 static int context_lex_best_split(struct isl_context *context,
2274                 struct isl_tab *tab)
2275 {
2276         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2277         struct isl_tab_undo *snap;
2278         int r;
2279
2280         snap = isl_tab_snap(clex->tab);
2281         if (isl_tab_push_basis(clex->tab) < 0)
2282                 return -1;
2283         r = best_split(tab, clex->tab);
2284
2285         if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2286                 return -1;
2287
2288         return r;
2289 }
2290
2291 static int context_lex_is_empty(struct isl_context *context)
2292 {
2293         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2294         if (!clex->tab)
2295                 return -1;
2296         return clex->tab->empty;
2297 }
2298
2299 static void *context_lex_save(struct isl_context *context)
2300 {
2301         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2302         struct isl_tab_undo *snap;
2303
2304         snap = isl_tab_snap(clex->tab);
2305         if (isl_tab_push_basis(clex->tab) < 0)
2306                 return NULL;
2307         if (isl_tab_save_samples(clex->tab) < 0)
2308                 return NULL;
2309
2310         return snap;
2311 }
2312
2313 static void context_lex_restore(struct isl_context *context, void *save)
2314 {
2315         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2316         if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2317                 isl_tab_free(clex->tab);
2318                 clex->tab = NULL;
2319         }
2320 }
2321
2322 static int context_lex_is_ok(struct isl_context *context)
2323 {
2324         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2325         return !!clex->tab;
2326 }
2327
2328 /* For each variable in the context tableau, check if the variable can
2329  * only attain non-negative values.  If so, mark the parameter as non-negative
2330  * in the main tableau.  This allows for a more direct identification of some
2331  * cases of violated constraints.
2332  */
2333 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2334         struct isl_tab *context_tab)
2335 {
2336         int i;
2337         struct isl_tab_undo *snap;
2338         struct isl_vec *ineq = NULL;
2339         struct isl_tab_var *var;
2340         int n;
2341
2342         if (context_tab->n_var == 0)
2343                 return tab;
2344
2345         ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2346         if (!ineq)
2347                 goto error;
2348
2349         if (isl_tab_extend_cons(context_tab, 1) < 0)
2350                 goto error;
2351
2352         snap = isl_tab_snap(context_tab);
2353
2354         n = 0;
2355         isl_seq_clr(ineq->el, ineq->size);
2356         for (i = 0; i < context_tab->n_var; ++i) {
2357                 isl_int_set_si(ineq->el[1 + i], 1);
2358                 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2359                         goto error;
2360                 var = &context_tab->con[context_tab->n_con - 1];
2361                 if (!context_tab->empty &&
2362                     !isl_tab_min_at_most_neg_one(context_tab, var)) {
2363                         int j = i;
2364                         if (i >= tab->n_param)
2365                                 j = i - tab->n_param + tab->n_var - tab->n_div;
2366                         tab->var[j].is_nonneg = 1;
2367                         n++;
2368                 }
2369                 isl_int_set_si(ineq->el[1 + i], 0);
2370                 if (isl_tab_rollback(context_tab, snap) < 0)
2371                         goto error;
2372         }
2373
2374         if (context_tab->M && n == context_tab->n_var) {
2375                 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2376                 context_tab->M = 0;
2377         }
2378
2379         isl_vec_free(ineq);
2380         return tab;
2381 error:
2382         isl_vec_free(ineq);
2383         isl_tab_free(tab);
2384         return NULL;
2385 }
2386
2387 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2388         struct isl_context *context, struct isl_tab *tab)
2389 {
2390         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2391         struct isl_tab_undo *snap;
2392
2393         if (!tab)
2394                 return NULL;
2395
2396         snap = isl_tab_snap(clex->tab);
2397         if (isl_tab_push_basis(clex->tab) < 0)
2398                 goto error;
2399
2400         tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2401
2402         if (isl_tab_rollback(clex->tab, snap) < 0)
2403                 goto error;
2404
2405         return tab;
2406 error:
2407         isl_tab_free(tab);
2408         return NULL;
2409 }
2410
2411 static void context_lex_invalidate(struct isl_context *context)
2412 {
2413         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2414         isl_tab_free(clex->tab);
2415         clex->tab = NULL;
2416 }
2417
2418 static void context_lex_free(struct isl_context *context)
2419 {
2420         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2421         isl_tab_free(clex->tab);
2422         free(clex);
2423 }
2424
2425 struct isl_context_op isl_context_lex_op = {
2426         context_lex_detect_nonnegative_parameters,
2427         context_lex_peek_basic_set,
2428         context_lex_peek_tab,
2429         context_lex_add_eq,
2430         context_lex_add_ineq,
2431         context_lex_ineq_sign,
2432         context_lex_test_ineq,
2433         context_lex_get_div,
2434         context_lex_add_div,
2435         context_lex_detect_equalities,
2436         context_lex_best_split,
2437         context_lex_is_empty,
2438         context_lex_is_ok,
2439         context_lex_save,
2440         context_lex_restore,
2441         context_lex_invalidate,
2442         context_lex_free,
2443 };
2444
2445 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
2446 {
2447         struct isl_tab *tab;
2448
2449         bset = isl_basic_set_cow(bset);
2450         if (!bset)
2451                 return NULL;
2452         tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
2453         if (!tab)
2454                 goto error;
2455         if (isl_tab_track_bset(tab, bset) < 0)
2456                 goto error;
2457         tab = isl_tab_init_samples(tab);
2458         return tab;
2459 error:
2460         isl_basic_set_free(bset);
2461         return NULL;
2462 }
2463
2464 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2465 {
2466         struct isl_context_lex *clex;
2467
2468         if (!dom)
2469                 return NULL;
2470
2471         clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2472         if (!clex)
2473                 return NULL;
2474
2475         clex->context.op = &isl_context_lex_op;
2476
2477         clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2478         clex->tab = restore_lexmin(clex->tab);
2479         clex->tab = check_integer_feasible(clex->tab);
2480         if (!clex->tab)
2481                 goto error;
2482
2483         return &clex->context;
2484 error:
2485         clex->context.op->free(&clex->context);
2486         return NULL;
2487 }
2488
2489 struct isl_context_gbr {
2490         struct isl_context context;
2491         struct isl_tab *tab;
2492         struct isl_tab *shifted;
2493         struct isl_tab *cone;
2494 };
2495
2496 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2497         struct isl_context *context, struct isl_tab *tab)
2498 {
2499         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2500         if (!tab)
2501                 return NULL;
2502         return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2503 }
2504
2505 static struct isl_basic_set *context_gbr_peek_basic_set(
2506         struct isl_context *context)
2507 {
2508         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2509         if (!cgbr->tab)
2510                 return NULL;
2511         return isl_tab_peek_bset(cgbr->tab);
2512 }
2513
2514 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2515 {
2516         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2517         return cgbr->tab;
2518 }
2519
2520 /* Initialize the "shifted" tableau of the context, which
2521  * contains the constraints of the original tableau shifted
2522  * by the sum of all negative coefficients.  This ensures
2523  * that any rational point in the shifted tableau can
2524  * be rounded up to yield an integer point in the original tableau.
2525  */
2526 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2527 {
2528         int i, j;
2529         struct isl_vec *cst;
2530         struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2531         unsigned dim = isl_basic_set_total_dim(bset);
2532
2533         cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2534         if (!cst)
2535                 return;
2536
2537         for (i = 0; i < bset->n_ineq; ++i) {
2538                 isl_int_set(cst->el[i], bset->ineq[i][0]);
2539                 for (j = 0; j < dim; ++j) {
2540                         if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2541                                 continue;
2542                         isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2543                                     bset->ineq[i][1 + j]);
2544                 }
2545         }
2546
2547         cgbr->shifted = isl_tab_from_basic_set(bset);
2548
2549         for (i = 0; i < bset->n_ineq; ++i)
2550                 isl_int_set(bset->ineq[i][0], cst->el[i]);
2551
2552         isl_vec_free(cst);
2553 }
2554
2555 /* Check if the shifted tableau is non-empty, and if so
2556  * use the sample point to construct an integer point
2557  * of the context tableau.
2558  */
2559 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2560 {
2561         struct isl_vec *sample;
2562
2563         if (!cgbr->shifted)
2564                 gbr_init_shifted(cgbr);
2565         if (!cgbr->shifted)
2566                 return NULL;
2567         if (cgbr->shifted->empty)
2568                 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2569
2570         sample = isl_tab_get_sample_value(cgbr->shifted);
2571         sample = isl_vec_ceil(sample);
2572
2573         return sample;
2574 }
2575
2576 static struct isl_basic_set *drop_constant_terms(struct isl_basic_set *bset)
2577 {
2578         int i;
2579
2580         if (!bset)
2581                 return NULL;
2582
2583         for (i = 0; i < bset->n_eq; ++i)
2584                 isl_int_set_si(bset->eq[i][0], 0);
2585
2586         for (i = 0; i < bset->n_ineq; ++i)
2587                 isl_int_set_si(bset->ineq[i][0], 0);
2588
2589         return bset;
2590 }
2591
2592 static int use_shifted(struct isl_context_gbr *cgbr)
2593 {
2594         return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2595 }
2596
2597 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2598 {
2599         struct isl_basic_set *bset;
2600         struct isl_basic_set *cone;
2601
2602         if (isl_tab_sample_is_integer(cgbr->tab))
2603                 return isl_tab_get_sample_value(cgbr->tab);
2604
2605         if (use_shifted(cgbr)) {
2606                 struct isl_vec *sample;
2607
2608                 sample = gbr_get_shifted_sample(cgbr);
2609                 if (!sample || sample->size > 0)
2610                         return sample;
2611
2612                 isl_vec_free(sample);
2613         }
2614
2615         if (!cgbr->cone) {
2616                 bset = isl_tab_peek_bset(cgbr->tab);
2617                 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2618                 if (!cgbr->cone)
2619                         return NULL;
2620                 if (isl_tab_track_bset(cgbr->cone, isl_basic_set_dup(bset)) < 0)
2621                         return NULL;
2622         }
2623         if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2624                 return NULL;
2625
2626         if (cgbr->cone->n_dead == cgbr->cone->n_col) {
2627                 struct isl_vec *sample;
2628                 struct isl_tab_undo *snap;
2629
2630                 if (cgbr->tab->basis) {
2631                         if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
2632                                 isl_mat_free(cgbr->tab->basis);
2633                                 cgbr->tab->basis = NULL;
2634                         }
2635                         cgbr->tab->n_zero = 0;
2636                         cgbr->tab->n_unbounded = 0;
2637                 }
2638
2639                 snap = isl_tab_snap(cgbr->tab);
2640
2641                 sample = isl_tab_sample(cgbr->tab);
2642
2643                 if (isl_tab_rollback(cgbr->tab, snap) < 0) {
2644                         isl_vec_free(sample);
2645                         return NULL;
2646                 }
2647
2648                 return sample;
2649         }
2650
2651         cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
2652         cone = drop_constant_terms(cone);
2653         cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
2654         cone = isl_basic_set_underlying_set(cone);
2655         cone = isl_basic_set_gauss(cone, NULL);
2656
2657         bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
2658         bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
2659         bset = isl_basic_set_underlying_set(bset);
2660         bset = isl_basic_set_gauss(bset, NULL);
2661
2662         return isl_basic_set_sample_with_cone(bset, cone);
2663 }
2664
2665 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
2666 {
2667         struct isl_vec *sample;
2668
2669         if (!cgbr->tab)
2670                 return;
2671
2672         if (cgbr->tab->empty)
2673                 return;
2674
2675         sample = gbr_get_sample(cgbr);
2676         if (!sample)
2677                 goto error;
2678
2679         if (sample->size == 0) {
2680                 isl_vec_free(sample);
2681                 if (isl_tab_mark_empty(cgbr->tab) < 0)
2682                         goto error;
2683                 return;
2684         }
2685
2686         cgbr->tab = isl_tab_add_sample(cgbr->tab, sample);
2687
2688         return;
2689 error:
2690         isl_tab_free(cgbr->tab);
2691         cgbr->tab = NULL;
2692 }
2693
2694 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
2695 {
2696         int r;
2697
2698         if (!tab)
2699                 return NULL;
2700
2701         if (isl_tab_extend_cons(tab, 2) < 0)
2702                 goto error;
2703
2704         if (isl_tab_add_eq(tab, eq) < 0)
2705                 goto error;
2706
2707         return tab;
2708 error:
2709         isl_tab_free(tab);
2710         return NULL;
2711 }
2712
2713 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
2714                 int check, int update)
2715 {
2716         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2717
2718         cgbr->tab = add_gbr_eq(cgbr->tab, eq);
2719
2720         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2721                 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
2722                         goto error;
2723                 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
2724                         goto error;
2725         }
2726
2727         if (check) {
2728                 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
2729                 if (v < 0)
2730                         goto error;
2731                 if (!v)
2732                         check_gbr_integer_feasible(cgbr);
2733         }
2734         if (update)
2735                 cgbr->tab = check_samples(cgbr->tab, eq, 1);
2736         return;
2737 error:
2738         isl_tab_free(cgbr->tab);
2739         cgbr->tab = NULL;
2740 }
2741
2742 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
2743 {
2744         if (!cgbr->tab)
2745                 return;
2746
2747         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2748                 goto error;
2749
2750         if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
2751                 goto error;
2752
2753         if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
2754                 int i;
2755                 unsigned dim;
2756                 dim = isl_basic_map_total_dim(cgbr->tab->bmap);
2757
2758                 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
2759                         goto error;
2760
2761                 for (i = 0; i < dim; ++i) {
2762                         if (!isl_int_is_neg(ineq[1 + i]))
2763                                 continue;
2764                         isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
2765                 }
2766
2767                 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
2768                         goto error;
2769
2770                 for (i = 0; i < dim; ++i) {
2771                         if (!isl_int_is_neg(ineq[1 + i]))
2772                                 continue;
2773                         isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
2774                 }
2775         }
2776
2777         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2778                 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
2779                         goto error;
2780                 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
2781                         goto error;
2782         }
2783
2784         return;
2785 error:
2786         isl_tab_free(cgbr->tab);
2787         cgbr->tab = NULL;
2788 }
2789
2790 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
2791                 int check, int update)
2792 {
2793         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2794
2795         add_gbr_ineq(cgbr, ineq);
2796         if (!cgbr->tab)
2797                 return;
2798
2799         if (check) {
2800                 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
2801                 if (v < 0)
2802                         goto error;
2803                 if (!v)
2804                         check_gbr_integer_feasible(cgbr);
2805         }
2806         if (update)
2807                 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
2808         return;
2809 error:
2810         isl_tab_free(cgbr->tab);
2811         cgbr->tab = NULL;
2812 }
2813
2814 static int context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
2815 {
2816         struct isl_context *context = (struct isl_context *)user;
2817         context_gbr_add_ineq(context, ineq, 0, 0);
2818         return context->op->is_ok(context) ? 0 : -1;
2819 }
2820
2821 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
2822                         isl_int *ineq, int strict)
2823 {
2824         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2825         return tab_ineq_sign(cgbr->tab, ineq, strict);
2826 }
2827
2828 /* Check whether "ineq" can be added to the tableau without rendering
2829  * it infeasible.
2830  */
2831 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
2832 {
2833         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2834         struct isl_tab_undo *snap;
2835         struct isl_tab_undo *shifted_snap = NULL;
2836         struct isl_tab_undo *cone_snap = NULL;
2837         int feasible;
2838
2839         if (!cgbr->tab)
2840                 return -1;
2841
2842         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2843                 return -1;
2844
2845         snap = isl_tab_snap(cgbr->tab);
2846         if (cgbr->shifted)
2847                 shifted_snap = isl_tab_snap(cgbr->shifted);
2848         if (cgbr->cone)
2849                 cone_snap = isl_tab_snap(cgbr->cone);
2850         add_gbr_ineq(cgbr, ineq);
2851         check_gbr_integer_feasible(cgbr);
2852         if (!cgbr->tab)
2853                 return -1;
2854         feasible = !cgbr->tab->empty;
2855         if (isl_tab_rollback(cgbr->tab, snap) < 0)
2856                 return -1;
2857         if (shifted_snap) {
2858                 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
2859                         return -1;
2860         } else if (cgbr->shifted) {
2861                 isl_tab_free(cgbr->shifted);
2862                 cgbr->shifted = NULL;
2863         }
2864         if (cone_snap) {
2865                 if (isl_tab_rollback(cgbr->cone, cone_snap))
2866                         return -1;
2867         } else if (cgbr->cone) {
2868                 isl_tab_free(cgbr->cone);
2869                 cgbr->cone = NULL;
2870         }
2871
2872         return feasible;
2873 }
2874
2875 /* Return the column of the last of the variables associated to
2876  * a column that has a non-zero coefficient.
2877  * This function is called in a context where only coefficients
2878  * of parameters or divs can be non-zero.
2879  */
2880 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
2881 {
2882         int i;
2883         int col;
2884         unsigned dim = tab->n_var - tab->n_param - tab->n_div;
2885
2886         if (tab->n_var == 0)
2887                 return -1;
2888
2889         for (i = tab->n_var - 1; i >= 0; --i) {
2890                 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
2891                         continue;
2892                 if (tab->var[i].is_row)
2893                         continue;
2894                 col = tab->var[i].index;
2895                 if (!isl_int_is_zero(p[col]))
2896                         return col;
2897         }
2898
2899         return -1;
2900 }
2901
2902 /* Look through all the recently added equalities in the context
2903  * to see if we can propagate any of them to the main tableau.
2904  *
2905  * The newly added equalities in the context are encoded as pairs
2906  * of inequalities starting at inequality "first".
2907  *
2908  * We tentatively add each of these equalities to the main tableau
2909  * and if this happens to result in a row with a final coefficient
2910  * that is one or negative one, we use it to kill a column
2911  * in the main tableau.  Otherwise, we discard the tentatively
2912  * added row.
2913  */
2914 static void propagate_equalities(struct isl_context_gbr *cgbr,
2915         struct isl_tab *tab, unsigned first)
2916 {
2917         int i;
2918         struct isl_vec *eq = NULL;
2919
2920         eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
2921         if (!eq)
2922                 goto error;
2923
2924         if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
2925                 goto error;
2926
2927         isl_seq_clr(eq->el + 1 + tab->n_param,
2928                     tab->n_var - tab->n_param - tab->n_div);
2929         for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
2930                 int j;
2931                 int r;
2932                 struct isl_tab_undo *snap;
2933                 snap = isl_tab_snap(tab);
2934
2935                 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
2936                 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
2937                             cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
2938                             tab->n_div);
2939
2940                 r = isl_tab_add_row(tab, eq->el);
2941                 if (r < 0)
2942                         goto error;
2943                 r = tab->con[r].index;
2944                 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
2945                 if (j < 0 || j < tab->n_dead ||
2946                     !isl_int_is_one(tab->mat->row[r][0]) ||
2947                     (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
2948                      !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
2949                         if (isl_tab_rollback(tab, snap) < 0)
2950                                 goto error;
2951                         continue;
2952                 }
2953                 if (isl_tab_pivot(tab, r, j) < 0)
2954                         goto error;
2955                 if (isl_tab_kill_col(tab, j) < 0)
2956                         goto error;
2957
2958                 tab = restore_lexmin(tab);
2959         }
2960
2961         isl_vec_free(eq);
2962
2963         return;
2964 error:
2965         isl_vec_free(eq);
2966         isl_tab_free(cgbr->tab);
2967         cgbr->tab = NULL;
2968 }
2969
2970 static int context_gbr_detect_equalities(struct isl_context *context,
2971         struct isl_tab *tab)
2972 {
2973         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2974         struct isl_ctx *ctx;
2975         int i;
2976         enum isl_lp_result res;
2977         unsigned n_ineq;
2978
2979         ctx = cgbr->tab->mat->ctx;
2980
2981         if (!cgbr->cone) {
2982                 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2983                 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2984                 if (!cgbr->cone)
2985                         goto error;
2986                 if (isl_tab_track_bset(cgbr->cone, isl_basic_set_dup(bset)) < 0)
2987                         goto error;
2988         }
2989         if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2990                 goto error;
2991
2992         n_ineq = cgbr->tab->bmap->n_ineq;
2993         cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
2994         if (cgbr->tab && cgbr->tab->bmap->n_ineq > n_ineq)
2995                 propagate_equalities(cgbr, tab, n_ineq);
2996
2997         return 0;
2998 error:
2999         isl_tab_free(cgbr->tab);
3000         cgbr->tab = NULL;
3001         return -1;
3002 }
3003
3004 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3005                 struct isl_vec *div)
3006 {
3007         return get_div(tab, context, div);
3008 }
3009
3010 static int context_gbr_add_div(struct isl_context *context, struct isl_vec *div)
3011 {
3012         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3013         if (cgbr->cone) {
3014                 int k;
3015
3016                 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3017                         return -1;
3018                 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3019                         return -1;
3020                 if (isl_tab_allocate_var(cgbr->cone) <0)
3021                         return -1;
3022
3023                 cgbr->cone->bmap = isl_basic_map_extend_dim(cgbr->cone->bmap,
3024                         isl_basic_map_get_dim(cgbr->cone->bmap), 1, 0, 2);
3025                 k = isl_basic_map_alloc_div(cgbr->cone->bmap);
3026                 if (k < 0)
3027                         return -1;
3028                 isl_seq_cpy(cgbr->cone->bmap->div[k], div->el, div->size);
3029                 if (isl_tab_push(cgbr->cone, isl_tab_undo_bmap_div) < 0)
3030                         return -1;
3031         }
3032         return context_tab_add_div(cgbr->tab, div,
3033                                         context_gbr_add_ineq_wrap, context);
3034 }
3035
3036 static int context_gbr_best_split(struct isl_context *context,
3037                 struct isl_tab *tab)
3038 {
3039         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3040         struct isl_tab_undo *snap;
3041         int r;
3042
3043         snap = isl_tab_snap(cgbr->tab);
3044         r = best_split(tab, cgbr->tab);
3045
3046         if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3047                 return -1;
3048
3049         return r;
3050 }
3051
3052 static int context_gbr_is_empty(struct isl_context *context)
3053 {
3054         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3055         if (!cgbr->tab)
3056                 return -1;
3057         return cgbr->tab->empty;
3058 }
3059
3060 struct isl_gbr_tab_undo {
3061         struct isl_tab_undo *tab_snap;
3062         struct isl_tab_undo *shifted_snap;
3063         struct isl_tab_undo *cone_snap;
3064 };
3065
3066 static void *context_gbr_save(struct isl_context *context)
3067 {
3068         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3069         struct isl_gbr_tab_undo *snap;
3070
3071         snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3072         if (!snap)
3073                 return NULL;
3074
3075         snap->tab_snap = isl_tab_snap(cgbr->tab);
3076         if (isl_tab_save_samples(cgbr->tab) < 0)
3077                 goto error;
3078
3079         if (cgbr->shifted)
3080                 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3081         else
3082                 snap->shifted_snap = NULL;
3083
3084         if (cgbr->cone)
3085                 snap->cone_snap = isl_tab_snap(cgbr->cone);
3086         else
3087                 snap->cone_snap = NULL;
3088
3089         return snap;
3090 error:
3091         free(snap);
3092         return NULL;
3093 }
3094
3095 static void context_gbr_restore(struct isl_context *context, void *save)
3096 {
3097         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3098         struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3099         if (!snap)
3100                 goto error;
3101         if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0) {
3102                 isl_tab_free(cgbr->tab);
3103                 cgbr->tab = NULL;
3104         }
3105
3106         if (snap->shifted_snap) {
3107                 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3108                         goto error;
3109         } else if (cgbr->shifted) {
3110                 isl_tab_free(cgbr->shifted);
3111                 cgbr->shifted = NULL;
3112         }
3113
3114         if (snap->cone_snap) {
3115                 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3116                         goto error;
3117         } else if (cgbr->cone) {
3118                 isl_tab_free(cgbr->cone);
3119                 cgbr->cone = NULL;
3120         }
3121
3122         free(snap);
3123
3124         return;
3125 error:
3126         free(snap);
3127         isl_tab_free(cgbr->tab);
3128         cgbr->tab = NULL;
3129 }
3130
3131 static int context_gbr_is_ok(struct isl_context *context)
3132 {
3133         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3134         return !!cgbr->tab;
3135 }
3136
3137 static void context_gbr_invalidate(struct isl_context *context)
3138 {
3139         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3140         isl_tab_free(cgbr->tab);
3141         cgbr->tab = NULL;
3142 }
3143
3144 static void context_gbr_free(struct isl_context *context)
3145 {
3146         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3147         isl_tab_free(cgbr->tab);
3148         isl_tab_free(cgbr->shifted);
3149         isl_tab_free(cgbr->cone);
3150         free(cgbr);
3151 }
3152
3153 struct isl_context_op isl_context_gbr_op = {
3154         context_gbr_detect_nonnegative_parameters,
3155         context_gbr_peek_basic_set,
3156         context_gbr_peek_tab,
3157         context_gbr_add_eq,
3158         context_gbr_add_ineq,
3159         context_gbr_ineq_sign,
3160         context_gbr_test_ineq,
3161         context_gbr_get_div,
3162         context_gbr_add_div,
3163         context_gbr_detect_equalities,
3164         context_gbr_best_split,
3165         context_gbr_is_empty,
3166         context_gbr_is_ok,
3167         context_gbr_save,
3168         context_gbr_restore,
3169         context_gbr_invalidate,
3170         context_gbr_free,
3171 };
3172
3173 static struct isl_context *isl_context_gbr_alloc(struct isl_basic_set *dom)
3174 {
3175         struct isl_context_gbr *cgbr;
3176
3177         if (!dom)
3178                 return NULL;
3179
3180         cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3181         if (!cgbr)
3182                 return NULL;
3183
3184         cgbr->context.op = &isl_context_gbr_op;
3185
3186         cgbr->shifted = NULL;
3187         cgbr->cone = NULL;
3188         cgbr->tab = isl_tab_from_basic_set(dom);
3189         cgbr->tab = isl_tab_init_samples(cgbr->tab);
3190         if (!cgbr->tab)
3191                 goto error;
3192         if (isl_tab_track_bset(cgbr->tab,
3193                                 isl_basic_set_cow(isl_basic_set_copy(dom))) < 0)
3194                 goto error;
3195         check_gbr_integer_feasible(cgbr);
3196
3197         return &cgbr->context;
3198 error:
3199         cgbr->context.op->free(&cgbr->context);
3200         return NULL;
3201 }
3202
3203 static struct isl_context *isl_context_alloc(struct isl_basic_set *dom)
3204 {
3205         if (!dom)
3206                 return NULL;
3207
3208         if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3209                 return isl_context_lex_alloc(dom);
3210         else
3211                 return isl_context_gbr_alloc(dom);
3212 }
3213
3214 /* Construct an isl_sol_map structure for accumulating the solution.
3215  * If track_empty is set, then we also keep track of the parts
3216  * of the context where there is no solution.
3217  * If max is set, then we are solving a maximization, rather than
3218  * a minimization problem, which means that the variables in the
3219  * tableau have value "M - x" rather than "M + x".
3220  */
3221 static struct isl_sol_map *sol_map_init(struct isl_basic_map *bmap,
3222         struct isl_basic_set *dom, int track_empty, int max)
3223 {
3224         struct isl_sol_map *sol_map = NULL;
3225
3226         if (!bmap)
3227                 goto error;
3228
3229         sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3230         if (!sol_map)
3231                 goto error;
3232
3233         sol_map->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3234         sol_map->sol.dec_level.callback.run = &sol_dec_level_wrap;
3235         sol_map->sol.dec_level.sol = &sol_map->sol;
3236         sol_map->sol.max = max;
3237         sol_map->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
3238         sol_map->sol.add = &sol_map_add_wrap;
3239         sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3240         sol_map->sol.free = &sol_map_free_wrap;
3241         sol_map->map = isl_map_alloc_dim(isl_basic_map_get_dim(bmap), 1,
3242                                             ISL_MAP_DISJOINT);
3243         if (!sol_map->map)
3244                 goto error;
3245
3246         sol_map->sol.context = isl_context_alloc(dom);
3247         if (!sol_map->sol.context)
3248                 goto error;
3249
3250         if (track_empty) {
3251                 sol_map->empty = isl_set_alloc_dim(isl_basic_set_get_dim(dom),
3252                                                         1, ISL_SET_DISJOINT);
3253                 if (!sol_map->empty)
3254                         goto error;
3255         }
3256
3257         isl_basic_set_free(dom);
3258         return sol_map;
3259 error:
3260         isl_basic_set_free(dom);
3261         sol_map_free(sol_map);
3262         return NULL;
3263 }
3264
3265 /* Check whether all coefficients of (non-parameter) variables
3266  * are non-positive, meaning that no pivots can be performed on the row.
3267  */
3268 static int is_critical(struct isl_tab *tab, int row)
3269 {
3270         int j;
3271         unsigned off = 2 + tab->M;
3272
3273         for (j = tab->n_dead; j < tab->n_col; ++j) {
3274                 if (tab->col_var[j] >= 0 &&
3275                     (tab->col_var[j] < tab->n_param  ||
3276                     tab->col_var[j] >= tab->n_var - tab->n_div))
3277                         continue;
3278
3279                 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3280                         return 0;
3281         }
3282
3283         return 1;
3284 }
3285
3286 /* Check whether the inequality represented by vec is strict over the integers,
3287  * i.e., there are no integer values satisfying the constraint with
3288  * equality.  This happens if the gcd of the coefficients is not a divisor
3289  * of the constant term.  If so, scale the constraint down by the gcd
3290  * of the coefficients.
3291  */
3292 static int is_strict(struct isl_vec *vec)
3293 {
3294         isl_int gcd;
3295         int strict = 0;
3296
3297         isl_int_init(gcd);
3298         isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3299         if (!isl_int_is_one(gcd)) {
3300                 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3301                 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3302                 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3303         }
3304         isl_int_clear(gcd);
3305
3306         return strict;
3307 }
3308
3309 /* Determine the sign of the given row of the main tableau.
3310  * The result is one of
3311  *      isl_tab_row_pos: always non-negative; no pivot needed
3312  *      isl_tab_row_neg: always non-positive; pivot
3313  *      isl_tab_row_any: can be both positive and negative; split
3314  *
3315  * We first handle some simple cases
3316  *      - the row sign may be known already
3317  *      - the row may be obviously non-negative
3318  *      - the parametric constant may be equal to that of another row
3319  *        for which we know the sign.  This sign will be either "pos" or
3320  *        "any".  If it had been "neg" then we would have pivoted before.
3321  *
3322  * If none of these cases hold, we check the value of the row for each
3323  * of the currently active samples.  Based on the signs of these values
3324  * we make an initial determination of the sign of the row.
3325  *
3326  *      all zero                        ->      unk(nown)
3327  *      all non-negative                ->      pos
3328  *      all non-positive                ->      neg
3329  *      both negative and positive      ->      all
3330  *
3331  * If we end up with "all", we are done.
3332  * Otherwise, we perform a check for positive and/or negative
3333  * values as follows.
3334  *
3335  *      samples        neg             unk             pos
3336  *      <0 ?                        Y        N      Y        N
3337  *                                          pos    any      pos
3338  *      >0 ?         Y      N    Y     N
3339  *                  any    neg  any   neg
3340  *
3341  * There is no special sign for "zero", because we can usually treat zero
3342  * as either non-negative or non-positive, whatever works out best.
3343  * However, if the row is "critical", meaning that pivoting is impossible
3344  * then we don't want to limp zero with the non-positive case, because
3345  * then we we would lose the solution for those values of the parameters
3346  * where the value of the row is zero.  Instead, we treat 0 as non-negative
3347  * ensuring a split if the row can attain both zero and negative values.
3348  * The same happens when the original constraint was one that could not
3349  * be satisfied with equality by any integer values of the parameters.
3350  * In this case, we normalize the constraint, but then a value of zero
3351  * for the normalized constraint is actually a positive value for the
3352  * original constraint, so again we need to treat zero as non-negative.
3353  * In both these cases, we have the following decision tree instead:
3354  *
3355  *      all non-negative                ->      pos
3356  *      all negative                    ->      neg
3357  *      both negative and non-negative  ->      all
3358  *
3359  *      samples        neg                             pos
3360  *      <0 ?                                        Y        N
3361  *                                                 any      pos
3362  *      >=0 ?        Y      N
3363  *                  any    neg
3364  */
3365 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3366         struct isl_sol *sol, int row)
3367 {
3368         struct isl_vec *ineq = NULL;
3369         enum isl_tab_row_sign res = isl_tab_row_unknown;
3370         int critical;
3371         int strict;
3372         int row2;
3373
3374         if (tab->row_sign[row] != isl_tab_row_unknown)
3375                 return tab->row_sign[row];
3376         if (is_obviously_nonneg(tab, row))
3377                 return isl_tab_row_pos;
3378         for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3379                 if (tab->row_sign[row2] == isl_tab_row_unknown)
3380                         continue;
3381                 if (identical_parameter_line(tab, row, row2))
3382                         return tab->row_sign[row2];
3383         }
3384
3385         critical = is_critical(tab, row);
3386
3387         ineq = get_row_parameter_ineq(tab, row);
3388         if (!ineq)
3389                 goto error;
3390
3391         strict = is_strict(ineq);
3392
3393         res = sol->context->op->ineq_sign(sol->context, ineq->el,
3394                                           critical || strict);
3395
3396         if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3397                 /* test for negative values */
3398                 int feasible;
3399                 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3400                 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3401
3402                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3403                 if (feasible < 0)
3404                         goto error;
3405                 if (!feasible)
3406                         res = isl_tab_row_pos;
3407                 else
3408                         res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3409                                                            : isl_tab_row_any;
3410                 if (res == isl_tab_row_neg) {
3411                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3412                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3413                 }
3414         }
3415
3416         if (res == isl_tab_row_neg) {
3417                 /* test for positive values */
3418                 int feasible;
3419                 if (!critical && !strict)
3420                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3421
3422                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3423                 if (feasible < 0)
3424                         goto error;
3425                 if (feasible)
3426                         res = isl_tab_row_any;
3427         }
3428
3429         isl_vec_free(ineq);
3430         return res;
3431 error:
3432         isl_vec_free(ineq);
3433         return isl_tab_row_unknown;
3434 }
3435
3436 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3437
3438 /* Find solutions for values of the parameters that satisfy the given
3439  * inequality.
3440  *
3441  * We currently take a snapshot of the context tableau that is reset
3442  * when we return from this function, while we make a copy of the main
3443  * tableau, leaving the original main tableau untouched.
3444  * These are fairly arbitrary choices.  Making a copy also of the context
3445  * tableau would obviate the need to undo any changes made to it later,
3446  * while taking a snapshot of the main tableau could reduce memory usage.
3447  * If we were to switch to taking a snapshot of the main tableau,
3448  * we would have to keep in mind that we need to save the row signs
3449  * and that we need to do this before saving the current basis
3450  * such that the basis has been restore before we restore the row signs.
3451  */
3452 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3453 {
3454         void *saved;
3455
3456         if (!sol->context)
3457                 goto error;
3458         saved = sol->context->op->save(sol->context);
3459
3460         tab = isl_tab_dup(tab);
3461         if (!tab)
3462                 goto error;
3463
3464         sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3465
3466         find_solutions(sol, tab);
3467
3468         if (!sol->error)
3469                 sol->context->op->restore(sol->context, saved);
3470         return;
3471 error:
3472         sol->error = 1;
3473 }
3474
3475 /* Record the absence of solutions for those values of the parameters
3476  * that do not satisfy the given inequality with equality.
3477  */
3478 static void no_sol_in_strict(struct isl_sol *sol,
3479         struct isl_tab *tab, struct isl_vec *ineq)
3480 {
3481         int empty;
3482         void *saved;
3483
3484         if (!sol->context || sol->error)
3485                 goto error;
3486         saved = sol->context->op->save(sol->context);
3487
3488         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3489
3490         sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3491         if (!sol->context)
3492                 goto error;
3493
3494         empty = tab->empty;
3495         tab->empty = 1;
3496         sol_add(sol, tab);
3497         tab->empty = empty;
3498
3499         isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3500
3501         sol->context->op->restore(sol->context, saved);
3502         return;
3503 error:
3504         sol->error = 1;
3505 }
3506
3507 /* Compute the lexicographic minimum of the set represented by the main
3508  * tableau "tab" within the context "sol->context_tab".
3509  * On entry the sample value of the main tableau is lexicographically
3510  * less than or equal to this lexicographic minimum.
3511  * Pivots are performed until a feasible point is found, which is then
3512  * necessarily equal to the minimum, or until the tableau is found to
3513  * be infeasible.  Some pivots may need to be performed for only some
3514  * feasible values of the context tableau.  If so, the context tableau
3515  * is split into a part where the pivot is needed and a part where it is not.
3516  *
3517  * Whenever we enter the main loop, the main tableau is such that no
3518  * "obvious" pivots need to be performed on it, where "obvious" means
3519  * that the given row can be seen to be negative without looking at
3520  * the context tableau.  In particular, for non-parametric problems,
3521  * no pivots need to be performed on the main tableau.
3522  * The caller of find_solutions is responsible for making this property
3523  * hold prior to the first iteration of the loop, while restore_lexmin
3524  * is called before every other iteration.
3525  *
3526  * Inside the main loop, we first examine the signs of the rows of
3527  * the main tableau within the context of the context tableau.
3528  * If we find a row that is always non-positive for all values of
3529  * the parameters satisfying the context tableau and negative for at
3530  * least one value of the parameters, we perform the appropriate pivot
3531  * and start over.  An exception is the case where no pivot can be
3532  * performed on the row.  In this case, we require that the sign of
3533  * the row is negative for all values of the parameters (rather than just
3534  * non-positive).  This special case is handled inside row_sign, which
3535  * will say that the row can have any sign if it determines that it can
3536  * attain both negative and zero values.
3537  *
3538  * If we can't find a row that always requires a pivot, but we can find
3539  * one or more rows that require a pivot for some values of the parameters
3540  * (i.e., the row can attain both positive and negative signs), then we split
3541  * the context tableau into two parts, one where we force the sign to be
3542  * non-negative and one where we force is to be negative.
3543  * The non-negative part is handled by a recursive call (through find_in_pos).
3544  * Upon returning from this call, we continue with the negative part and
3545  * perform the required pivot.
3546  *
3547  * If no such rows can be found, all rows are non-negative and we have
3548  * found a (rational) feasible point.  If we only wanted a rational point
3549  * then we are done.
3550  * Otherwise, we check if all values of the sample point of the tableau
3551  * are integral for the variables.  If so, we have found the minimal
3552  * integral point and we are done.
3553  * If the sample point is not integral, then we need to make a distinction
3554  * based on whether the constant term is non-integral or the coefficients
3555  * of the parameters.  Furthermore, in order to decide how to handle
3556  * the non-integrality, we also need to know whether the coefficients
3557  * of the other columns in the tableau are integral.  This leads
3558  * to the following table.  The first two rows do not correspond
3559  * to a non-integral sample point and are only mentioned for completeness.
3560  *
3561  *      constant        parameters      other
3562  *
3563  *      int             int             int     |
3564  *      int             int             rat     | -> no problem
3565  *
3566  *      rat             int             int       -> fail
3567  *
3568  *      rat             int             rat       -> cut
3569  *
3570  *      int             rat             rat     |
3571  *      rat             rat             rat     | -> parametric cut
3572  *
3573  *      int             rat             int     |
3574  *      rat             rat             int     | -> split context
3575  *
3576  * If the parametric constant is completely integral, then there is nothing
3577  * to be done.  If the constant term is non-integral, but all the other
3578  * coefficient are integral, then there is nothing that can be done
3579  * and the tableau has no integral solution.
3580  * If, on the other hand, one or more of the other columns have rational
3581  * coefficients, but the parameter coefficients are all integral, then
3582  * we can perform a regular (non-parametric) cut.
3583  * Finally, if there is any parameter coefficient that is non-integral,
3584  * then we need to involve the context tableau.  There are two cases here.
3585  * If at least one other column has a rational coefficient, then we
3586  * can perform a parametric cut in the main tableau by adding a new
3587  * integer division in the context tableau.
3588  * If all other columns have integral coefficients, then we need to
3589  * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
3590  * is always integral.  We do this by introducing an integer division
3591  * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
3592  * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
3593  * Since q is expressed in the tableau as
3594  *      c + \sum a_i y_i - m q >= 0
3595  *      -c - \sum a_i y_i + m q + m - 1 >= 0
3596  * it is sufficient to add the inequality
3597  *      -c - \sum a_i y_i + m q >= 0
3598  * In the part of the context where this inequality does not hold, the
3599  * main tableau is marked as being empty.
3600  */
3601 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
3602 {
3603         struct isl_context *context;
3604
3605         if (!tab || sol->error)
3606                 goto error;
3607
3608         context = sol->context;
3609
3610         if (tab->empty)
3611                 goto done;
3612         if (context->op->is_empty(context))
3613                 goto done;
3614
3615         for (; tab && !tab->empty; tab = restore_lexmin(tab)) {
3616                 int flags;
3617                 int row;
3618                 enum isl_tab_row_sign sgn;
3619                 int split = -1;
3620                 int n_split = 0;
3621
3622                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3623                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3624                                 continue;
3625                         sgn = row_sign(tab, sol, row);
3626                         if (!sgn)
3627                                 goto error;
3628                         tab->row_sign[row] = sgn;
3629                         if (sgn == isl_tab_row_any)
3630                                 n_split++;
3631                         if (sgn == isl_tab_row_any && split == -1)
3632                                 split = row;
3633                         if (sgn == isl_tab_row_neg)
3634                                 break;
3635                 }
3636                 if (row < tab->n_row)
3637                         continue;
3638                 if (split != -1) {
3639                         struct isl_vec *ineq;
3640                         if (n_split != 1)
3641                                 split = context->op->best_split(context, tab);
3642                         if (split < 0)
3643                                 goto error;
3644                         ineq = get_row_parameter_ineq(tab, split);
3645                         if (!ineq)
3646                                 goto error;
3647                         is_strict(ineq);
3648                         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3649                                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3650                                         continue;
3651                                 if (tab->row_sign[row] == isl_tab_row_any)
3652                                         tab->row_sign[row] = isl_tab_row_unknown;
3653                         }
3654                         tab->row_sign[split] = isl_tab_row_pos;
3655                         sol_inc_level(sol);
3656                         find_in_pos(sol, tab, ineq->el);
3657                         tab->row_sign[split] = isl_tab_row_neg;
3658                         row = split;
3659                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3660                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3661                         if (!sol->error)
3662                                 context->op->add_ineq(context, ineq->el, 0, 1);
3663                         isl_vec_free(ineq);
3664                         if (sol->error)
3665                                 goto error;
3666                         continue;
3667                 }
3668                 if (tab->rational)
3669                         break;
3670                 row = first_non_integer_row(tab, &flags);
3671                 if (row < 0)
3672                         break;
3673                 if (ISL_FL_ISSET(flags, I_PAR)) {
3674                         if (ISL_FL_ISSET(flags, I_VAR)) {
3675                                 if (isl_tab_mark_empty(tab) < 0)
3676                                         goto error;
3677                                 break;
3678                         }
3679                         row = add_cut(tab, row);
3680                 } else if (ISL_FL_ISSET(flags, I_VAR)) {
3681                         struct isl_vec *div;
3682                         struct isl_vec *ineq;
3683                         int d;
3684                         div = get_row_split_div(tab, row);
3685                         if (!div)
3686                                 goto error;
3687                         d = context->op->get_div(context, tab, div);
3688                         isl_vec_free(div);
3689                         if (d < 0)
3690                                 goto error;
3691                         ineq = ineq_for_div(context->op->peek_basic_set(context), d);
3692                         if (!ineq)
3693                                 goto error;
3694                         sol_inc_level(sol);
3695                         no_sol_in_strict(sol, tab, ineq);
3696                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3697                         context->op->add_ineq(context, ineq->el, 1, 1);
3698                         isl_vec_free(ineq);
3699                         if (sol->error || !context->op->is_ok(context))
3700                                 goto error;
3701                         tab = set_row_cst_to_div(tab, row, d);
3702                         if (context->op->is_empty(context))
3703                                 break;
3704                 } else
3705                         row = add_parametric_cut(tab, row, context);
3706                 if (row < 0)
3707                         goto error;
3708         }
3709 done:
3710         sol_add(sol, tab);
3711         isl_tab_free(tab);
3712         return;
3713 error:
3714         isl_tab_free(tab);
3715         sol->error = 1;
3716 }
3717
3718 /* Compute the lexicographic minimum of the set represented by the main
3719  * tableau "tab" within the context "sol->context_tab".
3720  *
3721  * As a preprocessing step, we first transfer all the purely parametric
3722  * equalities from the main tableau to the context tableau, i.e.,
3723  * parameters that have been pivoted to a row.
3724  * These equalities are ignored by the main algorithm, because the
3725  * corresponding rows may not be marked as being non-negative.
3726  * In parts of the context where the added equality does not hold,
3727  * the main tableau is marked as being empty.
3728  */
3729 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
3730 {
3731         int row;
3732
3733         if (!tab)
3734                 goto error;
3735
3736         sol->level = 0;
3737
3738         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3739                 int p;
3740                 struct isl_vec *eq;
3741
3742                 if (tab->row_var[row] < 0)
3743                         continue;
3744                 if (tab->row_var[row] >= tab->n_param &&
3745                     tab->row_var[row] < tab->n_var - tab->n_div)
3746                         continue;
3747                 if (tab->row_var[row] < tab->n_param)
3748                         p = tab->row_var[row];
3749                 else
3750                         p = tab->row_var[row]
3751                                 + tab->n_param - (tab->n_var - tab->n_div);
3752
3753                 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
3754                 if (!eq)
3755                         goto error;
3756                 get_row_parameter_line(tab, row, eq->el);
3757                 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
3758                 eq = isl_vec_normalize(eq);
3759
3760                 sol_inc_level(sol);
3761                 no_sol_in_strict(sol, tab, eq);
3762
3763                 isl_seq_neg(eq->el, eq->el, eq->size);
3764                 sol_inc_level(sol);
3765                 no_sol_in_strict(sol, tab, eq);
3766                 isl_seq_neg(eq->el, eq->el, eq->size);
3767
3768                 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
3769
3770                 isl_vec_free(eq);
3771
3772                 if (isl_tab_mark_redundant(tab, row) < 0)
3773                         goto error;
3774
3775                 if (sol->context->op->is_empty(sol->context))
3776                         break;
3777
3778                 row = tab->n_redundant - 1;
3779         }
3780
3781         find_solutions(sol, tab);
3782
3783         sol->level = 0;
3784         sol_pop(sol);
3785
3786         return;
3787 error:
3788         isl_tab_free(tab);
3789         sol->error = 1;
3790 }
3791
3792 static void sol_map_find_solutions(struct isl_sol_map *sol_map,
3793         struct isl_tab *tab)
3794 {
3795         find_solutions_main(&sol_map->sol, tab);
3796 }
3797
3798 /* Check if integer division "div" of "dom" also occurs in "bmap".
3799  * If so, return its position within the divs.
3800  * If not, return -1.
3801  */
3802 static int find_context_div(struct isl_basic_map *bmap,
3803         struct isl_basic_set *dom, unsigned div)
3804 {
3805         int i;
3806         unsigned b_dim = isl_dim_total(bmap->dim);
3807         unsigned d_dim = isl_dim_total(dom->dim);
3808
3809         if (isl_int_is_zero(dom->div[div][0]))
3810                 return -1;
3811         if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
3812                 return -1;
3813
3814         for (i = 0; i < bmap->n_div; ++i) {
3815                 if (isl_int_is_zero(bmap->div[i][0]))
3816                         continue;
3817                 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
3818                                            (b_dim - d_dim) + bmap->n_div) != -1)
3819                         continue;
3820                 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
3821                         return i;
3822         }
3823         return -1;
3824 }
3825
3826 /* The correspondence between the variables in the main tableau,
3827  * the context tableau, and the input map and domain is as follows.
3828  * The first n_param and the last n_div variables of the main tableau
3829  * form the variables of the context tableau.
3830  * In the basic map, these n_param variables correspond to the
3831  * parameters and the input dimensions.  In the domain, they correspond
3832  * to the parameters and the set dimensions.
3833  * The n_div variables correspond to the integer divisions in the domain.
3834  * To ensure that everything lines up, we may need to copy some of the
3835  * integer divisions of the domain to the map.  These have to be placed
3836  * in the same order as those in the context and they have to be placed
3837  * after any other integer divisions that the map may have.
3838  * This function performs the required reordering.
3839  */
3840 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
3841         struct isl_basic_set *dom)
3842 {
3843         int i;
3844         int common = 0;
3845         int other;
3846
3847         for (i = 0; i < dom->n_div; ++i)
3848                 if (find_context_div(bmap, dom, i) != -1)
3849                         common++;
3850         other = bmap->n_div - common;
3851         if (dom->n_div - common > 0) {
3852                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
3853                                 dom->n_div - common, 0, 0);
3854                 if (!bmap)
3855                         return NULL;
3856         }
3857         for (i = 0; i < dom->n_div; ++i) {
3858                 int pos = find_context_div(bmap, dom, i);
3859                 if (pos < 0) {
3860                         pos = isl_basic_map_alloc_div(bmap);
3861                         if (pos < 0)
3862                                 goto error;
3863                         isl_int_set_si(bmap->div[pos][0], 0);
3864                 }
3865                 if (pos != other + i)
3866                         isl_basic_map_swap_div(bmap, pos, other + i);
3867         }
3868         return bmap;
3869 error:
3870         isl_basic_map_free(bmap);
3871         return NULL;
3872 }
3873
3874 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
3875  * some obvious symmetries.
3876  *
3877  * We make sure the divs in the domain are properly ordered,
3878  * because they will be added one by one in the given order
3879  * during the construction of the solution map.
3880  */
3881 static __isl_give isl_map *basic_map_partial_lexopt_base(
3882         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
3883         __isl_give isl_set **empty, int max)
3884 {
3885         isl_map *result = NULL;
3886         struct isl_tab *tab;
3887         struct isl_sol_map *sol_map = NULL;
3888         struct isl_context *context;
3889
3890         if (dom->n_div) {
3891                 dom = isl_basic_set_order_divs(dom);
3892                 bmap = align_context_divs(bmap, dom);
3893         }
3894         sol_map = sol_map_init(bmap, dom, !!empty, max);
3895         if (!sol_map)
3896                 goto error;
3897
3898         context = sol_map->sol.context;
3899         if (isl_basic_set_fast_is_empty(context->op->peek_basic_set(context)))
3900                 /* nothing */;
3901         else if (isl_basic_map_fast_is_empty(bmap))
3902                 sol_map_add_empty_if_needed(sol_map,
3903                     isl_basic_set_copy(context->op->peek_basic_set(context)));
3904         else {
3905                 tab = tab_for_lexmin(bmap,
3906                                     context->op->peek_basic_set(context), 1, max);
3907                 tab = context->op->detect_nonnegative_parameters(context, tab);
3908                 sol_map_find_solutions(sol_map, tab);
3909         }
3910         if (sol_map->sol.error)
3911                 goto error;
3912
3913         result = isl_map_copy(sol_map->map);
3914         if (empty)
3915                 *empty = isl_set_copy(sol_map->empty);
3916         sol_free(&sol_map->sol);
3917         isl_basic_map_free(bmap);
3918         return result;
3919 error:
3920         sol_free(&sol_map->sol);
3921         isl_basic_map_free(bmap);
3922         return NULL;
3923 }
3924
3925 /* Structure used during detection of parallel constraints.
3926  * n_in: number of "input" variables: isl_dim_param + isl_dim_in
3927  * n_out: number of "output" variables: isl_dim_out + isl_dim_div
3928  * val: the coefficients of the output variables
3929  */
3930 struct isl_constraint_equal_info {
3931         isl_basic_map *bmap;
3932         unsigned n_in;
3933         unsigned n_out;
3934         isl_int *val;
3935 };
3936
3937 /* Check whether the coefficients of the output variables
3938  * of the constraint in "entry" are equal to info->val.
3939  */
3940 static int constraint_equal(const void *entry, const void *val)
3941 {
3942         isl_int **row = (isl_int **)entry;
3943         const struct isl_constraint_equal_info *info = val;
3944
3945         return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
3946 }
3947
3948 /* Check whether "bmap" has a pair of constraints that have
3949  * the same coefficients for the output variables.
3950  * Note that the coefficients of the existentially quantified
3951  * variables need to be zero since the existentially quantified
3952  * of the result are usually not the same as those of the input.
3953  * the isl_dim_out and isl_dim_div dimensions.
3954  * If so, return 1 and return the row indices of the two constraints
3955  * in *first and *second.
3956  */
3957 static int parallel_constraints(__isl_keep isl_basic_map *bmap,
3958         int *first, int *second)
3959 {
3960         int i;
3961         isl_ctx *ctx = isl_basic_map_get_ctx(bmap);
3962         struct isl_hash_table *table = NULL;
3963         struct isl_hash_table_entry *entry;
3964         struct isl_constraint_equal_info info;
3965         unsigned n_out;
3966         unsigned n_div;
3967
3968         ctx = isl_basic_map_get_ctx(bmap);
3969         table = isl_hash_table_alloc(ctx, bmap->n_ineq);
3970         if (!table)
3971                 goto error;
3972
3973         info.n_in = isl_basic_map_dim(bmap, isl_dim_param) +
3974                     isl_basic_map_dim(bmap, isl_dim_in);
3975         info.bmap = bmap;
3976         n_out = isl_basic_map_dim(bmap, isl_dim_out);
3977         n_div = isl_basic_map_dim(bmap, isl_dim_div);
3978         info.n_out = n_out + n_div;
3979         for (i = 0; i < bmap->n_ineq; ++i) {
3980                 uint32_t hash;
3981
3982                 info.val = bmap->ineq[i] + 1 + info.n_in;
3983                 if (isl_seq_first_non_zero(info.val, n_out) < 0)
3984                         continue;
3985                 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
3986                         continue;
3987                 hash = isl_seq_get_hash(info.val, info.n_out);
3988                 entry = isl_hash_table_find(ctx, table, hash,
3989                                             constraint_equal, &info, 1);
3990                 if (!entry)
3991                         goto error;
3992                 if (entry->data)
3993                         break;
3994                 entry->data = &bmap->ineq[i];
3995         }
3996
3997         if (i < bmap->n_ineq) {
3998                 *first = ((isl_int **)entry->data) - bmap->ineq; 
3999                 *second = i;
4000         }
4001
4002         isl_hash_table_free(ctx, table);
4003
4004         return i < bmap->n_ineq;
4005 error:
4006         isl_hash_table_free(ctx, table);
4007         return -1;
4008 }
4009
4010 /* Given a set of upper bounds on the last "input" variable m,
4011  * construct a set that assigns the minimal upper bound to m, i.e.,
4012  * construct a set that divides the space into cells where one
4013  * of the upper bounds is smaller than all the others and assign
4014  * this upper bound to m.
4015  *
4016  * In particular, if there are n bounds b_i, then the result
4017  * consists of n basic sets, each one of the form
4018  *
4019  *      m = b_i
4020  *      b_i <= b_j      for j > i
4021  *      b_i <  b_j      for j < i
4022  */
4023 static __isl_give isl_set *set_minimum(__isl_take isl_dim *dim,
4024         __isl_take isl_mat *var)
4025 {
4026         int i, j, k;
4027         isl_basic_set *bset = NULL;
4028         isl_ctx *ctx;
4029         isl_set *set = NULL;
4030
4031         if (!dim || !var)
4032                 goto error;
4033
4034         ctx = isl_dim_get_ctx(dim);
4035         set = isl_set_alloc_dim(isl_dim_copy(dim),
4036                                 var->n_row, ISL_SET_DISJOINT);
4037
4038         for (i = 0; i < var->n_row; ++i) {
4039                 bset = isl_basic_set_alloc_dim(isl_dim_copy(dim), 0,
4040                                                1, var->n_row - 1);
4041                 k = isl_basic_set_alloc_equality(bset);
4042                 if (k < 0)
4043                         goto error;
4044                 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4045                 isl_int_set_si(bset->eq[k][var->n_col], -1);
4046                 for (j = 0; j < var->n_row; ++j) {
4047                         if (j == i)
4048                                 continue;
4049                         k = isl_basic_set_alloc_inequality(bset);
4050                         if (k < 0)
4051                                 goto error;
4052                         isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4053                                         ctx->negone, var->row[i],
4054                                         var->n_col);
4055                         isl_int_set_si(bset->ineq[k][var->n_col], 0);
4056                         if (j < i)
4057                                 isl_int_sub_ui(bset->ineq[k][0],
4058                                                bset->ineq[k][0], 1);
4059                 }
4060                 bset = isl_basic_set_finalize(bset);
4061                 set = isl_set_add_basic_set(set, bset);
4062         }
4063
4064         isl_dim_free(dim);
4065         isl_mat_free(var);
4066         return set;
4067 error:
4068         isl_basic_set_free(bset);
4069         isl_set_free(set);
4070         isl_dim_free(dim);
4071         isl_mat_free(var);
4072         return NULL;
4073 }
4074
4075 /* Given that the last input variable of "bmap" represents the minimum
4076  * of the bounds in "cst", check whether we need to split the domain
4077  * based on which bound attains the minimum.
4078  *
4079  * A split is needed when the minimum appears in an integer division
4080  * or in an equality.  Otherwise, it is only needed if it appears in
4081  * an upper bound that is different from the upper bounds on which it
4082  * is defined.
4083  */
4084 static int need_split_map(__isl_keep isl_basic_map *bmap,
4085         __isl_keep isl_mat *cst)
4086 {
4087         int i, j;
4088         unsigned total;
4089         unsigned pos;
4090
4091         pos = cst->n_col - 1;
4092         total = isl_basic_map_dim(bmap, isl_dim_all);
4093
4094         for (i = 0; i < bmap->n_div; ++i)
4095                 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4096                         return 1;
4097
4098         for (i = 0; i < bmap->n_eq; ++i)
4099                 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4100                         return 1;
4101
4102         for (i = 0; i < bmap->n_ineq; ++i) {
4103                 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4104                         continue;
4105                 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4106                         return 1;
4107                 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4108                                            total - pos - 1) >= 0)
4109                         return 1;
4110
4111                 for (j = 0; j < cst->n_row; ++j)
4112                         if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4113                                 break;
4114                 if (j >= cst->n_row)
4115                         return 1;
4116         }
4117
4118         return 0;
4119 }
4120
4121 static int need_split_set(__isl_keep isl_basic_set *bset,
4122         __isl_keep isl_mat *cst)
4123 {
4124         return need_split_map((isl_basic_map *)bset, cst);
4125 }
4126
4127 /* Given a set of which the last set variable is the minimum
4128  * of the bounds in "cst", split each basic set in the set
4129  * in pieces where one of the bounds is (strictly) smaller than the others.
4130  * This subdivision is given in "min_expr".
4131  * The variable is subsequently projected out.
4132  *
4133  * We only do the split when it is needed.
4134  * For example if the last input variable m = min(a,b) and the only
4135  * constraints in the given basic set are lower bounds on m,
4136  * i.e., l <= m = min(a,b), then we can simply project out m
4137  * to obtain l <= a and l <= b, without having to split on whether
4138  * m is equal to a or b.
4139  */
4140 static __isl_give isl_set *split(__isl_take isl_set *empty,
4141         __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4142 {
4143         int n_in;
4144         int i;
4145         isl_dim *dim;
4146         isl_set *res;
4147
4148         if (!empty || !min_expr || !cst)
4149                 goto error;
4150
4151         n_in = isl_set_dim(empty, isl_dim_set);
4152         dim = isl_set_get_dim(empty);
4153         dim = isl_dim_drop(dim, isl_dim_set, n_in - 1, 1);
4154         res = isl_set_empty(dim);
4155
4156         for (i = 0; i < empty->n; ++i) {
4157                 isl_set *set;
4158
4159                 set = isl_set_from_basic_set(isl_basic_set_copy(empty->p[i]));
4160                 if (need_split_set(empty->p[i], cst))
4161                         set = isl_set_intersect(set, isl_set_copy(min_expr));
4162                 set = isl_set_remove_dims(set, isl_dim_set, n_in - 1, 1);
4163
4164                 res = isl_set_union_disjoint(res, set);
4165         }
4166
4167         isl_set_free(empty);
4168         isl_set_free(min_expr);
4169         isl_mat_free(cst);
4170         return res;
4171 error:
4172         isl_set_free(empty);
4173         isl_set_free(min_expr);
4174         isl_mat_free(cst);
4175         return NULL;
4176 }
4177
4178 /* Given a map of which the last input variable is the minimum
4179  * of the bounds in "cst", split each basic set in the set
4180  * in pieces where one of the bounds is (strictly) smaller than the others.
4181  * This subdivision is given in "min_expr".
4182  * The variable is subsequently projected out.
4183  *
4184  * The implementation is essentially the same as that of "split".
4185  */
4186 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4187         __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4188 {
4189         int n_in;
4190         int i;
4191         isl_dim *dim;
4192         isl_map *res;
4193
4194         if (!opt || !min_expr || !cst)
4195                 goto error;
4196
4197         n_in = isl_map_dim(opt, isl_dim_in);
4198         dim = isl_map_get_dim(opt);
4199         dim = isl_dim_drop(dim, isl_dim_in, n_in - 1, 1);
4200         res = isl_map_empty(dim);
4201
4202         for (i = 0; i < opt->n; ++i) {
4203                 isl_map *map;
4204
4205                 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4206                 if (need_split_map(opt->p[i], cst))
4207                         map = isl_map_intersect_domain(map,
4208                                                        isl_set_copy(min_expr));
4209                 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4210
4211                 res = isl_map_union_disjoint(res, map);
4212         }
4213
4214         isl_map_free(opt);
4215         isl_set_free(min_expr);
4216         isl_mat_free(cst);
4217         return res;
4218 error:
4219         isl_map_free(opt);
4220         isl_set_free(min_expr);
4221         isl_mat_free(cst);
4222         return NULL;
4223 }
4224
4225 static __isl_give isl_map *basic_map_partial_lexopt(
4226         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4227         __isl_give isl_set **empty, int max);
4228
4229 /* Given a basic map with at least two parallel constraints (as found
4230  * by the function parallel_constraints), first look for more constraints
4231  * parallel to the two constraint and replace the found list of parallel
4232  * constraints by a single constraint with as "input" part the minimum
4233  * of the input parts of the list of constraints.  Then, recursively call
4234  * basic_map_partial_lexopt (possibly finding more parallel constraints)
4235  * and plug in the definition of the minimum in the result.
4236  *
4237  * More specifically, given a set of constraints
4238  *
4239  *      a x + b_i(p) >= 0
4240  *
4241  * Replace this set by a single constraint
4242  *
4243  *      a x + u >= 0
4244  *
4245  * with u a new parameter with constraints
4246  *
4247  *      u <= b_i(p)
4248  *
4249  * Any solution to the new system is also a solution for the original system
4250  * since
4251  *
4252  *      a x >= -u >= -b_i(p)
4253  *
4254  * Moreover, m = min_i(b_i(p)) satisfied the constraints on u and can
4255  * therefore be plugged into the solution.
4256  */
4257 static __isl_give isl_map *basic_map_partial_lexopt_symm(
4258         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4259         __isl_give isl_set **empty, int max, int first, int second)
4260 {
4261         int i, n, k;
4262         int *list = NULL;
4263         unsigned n_in, n_out, n_div;
4264         isl_ctx *ctx;
4265         isl_vec *var = NULL;
4266         isl_mat *cst = NULL;
4267         isl_map *opt;
4268         isl_set *min_expr;
4269         isl_dim *map_dim, *set_dim;
4270
4271         map_dim = isl_basic_map_get_dim(bmap);
4272         set_dim = empty ? isl_basic_set_get_dim(dom) : NULL;
4273
4274         n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4275                isl_basic_map_dim(bmap, isl_dim_in);
4276         n_out = isl_basic_map_dim(bmap, isl_dim_all) - n_in;
4277
4278         ctx = isl_basic_map_get_ctx(bmap);
4279         list = isl_alloc_array(ctx, int, bmap->n_ineq);
4280         var = isl_vec_alloc(ctx, n_out);
4281         if (!list || !var)
4282                 goto error;
4283
4284         list[0] = first;
4285         list[1] = second;
4286         isl_seq_cpy(var->el, bmap->ineq[first] + 1 + n_in, n_out);
4287         for (i = second + 1, n = 2; i < bmap->n_ineq; ++i) {
4288                 if (isl_seq_eq(var->el, bmap->ineq[i] + 1 + n_in, n_out))
4289                         list[n++] = i;
4290         }
4291
4292         cst = isl_mat_alloc(ctx, n, 1 + n_in);
4293         if (!cst)
4294                 goto error;
4295
4296         for (i = 0; i < n; ++i)
4297                 isl_seq_cpy(cst->row[i], bmap->ineq[list[i]], 1 + n_in);
4298
4299         bmap = isl_basic_map_cow(bmap);
4300         if (!bmap)
4301                 goto error;
4302         for (i = n - 1; i >= 0; --i)
4303                 if (isl_basic_map_drop_inequality(bmap, list[i]) < 0)
4304                         goto error;
4305
4306         bmap = isl_basic_map_add(bmap, isl_dim_in, 1);
4307         bmap = isl_basic_map_extend_constraints(bmap, 0, 1);
4308         k = isl_basic_map_alloc_inequality(bmap);
4309         if (k < 0)
4310                 goto error;
4311         isl_seq_clr(bmap->ineq[k], 1 + n_in);
4312         isl_int_set_si(bmap->ineq[k][1 + n_in], 1);
4313         isl_seq_cpy(bmap->ineq[k] + 1 + n_in + 1, var->el, n_out);
4314         bmap = isl_basic_map_finalize(bmap);
4315
4316         n_div = isl_basic_set_dim(dom, isl_dim_div);
4317         dom = isl_basic_set_add(dom, isl_dim_set, 1);
4318         dom = isl_basic_set_extend_constraints(dom, 0, n);
4319         for (i = 0; i < n; ++i) {
4320                 k = isl_basic_set_alloc_inequality(dom);
4321                 if (k < 0)
4322                         goto error;
4323                 isl_seq_cpy(dom->ineq[k], cst->row[i], 1 + n_in);
4324                 isl_int_set_si(dom->ineq[k][1 + n_in], -1);
4325                 isl_seq_clr(dom->ineq[k] + 1 + n_in + 1, n_div);
4326         }
4327
4328         min_expr = set_minimum(isl_basic_set_get_dim(dom), isl_mat_copy(cst));
4329
4330         isl_vec_free(var);
4331         free(list);
4332
4333         opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4334
4335         if (empty) {
4336                 *empty = split(*empty,
4337                                isl_set_copy(min_expr), isl_mat_copy(cst));
4338                 *empty = isl_set_reset_dim(*empty, set_dim);
4339         }
4340
4341         opt = split_domain(opt, min_expr, cst);
4342         opt = isl_map_reset_dim(opt, map_dim);
4343
4344         return opt;
4345 error:
4346         isl_dim_free(map_dim);
4347         isl_dim_free(set_dim);
4348         isl_mat_free(cst);
4349         isl_vec_free(var);
4350         free(list);
4351         isl_basic_set_free(dom);
4352         isl_basic_map_free(bmap);
4353         return NULL;
4354 }
4355
4356 /* Recursive part of isl_tab_basic_map_partial_lexopt, after detecting
4357  * equalities and removing redundant constraints.
4358  *
4359  * We first check if there are any parallel constraints (left).
4360  * If not, we are in the base case.
4361  * If there are parallel constraints, we replace them by a single
4362  * constraint in basic_map_partial_lexopt_symm and then call
4363  * this function recursively to look for more parallel constraints.
4364  */
4365 static __isl_give isl_map *basic_map_partial_lexopt(
4366         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4367         __isl_give isl_set **empty, int max)
4368 {
4369         int par = 0;
4370         int first, second;
4371
4372         if (!bmap)
4373                 goto error;
4374
4375         if (bmap->ctx->opt->pip_symmetry)
4376                 par = parallel_constraints(bmap, &first, &second);
4377         if (par < 0)
4378                 goto error;
4379         if (!par)
4380                 return basic_map_partial_lexopt_base(bmap, dom, empty, max);
4381         
4382         return basic_map_partial_lexopt_symm(bmap, dom, empty, max,
4383                                              first, second);
4384 error:
4385         isl_basic_set_free(dom);
4386         isl_basic_map_free(bmap);
4387         return NULL;
4388 }
4389
4390 /* Compute the lexicographic minimum (or maximum if "max" is set)
4391  * of "bmap" over the domain "dom" and return the result as a map.
4392  * If "empty" is not NULL, then *empty is assigned a set that
4393  * contains those parts of the domain where there is no solution.
4394  * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
4395  * then we compute the rational optimum.  Otherwise, we compute
4396  * the integral optimum.
4397  *
4398  * We perform some preprocessing.  As the PILP solver does not
4399  * handle implicit equalities very well, we first make sure all
4400  * the equalities are explicitly available.
4401  *
4402  * We also add context constraints to the basic map and remove
4403  * redundant constraints.  This is only needed because of the
4404  * way we handle simple symmetries.  In particular, we currently look
4405  * for symmetries on the constraints, before we set up the main tableau.
4406  * It is then no good to look for symmetries on possibly redundant constraints.
4407  */
4408 struct isl_map *isl_tab_basic_map_partial_lexopt(
4409                 struct isl_basic_map *bmap, struct isl_basic_set *dom,
4410                 struct isl_set **empty, int max)
4411 {
4412         if (empty)
4413                 *empty = NULL;
4414         if (!bmap || !dom)
4415                 goto error;
4416
4417         isl_assert(bmap->ctx,
4418             isl_basic_map_compatible_domain(bmap, dom), goto error);
4419
4420         bmap = isl_basic_map_intersect_domain(bmap, isl_basic_set_copy(dom));
4421         bmap = isl_basic_map_detect_equalities(bmap);
4422         bmap = isl_basic_map_remove_redundancies(bmap);
4423
4424         return basic_map_partial_lexopt(bmap, dom, empty, max);
4425 error:
4426         isl_basic_set_free(dom);
4427         isl_basic_map_free(bmap);
4428         return NULL;
4429 }
4430
4431 struct isl_sol_for {
4432         struct isl_sol  sol;
4433         int             (*fn)(__isl_take isl_basic_set *dom,
4434                                 __isl_take isl_mat *map, void *user);
4435         void            *user;
4436 };
4437
4438 static void sol_for_free(struct isl_sol_for *sol_for)
4439 {
4440         if (sol_for->sol.context)
4441                 sol_for->sol.context->op->free(sol_for->sol.context);
4442         free(sol_for);
4443 }
4444
4445 static void sol_for_free_wrap(struct isl_sol *sol)
4446 {
4447         sol_for_free((struct isl_sol_for *)sol);
4448 }
4449
4450 /* Add the solution identified by the tableau and the context tableau.
4451  *
4452  * See documentation of sol_add for more details.
4453  *
4454  * Instead of constructing a basic map, this function calls a user
4455  * defined function with the current context as a basic set and
4456  * an affine matrix representing the relation between the input and output.
4457  * The number of rows in this matrix is equal to one plus the number
4458  * of output variables.  The number of columns is equal to one plus
4459  * the total dimension of the context, i.e., the number of parameters,
4460  * input variables and divs.  Since some of the columns in the matrix
4461  * may refer to the divs, the basic set is not simplified.
4462  * (Simplification may reorder or remove divs.)
4463  */
4464 static void sol_for_add(struct isl_sol_for *sol,
4465         struct isl_basic_set *dom, struct isl_mat *M)
4466 {
4467         if (sol->sol.error || !dom || !M)
4468                 goto error;
4469
4470         dom = isl_basic_set_simplify(dom);
4471         dom = isl_basic_set_finalize(dom);
4472
4473         if (sol->fn(isl_basic_set_copy(dom), isl_mat_copy(M), sol->user) < 0)
4474                 goto error;
4475
4476         isl_basic_set_free(dom);
4477         isl_mat_free(M);
4478         return;
4479 error:
4480         isl_basic_set_free(dom);
4481         isl_mat_free(M);
4482         sol->sol.error = 1;
4483 }
4484
4485 static void sol_for_add_wrap(struct isl_sol *sol,
4486         struct isl_basic_set *dom, struct isl_mat *M)
4487 {
4488         sol_for_add((struct isl_sol_for *)sol, dom, M);
4489 }
4490
4491 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
4492         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4493                   void *user),
4494         void *user)
4495 {
4496         struct isl_sol_for *sol_for = NULL;
4497         struct isl_dim *dom_dim;
4498         struct isl_basic_set *dom = NULL;
4499
4500         sol_for = isl_calloc_type(bmap->ctx, struct isl_sol_for);
4501         if (!sol_for)
4502                 goto error;
4503
4504         dom_dim = isl_dim_domain(isl_dim_copy(bmap->dim));
4505         dom = isl_basic_set_universe(dom_dim);
4506
4507         sol_for->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
4508         sol_for->sol.dec_level.callback.run = &sol_dec_level_wrap;
4509         sol_for->sol.dec_level.sol = &sol_for->sol;
4510         sol_for->fn = fn;
4511         sol_for->user = user;
4512         sol_for->sol.max = max;
4513         sol_for->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
4514         sol_for->sol.add = &sol_for_add_wrap;
4515         sol_for->sol.add_empty = NULL;
4516         sol_for->sol.free = &sol_for_free_wrap;
4517
4518         sol_for->sol.context = isl_context_alloc(dom);
4519         if (!sol_for->sol.context)
4520                 goto error;
4521
4522         isl_basic_set_free(dom);
4523         return sol_for;
4524 error:
4525         isl_basic_set_free(dom);
4526         sol_for_free(sol_for);
4527         return NULL;
4528 }
4529
4530 static void sol_for_find_solutions(struct isl_sol_for *sol_for,
4531         struct isl_tab *tab)
4532 {
4533         find_solutions_main(&sol_for->sol, tab);
4534 }
4535
4536 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
4537         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4538                   void *user),
4539         void *user)
4540 {
4541         struct isl_sol_for *sol_for = NULL;
4542
4543         bmap = isl_basic_map_copy(bmap);
4544         if (!bmap)
4545                 return -1;
4546
4547         bmap = isl_basic_map_detect_equalities(bmap);
4548         sol_for = sol_for_init(bmap, max, fn, user);
4549
4550         if (isl_basic_map_fast_is_empty(bmap))
4551                 /* nothing */;
4552         else {
4553                 struct isl_tab *tab;
4554                 struct isl_context *context = sol_for->sol.context;
4555                 tab = tab_for_lexmin(bmap,
4556                                 context->op->peek_basic_set(context), 1, max);
4557                 tab = context->op->detect_nonnegative_parameters(context, tab);
4558                 sol_for_find_solutions(sol_for, tab);
4559                 if (sol_for->sol.error)
4560                         goto error;
4561         }
4562
4563         sol_free(&sol_for->sol);
4564         isl_basic_map_free(bmap);
4565         return 0;
4566 error:
4567         sol_free(&sol_for->sol);
4568         isl_basic_map_free(bmap);
4569         return -1;
4570 }
4571
4572 int isl_basic_map_foreach_lexmin(__isl_keep isl_basic_map *bmap,
4573         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4574                   void *user),
4575         void *user)
4576 {
4577         return isl_basic_map_foreach_lexopt(bmap, 0, fn, user);
4578 }
4579
4580 int isl_basic_map_foreach_lexmax(__isl_keep isl_basic_map *bmap,
4581         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4582                   void *user),
4583         void *user)
4584 {
4585         return isl_basic_map_foreach_lexopt(bmap, 1, fn, user);
4586 }