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