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