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