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