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