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