privately export isl_basic_set_add_{in,}eq
[platform/upstream/isl.git] / isl_tab_pip.c
1 #include "isl_map_private.h"
2 #include "isl_seq.h"
3 #include "isl_tab.h"
4
5 /*
6  * The implementation of parametric integer linear programming in this file
7  * was inspired by the paper "Parametric Integer Programming" and the
8  * report "Solving systems of affine (in)equalities" by Paul Feautrier
9  * (and others).
10  *
11  * The strategy used for obtaining a feasible solution is different
12  * from the one used in isl_tab.c.  In particular, in isl_tab.c,
13  * upon finding a constraint that is not yet satisfied, we pivot
14  * in a row that increases the constant term of row holding the
15  * constraint, making sure the sample solution remains feasible
16  * for all the constraints it already satisfied.
17  * Here, we always pivot in the row holding the constraint,
18  * choosing a column that induces the lexicographically smallest
19  * increment to the sample solution.
20  *
21  * By starting out from a sample value that is lexicographically
22  * smaller than any integer point in the problem space, the first
23  * feasible integer sample point we find will also be the lexicographically
24  * smallest.  If all variables can be assumed to be non-negative,
25  * then the initial sample value may be chosen equal to zero.
26  * However, we will not make this assumption.  Instead, we apply
27  * the "big parameter" trick.  Any variable x is then not directly
28  * used in the tableau, but instead it its represented by another
29  * variable x' = M + x, where M is an arbitrarily large (positive)
30  * value.  x' is therefore always non-negative, whatever the value of x.
31  * Taking as initial smaple value x' = 0 corresponds to x = -M,
32  * which is always smaller than any possible value of x.
33  *
34  * We use the big parameter trick both in the main tableau and
35  * the context tableau, each of course having its own big parameter.
36  * Before doing any real work, we check if all the parameters
37  * happen to be non-negative.  If so, we drop the column corresponding
38  * to M from the initial context tableau.
39  */
40
41 /* isl_sol is an interface for constructing a solution to
42  * a parametric integer linear programming problem.
43  * Every time the algorithm reaches a state where a solution
44  * can be read off from the tableau (including cases where the tableau
45  * is empty), the function "add" is called on the isl_sol passed
46  * to find_solutions_main.
47  *
48  * The context tableau is owned by isl_sol and is updated incrementally.
49  *
50  * There are currently two implementations of this interface,
51  * isl_sol_map, which simply collects the solutions in an isl_map
52  * and (optionally) the parts of the context where there is no solution
53  * in an isl_set, and
54  * isl_sol_for, which calls a user-defined function for each part of
55  * the solution.
56  */
57 struct isl_sol {
58         struct isl_tab *context_tab;
59         struct isl_sol *(*add)(struct isl_sol *sol, struct isl_tab *tab);
60         void (*free)(struct isl_sol *sol);
61 };
62
63 static void sol_free(struct isl_sol *sol)
64 {
65         if (!sol)
66                 return;
67         sol->free(sol);
68 }
69
70 struct isl_sol_map {
71         struct isl_sol  sol;
72         struct isl_map  *map;
73         struct isl_set  *empty;
74         int             max;
75 };
76
77 static void sol_map_free(struct isl_sol_map *sol_map)
78 {
79         isl_tab_free(sol_map->sol.context_tab);
80         isl_map_free(sol_map->map);
81         isl_set_free(sol_map->empty);
82         free(sol_map);
83 }
84
85 static void sol_map_free_wrap(struct isl_sol *sol)
86 {
87         sol_map_free((struct isl_sol_map *)sol);
88 }
89
90 static struct isl_sol_map *add_empty(struct isl_sol_map *sol)
91 {
92         struct isl_basic_set *bset;
93
94         if (!sol->empty)
95                 return sol;
96         sol->empty = isl_set_grow(sol->empty, 1);
97         bset = isl_basic_set_copy(sol->sol.context_tab->bset);
98         bset = isl_basic_set_simplify(bset);
99         bset = isl_basic_set_finalize(bset);
100         sol->empty = isl_set_add(sol->empty, bset);
101         if (!sol->empty)
102                 goto error;
103         return sol;
104 error:
105         sol_map_free(sol);
106         return NULL;
107 }
108
109 /* Add the solution identified by the tableau and the context tableau.
110  *
111  * The layout of the variables is as follows.
112  *      tab->n_var is equal to the total number of variables in the input
113  *                      map (including divs that were copied from the context)
114  *                      + the number of extra divs constructed
115  *      Of these, the first tab->n_param and the last tab->n_div variables
116  *      correspond to the variables in the context, i.e.,
117  *              tab->n_param + tab->n_div = context_tab->n_var
118  *      tab->n_param is equal to the number of parameters and input
119  *                      dimensions in the input map
120  *      tab->n_div is equal to the number of divs in the context
121  *
122  * If there is no solution, then the basic set corresponding to the
123  * context tableau is added to the set "empty".
124  *
125  * Otherwise, a basic map is constructed with the same parameters
126  * and divs as the context, the dimensions of the context as input
127  * dimensions and a number of output dimensions that is equal to
128  * the number of output dimensions in the input map.
129  * The divs in the input map (if any) that do not correspond to any
130  * div in the context do not appear in the solution.
131  * The algorithm will make sure that they have an integer value,
132  * but these values themselves are of no interest.
133  *
134  * The constraints and divs of the context are simply copied
135  * fron context_tab->bset.
136  * To extract the value of the output variables, it should be noted
137  * that we always use a big parameter M and so the variable stored
138  * in the tableau is not an output variable x itself, but
139  *      x' = M + x (in case of minimization)
140  * or
141  *      x' = M - x (in case of maximization)
142  * If x' appears in a column, then its optimal value is zero,
143  * which means that the optimal value of x is an unbounded number
144  * (-M for minimization and M for maximization).
145  * We currently assume that the output dimensions in the original map
146  * are bounded, so this cannot occur.
147  * Similarly, when x' appears in a row, then the coefficient of M in that
148  * row is necessarily 1.
149  * If the row represents
150  *      d x' = c + d M + e(y)
151  * then, in case of minimization, an equality
152  *      c + e(y) - d x' = 0
153  * is added, and in case of maximization,
154  *      c + e(y) + d x' = 0
155  */
156 static struct isl_sol_map *sol_map_add(struct isl_sol_map *sol,
157         struct isl_tab *tab)
158 {
159         int i;
160         struct isl_basic_map *bmap = NULL;
161         struct isl_tab *context_tab;
162         unsigned n_eq;
163         unsigned n_ineq;
164         unsigned nparam;
165         unsigned total;
166         unsigned n_div;
167         unsigned n_out;
168         unsigned off;
169
170         if (!sol || !tab)
171                 goto error;
172
173         if (tab->empty)
174                 return add_empty(sol);
175
176         context_tab = sol->sol.context_tab;
177         off = 2 + tab->M;
178         n_out = isl_map_dim(sol->map, isl_dim_out);
179         n_eq = context_tab->bset->n_eq + n_out;
180         n_ineq = context_tab->bset->n_ineq;
181         nparam = tab->n_param;
182         total = isl_map_dim(sol->map, isl_dim_all);
183         bmap = isl_basic_map_alloc_dim(isl_map_get_dim(sol->map),
184                                     tab->n_div, n_eq, 2 * tab->n_div + n_ineq);
185         if (!bmap)
186                 goto error;
187         n_div = tab->n_div;
188         if (tab->rational)
189                 ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
190         for (i = 0; i < context_tab->bset->n_div; ++i) {
191                 int k = isl_basic_map_alloc_div(bmap);
192                 if (k < 0)
193                         goto error;
194                 isl_seq_cpy(bmap->div[k],
195                             context_tab->bset->div[i], 1 + 1 + nparam);
196                 isl_seq_clr(bmap->div[k] + 1 + 1 + nparam, total - nparam);
197                 isl_seq_cpy(bmap->div[k] + 1 + 1 + total,
198                             context_tab->bset->div[i] + 1 + 1 + nparam, i);
199         }
200         for (i = 0; i < context_tab->bset->n_eq; ++i) {
201                 int k = isl_basic_map_alloc_equality(bmap);
202                 if (k < 0)
203                         goto error;
204                 isl_seq_cpy(bmap->eq[k], context_tab->bset->eq[i], 1 + nparam);
205                 isl_seq_clr(bmap->eq[k] + 1 + nparam, total - nparam);
206                 isl_seq_cpy(bmap->eq[k] + 1 + total,
207                             context_tab->bset->eq[i] + 1 + nparam, n_div);
208         }
209         for (i = 0; i < context_tab->bset->n_ineq; ++i) {
210                 int k = isl_basic_map_alloc_inequality(bmap);
211                 if (k < 0)
212                         goto error;
213                 isl_seq_cpy(bmap->ineq[k],
214                         context_tab->bset->ineq[i], 1 + nparam);
215                 isl_seq_clr(bmap->ineq[k] + 1 + nparam, total - nparam);
216                 isl_seq_cpy(bmap->ineq[k] + 1 + total,
217                         context_tab->bset->ineq[i] + 1 + nparam, n_div);
218         }
219         for (i = tab->n_param; i < total; ++i) {
220                 int k = isl_basic_map_alloc_equality(bmap);
221                 if (k < 0)
222                         goto error;
223                 isl_seq_clr(bmap->eq[k] + 1, isl_basic_map_total_dim(bmap));
224                 if (!tab->var[i].is_row) {
225                         /* no unbounded */
226                         isl_assert(bmap->ctx, !tab->M, goto error);
227                         isl_int_set_si(bmap->eq[k][0], 0);
228                         if (sol->max)
229                                 isl_int_set_si(bmap->eq[k][1 + i], 1);
230                         else
231                                 isl_int_set_si(bmap->eq[k][1 + i], -1);
232                 } else {
233                         int row, j;
234                         row = tab->var[i].index;
235                         /* no unbounded */
236                         if (tab->M)
237                                 isl_assert(bmap->ctx,
238                                         isl_int_eq(tab->mat->row[row][2],
239                                                    tab->mat->row[row][0]),
240                                         goto error);
241                         isl_int_set(bmap->eq[k][0], tab->mat->row[row][1]);
242                         for (j = 0; j < tab->n_param; ++j) {
243                                 int col;
244                                 if (tab->var[j].is_row)
245                                         continue;
246                                 col = tab->var[j].index;
247                                 isl_int_set(bmap->eq[k][1 + j],
248                                             tab->mat->row[row][off + col]);
249                         }
250                         for (j = 0; j < tab->n_div; ++j) {
251                                 int col;
252                                 if (tab->var[tab->n_var - tab->n_div+j].is_row)
253                                         continue;
254                                 col = tab->var[tab->n_var - tab->n_div+j].index;
255                                 isl_int_set(bmap->eq[k][1 + total + j],
256                                             tab->mat->row[row][off + col]);
257                         }
258                         if (sol->max)
259                                 isl_int_set(bmap->eq[k][1 + i],
260                                             tab->mat->row[row][0]);
261                         else
262                                 isl_int_neg(bmap->eq[k][1 + i],
263                                             tab->mat->row[row][0]);
264                 }
265         }
266         bmap = isl_basic_map_gauss(bmap, NULL);
267         bmap = isl_basic_map_normalize_constraints(bmap);
268         bmap = isl_basic_map_finalize(bmap);
269         sol->map = isl_map_grow(sol->map, 1);
270         sol->map = isl_map_add(sol->map, bmap);
271         if (!sol->map)
272                 goto error;
273         return sol;
274 error:
275         isl_basic_map_free(bmap);
276         sol_free(&sol->sol);
277         return NULL;
278 }
279
280 static struct isl_sol *sol_map_add_wrap(struct isl_sol *sol,
281         struct isl_tab *tab)
282 {
283         return (struct isl_sol *)sol_map_add((struct isl_sol_map *)sol, tab);
284 }
285
286
287 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
288  * i.e., the constant term and the coefficients of all variables that
289  * appear in the context tableau.
290  * Note that the coefficient of the big parameter M is NOT copied.
291  * The context tableau may not have a big parameter and even when it
292  * does, it is a different big parameter.
293  */
294 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
295 {
296         int i;
297         unsigned off = 2 + tab->M;
298
299         isl_int_set(line[0], tab->mat->row[row][1]);
300         for (i = 0; i < tab->n_param; ++i) {
301                 if (tab->var[i].is_row)
302                         isl_int_set_si(line[1 + i], 0);
303                 else {
304                         int col = tab->var[i].index;
305                         isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
306                 }
307         }
308         for (i = 0; i < tab->n_div; ++i) {
309                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
310                         isl_int_set_si(line[1 + tab->n_param + i], 0);
311                 else {
312                         int col = tab->var[tab->n_var - tab->n_div + i].index;
313                         isl_int_set(line[1 + tab->n_param + i],
314                                     tab->mat->row[row][off + col]);
315                 }
316         }
317 }
318
319 /* Check if rows "row1" and "row2" have identical "parametric constants",
320  * as explained above.
321  * In this case, we also insist that the coefficients of the big parameter
322  * be the same as the values of the constants will only be the same
323  * if these coefficients are also the same.
324  */
325 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
326 {
327         int i;
328         unsigned off = 2 + tab->M;
329
330         if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
331                 return 0;
332
333         if (tab->M && isl_int_ne(tab->mat->row[row1][2],
334                                  tab->mat->row[row2][2]))
335                 return 0;
336
337         for (i = 0; i < tab->n_param + tab->n_div; ++i) {
338                 int pos = i < tab->n_param ? i :
339                         tab->n_var - tab->n_div + i - tab->n_param;
340                 int col;
341
342                 if (tab->var[pos].is_row)
343                         continue;
344                 col = tab->var[pos].index;
345                 if (isl_int_ne(tab->mat->row[row1][off + col],
346                                tab->mat->row[row2][off + col]))
347                         return 0;
348         }
349         return 1;
350 }
351
352 /* Return an inequality that expresses that the "parametric constant"
353  * should be non-negative.
354  * This function is only called when the coefficient of the big parameter
355  * is equal to zero.
356  */
357 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
358 {
359         struct isl_vec *ineq;
360
361         ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
362         if (!ineq)
363                 return NULL;
364
365         get_row_parameter_line(tab, row, ineq->el);
366         if (ineq)
367                 ineq = isl_vec_normalize(ineq);
368
369         return ineq;
370 }
371
372 /* Return a integer division for use in a parametric cut based on the given row.
373  * In particular, let the parametric constant of the row be
374  *
375  *              \sum_i a_i y_i
376  *
377  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
378  * The div returned is equal to
379  *
380  *              floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
381  */
382 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
383 {
384         struct isl_vec *div;
385
386         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
387         if (!div)
388                 return NULL;
389
390         isl_int_set(div->el[0], tab->mat->row[row][0]);
391         get_row_parameter_line(tab, row, div->el + 1);
392         div = isl_vec_normalize(div);
393         isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
394         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
395
396         return div;
397 }
398
399 /* Return a integer division for use in transferring an integrality constraint
400  * to the context.
401  * In particular, let the parametric constant of the row be
402  *
403  *              \sum_i a_i y_i
404  *
405  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
406  * The the returned div is equal to
407  *
408  *              floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
409  */
410 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
411 {
412         struct isl_vec *div;
413
414         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
415         if (!div)
416                 return NULL;
417
418         isl_int_set(div->el[0], tab->mat->row[row][0]);
419         get_row_parameter_line(tab, row, div->el + 1);
420         div = isl_vec_normalize(div);
421         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
422
423         return div;
424 }
425
426 /* Construct and return an inequality that expresses an upper bound
427  * on the given div.
428  * In particular, if the div is given by
429  *
430  *      d = floor(e/m)
431  *
432  * then the inequality expresses
433  *
434  *      m d <= e
435  */
436 static struct isl_vec *ineq_for_div(struct isl_basic_set *bset, unsigned div)
437 {
438         unsigned total;
439         unsigned div_pos;
440         struct isl_vec *ineq;
441
442         total = isl_basic_set_total_dim(bset);
443         div_pos = 1 + total - bset->n_div + div;
444
445         ineq = isl_vec_alloc(bset->ctx, 1 + total);
446         if (!ineq)
447                 return NULL;
448
449         isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
450         isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
451         return ineq;
452 }
453
454 /* Given a row in the tableau and a div that was created
455  * using get_row_split_div and that been constrained to equality, i.e.,
456  *
457  *              d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
458  *
459  * replace the expression "\sum_i {a_i} y_i" in the row by d,
460  * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
461  * The coefficients of the non-parameters in the tableau have been
462  * verified to be integral.  We can therefore simply replace coefficient b
463  * by floor(b).  For the coefficients of the parameters we have
464  * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
465  * floor(b) = b.
466  */
467 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
468 {
469         int col;
470         unsigned off = 2 + tab->M;
471
472         isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
473                         tab->mat->row[row][0], 1 + tab->M + tab->n_col);
474
475         isl_int_set_si(tab->mat->row[row][0], 1);
476
477         isl_assert(tab->mat->ctx,
478                 !tab->var[tab->n_var - tab->n_div + div].is_row, goto error);
479
480         col = tab->var[tab->n_var - tab->n_div + div].index;
481         isl_int_set_si(tab->mat->row[row][off + col], 1);
482
483         return tab;
484 error:
485         isl_tab_free(tab);
486         return NULL;
487 }
488
489 /* Check if the (parametric) constant of the given row is obviously
490  * negative, meaning that we don't need to consult the context tableau.
491  * If there is a big parameter and its coefficient is non-zero,
492  * then this coefficient determines the outcome.
493  * Otherwise, we check whether the constant is negative and
494  * all non-zero coefficients of parameters are negative and
495  * belong to non-negative parameters.
496  */
497 static int is_obviously_neg(struct isl_tab *tab, int row)
498 {
499         int i;
500         int col;
501         unsigned off = 2 + tab->M;
502
503         if (tab->M) {
504                 if (isl_int_is_pos(tab->mat->row[row][2]))
505                         return 0;
506                 if (isl_int_is_neg(tab->mat->row[row][2]))
507                         return 1;
508         }
509
510         if (isl_int_is_nonneg(tab->mat->row[row][1]))
511                 return 0;
512         for (i = 0; i < tab->n_param; ++i) {
513                 /* Eliminated parameter */
514                 if (tab->var[i].is_row)
515                         continue;
516                 col = tab->var[i].index;
517                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
518                         continue;
519                 if (!tab->var[i].is_nonneg)
520                         return 0;
521                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
522                         return 0;
523         }
524         for (i = 0; i < tab->n_div; ++i) {
525                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
526                         continue;
527                 col = tab->var[tab->n_var - tab->n_div + i].index;
528                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
529                         continue;
530                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
531                         return 0;
532                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
533                         return 0;
534         }
535         return 1;
536 }
537
538 /* Check if the (parametric) constant of the given row is obviously
539  * non-negative, meaning that we don't need to consult the context tableau.
540  * If there is a big parameter and its coefficient is non-zero,
541  * then this coefficient determines the outcome.
542  * Otherwise, we check whether the constant is non-negative and
543  * all non-zero coefficients of parameters are positive and
544  * belong to non-negative parameters.
545  */
546 static int is_obviously_nonneg(struct isl_tab *tab, int row)
547 {
548         int i;
549         int col;
550         unsigned off = 2 + tab->M;
551
552         if (tab->M) {
553                 if (isl_int_is_pos(tab->mat->row[row][2]))
554                         return 1;
555                 if (isl_int_is_neg(tab->mat->row[row][2]))
556                         return 0;
557         }
558
559         if (isl_int_is_neg(tab->mat->row[row][1]))
560                 return 0;
561         for (i = 0; i < tab->n_param; ++i) {
562                 /* Eliminated parameter */
563                 if (tab->var[i].is_row)
564                         continue;
565                 col = tab->var[i].index;
566                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
567                         continue;
568                 if (!tab->var[i].is_nonneg)
569                         return 0;
570                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
571                         return 0;
572         }
573         for (i = 0; i < tab->n_div; ++i) {
574                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
575                         continue;
576                 col = tab->var[tab->n_var - tab->n_div + i].index;
577                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
578                         continue;
579                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
580                         return 0;
581                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
582                         return 0;
583         }
584         return 1;
585 }
586
587 /* Given a row r and two columns, return the column that would
588  * lead to the lexicographically smallest increment in the sample
589  * solution when leaving the basis in favor of the row.
590  * Pivoting with column c will increment the sample value by a non-negative
591  * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
592  * corresponding to the non-parametric variables.
593  * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
594  * with all other entries in this virtual row equal to zero.
595  * If variable v appears in a row, then a_{v,c} is the element in column c
596  * of that row.
597  *
598  * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
599  * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
600  * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
601  * increment.  Otherwise, it's c2.
602  */
603 static int lexmin_col_pair(struct isl_tab *tab,
604         int row, int col1, int col2, isl_int tmp)
605 {
606         int i;
607         isl_int *tr;
608
609         tr = tab->mat->row[row] + 2 + tab->M;
610
611         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
612                 int s1, s2;
613                 isl_int *r;
614
615                 if (!tab->var[i].is_row) {
616                         if (tab->var[i].index == col1)
617                                 return col2;
618                         if (tab->var[i].index == col2)
619                                 return col1;
620                         continue;
621                 }
622
623                 if (tab->var[i].index == row)
624                         continue;
625
626                 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
627                 s1 = isl_int_sgn(r[col1]);
628                 s2 = isl_int_sgn(r[col2]);
629                 if (s1 == 0 && s2 == 0)
630                         continue;
631                 if (s1 < s2)
632                         return col1;
633                 if (s2 < s1)
634                         return col2;
635
636                 isl_int_mul(tmp, r[col2], tr[col1]);
637                 isl_int_submul(tmp, r[col1], tr[col2]);
638                 if (isl_int_is_pos(tmp))
639                         return col1;
640                 if (isl_int_is_neg(tmp))
641                         return col2;
642         }
643         return -1;
644 }
645
646 /* Given a row in the tableau, find and return the column that would
647  * result in the lexicographically smallest, but positive, increment
648  * in the sample point.
649  * If there is no such column, then return tab->n_col.
650  * If anything goes wrong, return -1.
651  */
652 static int lexmin_pivot_col(struct isl_tab *tab, int row)
653 {
654         int j;
655         int col = tab->n_col;
656         isl_int *tr;
657         isl_int tmp;
658
659         tr = tab->mat->row[row] + 2 + tab->M;
660
661         isl_int_init(tmp);
662
663         for (j = tab->n_dead; j < tab->n_col; ++j) {
664                 if (tab->col_var[j] >= 0 &&
665                     (tab->col_var[j] < tab->n_param  ||
666                     tab->col_var[j] >= tab->n_var - tab->n_div))
667                         continue;
668
669                 if (!isl_int_is_pos(tr[j]))
670                         continue;
671
672                 if (col == tab->n_col)
673                         col = j;
674                 else
675                         col = lexmin_col_pair(tab, row, col, j, tmp);
676                 isl_assert(tab->mat->ctx, col >= 0, goto error);
677         }
678
679         isl_int_clear(tmp);
680         return col;
681 error:
682         isl_int_clear(tmp);
683         return -1;
684 }
685
686 /* Return the first known violated constraint, i.e., a non-negative
687  * contraint that currently has an either obviously negative value
688  * or a previously determined to be negative value.
689  *
690  * If any constraint has a negative coefficient for the big parameter,
691  * if any, then we return one of these first.
692  */
693 static int first_neg(struct isl_tab *tab)
694 {
695         int row;
696
697         if (tab->M)
698                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
699                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
700                                 continue;
701                         if (isl_int_is_neg(tab->mat->row[row][2]))
702                                 return row;
703                 }
704         for (row = tab->n_redundant; row < tab->n_row; ++row) {
705                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
706                         continue;
707                 if (tab->row_sign) {
708                         if (tab->row_sign[row] == 0 &&
709                             is_obviously_neg(tab, row))
710                                 tab->row_sign[row] = isl_tab_row_neg;
711                         if (tab->row_sign[row] != isl_tab_row_neg)
712                                 continue;
713                 } else if (!is_obviously_neg(tab, row))
714                         continue;
715                 return row;
716         }
717         return -1;
718 }
719
720 /* Resolve all known or obviously violated constraints through pivoting.
721  * In particular, as long as we can find any violated constraint, we
722  * look for a pivoting column that would result in the lexicographicallly
723  * smallest increment in the sample point.  If there is no such column
724  * then the tableau is infeasible.
725  */
726 static struct isl_tab *restore_lexmin(struct isl_tab *tab)
727 {
728         int row, col;
729
730         if (!tab)
731                 return NULL;
732         if (tab->empty)
733                 return tab;
734         while ((row = first_neg(tab)) != -1) {
735                 col = lexmin_pivot_col(tab, row);
736                 if (col >= tab->n_col)
737                         return isl_tab_mark_empty(tab);
738                 if (col < 0)
739                         goto error;
740                 isl_tab_pivot(tab, row, col);
741         }
742         return tab;
743 error:
744         isl_tab_free(tab);
745         return NULL;
746 }
747
748 /* Given a row that represents an equality, look for an appropriate
749  * pivoting column.
750  * In particular, if there are any non-zero coefficients among
751  * the non-parameter variables, then we take the last of these
752  * variables.  Eliminating this variable in terms of the other
753  * variables and/or parameters does not influence the property
754  * that all column in the initial tableau are lexicographically
755  * positive.  The row corresponding to the eliminated variable
756  * will only have non-zero entries below the diagonal of the
757  * initial tableau.  That is, we transform
758  *
759  *              I                               I
760  *                1             into            a
761  *                  I                             I
762  *
763  * If there is no such non-parameter variable, then we are dealing with
764  * pure parameter equality and we pick any parameter with coefficient 1 or -1
765  * for elimination.  This will ensure that the eliminated parameter
766  * always has an integer value whenever all the other parameters are integral.
767  * If there is no such parameter then we return -1.
768  */
769 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
770 {
771         unsigned off = 2 + tab->M;
772         int i;
773
774         for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
775                 int col;
776                 if (tab->var[i].is_row)
777                         continue;
778                 col = tab->var[i].index;
779                 if (col <= tab->n_dead)
780                         continue;
781                 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
782                         return col;
783         }
784         for (i = tab->n_dead; i < tab->n_col; ++i) {
785                 if (isl_int_is_one(tab->mat->row[row][off + i]))
786                         return i;
787                 if (isl_int_is_negone(tab->mat->row[row][off + i]))
788                         return i;
789         }
790         return -1;
791 }
792
793 /* Add an equality that is known to be valid to the tableau.
794  * We first check if we can eliminate a variable or a parameter.
795  * If not, we add the equality as two inequalities.
796  * In this case, the equality was a pure parameter equality and there
797  * is no need to resolve any constraint violations.
798  */
799 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
800 {
801         int i;
802         int r;
803
804         if (!tab)
805                 return NULL;
806         r = isl_tab_add_row(tab, eq);
807         if (r < 0)
808                 goto error;
809
810         r = tab->con[r].index;
811         i = last_var_col_or_int_par_col(tab, r);
812         if (i < 0) {
813                 tab->con[r].is_nonneg = 1;
814                 isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
815                 isl_seq_neg(eq, eq, 1 + tab->n_var);
816                 r = isl_tab_add_row(tab, eq);
817                 if (r < 0)
818                         goto error;
819                 tab->con[r].is_nonneg = 1;
820                 isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
821         } else {
822                 isl_tab_pivot(tab, r, i);
823                 isl_tab_kill_col(tab, i);
824                 tab->n_eq++;
825
826                 tab = restore_lexmin(tab);
827         }
828
829         return tab;
830 error:
831         isl_tab_free(tab);
832         return NULL;
833 }
834
835 /* Check if the given row is a pure constant.
836  */
837 static int is_constant(struct isl_tab *tab, int row)
838 {
839         unsigned off = 2 + tab->M;
840
841         return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
842                                         tab->n_col - tab->n_dead) == -1;
843 }
844
845 /* Add an equality that may or may not be valid to the tableau.
846  * If the resulting row is a pure constant, then it must be zero.
847  * Otherwise, the resulting tableau is empty.
848  *
849  * If the row is not a pure constant, then we add two inequalities,
850  * each time checking that they can be satisfied.
851  * In the end we try to use one of the two constraints to eliminate
852  * a column.
853  */
854 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
855 {
856         int r1, r2;
857         int row;
858
859         if (!tab)
860                 return NULL;
861         if (tab->bset) {
862                 tab->bset = isl_basic_set_add_eq(tab->bset, eq);
863                 isl_tab_push(tab, isl_tab_undo_bset_eq);
864                 if (!tab->bset)
865                         goto error;
866         }
867         r1 = isl_tab_add_row(tab, eq);
868         if (r1 < 0)
869                 goto error;
870         tab->con[r1].is_nonneg = 1;
871         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]);
872
873         row = tab->con[r1].index;
874         if (is_constant(tab, row)) {
875                 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
876                     (tab->M && !isl_int_is_zero(tab->mat->row[row][2])))
877                         return isl_tab_mark_empty(tab);
878                 return tab;
879         }
880
881         tab = restore_lexmin(tab);
882         if (!tab || tab->empty)
883                 return tab;
884
885         isl_seq_neg(eq, eq, 1 + tab->n_var);
886
887         r2 = isl_tab_add_row(tab, eq);
888         if (r2 < 0)
889                 goto error;
890         tab->con[r2].is_nonneg = 1;
891         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]);
892
893         tab = restore_lexmin(tab);
894         if (!tab || tab->empty)
895                 return tab;
896
897         if (!tab->con[r1].is_row)
898                 isl_tab_kill_col(tab, tab->con[r1].index);
899         else if (!tab->con[r2].is_row)
900                 isl_tab_kill_col(tab, tab->con[r2].index);
901         else if (isl_int_is_zero(tab->mat->row[tab->con[r1].index][1])) {
902                 unsigned off = 2 + tab->M;
903                 int i;
904                 int row = tab->con[r1].index;
905                 i = isl_seq_first_non_zero(tab->mat->row[row]+off+tab->n_dead,
906                                                 tab->n_col - tab->n_dead);
907                 if (i != -1) {
908                         isl_tab_pivot(tab, row, tab->n_dead + i);
909                         isl_tab_kill_col(tab, tab->n_dead + i);
910                 }
911         }
912
913         return tab;
914 error:
915         isl_tab_free(tab);
916         return NULL;
917 }
918
919 /* Add an inequality to the tableau, resolving violations using
920  * restore_lexmin.
921  */
922 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
923 {
924         int r;
925
926         if (!tab)
927                 return NULL;
928         if (tab->bset) {
929                 tab->bset = isl_basic_set_add_ineq(tab->bset, ineq);
930                 isl_tab_push(tab, isl_tab_undo_bset_ineq);
931                 if (!tab->bset)
932                         goto error;
933         }
934         r = isl_tab_add_row(tab, ineq);
935         if (r < 0)
936                 goto error;
937         tab->con[r].is_nonneg = 1;
938         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
939         if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
940                 isl_tab_mark_redundant(tab, tab->con[r].index);
941                 return tab;
942         }
943
944         tab = restore_lexmin(tab);
945         if (tab && !tab->empty && tab->con[r].is_row &&
946                  isl_tab_row_is_redundant(tab, tab->con[r].index))
947                 isl_tab_mark_redundant(tab, tab->con[r].index);
948         return tab;
949 error:
950         isl_tab_free(tab);
951         return NULL;
952 }
953
954 /* Check if the coefficients of the parameters are all integral.
955  */
956 static int integer_parameter(struct isl_tab *tab, int row)
957 {
958         int i;
959         int col;
960         unsigned off = 2 + tab->M;
961
962         for (i = 0; i < tab->n_param; ++i) {
963                 /* Eliminated parameter */
964                 if (tab->var[i].is_row)
965                         continue;
966                 col = tab->var[i].index;
967                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
968                                                 tab->mat->row[row][0]))
969                         return 0;
970         }
971         for (i = 0; i < tab->n_div; ++i) {
972                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
973                         continue;
974                 col = tab->var[tab->n_var - tab->n_div + i].index;
975                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
976                                                 tab->mat->row[row][0]))
977                         return 0;
978         }
979         return 1;
980 }
981
982 /* Check if the coefficients of the non-parameter variables are all integral.
983  */
984 static int integer_variable(struct isl_tab *tab, int row)
985 {
986         int i;
987         unsigned off = 2 + tab->M;
988
989         for (i = 0; i < tab->n_col; ++i) {
990                 if (tab->col_var[i] >= 0 &&
991                     (tab->col_var[i] < tab->n_param ||
992                      tab->col_var[i] >= tab->n_var - tab->n_div))
993                         continue;
994                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
995                                                 tab->mat->row[row][0]))
996                         return 0;
997         }
998         return 1;
999 }
1000
1001 /* Check if the constant term is integral.
1002  */
1003 static int integer_constant(struct isl_tab *tab, int row)
1004 {
1005         return isl_int_is_divisible_by(tab->mat->row[row][1],
1006                                         tab->mat->row[row][0]);
1007 }
1008
1009 #define I_CST   1 << 0
1010 #define I_PAR   1 << 1
1011 #define I_VAR   1 << 2
1012
1013 /* Check for first (non-parameter) variable that is non-integer and
1014  * therefore requires a cut.
1015  * For parametric tableaus, there are three parts in a row,
1016  * the constant, the coefficients of the parameters and the rest.
1017  * For each part, we check whether the coefficients in that part
1018  * are all integral and if so, set the corresponding flag in *f.
1019  * If the constant and the parameter part are integral, then the
1020  * current sample value is integral and no cut is required
1021  * (irrespective of whether the variable part is integral).
1022  */
1023 static int first_non_integer(struct isl_tab *tab, int *f)
1024 {
1025         int i;
1026
1027         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1028                 int flags = 0;
1029                 int row;
1030                 if (!tab->var[i].is_row)
1031                         continue;
1032                 row = tab->var[i].index;
1033                 if (integer_constant(tab, row))
1034                         ISL_FL_SET(flags, I_CST);
1035                 if (integer_parameter(tab, row))
1036                         ISL_FL_SET(flags, I_PAR);
1037                 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1038                         continue;
1039                 if (integer_variable(tab, row))
1040                         ISL_FL_SET(flags, I_VAR);
1041                 *f = flags;
1042                 return row;
1043         }
1044         return -1;
1045 }
1046
1047 /* Add a (non-parametric) cut to cut away the non-integral sample
1048  * value of the given row.
1049  *
1050  * If the row is given by
1051  *
1052  *      m r = f + \sum_i a_i y_i
1053  *
1054  * then the cut is
1055  *
1056  *      c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1057  *
1058  * The big parameter, if any, is ignored, since it is assumed to be big
1059  * enough to be divisible by any integer.
1060  * If the tableau is actually a parametric tableau, then this function
1061  * is only called when all coefficients of the parameters are integral.
1062  * The cut therefore has zero coefficients for the parameters.
1063  *
1064  * The current value is known to be negative, so row_sign, if it
1065  * exists, is set accordingly.
1066  *
1067  * Return the row of the cut or -1.
1068  */
1069 static int add_cut(struct isl_tab *tab, int row)
1070 {
1071         int i;
1072         int r;
1073         isl_int *r_row;
1074         unsigned off = 2 + tab->M;
1075
1076         if (isl_tab_extend_cons(tab, 1) < 0)
1077                 return -1;
1078         r = isl_tab_allocate_con(tab);
1079         if (r < 0)
1080                 return -1;
1081
1082         r_row = tab->mat->row[tab->con[r].index];
1083         isl_int_set(r_row[0], tab->mat->row[row][0]);
1084         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1085         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1086         isl_int_neg(r_row[1], r_row[1]);
1087         if (tab->M)
1088                 isl_int_set_si(r_row[2], 0);
1089         for (i = 0; i < tab->n_col; ++i)
1090                 isl_int_fdiv_r(r_row[off + i],
1091                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1092
1093         tab->con[r].is_nonneg = 1;
1094         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
1095         if (tab->row_sign)
1096                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1097
1098         return tab->con[r].index;
1099 }
1100
1101 /* Given a non-parametric tableau, add cuts until an integer
1102  * sample point is obtained or until the tableau is determined
1103  * to be integer infeasible.
1104  * As long as there is any non-integer value in the sample point,
1105  * we add an appropriate cut, if possible and resolve the violated
1106  * cut constraint using restore_lexmin.
1107  * If one of the corresponding rows is equal to an integral
1108  * combination of variables/constraints plus a non-integral constant,
1109  * then there is no way to obtain an integer point an we return
1110  * a tableau that is marked empty.
1111  */
1112 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab)
1113 {
1114         int row;
1115         int flags;
1116
1117         if (!tab)
1118                 return NULL;
1119         if (tab->empty)
1120                 return tab;
1121
1122         while ((row = first_non_integer(tab, &flags)) != -1) {
1123                 if (ISL_FL_ISSET(flags, I_VAR))
1124                         return isl_tab_mark_empty(tab);
1125                 row = add_cut(tab, row);
1126                 if (row < 0)
1127                         goto error;
1128                 tab = restore_lexmin(tab);
1129                 if (!tab || tab->empty)
1130                         break;
1131         }
1132         return tab;
1133 error:
1134         isl_tab_free(tab);
1135         return NULL;
1136 }
1137
1138 static struct isl_tab *drop_sample(struct isl_tab *tab, int s)
1139 {
1140         if (s != tab->n_outside)
1141                 isl_mat_swap_rows(tab->samples, tab->n_outside, s);
1142         tab->n_outside++;
1143         isl_tab_push(tab, isl_tab_undo_drop_sample);
1144
1145         return tab;
1146 }
1147
1148 /* Check whether all the currently active samples also satisfy the inequality
1149  * "ineq" (treated as an equality if eq is set).
1150  * Remove those samples that do not.
1151  */
1152 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1153 {
1154         int i;
1155         isl_int v;
1156
1157         if (!tab)
1158                 return NULL;
1159
1160         isl_assert(tab->mat->ctx, tab->bset, goto error);
1161         isl_assert(tab->mat->ctx, tab->samples, goto error);
1162         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1163
1164         isl_int_init(v);
1165         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1166                 int sgn;
1167                 isl_seq_inner_product(ineq, tab->samples->row[i],
1168                                         1 + tab->n_var, &v);
1169                 sgn = isl_int_sgn(v);
1170                 if (eq ? (sgn == 0) : (sgn >= 0))
1171                         continue;
1172                 tab = drop_sample(tab, i);
1173                 if (!tab)
1174                         break;
1175         }
1176         isl_int_clear(v);
1177
1178         return tab;
1179 error:
1180         isl_tab_free(tab);
1181         return NULL;
1182 }
1183
1184 /* Check whether the sample value of the tableau is finite,
1185  * i.e., either the tableau does not use a big parameter, or
1186  * all values of the variables are equal to the big parameter plus
1187  * some constant.  This constant is the actual sample value.
1188  */
1189 static int sample_is_finite(struct isl_tab *tab)
1190 {
1191         int i;
1192
1193         if (!tab->M)
1194                 return 1;
1195
1196         for (i = 0; i < tab->n_var; ++i) {
1197                 int row;
1198                 if (!tab->var[i].is_row)
1199                         return 0;
1200                 row = tab->var[i].index;
1201                 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1202                         return 0;
1203         }
1204         return 1;
1205 }
1206
1207 /* Check if the context tableau of sol has any integer points.
1208  * Returns -1 if an error occurred.
1209  * If an integer point can be found and if moreover it is finite,
1210  * then it is added to the list of sample values.
1211  *
1212  * This function is only called when none of the currently active sample
1213  * values satisfies the most recently added constraint.
1214  */
1215 static int context_is_feasible(struct isl_sol *sol)
1216 {
1217         struct isl_tab_undo *snap;
1218         struct isl_tab *tab;
1219         int feasible;
1220
1221         if (!sol || !sol->context_tab)
1222                 return -1;
1223
1224         snap = isl_tab_snap(sol->context_tab);
1225         isl_tab_push_basis(sol->context_tab);
1226
1227         sol->context_tab = cut_to_integer_lexmin(sol->context_tab);
1228         if (!sol->context_tab)
1229                 goto error;
1230
1231         tab = sol->context_tab;
1232         if (!tab->empty && sample_is_finite(tab)) {
1233                 struct isl_vec *sample;
1234
1235                 tab->samples = isl_mat_extend(tab->samples,
1236                                         tab->n_sample + 1, tab->samples->n_col);
1237                 if (!tab->samples)
1238                         goto error;
1239
1240                 sample = isl_tab_get_sample_value(tab);
1241                 if (!sample)
1242                         goto error;
1243                 isl_seq_cpy(tab->samples->row[tab->n_sample],
1244                                 sample->el, sample->size);
1245                 isl_vec_free(sample);
1246                 tab->n_sample++;
1247         }
1248
1249         feasible = !sol->context_tab->empty;
1250         if (isl_tab_rollback(sol->context_tab, snap) < 0)
1251                 goto error;
1252
1253         return feasible;
1254 error:
1255         isl_tab_free(sol->context_tab);
1256         sol->context_tab = NULL;
1257         return -1;
1258 }
1259
1260 /* First check if any of the currently active sample values satisfies
1261  * the inequality "ineq" (an equality if eq is set).
1262  * If not, continue with check_integer_feasible.
1263  */
1264 static int context_valid_sample_or_feasible(struct isl_sol *sol,
1265         isl_int *ineq, int eq)
1266 {
1267         int i;
1268         isl_int v;
1269         struct isl_tab *tab;
1270
1271         if (!sol || !sol->context_tab)
1272                 return -1;
1273
1274         tab = sol->context_tab;
1275         isl_assert(tab->mat->ctx, tab->bset, return -1);
1276         isl_assert(tab->mat->ctx, tab->samples, return -1);
1277         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1278
1279         isl_int_init(v);
1280         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1281                 int sgn;
1282                 isl_seq_inner_product(ineq, tab->samples->row[i],
1283                                         1 + tab->n_var, &v);
1284                 sgn = isl_int_sgn(v);
1285                 if (eq ? (sgn == 0) : (sgn >= 0))
1286                         break;
1287         }
1288         isl_int_clear(v);
1289
1290         if (i < tab->n_sample)
1291                 return 1;
1292
1293         return context_is_feasible(sol);
1294 }
1295
1296 /* For a div d = floor(f/m), add the constraints
1297  *
1298  *              f - m d >= 0
1299  *              -(f-(m-1)) + m d >= 0
1300  *
1301  * Note that the second constraint is the negation of
1302  *
1303  *              f - m d >= m
1304  */
1305 static struct isl_tab *add_div_constraints(struct isl_tab *tab, unsigned div)
1306 {
1307         unsigned total;
1308         unsigned div_pos;
1309         struct isl_vec *ineq;
1310
1311         if (!tab)
1312                 return NULL;
1313
1314         total = isl_basic_set_total_dim(tab->bset);
1315         div_pos = 1 + total - tab->bset->n_div + div;
1316
1317         ineq = ineq_for_div(tab->bset, div);
1318         if (!ineq)
1319                 goto error;
1320
1321         tab = add_lexmin_ineq(tab, ineq->el);
1322
1323         isl_seq_neg(ineq->el, tab->bset->div[div] + 1, 1 + total);
1324         isl_int_set(ineq->el[div_pos], tab->bset->div[div][0]);
1325         isl_int_add(ineq->el[0], ineq->el[0], ineq->el[div_pos]);
1326         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1327         tab = add_lexmin_ineq(tab, ineq->el);
1328
1329         isl_vec_free(ineq);
1330
1331         return tab;
1332 error:
1333         isl_tab_free(tab);
1334         return NULL;
1335 }
1336
1337 /* Add a div specified by "div" to both the main tableau and
1338  * the context tableau.  In case of the main tableau, we only
1339  * need to add an extra div.  In the context tableau, we also
1340  * need to express the meaning of the div.
1341  * Return the index of the div or -1 if anything went wrong.
1342  */
1343 static int add_div(struct isl_tab *tab, struct isl_tab **context_tab,
1344         struct isl_vec *div)
1345 {
1346         int i;
1347         int r;
1348         int k;
1349         struct isl_mat *samples;
1350
1351         if (isl_tab_extend_vars(*context_tab, 1) < 0)
1352                 goto error;
1353         r = isl_tab_allocate_var(*context_tab);
1354         if (r < 0)
1355                 goto error;
1356         (*context_tab)->var[r].is_nonneg = 1;
1357         (*context_tab)->var[r].frozen = 1;
1358
1359         samples = isl_mat_extend((*context_tab)->samples,
1360                         (*context_tab)->n_sample, 1 + (*context_tab)->n_var);
1361         (*context_tab)->samples = samples;
1362         if (!samples)
1363                 goto error;
1364         for (i = (*context_tab)->n_outside; i < samples->n_row; ++i) {
1365                 isl_seq_inner_product(div->el + 1, samples->row[i],
1366                         div->size - 1, &samples->row[i][samples->n_col - 1]);
1367                 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1368                                samples->row[i][samples->n_col - 1], div->el[0]);
1369         }
1370
1371         (*context_tab)->bset = isl_basic_set_extend_dim((*context_tab)->bset,
1372                 isl_basic_set_get_dim((*context_tab)->bset), 1, 0, 2);
1373         k = isl_basic_set_alloc_div((*context_tab)->bset);
1374         if (k < 0)
1375                 goto error;
1376         isl_seq_cpy((*context_tab)->bset->div[k], div->el, div->size);
1377         isl_tab_push((*context_tab), isl_tab_undo_bset_div);
1378         *context_tab = add_div_constraints(*context_tab, k);
1379         if (!*context_tab)
1380                 goto error;
1381
1382         if (isl_tab_extend_vars(tab, 1) < 0)
1383                 goto error;
1384         r = isl_tab_allocate_var(tab);
1385         if (r < 0)
1386                 goto error;
1387         if (!(*context_tab)->M)
1388                 tab->var[r].is_nonneg = 1;
1389         tab->var[r].frozen = 1;
1390         tab->n_div++;
1391
1392         return tab->n_div - 1;
1393 error:
1394         isl_tab_free(*context_tab);
1395         *context_tab = NULL;
1396         return -1;
1397 }
1398
1399 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1400 {
1401         int i;
1402         unsigned total = isl_basic_set_total_dim(tab->bset);
1403
1404         for (i = 0; i < tab->bset->n_div; ++i) {
1405                 if (isl_int_ne(tab->bset->div[i][0], denom))
1406                         continue;
1407                 if (!isl_seq_eq(tab->bset->div[i] + 1, div, total))
1408                         continue;
1409                 return i;
1410         }
1411         return -1;
1412 }
1413
1414 /* Return the index of a div that corresponds to "div".
1415  * We first check if we already have such a div and if not, we create one.
1416  */
1417 static int get_div(struct isl_tab *tab, struct isl_tab **context_tab,
1418         struct isl_vec *div)
1419 {
1420         int d;
1421
1422         d = find_div(*context_tab, div->el + 1, div->el[0]);
1423         if (d != -1)
1424                 return d;
1425
1426         return add_div(tab, context_tab, div);
1427 }
1428
1429 /* Add a parametric cut to cut away the non-integral sample value
1430  * of the give row.
1431  * Let a_i be the coefficients of the constant term and the parameters
1432  * and let b_i be the coefficients of the variables or constraints
1433  * in basis of the tableau.
1434  * Let q be the div q = floor(\sum_i {-a_i} y_i).
1435  *
1436  * The cut is expressed as
1437  *
1438  *      c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1439  *
1440  * If q did not already exist in the context tableau, then it is added first.
1441  * If q is in a column of the main tableau then the "+ q" can be accomplished
1442  * by setting the corresponding entry to the denominator of the constraint.
1443  * If q happens to be in a row of the main tableau, then the corresponding
1444  * row needs to be added instead (taking care of the denominators).
1445  * Note that this is very unlikely, but perhaps not entirely impossible.
1446  *
1447  * The current value of the cut is known to be negative (or at least
1448  * non-positive), so row_sign is set accordingly.
1449  *
1450  * Return the row of the cut or -1.
1451  */
1452 static int add_parametric_cut(struct isl_tab *tab, int row,
1453         struct isl_tab **context_tab)
1454 {
1455         struct isl_vec *div;
1456         int d;
1457         int i;
1458         int r;
1459         isl_int *r_row;
1460         int col;
1461         unsigned off = 2 + tab->M;
1462
1463         if (!*context_tab)
1464                 goto error;
1465
1466         if (isl_tab_extend_cons(*context_tab, 3) < 0)
1467                 goto error;
1468
1469         div = get_row_parameter_div(tab, row);
1470         if (!div)
1471                 return -1;
1472
1473         d = get_div(tab, context_tab, div);
1474         if (d < 0)
1475                 goto error;
1476
1477         if (isl_tab_extend_cons(tab, 1) < 0)
1478                 return -1;
1479         r = isl_tab_allocate_con(tab);
1480         if (r < 0)
1481                 return -1;
1482
1483         r_row = tab->mat->row[tab->con[r].index];
1484         isl_int_set(r_row[0], tab->mat->row[row][0]);
1485         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1486         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1487         isl_int_neg(r_row[1], r_row[1]);
1488         if (tab->M)
1489                 isl_int_set_si(r_row[2], 0);
1490         for (i = 0; i < tab->n_param; ++i) {
1491                 if (tab->var[i].is_row)
1492                         continue;
1493                 col = tab->var[i].index;
1494                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1495                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1496                                 tab->mat->row[row][0]);
1497                 isl_int_neg(r_row[off + col], r_row[off + col]);
1498         }
1499         for (i = 0; i < tab->n_div; ++i) {
1500                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1501                         continue;
1502                 col = tab->var[tab->n_var - tab->n_div + i].index;
1503                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1504                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1505                                 tab->mat->row[row][0]);
1506                 isl_int_neg(r_row[off + col], r_row[off + col]);
1507         }
1508         for (i = 0; i < tab->n_col; ++i) {
1509                 if (tab->col_var[i] >= 0 &&
1510                     (tab->col_var[i] < tab->n_param ||
1511                      tab->col_var[i] >= tab->n_var - tab->n_div))
1512                         continue;
1513                 isl_int_fdiv_r(r_row[off + i],
1514                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1515         }
1516         if (tab->var[tab->n_var - tab->n_div + d].is_row) {
1517                 isl_int gcd;
1518                 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
1519                 isl_int_init(gcd);
1520                 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
1521                 isl_int_divexact(r_row[0], r_row[0], gcd);
1522                 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
1523                 isl_seq_combine(r_row + 1, gcd, r_row + 1,
1524                                 r_row[0], tab->mat->row[d_row] + 1,
1525                                 off - 1 + tab->n_col);
1526                 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
1527                 isl_int_clear(gcd);
1528         } else {
1529                 col = tab->var[tab->n_var - tab->n_div + d].index;
1530                 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
1531         }
1532
1533         tab->con[r].is_nonneg = 1;
1534         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
1535         if (tab->row_sign)
1536                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1537
1538         isl_vec_free(div);
1539
1540         return tab->con[r].index;
1541 error:
1542         isl_tab_free(*context_tab);
1543         *context_tab = NULL;
1544         return -1;
1545 }
1546
1547 /* Construct a tableau for bmap that can be used for computing
1548  * the lexicographic minimum (or maximum) of bmap.
1549  * If not NULL, then dom is the domain where the minimum
1550  * should be computed.  In this case, we set up a parametric
1551  * tableau with row signs (initialized to "unknown").
1552  * If M is set, then the tableau will use a big parameter.
1553  * If max is set, then a maximum should be computed instead of a minimum.
1554  * This means that for each variable x, the tableau will contain the variable
1555  * x' = M - x, rather than x' = M + x.  This in turn means that the coefficient
1556  * of the variables in all constraints are negated prior to adding them
1557  * to the tableau.
1558  */
1559 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
1560         struct isl_basic_set *dom, unsigned M, int max)
1561 {
1562         int i;
1563         struct isl_tab *tab;
1564
1565         tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
1566                             isl_basic_map_total_dim(bmap), M);
1567         if (!tab)
1568                 return NULL;
1569
1570         tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
1571         if (dom) {
1572                 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
1573                 tab->n_div = dom->n_div;
1574                 tab->row_sign = isl_calloc_array(bmap->ctx,
1575                                         enum isl_tab_row_sign, tab->mat->n_row);
1576                 if (!tab->row_sign)
1577                         goto error;
1578         }
1579         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1580                 return isl_tab_mark_empty(tab);
1581
1582         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1583                 tab->var[i].is_nonneg = 1;
1584                 tab->var[i].frozen = 1;
1585         }
1586         for (i = 0; i < bmap->n_eq; ++i) {
1587                 if (max)
1588                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1589                                     bmap->eq[i] + 1 + tab->n_param,
1590                                     tab->n_var - tab->n_param - tab->n_div);
1591                 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
1592                 if (max)
1593                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1594                                     bmap->eq[i] + 1 + tab->n_param,
1595                                     tab->n_var - tab->n_param - tab->n_div);
1596                 if (!tab || tab->empty)
1597                         return tab;
1598         }
1599         for (i = 0; i < bmap->n_ineq; ++i) {
1600                 if (max)
1601                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
1602                                     bmap->ineq[i] + 1 + tab->n_param,
1603                                     tab->n_var - tab->n_param - tab->n_div);
1604                 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
1605                 if (max)
1606                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
1607                                     bmap->ineq[i] + 1 + tab->n_param,
1608                                     tab->n_var - tab->n_param - tab->n_div);
1609                 if (!tab || tab->empty)
1610                         return tab;
1611         }
1612         return tab;
1613 error:
1614         isl_tab_free(tab);
1615         return NULL;
1616 }
1617
1618 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
1619 {
1620         struct isl_tab *tab;
1621
1622         bset = isl_basic_set_cow(bset);
1623         if (!bset)
1624                 return NULL;
1625         tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
1626         if (!tab)
1627                 goto error;
1628         tab->bset = bset;
1629         tab->n_sample = 0;
1630         tab->n_outside = 0;
1631         tab->samples = isl_mat_alloc(bset->ctx, 1, 1 + tab->n_var);
1632         if (!tab->samples)
1633                 goto error;
1634         return tab;
1635 error:
1636         isl_basic_set_free(bset);
1637         return NULL;
1638 }
1639
1640 /* Construct an isl_sol_map structure for accumulating the solution.
1641  * If track_empty is set, then we also keep track of the parts
1642  * of the context where there is no solution.
1643  * If max is set, then we are solving a maximization, rather than
1644  * a minimization problem, which means that the variables in the
1645  * tableau have value "M - x" rather than "M + x".
1646  */
1647 static struct isl_sol_map *sol_map_init(struct isl_basic_map *bmap,
1648         struct isl_basic_set *dom, int track_empty, int max)
1649 {
1650         struct isl_sol_map *sol_map;
1651         struct isl_tab *context_tab;
1652         int f;
1653
1654         sol_map = isl_calloc_type(bset->ctx, struct isl_sol_map);
1655         if (!sol_map)
1656                 goto error;
1657
1658         sol_map->max = max;
1659         sol_map->sol.add = &sol_map_add_wrap;
1660         sol_map->sol.free = &sol_map_free_wrap;
1661         sol_map->map = isl_map_alloc_dim(isl_basic_map_get_dim(bmap), 1,
1662                                             ISL_MAP_DISJOINT);
1663         if (!sol_map->map)
1664                 goto error;
1665
1666         context_tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
1667         context_tab = restore_lexmin(context_tab);
1668         sol_map->sol.context_tab = context_tab;
1669         f = context_is_feasible(&sol_map->sol);
1670         if (f < 0)
1671                 goto error;
1672
1673         if (track_empty) {
1674                 sol_map->empty = isl_set_alloc_dim(isl_basic_set_get_dim(dom),
1675                                                         1, ISL_SET_DISJOINT);
1676                 if (!sol_map->empty)
1677                         goto error;
1678         }
1679
1680         isl_basic_set_free(dom);
1681         return sol_map;
1682 error:
1683         isl_basic_set_free(dom);
1684         sol_map_free(sol_map);
1685         return NULL;
1686 }
1687
1688 /* For each variable in the context tableau, check if the variable can
1689  * only attain non-negative values.  If so, mark the parameter as non-negative
1690  * in the main tableau.  This allows for a more direct identification of some
1691  * cases of violated constraints.
1692  */
1693 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
1694         struct isl_tab *context_tab)
1695 {
1696         int i;
1697         struct isl_tab_undo *snap, *snap2;
1698         struct isl_vec *ineq = NULL;
1699         struct isl_tab_var *var;
1700         int n;
1701
1702         if (context_tab->n_var == 0)
1703                 return tab;
1704
1705         ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
1706         if (!ineq)
1707                 goto error;
1708
1709         if (isl_tab_extend_cons(context_tab, 1) < 0)
1710                 goto error;
1711
1712         snap = isl_tab_snap(context_tab);
1713         isl_tab_push_basis(context_tab);
1714
1715         snap2 = isl_tab_snap(context_tab);
1716
1717         n = 0;
1718         isl_seq_clr(ineq->el, ineq->size);
1719         for (i = 0; i < context_tab->n_var; ++i) {
1720                 isl_int_set_si(ineq->el[1 + i], 1);
1721                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
1722                 var = &context_tab->con[context_tab->n_con - 1];
1723                 if (!context_tab->empty &&
1724                     !isl_tab_min_at_most_neg_one(context_tab, var)) {
1725                         int j = i;
1726                         if (i >= tab->n_param)
1727                                 j = i - tab->n_param + tab->n_var - tab->n_div;
1728                         tab->var[j].is_nonneg = 1;
1729                         n++;
1730                 }
1731                 isl_int_set_si(ineq->el[1 + i], 0);
1732                 if (isl_tab_rollback(context_tab, snap2) < 0)
1733                         goto error;
1734         }
1735
1736         if (isl_tab_rollback(context_tab, snap) < 0)
1737                 goto error;
1738
1739         if (n == context_tab->n_var) {
1740                 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
1741                 context_tab->M = 0;
1742         }
1743
1744         isl_vec_free(ineq);
1745         return tab;
1746 error:
1747         isl_vec_free(ineq);
1748         isl_tab_free(tab);
1749         return NULL;
1750 }
1751
1752 /* Check whether all coefficients of (non-parameter) variables
1753  * are non-positive, meaning that no pivots can be performed on the row.
1754  */
1755 static int is_critical(struct isl_tab *tab, int row)
1756 {
1757         int j;
1758         unsigned off = 2 + tab->M;
1759
1760         for (j = tab->n_dead; j < tab->n_col; ++j) {
1761                 if (tab->col_var[j] >= 0 &&
1762                     (tab->col_var[j] < tab->n_param  ||
1763                     tab->col_var[j] >= tab->n_var - tab->n_div))
1764                         continue;
1765
1766                 if (isl_int_is_pos(tab->mat->row[row][off + j]))
1767                         return 0;
1768         }
1769
1770         return 1;
1771 }
1772
1773 /* Check whether the inequality represented by vec is strict over the integers,
1774  * i.e., there are no integer values satisfying the constraint with
1775  * equality.  This happens if the gcd of the coefficients is not a divisor
1776  * of the constant term.  If so, scale the constraint down by the gcd
1777  * of the coefficients.
1778  */
1779 static int is_strict(struct isl_vec *vec)
1780 {
1781         isl_int gcd;
1782         int strict = 0;
1783
1784         isl_int_init(gcd);
1785         isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
1786         if (!isl_int_is_one(gcd)) {
1787                 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
1788                 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
1789                 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
1790         }
1791         isl_int_clear(gcd);
1792
1793         return strict;
1794 }
1795
1796 /* Determine the sign of the given row of the main tableau.
1797  * The result is one of
1798  *      isl_tab_row_pos: always non-negative; no pivot needed
1799  *      isl_tab_row_neg: always non-positive; pivot
1800  *      isl_tab_row_any: can be both positive and negative; split
1801  *
1802  * We first handle some simple cases
1803  *      - the row sign may be known already
1804  *      - the row may be obviously non-negative
1805  *      - the parametric constant may be equal to that of another row
1806  *        for which we know the sign.  This sign will be either "pos" or
1807  *        "any".  If it had been "neg" then we would have pivoted before.
1808  *
1809  * If none of these cases hold, we check the value of the row for each
1810  * of the currently active samples.  Based on the signs of these values
1811  * we make an initial determination of the sign of the row.
1812  *
1813  *      all zero                        ->      unk(nown)
1814  *      all non-negative                ->      pos
1815  *      all non-positive                ->      neg
1816  *      both negative and positive      ->      all
1817  *
1818  * If we end up with "all", we are done.
1819  * Otherwise, we perform a check for positive and/or negative
1820  * values as follows.
1821  *
1822  *      samples        neg             unk             pos
1823  *      <0 ?                        Y        N      Y        N
1824  *                                          pos    any      pos
1825  *      >0 ?         Y      N    Y     N
1826  *                  any    neg  any   neg
1827  *
1828  * There is no special sign for "zero", because we can usually treat zero
1829  * as either non-negative or non-positive, whatever works out best.
1830  * However, if the row is "critical", meaning that pivoting is impossible
1831  * then we don't want to limp zero with the non-positive case, because
1832  * then we we would lose the solution for those values of the parameters
1833  * where the value of the row is zero.  Instead, we treat 0 as non-negative
1834  * ensuring a split if the row can attain both zero and negative values.
1835  * The same happens when the original constraint was one that could not
1836  * be satisfied with equality by any integer values of the parameters.
1837  * In this case, we normalize the constraint, but then a value of zero
1838  * for the normalized constraint is actually a positive value for the
1839  * original constraint, so again we need to treat zero as non-negative.
1840  * In both these cases, we have the following decision tree instead:
1841  *
1842  *      all non-negative                ->      pos
1843  *      all negative                    ->      neg
1844  *      both negative and non-negative  ->      all
1845  *
1846  *      samples        neg                             pos
1847  *      <0 ?                                        Y        N
1848  *                                                 any      pos
1849  *      >=0 ?        Y      N
1850  *                  any    neg
1851  */
1852 static int row_sign(struct isl_tab *tab, struct isl_sol *sol, int row)
1853 {
1854         int i;
1855         struct isl_tab_undo *snap = NULL;
1856         struct isl_vec *ineq = NULL;
1857         int res = isl_tab_row_unknown;
1858         int critical;
1859         int strict;
1860         int sgn;
1861         int row2;
1862         isl_int tmp;
1863         struct isl_tab *context_tab = sol->context_tab;
1864
1865         if (tab->row_sign[row] != isl_tab_row_unknown)
1866                 return tab->row_sign[row];
1867         if (is_obviously_nonneg(tab, row))
1868                 return isl_tab_row_pos;
1869         for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
1870                 if (tab->row_sign[row2] == isl_tab_row_unknown)
1871                         continue;
1872                 if (identical_parameter_line(tab, row, row2))
1873                         return tab->row_sign[row2];
1874         }
1875
1876         critical = is_critical(tab, row);
1877
1878         isl_assert(tab->mat->ctx, context_tab->samples, goto error);
1879         isl_assert(tab->mat->ctx, context_tab->samples->n_col == 1 + context_tab->n_var, goto error);
1880
1881         ineq = get_row_parameter_ineq(tab, row);
1882         if (!ineq)
1883                 goto error;
1884
1885         strict = is_strict(ineq);
1886
1887         isl_int_init(tmp);
1888         for (i = context_tab->n_outside; i < context_tab->n_sample; ++i) {
1889                 isl_seq_inner_product(context_tab->samples->row[i], ineq->el,
1890                                         ineq->size, &tmp);
1891                 sgn = isl_int_sgn(tmp);
1892                 if (sgn > 0 || (sgn == 0 && (critical || strict))) {
1893                         if (res == isl_tab_row_unknown)
1894                                 res = isl_tab_row_pos;
1895                         if (res == isl_tab_row_neg)
1896                                 res = isl_tab_row_any;
1897                 }
1898                 if (sgn < 0) {
1899                         if (res == isl_tab_row_unknown)
1900                                 res = isl_tab_row_neg;
1901                         if (res == isl_tab_row_pos)
1902                                 res = isl_tab_row_any;
1903                 }
1904                 if (res == isl_tab_row_any)
1905                         break;
1906         }
1907         isl_int_clear(tmp);
1908
1909         if (res != isl_tab_row_any) {
1910                 if (isl_tab_extend_cons(context_tab, 1) < 0)
1911                         goto error;
1912
1913                 snap = isl_tab_snap(context_tab);
1914                 isl_tab_push_basis(context_tab);
1915         }
1916
1917         if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
1918                 /* test for negative values */
1919                 int feasible;
1920                 isl_seq_neg(ineq->el, ineq->el, ineq->size);
1921                 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1922
1923                 isl_tab_push_basis(context_tab);
1924                 sol->context_tab = add_lexmin_ineq(sol->context_tab, ineq->el);
1925                 feasible = context_is_feasible(sol);
1926                 if (feasible < 0)
1927                         goto error;
1928                 context_tab = sol->context_tab;
1929                 if (!feasible)
1930                         res = isl_tab_row_pos;
1931                 else
1932                         res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
1933                                                            : isl_tab_row_any;
1934                 if (isl_tab_rollback(context_tab, snap) < 0)
1935                         goto error;
1936
1937                 if (res == isl_tab_row_neg) {
1938                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
1939                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1940                 }
1941         }
1942
1943         if (res == isl_tab_row_neg) {
1944                 /* test for positive values */
1945                 int feasible;
1946                 if (!critical && !strict)
1947                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1948
1949                 isl_tab_push_basis(context_tab);
1950                 sol->context_tab = add_lexmin_ineq(sol->context_tab, ineq->el);
1951                 feasible = context_is_feasible(sol);
1952                 if (feasible < 0)
1953                         goto error;
1954                 context_tab = sol->context_tab;
1955                 if (feasible)
1956                         res = isl_tab_row_any;
1957                 if (isl_tab_rollback(context_tab, snap) < 0)
1958                         goto error;
1959         }
1960
1961         isl_vec_free(ineq);
1962         return res;
1963 error:
1964         isl_vec_free(ineq);
1965         return 0;
1966 }
1967
1968 static struct isl_sol *find_solutions(struct isl_sol *sol, struct isl_tab *tab);
1969
1970 /* Find solutions for values of the parameters that satisfy the given
1971  * inequality.
1972  *
1973  * We currently take a snapshot of the context tableau that is reset
1974  * when we return from this function, while we make a copy of the main
1975  * tableau, leaving the original main tableau untouched.
1976  * These are fairly arbitrary choices.  Making a copy also of the context
1977  * tableau would obviate the need to undo any changes made to it later,
1978  * while taking a snapshot of the main tableau could reduce memory usage.
1979  * If we were to switch to taking a snapshot of the main tableau,
1980  * we would have to keep in mind that we need to save the row signs
1981  * and that we need to do this before saving the current basis
1982  * such that the basis has been restore before we restore the row signs.
1983  */
1984 static struct isl_sol *find_in_pos(struct isl_sol *sol,
1985         struct isl_tab *tab, isl_int *ineq)
1986 {
1987         struct isl_tab_undo *snap;
1988
1989         snap = isl_tab_snap(sol->context_tab);
1990         isl_tab_push_basis(sol->context_tab);
1991         if (isl_tab_extend_cons(sol->context_tab, 1) < 0)
1992                 goto error;
1993
1994         tab = isl_tab_dup(tab);
1995         if (!tab)
1996                 goto error;
1997
1998         sol->context_tab = add_lexmin_ineq(sol->context_tab, ineq);
1999         sol->context_tab = check_samples(sol->context_tab, ineq, 0);
2000
2001         sol = find_solutions(sol, tab);
2002
2003         isl_tab_rollback(sol->context_tab, snap);
2004         return sol;
2005 error:
2006         isl_tab_rollback(sol->context_tab, snap);
2007         sol_free(sol);
2008         return NULL;
2009 }
2010
2011 /* Record the absence of solutions for those values of the parameters
2012  * that do not satisfy the given inequality with equality.
2013  */
2014 static struct isl_sol *no_sol_in_strict(struct isl_sol *sol,
2015         struct isl_tab *tab, struct isl_vec *ineq)
2016 {
2017         int empty;
2018         int f;
2019         struct isl_tab_undo *snap;
2020         snap = isl_tab_snap(sol->context_tab);
2021         isl_tab_push_basis(sol->context_tab);
2022         if (isl_tab_extend_cons(sol->context_tab, 1) < 0)
2023                 goto error;
2024
2025         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2026
2027         sol->context_tab = add_lexmin_ineq(sol->context_tab, ineq->el);
2028         f = context_valid_sample_or_feasible(sol, ineq->el, 0);
2029         if (f < 0)
2030                 goto error;
2031
2032         empty = tab->empty;
2033         tab->empty = 1;
2034         sol = sol->add(sol, tab);
2035         tab->empty = empty;
2036
2037         isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
2038
2039         if (isl_tab_rollback(sol->context_tab, snap) < 0)
2040                 goto error;
2041         return sol;
2042 error:
2043         sol_free(sol);
2044         return NULL;
2045 }
2046
2047 /* Given a main tableau where more than one row requires a split,
2048  * determine and return the "best" row to split on.
2049  *
2050  * Given two rows in the main tableau, if the inequality corresponding
2051  * to the first row is redundant with respect to that of the second row
2052  * in the current tableau, then it is better to split on the second row,
2053  * since in the positive part, both row will be positive.
2054  * (In the negative part a pivot will have to be performed and just about
2055  * anything can happen to the sign of the other row.)
2056  *
2057  * As a simple heuristic, we therefore select the row that makes the most
2058  * of the other rows redundant.
2059  *
2060  * Perhaps it would also be useful to look at the number of constraints
2061  * that conflict with any given constraint.
2062  */
2063 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2064 {
2065         struct isl_tab_undo *snap, *snap2;
2066         int split;
2067         int row;
2068         int best = -1;
2069         int best_r;
2070
2071         if (isl_tab_extend_cons(context_tab, 2) < 0)
2072                 return -1;
2073
2074         snap = isl_tab_snap(context_tab);
2075         isl_tab_push_basis(context_tab);
2076         snap2 = isl_tab_snap(context_tab);
2077
2078         for (split = tab->n_redundant; split < tab->n_row; ++split) {
2079                 struct isl_tab_undo *snap3;
2080                 struct isl_vec *ineq = NULL;
2081                 int r = 0;
2082
2083                 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2084                         continue;
2085                 if (tab->row_sign[split] != isl_tab_row_any)
2086                         continue;
2087
2088                 ineq = get_row_parameter_ineq(tab, split);
2089                 if (!ineq)
2090                         return -1;
2091                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2092                 isl_vec_free(ineq);
2093
2094                 snap3 = isl_tab_snap(context_tab);
2095
2096                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2097                         struct isl_tab_var *var;
2098
2099                         if (row == split)
2100                                 continue;
2101                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2102                                 continue;
2103                         if (tab->row_sign[row] != isl_tab_row_any)
2104                                 continue;
2105
2106                         ineq = get_row_parameter_ineq(tab, row);
2107                         if (!ineq)
2108                                 return -1;
2109                         context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2110                         isl_vec_free(ineq);
2111                         var = &context_tab->con[context_tab->n_con - 1];
2112                         if (!context_tab->empty &&
2113                             !isl_tab_min_at_most_neg_one(context_tab, var))
2114                                 r++;
2115                         if (isl_tab_rollback(context_tab, snap3) < 0)
2116                                 return -1;
2117                 }
2118                 if (best == -1 || r > best_r) {
2119                         best = split;
2120                         best_r = r;
2121                 }
2122                 if (isl_tab_rollback(context_tab, snap2) < 0)
2123                         return -1;
2124         }
2125
2126         if (isl_tab_rollback(context_tab, snap) < 0)
2127                 return -1;
2128
2129         return best;
2130 }
2131
2132 /* Compute the lexicographic minimum of the set represented by the main
2133  * tableau "tab" within the context "sol->context_tab".
2134  * On entry the sample value of the main tableau is lexicographically
2135  * less than or equal to this lexicographic minimum.
2136  * Pivots are performed until a feasible point is found, which is then
2137  * necessarily equal to the minimum, or until the tableau is found to
2138  * be infeasible.  Some pivots may need to be performed for only some
2139  * feasible values of the context tableau.  If so, the context tableau
2140  * is split into a part where the pivot is needed and a part where it is not.
2141  *
2142  * Whenever we enter the main loop, the main tableau is such that no
2143  * "obvious" pivots need to be performed on it, where "obvious" means
2144  * that the given row can be seen to be negative without looking at
2145  * the context tableau.  In particular, for non-parametric problems,
2146  * no pivots need to be performed on the main tableau.
2147  * The caller of find_solutions is responsible for making this property
2148  * hold prior to the first iteration of the loop, while restore_lexmin
2149  * is called before every other iteration.
2150  *
2151  * Inside the main loop, we first examine the signs of the rows of
2152  * the main tableau within the context of the context tableau.
2153  * If we find a row that is always non-positive for all values of
2154  * the parameters satisfying the context tableau and negative for at
2155  * least one value of the parameters, we perform the appropriate pivot
2156  * and start over.  An exception is the case where no pivot can be
2157  * performed on the row.  In this case, we require that the sign of
2158  * the row is negative for all values of the parameters (rather than just
2159  * non-positive).  This special case is handled inside row_sign, which
2160  * will say that the row can have any sign if it determines that it can
2161  * attain both negative and zero values.
2162  *
2163  * If we can't find a row that always requires a pivot, but we can find
2164  * one or more rows that require a pivot for some values of the parameters
2165  * (i.e., the row can attain both positive and negative signs), then we split
2166  * the context tableau into two parts, one where we force the sign to be
2167  * non-negative and one where we force is to be negative.
2168  * The non-negative part is handled by a recursive call (through find_in_pos).
2169  * Upon returning from this call, we continue with the negative part and
2170  * perform the required pivot.
2171  *
2172  * If no such rows can be found, all rows are non-negative and we have
2173  * found a (rational) feasible point.  If we only wanted a rational point
2174  * then we are done.
2175  * Otherwise, we check if all values of the sample point of the tableau
2176  * are integral for the variables.  If so, we have found the minimal
2177  * integral point and we are done.
2178  * If the sample point is not integral, then we need to make a distinction
2179  * based on whether the constant term is non-integral or the coefficients
2180  * of the parameters.  Furthermore, in order to decide how to handle
2181  * the non-integrality, we also need to know whether the coefficients
2182  * of the other columns in the tableau are integral.  This leads
2183  * to the following table.  The first two rows do not correspond
2184  * to a non-integral sample point and are only mentioned for completeness.
2185  *
2186  *      constant        parameters      other
2187  *
2188  *      int             int             int     |
2189  *      int             int             rat     | -> no problem
2190  *
2191  *      rat             int             int       -> fail
2192  *
2193  *      rat             int             rat       -> cut
2194  *
2195  *      int             rat             rat     |
2196  *      rat             rat             rat     | -> parametric cut
2197  *
2198  *      int             rat             int     |
2199  *      rat             rat             int     | -> split context
2200  *
2201  * If the parametric constant is completely integral, then there is nothing
2202  * to be done.  If the constant term is non-integral, but all the other
2203  * coefficient are integral, then there is nothing that can be done
2204  * and the tableau has no integral solution.
2205  * If, on the other hand, one or more of the other columns have rational
2206  * coeffcients, but the parameter coefficients are all integral, then
2207  * we can perform a regular (non-parametric) cut.
2208  * Finally, if there is any parameter coefficient that is non-integral,
2209  * then we need to involve the context tableau.  There are two cases here.
2210  * If at least one other column has a rational coefficient, then we
2211  * can perform a parametric cut in the main tableau by adding a new
2212  * integer division in the context tableau.
2213  * If all other columns have integral coefficients, then we need to
2214  * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
2215  * is always integral.  We do this by introducing an integer division
2216  * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
2217  * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
2218  * Since q is expressed in the tableau as
2219  *      c + \sum a_i y_i - m q >= 0
2220  *      -c - \sum a_i y_i + m q + m - 1 >= 0
2221  * it is sufficient to add the inequality
2222  *      -c - \sum a_i y_i + m q >= 0
2223  * In the part of the context where this inequality does not hold, the
2224  * main tableau is marked as being empty.
2225  */
2226 static struct isl_sol *find_solutions(struct isl_sol *sol, struct isl_tab *tab)
2227 {
2228         struct isl_tab **context_tab;
2229
2230         if (!tab || !sol)
2231                 goto error;
2232
2233         context_tab = &sol->context_tab;
2234
2235         if (tab->empty)
2236                 goto done;
2237         if ((*context_tab)->empty)
2238                 goto done;
2239
2240         for (; tab && !tab->empty; tab = restore_lexmin(tab)) {
2241                 int flags;
2242                 int row;
2243                 int sgn;
2244                 int split = -1;
2245                 int n_split = 0;
2246
2247                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2248                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2249                                 continue;
2250                         sgn = row_sign(tab, sol, row);
2251                         if (!sgn)
2252                                 goto error;
2253                         tab->row_sign[row] = sgn;
2254                         if (sgn == isl_tab_row_any)
2255                                 n_split++;
2256                         if (sgn == isl_tab_row_any && split == -1)
2257                                 split = row;
2258                         if (sgn == isl_tab_row_neg)
2259                                 break;
2260                 }
2261                 if (row < tab->n_row)
2262                         continue;
2263                 if (split != -1) {
2264                         struct isl_vec *ineq;
2265                         if (n_split != 1)
2266                                 split = best_split(tab, *context_tab);
2267                         if (split < 0)
2268                                 goto error;
2269                         ineq = get_row_parameter_ineq(tab, split);
2270                         if (!ineq)
2271                                 goto error;
2272                         is_strict(ineq);
2273                         for (row = tab->n_redundant; row < tab->n_row; ++row) {
2274                                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2275                                         continue;
2276                                 if (tab->row_sign[row] == isl_tab_row_any)
2277                                         tab->row_sign[row] = isl_tab_row_unknown;
2278                         }
2279                         tab->row_sign[split] = isl_tab_row_pos;
2280                         sol = find_in_pos(sol, tab, ineq->el);
2281                         tab->row_sign[split] = isl_tab_row_neg;
2282                         row = split;
2283                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
2284                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2285                         *context_tab = add_lexmin_ineq(*context_tab, ineq->el);
2286                         *context_tab = check_samples(*context_tab, ineq->el, 0);
2287                         isl_vec_free(ineq);
2288                         if (!sol)
2289                                 goto error;
2290                         continue;
2291                 }
2292                 if (tab->rational)
2293                         break;
2294                 row = first_non_integer(tab, &flags);
2295                 if (row < 0)
2296                         break;
2297                 if (ISL_FL_ISSET(flags, I_PAR)) {
2298                         if (ISL_FL_ISSET(flags, I_VAR)) {
2299                                 tab = isl_tab_mark_empty(tab);
2300                                 break;
2301                         }
2302                         row = add_cut(tab, row);
2303                 } else if (ISL_FL_ISSET(flags, I_VAR)) {
2304                         struct isl_vec *div;
2305                         struct isl_vec *ineq;
2306                         int d;
2307                         if (isl_tab_extend_cons(*context_tab, 3) < 0)
2308                                 goto error;
2309                         div = get_row_split_div(tab, row);
2310                         if (!div)
2311                                 goto error;
2312                         d = get_div(tab, context_tab, div);
2313                         isl_vec_free(div);
2314                         if (d < 0)
2315                                 goto error;
2316                         ineq = ineq_for_div((*context_tab)->bset, d);
2317                         sol = no_sol_in_strict(sol, tab, ineq);
2318                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
2319                         *context_tab = add_lexmin_ineq(*context_tab, ineq->el);
2320                         *context_tab = check_samples(*context_tab, ineq->el, 0);
2321                         isl_vec_free(ineq);
2322                         if (!sol)
2323                                 goto error;
2324                         tab = set_row_cst_to_div(tab, row, d);
2325                 } else
2326                         row = add_parametric_cut(tab, row, context_tab);
2327                 if (row < 0)
2328                         goto error;
2329         }
2330 done:
2331         sol = sol->add(sol, tab);
2332         isl_tab_free(tab);
2333         return sol;
2334 error:
2335         isl_tab_free(tab);
2336         sol_free(sol);
2337         return NULL;
2338 }
2339
2340 /* Compute the lexicographic minimum of the set represented by the main
2341  * tableau "tab" within the context "sol->context_tab".
2342  *
2343  * As a preprocessing step, we first transfer all the purely parametric
2344  * equalities from the main tableau to the context tableau, i.e.,
2345  * parameters that have been pivoted to a row.
2346  * These equalities are ignored by the main algorithm, because the
2347  * corresponding rows may not be marked as being non-negative.
2348  * In parts of the context where the added equality does not hold,
2349  * the main tableau is marked as being empty.
2350  */
2351 static struct isl_sol *find_solutions_main(struct isl_sol *sol,
2352         struct isl_tab *tab)
2353 {
2354         int row;
2355
2356         for (row = tab->n_redundant; row < tab->n_row; ++row) {
2357                 int p;
2358                 struct isl_vec *eq;
2359
2360                 if (tab->row_var[row] < 0)
2361                         continue;
2362                 if (tab->row_var[row] >= tab->n_param &&
2363                     tab->row_var[row] < tab->n_var - tab->n_div)
2364                         continue;
2365                 if (tab->row_var[row] < tab->n_param)
2366                         p = tab->row_var[row];
2367                 else
2368                         p = tab->row_var[row]
2369                                 + tab->n_param - (tab->n_var - tab->n_div);
2370
2371                 if (isl_tab_extend_cons(sol->context_tab, 2) < 0)
2372                         goto error;
2373
2374                 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
2375                 get_row_parameter_line(tab, row, eq->el);
2376                 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
2377                 eq = isl_vec_normalize(eq);
2378
2379                 sol = no_sol_in_strict(sol, tab, eq);
2380
2381                 isl_seq_neg(eq->el, eq->el, eq->size);
2382                 sol = no_sol_in_strict(sol, tab, eq);
2383                 isl_seq_neg(eq->el, eq->el, eq->size);
2384
2385                 sol->context_tab = add_lexmin_eq(sol->context_tab, eq->el);
2386                 context_valid_sample_or_feasible(sol, eq->el, 1);
2387                 sol->context_tab = check_samples(sol->context_tab, eq->el, 1);
2388
2389                 isl_vec_free(eq);
2390
2391                 isl_tab_mark_redundant(tab, row);
2392
2393                 if (!sol->context_tab)
2394                         goto error;
2395                 if (sol->context_tab->empty)
2396                         break;
2397
2398                 row = tab->n_redundant - 1;
2399         }
2400
2401         return find_solutions(sol, tab);
2402 error:
2403         isl_tab_free(tab);
2404         sol_free(sol);
2405         return NULL;
2406 }
2407
2408 static struct isl_sol_map *sol_map_find_solutions(struct isl_sol_map *sol_map,
2409         struct isl_tab *tab)
2410 {
2411         return (struct isl_sol_map *)find_solutions_main(&sol_map->sol, tab);
2412 }
2413
2414 /* Check if integer division "div" of "dom" also occurs in "bmap".
2415  * If so, return its position within the divs.
2416  * If not, return -1.
2417  */
2418 static int find_context_div(struct isl_basic_map *bmap,
2419         struct isl_basic_set *dom, unsigned div)
2420 {
2421         int i;
2422         unsigned b_dim = isl_dim_total(bmap->dim);
2423         unsigned d_dim = isl_dim_total(dom->dim);
2424
2425         if (isl_int_is_zero(dom->div[div][0]))
2426                 return -1;
2427         if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
2428                 return -1;
2429
2430         for (i = 0; i < bmap->n_div; ++i) {
2431                 if (isl_int_is_zero(bmap->div[i][0]))
2432                         continue;
2433                 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
2434                                            (b_dim - d_dim) + bmap->n_div) != -1)
2435                         continue;
2436                 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
2437                         return i;
2438         }
2439         return -1;
2440 }
2441
2442 /* The correspondence between the variables in the main tableau,
2443  * the context tableau, and the input map and domain is as follows.
2444  * The first n_param and the last n_div variables of the main tableau
2445  * form the variables of the context tableau.
2446  * In the basic map, these n_param variables correspond to the
2447  * parameters and the input dimensions.  In the domain, they correspond
2448  * to the parameters and the set dimensions.
2449  * The n_div variables correspond to the integer divisions in the domain.
2450  * To ensure that everything lines up, we may need to copy some of the
2451  * integer divisions of the domain to the map.  These have to be placed
2452  * in the same order as those in the context and they have to be placed
2453  * after any other integer divisions that the map may have.
2454  * This function performs the required reordering.
2455  */
2456 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
2457         struct isl_basic_set *dom)
2458 {
2459         int i;
2460         int common = 0;
2461         int other;
2462
2463         for (i = 0; i < dom->n_div; ++i)
2464                 if (find_context_div(bmap, dom, i) != -1)
2465                         common++;
2466         other = bmap->n_div - common;
2467         if (dom->n_div - common > 0) {
2468                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
2469                                 dom->n_div - common, 0, 0);
2470                 if (!bmap)
2471                         return NULL;
2472         }
2473         for (i = 0; i < dom->n_div; ++i) {
2474                 int pos = find_context_div(bmap, dom, i);
2475                 if (pos < 0) {
2476                         pos = isl_basic_map_alloc_div(bmap);
2477                         if (pos < 0)
2478                                 goto error;
2479                         isl_int_set_si(bmap->div[pos][0], 0);
2480                 }
2481                 if (pos != other + i)
2482                         isl_basic_map_swap_div(bmap, pos, other + i);
2483         }
2484         return bmap;
2485 error:
2486         isl_basic_map_free(bmap);
2487         return NULL;
2488 }
2489
2490 /* Compute the lexicographic minimum (or maximum if "max" is set)
2491  * of "bmap" over the domain "dom" and return the result as a map.
2492  * If "empty" is not NULL, then *empty is assigned a set that
2493  * contains those parts of the domain where there is no solution.
2494  * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
2495  * then we compute the rational optimum.  Otherwise, we compute
2496  * the integral optimum.
2497  *
2498  * We perform some preprocessing.  As the PILP solver does not
2499  * handle implicit equalities very well, we first make sure all
2500  * the equalities are explicitly available.
2501  * We also make sure the divs in the domain are properly order,
2502  * because they will be added one by one in the given order
2503  * during the construction of the solution map.
2504  */
2505 struct isl_map *isl_tab_basic_map_partial_lexopt(
2506                 struct isl_basic_map *bmap, struct isl_basic_set *dom,
2507                 struct isl_set **empty, int max)
2508 {
2509         struct isl_tab *tab;
2510         struct isl_map *result = NULL;
2511         struct isl_sol_map *sol_map = NULL;
2512
2513         if (empty)
2514                 *empty = NULL;
2515         if (!bmap || !dom)
2516                 goto error;
2517
2518         isl_assert(bmap->ctx,
2519             isl_basic_map_compatible_domain(bmap, dom), goto error);
2520
2521         bmap = isl_basic_map_detect_equalities(bmap);
2522
2523         if (dom->n_div) {
2524                 dom = isl_basic_set_order_divs(dom);
2525                 bmap = align_context_divs(bmap, dom);
2526         }
2527         sol_map = sol_map_init(bmap, dom, !!empty, max);
2528         if (!sol_map)
2529                 goto error;
2530
2531         if (isl_basic_set_fast_is_empty(sol_map->sol.context_tab->bset))
2532                 /* nothing */;
2533         else if (isl_basic_map_fast_is_empty(bmap))
2534                 sol_map = add_empty(sol_map);
2535         else {
2536                 tab = tab_for_lexmin(bmap,
2537                                         sol_map->sol.context_tab->bset, 1, max);
2538                 tab = tab_detect_nonnegative_parameters(tab,
2539                                                 sol_map->sol.context_tab);
2540                 sol_map = sol_map_find_solutions(sol_map, tab);
2541                 if (!sol_map)
2542                         goto error;
2543         }
2544
2545         result = isl_map_copy(sol_map->map);
2546         if (empty)
2547                 *empty = isl_set_copy(sol_map->empty);
2548         sol_map_free(sol_map);
2549         isl_basic_map_free(bmap);
2550         return result;
2551 error:
2552         sol_map_free(sol_map);
2553         isl_basic_map_free(bmap);
2554         return NULL;
2555 }
2556
2557 struct isl_sol_for {
2558         struct isl_sol  sol;
2559         int             (*fn)(__isl_take isl_basic_set *dom,
2560                                 __isl_take isl_mat *map, void *user);
2561         void            *user;
2562         int             max;
2563 };
2564
2565 static void sol_for_free(struct isl_sol_for *sol_for)
2566 {
2567         isl_tab_free(sol_for->sol.context_tab);
2568         free(sol_for);
2569 }
2570
2571 static void sol_for_free_wrap(struct isl_sol *sol)
2572 {
2573         sol_for_free((struct isl_sol_for *)sol);
2574 }
2575
2576 /* Add the solution identified by the tableau and the context tableau.
2577  *
2578  * See documentation of sol_map_add for more details.
2579  *
2580  * Instead of constructing a basic map, this function calls a user
2581  * defined function with the current context as a basic set and
2582  * an affine matrix reprenting the relation between the input and output.
2583  * The number of rows in this matrix is equal to one plus the number
2584  * of output variables.  The number of columns is equal to one plus
2585  * the total dimension of the context, i.e., the number of parameters,
2586  * input variables and divs.  Since some of the columns in the matrix
2587  * may refer to the divs, the basic set is not simplified.
2588  * (Simplification may reorder or remove divs.)
2589  */
2590 static struct isl_sol_for *sol_for_add(struct isl_sol_for *sol,
2591         struct isl_tab *tab)
2592 {
2593         struct isl_tab *context_tab;
2594         struct isl_basic_set *bset;
2595         struct isl_mat *mat = NULL;
2596         unsigned n_out;
2597         unsigned off;
2598         int row, i;
2599
2600         if (!sol || !tab)
2601                 goto error;
2602
2603         if (tab->empty)
2604                 return sol;
2605
2606         off = 2 + tab->M;
2607         context_tab = sol->sol.context_tab;
2608
2609         n_out = tab->n_var - tab->n_param - tab->n_div;
2610         mat = isl_mat_alloc(tab->mat->ctx, 1 + n_out, 1 + tab->n_param + tab->n_div);
2611         if (!mat)
2612                 goto error;
2613
2614         isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
2615         isl_int_set_si(mat->row[0][0], 1);
2616         for (row = 0; row < n_out; ++row) {
2617                 int i = tab->n_param + row;
2618                 int r, j;
2619
2620                 isl_seq_clr(mat->row[1 + row], mat->n_col);
2621                 if (!tab->var[i].is_row)
2622                         continue;
2623
2624                 r = tab->var[i].index;
2625                 /* no unbounded */
2626                 if (tab->M)
2627                         isl_assert(mat->ctx, isl_int_eq(tab->mat->row[r][2],
2628                                                         tab->mat->row[r][0]),
2629                                     goto error);
2630                 isl_int_set(mat->row[1 + row][0], tab->mat->row[r][1]);
2631                 for (j = 0; j < tab->n_param; ++j) {
2632                         int col;
2633                         if (tab->var[j].is_row)
2634                                 continue;
2635                         col = tab->var[j].index;
2636                         isl_int_set(mat->row[1 + row][1 + j],
2637                                     tab->mat->row[r][off + col]);
2638                 }
2639                 for (j = 0; j < tab->n_div; ++j) {
2640                         int col;
2641                         if (tab->var[tab->n_var - tab->n_div+j].is_row)
2642                                 continue;
2643                         col = tab->var[tab->n_var - tab->n_div+j].index;
2644                         isl_int_set(mat->row[1 + row][1 + tab->n_param + j],
2645                                     tab->mat->row[r][off + col]);
2646                 }
2647                 if (!isl_int_is_one(tab->mat->row[r][0]))
2648                         isl_seq_scale_down(mat->row[1 + row], mat->row[1 + row],
2649                                             tab->mat->row[r][0], mat->n_col);
2650                 if (sol->max)
2651                         isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
2652                                     mat->n_col);
2653         }
2654
2655         bset = isl_basic_set_dup(context_tab->bset);
2656         bset = isl_basic_set_finalize(bset);
2657
2658         if (sol->fn(bset, isl_mat_copy(mat), sol->user) < 0)
2659                 goto error;
2660
2661         isl_mat_free(mat);
2662         return sol;
2663 error:
2664         isl_mat_free(mat);
2665         sol_free(&sol->sol);
2666         return NULL;
2667 }
2668
2669 static struct isl_sol *sol_for_add_wrap(struct isl_sol *sol,
2670         struct isl_tab *tab)
2671 {
2672         return (struct isl_sol *)sol_for_add((struct isl_sol_for *)sol, tab);
2673 }
2674
2675 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
2676         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2677                   void *user),
2678         void *user)
2679 {
2680         struct isl_sol_for *sol_for = NULL;
2681         struct isl_dim *dom_dim;
2682         struct isl_basic_set *dom = NULL;
2683         struct isl_tab *context_tab;
2684         int f;
2685
2686         sol_for = isl_calloc_type(bset->ctx, struct isl_sol_for);
2687         if (!sol_for)
2688                 goto error;
2689
2690         dom_dim = isl_dim_domain(isl_dim_copy(bmap->dim));
2691         dom = isl_basic_set_universe(dom_dim);
2692
2693         sol_for->fn = fn;
2694         sol_for->user = user;
2695         sol_for->max = max;
2696         sol_for->sol.add = &sol_for_add_wrap;
2697         sol_for->sol.free = &sol_for_free_wrap;
2698
2699         context_tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2700         context_tab = restore_lexmin(context_tab);
2701         sol_for->sol.context_tab = context_tab;
2702         f = context_is_feasible(&sol_for->sol);
2703         if (f < 0)
2704                 goto error;
2705
2706         isl_basic_set_free(dom);
2707         return sol_for;
2708 error:
2709         isl_basic_set_free(dom);
2710         sol_for_free(sol_for);
2711         return NULL;
2712 }
2713
2714 static struct isl_sol_for *sol_for_find_solutions(struct isl_sol_for *sol_for,
2715         struct isl_tab *tab)
2716 {
2717         return (struct isl_sol_for *)find_solutions_main(&sol_for->sol, tab);
2718 }
2719
2720 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
2721         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2722                   void *user),
2723         void *user)
2724 {
2725         struct isl_sol_for *sol_for = NULL;
2726
2727         bmap = isl_basic_map_copy(bmap);
2728         if (!bmap)
2729                 return -1;
2730
2731         bmap = isl_basic_map_detect_equalities(bmap);
2732         sol_for = sol_for_init(bmap, max, fn, user);
2733
2734         if (isl_basic_map_fast_is_empty(bmap))
2735                 /* nothing */;
2736         else {
2737                 struct isl_tab *tab;
2738                 tab = tab_for_lexmin(bmap,
2739                                         sol_for->sol.context_tab->bset, 1, max);
2740                 tab = tab_detect_nonnegative_parameters(tab,
2741                                                 sol_for->sol.context_tab);
2742                 sol_for = sol_for_find_solutions(sol_for, tab);
2743                 if (!sol_for)
2744                         goto error;
2745         }
2746
2747         sol_for_free(sol_for);
2748         isl_basic_map_free(bmap);
2749         return 0;
2750 error:
2751         sol_for_free(sol_for);
2752         isl_basic_map_free(bmap);
2753         return -1;
2754 }
2755
2756 int isl_basic_map_foreach_lexmin(__isl_keep isl_basic_map *bmap,
2757         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2758                   void *user),
2759         void *user)
2760 {
2761         return isl_basic_map_foreach_lexopt(bmap, 0, fn, user);
2762 }
2763
2764 int isl_basic_map_foreach_lexmax(__isl_keep isl_basic_map *bmap,
2765         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2766                   void *user),
2767         void *user)
2768 {
2769         return isl_basic_map_foreach_lexopt(bmap, 1, fn, user);
2770 }