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