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