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