ddde3e38a4f08abb3e8668b92635742d50109550
[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 the 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 /* Check whether the invariant that all columns are lexico-positive
1117  * is satisfied.  This function is not called from the current code
1118  * but is useful during debugging.
1119  */
1120 static void check_lexpos(struct isl_tab *tab)
1121 {
1122         unsigned off = 2 + tab->M;
1123         int col;
1124         int var;
1125         int row;
1126
1127         for (col = tab->n_dead; col < tab->n_col; ++col) {
1128                 if (tab->col_var[col] >= 0 &&
1129                     (tab->col_var[col] < tab->n_param ||
1130                      tab->col_var[col] >= tab->n_var - tab->n_div))
1131                         continue;
1132                 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1133                         if (!tab->var[var].is_row) {
1134                                 if (tab->var[var].index == col)
1135                                         break;
1136                                 else
1137                                         continue;
1138                         }
1139                         row = tab->var[var].index;
1140                         if (isl_int_is_zero(tab->mat->row[row][off + col]))
1141                                 continue;
1142                         if (isl_int_is_pos(tab->mat->row[row][off + col]))
1143                                 break;
1144                         fprintf(stderr, "lexneg column %d (row %d)\n",
1145                                 col, row);
1146                 }
1147                 if (var >= tab->n_var - tab->n_div)
1148                         fprintf(stderr, "zero column %d\n", col);
1149         }
1150 }
1151
1152 /* Resolve all known or obviously violated constraints through pivoting.
1153  * In particular, as long as we can find any violated constraint, we
1154  * look for a pivoting column that would result in the lexicographically
1155  * smallest increment in the sample point.  If there is no such column
1156  * then the tableau is infeasible.
1157  */
1158 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1159 static int restore_lexmin(struct isl_tab *tab)
1160 {
1161         int row, col;
1162
1163         if (!tab)
1164                 return -1;
1165         if (tab->empty)
1166                 return 0;
1167         while ((row = first_neg(tab)) != -1) {
1168                 col = lexmin_pivot_col(tab, row);
1169                 if (col >= tab->n_col) {
1170                         if (isl_tab_mark_empty(tab) < 0)
1171                                 return -1;
1172                         return 0;
1173                 }
1174                 if (col < 0)
1175                         return -1;
1176                 if (isl_tab_pivot(tab, row, col) < 0)
1177                         return -1;
1178         }
1179         return 0;
1180 }
1181
1182 /* Given a row that represents an equality, look for an appropriate
1183  * pivoting column.
1184  * In particular, if there are any non-zero coefficients among
1185  * the non-parameter variables, then we take the last of these
1186  * variables.  Eliminating this variable in terms of the other
1187  * variables and/or parameters does not influence the property
1188  * that all column in the initial tableau are lexicographically
1189  * positive.  The row corresponding to the eliminated variable
1190  * will only have non-zero entries below the diagonal of the
1191  * initial tableau.  That is, we transform
1192  *
1193  *              I                               I
1194  *                1             into            a
1195  *                  I                             I
1196  *
1197  * If there is no such non-parameter variable, then we are dealing with
1198  * pure parameter equality and we pick any parameter with coefficient 1 or -1
1199  * for elimination.  This will ensure that the eliminated parameter
1200  * always has an integer value whenever all the other parameters are integral.
1201  * If there is no such parameter then we return -1.
1202  */
1203 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1204 {
1205         unsigned off = 2 + tab->M;
1206         int i;
1207
1208         for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1209                 int col;
1210                 if (tab->var[i].is_row)
1211                         continue;
1212                 col = tab->var[i].index;
1213                 if (col <= tab->n_dead)
1214                         continue;
1215                 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1216                         return col;
1217         }
1218         for (i = tab->n_dead; i < tab->n_col; ++i) {
1219                 if (isl_int_is_one(tab->mat->row[row][off + i]))
1220                         return i;
1221                 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1222                         return i;
1223         }
1224         return -1;
1225 }
1226
1227 /* Add an equality that is known to be valid to the tableau.
1228  * We first check if we can eliminate a variable or a parameter.
1229  * If not, we add the equality as two inequalities.
1230  * In this case, the equality was a pure parameter equality and there
1231  * is no need to resolve any constraint violations.
1232  */
1233 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1234 {
1235         int i;
1236         int r;
1237
1238         if (!tab)
1239                 return NULL;
1240         r = isl_tab_add_row(tab, eq);
1241         if (r < 0)
1242                 goto error;
1243
1244         r = tab->con[r].index;
1245         i = last_var_col_or_int_par_col(tab, r);
1246         if (i < 0) {
1247                 tab->con[r].is_nonneg = 1;
1248                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1249                         goto error;
1250                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1251                 r = isl_tab_add_row(tab, eq);
1252                 if (r < 0)
1253                         goto error;
1254                 tab->con[r].is_nonneg = 1;
1255                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1256                         goto error;
1257         } else {
1258                 if (isl_tab_pivot(tab, r, i) < 0)
1259                         goto error;
1260                 if (isl_tab_kill_col(tab, i) < 0)
1261                         goto error;
1262                 tab->n_eq++;
1263         }
1264
1265         return tab;
1266 error:
1267         isl_tab_free(tab);
1268         return NULL;
1269 }
1270
1271 /* Check if the given row is a pure constant.
1272  */
1273 static int is_constant(struct isl_tab *tab, int row)
1274 {
1275         unsigned off = 2 + tab->M;
1276
1277         return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1278                                         tab->n_col - tab->n_dead) == -1;
1279 }
1280
1281 /* Add an equality that may or may not be valid to the tableau.
1282  * If the resulting row is a pure constant, then it must be zero.
1283  * Otherwise, the resulting tableau is empty.
1284  *
1285  * If the row is not a pure constant, then we add two inequalities,
1286  * each time checking that they can be satisfied.
1287  * In the end we try to use one of the two constraints to eliminate
1288  * a column.
1289  */
1290 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1291 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1292 {
1293         int r1, r2;
1294         int row;
1295         struct isl_tab_undo *snap;
1296
1297         if (!tab)
1298                 return -1;
1299         snap = isl_tab_snap(tab);
1300         r1 = isl_tab_add_row(tab, eq);
1301         if (r1 < 0)
1302                 return -1;
1303         tab->con[r1].is_nonneg = 1;
1304         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1305                 return -1;
1306
1307         row = tab->con[r1].index;
1308         if (is_constant(tab, row)) {
1309                 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1310                     (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1311                         if (isl_tab_mark_empty(tab) < 0)
1312                                 return -1;
1313                         return 0;
1314                 }
1315                 if (isl_tab_rollback(tab, snap) < 0)
1316                         return -1;
1317                 return 0;
1318         }
1319
1320         if (restore_lexmin(tab) < 0)
1321                 return -1;
1322         if (tab->empty)
1323                 return 0;
1324
1325         isl_seq_neg(eq, eq, 1 + tab->n_var);
1326
1327         r2 = isl_tab_add_row(tab, eq);
1328         if (r2 < 0)
1329                 return -1;
1330         tab->con[r2].is_nonneg = 1;
1331         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1332                 return -1;
1333
1334         if (restore_lexmin(tab) < 0)
1335                 return -1;
1336         if (tab->empty)
1337                 return 0;
1338
1339         if (!tab->con[r1].is_row) {
1340                 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1341                         return -1;
1342         } else if (!tab->con[r2].is_row) {
1343                 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1344                         return -1;
1345         }
1346
1347         if (tab->bmap) {
1348                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1349                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1350                         return -1;
1351                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1352                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1353                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1354                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1355                         return -1;
1356                 if (!tab->bmap)
1357                         return -1;
1358         }
1359
1360         return 0;
1361 }
1362
1363 /* Add an inequality to the tableau, resolving violations using
1364  * restore_lexmin.
1365  */
1366 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1367 {
1368         int r;
1369
1370         if (!tab)
1371                 return NULL;
1372         if (tab->bmap) {
1373                 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1374                 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1375                         goto error;
1376                 if (!tab->bmap)
1377                         goto error;
1378         }
1379         r = isl_tab_add_row(tab, ineq);
1380         if (r < 0)
1381                 goto error;
1382         tab->con[r].is_nonneg = 1;
1383         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1384                 goto error;
1385         if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1386                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1387                         goto error;
1388                 return tab;
1389         }
1390
1391         if (restore_lexmin(tab) < 0)
1392                 goto error;
1393         if (!tab->empty && tab->con[r].is_row &&
1394                  isl_tab_row_is_redundant(tab, tab->con[r].index))
1395                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1396                         goto error;
1397         return tab;
1398 error:
1399         isl_tab_free(tab);
1400         return NULL;
1401 }
1402
1403 /* Check if the coefficients of the parameters are all integral.
1404  */
1405 static int integer_parameter(struct isl_tab *tab, int row)
1406 {
1407         int i;
1408         int col;
1409         unsigned off = 2 + tab->M;
1410
1411         for (i = 0; i < tab->n_param; ++i) {
1412                 /* Eliminated parameter */
1413                 if (tab->var[i].is_row)
1414                         continue;
1415                 col = tab->var[i].index;
1416                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1417                                                 tab->mat->row[row][0]))
1418                         return 0;
1419         }
1420         for (i = 0; i < tab->n_div; ++i) {
1421                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1422                         continue;
1423                 col = tab->var[tab->n_var - tab->n_div + i].index;
1424                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1425                                                 tab->mat->row[row][0]))
1426                         return 0;
1427         }
1428         return 1;
1429 }
1430
1431 /* Check if the coefficients of the non-parameter variables are all integral.
1432  */
1433 static int integer_variable(struct isl_tab *tab, int row)
1434 {
1435         int i;
1436         unsigned off = 2 + tab->M;
1437
1438         for (i = tab->n_dead; i < tab->n_col; ++i) {
1439                 if (tab->col_var[i] >= 0 &&
1440                     (tab->col_var[i] < tab->n_param ||
1441                      tab->col_var[i] >= tab->n_var - tab->n_div))
1442                         continue;
1443                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1444                                                 tab->mat->row[row][0]))
1445                         return 0;
1446         }
1447         return 1;
1448 }
1449
1450 /* Check if the constant term is integral.
1451  */
1452 static int integer_constant(struct isl_tab *tab, int row)
1453 {
1454         return isl_int_is_divisible_by(tab->mat->row[row][1],
1455                                         tab->mat->row[row][0]);
1456 }
1457
1458 #define I_CST   1 << 0
1459 #define I_PAR   1 << 1
1460 #define I_VAR   1 << 2
1461
1462 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1463  * that is non-integer and therefore requires a cut and return
1464  * the index of the variable.
1465  * For parametric tableaus, there are three parts in a row,
1466  * the constant, the coefficients of the parameters and the rest.
1467  * For each part, we check whether the coefficients in that part
1468  * are all integral and if so, set the corresponding flag in *f.
1469  * If the constant and the parameter part are integral, then the
1470  * current sample value is integral and no cut is required
1471  * (irrespective of whether the variable part is integral).
1472  */
1473 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1474 {
1475         var = var < 0 ? tab->n_param : var + 1;
1476
1477         for (; var < tab->n_var - tab->n_div; ++var) {
1478                 int flags = 0;
1479                 int row;
1480                 if (!tab->var[var].is_row)
1481                         continue;
1482                 row = tab->var[var].index;
1483                 if (integer_constant(tab, row))
1484                         ISL_FL_SET(flags, I_CST);
1485                 if (integer_parameter(tab, row))
1486                         ISL_FL_SET(flags, I_PAR);
1487                 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1488                         continue;
1489                 if (integer_variable(tab, row))
1490                         ISL_FL_SET(flags, I_VAR);
1491                 *f = flags;
1492                 return var;
1493         }
1494         return -1;
1495 }
1496
1497 /* Check for first (non-parameter) variable that is non-integer and
1498  * therefore requires a cut and return the corresponding row.
1499  * For parametric tableaus, there are three parts in a row,
1500  * the constant, the coefficients of the parameters and the rest.
1501  * For each part, we check whether the coefficients in that part
1502  * are all integral and if so, set the corresponding flag in *f.
1503  * If the constant and the parameter part are integral, then the
1504  * current sample value is integral and no cut is required
1505  * (irrespective of whether the variable part is integral).
1506  */
1507 static int first_non_integer_row(struct isl_tab *tab, int *f)
1508 {
1509         int var = next_non_integer_var(tab, -1, f);
1510
1511         return var < 0 ? -1 : tab->var[var].index;
1512 }
1513
1514 /* Add a (non-parametric) cut to cut away the non-integral sample
1515  * value of the given row.
1516  *
1517  * If the row is given by
1518  *
1519  *      m r = f + \sum_i a_i y_i
1520  *
1521  * then the cut is
1522  *
1523  *      c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1524  *
1525  * The big parameter, if any, is ignored, since it is assumed to be big
1526  * enough to be divisible by any integer.
1527  * If the tableau is actually a parametric tableau, then this function
1528  * is only called when all coefficients of the parameters are integral.
1529  * The cut therefore has zero coefficients for the parameters.
1530  *
1531  * The current value is known to be negative, so row_sign, if it
1532  * exists, is set accordingly.
1533  *
1534  * Return the row of the cut or -1.
1535  */
1536 static int add_cut(struct isl_tab *tab, int row)
1537 {
1538         int i;
1539         int r;
1540         isl_int *r_row;
1541         unsigned off = 2 + tab->M;
1542
1543         if (isl_tab_extend_cons(tab, 1) < 0)
1544                 return -1;
1545         r = isl_tab_allocate_con(tab);
1546         if (r < 0)
1547                 return -1;
1548
1549         r_row = tab->mat->row[tab->con[r].index];
1550         isl_int_set(r_row[0], tab->mat->row[row][0]);
1551         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1552         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1553         isl_int_neg(r_row[1], r_row[1]);
1554         if (tab->M)
1555                 isl_int_set_si(r_row[2], 0);
1556         for (i = 0; i < tab->n_col; ++i)
1557                 isl_int_fdiv_r(r_row[off + i],
1558                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1559
1560         tab->con[r].is_nonneg = 1;
1561         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1562                 return -1;
1563         if (tab->row_sign)
1564                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1565
1566         return tab->con[r].index;
1567 }
1568
1569 /* Given a non-parametric tableau, add cuts until an integer
1570  * sample point is obtained or until the tableau is determined
1571  * to be integer infeasible.
1572  * As long as there is any non-integer value in the sample point,
1573  * we add appropriate cuts, if possible, for each of these
1574  * non-integer values and then resolve the violated
1575  * cut constraints using restore_lexmin.
1576  * If one of the corresponding rows is equal to an integral
1577  * combination of variables/constraints plus a non-integral constant,
1578  * then there is no way to obtain an integer point and we return
1579  * a tableau that is marked empty.
1580  */
1581 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab)
1582 {
1583         int var;
1584         int row;
1585         int flags;
1586
1587         if (!tab)
1588                 return NULL;
1589         if (tab->empty)
1590                 return tab;
1591
1592         while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1593                 do {
1594                         if (ISL_FL_ISSET(flags, I_VAR)) {
1595                                 if (isl_tab_mark_empty(tab) < 0)
1596                                         goto error;
1597                                 return tab;
1598                         }
1599                         row = tab->var[var].index;
1600                         row = add_cut(tab, row);
1601                         if (row < 0)
1602                                 goto error;
1603                 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1604                 if (restore_lexmin(tab) < 0)
1605                         goto error;
1606                 if (tab->empty)
1607                         break;
1608         }
1609         return tab;
1610 error:
1611         isl_tab_free(tab);
1612         return NULL;
1613 }
1614
1615 /* Check whether all the currently active samples also satisfy the inequality
1616  * "ineq" (treated as an equality if eq is set).
1617  * Remove those samples that do not.
1618  */
1619 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1620 {
1621         int i;
1622         isl_int v;
1623
1624         if (!tab)
1625                 return NULL;
1626
1627         isl_assert(tab->mat->ctx, tab->bmap, goto error);
1628         isl_assert(tab->mat->ctx, tab->samples, goto error);
1629         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1630
1631         isl_int_init(v);
1632         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1633                 int sgn;
1634                 isl_seq_inner_product(ineq, tab->samples->row[i],
1635                                         1 + tab->n_var, &v);
1636                 sgn = isl_int_sgn(v);
1637                 if (eq ? (sgn == 0) : (sgn >= 0))
1638                         continue;
1639                 tab = isl_tab_drop_sample(tab, i);
1640                 if (!tab)
1641                         break;
1642         }
1643         isl_int_clear(v);
1644
1645         return tab;
1646 error:
1647         isl_tab_free(tab);
1648         return NULL;
1649 }
1650
1651 /* Check whether the sample value of the tableau is finite,
1652  * i.e., either the tableau does not use a big parameter, or
1653  * all values of the variables are equal to the big parameter plus
1654  * some constant.  This constant is the actual sample value.
1655  */
1656 static int sample_is_finite(struct isl_tab *tab)
1657 {
1658         int i;
1659
1660         if (!tab->M)
1661                 return 1;
1662
1663         for (i = 0; i < tab->n_var; ++i) {
1664                 int row;
1665                 if (!tab->var[i].is_row)
1666                         return 0;
1667                 row = tab->var[i].index;
1668                 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1669                         return 0;
1670         }
1671         return 1;
1672 }
1673
1674 /* Check if the context tableau of sol has any integer points.
1675  * Leave tab in empty state if no integer point can be found.
1676  * If an integer point can be found and if moreover it is finite,
1677  * then it is added to the list of sample values.
1678  *
1679  * This function is only called when none of the currently active sample
1680  * values satisfies the most recently added constraint.
1681  */
1682 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1683 {
1684         struct isl_tab_undo *snap;
1685         int feasible;
1686
1687         if (!tab)
1688                 return NULL;
1689
1690         snap = isl_tab_snap(tab);
1691         if (isl_tab_push_basis(tab) < 0)
1692                 goto error;
1693
1694         tab = cut_to_integer_lexmin(tab);
1695         if (!tab)
1696                 goto error;
1697
1698         if (!tab->empty && sample_is_finite(tab)) {
1699                 struct isl_vec *sample;
1700
1701                 sample = isl_tab_get_sample_value(tab);
1702
1703                 tab = isl_tab_add_sample(tab, sample);
1704         }
1705
1706         if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1707                 goto error;
1708
1709         return tab;
1710 error:
1711         isl_tab_free(tab);
1712         return NULL;
1713 }
1714
1715 /* Check if any of the currently active sample values satisfies
1716  * the inequality "ineq" (an equality if eq is set).
1717  */
1718 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1719 {
1720         int i;
1721         isl_int v;
1722
1723         if (!tab)
1724                 return -1;
1725
1726         isl_assert(tab->mat->ctx, tab->bmap, return -1);
1727         isl_assert(tab->mat->ctx, tab->samples, return -1);
1728         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1729
1730         isl_int_init(v);
1731         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1732                 int sgn;
1733                 isl_seq_inner_product(ineq, tab->samples->row[i],
1734                                         1 + tab->n_var, &v);
1735                 sgn = isl_int_sgn(v);
1736                 if (eq ? (sgn == 0) : (sgn >= 0))
1737                         break;
1738         }
1739         isl_int_clear(v);
1740
1741         return i < tab->n_sample;
1742 }
1743
1744 /* Add a div specified by "div" to the tableau "tab" and return
1745  * 1 if the div is obviously non-negative.
1746  */
1747 static int context_tab_add_div(struct isl_tab *tab, struct isl_vec *div,
1748         int (*add_ineq)(void *user, isl_int *), void *user)
1749 {
1750         int i;
1751         int r;
1752         struct isl_mat *samples;
1753         int nonneg;
1754
1755         r = isl_tab_add_div(tab, div, add_ineq, user);
1756         if (r < 0)
1757                 return -1;
1758         nonneg = tab->var[r].is_nonneg;
1759         tab->var[r].frozen = 1;
1760
1761         samples = isl_mat_extend(tab->samples,
1762                         tab->n_sample, 1 + tab->n_var);
1763         tab->samples = samples;
1764         if (!samples)
1765                 return -1;
1766         for (i = tab->n_outside; i < samples->n_row; ++i) {
1767                 isl_seq_inner_product(div->el + 1, samples->row[i],
1768                         div->size - 1, &samples->row[i][samples->n_col - 1]);
1769                 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1770                                samples->row[i][samples->n_col - 1], div->el[0]);
1771         }
1772
1773         return nonneg;
1774 }
1775
1776 /* Add a div specified by "div" to both the main tableau and
1777  * the context tableau.  In case of the main tableau, we only
1778  * need to add an extra div.  In the context tableau, we also
1779  * need to express the meaning of the div.
1780  * Return the index of the div or -1 if anything went wrong.
1781  */
1782 static int add_div(struct isl_tab *tab, struct isl_context *context,
1783         struct isl_vec *div)
1784 {
1785         int r;
1786         int nonneg;
1787
1788         if ((nonneg = context->op->add_div(context, div)) < 0)
1789                 goto error;
1790
1791         if (!context->op->is_ok(context))
1792                 goto error;
1793
1794         if (isl_tab_extend_vars(tab, 1) < 0)
1795                 goto error;
1796         r = isl_tab_allocate_var(tab);
1797         if (r < 0)
1798                 goto error;
1799         if (nonneg)
1800                 tab->var[r].is_nonneg = 1;
1801         tab->var[r].frozen = 1;
1802         tab->n_div++;
1803
1804         return tab->n_div - 1;
1805 error:
1806         context->op->invalidate(context);
1807         return -1;
1808 }
1809
1810 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1811 {
1812         int i;
1813         unsigned total = isl_basic_map_total_dim(tab->bmap);
1814
1815         for (i = 0; i < tab->bmap->n_div; ++i) {
1816                 if (isl_int_ne(tab->bmap->div[i][0], denom))
1817                         continue;
1818                 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
1819                         continue;
1820                 return i;
1821         }
1822         return -1;
1823 }
1824
1825 /* Return the index of a div that corresponds to "div".
1826  * We first check if we already have such a div and if not, we create one.
1827  */
1828 static int get_div(struct isl_tab *tab, struct isl_context *context,
1829         struct isl_vec *div)
1830 {
1831         int d;
1832         struct isl_tab *context_tab = context->op->peek_tab(context);
1833
1834         if (!context_tab)
1835                 return -1;
1836
1837         d = find_div(context_tab, div->el + 1, div->el[0]);
1838         if (d != -1)
1839                 return d;
1840
1841         return add_div(tab, context, div);
1842 }
1843
1844 /* Add a parametric cut to cut away the non-integral sample value
1845  * of the give row.
1846  * Let a_i be the coefficients of the constant term and the parameters
1847  * and let b_i be the coefficients of the variables or constraints
1848  * in basis of the tableau.
1849  * Let q be the div q = floor(\sum_i {-a_i} y_i).
1850  *
1851  * The cut is expressed as
1852  *
1853  *      c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1854  *
1855  * If q did not already exist in the context tableau, then it is added first.
1856  * If q is in a column of the main tableau then the "+ q" can be accomplished
1857  * by setting the corresponding entry to the denominator of the constraint.
1858  * If q happens to be in a row of the main tableau, then the corresponding
1859  * row needs to be added instead (taking care of the denominators).
1860  * Note that this is very unlikely, but perhaps not entirely impossible.
1861  *
1862  * The current value of the cut is known to be negative (or at least
1863  * non-positive), so row_sign is set accordingly.
1864  *
1865  * Return the row of the cut or -1.
1866  */
1867 static int add_parametric_cut(struct isl_tab *tab, int row,
1868         struct isl_context *context)
1869 {
1870         struct isl_vec *div;
1871         int d;
1872         int i;
1873         int r;
1874         isl_int *r_row;
1875         int col;
1876         int n;
1877         unsigned off = 2 + tab->M;
1878
1879         if (!context)
1880                 return -1;
1881
1882         div = get_row_parameter_div(tab, row);
1883         if (!div)
1884                 return -1;
1885
1886         n = tab->n_div;
1887         d = context->op->get_div(context, tab, div);
1888         if (d < 0)
1889                 return -1;
1890
1891         if (isl_tab_extend_cons(tab, 1) < 0)
1892                 return -1;
1893         r = isl_tab_allocate_con(tab);
1894         if (r < 0)
1895                 return -1;
1896
1897         r_row = tab->mat->row[tab->con[r].index];
1898         isl_int_set(r_row[0], tab->mat->row[row][0]);
1899         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1900         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1901         isl_int_neg(r_row[1], r_row[1]);
1902         if (tab->M)
1903                 isl_int_set_si(r_row[2], 0);
1904         for (i = 0; i < tab->n_param; ++i) {
1905                 if (tab->var[i].is_row)
1906                         continue;
1907                 col = tab->var[i].index;
1908                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1909                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1910                                 tab->mat->row[row][0]);
1911                 isl_int_neg(r_row[off + col], r_row[off + col]);
1912         }
1913         for (i = 0; i < tab->n_div; ++i) {
1914                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1915                         continue;
1916                 col = tab->var[tab->n_var - tab->n_div + i].index;
1917                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1918                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1919                                 tab->mat->row[row][0]);
1920                 isl_int_neg(r_row[off + col], r_row[off + col]);
1921         }
1922         for (i = 0; i < tab->n_col; ++i) {
1923                 if (tab->col_var[i] >= 0 &&
1924                     (tab->col_var[i] < tab->n_param ||
1925                      tab->col_var[i] >= tab->n_var - tab->n_div))
1926                         continue;
1927                 isl_int_fdiv_r(r_row[off + i],
1928                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1929         }
1930         if (tab->var[tab->n_var - tab->n_div + d].is_row) {
1931                 isl_int gcd;
1932                 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
1933                 isl_int_init(gcd);
1934                 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
1935                 isl_int_divexact(r_row[0], r_row[0], gcd);
1936                 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
1937                 isl_seq_combine(r_row + 1, gcd, r_row + 1,
1938                                 r_row[0], tab->mat->row[d_row] + 1,
1939                                 off - 1 + tab->n_col);
1940                 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
1941                 isl_int_clear(gcd);
1942         } else {
1943                 col = tab->var[tab->n_var - tab->n_div + d].index;
1944                 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
1945         }
1946
1947         tab->con[r].is_nonneg = 1;
1948         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1949                 return -1;
1950         if (tab->row_sign)
1951                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1952
1953         isl_vec_free(div);
1954
1955         row = tab->con[r].index;
1956
1957         if (d >= n && context->op->detect_equalities(context, tab) < 0)
1958                 return -1;
1959
1960         return row;
1961 }
1962
1963 /* Construct a tableau for bmap that can be used for computing
1964  * the lexicographic minimum (or maximum) of bmap.
1965  * If not NULL, then dom is the domain where the minimum
1966  * should be computed.  In this case, we set up a parametric
1967  * tableau with row signs (initialized to "unknown").
1968  * If M is set, then the tableau will use a big parameter.
1969  * If max is set, then a maximum should be computed instead of a minimum.
1970  * This means that for each variable x, the tableau will contain the variable
1971  * x' = M - x, rather than x' = M + x.  This in turn means that the coefficient
1972  * of the variables in all constraints are negated prior to adding them
1973  * to the tableau.
1974  */
1975 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
1976         struct isl_basic_set *dom, unsigned M, int max)
1977 {
1978         int i;
1979         struct isl_tab *tab;
1980
1981         tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
1982                             isl_basic_map_total_dim(bmap), M);
1983         if (!tab)
1984                 return NULL;
1985
1986         tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
1987         if (dom) {
1988                 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
1989                 tab->n_div = dom->n_div;
1990                 tab->row_sign = isl_calloc_array(bmap->ctx,
1991                                         enum isl_tab_row_sign, tab->mat->n_row);
1992                 if (!tab->row_sign)
1993                         goto error;
1994         }
1995         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
1996                 if (isl_tab_mark_empty(tab) < 0)
1997                         goto error;
1998                 return tab;
1999         }
2000
2001         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2002                 tab->var[i].is_nonneg = 1;
2003                 tab->var[i].frozen = 1;
2004         }
2005         for (i = 0; i < bmap->n_eq; ++i) {
2006                 if (max)
2007                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
2008                                     bmap->eq[i] + 1 + tab->n_param,
2009                                     tab->n_var - tab->n_param - tab->n_div);
2010                 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2011                 if (max)
2012                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
2013                                     bmap->eq[i] + 1 + tab->n_param,
2014                                     tab->n_var - tab->n_param - tab->n_div);
2015                 if (!tab || tab->empty)
2016                         return tab;
2017         }
2018         if (bmap->n_eq && restore_lexmin(tab) < 0)
2019                 goto error;
2020         for (i = 0; i < bmap->n_ineq; ++i) {
2021                 if (max)
2022                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2023                                     bmap->ineq[i] + 1 + tab->n_param,
2024                                     tab->n_var - tab->n_param - tab->n_div);
2025                 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2026                 if (max)
2027                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2028                                     bmap->ineq[i] + 1 + tab->n_param,
2029                                     tab->n_var - tab->n_param - tab->n_div);
2030                 if (!tab || tab->empty)
2031                         return tab;
2032         }
2033         return tab;
2034 error:
2035         isl_tab_free(tab);
2036         return NULL;
2037 }
2038
2039 /* Given a main tableau where more than one row requires a split,
2040  * determine and return the "best" row to split on.
2041  *
2042  * Given two rows in the main tableau, if the inequality corresponding
2043  * to the first row is redundant with respect to that of the second row
2044  * in the current tableau, then it is better to split on the second row,
2045  * since in the positive part, both row will be positive.
2046  * (In the negative part a pivot will have to be performed and just about
2047  * anything can happen to the sign of the other row.)
2048  *
2049  * As a simple heuristic, we therefore select the row that makes the most
2050  * of the other rows redundant.
2051  *
2052  * Perhaps it would also be useful to look at the number of constraints
2053  * that conflict with any given constraint.
2054  */
2055 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2056 {
2057         struct isl_tab_undo *snap;
2058         int split;
2059         int row;
2060         int best = -1;
2061         int best_r;
2062
2063         if (isl_tab_extend_cons(context_tab, 2) < 0)
2064                 return -1;
2065
2066         snap = isl_tab_snap(context_tab);
2067
2068         for (split = tab->n_redundant; split < tab->n_row; ++split) {
2069                 struct isl_tab_undo *snap2;
2070                 struct isl_vec *ineq = NULL;
2071                 int r = 0;
2072                 int ok;
2073
2074                 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2075                         continue;
2076                 if (tab->row_sign[split] != isl_tab_row_any)
2077                         continue;
2078
2079                 ineq = get_row_parameter_ineq(tab, split);
2080                 if (!ineq)
2081                         return -1;
2082                 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2083                 isl_vec_free(ineq);
2084                 if (!ok)
2085                         return -1;
2086
2087                 snap2 = isl_tab_snap(context_tab);
2088
2089                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2090                         struct isl_tab_var *var;
2091
2092                         if (row == split)
2093                                 continue;
2094                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2095                                 continue;
2096                         if (tab->row_sign[row] != isl_tab_row_any)
2097                                 continue;
2098
2099                         ineq = get_row_parameter_ineq(tab, row);
2100                         if (!ineq)
2101                                 return -1;
2102                         ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2103                         isl_vec_free(ineq);
2104                         if (!ok)
2105                                 return -1;
2106                         var = &context_tab->con[context_tab->n_con - 1];
2107                         if (!context_tab->empty &&
2108                             !isl_tab_min_at_most_neg_one(context_tab, var))
2109                                 r++;
2110                         if (isl_tab_rollback(context_tab, snap2) < 0)
2111                                 return -1;
2112                 }
2113                 if (best == -1 || r > best_r) {
2114                         best = split;
2115                         best_r = r;
2116                 }
2117                 if (isl_tab_rollback(context_tab, snap) < 0)
2118                         return -1;
2119         }
2120
2121         return best;
2122 }
2123
2124 static struct isl_basic_set *context_lex_peek_basic_set(
2125         struct isl_context *context)
2126 {
2127         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2128         if (!clex->tab)
2129                 return NULL;
2130         return isl_tab_peek_bset(clex->tab);
2131 }
2132
2133 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2134 {
2135         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2136         return clex->tab;
2137 }
2138
2139 static void context_lex_extend(struct isl_context *context, int n)
2140 {
2141         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2142         if (!clex->tab)
2143                 return;
2144         if (isl_tab_extend_cons(clex->tab, n) >= 0)
2145                 return;
2146         isl_tab_free(clex->tab);
2147         clex->tab = NULL;
2148 }
2149
2150 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
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, 2) < 0)
2155                 goto error;
2156         if (add_lexmin_eq(clex->tab, eq) < 0)
2157                 goto error;
2158         if (check) {
2159                 int v = tab_has_valid_sample(clex->tab, eq, 1);
2160                 if (v < 0)
2161                         goto error;
2162                 if (!v)
2163                         clex->tab = check_integer_feasible(clex->tab);
2164         }
2165         if (update)
2166                 clex->tab = check_samples(clex->tab, eq, 1);
2167         return;
2168 error:
2169         isl_tab_free(clex->tab);
2170         clex->tab = NULL;
2171 }
2172
2173 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2174                 int check, int update)
2175 {
2176         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2177         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2178                 goto error;
2179         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2180         if (check) {
2181                 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2182                 if (v < 0)
2183                         goto error;
2184                 if (!v)
2185                         clex->tab = check_integer_feasible(clex->tab);
2186         }
2187         if (update)
2188                 clex->tab = check_samples(clex->tab, ineq, 0);
2189         return;
2190 error:
2191         isl_tab_free(clex->tab);
2192         clex->tab = NULL;
2193 }
2194
2195 static int context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2196 {
2197         struct isl_context *context = (struct isl_context *)user;
2198         context_lex_add_ineq(context, ineq, 0, 0);
2199         return context->op->is_ok(context) ? 0 : -1;
2200 }
2201
2202 /* Check which signs can be obtained by "ineq" on all the currently
2203  * active sample values.  See row_sign for more information.
2204  */
2205 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2206         int strict)
2207 {
2208         int i;
2209         int sgn;
2210         isl_int tmp;
2211         enum isl_tab_row_sign res = isl_tab_row_unknown;
2212
2213         isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2214         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2215                         return isl_tab_row_unknown);
2216
2217         isl_int_init(tmp);
2218         for (i = tab->n_outside; i < tab->n_sample; ++i) {
2219                 isl_seq_inner_product(tab->samples->row[i], ineq,
2220                                         1 + tab->n_var, &tmp);
2221                 sgn = isl_int_sgn(tmp);
2222                 if (sgn > 0 || (sgn == 0 && strict)) {
2223                         if (res == isl_tab_row_unknown)
2224                                 res = isl_tab_row_pos;
2225                         if (res == isl_tab_row_neg)
2226                                 res = isl_tab_row_any;
2227                 }
2228                 if (sgn < 0) {
2229                         if (res == isl_tab_row_unknown)
2230                                 res = isl_tab_row_neg;
2231                         if (res == isl_tab_row_pos)
2232                                 res = isl_tab_row_any;
2233                 }
2234                 if (res == isl_tab_row_any)
2235                         break;
2236         }
2237         isl_int_clear(tmp);
2238
2239         return res;
2240 }
2241
2242 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2243                         isl_int *ineq, int strict)
2244 {
2245         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2246         return tab_ineq_sign(clex->tab, ineq, strict);
2247 }
2248
2249 /* Check whether "ineq" can be added to the tableau without rendering
2250  * it infeasible.
2251  */
2252 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2253 {
2254         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2255         struct isl_tab_undo *snap;
2256         int feasible;
2257
2258         if (!clex->tab)
2259                 return -1;
2260
2261         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2262                 return -1;
2263
2264         snap = isl_tab_snap(clex->tab);
2265         if (isl_tab_push_basis(clex->tab) < 0)
2266                 return -1;
2267         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2268         clex->tab = check_integer_feasible(clex->tab);
2269         if (!clex->tab)
2270                 return -1;
2271         feasible = !clex->tab->empty;
2272         if (isl_tab_rollback(clex->tab, snap) < 0)
2273                 return -1;
2274
2275         return feasible;
2276 }
2277
2278 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2279                 struct isl_vec *div)
2280 {
2281         return get_div(tab, context, div);
2282 }
2283
2284 /* Add a div specified by "div" to the context tableau and return
2285  * 1 if the div is obviously non-negative.
2286  * context_tab_add_div will always return 1, because all variables
2287  * in a isl_context_lex tableau are non-negative.
2288  * However, if we are using a big parameter in the context, then this only
2289  * reflects the non-negativity of the variable used to _encode_ the
2290  * div, i.e., div' = M + div, so we can't draw any conclusions.
2291  */
2292 static int context_lex_add_div(struct isl_context *context, struct isl_vec *div)
2293 {
2294         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2295         int nonneg;
2296         nonneg = context_tab_add_div(clex->tab, div,
2297                                         context_lex_add_ineq_wrap, context);
2298         if (nonneg < 0)
2299                 return -1;
2300         if (clex->tab->M)
2301                 return 0;
2302         return nonneg;
2303 }
2304
2305 static int context_lex_detect_equalities(struct isl_context *context,
2306                 struct isl_tab *tab)
2307 {
2308         return 0;
2309 }
2310
2311 static int context_lex_best_split(struct isl_context *context,
2312                 struct isl_tab *tab)
2313 {
2314         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2315         struct isl_tab_undo *snap;
2316         int r;
2317
2318         snap = isl_tab_snap(clex->tab);
2319         if (isl_tab_push_basis(clex->tab) < 0)
2320                 return -1;
2321         r = best_split(tab, clex->tab);
2322
2323         if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2324                 return -1;
2325
2326         return r;
2327 }
2328
2329 static int context_lex_is_empty(struct isl_context *context)
2330 {
2331         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2332         if (!clex->tab)
2333                 return -1;
2334         return clex->tab->empty;
2335 }
2336
2337 static void *context_lex_save(struct isl_context *context)
2338 {
2339         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2340         struct isl_tab_undo *snap;
2341
2342         snap = isl_tab_snap(clex->tab);
2343         if (isl_tab_push_basis(clex->tab) < 0)
2344                 return NULL;
2345         if (isl_tab_save_samples(clex->tab) < 0)
2346                 return NULL;
2347
2348         return snap;
2349 }
2350
2351 static void context_lex_restore(struct isl_context *context, void *save)
2352 {
2353         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2354         if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2355                 isl_tab_free(clex->tab);
2356                 clex->tab = NULL;
2357         }
2358 }
2359
2360 static int context_lex_is_ok(struct isl_context *context)
2361 {
2362         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2363         return !!clex->tab;
2364 }
2365
2366 /* For each variable in the context tableau, check if the variable can
2367  * only attain non-negative values.  If so, mark the parameter as non-negative
2368  * in the main tableau.  This allows for a more direct identification of some
2369  * cases of violated constraints.
2370  */
2371 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2372         struct isl_tab *context_tab)
2373 {
2374         int i;
2375         struct isl_tab_undo *snap;
2376         struct isl_vec *ineq = NULL;
2377         struct isl_tab_var *var;
2378         int n;
2379
2380         if (context_tab->n_var == 0)
2381                 return tab;
2382
2383         ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2384         if (!ineq)
2385                 goto error;
2386
2387         if (isl_tab_extend_cons(context_tab, 1) < 0)
2388                 goto error;
2389
2390         snap = isl_tab_snap(context_tab);
2391
2392         n = 0;
2393         isl_seq_clr(ineq->el, ineq->size);
2394         for (i = 0; i < context_tab->n_var; ++i) {
2395                 isl_int_set_si(ineq->el[1 + i], 1);
2396                 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2397                         goto error;
2398                 var = &context_tab->con[context_tab->n_con - 1];
2399                 if (!context_tab->empty &&
2400                     !isl_tab_min_at_most_neg_one(context_tab, var)) {
2401                         int j = i;
2402                         if (i >= tab->n_param)
2403                                 j = i - tab->n_param + tab->n_var - tab->n_div;
2404                         tab->var[j].is_nonneg = 1;
2405                         n++;
2406                 }
2407                 isl_int_set_si(ineq->el[1 + i], 0);
2408                 if (isl_tab_rollback(context_tab, snap) < 0)
2409                         goto error;
2410         }
2411
2412         if (context_tab->M && n == context_tab->n_var) {
2413                 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2414                 context_tab->M = 0;
2415         }
2416
2417         isl_vec_free(ineq);
2418         return tab;
2419 error:
2420         isl_vec_free(ineq);
2421         isl_tab_free(tab);
2422         return NULL;
2423 }
2424
2425 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2426         struct isl_context *context, struct isl_tab *tab)
2427 {
2428         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2429         struct isl_tab_undo *snap;
2430
2431         if (!tab)
2432                 return NULL;
2433
2434         snap = isl_tab_snap(clex->tab);
2435         if (isl_tab_push_basis(clex->tab) < 0)
2436                 goto error;
2437
2438         tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2439
2440         if (isl_tab_rollback(clex->tab, snap) < 0)
2441                 goto error;
2442
2443         return tab;
2444 error:
2445         isl_tab_free(tab);
2446         return NULL;
2447 }
2448
2449 static void context_lex_invalidate(struct isl_context *context)
2450 {
2451         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2452         isl_tab_free(clex->tab);
2453         clex->tab = NULL;
2454 }
2455
2456 static void context_lex_free(struct isl_context *context)
2457 {
2458         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2459         isl_tab_free(clex->tab);
2460         free(clex);
2461 }
2462
2463 struct isl_context_op isl_context_lex_op = {
2464         context_lex_detect_nonnegative_parameters,
2465         context_lex_peek_basic_set,
2466         context_lex_peek_tab,
2467         context_lex_add_eq,
2468         context_lex_add_ineq,
2469         context_lex_ineq_sign,
2470         context_lex_test_ineq,
2471         context_lex_get_div,
2472         context_lex_add_div,
2473         context_lex_detect_equalities,
2474         context_lex_best_split,
2475         context_lex_is_empty,
2476         context_lex_is_ok,
2477         context_lex_save,
2478         context_lex_restore,
2479         context_lex_invalidate,
2480         context_lex_free,
2481 };
2482
2483 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
2484 {
2485         struct isl_tab *tab;
2486
2487         bset = isl_basic_set_cow(bset);
2488         if (!bset)
2489                 return NULL;
2490         tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
2491         if (!tab)
2492                 goto error;
2493         if (isl_tab_track_bset(tab, bset) < 0)
2494                 goto error;
2495         tab = isl_tab_init_samples(tab);
2496         return tab;
2497 error:
2498         isl_basic_set_free(bset);
2499         return NULL;
2500 }
2501
2502 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2503 {
2504         struct isl_context_lex *clex;
2505
2506         if (!dom)
2507                 return NULL;
2508
2509         clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2510         if (!clex)
2511                 return NULL;
2512
2513         clex->context.op = &isl_context_lex_op;
2514
2515         clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2516         if (restore_lexmin(clex->tab) < 0)
2517                 goto error;
2518         clex->tab = check_integer_feasible(clex->tab);
2519         if (!clex->tab)
2520                 goto error;
2521
2522         return &clex->context;
2523 error:
2524         clex->context.op->free(&clex->context);
2525         return NULL;
2526 }
2527
2528 struct isl_context_gbr {
2529         struct isl_context context;
2530         struct isl_tab *tab;
2531         struct isl_tab *shifted;
2532         struct isl_tab *cone;
2533 };
2534
2535 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2536         struct isl_context *context, struct isl_tab *tab)
2537 {
2538         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2539         if (!tab)
2540                 return NULL;
2541         return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2542 }
2543
2544 static struct isl_basic_set *context_gbr_peek_basic_set(
2545         struct isl_context *context)
2546 {
2547         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2548         if (!cgbr->tab)
2549                 return NULL;
2550         return isl_tab_peek_bset(cgbr->tab);
2551 }
2552
2553 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2554 {
2555         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2556         return cgbr->tab;
2557 }
2558
2559 /* Initialize the "shifted" tableau of the context, which
2560  * contains the constraints of the original tableau shifted
2561  * by the sum of all negative coefficients.  This ensures
2562  * that any rational point in the shifted tableau can
2563  * be rounded up to yield an integer point in the original tableau.
2564  */
2565 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2566 {
2567         int i, j;
2568         struct isl_vec *cst;
2569         struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2570         unsigned dim = isl_basic_set_total_dim(bset);
2571
2572         cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2573         if (!cst)
2574                 return;
2575
2576         for (i = 0; i < bset->n_ineq; ++i) {
2577                 isl_int_set(cst->el[i], bset->ineq[i][0]);
2578                 for (j = 0; j < dim; ++j) {
2579                         if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2580                                 continue;
2581                         isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2582                                     bset->ineq[i][1 + j]);
2583                 }
2584         }
2585
2586         cgbr->shifted = isl_tab_from_basic_set(bset);
2587
2588         for (i = 0; i < bset->n_ineq; ++i)
2589                 isl_int_set(bset->ineq[i][0], cst->el[i]);
2590
2591         isl_vec_free(cst);
2592 }
2593
2594 /* Check if the shifted tableau is non-empty, and if so
2595  * use the sample point to construct an integer point
2596  * of the context tableau.
2597  */
2598 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2599 {
2600         struct isl_vec *sample;
2601
2602         if (!cgbr->shifted)
2603                 gbr_init_shifted(cgbr);
2604         if (!cgbr->shifted)
2605                 return NULL;
2606         if (cgbr->shifted->empty)
2607                 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2608
2609         sample = isl_tab_get_sample_value(cgbr->shifted);
2610         sample = isl_vec_ceil(sample);
2611
2612         return sample;
2613 }
2614
2615 static struct isl_basic_set *drop_constant_terms(struct isl_basic_set *bset)
2616 {
2617         int i;
2618
2619         if (!bset)
2620                 return NULL;
2621
2622         for (i = 0; i < bset->n_eq; ++i)
2623                 isl_int_set_si(bset->eq[i][0], 0);
2624
2625         for (i = 0; i < bset->n_ineq; ++i)
2626                 isl_int_set_si(bset->ineq[i][0], 0);
2627
2628         return bset;
2629 }
2630
2631 static int use_shifted(struct isl_context_gbr *cgbr)
2632 {
2633         return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2634 }
2635
2636 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2637 {
2638         struct isl_basic_set *bset;
2639         struct isl_basic_set *cone;
2640
2641         if (isl_tab_sample_is_integer(cgbr->tab))
2642                 return isl_tab_get_sample_value(cgbr->tab);
2643
2644         if (use_shifted(cgbr)) {
2645                 struct isl_vec *sample;
2646
2647                 sample = gbr_get_shifted_sample(cgbr);
2648                 if (!sample || sample->size > 0)
2649                         return sample;
2650
2651                 isl_vec_free(sample);
2652         }
2653
2654         if (!cgbr->cone) {
2655                 bset = isl_tab_peek_bset(cgbr->tab);
2656                 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2657                 if (!cgbr->cone)
2658                         return NULL;
2659                 if (isl_tab_track_bset(cgbr->cone, isl_basic_set_dup(bset)) < 0)
2660                         return NULL;
2661         }
2662         if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2663                 return NULL;
2664
2665         if (cgbr->cone->n_dead == cgbr->cone->n_col) {
2666                 struct isl_vec *sample;
2667                 struct isl_tab_undo *snap;
2668
2669                 if (cgbr->tab->basis) {
2670                         if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
2671                                 isl_mat_free(cgbr->tab->basis);
2672                                 cgbr->tab->basis = NULL;
2673                         }
2674                         cgbr->tab->n_zero = 0;
2675                         cgbr->tab->n_unbounded = 0;
2676                 }
2677
2678                 snap = isl_tab_snap(cgbr->tab);
2679
2680                 sample = isl_tab_sample(cgbr->tab);
2681
2682                 if (isl_tab_rollback(cgbr->tab, snap) < 0) {
2683                         isl_vec_free(sample);
2684                         return NULL;
2685                 }
2686
2687                 return sample;
2688         }
2689
2690         cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
2691         cone = drop_constant_terms(cone);
2692         cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
2693         cone = isl_basic_set_underlying_set(cone);
2694         cone = isl_basic_set_gauss(cone, NULL);
2695
2696         bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
2697         bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
2698         bset = isl_basic_set_underlying_set(bset);
2699         bset = isl_basic_set_gauss(bset, NULL);
2700
2701         return isl_basic_set_sample_with_cone(bset, cone);
2702 }
2703
2704 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
2705 {
2706         struct isl_vec *sample;
2707
2708         if (!cgbr->tab)
2709                 return;
2710
2711         if (cgbr->tab->empty)
2712                 return;
2713
2714         sample = gbr_get_sample(cgbr);
2715         if (!sample)
2716                 goto error;
2717
2718         if (sample->size == 0) {
2719                 isl_vec_free(sample);
2720                 if (isl_tab_mark_empty(cgbr->tab) < 0)
2721                         goto error;
2722                 return;
2723         }
2724
2725         cgbr->tab = isl_tab_add_sample(cgbr->tab, sample);
2726
2727         return;
2728 error:
2729         isl_tab_free(cgbr->tab);
2730         cgbr->tab = NULL;
2731 }
2732
2733 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
2734 {
2735         int r;
2736
2737         if (!tab)
2738                 return NULL;
2739
2740         if (isl_tab_extend_cons(tab, 2) < 0)
2741                 goto error;
2742
2743         if (isl_tab_add_eq(tab, eq) < 0)
2744                 goto error;
2745
2746         return tab;
2747 error:
2748         isl_tab_free(tab);
2749         return NULL;
2750 }
2751
2752 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
2753                 int check, int update)
2754 {
2755         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2756
2757         cgbr->tab = add_gbr_eq(cgbr->tab, eq);
2758
2759         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2760                 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
2761                         goto error;
2762                 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
2763                         goto error;
2764         }
2765
2766         if (check) {
2767                 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
2768                 if (v < 0)
2769                         goto error;
2770                 if (!v)
2771                         check_gbr_integer_feasible(cgbr);
2772         }
2773         if (update)
2774                 cgbr->tab = check_samples(cgbr->tab, eq, 1);
2775         return;
2776 error:
2777         isl_tab_free(cgbr->tab);
2778         cgbr->tab = NULL;
2779 }
2780
2781 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
2782 {
2783         if (!cgbr->tab)
2784                 return;
2785
2786         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2787                 goto error;
2788
2789         if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
2790                 goto error;
2791
2792         if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
2793                 int i;
2794                 unsigned dim;
2795                 dim = isl_basic_map_total_dim(cgbr->tab->bmap);
2796
2797                 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
2798                         goto error;
2799
2800                 for (i = 0; i < dim; ++i) {
2801                         if (!isl_int_is_neg(ineq[1 + i]))
2802                                 continue;
2803                         isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
2804                 }
2805
2806                 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
2807                         goto error;
2808
2809                 for (i = 0; i < dim; ++i) {
2810                         if (!isl_int_is_neg(ineq[1 + i]))
2811                                 continue;
2812                         isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
2813                 }
2814         }
2815
2816         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2817                 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
2818                         goto error;
2819                 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
2820                         goto error;
2821         }
2822
2823         return;
2824 error:
2825         isl_tab_free(cgbr->tab);
2826         cgbr->tab = NULL;
2827 }
2828
2829 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
2830                 int check, int update)
2831 {
2832         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2833
2834         add_gbr_ineq(cgbr, ineq);
2835         if (!cgbr->tab)
2836                 return;
2837
2838         if (check) {
2839                 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
2840                 if (v < 0)
2841                         goto error;
2842                 if (!v)
2843                         check_gbr_integer_feasible(cgbr);
2844         }
2845         if (update)
2846                 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
2847         return;
2848 error:
2849         isl_tab_free(cgbr->tab);
2850         cgbr->tab = NULL;
2851 }
2852
2853 static int context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
2854 {
2855         struct isl_context *context = (struct isl_context *)user;
2856         context_gbr_add_ineq(context, ineq, 0, 0);
2857         return context->op->is_ok(context) ? 0 : -1;
2858 }
2859
2860 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
2861                         isl_int *ineq, int strict)
2862 {
2863         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2864         return tab_ineq_sign(cgbr->tab, ineq, strict);
2865 }
2866
2867 /* Check whether "ineq" can be added to the tableau without rendering
2868  * it infeasible.
2869  */
2870 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
2871 {
2872         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2873         struct isl_tab_undo *snap;
2874         struct isl_tab_undo *shifted_snap = NULL;
2875         struct isl_tab_undo *cone_snap = NULL;
2876         int feasible;
2877
2878         if (!cgbr->tab)
2879                 return -1;
2880
2881         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2882                 return -1;
2883
2884         snap = isl_tab_snap(cgbr->tab);
2885         if (cgbr->shifted)
2886                 shifted_snap = isl_tab_snap(cgbr->shifted);
2887         if (cgbr->cone)
2888                 cone_snap = isl_tab_snap(cgbr->cone);
2889         add_gbr_ineq(cgbr, ineq);
2890         check_gbr_integer_feasible(cgbr);
2891         if (!cgbr->tab)
2892                 return -1;
2893         feasible = !cgbr->tab->empty;
2894         if (isl_tab_rollback(cgbr->tab, snap) < 0)
2895                 return -1;
2896         if (shifted_snap) {
2897                 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
2898                         return -1;
2899         } else if (cgbr->shifted) {
2900                 isl_tab_free(cgbr->shifted);
2901                 cgbr->shifted = NULL;
2902         }
2903         if (cone_snap) {
2904                 if (isl_tab_rollback(cgbr->cone, cone_snap))
2905                         return -1;
2906         } else if (cgbr->cone) {
2907                 isl_tab_free(cgbr->cone);
2908                 cgbr->cone = NULL;
2909         }
2910
2911         return feasible;
2912 }
2913
2914 /* Return the column of the last of the variables associated to
2915  * a column that has a non-zero coefficient.
2916  * This function is called in a context where only coefficients
2917  * of parameters or divs can be non-zero.
2918  */
2919 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
2920 {
2921         int i;
2922         int col;
2923         unsigned dim = tab->n_var - tab->n_param - tab->n_div;
2924
2925         if (tab->n_var == 0)
2926                 return -1;
2927
2928         for (i = tab->n_var - 1; i >= 0; --i) {
2929                 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
2930                         continue;
2931                 if (tab->var[i].is_row)
2932                         continue;
2933                 col = tab->var[i].index;
2934                 if (!isl_int_is_zero(p[col]))
2935                         return col;
2936         }
2937
2938         return -1;
2939 }
2940
2941 /* Look through all the recently added equalities in the context
2942  * to see if we can propagate any of them to the main tableau.
2943  *
2944  * The newly added equalities in the context are encoded as pairs
2945  * of inequalities starting at inequality "first".
2946  *
2947  * We tentatively add each of these equalities to the main tableau
2948  * and if this happens to result in a row with a final coefficient
2949  * that is one or negative one, we use it to kill a column
2950  * in the main tableau.  Otherwise, we discard the tentatively
2951  * added row.
2952  */
2953 static void propagate_equalities(struct isl_context_gbr *cgbr,
2954         struct isl_tab *tab, unsigned first)
2955 {
2956         int i;
2957         struct isl_vec *eq = NULL;
2958
2959         eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
2960         if (!eq)
2961                 goto error;
2962
2963         if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
2964                 goto error;
2965
2966         isl_seq_clr(eq->el + 1 + tab->n_param,
2967                     tab->n_var - tab->n_param - tab->n_div);
2968         for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
2969                 int j;
2970                 int r;
2971                 struct isl_tab_undo *snap;
2972                 snap = isl_tab_snap(tab);
2973
2974                 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
2975                 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
2976                             cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
2977                             tab->n_div);
2978
2979                 r = isl_tab_add_row(tab, eq->el);
2980                 if (r < 0)
2981                         goto error;
2982                 r = tab->con[r].index;
2983                 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
2984                 if (j < 0 || j < tab->n_dead ||
2985                     !isl_int_is_one(tab->mat->row[r][0]) ||
2986                     (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
2987                      !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
2988                         if (isl_tab_rollback(tab, snap) < 0)
2989                                 goto error;
2990                         continue;
2991                 }
2992                 if (isl_tab_pivot(tab, r, j) < 0)
2993                         goto error;
2994                 if (isl_tab_kill_col(tab, j) < 0)
2995                         goto error;
2996
2997                 if (restore_lexmin(tab) < 0)
2998                         goto error;
2999         }
3000
3001         isl_vec_free(eq);
3002
3003         return;
3004 error:
3005         isl_vec_free(eq);
3006         isl_tab_free(cgbr->tab);
3007         cgbr->tab = NULL;
3008 }
3009
3010 static int context_gbr_detect_equalities(struct isl_context *context,
3011         struct isl_tab *tab)
3012 {
3013         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3014         struct isl_ctx *ctx;
3015         int i;
3016         enum isl_lp_result res;
3017         unsigned n_ineq;
3018
3019         ctx = cgbr->tab->mat->ctx;
3020
3021         if (!cgbr->cone) {
3022                 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3023                 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3024                 if (!cgbr->cone)
3025                         goto error;
3026                 if (isl_tab_track_bset(cgbr->cone, isl_basic_set_dup(bset)) < 0)
3027                         goto error;
3028         }
3029         if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3030                 goto error;
3031
3032         n_ineq = cgbr->tab->bmap->n_ineq;
3033         cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3034         if (cgbr->tab && cgbr->tab->bmap->n_ineq > n_ineq)
3035                 propagate_equalities(cgbr, tab, n_ineq);
3036
3037         return 0;
3038 error:
3039         isl_tab_free(cgbr->tab);
3040         cgbr->tab = NULL;
3041         return -1;
3042 }
3043
3044 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3045                 struct isl_vec *div)
3046 {
3047         return get_div(tab, context, div);
3048 }
3049
3050 static int context_gbr_add_div(struct isl_context *context, struct isl_vec *div)
3051 {
3052         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3053         if (cgbr->cone) {
3054                 int k;
3055
3056                 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3057                         return -1;
3058                 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3059                         return -1;
3060                 if (isl_tab_allocate_var(cgbr->cone) <0)
3061                         return -1;
3062
3063                 cgbr->cone->bmap = isl_basic_map_extend_dim(cgbr->cone->bmap,
3064                         isl_basic_map_get_dim(cgbr->cone->bmap), 1, 0, 2);
3065                 k = isl_basic_map_alloc_div(cgbr->cone->bmap);
3066                 if (k < 0)
3067                         return -1;
3068                 isl_seq_cpy(cgbr->cone->bmap->div[k], div->el, div->size);
3069                 if (isl_tab_push(cgbr->cone, isl_tab_undo_bmap_div) < 0)
3070                         return -1;
3071         }
3072         return context_tab_add_div(cgbr->tab, div,
3073                                         context_gbr_add_ineq_wrap, context);
3074 }
3075
3076 static int context_gbr_best_split(struct isl_context *context,
3077                 struct isl_tab *tab)
3078 {
3079         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3080         struct isl_tab_undo *snap;
3081         int r;
3082
3083         snap = isl_tab_snap(cgbr->tab);
3084         r = best_split(tab, cgbr->tab);
3085
3086         if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3087                 return -1;
3088
3089         return r;
3090 }
3091
3092 static int context_gbr_is_empty(struct isl_context *context)
3093 {
3094         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3095         if (!cgbr->tab)
3096                 return -1;
3097         return cgbr->tab->empty;
3098 }
3099
3100 struct isl_gbr_tab_undo {
3101         struct isl_tab_undo *tab_snap;
3102         struct isl_tab_undo *shifted_snap;
3103         struct isl_tab_undo *cone_snap;
3104 };
3105
3106 static void *context_gbr_save(struct isl_context *context)
3107 {
3108         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3109         struct isl_gbr_tab_undo *snap;
3110
3111         snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3112         if (!snap)
3113                 return NULL;
3114
3115         snap->tab_snap = isl_tab_snap(cgbr->tab);
3116         if (isl_tab_save_samples(cgbr->tab) < 0)
3117                 goto error;
3118
3119         if (cgbr->shifted)
3120                 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3121         else
3122                 snap->shifted_snap = NULL;
3123
3124         if (cgbr->cone)
3125                 snap->cone_snap = isl_tab_snap(cgbr->cone);
3126         else
3127                 snap->cone_snap = NULL;
3128
3129         return snap;
3130 error:
3131         free(snap);
3132         return NULL;
3133 }
3134
3135 static void context_gbr_restore(struct isl_context *context, void *save)
3136 {
3137         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3138         struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3139         if (!snap)
3140                 goto error;
3141         if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0) {
3142                 isl_tab_free(cgbr->tab);
3143                 cgbr->tab = NULL;
3144         }
3145
3146         if (snap->shifted_snap) {
3147                 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3148                         goto error;
3149         } else if (cgbr->shifted) {
3150                 isl_tab_free(cgbr->shifted);
3151                 cgbr->shifted = NULL;
3152         }
3153
3154         if (snap->cone_snap) {
3155                 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3156                         goto error;
3157         } else if (cgbr->cone) {
3158                 isl_tab_free(cgbr->cone);
3159                 cgbr->cone = NULL;
3160         }
3161
3162         free(snap);
3163
3164         return;
3165 error:
3166         free(snap);
3167         isl_tab_free(cgbr->tab);
3168         cgbr->tab = NULL;
3169 }
3170
3171 static int context_gbr_is_ok(struct isl_context *context)
3172 {
3173         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3174         return !!cgbr->tab;
3175 }
3176
3177 static void context_gbr_invalidate(struct isl_context *context)
3178 {
3179         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3180         isl_tab_free(cgbr->tab);
3181         cgbr->tab = NULL;
3182 }
3183
3184 static void context_gbr_free(struct isl_context *context)
3185 {
3186         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3187         isl_tab_free(cgbr->tab);
3188         isl_tab_free(cgbr->shifted);
3189         isl_tab_free(cgbr->cone);
3190         free(cgbr);
3191 }
3192
3193 struct isl_context_op isl_context_gbr_op = {
3194         context_gbr_detect_nonnegative_parameters,
3195         context_gbr_peek_basic_set,
3196         context_gbr_peek_tab,
3197         context_gbr_add_eq,
3198         context_gbr_add_ineq,
3199         context_gbr_ineq_sign,
3200         context_gbr_test_ineq,
3201         context_gbr_get_div,
3202         context_gbr_add_div,
3203         context_gbr_detect_equalities,
3204         context_gbr_best_split,
3205         context_gbr_is_empty,
3206         context_gbr_is_ok,
3207         context_gbr_save,
3208         context_gbr_restore,
3209         context_gbr_invalidate,
3210         context_gbr_free,
3211 };
3212
3213 static struct isl_context *isl_context_gbr_alloc(struct isl_basic_set *dom)
3214 {
3215         struct isl_context_gbr *cgbr;
3216
3217         if (!dom)
3218                 return NULL;
3219
3220         cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3221         if (!cgbr)
3222                 return NULL;
3223
3224         cgbr->context.op = &isl_context_gbr_op;
3225
3226         cgbr->shifted = NULL;
3227         cgbr->cone = NULL;
3228         cgbr->tab = isl_tab_from_basic_set(dom);
3229         cgbr->tab = isl_tab_init_samples(cgbr->tab);
3230         if (!cgbr->tab)
3231                 goto error;
3232         if (isl_tab_track_bset(cgbr->tab,
3233                                 isl_basic_set_cow(isl_basic_set_copy(dom))) < 0)
3234                 goto error;
3235         check_gbr_integer_feasible(cgbr);
3236
3237         return &cgbr->context;
3238 error:
3239         cgbr->context.op->free(&cgbr->context);
3240         return NULL;
3241 }
3242
3243 static struct isl_context *isl_context_alloc(struct isl_basic_set *dom)
3244 {
3245         if (!dom)
3246                 return NULL;
3247
3248         if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3249                 return isl_context_lex_alloc(dom);
3250         else
3251                 return isl_context_gbr_alloc(dom);
3252 }
3253
3254 /* Construct an isl_sol_map structure for accumulating the solution.
3255  * If track_empty is set, then we also keep track of the parts
3256  * of the context where there is no solution.
3257  * If max is set, then we are solving a maximization, rather than
3258  * a minimization problem, which means that the variables in the
3259  * tableau have value "M - x" rather than "M + x".
3260  */
3261 static struct isl_sol_map *sol_map_init(struct isl_basic_map *bmap,
3262         struct isl_basic_set *dom, int track_empty, int max)
3263 {
3264         struct isl_sol_map *sol_map = NULL;
3265
3266         if (!bmap)
3267                 goto error;
3268
3269         sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3270         if (!sol_map)
3271                 goto error;
3272
3273         sol_map->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3274         sol_map->sol.dec_level.callback.run = &sol_dec_level_wrap;
3275         sol_map->sol.dec_level.sol = &sol_map->sol;
3276         sol_map->sol.max = max;
3277         sol_map->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
3278         sol_map->sol.add = &sol_map_add_wrap;
3279         sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3280         sol_map->sol.free = &sol_map_free_wrap;
3281         sol_map->map = isl_map_alloc_dim(isl_basic_map_get_dim(bmap), 1,
3282                                             ISL_MAP_DISJOINT);
3283         if (!sol_map->map)
3284                 goto error;
3285
3286         sol_map->sol.context = isl_context_alloc(dom);
3287         if (!sol_map->sol.context)
3288                 goto error;
3289
3290         if (track_empty) {
3291                 sol_map->empty = isl_set_alloc_dim(isl_basic_set_get_dim(dom),
3292                                                         1, ISL_SET_DISJOINT);
3293                 if (!sol_map->empty)
3294                         goto error;
3295         }
3296
3297         isl_basic_set_free(dom);
3298         return sol_map;
3299 error:
3300         isl_basic_set_free(dom);
3301         sol_map_free(sol_map);
3302         return NULL;
3303 }
3304
3305 /* Check whether all coefficients of (non-parameter) variables
3306  * are non-positive, meaning that no pivots can be performed on the row.
3307  */
3308 static int is_critical(struct isl_tab *tab, int row)
3309 {
3310         int j;
3311         unsigned off = 2 + tab->M;
3312
3313         for (j = tab->n_dead; j < tab->n_col; ++j) {
3314                 if (tab->col_var[j] >= 0 &&
3315                     (tab->col_var[j] < tab->n_param  ||
3316                     tab->col_var[j] >= tab->n_var - tab->n_div))
3317                         continue;
3318
3319                 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3320                         return 0;
3321         }
3322
3323         return 1;
3324 }
3325
3326 /* Check whether the inequality represented by vec is strict over the integers,
3327  * i.e., there are no integer values satisfying the constraint with
3328  * equality.  This happens if the gcd of the coefficients is not a divisor
3329  * of the constant term.  If so, scale the constraint down by the gcd
3330  * of the coefficients.
3331  */
3332 static int is_strict(struct isl_vec *vec)
3333 {
3334         isl_int gcd;
3335         int strict = 0;
3336
3337         isl_int_init(gcd);
3338         isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3339         if (!isl_int_is_one(gcd)) {
3340                 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3341                 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3342                 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3343         }
3344         isl_int_clear(gcd);
3345
3346         return strict;
3347 }
3348
3349 /* Determine the sign of the given row of the main tableau.
3350  * The result is one of
3351  *      isl_tab_row_pos: always non-negative; no pivot needed
3352  *      isl_tab_row_neg: always non-positive; pivot
3353  *      isl_tab_row_any: can be both positive and negative; split
3354  *
3355  * We first handle some simple cases
3356  *      - the row sign may be known already
3357  *      - the row may be obviously non-negative
3358  *      - the parametric constant may be equal to that of another row
3359  *        for which we know the sign.  This sign will be either "pos" or
3360  *        "any".  If it had been "neg" then we would have pivoted before.
3361  *
3362  * If none of these cases hold, we check the value of the row for each
3363  * of the currently active samples.  Based on the signs of these values
3364  * we make an initial determination of the sign of the row.
3365  *
3366  *      all zero                        ->      unk(nown)
3367  *      all non-negative                ->      pos
3368  *      all non-positive                ->      neg
3369  *      both negative and positive      ->      all
3370  *
3371  * If we end up with "all", we are done.
3372  * Otherwise, we perform a check for positive and/or negative
3373  * values as follows.
3374  *
3375  *      samples        neg             unk             pos
3376  *      <0 ?                        Y        N      Y        N
3377  *                                          pos    any      pos
3378  *      >0 ?         Y      N    Y     N
3379  *                  any    neg  any   neg
3380  *
3381  * There is no special sign for "zero", because we can usually treat zero
3382  * as either non-negative or non-positive, whatever works out best.
3383  * However, if the row is "critical", meaning that pivoting is impossible
3384  * then we don't want to limp zero with the non-positive case, because
3385  * then we we would lose the solution for those values of the parameters
3386  * where the value of the row is zero.  Instead, we treat 0 as non-negative
3387  * ensuring a split if the row can attain both zero and negative values.
3388  * The same happens when the original constraint was one that could not
3389  * be satisfied with equality by any integer values of the parameters.
3390  * In this case, we normalize the constraint, but then a value of zero
3391  * for the normalized constraint is actually a positive value for the
3392  * original constraint, so again we need to treat zero as non-negative.
3393  * In both these cases, we have the following decision tree instead:
3394  *
3395  *      all non-negative                ->      pos
3396  *      all negative                    ->      neg
3397  *      both negative and non-negative  ->      all
3398  *
3399  *      samples        neg                             pos
3400  *      <0 ?                                        Y        N
3401  *                                                 any      pos
3402  *      >=0 ?        Y      N
3403  *                  any    neg
3404  */
3405 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3406         struct isl_sol *sol, int row)
3407 {
3408         struct isl_vec *ineq = NULL;
3409         enum isl_tab_row_sign res = isl_tab_row_unknown;
3410         int critical;
3411         int strict;
3412         int row2;
3413
3414         if (tab->row_sign[row] != isl_tab_row_unknown)
3415                 return tab->row_sign[row];
3416         if (is_obviously_nonneg(tab, row))
3417                 return isl_tab_row_pos;
3418         for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3419                 if (tab->row_sign[row2] == isl_tab_row_unknown)
3420                         continue;
3421                 if (identical_parameter_line(tab, row, row2))
3422                         return tab->row_sign[row2];
3423         }
3424
3425         critical = is_critical(tab, row);
3426
3427         ineq = get_row_parameter_ineq(tab, row);
3428         if (!ineq)
3429                 goto error;
3430
3431         strict = is_strict(ineq);
3432
3433         res = sol->context->op->ineq_sign(sol->context, ineq->el,
3434                                           critical || strict);
3435
3436         if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3437                 /* test for negative values */
3438                 int feasible;
3439                 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3440                 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3441
3442                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3443                 if (feasible < 0)
3444                         goto error;
3445                 if (!feasible)
3446                         res = isl_tab_row_pos;
3447                 else
3448                         res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3449                                                            : isl_tab_row_any;
3450                 if (res == isl_tab_row_neg) {
3451                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3452                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3453                 }
3454         }
3455
3456         if (res == isl_tab_row_neg) {
3457                 /* test for positive values */
3458                 int feasible;
3459                 if (!critical && !strict)
3460                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3461
3462                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3463                 if (feasible < 0)
3464                         goto error;
3465                 if (feasible)
3466                         res = isl_tab_row_any;
3467         }
3468
3469         isl_vec_free(ineq);
3470         return res;
3471 error:
3472         isl_vec_free(ineq);
3473         return isl_tab_row_unknown;
3474 }
3475
3476 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3477
3478 /* Find solutions for values of the parameters that satisfy the given
3479  * inequality.
3480  *
3481  * We currently take a snapshot of the context tableau that is reset
3482  * when we return from this function, while we make a copy of the main
3483  * tableau, leaving the original main tableau untouched.
3484  * These are fairly arbitrary choices.  Making a copy also of the context
3485  * tableau would obviate the need to undo any changes made to it later,
3486  * while taking a snapshot of the main tableau could reduce memory usage.
3487  * If we were to switch to taking a snapshot of the main tableau,
3488  * we would have to keep in mind that we need to save the row signs
3489  * and that we need to do this before saving the current basis
3490  * such that the basis has been restore before we restore the row signs.
3491  */
3492 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3493 {
3494         void *saved;
3495
3496         if (!sol->context)
3497                 goto error;
3498         saved = sol->context->op->save(sol->context);
3499
3500         tab = isl_tab_dup(tab);
3501         if (!tab)
3502                 goto error;
3503
3504         sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3505
3506         find_solutions(sol, tab);
3507
3508         if (!sol->error)
3509                 sol->context->op->restore(sol->context, saved);
3510         return;
3511 error:
3512         sol->error = 1;
3513 }
3514
3515 /* Record the absence of solutions for those values of the parameters
3516  * that do not satisfy the given inequality with equality.
3517  */
3518 static void no_sol_in_strict(struct isl_sol *sol,
3519         struct isl_tab *tab, struct isl_vec *ineq)
3520 {
3521         int empty;
3522         void *saved;
3523
3524         if (!sol->context || sol->error)
3525                 goto error;
3526         saved = sol->context->op->save(sol->context);
3527
3528         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3529
3530         sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3531         if (!sol->context)
3532                 goto error;
3533
3534         empty = tab->empty;
3535         tab->empty = 1;
3536         sol_add(sol, tab);
3537         tab->empty = empty;
3538
3539         isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3540
3541         sol->context->op->restore(sol->context, saved);
3542         return;
3543 error:
3544         sol->error = 1;
3545 }
3546
3547 /* Compute the lexicographic minimum of the set represented by the main
3548  * tableau "tab" within the context "sol->context_tab".
3549  * On entry the sample value of the main tableau is lexicographically
3550  * less than or equal to this lexicographic minimum.
3551  * Pivots are performed until a feasible point is found, which is then
3552  * necessarily equal to the minimum, or until the tableau is found to
3553  * be infeasible.  Some pivots may need to be performed for only some
3554  * feasible values of the context tableau.  If so, the context tableau
3555  * is split into a part where the pivot is needed and a part where it is not.
3556  *
3557  * Whenever we enter the main loop, the main tableau is such that no
3558  * "obvious" pivots need to be performed on it, where "obvious" means
3559  * that the given row can be seen to be negative without looking at
3560  * the context tableau.  In particular, for non-parametric problems,
3561  * no pivots need to be performed on the main tableau.
3562  * The caller of find_solutions is responsible for making this property
3563  * hold prior to the first iteration of the loop, while restore_lexmin
3564  * is called before every other iteration.
3565  *
3566  * Inside the main loop, we first examine the signs of the rows of
3567  * the main tableau within the context of the context tableau.
3568  * If we find a row that is always non-positive for all values of
3569  * the parameters satisfying the context tableau and negative for at
3570  * least one value of the parameters, we perform the appropriate pivot
3571  * and start over.  An exception is the case where no pivot can be
3572  * performed on the row.  In this case, we require that the sign of
3573  * the row is negative for all values of the parameters (rather than just
3574  * non-positive).  This special case is handled inside row_sign, which
3575  * will say that the row can have any sign if it determines that it can
3576  * attain both negative and zero values.
3577  *
3578  * If we can't find a row that always requires a pivot, but we can find
3579  * one or more rows that require a pivot for some values of the parameters
3580  * (i.e., the row can attain both positive and negative signs), then we split
3581  * the context tableau into two parts, one where we force the sign to be
3582  * non-negative and one where we force is to be negative.
3583  * The non-negative part is handled by a recursive call (through find_in_pos).
3584  * Upon returning from this call, we continue with the negative part and
3585  * perform the required pivot.
3586  *
3587  * If no such rows can be found, all rows are non-negative and we have
3588  * found a (rational) feasible point.  If we only wanted a rational point
3589  * then we are done.
3590  * Otherwise, we check if all values of the sample point of the tableau
3591  * are integral for the variables.  If so, we have found the minimal
3592  * integral point and we are done.
3593  * If the sample point is not integral, then we need to make a distinction
3594  * based on whether the constant term is non-integral or the coefficients
3595  * of the parameters.  Furthermore, in order to decide how to handle
3596  * the non-integrality, we also need to know whether the coefficients
3597  * of the other columns in the tableau are integral.  This leads
3598  * to the following table.  The first two rows do not correspond
3599  * to a non-integral sample point and are only mentioned for completeness.
3600  *
3601  *      constant        parameters      other
3602  *
3603  *      int             int             int     |
3604  *      int             int             rat     | -> no problem
3605  *
3606  *      rat             int             int       -> fail
3607  *
3608  *      rat             int             rat       -> cut
3609  *
3610  *      int             rat             rat     |
3611  *      rat             rat             rat     | -> parametric cut
3612  *
3613  *      int             rat             int     |
3614  *      rat             rat             int     | -> split context
3615  *
3616  * If the parametric constant is completely integral, then there is nothing
3617  * to be done.  If the constant term is non-integral, but all the other
3618  * coefficient are integral, then there is nothing that can be done
3619  * and the tableau has no integral solution.
3620  * If, on the other hand, one or more of the other columns have rational
3621  * coefficients, but the parameter coefficients are all integral, then
3622  * we can perform a regular (non-parametric) cut.
3623  * Finally, if there is any parameter coefficient that is non-integral,
3624  * then we need to involve the context tableau.  There are two cases here.
3625  * If at least one other column has a rational coefficient, then we
3626  * can perform a parametric cut in the main tableau by adding a new
3627  * integer division in the context tableau.
3628  * If all other columns have integral coefficients, then we need to
3629  * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
3630  * is always integral.  We do this by introducing an integer division
3631  * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
3632  * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
3633  * Since q is expressed in the tableau as
3634  *      c + \sum a_i y_i - m q >= 0
3635  *      -c - \sum a_i y_i + m q + m - 1 >= 0
3636  * it is sufficient to add the inequality
3637  *      -c - \sum a_i y_i + m q >= 0
3638  * In the part of the context where this inequality does not hold, the
3639  * main tableau is marked as being empty.
3640  */
3641 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
3642 {
3643         struct isl_context *context;
3644         int r;
3645
3646         if (!tab || sol->error)
3647                 goto error;
3648
3649         context = sol->context;
3650
3651         if (tab->empty)
3652                 goto done;
3653         if (context->op->is_empty(context))
3654                 goto done;
3655
3656         for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
3657                 int flags;
3658                 int row;
3659                 enum isl_tab_row_sign sgn;
3660                 int split = -1;
3661                 int n_split = 0;
3662
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                         sgn = row_sign(tab, sol, row);
3667                         if (!sgn)
3668                                 goto error;
3669                         tab->row_sign[row] = sgn;
3670                         if (sgn == isl_tab_row_any)
3671                                 n_split++;
3672                         if (sgn == isl_tab_row_any && split == -1)
3673                                 split = row;
3674                         if (sgn == isl_tab_row_neg)
3675                                 break;
3676                 }
3677                 if (row < tab->n_row)
3678                         continue;
3679                 if (split != -1) {
3680                         struct isl_vec *ineq;
3681                         if (n_split != 1)
3682                                 split = context->op->best_split(context, tab);
3683                         if (split < 0)
3684                                 goto error;
3685                         ineq = get_row_parameter_ineq(tab, split);
3686                         if (!ineq)
3687                                 goto error;
3688                         is_strict(ineq);
3689                         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3690                                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3691                                         continue;
3692                                 if (tab->row_sign[row] == isl_tab_row_any)
3693                                         tab->row_sign[row] = isl_tab_row_unknown;
3694                         }
3695                         tab->row_sign[split] = isl_tab_row_pos;
3696                         sol_inc_level(sol);
3697                         find_in_pos(sol, tab, ineq->el);
3698                         tab->row_sign[split] = isl_tab_row_neg;
3699                         row = split;
3700                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3701                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3702                         if (!sol->error)
3703                                 context->op->add_ineq(context, ineq->el, 0, 1);
3704                         isl_vec_free(ineq);
3705                         if (sol->error)
3706                                 goto error;
3707                         continue;
3708                 }
3709                 if (tab->rational)
3710                         break;
3711                 row = first_non_integer_row(tab, &flags);
3712                 if (row < 0)
3713                         break;
3714                 if (ISL_FL_ISSET(flags, I_PAR)) {
3715                         if (ISL_FL_ISSET(flags, I_VAR)) {
3716                                 if (isl_tab_mark_empty(tab) < 0)
3717                                         goto error;
3718                                 break;
3719                         }
3720                         row = add_cut(tab, row);
3721                 } else if (ISL_FL_ISSET(flags, I_VAR)) {
3722                         struct isl_vec *div;
3723                         struct isl_vec *ineq;
3724                         int d;
3725                         div = get_row_split_div(tab, row);
3726                         if (!div)
3727                                 goto error;
3728                         d = context->op->get_div(context, tab, div);
3729                         isl_vec_free(div);
3730                         if (d < 0)
3731                                 goto error;
3732                         ineq = ineq_for_div(context->op->peek_basic_set(context), d);
3733                         if (!ineq)
3734                                 goto error;
3735                         sol_inc_level(sol);
3736                         no_sol_in_strict(sol, tab, ineq);
3737                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3738                         context->op->add_ineq(context, ineq->el, 1, 1);
3739                         isl_vec_free(ineq);
3740                         if (sol->error || !context->op->is_ok(context))
3741                                 goto error;
3742                         tab = set_row_cst_to_div(tab, row, d);
3743                         if (context->op->is_empty(context))
3744                                 break;
3745                 } else
3746                         row = add_parametric_cut(tab, row, context);
3747                 if (row < 0)
3748                         goto error;
3749         }
3750         if (r < 0)
3751                 goto error;
3752 done:
3753         sol_add(sol, tab);
3754         isl_tab_free(tab);
3755         return;
3756 error:
3757         isl_tab_free(tab);
3758         sol->error = 1;
3759 }
3760
3761 /* Compute the lexicographic minimum of the set represented by the main
3762  * tableau "tab" within the context "sol->context_tab".
3763  *
3764  * As a preprocessing step, we first transfer all the purely parametric
3765  * equalities from the main tableau to the context tableau, i.e.,
3766  * parameters that have been pivoted to a row.
3767  * These equalities are ignored by the main algorithm, because the
3768  * corresponding rows may not be marked as being non-negative.
3769  * In parts of the context where the added equality does not hold,
3770  * the main tableau is marked as being empty.
3771  */
3772 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
3773 {
3774         int row;
3775
3776         if (!tab)
3777                 goto error;
3778
3779         sol->level = 0;
3780
3781         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3782                 int p;
3783                 struct isl_vec *eq;
3784
3785                 if (tab->row_var[row] < 0)
3786                         continue;
3787                 if (tab->row_var[row] >= tab->n_param &&
3788                     tab->row_var[row] < tab->n_var - tab->n_div)
3789                         continue;
3790                 if (tab->row_var[row] < tab->n_param)
3791                         p = tab->row_var[row];
3792                 else
3793                         p = tab->row_var[row]
3794                                 + tab->n_param - (tab->n_var - tab->n_div);
3795
3796                 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
3797                 if (!eq)
3798                         goto error;
3799                 get_row_parameter_line(tab, row, eq->el);
3800                 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
3801                 eq = isl_vec_normalize(eq);
3802
3803                 sol_inc_level(sol);
3804                 no_sol_in_strict(sol, tab, eq);
3805
3806                 isl_seq_neg(eq->el, eq->el, eq->size);
3807                 sol_inc_level(sol);
3808                 no_sol_in_strict(sol, tab, eq);
3809                 isl_seq_neg(eq->el, eq->el, eq->size);
3810
3811                 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
3812
3813                 isl_vec_free(eq);
3814
3815                 if (isl_tab_mark_redundant(tab, row) < 0)
3816                         goto error;
3817
3818                 if (sol->context->op->is_empty(sol->context))
3819                         break;
3820
3821                 row = tab->n_redundant - 1;
3822         }
3823
3824         find_solutions(sol, tab);
3825
3826         sol->level = 0;
3827         sol_pop(sol);
3828
3829         return;
3830 error:
3831         isl_tab_free(tab);
3832         sol->error = 1;
3833 }
3834
3835 static void sol_map_find_solutions(struct isl_sol_map *sol_map,
3836         struct isl_tab *tab)
3837 {
3838         find_solutions_main(&sol_map->sol, tab);
3839 }
3840
3841 /* Check if integer division "div" of "dom" also occurs in "bmap".
3842  * If so, return its position within the divs.
3843  * If not, return -1.
3844  */
3845 static int find_context_div(struct isl_basic_map *bmap,
3846         struct isl_basic_set *dom, unsigned div)
3847 {
3848         int i;
3849         unsigned b_dim = isl_dim_total(bmap->dim);
3850         unsigned d_dim = isl_dim_total(dom->dim);
3851
3852         if (isl_int_is_zero(dom->div[div][0]))
3853                 return -1;
3854         if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
3855                 return -1;
3856
3857         for (i = 0; i < bmap->n_div; ++i) {
3858                 if (isl_int_is_zero(bmap->div[i][0]))
3859                         continue;
3860                 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
3861                                            (b_dim - d_dim) + bmap->n_div) != -1)
3862                         continue;
3863                 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
3864                         return i;
3865         }
3866         return -1;
3867 }
3868
3869 /* The correspondence between the variables in the main tableau,
3870  * the context tableau, and the input map and domain is as follows.
3871  * The first n_param and the last n_div variables of the main tableau
3872  * form the variables of the context tableau.
3873  * In the basic map, these n_param variables correspond to the
3874  * parameters and the input dimensions.  In the domain, they correspond
3875  * to the parameters and the set dimensions.
3876  * The n_div variables correspond to the integer divisions in the domain.
3877  * To ensure that everything lines up, we may need to copy some of the
3878  * integer divisions of the domain to the map.  These have to be placed
3879  * in the same order as those in the context and they have to be placed
3880  * after any other integer divisions that the map may have.
3881  * This function performs the required reordering.
3882  */
3883 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
3884         struct isl_basic_set *dom)
3885 {
3886         int i;
3887         int common = 0;
3888         int other;
3889
3890         for (i = 0; i < dom->n_div; ++i)
3891                 if (find_context_div(bmap, dom, i) != -1)
3892                         common++;
3893         other = bmap->n_div - common;
3894         if (dom->n_div - common > 0) {
3895                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
3896                                 dom->n_div - common, 0, 0);
3897                 if (!bmap)
3898                         return NULL;
3899         }
3900         for (i = 0; i < dom->n_div; ++i) {
3901                 int pos = find_context_div(bmap, dom, i);
3902                 if (pos < 0) {
3903                         pos = isl_basic_map_alloc_div(bmap);
3904                         if (pos < 0)
3905                                 goto error;
3906                         isl_int_set_si(bmap->div[pos][0], 0);
3907                 }
3908                 if (pos != other + i)
3909                         isl_basic_map_swap_div(bmap, pos, other + i);
3910         }
3911         return bmap;
3912 error:
3913         isl_basic_map_free(bmap);
3914         return NULL;
3915 }
3916
3917 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
3918  * some obvious symmetries.
3919  *
3920  * We make sure the divs in the domain are properly ordered,
3921  * because they will be added one by one in the given order
3922  * during the construction of the solution map.
3923  */
3924 static __isl_give isl_map *basic_map_partial_lexopt_base(
3925         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
3926         __isl_give isl_set **empty, int max)
3927 {
3928         isl_map *result = NULL;
3929         struct isl_tab *tab;
3930         struct isl_sol_map *sol_map = NULL;
3931         struct isl_context *context;
3932
3933         if (dom->n_div) {
3934                 dom = isl_basic_set_order_divs(dom);
3935                 bmap = align_context_divs(bmap, dom);
3936         }
3937         sol_map = sol_map_init(bmap, dom, !!empty, max);
3938         if (!sol_map)
3939                 goto error;
3940
3941         context = sol_map->sol.context;
3942         if (isl_basic_set_fast_is_empty(context->op->peek_basic_set(context)))
3943                 /* nothing */;
3944         else if (isl_basic_map_fast_is_empty(bmap))
3945                 sol_map_add_empty_if_needed(sol_map,
3946                     isl_basic_set_copy(context->op->peek_basic_set(context)));
3947         else {
3948                 tab = tab_for_lexmin(bmap,
3949                                     context->op->peek_basic_set(context), 1, max);
3950                 tab = context->op->detect_nonnegative_parameters(context, tab);
3951                 sol_map_find_solutions(sol_map, tab);
3952         }
3953         if (sol_map->sol.error)
3954                 goto error;
3955
3956         result = isl_map_copy(sol_map->map);
3957         if (empty)
3958                 *empty = isl_set_copy(sol_map->empty);
3959         sol_free(&sol_map->sol);
3960         isl_basic_map_free(bmap);
3961         return result;
3962 error:
3963         sol_free(&sol_map->sol);
3964         isl_basic_map_free(bmap);
3965         return NULL;
3966 }
3967
3968 /* Structure used during detection of parallel constraints.
3969  * n_in: number of "input" variables: isl_dim_param + isl_dim_in
3970  * n_out: number of "output" variables: isl_dim_out + isl_dim_div
3971  * val: the coefficients of the output variables
3972  */
3973 struct isl_constraint_equal_info {
3974         isl_basic_map *bmap;
3975         unsigned n_in;
3976         unsigned n_out;
3977         isl_int *val;
3978 };
3979
3980 /* Check whether the coefficients of the output variables
3981  * of the constraint in "entry" are equal to info->val.
3982  */
3983 static int constraint_equal(const void *entry, const void *val)
3984 {
3985         isl_int **row = (isl_int **)entry;
3986         const struct isl_constraint_equal_info *info = val;
3987
3988         return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
3989 }
3990
3991 /* Check whether "bmap" has a pair of constraints that have
3992  * the same coefficients for the output variables.
3993  * Note that the coefficients of the existentially quantified
3994  * variables need to be zero since the existentially quantified
3995  * of the result are usually not the same as those of the input.
3996  * the isl_dim_out and isl_dim_div dimensions.
3997  * If so, return 1 and return the row indices of the two constraints
3998  * in *first and *second.
3999  */
4000 static int parallel_constraints(__isl_keep isl_basic_map *bmap,
4001         int *first, int *second)
4002 {
4003         int i;
4004         isl_ctx *ctx = isl_basic_map_get_ctx(bmap);
4005         struct isl_hash_table *table = NULL;
4006         struct isl_hash_table_entry *entry;
4007         struct isl_constraint_equal_info info;
4008         unsigned n_out;
4009         unsigned n_div;
4010
4011         ctx = isl_basic_map_get_ctx(bmap);
4012         table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4013         if (!table)
4014                 goto error;
4015
4016         info.n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4017                     isl_basic_map_dim(bmap, isl_dim_in);
4018         info.bmap = bmap;
4019         n_out = isl_basic_map_dim(bmap, isl_dim_out);
4020         n_div = isl_basic_map_dim(bmap, isl_dim_div);
4021         info.n_out = n_out + n_div;
4022         for (i = 0; i < bmap->n_ineq; ++i) {
4023                 uint32_t hash;
4024
4025                 info.val = bmap->ineq[i] + 1 + info.n_in;
4026                 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4027                         continue;
4028                 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4029                         continue;
4030                 hash = isl_seq_get_hash(info.val, info.n_out);
4031                 entry = isl_hash_table_find(ctx, table, hash,
4032                                             constraint_equal, &info, 1);
4033                 if (!entry)
4034                         goto error;
4035                 if (entry->data)
4036                         break;
4037                 entry->data = &bmap->ineq[i];
4038         }
4039
4040         if (i < bmap->n_ineq) {
4041                 *first = ((isl_int **)entry->data) - bmap->ineq; 
4042                 *second = i;
4043         }
4044
4045         isl_hash_table_free(ctx, table);
4046
4047         return i < bmap->n_ineq;
4048 error:
4049         isl_hash_table_free(ctx, table);
4050         return -1;
4051 }
4052
4053 /* Given a set of upper bounds on the last "input" variable m,
4054  * construct a set that assigns the minimal upper bound to m, i.e.,
4055  * construct a set that divides the space into cells where one
4056  * of the upper bounds is smaller than all the others and assign
4057  * this upper bound to m.
4058  *
4059  * In particular, if there are n bounds b_i, then the result
4060  * consists of n basic sets, each one of the form
4061  *
4062  *      m = b_i
4063  *      b_i <= b_j      for j > i
4064  *      b_i <  b_j      for j < i
4065  */
4066 static __isl_give isl_set *set_minimum(__isl_take isl_dim *dim,
4067         __isl_take isl_mat *var)
4068 {
4069         int i, j, k;
4070         isl_basic_set *bset = NULL;
4071         isl_ctx *ctx;
4072         isl_set *set = NULL;
4073
4074         if (!dim || !var)
4075                 goto error;
4076
4077         ctx = isl_dim_get_ctx(dim);
4078         set = isl_set_alloc_dim(isl_dim_copy(dim),
4079                                 var->n_row, ISL_SET_DISJOINT);
4080
4081         for (i = 0; i < var->n_row; ++i) {
4082                 bset = isl_basic_set_alloc_dim(isl_dim_copy(dim), 0,
4083                                                1, var->n_row - 1);
4084                 k = isl_basic_set_alloc_equality(bset);
4085                 if (k < 0)
4086                         goto error;
4087                 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4088                 isl_int_set_si(bset->eq[k][var->n_col], -1);
4089                 for (j = 0; j < var->n_row; ++j) {
4090                         if (j == i)
4091                                 continue;
4092                         k = isl_basic_set_alloc_inequality(bset);
4093                         if (k < 0)
4094                                 goto error;
4095                         isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4096                                         ctx->negone, var->row[i],
4097                                         var->n_col);
4098                         isl_int_set_si(bset->ineq[k][var->n_col], 0);
4099                         if (j < i)
4100                                 isl_int_sub_ui(bset->ineq[k][0],
4101                                                bset->ineq[k][0], 1);
4102                 }
4103                 bset = isl_basic_set_finalize(bset);
4104                 set = isl_set_add_basic_set(set, bset);
4105         }
4106
4107         isl_dim_free(dim);
4108         isl_mat_free(var);
4109         return set;
4110 error:
4111         isl_basic_set_free(bset);
4112         isl_set_free(set);
4113         isl_dim_free(dim);
4114         isl_mat_free(var);
4115         return NULL;
4116 }
4117
4118 /* Given that the last input variable of "bmap" represents the minimum
4119  * of the bounds in "cst", check whether we need to split the domain
4120  * based on which bound attains the minimum.
4121  *
4122  * A split is needed when the minimum appears in an integer division
4123  * or in an equality.  Otherwise, it is only needed if it appears in
4124  * an upper bound that is different from the upper bounds on which it
4125  * is defined.
4126  */
4127 static int need_split_map(__isl_keep isl_basic_map *bmap,
4128         __isl_keep isl_mat *cst)
4129 {
4130         int i, j;
4131         unsigned total;
4132         unsigned pos;
4133
4134         pos = cst->n_col - 1;
4135         total = isl_basic_map_dim(bmap, isl_dim_all);
4136
4137         for (i = 0; i < bmap->n_div; ++i)
4138                 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4139                         return 1;
4140
4141         for (i = 0; i < bmap->n_eq; ++i)
4142                 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4143                         return 1;
4144
4145         for (i = 0; i < bmap->n_ineq; ++i) {
4146                 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4147                         continue;
4148                 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4149                         return 1;
4150                 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4151                                            total - pos - 1) >= 0)
4152                         return 1;
4153
4154                 for (j = 0; j < cst->n_row; ++j)
4155                         if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4156                                 break;
4157                 if (j >= cst->n_row)
4158                         return 1;
4159         }
4160
4161         return 0;
4162 }
4163
4164 static int need_split_set(__isl_keep isl_basic_set *bset,
4165         __isl_keep isl_mat *cst)
4166 {
4167         return need_split_map((isl_basic_map *)bset, cst);
4168 }
4169
4170 /* Given a set of which the last set variable is the minimum
4171  * of the bounds in "cst", split each basic set in the set
4172  * in pieces where one of the bounds is (strictly) smaller than the others.
4173  * This subdivision is given in "min_expr".
4174  * The variable is subsequently projected out.
4175  *
4176  * We only do the split when it is needed.
4177  * For example if the last input variable m = min(a,b) and the only
4178  * constraints in the given basic set are lower bounds on m,
4179  * i.e., l <= m = min(a,b), then we can simply project out m
4180  * to obtain l <= a and l <= b, without having to split on whether
4181  * m is equal to a or b.
4182  */
4183 static __isl_give isl_set *split(__isl_take isl_set *empty,
4184         __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4185 {
4186         int n_in;
4187         int i;
4188         isl_dim *dim;
4189         isl_set *res;
4190
4191         if (!empty || !min_expr || !cst)
4192                 goto error;
4193
4194         n_in = isl_set_dim(empty, isl_dim_set);
4195         dim = isl_set_get_dim(empty);
4196         dim = isl_dim_drop(dim, isl_dim_set, n_in - 1, 1);
4197         res = isl_set_empty(dim);
4198
4199         for (i = 0; i < empty->n; ++i) {
4200                 isl_set *set;
4201
4202                 set = isl_set_from_basic_set(isl_basic_set_copy(empty->p[i]));
4203                 if (need_split_set(empty->p[i], cst))
4204                         set = isl_set_intersect(set, isl_set_copy(min_expr));
4205                 set = isl_set_remove_dims(set, isl_dim_set, n_in - 1, 1);
4206
4207                 res = isl_set_union_disjoint(res, set);
4208         }
4209
4210         isl_set_free(empty);
4211         isl_set_free(min_expr);
4212         isl_mat_free(cst);
4213         return res;
4214 error:
4215         isl_set_free(empty);
4216         isl_set_free(min_expr);
4217         isl_mat_free(cst);
4218         return NULL;
4219 }
4220
4221 /* Given a map of which the last input variable is the minimum
4222  * of the bounds in "cst", split each basic set in the set
4223  * in pieces where one of the bounds is (strictly) smaller than the others.
4224  * This subdivision is given in "min_expr".
4225  * The variable is subsequently projected out.
4226  *
4227  * The implementation is essentially the same as that of "split".
4228  */
4229 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4230         __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4231 {
4232         int n_in;
4233         int i;
4234         isl_dim *dim;
4235         isl_map *res;
4236
4237         if (!opt || !min_expr || !cst)
4238                 goto error;
4239
4240         n_in = isl_map_dim(opt, isl_dim_in);
4241         dim = isl_map_get_dim(opt);
4242         dim = isl_dim_drop(dim, isl_dim_in, n_in - 1, 1);
4243         res = isl_map_empty(dim);
4244
4245         for (i = 0; i < opt->n; ++i) {
4246                 isl_map *map;
4247
4248                 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4249                 if (need_split_map(opt->p[i], cst))
4250                         map = isl_map_intersect_domain(map,
4251                                                        isl_set_copy(min_expr));
4252                 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4253
4254                 res = isl_map_union_disjoint(res, map);
4255         }
4256
4257         isl_map_free(opt);
4258         isl_set_free(min_expr);
4259         isl_mat_free(cst);
4260         return res;
4261 error:
4262         isl_map_free(opt);
4263         isl_set_free(min_expr);
4264         isl_mat_free(cst);
4265         return NULL;
4266 }
4267
4268 static __isl_give isl_map *basic_map_partial_lexopt(
4269         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4270         __isl_give isl_set **empty, int max);
4271
4272 /* Given a basic map with at least two parallel constraints (as found
4273  * by the function parallel_constraints), first look for more constraints
4274  * parallel to the two constraint and replace the found list of parallel
4275  * constraints by a single constraint with as "input" part the minimum
4276  * of the input parts of the list of constraints.  Then, recursively call
4277  * basic_map_partial_lexopt (possibly finding more parallel constraints)
4278  * and plug in the definition of the minimum in the result.
4279  *
4280  * More specifically, given a set of constraints
4281  *
4282  *      a x + b_i(p) >= 0
4283  *
4284  * Replace this set by a single constraint
4285  *
4286  *      a x + u >= 0
4287  *
4288  * with u a new parameter with constraints
4289  *
4290  *      u <= b_i(p)
4291  *
4292  * Any solution to the new system is also a solution for the original system
4293  * since
4294  *
4295  *      a x >= -u >= -b_i(p)
4296  *
4297  * Moreover, m = min_i(b_i(p)) satisfies the constraints on u and can
4298  * therefore be plugged into the solution.
4299  */
4300 static __isl_give isl_map *basic_map_partial_lexopt_symm(
4301         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4302         __isl_give isl_set **empty, int max, int first, int second)
4303 {
4304         int i, n, k;
4305         int *list = NULL;
4306         unsigned n_in, n_out, n_div;
4307         isl_ctx *ctx;
4308         isl_vec *var = NULL;
4309         isl_mat *cst = NULL;
4310         isl_map *opt;
4311         isl_set *min_expr;
4312         isl_dim *map_dim, *set_dim;
4313
4314         map_dim = isl_basic_map_get_dim(bmap);
4315         set_dim = empty ? isl_basic_set_get_dim(dom) : NULL;
4316
4317         n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4318                isl_basic_map_dim(bmap, isl_dim_in);
4319         n_out = isl_basic_map_dim(bmap, isl_dim_all) - n_in;
4320
4321         ctx = isl_basic_map_get_ctx(bmap);
4322         list = isl_alloc_array(ctx, int, bmap->n_ineq);
4323         var = isl_vec_alloc(ctx, n_out);
4324         if (!list || !var)
4325                 goto error;
4326
4327         list[0] = first;
4328         list[1] = second;
4329         isl_seq_cpy(var->el, bmap->ineq[first] + 1 + n_in, n_out);
4330         for (i = second + 1, n = 2; i < bmap->n_ineq; ++i) {
4331                 if (isl_seq_eq(var->el, bmap->ineq[i] + 1 + n_in, n_out))
4332                         list[n++] = i;
4333         }
4334
4335         cst = isl_mat_alloc(ctx, n, 1 + n_in);
4336         if (!cst)
4337                 goto error;
4338
4339         for (i = 0; i < n; ++i)
4340                 isl_seq_cpy(cst->row[i], bmap->ineq[list[i]], 1 + n_in);
4341
4342         bmap = isl_basic_map_cow(bmap);
4343         if (!bmap)
4344                 goto error;
4345         for (i = n - 1; i >= 0; --i)
4346                 if (isl_basic_map_drop_inequality(bmap, list[i]) < 0)
4347                         goto error;
4348
4349         bmap = isl_basic_map_add(bmap, isl_dim_in, 1);
4350         bmap = isl_basic_map_extend_constraints(bmap, 0, 1);
4351         k = isl_basic_map_alloc_inequality(bmap);
4352         if (k < 0)
4353                 goto error;
4354         isl_seq_clr(bmap->ineq[k], 1 + n_in);
4355         isl_int_set_si(bmap->ineq[k][1 + n_in], 1);
4356         isl_seq_cpy(bmap->ineq[k] + 1 + n_in + 1, var->el, n_out);
4357         bmap = isl_basic_map_finalize(bmap);
4358
4359         n_div = isl_basic_set_dim(dom, isl_dim_div);
4360         dom = isl_basic_set_add(dom, isl_dim_set, 1);
4361         dom = isl_basic_set_extend_constraints(dom, 0, n);
4362         for (i = 0; i < n; ++i) {
4363                 k = isl_basic_set_alloc_inequality(dom);
4364                 if (k < 0)
4365                         goto error;
4366                 isl_seq_cpy(dom->ineq[k], cst->row[i], 1 + n_in);
4367                 isl_int_set_si(dom->ineq[k][1 + n_in], -1);
4368                 isl_seq_clr(dom->ineq[k] + 1 + n_in + 1, n_div);
4369         }
4370
4371         min_expr = set_minimum(isl_basic_set_get_dim(dom), isl_mat_copy(cst));
4372
4373         isl_vec_free(var);
4374         free(list);
4375
4376         opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4377
4378         if (empty) {
4379                 *empty = split(*empty,
4380                                isl_set_copy(min_expr), isl_mat_copy(cst));
4381                 *empty = isl_set_reset_dim(*empty, set_dim);
4382         }
4383
4384         opt = split_domain(opt, min_expr, cst);
4385         opt = isl_map_reset_dim(opt, map_dim);
4386
4387         return opt;
4388 error:
4389         isl_dim_free(map_dim);
4390         isl_dim_free(set_dim);
4391         isl_mat_free(cst);
4392         isl_vec_free(var);
4393         free(list);
4394         isl_basic_set_free(dom);
4395         isl_basic_map_free(bmap);
4396         return NULL;
4397 }
4398
4399 /* Recursive part of isl_tab_basic_map_partial_lexopt, after detecting
4400  * equalities and removing redundant constraints.
4401  *
4402  * We first check if there are any parallel constraints (left).
4403  * If not, we are in the base case.
4404  * If there are parallel constraints, we replace them by a single
4405  * constraint in basic_map_partial_lexopt_symm and then call
4406  * this function recursively to look for more parallel constraints.
4407  */
4408 static __isl_give isl_map *basic_map_partial_lexopt(
4409         __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4410         __isl_give isl_set **empty, int max)
4411 {
4412         int par = 0;
4413         int first, second;
4414
4415         if (!bmap)
4416                 goto error;
4417
4418         if (bmap->ctx->opt->pip_symmetry)
4419                 par = parallel_constraints(bmap, &first, &second);
4420         if (par < 0)
4421                 goto error;
4422         if (!par)
4423                 return basic_map_partial_lexopt_base(bmap, dom, empty, max);
4424         
4425         return basic_map_partial_lexopt_symm(bmap, dom, empty, max,
4426                                              first, second);
4427 error:
4428         isl_basic_set_free(dom);
4429         isl_basic_map_free(bmap);
4430         return NULL;
4431 }
4432
4433 /* Compute the lexicographic minimum (or maximum if "max" is set)
4434  * of "bmap" over the domain "dom" and return the result as a map.
4435  * If "empty" is not NULL, then *empty is assigned a set that
4436  * contains those parts of the domain where there is no solution.
4437  * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
4438  * then we compute the rational optimum.  Otherwise, we compute
4439  * the integral optimum.
4440  *
4441  * We perform some preprocessing.  As the PILP solver does not
4442  * handle implicit equalities very well, we first make sure all
4443  * the equalities are explicitly available.
4444  *
4445  * We also add context constraints to the basic map and remove
4446  * redundant constraints.  This is only needed because of the
4447  * way we handle simple symmetries.  In particular, we currently look
4448  * for symmetries on the constraints, before we set up the main tableau.
4449  * It is then no good to look for symmetries on possibly redundant constraints.
4450  */
4451 struct isl_map *isl_tab_basic_map_partial_lexopt(
4452                 struct isl_basic_map *bmap, struct isl_basic_set *dom,
4453                 struct isl_set **empty, int max)
4454 {
4455         if (empty)
4456                 *empty = NULL;
4457         if (!bmap || !dom)
4458                 goto error;
4459
4460         isl_assert(bmap->ctx,
4461             isl_basic_map_compatible_domain(bmap, dom), goto error);
4462
4463         if (isl_basic_set_dim(dom, isl_dim_all) == 0)
4464                 return basic_map_partial_lexopt(bmap, dom, empty, max);
4465
4466         bmap = isl_basic_map_intersect_domain(bmap, isl_basic_set_copy(dom));
4467         bmap = isl_basic_map_detect_equalities(bmap);
4468         bmap = isl_basic_map_remove_redundancies(bmap);
4469
4470         return basic_map_partial_lexopt(bmap, dom, empty, max);
4471 error:
4472         isl_basic_set_free(dom);
4473         isl_basic_map_free(bmap);
4474         return NULL;
4475 }
4476
4477 struct isl_sol_for {
4478         struct isl_sol  sol;
4479         int             (*fn)(__isl_take isl_basic_set *dom,
4480                                 __isl_take isl_mat *map, void *user);
4481         void            *user;
4482 };
4483
4484 static void sol_for_free(struct isl_sol_for *sol_for)
4485 {
4486         if (sol_for->sol.context)
4487                 sol_for->sol.context->op->free(sol_for->sol.context);
4488         free(sol_for);
4489 }
4490
4491 static void sol_for_free_wrap(struct isl_sol *sol)
4492 {
4493         sol_for_free((struct isl_sol_for *)sol);
4494 }
4495
4496 /* Add the solution identified by the tableau and the context tableau.
4497  *
4498  * See documentation of sol_add for more details.
4499  *
4500  * Instead of constructing a basic map, this function calls a user
4501  * defined function with the current context as a basic set and
4502  * an affine matrix representing the relation between the input and output.
4503  * The number of rows in this matrix is equal to one plus the number
4504  * of output variables.  The number of columns is equal to one plus
4505  * the total dimension of the context, i.e., the number of parameters,
4506  * input variables and divs.  Since some of the columns in the matrix
4507  * may refer to the divs, the basic set is not simplified.
4508  * (Simplification may reorder or remove divs.)
4509  */
4510 static void sol_for_add(struct isl_sol_for *sol,
4511         struct isl_basic_set *dom, struct isl_mat *M)
4512 {
4513         if (sol->sol.error || !dom || !M)
4514                 goto error;
4515
4516         dom = isl_basic_set_simplify(dom);
4517         dom = isl_basic_set_finalize(dom);
4518
4519         if (sol->fn(isl_basic_set_copy(dom), isl_mat_copy(M), sol->user) < 0)
4520                 goto error;
4521
4522         isl_basic_set_free(dom);
4523         isl_mat_free(M);
4524         return;
4525 error:
4526         isl_basic_set_free(dom);
4527         isl_mat_free(M);
4528         sol->sol.error = 1;
4529 }
4530
4531 static void sol_for_add_wrap(struct isl_sol *sol,
4532         struct isl_basic_set *dom, struct isl_mat *M)
4533 {
4534         sol_for_add((struct isl_sol_for *)sol, dom, M);
4535 }
4536
4537 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
4538         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4539                   void *user),
4540         void *user)
4541 {
4542         struct isl_sol_for *sol_for = NULL;
4543         struct isl_dim *dom_dim;
4544         struct isl_basic_set *dom = NULL;
4545
4546         sol_for = isl_calloc_type(bmap->ctx, struct isl_sol_for);
4547         if (!sol_for)
4548                 goto error;
4549
4550         dom_dim = isl_dim_domain(isl_dim_copy(bmap->dim));
4551         dom = isl_basic_set_universe(dom_dim);
4552
4553         sol_for->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
4554         sol_for->sol.dec_level.callback.run = &sol_dec_level_wrap;
4555         sol_for->sol.dec_level.sol = &sol_for->sol;
4556         sol_for->fn = fn;
4557         sol_for->user = user;
4558         sol_for->sol.max = max;
4559         sol_for->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
4560         sol_for->sol.add = &sol_for_add_wrap;
4561         sol_for->sol.add_empty = NULL;
4562         sol_for->sol.free = &sol_for_free_wrap;
4563
4564         sol_for->sol.context = isl_context_alloc(dom);
4565         if (!sol_for->sol.context)
4566                 goto error;
4567
4568         isl_basic_set_free(dom);
4569         return sol_for;
4570 error:
4571         isl_basic_set_free(dom);
4572         sol_for_free(sol_for);
4573         return NULL;
4574 }
4575
4576 static void sol_for_find_solutions(struct isl_sol_for *sol_for,
4577         struct isl_tab *tab)
4578 {
4579         find_solutions_main(&sol_for->sol, tab);
4580 }
4581
4582 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
4583         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4584                   void *user),
4585         void *user)
4586 {
4587         struct isl_sol_for *sol_for = NULL;
4588
4589         bmap = isl_basic_map_copy(bmap);
4590         if (!bmap)
4591                 return -1;
4592
4593         bmap = isl_basic_map_detect_equalities(bmap);
4594         sol_for = sol_for_init(bmap, max, fn, user);
4595
4596         if (isl_basic_map_fast_is_empty(bmap))
4597                 /* nothing */;
4598         else {
4599                 struct isl_tab *tab;
4600                 struct isl_context *context = sol_for->sol.context;
4601                 tab = tab_for_lexmin(bmap,
4602                                 context->op->peek_basic_set(context), 1, max);
4603                 tab = context->op->detect_nonnegative_parameters(context, tab);
4604                 sol_for_find_solutions(sol_for, tab);
4605                 if (sol_for->sol.error)
4606                         goto error;
4607         }
4608
4609         sol_free(&sol_for->sol);
4610         isl_basic_map_free(bmap);
4611         return 0;
4612 error:
4613         sol_free(&sol_for->sol);
4614         isl_basic_map_free(bmap);
4615         return -1;
4616 }
4617
4618 int isl_basic_map_foreach_lexmin(__isl_keep isl_basic_map *bmap,
4619         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4620                   void *user),
4621         void *user)
4622 {
4623         return isl_basic_map_foreach_lexopt(bmap, 0, fn, user);
4624 }
4625
4626 int isl_basic_map_foreach_lexmax(__isl_keep isl_basic_map *bmap,
4627         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4628                   void *user),
4629         void *user)
4630 {
4631         return isl_basic_map_foreach_lexopt(bmap, 1, fn, user);
4632 }