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