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