isl_test.c: test_dim_max_1: extract out check_single_piece
[isl.git] / isl_tab_pip.c
blob46c218bd43350b870942db7c87214db9e2968728
1 /*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
3 * Copyright 2010 INRIA Saclay
4 * Copyright 2016-2017 Sven Verdoolaege
6 * Use of this software is governed by the MIT license
8 * Written by Sven Verdoolaege, K.U.Leuven, Departement
9 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
10 * and INRIA Saclay - Ile-de-France, Parc Club Orsay Universite,
11 * ZAC des vignes, 4 rue Jacques Monod, 91893 Orsay, France
14 #include <isl_ctx_private.h>
15 #include "isl_map_private.h"
16 #include <isl_seq.h>
17 #include "isl_tab.h"
18 #include "isl_sample.h"
19 #include <isl_mat_private.h>
20 #include <isl_vec_private.h>
21 #include <isl_aff_private.h>
22 #include <isl_constraint_private.h>
23 #include <isl_options_private.h>
24 #include <isl_config.h>
26 #include <bset_to_bmap.c>
29 * The implementation of parametric integer linear programming in this file
30 * was inspired by the paper "Parametric Integer Programming" and the
31 * report "Solving systems of affine (in)equalities" by Paul Feautrier
32 * (and others).
34 * The strategy used for obtaining a feasible solution is different
35 * from the one used in isl_tab.c. In particular, in isl_tab.c,
36 * upon finding a constraint that is not yet satisfied, we pivot
37 * in a row that increases the constant term of the row holding the
38 * constraint, making sure the sample solution remains feasible
39 * for all the constraints it already satisfied.
40 * Here, we always pivot in the row holding the constraint,
41 * choosing a column that induces the lexicographically smallest
42 * increment to the sample solution.
44 * By starting out from a sample value that is lexicographically
45 * smaller than any integer point in the problem space, the first
46 * feasible integer sample point we find will also be the lexicographically
47 * smallest. If all variables can be assumed to be non-negative,
48 * then the initial sample value may be chosen equal to zero.
49 * However, we will not make this assumption. Instead, we apply
50 * the "big parameter" trick. Any variable x is then not directly
51 * used in the tableau, but instead it is represented by another
52 * variable x' = M + x, where M is an arbitrarily large (positive)
53 * value. x' is therefore always non-negative, whatever the value of x.
54 * Taking as initial sample value x' = 0 corresponds to x = -M,
55 * which is always smaller than any possible value of x.
57 * The big parameter trick is used in the main tableau and
58 * also in the context tableau if isl_context_lex is used.
59 * In this case, each tableaus has its own big parameter.
60 * Before doing any real work, we check if all the parameters
61 * happen to be non-negative. If so, we drop the column corresponding
62 * to M from the initial context tableau.
63 * If isl_context_gbr is used, then the big parameter trick is only
64 * used in the main tableau.
67 struct isl_context;
68 struct isl_context_op {
69 /* detect nonnegative parameters in context and mark them in tab */
70 struct isl_tab *(*detect_nonnegative_parameters)(
71 struct isl_context *context, struct isl_tab *tab);
72 /* return temporary reference to basic set representation of context */
73 struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
74 /* return temporary reference to tableau representation of context */
75 struct isl_tab *(*peek_tab)(struct isl_context *context);
76 /* add equality; check is 1 if eq may not be valid;
77 * update is 1 if we may want to call ineq_sign on context later.
79 void (*add_eq)(struct isl_context *context, isl_int *eq,
80 int check, int update);
81 /* add inequality; check is 1 if ineq may not be valid;
82 * update is 1 if we may want to call ineq_sign on context later.
84 void (*add_ineq)(struct isl_context *context, isl_int *ineq,
85 int check, int update);
86 /* check sign of ineq based on previous information.
87 * strict is 1 if saturation should be treated as a positive sign.
89 enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
90 isl_int *ineq, int strict);
91 /* check if inequality maintains feasibility */
92 int (*test_ineq)(struct isl_context *context, isl_int *ineq);
93 /* return index of a div that corresponds to "div" */
94 int (*get_div)(struct isl_context *context, struct isl_tab *tab,
95 struct isl_vec *div);
96 /* insert div "div" to context at "pos" and return non-negativity */
97 isl_bool (*insert_div)(struct isl_context *context, int pos,
98 __isl_keep isl_vec *div);
99 int (*detect_equalities)(struct isl_context *context,
100 struct isl_tab *tab);
101 /* return row index of "best" split */
102 int (*best_split)(struct isl_context *context, struct isl_tab *tab);
103 /* check if context has already been determined to be empty */
104 int (*is_empty)(struct isl_context *context);
105 /* check if context is still usable */
106 int (*is_ok)(struct isl_context *context);
107 /* save a copy/snapshot of context */
108 void *(*save)(struct isl_context *context);
109 /* restore saved context */
110 void (*restore)(struct isl_context *context, void *);
111 /* discard saved context */
112 void (*discard)(void *);
113 /* invalidate context */
114 void (*invalidate)(struct isl_context *context);
115 /* free context */
116 __isl_null struct isl_context *(*free)(struct isl_context *context);
119 /* Shared parts of context representation.
121 * "n_unknown" is the number of final unknown integer divisions
122 * in the input domain.
124 struct isl_context {
125 struct isl_context_op *op;
126 int n_unknown;
129 struct isl_context_lex {
130 struct isl_context context;
131 struct isl_tab *tab;
134 /* A stack (linked list) of solutions of subtrees of the search space.
136 * "ma" describes the solution as a function of "dom".
137 * In particular, the domain space of "ma" is equal to the space of "dom".
139 * If "ma" is NULL, then there is no solution on "dom".
141 struct isl_partial_sol {
142 int level;
143 struct isl_basic_set *dom;
144 isl_multi_aff *ma;
146 struct isl_partial_sol *next;
149 struct isl_sol;
150 struct isl_sol_callback {
151 struct isl_tab_callback callback;
152 struct isl_sol *sol;
155 /* isl_sol is an interface for constructing a solution to
156 * a parametric integer linear programming problem.
157 * Every time the algorithm reaches a state where a solution
158 * can be read off from the tableau, the function "add" is called
159 * on the isl_sol passed to find_solutions_main. In a state where
160 * the tableau is empty, "add_empty" is called instead.
161 * "free" is called to free the implementation specific fields, if any.
163 * "error" is set if some error has occurred. This flag invalidates
164 * the remainder of the data structure.
165 * If "rational" is set, then a rational optimization is being performed.
166 * "level" is the current level in the tree with nodes for each
167 * split in the context.
168 * If "max" is set, then a maximization problem is being solved, rather than
169 * a minimization problem, which means that the variables in the
170 * tableau have value "M - x" rather than "M + x".
171 * "n_out" is the number of output dimensions in the input.
172 * "space" is the space in which the solution (and also the input) lives.
174 * The context tableau is owned by isl_sol and is updated incrementally.
176 * There are currently three implementations of this interface,
177 * isl_sol_map, which simply collects the solutions in an isl_map
178 * and (optionally) the parts of the context where there is no solution
179 * in an isl_set,
180 * isl_sol_pma, which collects an isl_pw_multi_aff instead, and
181 * isl_sol_for, which calls a user-defined function for each part of
182 * the solution.
184 struct isl_sol {
185 int error;
186 int rational;
187 int level;
188 int max;
189 int n_out;
190 isl_space *space;
191 struct isl_context *context;
192 struct isl_partial_sol *partial;
193 void (*add)(struct isl_sol *sol,
194 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma);
195 void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
196 void (*free)(struct isl_sol *sol);
197 struct isl_sol_callback dec_level;
200 static void sol_free(struct isl_sol *sol)
202 struct isl_partial_sol *partial, *next;
203 if (!sol)
204 return;
205 for (partial = sol->partial; partial; partial = next) {
206 next = partial->next;
207 isl_basic_set_free(partial->dom);
208 isl_multi_aff_free(partial->ma);
209 free(partial);
211 isl_space_free(sol->space);
212 if (sol->context)
213 sol->context->op->free(sol->context);
214 sol->free(sol);
215 free(sol);
218 /* Push a partial solution represented by a domain and function "ma"
219 * onto the stack of partial solutions.
220 * If "ma" is NULL, then "dom" represents a part of the domain
221 * with no solution.
223 static void sol_push_sol(struct isl_sol *sol,
224 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
226 struct isl_partial_sol *partial;
228 if (sol->error || !dom)
229 goto error;
231 partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
232 if (!partial)
233 goto error;
235 partial->level = sol->level;
236 partial->dom = dom;
237 partial->ma = ma;
238 partial->next = sol->partial;
240 sol->partial = partial;
242 return;
243 error:
244 isl_basic_set_free(dom);
245 isl_multi_aff_free(ma);
246 sol->error = 1;
249 /* Check that the final columns of "M", starting at "first", are zero.
251 static isl_stat check_final_columns_are_zero(__isl_keep isl_mat *M,
252 unsigned first)
254 int i;
255 unsigned rows, cols, n;
257 if (!M)
258 return isl_stat_error;
259 rows = isl_mat_rows(M);
260 cols = isl_mat_cols(M);
261 n = cols - first;
262 for (i = 0; i < rows; ++i)
263 if (isl_seq_first_non_zero(M->row[i] + first, n) != -1)
264 isl_die(isl_mat_get_ctx(M), isl_error_internal,
265 "final columns should be zero",
266 return isl_stat_error);
267 return isl_stat_ok;
270 /* Set the affine expressions in "ma" according to the rows in "M", which
271 * are defined over the local space "ls".
272 * The matrix "M" may have extra (zero) columns beyond the number
273 * of variables in "ls".
275 static __isl_give isl_multi_aff *set_from_affine_matrix(
276 __isl_take isl_multi_aff *ma, __isl_take isl_local_space *ls,
277 __isl_take isl_mat *M)
279 int i, dim;
280 isl_aff *aff;
282 if (!ma || !ls || !M)
283 goto error;
285 dim = isl_local_space_dim(ls, isl_dim_all);
286 if (check_final_columns_are_zero(M, 1 + dim) < 0)
287 goto error;
288 for (i = 1; i < M->n_row; ++i) {
289 aff = isl_aff_alloc(isl_local_space_copy(ls));
290 if (aff) {
291 isl_int_set(aff->v->el[0], M->row[0][0]);
292 isl_seq_cpy(aff->v->el + 1, M->row[i], 1 + dim);
294 aff = isl_aff_normalize(aff);
295 ma = isl_multi_aff_set_aff(ma, i - 1, aff);
297 isl_local_space_free(ls);
298 isl_mat_free(M);
300 return ma;
301 error:
302 isl_local_space_free(ls);
303 isl_mat_free(M);
304 isl_multi_aff_free(ma);
305 return NULL;
308 /* Push a partial solution represented by a domain and mapping M
309 * onto the stack of partial solutions.
311 * The affine matrix "M" maps the dimensions of the context
312 * to the output variables. Convert it into an isl_multi_aff and
313 * then call sol_push_sol.
315 * Note that the description of the initial context may have involved
316 * existentially quantified variables, in which case they also appear
317 * in "dom". These need to be removed before creating the affine
318 * expression because an affine expression cannot be defined in terms
319 * of existentially quantified variables without a known representation.
320 * Since newly added integer divisions are inserted before these
321 * existentially quantified variables, they are still in the final
322 * positions and the corresponding final columns of "M" are zero
323 * because align_context_divs adds the existentially quantified
324 * variables of the context to the main tableau without any constraints and
325 * any equality constraints that are added later on can only serve
326 * to eliminate these existentially quantified variables.
328 static void sol_push_sol_mat(struct isl_sol *sol,
329 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
331 isl_local_space *ls;
332 isl_multi_aff *ma;
333 int n_div, n_known;
335 n_div = isl_basic_set_dim(dom, isl_dim_div);
336 n_known = n_div - sol->context->n_unknown;
338 ma = isl_multi_aff_alloc(isl_space_copy(sol->space));
339 ls = isl_basic_set_get_local_space(dom);
340 ls = isl_local_space_drop_dims(ls, isl_dim_div,
341 n_known, n_div - n_known);
342 ma = set_from_affine_matrix(ma, ls, M);
344 if (!ma)
345 dom = isl_basic_set_free(dom);
346 sol_push_sol(sol, dom, ma);
349 /* Pop one partial solution from the partial solution stack and
350 * pass it on to sol->add or sol->add_empty.
352 static void sol_pop_one(struct isl_sol *sol)
354 struct isl_partial_sol *partial;
356 partial = sol->partial;
357 sol->partial = partial->next;
359 if (partial->ma)
360 sol->add(sol, partial->dom, partial->ma);
361 else
362 sol->add_empty(sol, partial->dom);
363 free(partial);
366 /* Return a fresh copy of the domain represented by the context tableau.
368 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
370 struct isl_basic_set *bset;
372 if (sol->error)
373 return NULL;
375 bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
376 bset = isl_basic_set_update_from_tab(bset,
377 sol->context->op->peek_tab(sol->context));
379 return bset;
382 /* Check whether two partial solutions have the same affine expressions.
384 static isl_bool same_solution(struct isl_partial_sol *s1,
385 struct isl_partial_sol *s2)
387 if (!s1->ma != !s2->ma)
388 return isl_bool_false;
389 if (!s1->ma)
390 return isl_bool_true;
392 return isl_multi_aff_plain_is_equal(s1->ma, s2->ma);
395 /* Swap the initial two partial solutions in "sol".
397 * That is, go from
399 * sol->partial = p1; p1->next = p2; p2->next = p3
401 * to
403 * sol->partial = p2; p2->next = p1; p1->next = p3
405 static void swap_initial(struct isl_sol *sol)
407 struct isl_partial_sol *partial;
409 partial = sol->partial;
410 sol->partial = partial->next;
411 partial->next = partial->next->next;
412 sol->partial->next = partial;
415 /* Combine the initial two partial solution of "sol" into
416 * a partial solution with the current context domain of "sol" and
417 * the function description of the second partial solution in the list.
418 * The level of the new partial solution is set to the current level.
420 * That is, the first two partial solutions (D1,M1) and (D2,M2) are
421 * replaced by (D,M2), where D is the domain of "sol", which is assumed
422 * to be the union of D1 and D2, while M1 is assumed to be equal to M2
423 * (at least on D1).
425 static isl_stat combine_initial_into_second(struct isl_sol *sol)
427 struct isl_partial_sol *partial;
428 isl_basic_set *bset;
430 partial = sol->partial;
432 bset = sol_domain(sol);
433 isl_basic_set_free(partial->next->dom);
434 partial->next->dom = bset;
435 partial->next->level = sol->level;
437 if (!bset)
438 return isl_stat_error;
440 sol->partial = partial->next;
441 isl_basic_set_free(partial->dom);
442 isl_multi_aff_free(partial->ma);
443 free(partial);
445 return isl_stat_ok;
448 /* Are "ma1" and "ma2" equal to each other on "dom"?
450 * Combine "ma1" and "ma2" with "dom" and check if the results are the same.
451 * "dom" may have existentially quantified variables. Eliminate them first
452 * as otherwise they would have to be eliminated twice, in a more complicated
453 * context.
455 static isl_bool equal_on_domain(__isl_keep isl_multi_aff *ma1,
456 __isl_keep isl_multi_aff *ma2, __isl_keep isl_basic_set *dom)
458 isl_set *set;
459 isl_pw_multi_aff *pma1, *pma2;
460 isl_bool equal;
462 set = isl_basic_set_compute_divs(isl_basic_set_copy(dom));
463 pma1 = isl_pw_multi_aff_alloc(isl_set_copy(set),
464 isl_multi_aff_copy(ma1));
465 pma2 = isl_pw_multi_aff_alloc(set, isl_multi_aff_copy(ma2));
466 equal = isl_pw_multi_aff_is_equal(pma1, pma2);
467 isl_pw_multi_aff_free(pma1);
468 isl_pw_multi_aff_free(pma2);
470 return equal;
473 /* The initial two partial solutions of "sol" are known to be at
474 * the same level.
475 * If they represent the same solution (on different parts of the domain),
476 * then combine them into a single solution at the current level.
477 * Otherwise, pop them both.
479 * Even if the two partial solution are not obviously the same,
480 * one may still be a simplification of the other over its own domain.
481 * Also check if the two sets of affine functions are equal when
482 * restricted to one of the domains. If so, combine the two
483 * using the set of affine functions on the other domain.
484 * That is, for two partial solutions (D1,M1) and (D2,M2),
485 * if M1 = M2 on D1, then the pair of partial solutions can
486 * be replaced by (D1+D2,M2) and similarly when M1 = M2 on D2.
488 static isl_stat combine_initial_if_equal(struct isl_sol *sol)
490 struct isl_partial_sol *partial;
491 isl_bool same;
493 partial = sol->partial;
495 same = same_solution(partial, partial->next);
496 if (same < 0)
497 return isl_stat_error;
498 if (same)
499 return combine_initial_into_second(sol);
500 if (partial->ma && partial->next->ma) {
501 same = equal_on_domain(partial->ma, partial->next->ma,
502 partial->dom);
503 if (same < 0)
504 return isl_stat_error;
505 if (same)
506 return combine_initial_into_second(sol);
507 same = equal_on_domain(partial->ma, partial->next->ma,
508 partial->next->dom);
509 if (same) {
510 swap_initial(sol);
511 return combine_initial_into_second(sol);
515 sol_pop_one(sol);
516 sol_pop_one(sol);
518 return isl_stat_ok;
521 /* Pop all solutions from the partial solution stack that were pushed onto
522 * the stack at levels that are deeper than the current level.
523 * If the two topmost elements on the stack have the same level
524 * and represent the same solution, then their domains are combined.
525 * This combined domain is the same as the current context domain
526 * as sol_pop is called each time we move back to a higher level.
527 * If the outer level (0) has been reached, then all partial solutions
528 * at the current level are also popped off.
530 static void sol_pop(struct isl_sol *sol)
532 struct isl_partial_sol *partial;
534 if (sol->error)
535 return;
537 partial = sol->partial;
538 if (!partial)
539 return;
541 if (partial->level == 0 && sol->level == 0) {
542 for (partial = sol->partial; partial; partial = sol->partial)
543 sol_pop_one(sol);
544 return;
547 if (partial->level <= sol->level)
548 return;
550 if (partial->next && partial->next->level == partial->level) {
551 if (combine_initial_if_equal(sol) < 0)
552 goto error;
553 } else
554 sol_pop_one(sol);
556 if (sol->level == 0) {
557 for (partial = sol->partial; partial; partial = sol->partial)
558 sol_pop_one(sol);
559 return;
562 if (0)
563 error: sol->error = 1;
566 static void sol_dec_level(struct isl_sol *sol)
568 if (sol->error)
569 return;
571 sol->level--;
573 sol_pop(sol);
576 static isl_stat sol_dec_level_wrap(struct isl_tab_callback *cb)
578 struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
580 sol_dec_level(callback->sol);
582 return callback->sol->error ? isl_stat_error : isl_stat_ok;
585 /* Move down to next level and push callback onto context tableau
586 * to decrease the level again when it gets rolled back across
587 * the current state. That is, dec_level will be called with
588 * the context tableau in the same state as it is when inc_level
589 * is called.
591 static void sol_inc_level(struct isl_sol *sol)
593 struct isl_tab *tab;
595 if (sol->error)
596 return;
598 sol->level++;
599 tab = sol->context->op->peek_tab(sol->context);
600 if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
601 sol->error = 1;
604 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
606 int i;
608 if (isl_int_is_one(m))
609 return;
611 for (i = 0; i < n_row; ++i)
612 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
615 /* Add the solution identified by the tableau and the context tableau.
617 * The layout of the variables is as follows.
618 * tab->n_var is equal to the total number of variables in the input
619 * map (including divs that were copied from the context)
620 * + the number of extra divs constructed
621 * Of these, the first tab->n_param and the last tab->n_div variables
622 * correspond to the variables in the context, i.e.,
623 * tab->n_param + tab->n_div = context_tab->n_var
624 * tab->n_param is equal to the number of parameters and input
625 * dimensions in the input map
626 * tab->n_div is equal to the number of divs in the context
628 * If there is no solution, then call add_empty with a basic set
629 * that corresponds to the context tableau. (If add_empty is NULL,
630 * then do nothing).
632 * If there is a solution, then first construct a matrix that maps
633 * all dimensions of the context to the output variables, i.e.,
634 * the output dimensions in the input map.
635 * The divs in the input map (if any) that do not correspond to any
636 * div in the context do not appear in the solution.
637 * The algorithm will make sure that they have an integer value,
638 * but these values themselves are of no interest.
639 * We have to be careful not to drop or rearrange any divs in the
640 * context because that would change the meaning of the matrix.
642 * To extract the value of the output variables, it should be noted
643 * that we always use a big parameter M in the main tableau and so
644 * the variable stored in this tableau is not an output variable x itself, but
645 * x' = M + x (in case of minimization)
646 * or
647 * x' = M - x (in case of maximization)
648 * If x' appears in a column, then its optimal value is zero,
649 * which means that the optimal value of x is an unbounded number
650 * (-M for minimization and M for maximization).
651 * We currently assume that the output dimensions in the original map
652 * are bounded, so this cannot occur.
653 * Similarly, when x' appears in a row, then the coefficient of M in that
654 * row is necessarily 1.
655 * If the row in the tableau represents
656 * d x' = c + d M + e(y)
657 * then, in case of minimization, the corresponding row in the matrix
658 * will be
659 * a c + a e(y)
660 * with a d = m, the (updated) common denominator of the matrix.
661 * In case of maximization, the row will be
662 * -a c - a e(y)
664 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
666 struct isl_basic_set *bset = NULL;
667 struct isl_mat *mat = NULL;
668 unsigned off;
669 int row;
670 isl_int m;
672 if (sol->error || !tab)
673 goto error;
675 if (tab->empty && !sol->add_empty)
676 return;
677 if (sol->context->op->is_empty(sol->context))
678 return;
680 bset = sol_domain(sol);
682 if (tab->empty) {
683 sol_push_sol(sol, bset, NULL);
684 return;
687 off = 2 + tab->M;
689 mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
690 1 + tab->n_param + tab->n_div);
691 if (!mat)
692 goto error;
694 isl_int_init(m);
696 isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
697 isl_int_set_si(mat->row[0][0], 1);
698 for (row = 0; row < sol->n_out; ++row) {
699 int i = tab->n_param + row;
700 int r, j;
702 isl_seq_clr(mat->row[1 + row], mat->n_col);
703 if (!tab->var[i].is_row) {
704 if (tab->M)
705 isl_die(mat->ctx, isl_error_invalid,
706 "unbounded optimum", goto error2);
707 continue;
710 r = tab->var[i].index;
711 if (tab->M &&
712 isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
713 isl_die(mat->ctx, isl_error_invalid,
714 "unbounded optimum", goto error2);
715 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
716 isl_int_divexact(m, tab->mat->row[r][0], m);
717 scale_rows(mat, m, 1 + row);
718 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
719 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
720 for (j = 0; j < tab->n_param; ++j) {
721 int col;
722 if (tab->var[j].is_row)
723 continue;
724 col = tab->var[j].index;
725 isl_int_mul(mat->row[1 + row][1 + j], m,
726 tab->mat->row[r][off + col]);
728 for (j = 0; j < tab->n_div; ++j) {
729 int col;
730 if (tab->var[tab->n_var - tab->n_div+j].is_row)
731 continue;
732 col = tab->var[tab->n_var - tab->n_div+j].index;
733 isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
734 tab->mat->row[r][off + col]);
736 if (sol->max)
737 isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
738 mat->n_col);
741 isl_int_clear(m);
743 sol_push_sol_mat(sol, bset, mat);
744 return;
745 error2:
746 isl_int_clear(m);
747 error:
748 isl_basic_set_free(bset);
749 isl_mat_free(mat);
750 sol->error = 1;
753 struct isl_sol_map {
754 struct isl_sol sol;
755 struct isl_map *map;
756 struct isl_set *empty;
759 static void sol_map_free(struct isl_sol *sol)
761 struct isl_sol_map *sol_map = (struct isl_sol_map *) sol;
762 isl_map_free(sol_map->map);
763 isl_set_free(sol_map->empty);
766 /* This function is called for parts of the context where there is
767 * no solution, with "bset" corresponding to the context tableau.
768 * Simply add the basic set to the set "empty".
770 static void sol_map_add_empty(struct isl_sol_map *sol,
771 struct isl_basic_set *bset)
773 if (!bset || !sol->empty)
774 goto error;
776 sol->empty = isl_set_grow(sol->empty, 1);
777 bset = isl_basic_set_simplify(bset);
778 bset = isl_basic_set_finalize(bset);
779 sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
780 if (!sol->empty)
781 goto error;
782 isl_basic_set_free(bset);
783 return;
784 error:
785 isl_basic_set_free(bset);
786 sol->sol.error = 1;
789 static void sol_map_add_empty_wrap(struct isl_sol *sol,
790 struct isl_basic_set *bset)
792 sol_map_add_empty((struct isl_sol_map *)sol, bset);
795 /* Given a basic set "dom" that represents the context and a tuple of
796 * affine expressions "ma" defined over this domain, construct a basic map
797 * that expresses this function on the domain.
799 static void sol_map_add(struct isl_sol_map *sol,
800 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
802 isl_basic_map *bmap;
804 if (sol->sol.error || !dom || !ma)
805 goto error;
807 bmap = isl_basic_map_from_multi_aff2(ma, sol->sol.rational);
808 bmap = isl_basic_map_intersect_domain(bmap, dom);
809 sol->map = isl_map_grow(sol->map, 1);
810 sol->map = isl_map_add_basic_map(sol->map, bmap);
811 if (!sol->map)
812 sol->sol.error = 1;
813 return;
814 error:
815 isl_basic_set_free(dom);
816 isl_multi_aff_free(ma);
817 sol->sol.error = 1;
820 static void sol_map_add_wrap(struct isl_sol *sol,
821 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
823 sol_map_add((struct isl_sol_map *)sol, dom, ma);
827 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
828 * i.e., the constant term and the coefficients of all variables that
829 * appear in the context tableau.
830 * Note that the coefficient of the big parameter M is NOT copied.
831 * The context tableau may not have a big parameter and even when it
832 * does, it is a different big parameter.
834 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
836 int i;
837 unsigned off = 2 + tab->M;
839 isl_int_set(line[0], tab->mat->row[row][1]);
840 for (i = 0; i < tab->n_param; ++i) {
841 if (tab->var[i].is_row)
842 isl_int_set_si(line[1 + i], 0);
843 else {
844 int col = tab->var[i].index;
845 isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
848 for (i = 0; i < tab->n_div; ++i) {
849 if (tab->var[tab->n_var - tab->n_div + i].is_row)
850 isl_int_set_si(line[1 + tab->n_param + i], 0);
851 else {
852 int col = tab->var[tab->n_var - tab->n_div + i].index;
853 isl_int_set(line[1 + tab->n_param + i],
854 tab->mat->row[row][off + col]);
859 /* Check if rows "row1" and "row2" have identical "parametric constants",
860 * as explained above.
861 * In this case, we also insist that the coefficients of the big parameter
862 * be the same as the values of the constants will only be the same
863 * if these coefficients are also the same.
865 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
867 int i;
868 unsigned off = 2 + tab->M;
870 if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
871 return 0;
873 if (tab->M && isl_int_ne(tab->mat->row[row1][2],
874 tab->mat->row[row2][2]))
875 return 0;
877 for (i = 0; i < tab->n_param + tab->n_div; ++i) {
878 int pos = i < tab->n_param ? i :
879 tab->n_var - tab->n_div + i - tab->n_param;
880 int col;
882 if (tab->var[pos].is_row)
883 continue;
884 col = tab->var[pos].index;
885 if (isl_int_ne(tab->mat->row[row1][off + col],
886 tab->mat->row[row2][off + col]))
887 return 0;
889 return 1;
892 /* Return an inequality that expresses that the "parametric constant"
893 * should be non-negative.
894 * This function is only called when the coefficient of the big parameter
895 * is equal to zero.
897 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
899 struct isl_vec *ineq;
901 ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
902 if (!ineq)
903 return NULL;
905 get_row_parameter_line(tab, row, ineq->el);
906 if (ineq)
907 ineq = isl_vec_normalize(ineq);
909 return ineq;
912 /* Normalize a div expression of the form
914 * [(g*f(x) + c)/(g * m)]
916 * with c the constant term and f(x) the remaining coefficients, to
918 * [(f(x) + [c/g])/m]
920 static void normalize_div(__isl_keep isl_vec *div)
922 isl_ctx *ctx = isl_vec_get_ctx(div);
923 int len = div->size - 2;
925 isl_seq_gcd(div->el + 2, len, &ctx->normalize_gcd);
926 isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, div->el[0]);
928 if (isl_int_is_one(ctx->normalize_gcd))
929 return;
931 isl_int_divexact(div->el[0], div->el[0], ctx->normalize_gcd);
932 isl_int_fdiv_q(div->el[1], div->el[1], ctx->normalize_gcd);
933 isl_seq_scale_down(div->el + 2, div->el + 2, ctx->normalize_gcd, len);
936 /* Return an integer division for use in a parametric cut based
937 * on the given row.
938 * In particular, let the parametric constant of the row be
940 * \sum_i a_i y_i
942 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
943 * The div returned is equal to
945 * floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
947 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
949 struct isl_vec *div;
951 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
952 if (!div)
953 return NULL;
955 isl_int_set(div->el[0], tab->mat->row[row][0]);
956 get_row_parameter_line(tab, row, div->el + 1);
957 isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
958 normalize_div(div);
959 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
961 return div;
964 /* Return an integer division for use in transferring an integrality constraint
965 * to the context.
966 * In particular, let the parametric constant of the row be
968 * \sum_i a_i y_i
970 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
971 * The the returned div is equal to
973 * floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
975 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
977 struct isl_vec *div;
979 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
980 if (!div)
981 return NULL;
983 isl_int_set(div->el[0], tab->mat->row[row][0]);
984 get_row_parameter_line(tab, row, div->el + 1);
985 normalize_div(div);
986 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
988 return div;
991 /* Construct and return an inequality that expresses an upper bound
992 * on the given div.
993 * In particular, if the div is given by
995 * d = floor(e/m)
997 * then the inequality expresses
999 * m d <= e
1001 static __isl_give isl_vec *ineq_for_div(__isl_keep isl_basic_set *bset,
1002 unsigned div)
1004 unsigned total;
1005 unsigned div_pos;
1006 struct isl_vec *ineq;
1008 if (!bset)
1009 return NULL;
1011 total = isl_basic_set_total_dim(bset);
1012 div_pos = 1 + total - bset->n_div + div;
1014 ineq = isl_vec_alloc(bset->ctx, 1 + total);
1015 if (!ineq)
1016 return NULL;
1018 isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
1019 isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
1020 return ineq;
1023 /* Given a row in the tableau and a div that was created
1024 * using get_row_split_div and that has been constrained to equality, i.e.,
1026 * d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
1028 * replace the expression "\sum_i {a_i} y_i" in the row by d,
1029 * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
1030 * The coefficients of the non-parameters in the tableau have been
1031 * verified to be integral. We can therefore simply replace coefficient b
1032 * by floor(b). For the coefficients of the parameters we have
1033 * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
1034 * floor(b) = b.
1036 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
1038 isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
1039 tab->mat->row[row][0], 1 + tab->M + tab->n_col);
1041 isl_int_set_si(tab->mat->row[row][0], 1);
1043 if (tab->var[tab->n_var - tab->n_div + div].is_row) {
1044 int drow = tab->var[tab->n_var - tab->n_div + div].index;
1046 isl_assert(tab->mat->ctx,
1047 isl_int_is_one(tab->mat->row[drow][0]), goto error);
1048 isl_seq_combine(tab->mat->row[row] + 1,
1049 tab->mat->ctx->one, tab->mat->row[row] + 1,
1050 tab->mat->ctx->one, tab->mat->row[drow] + 1,
1051 1 + tab->M + tab->n_col);
1052 } else {
1053 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
1055 isl_int_add_ui(tab->mat->row[row][2 + tab->M + dcol],
1056 tab->mat->row[row][2 + tab->M + dcol], 1);
1059 return tab;
1060 error:
1061 isl_tab_free(tab);
1062 return NULL;
1065 /* Check if the (parametric) constant of the given row is obviously
1066 * negative, meaning that we don't need to consult the context tableau.
1067 * If there is a big parameter and its coefficient is non-zero,
1068 * then this coefficient determines the outcome.
1069 * Otherwise, we check whether the constant is negative and
1070 * all non-zero coefficients of parameters are negative and
1071 * belong to non-negative parameters.
1073 static int is_obviously_neg(struct isl_tab *tab, int row)
1075 int i;
1076 int col;
1077 unsigned off = 2 + tab->M;
1079 if (tab->M) {
1080 if (isl_int_is_pos(tab->mat->row[row][2]))
1081 return 0;
1082 if (isl_int_is_neg(tab->mat->row[row][2]))
1083 return 1;
1086 if (isl_int_is_nonneg(tab->mat->row[row][1]))
1087 return 0;
1088 for (i = 0; i < tab->n_param; ++i) {
1089 /* Eliminated parameter */
1090 if (tab->var[i].is_row)
1091 continue;
1092 col = tab->var[i].index;
1093 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1094 continue;
1095 if (!tab->var[i].is_nonneg)
1096 return 0;
1097 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1098 return 0;
1100 for (i = 0; i < tab->n_div; ++i) {
1101 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1102 continue;
1103 col = tab->var[tab->n_var - tab->n_div + i].index;
1104 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1105 continue;
1106 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1107 return 0;
1108 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1109 return 0;
1111 return 1;
1114 /* Check if the (parametric) constant of the given row is obviously
1115 * non-negative, meaning that we don't need to consult the context tableau.
1116 * If there is a big parameter and its coefficient is non-zero,
1117 * then this coefficient determines the outcome.
1118 * Otherwise, we check whether the constant is non-negative and
1119 * all non-zero coefficients of parameters are positive and
1120 * belong to non-negative parameters.
1122 static int is_obviously_nonneg(struct isl_tab *tab, int row)
1124 int i;
1125 int col;
1126 unsigned off = 2 + tab->M;
1128 if (tab->M) {
1129 if (isl_int_is_pos(tab->mat->row[row][2]))
1130 return 1;
1131 if (isl_int_is_neg(tab->mat->row[row][2]))
1132 return 0;
1135 if (isl_int_is_neg(tab->mat->row[row][1]))
1136 return 0;
1137 for (i = 0; i < tab->n_param; ++i) {
1138 /* Eliminated parameter */
1139 if (tab->var[i].is_row)
1140 continue;
1141 col = tab->var[i].index;
1142 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1143 continue;
1144 if (!tab->var[i].is_nonneg)
1145 return 0;
1146 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1147 return 0;
1149 for (i = 0; i < tab->n_div; ++i) {
1150 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1151 continue;
1152 col = tab->var[tab->n_var - tab->n_div + i].index;
1153 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1154 continue;
1155 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1156 return 0;
1157 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1158 return 0;
1160 return 1;
1163 /* Given a row r and two columns, return the column that would
1164 * lead to the lexicographically smallest increment in the sample
1165 * solution when leaving the basis in favor of the row.
1166 * Pivoting with column c will increment the sample value by a non-negative
1167 * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
1168 * corresponding to the non-parametric variables.
1169 * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
1170 * with all other entries in this virtual row equal to zero.
1171 * If variable v appears in a row, then a_{v,c} is the element in column c
1172 * of that row.
1174 * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
1175 * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
1176 * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
1177 * increment. Otherwise, it's c2.
1179 static int lexmin_col_pair(struct isl_tab *tab,
1180 int row, int col1, int col2, isl_int tmp)
1182 int i;
1183 isl_int *tr;
1185 tr = tab->mat->row[row] + 2 + tab->M;
1187 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1188 int s1, s2;
1189 isl_int *r;
1191 if (!tab->var[i].is_row) {
1192 if (tab->var[i].index == col1)
1193 return col2;
1194 if (tab->var[i].index == col2)
1195 return col1;
1196 continue;
1199 if (tab->var[i].index == row)
1200 continue;
1202 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1203 s1 = isl_int_sgn(r[col1]);
1204 s2 = isl_int_sgn(r[col2]);
1205 if (s1 == 0 && s2 == 0)
1206 continue;
1207 if (s1 < s2)
1208 return col1;
1209 if (s2 < s1)
1210 return col2;
1212 isl_int_mul(tmp, r[col2], tr[col1]);
1213 isl_int_submul(tmp, r[col1], tr[col2]);
1214 if (isl_int_is_pos(tmp))
1215 return col1;
1216 if (isl_int_is_neg(tmp))
1217 return col2;
1219 return -1;
1222 /* Does the index into the tab->var or tab->con array "index"
1223 * correspond to a variable in the context tableau?
1224 * In particular, it needs to be an index into the tab->var array and
1225 * it needs to refer to either one of the first tab->n_param variables or
1226 * one of the last tab->n_div variables.
1228 static int is_parameter_var(struct isl_tab *tab, int index)
1230 if (index < 0)
1231 return 0;
1232 if (index < tab->n_param)
1233 return 1;
1234 if (index >= tab->n_var - tab->n_div)
1235 return 1;
1236 return 0;
1239 /* Does column "col" of "tab" refer to a variable in the context tableau?
1241 static int col_is_parameter_var(struct isl_tab *tab, int col)
1243 return is_parameter_var(tab, tab->col_var[col]);
1246 /* Does row "row" of "tab" refer to a variable in the context tableau?
1248 static int row_is_parameter_var(struct isl_tab *tab, int row)
1250 return is_parameter_var(tab, tab->row_var[row]);
1253 /* Given a row in the tableau, find and return the column that would
1254 * result in the lexicographically smallest, but positive, increment
1255 * in the sample point.
1256 * If there is no such column, then return tab->n_col.
1257 * If anything goes wrong, return -1.
1259 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1261 int j;
1262 int col = tab->n_col;
1263 isl_int *tr;
1264 isl_int tmp;
1266 tr = tab->mat->row[row] + 2 + tab->M;
1268 isl_int_init(tmp);
1270 for (j = tab->n_dead; j < tab->n_col; ++j) {
1271 if (col_is_parameter_var(tab, j))
1272 continue;
1274 if (!isl_int_is_pos(tr[j]))
1275 continue;
1277 if (col == tab->n_col)
1278 col = j;
1279 else
1280 col = lexmin_col_pair(tab, row, col, j, tmp);
1281 isl_assert(tab->mat->ctx, col >= 0, goto error);
1284 isl_int_clear(tmp);
1285 return col;
1286 error:
1287 isl_int_clear(tmp);
1288 return -1;
1291 /* Return the first known violated constraint, i.e., a non-negative
1292 * constraint that currently has an either obviously negative value
1293 * or a previously determined to be negative value.
1295 * If any constraint has a negative coefficient for the big parameter,
1296 * if any, then we return one of these first.
1298 static int first_neg(struct isl_tab *tab)
1300 int row;
1302 if (tab->M)
1303 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1304 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1305 continue;
1306 if (!isl_int_is_neg(tab->mat->row[row][2]))
1307 continue;
1308 if (tab->row_sign)
1309 tab->row_sign[row] = isl_tab_row_neg;
1310 return row;
1312 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1313 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1314 continue;
1315 if (tab->row_sign) {
1316 if (tab->row_sign[row] == 0 &&
1317 is_obviously_neg(tab, row))
1318 tab->row_sign[row] = isl_tab_row_neg;
1319 if (tab->row_sign[row] != isl_tab_row_neg)
1320 continue;
1321 } else if (!is_obviously_neg(tab, row))
1322 continue;
1323 return row;
1325 return -1;
1328 /* Check whether the invariant that all columns are lexico-positive
1329 * is satisfied. This function is not called from the current code
1330 * but is useful during debugging.
1332 static void check_lexpos(struct isl_tab *tab) __attribute__ ((unused));
1333 static void check_lexpos(struct isl_tab *tab)
1335 unsigned off = 2 + tab->M;
1336 int col;
1337 int var;
1338 int row;
1340 for (col = tab->n_dead; col < tab->n_col; ++col) {
1341 if (col_is_parameter_var(tab, col))
1342 continue;
1343 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1344 if (!tab->var[var].is_row) {
1345 if (tab->var[var].index == col)
1346 break;
1347 else
1348 continue;
1350 row = tab->var[var].index;
1351 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1352 continue;
1353 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1354 break;
1355 fprintf(stderr, "lexneg column %d (row %d)\n",
1356 col, row);
1358 if (var >= tab->n_var - tab->n_div)
1359 fprintf(stderr, "zero column %d\n", col);
1363 /* Report to the caller that the given constraint is part of an encountered
1364 * conflict.
1366 static int report_conflicting_constraint(struct isl_tab *tab, int con)
1368 return tab->conflict(con, tab->conflict_user);
1371 /* Given a conflicting row in the tableau, report all constraints
1372 * involved in the row to the caller. That is, the row itself
1373 * (if it represents a constraint) and all constraint columns with
1374 * non-zero (and therefore negative) coefficients.
1376 static int report_conflict(struct isl_tab *tab, int row)
1378 int j;
1379 isl_int *tr;
1381 if (!tab->conflict)
1382 return 0;
1384 if (tab->row_var[row] < 0 &&
1385 report_conflicting_constraint(tab, ~tab->row_var[row]) < 0)
1386 return -1;
1388 tr = tab->mat->row[row] + 2 + tab->M;
1390 for (j = tab->n_dead; j < tab->n_col; ++j) {
1391 if (col_is_parameter_var(tab, j))
1392 continue;
1394 if (!isl_int_is_neg(tr[j]))
1395 continue;
1397 if (tab->col_var[j] < 0 &&
1398 report_conflicting_constraint(tab, ~tab->col_var[j]) < 0)
1399 return -1;
1402 return 0;
1405 /* Resolve all known or obviously violated constraints through pivoting.
1406 * In particular, as long as we can find any violated constraint, we
1407 * look for a pivoting column that would result in the lexicographically
1408 * smallest increment in the sample point. If there is no such column
1409 * then the tableau is infeasible.
1411 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1412 static int restore_lexmin(struct isl_tab *tab)
1414 int row, col;
1416 if (!tab)
1417 return -1;
1418 if (tab->empty)
1419 return 0;
1420 while ((row = first_neg(tab)) != -1) {
1421 col = lexmin_pivot_col(tab, row);
1422 if (col >= tab->n_col) {
1423 if (report_conflict(tab, row) < 0)
1424 return -1;
1425 if (isl_tab_mark_empty(tab) < 0)
1426 return -1;
1427 return 0;
1429 if (col < 0)
1430 return -1;
1431 if (isl_tab_pivot(tab, row, col) < 0)
1432 return -1;
1434 return 0;
1437 /* Given a row that represents an equality, look for an appropriate
1438 * pivoting column.
1439 * In particular, if there are any non-zero coefficients among
1440 * the non-parameter variables, then we take the last of these
1441 * variables. Eliminating this variable in terms of the other
1442 * variables and/or parameters does not influence the property
1443 * that all column in the initial tableau are lexicographically
1444 * positive. The row corresponding to the eliminated variable
1445 * will only have non-zero entries below the diagonal of the
1446 * initial tableau. That is, we transform
1448 * I I
1449 * 1 into a
1450 * I I
1452 * If there is no such non-parameter variable, then we are dealing with
1453 * pure parameter equality and we pick any parameter with coefficient 1 or -1
1454 * for elimination. This will ensure that the eliminated parameter
1455 * always has an integer value whenever all the other parameters are integral.
1456 * If there is no such parameter then we return -1.
1458 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1460 unsigned off = 2 + tab->M;
1461 int i;
1463 for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1464 int col;
1465 if (tab->var[i].is_row)
1466 continue;
1467 col = tab->var[i].index;
1468 if (col <= tab->n_dead)
1469 continue;
1470 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1471 return col;
1473 for (i = tab->n_dead; i < tab->n_col; ++i) {
1474 if (isl_int_is_one(tab->mat->row[row][off + i]))
1475 return i;
1476 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1477 return i;
1479 return -1;
1482 /* Add an equality that is known to be valid to the tableau.
1483 * We first check if we can eliminate a variable or a parameter.
1484 * If not, we add the equality as two inequalities.
1485 * In this case, the equality was a pure parameter equality and there
1486 * is no need to resolve any constraint violations.
1488 * This function assumes that at least two more rows and at least
1489 * two more elements in the constraint array are available in the tableau.
1491 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1493 int i;
1494 int r;
1496 if (!tab)
1497 return NULL;
1498 r = isl_tab_add_row(tab, eq);
1499 if (r < 0)
1500 goto error;
1502 r = tab->con[r].index;
1503 i = last_var_col_or_int_par_col(tab, r);
1504 if (i < 0) {
1505 tab->con[r].is_nonneg = 1;
1506 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1507 goto error;
1508 isl_seq_neg(eq, eq, 1 + tab->n_var);
1509 r = isl_tab_add_row(tab, eq);
1510 if (r < 0)
1511 goto error;
1512 tab->con[r].is_nonneg = 1;
1513 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1514 goto error;
1515 } else {
1516 if (isl_tab_pivot(tab, r, i) < 0)
1517 goto error;
1518 if (isl_tab_kill_col(tab, i) < 0)
1519 goto error;
1520 tab->n_eq++;
1523 return tab;
1524 error:
1525 isl_tab_free(tab);
1526 return NULL;
1529 /* Check if the given row is a pure constant.
1531 static int is_constant(struct isl_tab *tab, int row)
1533 unsigned off = 2 + tab->M;
1535 return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1536 tab->n_col - tab->n_dead) == -1;
1539 /* Add an equality that may or may not be valid to the tableau.
1540 * If the resulting row is a pure constant, then it must be zero.
1541 * Otherwise, the resulting tableau is empty.
1543 * If the row is not a pure constant, then we add two inequalities,
1544 * each time checking that they can be satisfied.
1545 * In the end we try to use one of the two constraints to eliminate
1546 * a column.
1548 * This function assumes that at least two more rows and at least
1549 * two more elements in the constraint array are available in the tableau.
1551 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1552 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1554 int r1, r2;
1555 int row;
1556 struct isl_tab_undo *snap;
1558 if (!tab)
1559 return -1;
1560 snap = isl_tab_snap(tab);
1561 r1 = isl_tab_add_row(tab, eq);
1562 if (r1 < 0)
1563 return -1;
1564 tab->con[r1].is_nonneg = 1;
1565 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1566 return -1;
1568 row = tab->con[r1].index;
1569 if (is_constant(tab, row)) {
1570 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1571 (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1572 if (isl_tab_mark_empty(tab) < 0)
1573 return -1;
1574 return 0;
1576 if (isl_tab_rollback(tab, snap) < 0)
1577 return -1;
1578 return 0;
1581 if (restore_lexmin(tab) < 0)
1582 return -1;
1583 if (tab->empty)
1584 return 0;
1586 isl_seq_neg(eq, eq, 1 + tab->n_var);
1588 r2 = isl_tab_add_row(tab, eq);
1589 if (r2 < 0)
1590 return -1;
1591 tab->con[r2].is_nonneg = 1;
1592 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1593 return -1;
1595 if (restore_lexmin(tab) < 0)
1596 return -1;
1597 if (tab->empty)
1598 return 0;
1600 if (!tab->con[r1].is_row) {
1601 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1602 return -1;
1603 } else if (!tab->con[r2].is_row) {
1604 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1605 return -1;
1608 if (tab->bmap) {
1609 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1610 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1611 return -1;
1612 isl_seq_neg(eq, eq, 1 + tab->n_var);
1613 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1614 isl_seq_neg(eq, eq, 1 + tab->n_var);
1615 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1616 return -1;
1617 if (!tab->bmap)
1618 return -1;
1621 return 0;
1624 /* Add an inequality to the tableau, resolving violations using
1625 * restore_lexmin.
1627 * This function assumes that at least one more row and at least
1628 * one more element in the constraint array are available in the tableau.
1630 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1632 int r;
1634 if (!tab)
1635 return NULL;
1636 if (tab->bmap) {
1637 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1638 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1639 goto error;
1640 if (!tab->bmap)
1641 goto error;
1643 r = isl_tab_add_row(tab, ineq);
1644 if (r < 0)
1645 goto error;
1646 tab->con[r].is_nonneg = 1;
1647 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1648 goto error;
1649 if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1650 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1651 goto error;
1652 return tab;
1655 if (restore_lexmin(tab) < 0)
1656 goto error;
1657 if (!tab->empty && tab->con[r].is_row &&
1658 isl_tab_row_is_redundant(tab, tab->con[r].index))
1659 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1660 goto error;
1661 return tab;
1662 error:
1663 isl_tab_free(tab);
1664 return NULL;
1667 /* Check if the coefficients of the parameters are all integral.
1669 static int integer_parameter(struct isl_tab *tab, int row)
1671 int i;
1672 int col;
1673 unsigned off = 2 + tab->M;
1675 for (i = 0; i < tab->n_param; ++i) {
1676 /* Eliminated parameter */
1677 if (tab->var[i].is_row)
1678 continue;
1679 col = tab->var[i].index;
1680 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1681 tab->mat->row[row][0]))
1682 return 0;
1684 for (i = 0; i < tab->n_div; ++i) {
1685 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1686 continue;
1687 col = tab->var[tab->n_var - tab->n_div + i].index;
1688 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1689 tab->mat->row[row][0]))
1690 return 0;
1692 return 1;
1695 /* Check if the coefficients of the non-parameter variables are all integral.
1697 static int integer_variable(struct isl_tab *tab, int row)
1699 int i;
1700 unsigned off = 2 + tab->M;
1702 for (i = tab->n_dead; i < tab->n_col; ++i) {
1703 if (col_is_parameter_var(tab, i))
1704 continue;
1705 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1706 tab->mat->row[row][0]))
1707 return 0;
1709 return 1;
1712 /* Check if the constant term is integral.
1714 static int integer_constant(struct isl_tab *tab, int row)
1716 return isl_int_is_divisible_by(tab->mat->row[row][1],
1717 tab->mat->row[row][0]);
1720 #define I_CST 1 << 0
1721 #define I_PAR 1 << 1
1722 #define I_VAR 1 << 2
1724 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1725 * that is non-integer and therefore requires a cut and return
1726 * the index of the variable.
1727 * For parametric tableaus, there are three parts in a row,
1728 * the constant, the coefficients of the parameters and the rest.
1729 * For each part, we check whether the coefficients in that part
1730 * are all integral and if so, set the corresponding flag in *f.
1731 * If the constant and the parameter part are integral, then the
1732 * current sample value is integral and no cut is required
1733 * (irrespective of whether the variable part is integral).
1735 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1737 var = var < 0 ? tab->n_param : var + 1;
1739 for (; var < tab->n_var - tab->n_div; ++var) {
1740 int flags = 0;
1741 int row;
1742 if (!tab->var[var].is_row)
1743 continue;
1744 row = tab->var[var].index;
1745 if (integer_constant(tab, row))
1746 ISL_FL_SET(flags, I_CST);
1747 if (integer_parameter(tab, row))
1748 ISL_FL_SET(flags, I_PAR);
1749 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1750 continue;
1751 if (integer_variable(tab, row))
1752 ISL_FL_SET(flags, I_VAR);
1753 *f = flags;
1754 return var;
1756 return -1;
1759 /* Check for first (non-parameter) variable that is non-integer and
1760 * therefore requires a cut and return the corresponding row.
1761 * For parametric tableaus, there are three parts in a row,
1762 * the constant, the coefficients of the parameters and the rest.
1763 * For each part, we check whether the coefficients in that part
1764 * are all integral and if so, set the corresponding flag in *f.
1765 * If the constant and the parameter part are integral, then the
1766 * current sample value is integral and no cut is required
1767 * (irrespective of whether the variable part is integral).
1769 static int first_non_integer_row(struct isl_tab *tab, int *f)
1771 int var = next_non_integer_var(tab, -1, f);
1773 return var < 0 ? -1 : tab->var[var].index;
1776 /* Add a (non-parametric) cut to cut away the non-integral sample
1777 * value of the given row.
1779 * If the row is given by
1781 * m r = f + \sum_i a_i y_i
1783 * then the cut is
1785 * c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1787 * The big parameter, if any, is ignored, since it is assumed to be big
1788 * enough to be divisible by any integer.
1789 * If the tableau is actually a parametric tableau, then this function
1790 * is only called when all coefficients of the parameters are integral.
1791 * The cut therefore has zero coefficients for the parameters.
1793 * The current value is known to be negative, so row_sign, if it
1794 * exists, is set accordingly.
1796 * Return the row of the cut or -1.
1798 static int add_cut(struct isl_tab *tab, int row)
1800 int i;
1801 int r;
1802 isl_int *r_row;
1803 unsigned off = 2 + tab->M;
1805 if (isl_tab_extend_cons(tab, 1) < 0)
1806 return -1;
1807 r = isl_tab_allocate_con(tab);
1808 if (r < 0)
1809 return -1;
1811 r_row = tab->mat->row[tab->con[r].index];
1812 isl_int_set(r_row[0], tab->mat->row[row][0]);
1813 isl_int_neg(r_row[1], tab->mat->row[row][1]);
1814 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1815 isl_int_neg(r_row[1], r_row[1]);
1816 if (tab->M)
1817 isl_int_set_si(r_row[2], 0);
1818 for (i = 0; i < tab->n_col; ++i)
1819 isl_int_fdiv_r(r_row[off + i],
1820 tab->mat->row[row][off + i], tab->mat->row[row][0]);
1822 tab->con[r].is_nonneg = 1;
1823 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1824 return -1;
1825 if (tab->row_sign)
1826 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1828 return tab->con[r].index;
1831 #define CUT_ALL 1
1832 #define CUT_ONE 0
1834 /* Given a non-parametric tableau, add cuts until an integer
1835 * sample point is obtained or until the tableau is determined
1836 * to be integer infeasible.
1837 * As long as there is any non-integer value in the sample point,
1838 * we add appropriate cuts, if possible, for each of these
1839 * non-integer values and then resolve the violated
1840 * cut constraints using restore_lexmin.
1841 * If one of the corresponding rows is equal to an integral
1842 * combination of variables/constraints plus a non-integral constant,
1843 * then there is no way to obtain an integer point and we return
1844 * a tableau that is marked empty.
1845 * The parameter cutting_strategy controls the strategy used when adding cuts
1846 * to remove non-integer points. CUT_ALL adds all possible cuts
1847 * before continuing the search. CUT_ONE adds only one cut at a time.
1849 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab,
1850 int cutting_strategy)
1852 int var;
1853 int row;
1854 int flags;
1856 if (!tab)
1857 return NULL;
1858 if (tab->empty)
1859 return tab;
1861 while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1862 do {
1863 if (ISL_FL_ISSET(flags, I_VAR)) {
1864 if (isl_tab_mark_empty(tab) < 0)
1865 goto error;
1866 return tab;
1868 row = tab->var[var].index;
1869 row = add_cut(tab, row);
1870 if (row < 0)
1871 goto error;
1872 if (cutting_strategy == CUT_ONE)
1873 break;
1874 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1875 if (restore_lexmin(tab) < 0)
1876 goto error;
1877 if (tab->empty)
1878 break;
1880 return tab;
1881 error:
1882 isl_tab_free(tab);
1883 return NULL;
1886 /* Check whether all the currently active samples also satisfy the inequality
1887 * "ineq" (treated as an equality if eq is set).
1888 * Remove those samples that do not.
1890 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1892 int i;
1893 isl_int v;
1895 if (!tab)
1896 return NULL;
1898 isl_assert(tab->mat->ctx, tab->bmap, goto error);
1899 isl_assert(tab->mat->ctx, tab->samples, goto error);
1900 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1902 isl_int_init(v);
1903 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1904 int sgn;
1905 isl_seq_inner_product(ineq, tab->samples->row[i],
1906 1 + tab->n_var, &v);
1907 sgn = isl_int_sgn(v);
1908 if (eq ? (sgn == 0) : (sgn >= 0))
1909 continue;
1910 tab = isl_tab_drop_sample(tab, i);
1911 if (!tab)
1912 break;
1914 isl_int_clear(v);
1916 return tab;
1917 error:
1918 isl_tab_free(tab);
1919 return NULL;
1922 /* Check whether the sample value of the tableau is finite,
1923 * i.e., either the tableau does not use a big parameter, or
1924 * all values of the variables are equal to the big parameter plus
1925 * some constant. This constant is the actual sample value.
1927 static int sample_is_finite(struct isl_tab *tab)
1929 int i;
1931 if (!tab->M)
1932 return 1;
1934 for (i = 0; i < tab->n_var; ++i) {
1935 int row;
1936 if (!tab->var[i].is_row)
1937 return 0;
1938 row = tab->var[i].index;
1939 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1940 return 0;
1942 return 1;
1945 /* Check if the context tableau of sol has any integer points.
1946 * Leave tab in empty state if no integer point can be found.
1947 * If an integer point can be found and if moreover it is finite,
1948 * then it is added to the list of sample values.
1950 * This function is only called when none of the currently active sample
1951 * values satisfies the most recently added constraint.
1953 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1955 struct isl_tab_undo *snap;
1957 if (!tab)
1958 return NULL;
1960 snap = isl_tab_snap(tab);
1961 if (isl_tab_push_basis(tab) < 0)
1962 goto error;
1964 tab = cut_to_integer_lexmin(tab, CUT_ALL);
1965 if (!tab)
1966 goto error;
1968 if (!tab->empty && sample_is_finite(tab)) {
1969 struct isl_vec *sample;
1971 sample = isl_tab_get_sample_value(tab);
1973 if (isl_tab_add_sample(tab, sample) < 0)
1974 goto error;
1977 if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1978 goto error;
1980 return tab;
1981 error:
1982 isl_tab_free(tab);
1983 return NULL;
1986 /* Check if any of the currently active sample values satisfies
1987 * the inequality "ineq" (an equality if eq is set).
1989 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1991 int i;
1992 isl_int v;
1994 if (!tab)
1995 return -1;
1997 isl_assert(tab->mat->ctx, tab->bmap, return -1);
1998 isl_assert(tab->mat->ctx, tab->samples, return -1);
1999 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
2001 isl_int_init(v);
2002 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2003 int sgn;
2004 isl_seq_inner_product(ineq, tab->samples->row[i],
2005 1 + tab->n_var, &v);
2006 sgn = isl_int_sgn(v);
2007 if (eq ? (sgn == 0) : (sgn >= 0))
2008 break;
2010 isl_int_clear(v);
2012 return i < tab->n_sample;
2015 /* Insert a div specified by "div" to the tableau "tab" at position "pos" and
2016 * return isl_bool_true if the div is obviously non-negative.
2018 static isl_bool context_tab_insert_div(struct isl_tab *tab, int pos,
2019 __isl_keep isl_vec *div,
2020 isl_stat (*add_ineq)(void *user, isl_int *), void *user)
2022 int i;
2023 int r;
2024 struct isl_mat *samples;
2025 int nonneg;
2027 r = isl_tab_insert_div(tab, pos, div, add_ineq, user);
2028 if (r < 0)
2029 return isl_bool_error;
2030 nonneg = tab->var[r].is_nonneg;
2031 tab->var[r].frozen = 1;
2033 samples = isl_mat_extend(tab->samples,
2034 tab->n_sample, 1 + tab->n_var);
2035 tab->samples = samples;
2036 if (!samples)
2037 return isl_bool_error;
2038 for (i = tab->n_outside; i < samples->n_row; ++i) {
2039 isl_seq_inner_product(div->el + 1, samples->row[i],
2040 div->size - 1, &samples->row[i][samples->n_col - 1]);
2041 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
2042 samples->row[i][samples->n_col - 1], div->el[0]);
2044 tab->samples = isl_mat_move_cols(tab->samples, 1 + pos,
2045 1 + tab->n_var - 1, 1);
2046 if (!tab->samples)
2047 return isl_bool_error;
2049 return nonneg;
2052 /* Add a div specified by "div" to both the main tableau and
2053 * the context tableau. In case of the main tableau, we only
2054 * need to add an extra div. In the context tableau, we also
2055 * need to express the meaning of the div.
2056 * Return the index of the div or -1 if anything went wrong.
2058 * The new integer division is added before any unknown integer
2059 * divisions in the context to ensure that it does not get
2060 * equated to some linear combination involving unknown integer
2061 * divisions.
2063 static int add_div(struct isl_tab *tab, struct isl_context *context,
2064 __isl_keep isl_vec *div)
2066 int r;
2067 int pos;
2068 isl_bool nonneg;
2069 struct isl_tab *context_tab = context->op->peek_tab(context);
2071 if (!tab || !context_tab)
2072 goto error;
2074 pos = context_tab->n_var - context->n_unknown;
2075 if ((nonneg = context->op->insert_div(context, pos, div)) < 0)
2076 goto error;
2078 if (!context->op->is_ok(context))
2079 goto error;
2081 pos = tab->n_var - context->n_unknown;
2082 if (isl_tab_extend_vars(tab, 1) < 0)
2083 goto error;
2084 r = isl_tab_insert_var(tab, pos);
2085 if (r < 0)
2086 goto error;
2087 if (nonneg)
2088 tab->var[r].is_nonneg = 1;
2089 tab->var[r].frozen = 1;
2090 tab->n_div++;
2092 return tab->n_div - 1 - context->n_unknown;
2093 error:
2094 context->op->invalidate(context);
2095 return -1;
2098 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
2100 int i;
2101 unsigned total = isl_basic_map_total_dim(tab->bmap);
2103 for (i = 0; i < tab->bmap->n_div; ++i) {
2104 if (isl_int_ne(tab->bmap->div[i][0], denom))
2105 continue;
2106 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
2107 continue;
2108 return i;
2110 return -1;
2113 /* Return the index of a div that corresponds to "div".
2114 * We first check if we already have such a div and if not, we create one.
2116 static int get_div(struct isl_tab *tab, struct isl_context *context,
2117 struct isl_vec *div)
2119 int d;
2120 struct isl_tab *context_tab = context->op->peek_tab(context);
2122 if (!context_tab)
2123 return -1;
2125 d = find_div(context_tab, div->el + 1, div->el[0]);
2126 if (d != -1)
2127 return d;
2129 return add_div(tab, context, div);
2132 /* Add a parametric cut to cut away the non-integral sample value
2133 * of the give row.
2134 * Let a_i be the coefficients of the constant term and the parameters
2135 * and let b_i be the coefficients of the variables or constraints
2136 * in basis of the tableau.
2137 * Let q be the div q = floor(\sum_i {-a_i} y_i).
2139 * The cut is expressed as
2141 * c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
2143 * If q did not already exist in the context tableau, then it is added first.
2144 * If q is in a column of the main tableau then the "+ q" can be accomplished
2145 * by setting the corresponding entry to the denominator of the constraint.
2146 * If q happens to be in a row of the main tableau, then the corresponding
2147 * row needs to be added instead (taking care of the denominators).
2148 * Note that this is very unlikely, but perhaps not entirely impossible.
2150 * The current value of the cut is known to be negative (or at least
2151 * non-positive), so row_sign is set accordingly.
2153 * Return the row of the cut or -1.
2155 static int add_parametric_cut(struct isl_tab *tab, int row,
2156 struct isl_context *context)
2158 struct isl_vec *div;
2159 int d;
2160 int i;
2161 int r;
2162 isl_int *r_row;
2163 int col;
2164 int n;
2165 unsigned off = 2 + tab->M;
2167 if (!context)
2168 return -1;
2170 div = get_row_parameter_div(tab, row);
2171 if (!div)
2172 return -1;
2174 n = tab->n_div - context->n_unknown;
2175 d = context->op->get_div(context, tab, div);
2176 isl_vec_free(div);
2177 if (d < 0)
2178 return -1;
2180 if (isl_tab_extend_cons(tab, 1) < 0)
2181 return -1;
2182 r = isl_tab_allocate_con(tab);
2183 if (r < 0)
2184 return -1;
2186 r_row = tab->mat->row[tab->con[r].index];
2187 isl_int_set(r_row[0], tab->mat->row[row][0]);
2188 isl_int_neg(r_row[1], tab->mat->row[row][1]);
2189 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
2190 isl_int_neg(r_row[1], r_row[1]);
2191 if (tab->M)
2192 isl_int_set_si(r_row[2], 0);
2193 for (i = 0; i < tab->n_param; ++i) {
2194 if (tab->var[i].is_row)
2195 continue;
2196 col = tab->var[i].index;
2197 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2198 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2199 tab->mat->row[row][0]);
2200 isl_int_neg(r_row[off + col], r_row[off + col]);
2202 for (i = 0; i < tab->n_div; ++i) {
2203 if (tab->var[tab->n_var - tab->n_div + i].is_row)
2204 continue;
2205 col = tab->var[tab->n_var - tab->n_div + i].index;
2206 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2207 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2208 tab->mat->row[row][0]);
2209 isl_int_neg(r_row[off + col], r_row[off + col]);
2211 for (i = 0; i < tab->n_col; ++i) {
2212 if (tab->col_var[i] >= 0 &&
2213 (tab->col_var[i] < tab->n_param ||
2214 tab->col_var[i] >= tab->n_var - tab->n_div))
2215 continue;
2216 isl_int_fdiv_r(r_row[off + i],
2217 tab->mat->row[row][off + i], tab->mat->row[row][0]);
2219 if (tab->var[tab->n_var - tab->n_div + d].is_row) {
2220 isl_int gcd;
2221 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
2222 isl_int_init(gcd);
2223 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
2224 isl_int_divexact(r_row[0], r_row[0], gcd);
2225 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
2226 isl_seq_combine(r_row + 1, gcd, r_row + 1,
2227 r_row[0], tab->mat->row[d_row] + 1,
2228 off - 1 + tab->n_col);
2229 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
2230 isl_int_clear(gcd);
2231 } else {
2232 col = tab->var[tab->n_var - tab->n_div + d].index;
2233 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
2236 tab->con[r].is_nonneg = 1;
2237 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
2238 return -1;
2239 if (tab->row_sign)
2240 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
2242 row = tab->con[r].index;
2244 if (d >= n && context->op->detect_equalities(context, tab) < 0)
2245 return -1;
2247 return row;
2250 /* Construct a tableau for bmap that can be used for computing
2251 * the lexicographic minimum (or maximum) of bmap.
2252 * If not NULL, then dom is the domain where the minimum
2253 * should be computed. In this case, we set up a parametric
2254 * tableau with row signs (initialized to "unknown").
2255 * If M is set, then the tableau will use a big parameter.
2256 * If max is set, then a maximum should be computed instead of a minimum.
2257 * This means that for each variable x, the tableau will contain the variable
2258 * x' = M - x, rather than x' = M + x. This in turn means that the coefficient
2259 * of the variables in all constraints are negated prior to adding them
2260 * to the tableau.
2262 static __isl_give struct isl_tab *tab_for_lexmin(__isl_keep isl_basic_map *bmap,
2263 __isl_keep isl_basic_set *dom, unsigned M, int max)
2265 int i;
2266 struct isl_tab *tab;
2267 unsigned n_var;
2268 unsigned o_var;
2270 tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
2271 isl_basic_map_total_dim(bmap), M);
2272 if (!tab)
2273 return NULL;
2275 tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
2276 if (dom) {
2277 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
2278 tab->n_div = dom->n_div;
2279 tab->row_sign = isl_calloc_array(bmap->ctx,
2280 enum isl_tab_row_sign, tab->mat->n_row);
2281 if (tab->mat->n_row && !tab->row_sign)
2282 goto error;
2284 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
2285 if (isl_tab_mark_empty(tab) < 0)
2286 goto error;
2287 return tab;
2290 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2291 tab->var[i].is_nonneg = 1;
2292 tab->var[i].frozen = 1;
2294 o_var = 1 + tab->n_param;
2295 n_var = tab->n_var - tab->n_param - tab->n_div;
2296 for (i = 0; i < bmap->n_eq; ++i) {
2297 if (max)
2298 isl_seq_neg(bmap->eq[i] + o_var,
2299 bmap->eq[i] + o_var, n_var);
2300 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2301 if (max)
2302 isl_seq_neg(bmap->eq[i] + o_var,
2303 bmap->eq[i] + o_var, n_var);
2304 if (!tab || tab->empty)
2305 return tab;
2307 if (bmap->n_eq && restore_lexmin(tab) < 0)
2308 goto error;
2309 for (i = 0; i < bmap->n_ineq; ++i) {
2310 if (max)
2311 isl_seq_neg(bmap->ineq[i] + o_var,
2312 bmap->ineq[i] + o_var, n_var);
2313 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2314 if (max)
2315 isl_seq_neg(bmap->ineq[i] + o_var,
2316 bmap->ineq[i] + o_var, n_var);
2317 if (!tab || tab->empty)
2318 return tab;
2320 return tab;
2321 error:
2322 isl_tab_free(tab);
2323 return NULL;
2326 /* Given a main tableau where more than one row requires a split,
2327 * determine and return the "best" row to split on.
2329 * Given two rows in the main tableau, if the inequality corresponding
2330 * to the first row is redundant with respect to that of the second row
2331 * in the current tableau, then it is better to split on the second row,
2332 * since in the positive part, both rows will be positive.
2333 * (In the negative part a pivot will have to be performed and just about
2334 * anything can happen to the sign of the other row.)
2336 * As a simple heuristic, we therefore select the row that makes the most
2337 * of the other rows redundant.
2339 * Perhaps it would also be useful to look at the number of constraints
2340 * that conflict with any given constraint.
2342 * best is the best row so far (-1 when we have not found any row yet).
2343 * best_r is the number of other rows made redundant by row best.
2344 * When best is still -1, bset_r is meaningless, but it is initialized
2345 * to some arbitrary value (0) anyway. Without this redundant initialization
2346 * valgrind may warn about uninitialized memory accesses when isl
2347 * is compiled with some versions of gcc.
2349 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2351 struct isl_tab_undo *snap;
2352 int split;
2353 int row;
2354 int best = -1;
2355 int best_r = 0;
2357 if (isl_tab_extend_cons(context_tab, 2) < 0)
2358 return -1;
2360 snap = isl_tab_snap(context_tab);
2362 for (split = tab->n_redundant; split < tab->n_row; ++split) {
2363 struct isl_tab_undo *snap2;
2364 struct isl_vec *ineq = NULL;
2365 int r = 0;
2366 int ok;
2368 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2369 continue;
2370 if (tab->row_sign[split] != isl_tab_row_any)
2371 continue;
2373 ineq = get_row_parameter_ineq(tab, split);
2374 if (!ineq)
2375 return -1;
2376 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2377 isl_vec_free(ineq);
2378 if (!ok)
2379 return -1;
2381 snap2 = isl_tab_snap(context_tab);
2383 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2384 struct isl_tab_var *var;
2386 if (row == split)
2387 continue;
2388 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2389 continue;
2390 if (tab->row_sign[row] != isl_tab_row_any)
2391 continue;
2393 ineq = get_row_parameter_ineq(tab, row);
2394 if (!ineq)
2395 return -1;
2396 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2397 isl_vec_free(ineq);
2398 if (!ok)
2399 return -1;
2400 var = &context_tab->con[context_tab->n_con - 1];
2401 if (!context_tab->empty &&
2402 !isl_tab_min_at_most_neg_one(context_tab, var))
2403 r++;
2404 if (isl_tab_rollback(context_tab, snap2) < 0)
2405 return -1;
2407 if (best == -1 || r > best_r) {
2408 best = split;
2409 best_r = r;
2411 if (isl_tab_rollback(context_tab, snap) < 0)
2412 return -1;
2415 return best;
2418 static struct isl_basic_set *context_lex_peek_basic_set(
2419 struct isl_context *context)
2421 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2422 if (!clex->tab)
2423 return NULL;
2424 return isl_tab_peek_bset(clex->tab);
2427 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2429 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2430 return clex->tab;
2433 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2434 int check, int update)
2436 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2437 if (isl_tab_extend_cons(clex->tab, 2) < 0)
2438 goto error;
2439 if (add_lexmin_eq(clex->tab, eq) < 0)
2440 goto error;
2441 if (check) {
2442 int v = tab_has_valid_sample(clex->tab, eq, 1);
2443 if (v < 0)
2444 goto error;
2445 if (!v)
2446 clex->tab = check_integer_feasible(clex->tab);
2448 if (update)
2449 clex->tab = check_samples(clex->tab, eq, 1);
2450 return;
2451 error:
2452 isl_tab_free(clex->tab);
2453 clex->tab = NULL;
2456 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2457 int check, int update)
2459 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2460 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2461 goto error;
2462 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2463 if (check) {
2464 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2465 if (v < 0)
2466 goto error;
2467 if (!v)
2468 clex->tab = check_integer_feasible(clex->tab);
2470 if (update)
2471 clex->tab = check_samples(clex->tab, ineq, 0);
2472 return;
2473 error:
2474 isl_tab_free(clex->tab);
2475 clex->tab = NULL;
2478 static isl_stat context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2480 struct isl_context *context = (struct isl_context *)user;
2481 context_lex_add_ineq(context, ineq, 0, 0);
2482 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
2485 /* Check which signs can be obtained by "ineq" on all the currently
2486 * active sample values. See row_sign for more information.
2488 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2489 int strict)
2491 int i;
2492 int sgn;
2493 isl_int tmp;
2494 enum isl_tab_row_sign res = isl_tab_row_unknown;
2496 isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2497 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2498 return isl_tab_row_unknown);
2500 isl_int_init(tmp);
2501 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2502 isl_seq_inner_product(tab->samples->row[i], ineq,
2503 1 + tab->n_var, &tmp);
2504 sgn = isl_int_sgn(tmp);
2505 if (sgn > 0 || (sgn == 0 && strict)) {
2506 if (res == isl_tab_row_unknown)
2507 res = isl_tab_row_pos;
2508 if (res == isl_tab_row_neg)
2509 res = isl_tab_row_any;
2511 if (sgn < 0) {
2512 if (res == isl_tab_row_unknown)
2513 res = isl_tab_row_neg;
2514 if (res == isl_tab_row_pos)
2515 res = isl_tab_row_any;
2517 if (res == isl_tab_row_any)
2518 break;
2520 isl_int_clear(tmp);
2522 return res;
2525 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2526 isl_int *ineq, int strict)
2528 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2529 return tab_ineq_sign(clex->tab, ineq, strict);
2532 /* Check whether "ineq" can be added to the tableau without rendering
2533 * it infeasible.
2535 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2537 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2538 struct isl_tab_undo *snap;
2539 int feasible;
2541 if (!clex->tab)
2542 return -1;
2544 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2545 return -1;
2547 snap = isl_tab_snap(clex->tab);
2548 if (isl_tab_push_basis(clex->tab) < 0)
2549 return -1;
2550 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2551 clex->tab = check_integer_feasible(clex->tab);
2552 if (!clex->tab)
2553 return -1;
2554 feasible = !clex->tab->empty;
2555 if (isl_tab_rollback(clex->tab, snap) < 0)
2556 return -1;
2558 return feasible;
2561 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2562 struct isl_vec *div)
2564 return get_div(tab, context, div);
2567 /* Insert a div specified by "div" to the context tableau at position "pos" and
2568 * return isl_bool_true if the div is obviously non-negative.
2569 * context_tab_add_div will always return isl_bool_true, because all variables
2570 * in a isl_context_lex tableau are non-negative.
2571 * However, if we are using a big parameter in the context, then this only
2572 * reflects the non-negativity of the variable used to _encode_ the
2573 * div, i.e., div' = M + div, so we can't draw any conclusions.
2575 static isl_bool context_lex_insert_div(struct isl_context *context, int pos,
2576 __isl_keep isl_vec *div)
2578 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2579 isl_bool nonneg;
2580 nonneg = context_tab_insert_div(clex->tab, pos, div,
2581 context_lex_add_ineq_wrap, context);
2582 if (nonneg < 0)
2583 return isl_bool_error;
2584 if (clex->tab->M)
2585 return isl_bool_false;
2586 return nonneg;
2589 static int context_lex_detect_equalities(struct isl_context *context,
2590 struct isl_tab *tab)
2592 return 0;
2595 static int context_lex_best_split(struct isl_context *context,
2596 struct isl_tab *tab)
2598 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2599 struct isl_tab_undo *snap;
2600 int r;
2602 snap = isl_tab_snap(clex->tab);
2603 if (isl_tab_push_basis(clex->tab) < 0)
2604 return -1;
2605 r = best_split(tab, clex->tab);
2607 if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2608 return -1;
2610 return r;
2613 static int context_lex_is_empty(struct isl_context *context)
2615 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2616 if (!clex->tab)
2617 return -1;
2618 return clex->tab->empty;
2621 static void *context_lex_save(struct isl_context *context)
2623 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2624 struct isl_tab_undo *snap;
2626 snap = isl_tab_snap(clex->tab);
2627 if (isl_tab_push_basis(clex->tab) < 0)
2628 return NULL;
2629 if (isl_tab_save_samples(clex->tab) < 0)
2630 return NULL;
2632 return snap;
2635 static void context_lex_restore(struct isl_context *context, void *save)
2637 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2638 if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2639 isl_tab_free(clex->tab);
2640 clex->tab = NULL;
2644 static void context_lex_discard(void *save)
2648 static int context_lex_is_ok(struct isl_context *context)
2650 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2651 return !!clex->tab;
2654 /* For each variable in the context tableau, check if the variable can
2655 * only attain non-negative values. If so, mark the parameter as non-negative
2656 * in the main tableau. This allows for a more direct identification of some
2657 * cases of violated constraints.
2659 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2660 struct isl_tab *context_tab)
2662 int i;
2663 struct isl_tab_undo *snap;
2664 struct isl_vec *ineq = NULL;
2665 struct isl_tab_var *var;
2666 int n;
2668 if (context_tab->n_var == 0)
2669 return tab;
2671 ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2672 if (!ineq)
2673 goto error;
2675 if (isl_tab_extend_cons(context_tab, 1) < 0)
2676 goto error;
2678 snap = isl_tab_snap(context_tab);
2680 n = 0;
2681 isl_seq_clr(ineq->el, ineq->size);
2682 for (i = 0; i < context_tab->n_var; ++i) {
2683 isl_int_set_si(ineq->el[1 + i], 1);
2684 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2685 goto error;
2686 var = &context_tab->con[context_tab->n_con - 1];
2687 if (!context_tab->empty &&
2688 !isl_tab_min_at_most_neg_one(context_tab, var)) {
2689 int j = i;
2690 if (i >= tab->n_param)
2691 j = i - tab->n_param + tab->n_var - tab->n_div;
2692 tab->var[j].is_nonneg = 1;
2693 n++;
2695 isl_int_set_si(ineq->el[1 + i], 0);
2696 if (isl_tab_rollback(context_tab, snap) < 0)
2697 goto error;
2700 if (context_tab->M && n == context_tab->n_var) {
2701 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2702 context_tab->M = 0;
2705 isl_vec_free(ineq);
2706 return tab;
2707 error:
2708 isl_vec_free(ineq);
2709 isl_tab_free(tab);
2710 return NULL;
2713 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2714 struct isl_context *context, struct isl_tab *tab)
2716 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2717 struct isl_tab_undo *snap;
2719 if (!tab)
2720 return NULL;
2722 snap = isl_tab_snap(clex->tab);
2723 if (isl_tab_push_basis(clex->tab) < 0)
2724 goto error;
2726 tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2728 if (isl_tab_rollback(clex->tab, snap) < 0)
2729 goto error;
2731 return tab;
2732 error:
2733 isl_tab_free(tab);
2734 return NULL;
2737 static void context_lex_invalidate(struct isl_context *context)
2739 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2740 isl_tab_free(clex->tab);
2741 clex->tab = NULL;
2744 static __isl_null struct isl_context *context_lex_free(
2745 struct isl_context *context)
2747 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2748 isl_tab_free(clex->tab);
2749 free(clex);
2751 return NULL;
2754 struct isl_context_op isl_context_lex_op = {
2755 context_lex_detect_nonnegative_parameters,
2756 context_lex_peek_basic_set,
2757 context_lex_peek_tab,
2758 context_lex_add_eq,
2759 context_lex_add_ineq,
2760 context_lex_ineq_sign,
2761 context_lex_test_ineq,
2762 context_lex_get_div,
2763 context_lex_insert_div,
2764 context_lex_detect_equalities,
2765 context_lex_best_split,
2766 context_lex_is_empty,
2767 context_lex_is_ok,
2768 context_lex_save,
2769 context_lex_restore,
2770 context_lex_discard,
2771 context_lex_invalidate,
2772 context_lex_free,
2775 static struct isl_tab *context_tab_for_lexmin(__isl_take isl_basic_set *bset)
2777 struct isl_tab *tab;
2779 if (!bset)
2780 return NULL;
2781 tab = tab_for_lexmin(bset_to_bmap(bset), NULL, 1, 0);
2782 if (isl_tab_track_bset(tab, bset) < 0)
2783 goto error;
2784 tab = isl_tab_init_samples(tab);
2785 return tab;
2786 error:
2787 isl_tab_free(tab);
2788 return NULL;
2791 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2793 struct isl_context_lex *clex;
2795 if (!dom)
2796 return NULL;
2798 clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2799 if (!clex)
2800 return NULL;
2802 clex->context.op = &isl_context_lex_op;
2804 clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2805 if (restore_lexmin(clex->tab) < 0)
2806 goto error;
2807 clex->tab = check_integer_feasible(clex->tab);
2808 if (!clex->tab)
2809 goto error;
2811 return &clex->context;
2812 error:
2813 clex->context.op->free(&clex->context);
2814 return NULL;
2817 /* Representation of the context when using generalized basis reduction.
2819 * "shifted" contains the offsets of the unit hypercubes that lie inside the
2820 * context. Any rational point in "shifted" can therefore be rounded
2821 * up to an integer point in the context.
2822 * If the context is constrained by any equality, then "shifted" is not used
2823 * as it would be empty.
2825 struct isl_context_gbr {
2826 struct isl_context context;
2827 struct isl_tab *tab;
2828 struct isl_tab *shifted;
2829 struct isl_tab *cone;
2832 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2833 struct isl_context *context, struct isl_tab *tab)
2835 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2836 if (!tab)
2837 return NULL;
2838 return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2841 static struct isl_basic_set *context_gbr_peek_basic_set(
2842 struct isl_context *context)
2844 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2845 if (!cgbr->tab)
2846 return NULL;
2847 return isl_tab_peek_bset(cgbr->tab);
2850 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2852 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2853 return cgbr->tab;
2856 /* Initialize the "shifted" tableau of the context, which
2857 * contains the constraints of the original tableau shifted
2858 * by the sum of all negative coefficients. This ensures
2859 * that any rational point in the shifted tableau can
2860 * be rounded up to yield an integer point in the original tableau.
2862 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2864 int i, j;
2865 struct isl_vec *cst;
2866 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2867 unsigned dim = isl_basic_set_total_dim(bset);
2869 cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2870 if (!cst)
2871 return;
2873 for (i = 0; i < bset->n_ineq; ++i) {
2874 isl_int_set(cst->el[i], bset->ineq[i][0]);
2875 for (j = 0; j < dim; ++j) {
2876 if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2877 continue;
2878 isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2879 bset->ineq[i][1 + j]);
2883 cgbr->shifted = isl_tab_from_basic_set(bset, 0);
2885 for (i = 0; i < bset->n_ineq; ++i)
2886 isl_int_set(bset->ineq[i][0], cst->el[i]);
2888 isl_vec_free(cst);
2891 /* Check if the shifted tableau is non-empty, and if so
2892 * use the sample point to construct an integer point
2893 * of the context tableau.
2895 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2897 struct isl_vec *sample;
2899 if (!cgbr->shifted)
2900 gbr_init_shifted(cgbr);
2901 if (!cgbr->shifted)
2902 return NULL;
2903 if (cgbr->shifted->empty)
2904 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2906 sample = isl_tab_get_sample_value(cgbr->shifted);
2907 sample = isl_vec_ceil(sample);
2909 return sample;
2912 static __isl_give isl_basic_set *drop_constant_terms(
2913 __isl_take isl_basic_set *bset)
2915 int i;
2917 if (!bset)
2918 return NULL;
2920 for (i = 0; i < bset->n_eq; ++i)
2921 isl_int_set_si(bset->eq[i][0], 0);
2923 for (i = 0; i < bset->n_ineq; ++i)
2924 isl_int_set_si(bset->ineq[i][0], 0);
2926 return bset;
2929 static int use_shifted(struct isl_context_gbr *cgbr)
2931 if (!cgbr->tab)
2932 return 0;
2933 return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2936 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2938 struct isl_basic_set *bset;
2939 struct isl_basic_set *cone;
2941 if (isl_tab_sample_is_integer(cgbr->tab))
2942 return isl_tab_get_sample_value(cgbr->tab);
2944 if (use_shifted(cgbr)) {
2945 struct isl_vec *sample;
2947 sample = gbr_get_shifted_sample(cgbr);
2948 if (!sample || sample->size > 0)
2949 return sample;
2951 isl_vec_free(sample);
2954 if (!cgbr->cone) {
2955 bset = isl_tab_peek_bset(cgbr->tab);
2956 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2957 if (!cgbr->cone)
2958 return NULL;
2959 if (isl_tab_track_bset(cgbr->cone,
2960 isl_basic_set_copy(bset)) < 0)
2961 return NULL;
2963 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2964 return NULL;
2966 if (cgbr->cone->n_dead == cgbr->cone->n_col) {
2967 struct isl_vec *sample;
2968 struct isl_tab_undo *snap;
2970 if (cgbr->tab->basis) {
2971 if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
2972 isl_mat_free(cgbr->tab->basis);
2973 cgbr->tab->basis = NULL;
2975 cgbr->tab->n_zero = 0;
2976 cgbr->tab->n_unbounded = 0;
2979 snap = isl_tab_snap(cgbr->tab);
2981 sample = isl_tab_sample(cgbr->tab);
2983 if (!sample || isl_tab_rollback(cgbr->tab, snap) < 0) {
2984 isl_vec_free(sample);
2985 return NULL;
2988 return sample;
2991 cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
2992 cone = drop_constant_terms(cone);
2993 cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
2994 cone = isl_basic_set_underlying_set(cone);
2995 cone = isl_basic_set_gauss(cone, NULL);
2997 bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
2998 bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
2999 bset = isl_basic_set_underlying_set(bset);
3000 bset = isl_basic_set_gauss(bset, NULL);
3002 return isl_basic_set_sample_with_cone(bset, cone);
3005 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
3007 struct isl_vec *sample;
3009 if (!cgbr->tab)
3010 return;
3012 if (cgbr->tab->empty)
3013 return;
3015 sample = gbr_get_sample(cgbr);
3016 if (!sample)
3017 goto error;
3019 if (sample->size == 0) {
3020 isl_vec_free(sample);
3021 if (isl_tab_mark_empty(cgbr->tab) < 0)
3022 goto error;
3023 return;
3026 if (isl_tab_add_sample(cgbr->tab, sample) < 0)
3027 goto error;
3029 return;
3030 error:
3031 isl_tab_free(cgbr->tab);
3032 cgbr->tab = NULL;
3035 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
3037 if (!tab)
3038 return NULL;
3040 if (isl_tab_extend_cons(tab, 2) < 0)
3041 goto error;
3043 if (isl_tab_add_eq(tab, eq) < 0)
3044 goto error;
3046 return tab;
3047 error:
3048 isl_tab_free(tab);
3049 return NULL;
3052 /* Add the equality described by "eq" to the context.
3053 * If "check" is set, then we check if the context is empty after
3054 * adding the equality.
3055 * If "update" is set, then we check if the samples are still valid.
3057 * We do not explicitly add shifted copies of the equality to
3058 * cgbr->shifted since they would conflict with each other.
3059 * Instead, we directly mark cgbr->shifted empty.
3061 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
3062 int check, int update)
3064 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3066 cgbr->tab = add_gbr_eq(cgbr->tab, eq);
3068 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3069 if (isl_tab_mark_empty(cgbr->shifted) < 0)
3070 goto error;
3073 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3074 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
3075 goto error;
3076 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
3077 goto error;
3080 if (check) {
3081 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
3082 if (v < 0)
3083 goto error;
3084 if (!v)
3085 check_gbr_integer_feasible(cgbr);
3087 if (update)
3088 cgbr->tab = check_samples(cgbr->tab, eq, 1);
3089 return;
3090 error:
3091 isl_tab_free(cgbr->tab);
3092 cgbr->tab = NULL;
3095 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
3097 if (!cgbr->tab)
3098 return;
3100 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3101 goto error;
3103 if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
3104 goto error;
3106 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3107 int i;
3108 unsigned dim;
3109 dim = isl_basic_map_total_dim(cgbr->tab->bmap);
3111 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
3112 goto error;
3114 for (i = 0; i < dim; ++i) {
3115 if (!isl_int_is_neg(ineq[1 + i]))
3116 continue;
3117 isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
3120 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
3121 goto error;
3123 for (i = 0; i < dim; ++i) {
3124 if (!isl_int_is_neg(ineq[1 + i]))
3125 continue;
3126 isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
3130 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3131 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
3132 goto error;
3133 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
3134 goto error;
3137 return;
3138 error:
3139 isl_tab_free(cgbr->tab);
3140 cgbr->tab = NULL;
3143 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
3144 int check, int update)
3146 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3148 add_gbr_ineq(cgbr, ineq);
3149 if (!cgbr->tab)
3150 return;
3152 if (check) {
3153 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
3154 if (v < 0)
3155 goto error;
3156 if (!v)
3157 check_gbr_integer_feasible(cgbr);
3159 if (update)
3160 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
3161 return;
3162 error:
3163 isl_tab_free(cgbr->tab);
3164 cgbr->tab = NULL;
3167 static isl_stat context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
3169 struct isl_context *context = (struct isl_context *)user;
3170 context_gbr_add_ineq(context, ineq, 0, 0);
3171 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
3174 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
3175 isl_int *ineq, int strict)
3177 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3178 return tab_ineq_sign(cgbr->tab, ineq, strict);
3181 /* Check whether "ineq" can be added to the tableau without rendering
3182 * it infeasible.
3184 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
3186 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3187 struct isl_tab_undo *snap;
3188 struct isl_tab_undo *shifted_snap = NULL;
3189 struct isl_tab_undo *cone_snap = NULL;
3190 int feasible;
3192 if (!cgbr->tab)
3193 return -1;
3195 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3196 return -1;
3198 snap = isl_tab_snap(cgbr->tab);
3199 if (cgbr->shifted)
3200 shifted_snap = isl_tab_snap(cgbr->shifted);
3201 if (cgbr->cone)
3202 cone_snap = isl_tab_snap(cgbr->cone);
3203 add_gbr_ineq(cgbr, ineq);
3204 check_gbr_integer_feasible(cgbr);
3205 if (!cgbr->tab)
3206 return -1;
3207 feasible = !cgbr->tab->empty;
3208 if (isl_tab_rollback(cgbr->tab, snap) < 0)
3209 return -1;
3210 if (shifted_snap) {
3211 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
3212 return -1;
3213 } else if (cgbr->shifted) {
3214 isl_tab_free(cgbr->shifted);
3215 cgbr->shifted = NULL;
3217 if (cone_snap) {
3218 if (isl_tab_rollback(cgbr->cone, cone_snap))
3219 return -1;
3220 } else if (cgbr->cone) {
3221 isl_tab_free(cgbr->cone);
3222 cgbr->cone = NULL;
3225 return feasible;
3228 /* Return the column of the last of the variables associated to
3229 * a column that has a non-zero coefficient.
3230 * This function is called in a context where only coefficients
3231 * of parameters or divs can be non-zero.
3233 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
3235 int i;
3236 int col;
3238 if (tab->n_var == 0)
3239 return -1;
3241 for (i = tab->n_var - 1; i >= 0; --i) {
3242 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
3243 continue;
3244 if (tab->var[i].is_row)
3245 continue;
3246 col = tab->var[i].index;
3247 if (!isl_int_is_zero(p[col]))
3248 return col;
3251 return -1;
3254 /* Look through all the recently added equalities in the context
3255 * to see if we can propagate any of them to the main tableau.
3257 * The newly added equalities in the context are encoded as pairs
3258 * of inequalities starting at inequality "first".
3260 * We tentatively add each of these equalities to the main tableau
3261 * and if this happens to result in a row with a final coefficient
3262 * that is one or negative one, we use it to kill a column
3263 * in the main tableau. Otherwise, we discard the tentatively
3264 * added row.
3265 * This tentative addition of equality constraints turns
3266 * on the undo facility of the tableau. Turn it off again
3267 * at the end, assuming it was turned off to begin with.
3269 * Return 0 on success and -1 on failure.
3271 static int propagate_equalities(struct isl_context_gbr *cgbr,
3272 struct isl_tab *tab, unsigned first)
3274 int i;
3275 struct isl_vec *eq = NULL;
3276 isl_bool needs_undo;
3278 needs_undo = isl_tab_need_undo(tab);
3279 if (needs_undo < 0)
3280 goto error;
3281 eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
3282 if (!eq)
3283 goto error;
3285 if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
3286 goto error;
3288 isl_seq_clr(eq->el + 1 + tab->n_param,
3289 tab->n_var - tab->n_param - tab->n_div);
3290 for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
3291 int j;
3292 int r;
3293 struct isl_tab_undo *snap;
3294 snap = isl_tab_snap(tab);
3296 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
3297 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
3298 cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
3299 tab->n_div);
3301 r = isl_tab_add_row(tab, eq->el);
3302 if (r < 0)
3303 goto error;
3304 r = tab->con[r].index;
3305 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
3306 if (j < 0 || j < tab->n_dead ||
3307 !isl_int_is_one(tab->mat->row[r][0]) ||
3308 (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
3309 !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
3310 if (isl_tab_rollback(tab, snap) < 0)
3311 goto error;
3312 continue;
3314 if (isl_tab_pivot(tab, r, j) < 0)
3315 goto error;
3316 if (isl_tab_kill_col(tab, j) < 0)
3317 goto error;
3319 if (restore_lexmin(tab) < 0)
3320 goto error;
3323 if (!needs_undo)
3324 isl_tab_clear_undo(tab);
3325 isl_vec_free(eq);
3327 return 0;
3328 error:
3329 isl_vec_free(eq);
3330 isl_tab_free(cgbr->tab);
3331 cgbr->tab = NULL;
3332 return -1;
3335 static int context_gbr_detect_equalities(struct isl_context *context,
3336 struct isl_tab *tab)
3338 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3339 unsigned n_ineq;
3341 if (!cgbr->cone) {
3342 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3343 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3344 if (!cgbr->cone)
3345 goto error;
3346 if (isl_tab_track_bset(cgbr->cone,
3347 isl_basic_set_copy(bset)) < 0)
3348 goto error;
3350 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3351 goto error;
3353 n_ineq = cgbr->tab->bmap->n_ineq;
3354 cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3355 if (!cgbr->tab)
3356 return -1;
3357 if (cgbr->tab->bmap->n_ineq > n_ineq &&
3358 propagate_equalities(cgbr, tab, n_ineq) < 0)
3359 return -1;
3361 return 0;
3362 error:
3363 isl_tab_free(cgbr->tab);
3364 cgbr->tab = NULL;
3365 return -1;
3368 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3369 struct isl_vec *div)
3371 return get_div(tab, context, div);
3374 static isl_bool context_gbr_insert_div(struct isl_context *context, int pos,
3375 __isl_keep isl_vec *div)
3377 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3378 if (cgbr->cone) {
3379 int r, n_div, o_div;
3381 n_div = isl_basic_map_dim(cgbr->cone->bmap, isl_dim_div);
3382 o_div = cgbr->cone->n_var - n_div;
3384 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3385 return isl_bool_error;
3386 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3387 return isl_bool_error;
3388 if ((r = isl_tab_insert_var(cgbr->cone, pos)) <0)
3389 return isl_bool_error;
3391 cgbr->cone->bmap = isl_basic_map_insert_div(cgbr->cone->bmap,
3392 r - o_div, div);
3393 if (!cgbr->cone->bmap)
3394 return isl_bool_error;
3395 if (isl_tab_push_var(cgbr->cone, isl_tab_undo_bmap_div,
3396 &cgbr->cone->var[r]) < 0)
3397 return isl_bool_error;
3399 return context_tab_insert_div(cgbr->tab, pos, div,
3400 context_gbr_add_ineq_wrap, context);
3403 static int context_gbr_best_split(struct isl_context *context,
3404 struct isl_tab *tab)
3406 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3407 struct isl_tab_undo *snap;
3408 int r;
3410 snap = isl_tab_snap(cgbr->tab);
3411 r = best_split(tab, cgbr->tab);
3413 if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3414 return -1;
3416 return r;
3419 static int context_gbr_is_empty(struct isl_context *context)
3421 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3422 if (!cgbr->tab)
3423 return -1;
3424 return cgbr->tab->empty;
3427 struct isl_gbr_tab_undo {
3428 struct isl_tab_undo *tab_snap;
3429 struct isl_tab_undo *shifted_snap;
3430 struct isl_tab_undo *cone_snap;
3433 static void *context_gbr_save(struct isl_context *context)
3435 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3436 struct isl_gbr_tab_undo *snap;
3438 if (!cgbr->tab)
3439 return NULL;
3441 snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3442 if (!snap)
3443 return NULL;
3445 snap->tab_snap = isl_tab_snap(cgbr->tab);
3446 if (isl_tab_save_samples(cgbr->tab) < 0)
3447 goto error;
3449 if (cgbr->shifted)
3450 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3451 else
3452 snap->shifted_snap = NULL;
3454 if (cgbr->cone)
3455 snap->cone_snap = isl_tab_snap(cgbr->cone);
3456 else
3457 snap->cone_snap = NULL;
3459 return snap;
3460 error:
3461 free(snap);
3462 return NULL;
3465 static void context_gbr_restore(struct isl_context *context, void *save)
3467 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3468 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3469 if (!snap)
3470 goto error;
3471 if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0)
3472 goto error;
3474 if (snap->shifted_snap) {
3475 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3476 goto error;
3477 } else if (cgbr->shifted) {
3478 isl_tab_free(cgbr->shifted);
3479 cgbr->shifted = NULL;
3482 if (snap->cone_snap) {
3483 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3484 goto error;
3485 } else if (cgbr->cone) {
3486 isl_tab_free(cgbr->cone);
3487 cgbr->cone = NULL;
3490 free(snap);
3492 return;
3493 error:
3494 free(snap);
3495 isl_tab_free(cgbr->tab);
3496 cgbr->tab = NULL;
3499 static void context_gbr_discard(void *save)
3501 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3502 free(snap);
3505 static int context_gbr_is_ok(struct isl_context *context)
3507 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3508 return !!cgbr->tab;
3511 static void context_gbr_invalidate(struct isl_context *context)
3513 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3514 isl_tab_free(cgbr->tab);
3515 cgbr->tab = NULL;
3518 static __isl_null struct isl_context *context_gbr_free(
3519 struct isl_context *context)
3521 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3522 isl_tab_free(cgbr->tab);
3523 isl_tab_free(cgbr->shifted);
3524 isl_tab_free(cgbr->cone);
3525 free(cgbr);
3527 return NULL;
3530 struct isl_context_op isl_context_gbr_op = {
3531 context_gbr_detect_nonnegative_parameters,
3532 context_gbr_peek_basic_set,
3533 context_gbr_peek_tab,
3534 context_gbr_add_eq,
3535 context_gbr_add_ineq,
3536 context_gbr_ineq_sign,
3537 context_gbr_test_ineq,
3538 context_gbr_get_div,
3539 context_gbr_insert_div,
3540 context_gbr_detect_equalities,
3541 context_gbr_best_split,
3542 context_gbr_is_empty,
3543 context_gbr_is_ok,
3544 context_gbr_save,
3545 context_gbr_restore,
3546 context_gbr_discard,
3547 context_gbr_invalidate,
3548 context_gbr_free,
3551 static struct isl_context *isl_context_gbr_alloc(__isl_keep isl_basic_set *dom)
3553 struct isl_context_gbr *cgbr;
3555 if (!dom)
3556 return NULL;
3558 cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3559 if (!cgbr)
3560 return NULL;
3562 cgbr->context.op = &isl_context_gbr_op;
3564 cgbr->shifted = NULL;
3565 cgbr->cone = NULL;
3566 cgbr->tab = isl_tab_from_basic_set(dom, 1);
3567 cgbr->tab = isl_tab_init_samples(cgbr->tab);
3568 if (!cgbr->tab)
3569 goto error;
3570 check_gbr_integer_feasible(cgbr);
3572 return &cgbr->context;
3573 error:
3574 cgbr->context.op->free(&cgbr->context);
3575 return NULL;
3578 /* Allocate a context corresponding to "dom".
3579 * The representation specific fields are initialized by
3580 * isl_context_lex_alloc or isl_context_gbr_alloc.
3581 * The shared "n_unknown" field is initialized to the number
3582 * of final unknown integer divisions in "dom".
3584 static struct isl_context *isl_context_alloc(__isl_keep isl_basic_set *dom)
3586 struct isl_context *context;
3587 int first;
3589 if (!dom)
3590 return NULL;
3592 if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3593 context = isl_context_lex_alloc(dom);
3594 else
3595 context = isl_context_gbr_alloc(dom);
3597 if (!context)
3598 return NULL;
3600 first = isl_basic_set_first_unknown_div(dom);
3601 if (first < 0)
3602 return context->op->free(context);
3603 context->n_unknown = isl_basic_set_dim(dom, isl_dim_div) - first;
3605 return context;
3608 /* Initialize some common fields of "sol", which keeps track
3609 * of the solution of an optimization problem on "bmap" over
3610 * the domain "dom".
3611 * If "max" is set, then a maximization problem is being solved, rather than
3612 * a minimization problem, which means that the variables in the
3613 * tableau have value "M - x" rather than "M + x".
3615 static isl_stat sol_init(struct isl_sol *sol, __isl_keep isl_basic_map *bmap,
3616 __isl_keep isl_basic_set *dom, int max)
3618 sol->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3619 sol->dec_level.callback.run = &sol_dec_level_wrap;
3620 sol->dec_level.sol = sol;
3621 sol->max = max;
3622 sol->n_out = isl_basic_map_dim(bmap, isl_dim_out);
3623 sol->space = isl_basic_map_get_space(bmap);
3625 sol->context = isl_context_alloc(dom);
3626 if (!sol->space || !sol->context)
3627 return isl_stat_error;
3629 return isl_stat_ok;
3632 /* Construct an isl_sol_map structure for accumulating the solution.
3633 * If track_empty is set, then we also keep track of the parts
3634 * of the context where there is no solution.
3635 * If max is set, then we are solving a maximization, rather than
3636 * a minimization problem, which means that the variables in the
3637 * tableau have value "M - x" rather than "M + x".
3639 static struct isl_sol *sol_map_init(__isl_keep isl_basic_map *bmap,
3640 __isl_take isl_basic_set *dom, int track_empty, int max)
3642 struct isl_sol_map *sol_map = NULL;
3643 isl_space *space;
3645 if (!bmap)
3646 goto error;
3648 sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3649 if (!sol_map)
3650 goto error;
3652 sol_map->sol.free = &sol_map_free;
3653 if (sol_init(&sol_map->sol, bmap, dom, max) < 0)
3654 goto error;
3655 sol_map->sol.add = &sol_map_add_wrap;
3656 sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3657 space = isl_space_copy(sol_map->sol.space);
3658 sol_map->map = isl_map_alloc_space(space, 1, ISL_MAP_DISJOINT);
3659 if (!sol_map->map)
3660 goto error;
3662 if (track_empty) {
3663 sol_map->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
3664 1, ISL_SET_DISJOINT);
3665 if (!sol_map->empty)
3666 goto error;
3669 isl_basic_set_free(dom);
3670 return &sol_map->sol;
3671 error:
3672 isl_basic_set_free(dom);
3673 sol_free(&sol_map->sol);
3674 return NULL;
3677 /* Check whether all coefficients of (non-parameter) variables
3678 * are non-positive, meaning that no pivots can be performed on the row.
3680 static int is_critical(struct isl_tab *tab, int row)
3682 int j;
3683 unsigned off = 2 + tab->M;
3685 for (j = tab->n_dead; j < tab->n_col; ++j) {
3686 if (col_is_parameter_var(tab, j))
3687 continue;
3689 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3690 return 0;
3693 return 1;
3696 /* Check whether the inequality represented by vec is strict over the integers,
3697 * i.e., there are no integer values satisfying the constraint with
3698 * equality. This happens if the gcd of the coefficients is not a divisor
3699 * of the constant term. If so, scale the constraint down by the gcd
3700 * of the coefficients.
3702 static int is_strict(struct isl_vec *vec)
3704 isl_int gcd;
3705 int strict = 0;
3707 isl_int_init(gcd);
3708 isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3709 if (!isl_int_is_one(gcd)) {
3710 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3711 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3712 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3714 isl_int_clear(gcd);
3716 return strict;
3719 /* Determine the sign of the given row of the main tableau.
3720 * The result is one of
3721 * isl_tab_row_pos: always non-negative; no pivot needed
3722 * isl_tab_row_neg: always non-positive; pivot
3723 * isl_tab_row_any: can be both positive and negative; split
3725 * We first handle some simple cases
3726 * - the row sign may be known already
3727 * - the row may be obviously non-negative
3728 * - the parametric constant may be equal to that of another row
3729 * for which we know the sign. This sign will be either "pos" or
3730 * "any". If it had been "neg" then we would have pivoted before.
3732 * If none of these cases hold, we check the value of the row for each
3733 * of the currently active samples. Based on the signs of these values
3734 * we make an initial determination of the sign of the row.
3736 * all zero -> unk(nown)
3737 * all non-negative -> pos
3738 * all non-positive -> neg
3739 * both negative and positive -> all
3741 * If we end up with "all", we are done.
3742 * Otherwise, we perform a check for positive and/or negative
3743 * values as follows.
3745 * samples neg unk pos
3746 * <0 ? Y N Y N
3747 * pos any pos
3748 * >0 ? Y N Y N
3749 * any neg any neg
3751 * There is no special sign for "zero", because we can usually treat zero
3752 * as either non-negative or non-positive, whatever works out best.
3753 * However, if the row is "critical", meaning that pivoting is impossible
3754 * then we don't want to limp zero with the non-positive case, because
3755 * then we we would lose the solution for those values of the parameters
3756 * where the value of the row is zero. Instead, we treat 0 as non-negative
3757 * ensuring a split if the row can attain both zero and negative values.
3758 * The same happens when the original constraint was one that could not
3759 * be satisfied with equality by any integer values of the parameters.
3760 * In this case, we normalize the constraint, but then a value of zero
3761 * for the normalized constraint is actually a positive value for the
3762 * original constraint, so again we need to treat zero as non-negative.
3763 * In both these cases, we have the following decision tree instead:
3765 * all non-negative -> pos
3766 * all negative -> neg
3767 * both negative and non-negative -> all
3769 * samples neg pos
3770 * <0 ? Y N
3771 * any pos
3772 * >=0 ? Y N
3773 * any neg
3775 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3776 struct isl_sol *sol, int row)
3778 struct isl_vec *ineq = NULL;
3779 enum isl_tab_row_sign res = isl_tab_row_unknown;
3780 int critical;
3781 int strict;
3782 int row2;
3784 if (tab->row_sign[row] != isl_tab_row_unknown)
3785 return tab->row_sign[row];
3786 if (is_obviously_nonneg(tab, row))
3787 return isl_tab_row_pos;
3788 for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3789 if (tab->row_sign[row2] == isl_tab_row_unknown)
3790 continue;
3791 if (identical_parameter_line(tab, row, row2))
3792 return tab->row_sign[row2];
3795 critical = is_critical(tab, row);
3797 ineq = get_row_parameter_ineq(tab, row);
3798 if (!ineq)
3799 goto error;
3801 strict = is_strict(ineq);
3803 res = sol->context->op->ineq_sign(sol->context, ineq->el,
3804 critical || strict);
3806 if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3807 /* test for negative values */
3808 int feasible;
3809 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3810 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3812 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3813 if (feasible < 0)
3814 goto error;
3815 if (!feasible)
3816 res = isl_tab_row_pos;
3817 else
3818 res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3819 : isl_tab_row_any;
3820 if (res == isl_tab_row_neg) {
3821 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3822 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3826 if (res == isl_tab_row_neg) {
3827 /* test for positive values */
3828 int feasible;
3829 if (!critical && !strict)
3830 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3832 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3833 if (feasible < 0)
3834 goto error;
3835 if (feasible)
3836 res = isl_tab_row_any;
3839 isl_vec_free(ineq);
3840 return res;
3841 error:
3842 isl_vec_free(ineq);
3843 return isl_tab_row_unknown;
3846 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3848 /* Find solutions for values of the parameters that satisfy the given
3849 * inequality.
3851 * We currently take a snapshot of the context tableau that is reset
3852 * when we return from this function, while we make a copy of the main
3853 * tableau, leaving the original main tableau untouched.
3854 * These are fairly arbitrary choices. Making a copy also of the context
3855 * tableau would obviate the need to undo any changes made to it later,
3856 * while taking a snapshot of the main tableau could reduce memory usage.
3857 * If we were to switch to taking a snapshot of the main tableau,
3858 * we would have to keep in mind that we need to save the row signs
3859 * and that we need to do this before saving the current basis
3860 * such that the basis has been restore before we restore the row signs.
3862 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3864 void *saved;
3866 if (!sol->context)
3867 goto error;
3868 saved = sol->context->op->save(sol->context);
3870 tab = isl_tab_dup(tab);
3871 if (!tab)
3872 goto error;
3874 sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3876 find_solutions(sol, tab);
3878 if (!sol->error)
3879 sol->context->op->restore(sol->context, saved);
3880 else
3881 sol->context->op->discard(saved);
3882 return;
3883 error:
3884 sol->error = 1;
3887 /* Record the absence of solutions for those values of the parameters
3888 * that do not satisfy the given inequality with equality.
3890 static void no_sol_in_strict(struct isl_sol *sol,
3891 struct isl_tab *tab, struct isl_vec *ineq)
3893 int empty;
3894 void *saved;
3896 if (!sol->context || sol->error)
3897 goto error;
3898 saved = sol->context->op->save(sol->context);
3900 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3902 sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3903 if (!sol->context)
3904 goto error;
3906 empty = tab->empty;
3907 tab->empty = 1;
3908 sol_add(sol, tab);
3909 tab->empty = empty;
3911 isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3913 sol->context->op->restore(sol->context, saved);
3914 return;
3915 error:
3916 sol->error = 1;
3919 /* Reset all row variables that are marked to have a sign that may
3920 * be both positive and negative to have an unknown sign.
3922 static void reset_any_to_unknown(struct isl_tab *tab)
3924 int row;
3926 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3927 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3928 continue;
3929 if (tab->row_sign[row] == isl_tab_row_any)
3930 tab->row_sign[row] = isl_tab_row_unknown;
3934 /* Compute the lexicographic minimum of the set represented by the main
3935 * tableau "tab" within the context "sol->context_tab".
3936 * On entry the sample value of the main tableau is lexicographically
3937 * less than or equal to this lexicographic minimum.
3938 * Pivots are performed until a feasible point is found, which is then
3939 * necessarily equal to the minimum, or until the tableau is found to
3940 * be infeasible. Some pivots may need to be performed for only some
3941 * feasible values of the context tableau. If so, the context tableau
3942 * is split into a part where the pivot is needed and a part where it is not.
3944 * Whenever we enter the main loop, the main tableau is such that no
3945 * "obvious" pivots need to be performed on it, where "obvious" means
3946 * that the given row can be seen to be negative without looking at
3947 * the context tableau. In particular, for non-parametric problems,
3948 * no pivots need to be performed on the main tableau.
3949 * The caller of find_solutions is responsible for making this property
3950 * hold prior to the first iteration of the loop, while restore_lexmin
3951 * is called before every other iteration.
3953 * Inside the main loop, we first examine the signs of the rows of
3954 * the main tableau within the context of the context tableau.
3955 * If we find a row that is always non-positive for all values of
3956 * the parameters satisfying the context tableau and negative for at
3957 * least one value of the parameters, we perform the appropriate pivot
3958 * and start over. An exception is the case where no pivot can be
3959 * performed on the row. In this case, we require that the sign of
3960 * the row is negative for all values of the parameters (rather than just
3961 * non-positive). This special case is handled inside row_sign, which
3962 * will say that the row can have any sign if it determines that it can
3963 * attain both negative and zero values.
3965 * If we can't find a row that always requires a pivot, but we can find
3966 * one or more rows that require a pivot for some values of the parameters
3967 * (i.e., the row can attain both positive and negative signs), then we split
3968 * the context tableau into two parts, one where we force the sign to be
3969 * non-negative and one where we force is to be negative.
3970 * The non-negative part is handled by a recursive call (through find_in_pos).
3971 * Upon returning from this call, we continue with the negative part and
3972 * perform the required pivot.
3974 * If no such rows can be found, all rows are non-negative and we have
3975 * found a (rational) feasible point. If we only wanted a rational point
3976 * then we are done.
3977 * Otherwise, we check if all values of the sample point of the tableau
3978 * are integral for the variables. If so, we have found the minimal
3979 * integral point and we are done.
3980 * If the sample point is not integral, then we need to make a distinction
3981 * based on whether the constant term is non-integral or the coefficients
3982 * of the parameters. Furthermore, in order to decide how to handle
3983 * the non-integrality, we also need to know whether the coefficients
3984 * of the other columns in the tableau are integral. This leads
3985 * to the following table. The first two rows do not correspond
3986 * to a non-integral sample point and are only mentioned for completeness.
3988 * constant parameters other
3990 * int int int |
3991 * int int rat | -> no problem
3993 * rat int int -> fail
3995 * rat int rat -> cut
3997 * int rat rat |
3998 * rat rat rat | -> parametric cut
4000 * int rat int |
4001 * rat rat int | -> split context
4003 * If the parametric constant is completely integral, then there is nothing
4004 * to be done. If the constant term is non-integral, but all the other
4005 * coefficient are integral, then there is nothing that can be done
4006 * and the tableau has no integral solution.
4007 * If, on the other hand, one or more of the other columns have rational
4008 * coefficients, but the parameter coefficients are all integral, then
4009 * we can perform a regular (non-parametric) cut.
4010 * Finally, if there is any parameter coefficient that is non-integral,
4011 * then we need to involve the context tableau. There are two cases here.
4012 * If at least one other column has a rational coefficient, then we
4013 * can perform a parametric cut in the main tableau by adding a new
4014 * integer division in the context tableau.
4015 * If all other columns have integral coefficients, then we need to
4016 * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
4017 * is always integral. We do this by introducing an integer division
4018 * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
4019 * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
4020 * Since q is expressed in the tableau as
4021 * c + \sum a_i y_i - m q >= 0
4022 * -c - \sum a_i y_i + m q + m - 1 >= 0
4023 * it is sufficient to add the inequality
4024 * -c - \sum a_i y_i + m q >= 0
4025 * In the part of the context where this inequality does not hold, the
4026 * main tableau is marked as being empty.
4028 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
4030 struct isl_context *context;
4031 int r;
4033 if (!tab || sol->error)
4034 goto error;
4036 context = sol->context;
4038 if (tab->empty)
4039 goto done;
4040 if (context->op->is_empty(context))
4041 goto done;
4043 for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
4044 int flags;
4045 int row;
4046 enum isl_tab_row_sign sgn;
4047 int split = -1;
4048 int n_split = 0;
4050 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4051 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
4052 continue;
4053 sgn = row_sign(tab, sol, row);
4054 if (!sgn)
4055 goto error;
4056 tab->row_sign[row] = sgn;
4057 if (sgn == isl_tab_row_any)
4058 n_split++;
4059 if (sgn == isl_tab_row_any && split == -1)
4060 split = row;
4061 if (sgn == isl_tab_row_neg)
4062 break;
4064 if (row < tab->n_row)
4065 continue;
4066 if (split != -1) {
4067 struct isl_vec *ineq;
4068 if (n_split != 1)
4069 split = context->op->best_split(context, tab);
4070 if (split < 0)
4071 goto error;
4072 ineq = get_row_parameter_ineq(tab, split);
4073 if (!ineq)
4074 goto error;
4075 is_strict(ineq);
4076 reset_any_to_unknown(tab);
4077 tab->row_sign[split] = isl_tab_row_pos;
4078 sol_inc_level(sol);
4079 find_in_pos(sol, tab, ineq->el);
4080 tab->row_sign[split] = isl_tab_row_neg;
4081 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4082 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
4083 if (!sol->error)
4084 context->op->add_ineq(context, ineq->el, 0, 1);
4085 isl_vec_free(ineq);
4086 if (sol->error)
4087 goto error;
4088 continue;
4090 if (tab->rational)
4091 break;
4092 row = first_non_integer_row(tab, &flags);
4093 if (row < 0)
4094 break;
4095 if (ISL_FL_ISSET(flags, I_PAR)) {
4096 if (ISL_FL_ISSET(flags, I_VAR)) {
4097 if (isl_tab_mark_empty(tab) < 0)
4098 goto error;
4099 break;
4101 row = add_cut(tab, row);
4102 } else if (ISL_FL_ISSET(flags, I_VAR)) {
4103 struct isl_vec *div;
4104 struct isl_vec *ineq;
4105 int d;
4106 div = get_row_split_div(tab, row);
4107 if (!div)
4108 goto error;
4109 d = context->op->get_div(context, tab, div);
4110 isl_vec_free(div);
4111 if (d < 0)
4112 goto error;
4113 ineq = ineq_for_div(context->op->peek_basic_set(context), d);
4114 if (!ineq)
4115 goto error;
4116 sol_inc_level(sol);
4117 no_sol_in_strict(sol, tab, ineq);
4118 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4119 context->op->add_ineq(context, ineq->el, 1, 1);
4120 isl_vec_free(ineq);
4121 if (sol->error || !context->op->is_ok(context))
4122 goto error;
4123 tab = set_row_cst_to_div(tab, row, d);
4124 if (context->op->is_empty(context))
4125 break;
4126 } else
4127 row = add_parametric_cut(tab, row, context);
4128 if (row < 0)
4129 goto error;
4131 if (r < 0)
4132 goto error;
4133 done:
4134 sol_add(sol, tab);
4135 isl_tab_free(tab);
4136 return;
4137 error:
4138 isl_tab_free(tab);
4139 sol->error = 1;
4142 /* Does "sol" contain a pair of partial solutions that could potentially
4143 * be merged?
4145 * We currently only check that "sol" is not in an error state
4146 * and that there are at least two partial solutions of which the final two
4147 * are defined at the same level.
4149 static int sol_has_mergeable_solutions(struct isl_sol *sol)
4151 if (sol->error)
4152 return 0;
4153 if (!sol->partial)
4154 return 0;
4155 if (!sol->partial->next)
4156 return 0;
4157 return sol->partial->level == sol->partial->next->level;
4160 /* Compute the lexicographic minimum of the set represented by the main
4161 * tableau "tab" within the context "sol->context_tab".
4163 * As a preprocessing step, we first transfer all the purely parametric
4164 * equalities from the main tableau to the context tableau, i.e.,
4165 * parameters that have been pivoted to a row.
4166 * These equalities are ignored by the main algorithm, because the
4167 * corresponding rows may not be marked as being non-negative.
4168 * In parts of the context where the added equality does not hold,
4169 * the main tableau is marked as being empty.
4171 * Before we embark on the actual computation, we save a copy
4172 * of the context. When we return, we check if there are any
4173 * partial solutions that can potentially be merged. If so,
4174 * we perform a rollback to the initial state of the context.
4175 * The merging of partial solutions happens inside calls to
4176 * sol_dec_level that are pushed onto the undo stack of the context.
4177 * If there are no partial solutions that can potentially be merged
4178 * then the rollback is skipped as it would just be wasted effort.
4180 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
4182 int row;
4183 void *saved;
4185 if (!tab)
4186 goto error;
4188 sol->level = 0;
4190 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4191 int p;
4192 struct isl_vec *eq;
4194 if (!row_is_parameter_var(tab, row))
4195 continue;
4196 if (tab->row_var[row] < tab->n_param)
4197 p = tab->row_var[row];
4198 else
4199 p = tab->row_var[row]
4200 + tab->n_param - (tab->n_var - tab->n_div);
4202 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
4203 if (!eq)
4204 goto error;
4205 get_row_parameter_line(tab, row, eq->el);
4206 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
4207 eq = isl_vec_normalize(eq);
4209 sol_inc_level(sol);
4210 no_sol_in_strict(sol, tab, eq);
4212 isl_seq_neg(eq->el, eq->el, eq->size);
4213 sol_inc_level(sol);
4214 no_sol_in_strict(sol, tab, eq);
4215 isl_seq_neg(eq->el, eq->el, eq->size);
4217 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
4219 isl_vec_free(eq);
4221 if (isl_tab_mark_redundant(tab, row) < 0)
4222 goto error;
4224 if (sol->context->op->is_empty(sol->context))
4225 break;
4227 row = tab->n_redundant - 1;
4230 saved = sol->context->op->save(sol->context);
4232 find_solutions(sol, tab);
4234 if (sol_has_mergeable_solutions(sol))
4235 sol->context->op->restore(sol->context, saved);
4236 else
4237 sol->context->op->discard(saved);
4239 sol->level = 0;
4240 sol_pop(sol);
4242 return;
4243 error:
4244 isl_tab_free(tab);
4245 sol->error = 1;
4248 /* Check if integer division "div" of "dom" also occurs in "bmap".
4249 * If so, return its position within the divs.
4250 * If not, return -1.
4252 static int find_context_div(struct isl_basic_map *bmap,
4253 struct isl_basic_set *dom, unsigned div)
4255 int i;
4256 unsigned b_dim = isl_space_dim(bmap->dim, isl_dim_all);
4257 unsigned d_dim = isl_space_dim(dom->dim, isl_dim_all);
4259 if (isl_int_is_zero(dom->div[div][0]))
4260 return -1;
4261 if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
4262 return -1;
4264 for (i = 0; i < bmap->n_div; ++i) {
4265 if (isl_int_is_zero(bmap->div[i][0]))
4266 continue;
4267 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
4268 (b_dim - d_dim) + bmap->n_div) != -1)
4269 continue;
4270 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
4271 return i;
4273 return -1;
4276 /* The correspondence between the variables in the main tableau,
4277 * the context tableau, and the input map and domain is as follows.
4278 * The first n_param and the last n_div variables of the main tableau
4279 * form the variables of the context tableau.
4280 * In the basic map, these n_param variables correspond to the
4281 * parameters and the input dimensions. In the domain, they correspond
4282 * to the parameters and the set dimensions.
4283 * The n_div variables correspond to the integer divisions in the domain.
4284 * To ensure that everything lines up, we may need to copy some of the
4285 * integer divisions of the domain to the map. These have to be placed
4286 * in the same order as those in the context and they have to be placed
4287 * after any other integer divisions that the map may have.
4288 * This function performs the required reordering.
4290 static __isl_give isl_basic_map *align_context_divs(
4291 __isl_take isl_basic_map *bmap, __isl_keep isl_basic_set *dom)
4293 int i;
4294 int common = 0;
4295 int other;
4297 for (i = 0; i < dom->n_div; ++i)
4298 if (find_context_div(bmap, dom, i) != -1)
4299 common++;
4300 other = bmap->n_div - common;
4301 if (dom->n_div - common > 0) {
4302 bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
4303 dom->n_div - common, 0, 0);
4304 if (!bmap)
4305 return NULL;
4307 for (i = 0; i < dom->n_div; ++i) {
4308 int pos = find_context_div(bmap, dom, i);
4309 if (pos < 0) {
4310 pos = isl_basic_map_alloc_div(bmap);
4311 if (pos < 0)
4312 goto error;
4313 isl_int_set_si(bmap->div[pos][0], 0);
4315 if (pos != other + i)
4316 isl_basic_map_swap_div(bmap, pos, other + i);
4318 return bmap;
4319 error:
4320 isl_basic_map_free(bmap);
4321 return NULL;
4324 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4325 * some obvious symmetries.
4327 * We make sure the divs in the domain are properly ordered,
4328 * because they will be added one by one in the given order
4329 * during the construction of the solution map.
4330 * Furthermore, make sure that the known integer divisions
4331 * appear before any unknown integer division because the solution
4332 * may depend on the known integer divisions, while anything that
4333 * depends on any variable starting from the first unknown integer
4334 * division is ignored in sol_pma_add.
4336 static struct isl_sol *basic_map_partial_lexopt_base_sol(
4337 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4338 __isl_give isl_set **empty, int max,
4339 struct isl_sol *(*init)(__isl_keep isl_basic_map *bmap,
4340 __isl_take isl_basic_set *dom, int track_empty, int max))
4342 struct isl_tab *tab;
4343 struct isl_sol *sol = NULL;
4344 struct isl_context *context;
4346 if (dom->n_div) {
4347 dom = isl_basic_set_sort_divs(dom);
4348 bmap = align_context_divs(bmap, dom);
4350 sol = init(bmap, dom, !!empty, max);
4351 if (!sol)
4352 goto error;
4354 context = sol->context;
4355 if (isl_basic_set_plain_is_empty(context->op->peek_basic_set(context)))
4356 /* nothing */;
4357 else if (isl_basic_map_plain_is_empty(bmap)) {
4358 if (sol->add_empty)
4359 sol->add_empty(sol,
4360 isl_basic_set_copy(context->op->peek_basic_set(context)));
4361 } else {
4362 tab = tab_for_lexmin(bmap,
4363 context->op->peek_basic_set(context), 1, max);
4364 tab = context->op->detect_nonnegative_parameters(context, tab);
4365 find_solutions_main(sol, tab);
4367 if (sol->error)
4368 goto error;
4370 isl_basic_map_free(bmap);
4371 return sol;
4372 error:
4373 sol_free(sol);
4374 isl_basic_map_free(bmap);
4375 return NULL;
4378 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4379 * some obvious symmetries.
4381 * We call basic_map_partial_lexopt_base_sol and extract the results.
4383 static __isl_give isl_map *basic_map_partial_lexopt_base(
4384 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4385 __isl_give isl_set **empty, int max)
4387 isl_map *result = NULL;
4388 struct isl_sol *sol;
4389 struct isl_sol_map *sol_map;
4391 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
4392 &sol_map_init);
4393 if (!sol)
4394 return NULL;
4395 sol_map = (struct isl_sol_map *) sol;
4397 result = isl_map_copy(sol_map->map);
4398 if (empty)
4399 *empty = isl_set_copy(sol_map->empty);
4400 sol_free(&sol_map->sol);
4401 return result;
4404 /* Return a count of the number of occurrences of the "n" first
4405 * variables in the inequality constraints of "bmap".
4407 static __isl_give int *count_occurrences(__isl_keep isl_basic_map *bmap,
4408 int n)
4410 int i, j;
4411 isl_ctx *ctx;
4412 int *occurrences;
4414 if (!bmap)
4415 return NULL;
4416 ctx = isl_basic_map_get_ctx(bmap);
4417 occurrences = isl_calloc_array(ctx, int, n);
4418 if (!occurrences)
4419 return NULL;
4421 for (i = 0; i < bmap->n_ineq; ++i) {
4422 for (j = 0; j < n; ++j) {
4423 if (!isl_int_is_zero(bmap->ineq[i][1 + j]))
4424 occurrences[j]++;
4428 return occurrences;
4431 /* Do all of the "n" variables with non-zero coefficients in "c"
4432 * occur in exactly a single constraint.
4433 * "occurrences" is an array of length "n" containing the number
4434 * of occurrences of each of the variables in the inequality constraints.
4436 static int single_occurrence(int n, isl_int *c, int *occurrences)
4438 int i;
4440 for (i = 0; i < n; ++i) {
4441 if (isl_int_is_zero(c[i]))
4442 continue;
4443 if (occurrences[i] != 1)
4444 return 0;
4447 return 1;
4450 /* Do all of the "n" initial variables that occur in inequality constraint
4451 * "ineq" of "bmap" only occur in that constraint?
4453 static int all_single_occurrence(__isl_keep isl_basic_map *bmap, int ineq,
4454 int n)
4456 int i, j;
4458 for (i = 0; i < n; ++i) {
4459 if (isl_int_is_zero(bmap->ineq[ineq][1 + i]))
4460 continue;
4461 for (j = 0; j < bmap->n_ineq; ++j) {
4462 if (j == ineq)
4463 continue;
4464 if (!isl_int_is_zero(bmap->ineq[j][1 + i]))
4465 return 0;
4469 return 1;
4472 /* Structure used during detection of parallel constraints.
4473 * n_in: number of "input" variables: isl_dim_param + isl_dim_in
4474 * n_out: number of "output" variables: isl_dim_out + isl_dim_div
4475 * val: the coefficients of the output variables
4477 struct isl_constraint_equal_info {
4478 unsigned n_in;
4479 unsigned n_out;
4480 isl_int *val;
4483 /* Check whether the coefficients of the output variables
4484 * of the constraint in "entry" are equal to info->val.
4486 static int constraint_equal(const void *entry, const void *val)
4488 isl_int **row = (isl_int **)entry;
4489 const struct isl_constraint_equal_info *info = val;
4491 return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
4494 /* Check whether "bmap" has a pair of constraints that have
4495 * the same coefficients for the output variables.
4496 * Note that the coefficients of the existentially quantified
4497 * variables need to be zero since the existentially quantified
4498 * of the result are usually not the same as those of the input.
4499 * Furthermore, check that each of the input variables that occur
4500 * in those constraints does not occur in any other constraint.
4501 * If so, return true and return the row indices of the two constraints
4502 * in *first and *second.
4504 static isl_bool parallel_constraints(__isl_keep isl_basic_map *bmap,
4505 int *first, int *second)
4507 int i;
4508 isl_ctx *ctx;
4509 int *occurrences = NULL;
4510 struct isl_hash_table *table = NULL;
4511 struct isl_hash_table_entry *entry;
4512 struct isl_constraint_equal_info info;
4513 unsigned n_out;
4514 unsigned n_div;
4516 ctx = isl_basic_map_get_ctx(bmap);
4517 table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4518 if (!table)
4519 goto error;
4521 info.n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4522 isl_basic_map_dim(bmap, isl_dim_in);
4523 occurrences = count_occurrences(bmap, info.n_in);
4524 if (info.n_in && !occurrences)
4525 goto error;
4526 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4527 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4528 info.n_out = n_out + n_div;
4529 for (i = 0; i < bmap->n_ineq; ++i) {
4530 uint32_t hash;
4532 info.val = bmap->ineq[i] + 1 + info.n_in;
4533 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4534 continue;
4535 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4536 continue;
4537 if (!single_occurrence(info.n_in, bmap->ineq[i] + 1,
4538 occurrences))
4539 continue;
4540 hash = isl_seq_get_hash(info.val, info.n_out);
4541 entry = isl_hash_table_find(ctx, table, hash,
4542 constraint_equal, &info, 1);
4543 if (!entry)
4544 goto error;
4545 if (entry->data)
4546 break;
4547 entry->data = &bmap->ineq[i];
4550 if (i < bmap->n_ineq) {
4551 *first = ((isl_int **)entry->data) - bmap->ineq;
4552 *second = i;
4555 isl_hash_table_free(ctx, table);
4556 free(occurrences);
4558 return i < bmap->n_ineq;
4559 error:
4560 isl_hash_table_free(ctx, table);
4561 free(occurrences);
4562 return isl_bool_error;
4565 /* Given a set of upper bounds in "var", add constraints to "bset"
4566 * that make the i-th bound smallest.
4568 * In particular, if there are n bounds b_i, then add the constraints
4570 * b_i <= b_j for j > i
4571 * b_i < b_j for j < i
4573 static __isl_give isl_basic_set *select_minimum(__isl_take isl_basic_set *bset,
4574 __isl_keep isl_mat *var, int i)
4576 isl_ctx *ctx;
4577 int j, k;
4579 ctx = isl_mat_get_ctx(var);
4581 for (j = 0; j < var->n_row; ++j) {
4582 if (j == i)
4583 continue;
4584 k = isl_basic_set_alloc_inequality(bset);
4585 if (k < 0)
4586 goto error;
4587 isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4588 ctx->negone, var->row[i], var->n_col);
4589 isl_int_set_si(bset->ineq[k][var->n_col], 0);
4590 if (j < i)
4591 isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4594 bset = isl_basic_set_finalize(bset);
4596 return bset;
4597 error:
4598 isl_basic_set_free(bset);
4599 return NULL;
4602 /* Given a set of upper bounds on the last "input" variable m,
4603 * construct a set that assigns the minimal upper bound to m, i.e.,
4604 * construct a set that divides the space into cells where one
4605 * of the upper bounds is smaller than all the others and assign
4606 * this upper bound to m.
4608 * In particular, if there are n bounds b_i, then the result
4609 * consists of n basic sets, each one of the form
4611 * m = b_i
4612 * b_i <= b_j for j > i
4613 * b_i < b_j for j < i
4615 static __isl_give isl_set *set_minimum(__isl_take isl_space *dim,
4616 __isl_take isl_mat *var)
4618 int i, k;
4619 isl_basic_set *bset = NULL;
4620 isl_set *set = NULL;
4622 if (!dim || !var)
4623 goto error;
4625 set = isl_set_alloc_space(isl_space_copy(dim),
4626 var->n_row, ISL_SET_DISJOINT);
4628 for (i = 0; i < var->n_row; ++i) {
4629 bset = isl_basic_set_alloc_space(isl_space_copy(dim), 0,
4630 1, var->n_row - 1);
4631 k = isl_basic_set_alloc_equality(bset);
4632 if (k < 0)
4633 goto error;
4634 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4635 isl_int_set_si(bset->eq[k][var->n_col], -1);
4636 bset = select_minimum(bset, var, i);
4637 set = isl_set_add_basic_set(set, bset);
4640 isl_space_free(dim);
4641 isl_mat_free(var);
4642 return set;
4643 error:
4644 isl_basic_set_free(bset);
4645 isl_set_free(set);
4646 isl_space_free(dim);
4647 isl_mat_free(var);
4648 return NULL;
4651 /* Given that the last input variable of "bmap" represents the minimum
4652 * of the bounds in "cst", check whether we need to split the domain
4653 * based on which bound attains the minimum.
4655 * A split is needed when the minimum appears in an integer division
4656 * or in an equality. Otherwise, it is only needed if it appears in
4657 * an upper bound that is different from the upper bounds on which it
4658 * is defined.
4660 static isl_bool need_split_basic_map(__isl_keep isl_basic_map *bmap,
4661 __isl_keep isl_mat *cst)
4663 int i, j;
4664 unsigned total;
4665 unsigned pos;
4667 pos = cst->n_col - 1;
4668 total = isl_basic_map_dim(bmap, isl_dim_all);
4670 for (i = 0; i < bmap->n_div; ++i)
4671 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4672 return isl_bool_true;
4674 for (i = 0; i < bmap->n_eq; ++i)
4675 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4676 return isl_bool_true;
4678 for (i = 0; i < bmap->n_ineq; ++i) {
4679 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4680 continue;
4681 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4682 return isl_bool_true;
4683 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4684 total - pos - 1) >= 0)
4685 return isl_bool_true;
4687 for (j = 0; j < cst->n_row; ++j)
4688 if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4689 break;
4690 if (j >= cst->n_row)
4691 return isl_bool_true;
4694 return isl_bool_false;
4697 /* Given that the last set variable of "bset" represents the minimum
4698 * of the bounds in "cst", check whether we need to split the domain
4699 * based on which bound attains the minimum.
4701 * We simply call need_split_basic_map here. This is safe because
4702 * the position of the minimum is computed from "cst" and not
4703 * from "bmap".
4705 static isl_bool need_split_basic_set(__isl_keep isl_basic_set *bset,
4706 __isl_keep isl_mat *cst)
4708 return need_split_basic_map(bset_to_bmap(bset), cst);
4711 /* Given that the last set variable of "set" represents the minimum
4712 * of the bounds in "cst", check whether we need to split the domain
4713 * based on which bound attains the minimum.
4715 static isl_bool need_split_set(__isl_keep isl_set *set, __isl_keep isl_mat *cst)
4717 int i;
4719 for (i = 0; i < set->n; ++i) {
4720 isl_bool split;
4722 split = need_split_basic_set(set->p[i], cst);
4723 if (split < 0 || split)
4724 return split;
4727 return isl_bool_false;
4730 /* Given a set of which the last set variable is the minimum
4731 * of the bounds in "cst", split each basic set in the set
4732 * in pieces where one of the bounds is (strictly) smaller than the others.
4733 * This subdivision is given in "min_expr".
4734 * The variable is subsequently projected out.
4736 * We only do the split when it is needed.
4737 * For example if the last input variable m = min(a,b) and the only
4738 * constraints in the given basic set are lower bounds on m,
4739 * i.e., l <= m = min(a,b), then we can simply project out m
4740 * to obtain l <= a and l <= b, without having to split on whether
4741 * m is equal to a or b.
4743 static __isl_give isl_set *split(__isl_take isl_set *empty,
4744 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4746 int n_in;
4747 int i;
4748 isl_space *dim;
4749 isl_set *res;
4751 if (!empty || !min_expr || !cst)
4752 goto error;
4754 n_in = isl_set_dim(empty, isl_dim_set);
4755 dim = isl_set_get_space(empty);
4756 dim = isl_space_drop_dims(dim, isl_dim_set, n_in - 1, 1);
4757 res = isl_set_empty(dim);
4759 for (i = 0; i < empty->n; ++i) {
4760 isl_bool split;
4761 isl_set *set;
4763 set = isl_set_from_basic_set(isl_basic_set_copy(empty->p[i]));
4764 split = need_split_basic_set(empty->p[i], cst);
4765 if (split < 0)
4766 set = isl_set_free(set);
4767 else if (split)
4768 set = isl_set_intersect(set, isl_set_copy(min_expr));
4769 set = isl_set_remove_dims(set, isl_dim_set, n_in - 1, 1);
4771 res = isl_set_union_disjoint(res, set);
4774 isl_set_free(empty);
4775 isl_set_free(min_expr);
4776 isl_mat_free(cst);
4777 return res;
4778 error:
4779 isl_set_free(empty);
4780 isl_set_free(min_expr);
4781 isl_mat_free(cst);
4782 return NULL;
4785 /* Given a map of which the last input variable is the minimum
4786 * of the bounds in "cst", split each basic set in the set
4787 * in pieces where one of the bounds is (strictly) smaller than the others.
4788 * This subdivision is given in "min_expr".
4789 * The variable is subsequently projected out.
4791 * The implementation is essentially the same as that of "split".
4793 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4794 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4796 int n_in;
4797 int i;
4798 isl_space *dim;
4799 isl_map *res;
4801 if (!opt || !min_expr || !cst)
4802 goto error;
4804 n_in = isl_map_dim(opt, isl_dim_in);
4805 dim = isl_map_get_space(opt);
4806 dim = isl_space_drop_dims(dim, isl_dim_in, n_in - 1, 1);
4807 res = isl_map_empty(dim);
4809 for (i = 0; i < opt->n; ++i) {
4810 isl_map *map;
4811 isl_bool split;
4813 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4814 split = need_split_basic_map(opt->p[i], cst);
4815 if (split < 0)
4816 map = isl_map_free(map);
4817 else if (split)
4818 map = isl_map_intersect_domain(map,
4819 isl_set_copy(min_expr));
4820 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4822 res = isl_map_union_disjoint(res, map);
4825 isl_map_free(opt);
4826 isl_set_free(min_expr);
4827 isl_mat_free(cst);
4828 return res;
4829 error:
4830 isl_map_free(opt);
4831 isl_set_free(min_expr);
4832 isl_mat_free(cst);
4833 return NULL;
4836 static __isl_give isl_map *basic_map_partial_lexopt(
4837 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4838 __isl_give isl_set **empty, int max);
4840 /* This function is called from basic_map_partial_lexopt_symm.
4841 * The last variable of "bmap" and "dom" corresponds to the minimum
4842 * of the bounds in "cst". "map_space" is the space of the original
4843 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
4844 * is the space of the original domain.
4846 * We recursively call basic_map_partial_lexopt and then plug in
4847 * the definition of the minimum in the result.
4849 static __isl_give isl_map *basic_map_partial_lexopt_symm_core(
4850 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4851 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
4852 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
4854 isl_map *opt;
4855 isl_set *min_expr;
4857 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
4859 opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4861 if (empty) {
4862 *empty = split(*empty,
4863 isl_set_copy(min_expr), isl_mat_copy(cst));
4864 *empty = isl_set_reset_space(*empty, set_space);
4867 opt = split_domain(opt, min_expr, cst);
4868 opt = isl_map_reset_space(opt, map_space);
4870 return opt;
4873 /* Extract a domain from "bmap" for the purpose of computing
4874 * a lexicographic optimum.
4876 * This function is only called when the caller wants to compute a full
4877 * lexicographic optimum, i.e., without specifying a domain. In this case,
4878 * the caller is not interested in the part of the domain space where
4879 * there is no solution and the domain can be initialized to those constraints
4880 * of "bmap" that only involve the parameters and the input dimensions.
4881 * This relieves the parametric programming engine from detecting those
4882 * inequalities and transferring them to the context. More importantly,
4883 * it ensures that those inequalities are transferred first and not
4884 * intermixed with inequalities that actually split the domain.
4886 * If the caller does not require the absence of existentially quantified
4887 * variables in the result (i.e., if ISL_OPT_QE is not set in "flags"),
4888 * then the actual domain of "bmap" can be used. This ensures that
4889 * the domain does not need to be split at all just to separate out
4890 * pieces of the domain that do not have a solution from piece that do.
4891 * This domain cannot be used in general because it may involve
4892 * (unknown) existentially quantified variables which will then also
4893 * appear in the solution.
4895 static __isl_give isl_basic_set *extract_domain(__isl_keep isl_basic_map *bmap,
4896 unsigned flags)
4898 int n_div;
4899 int n_out;
4901 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4902 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4903 bmap = isl_basic_map_copy(bmap);
4904 if (ISL_FL_ISSET(flags, ISL_OPT_QE)) {
4905 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4906 isl_dim_div, 0, n_div);
4907 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4908 isl_dim_out, 0, n_out);
4910 return isl_basic_map_domain(bmap);
4913 #undef TYPE
4914 #define TYPE isl_map
4915 #undef SUFFIX
4916 #define SUFFIX
4917 #include "isl_tab_lexopt_templ.c"
4919 struct isl_sol_for {
4920 struct isl_sol sol;
4921 isl_stat (*fn)(__isl_take isl_basic_set *dom,
4922 __isl_take isl_aff_list *list, void *user);
4923 void *user;
4926 static void sol_for_free(struct isl_sol *sol)
4930 /* Add the solution identified by the tableau and the context tableau.
4931 * In particular, "dom" represents the context and "ma" expresses
4932 * the solution on that context.
4934 * See documentation of sol_add for more details.
4936 * Instead of constructing a basic map, this function calls a user
4937 * defined function with the current context as a basic set and
4938 * a list of affine expressions representing the relation between
4939 * the input and output. The space over which the affine expressions
4940 * are defined is the same as that of the domain. The number of
4941 * affine expressions in the list is equal to the number of output variables.
4943 static void sol_for_add(struct isl_sol_for *sol,
4944 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
4946 int i, n;
4947 isl_ctx *ctx;
4948 isl_aff *aff;
4949 isl_aff_list *list;
4951 if (sol->sol.error || !dom || !ma)
4952 goto error;
4954 ctx = isl_basic_set_get_ctx(dom);
4955 n = isl_multi_aff_dim(ma, isl_dim_out);
4956 list = isl_aff_list_alloc(ctx, n);
4957 for (i = 0; i < n; ++i) {
4958 aff = isl_multi_aff_get_aff(ma, i);
4959 list = isl_aff_list_add(list, aff);
4962 dom = isl_basic_set_finalize(dom);
4964 if (sol->fn(isl_basic_set_copy(dom), list, sol->user) < 0)
4965 goto error;
4967 isl_basic_set_free(dom);
4968 isl_multi_aff_free(ma);
4969 return;
4970 error:
4971 isl_basic_set_free(dom);
4972 isl_multi_aff_free(ma);
4973 sol->sol.error = 1;
4976 static void sol_for_add_wrap(struct isl_sol *sol,
4977 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
4979 sol_for_add((struct isl_sol_for *)sol, dom, ma);
4982 static struct isl_sol_for *sol_for_init(__isl_keep isl_basic_map *bmap, int max,
4983 isl_stat (*fn)(__isl_take isl_basic_set *dom,
4984 __isl_take isl_aff_list *list, void *user),
4985 void *user)
4987 struct isl_sol_for *sol_for = NULL;
4988 isl_space *dom_dim;
4989 struct isl_basic_set *dom = NULL;
4991 sol_for = isl_calloc_type(bmap->ctx, struct isl_sol_for);
4992 if (!sol_for)
4993 goto error;
4995 dom_dim = isl_space_domain(isl_space_copy(bmap->dim));
4996 dom = isl_basic_set_universe(dom_dim);
4998 sol_for->sol.free = &sol_for_free;
4999 if (sol_init(&sol_for->sol, bmap, dom, max) < 0)
5000 goto error;
5001 sol_for->fn = fn;
5002 sol_for->user = user;
5003 sol_for->sol.add = &sol_for_add_wrap;
5004 sol_for->sol.add_empty = NULL;
5006 isl_basic_set_free(dom);
5007 return sol_for;
5008 error:
5009 isl_basic_set_free(dom);
5010 sol_free(&sol_for->sol);
5011 return NULL;
5014 static void sol_for_find_solutions(struct isl_sol_for *sol_for,
5015 struct isl_tab *tab)
5017 find_solutions_main(&sol_for->sol, tab);
5020 isl_stat isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
5021 isl_stat (*fn)(__isl_take isl_basic_set *dom,
5022 __isl_take isl_aff_list *list, void *user),
5023 void *user)
5025 struct isl_sol_for *sol_for = NULL;
5027 bmap = isl_basic_map_copy(bmap);
5028 bmap = isl_basic_map_detect_equalities(bmap);
5029 if (!bmap)
5030 return isl_stat_error;
5032 sol_for = sol_for_init(bmap, max, fn, user);
5033 if (!sol_for)
5034 goto error;
5036 if (isl_basic_map_plain_is_empty(bmap))
5037 /* nothing */;
5038 else {
5039 struct isl_tab *tab;
5040 struct isl_context *context = sol_for->sol.context;
5041 tab = tab_for_lexmin(bmap,
5042 context->op->peek_basic_set(context), 1, max);
5043 tab = context->op->detect_nonnegative_parameters(context, tab);
5044 sol_for_find_solutions(sol_for, tab);
5045 if (sol_for->sol.error)
5046 goto error;
5049 sol_free(&sol_for->sol);
5050 isl_basic_map_free(bmap);
5051 return isl_stat_ok;
5052 error:
5053 sol_free(&sol_for->sol);
5054 isl_basic_map_free(bmap);
5055 return isl_stat_error;
5058 /* Extract the subsequence of the sample value of "tab"
5059 * starting at "pos" and of length "len".
5061 static __isl_give isl_vec *extract_sample_sequence(struct isl_tab *tab,
5062 int pos, int len)
5064 int i;
5065 isl_ctx *ctx;
5066 isl_vec *v;
5068 ctx = isl_tab_get_ctx(tab);
5069 v = isl_vec_alloc(ctx, len);
5070 if (!v)
5071 return NULL;
5072 for (i = 0; i < len; ++i) {
5073 if (!tab->var[pos + i].is_row) {
5074 isl_int_set_si(v->el[i], 0);
5075 } else {
5076 int row;
5078 row = tab->var[pos + i].index;
5079 isl_int_divexact(v->el[i], tab->mat->row[row][1],
5080 tab->mat->row[row][0]);
5084 return v;
5087 /* Check if the sequence of variables starting at "pos"
5088 * represents a trivial solution according to "trivial".
5089 * That is, is the result of applying "trivial" to this sequence
5090 * equal to the zero vector?
5092 static isl_bool region_is_trivial(struct isl_tab *tab, int pos,
5093 __isl_keep isl_mat *trivial)
5095 int n, len;
5096 isl_vec *v;
5097 isl_bool is_trivial;
5099 if (!trivial)
5100 return isl_bool_error;
5102 n = isl_mat_rows(trivial);
5103 if (n == 0)
5104 return isl_bool_false;
5106 len = isl_mat_cols(trivial);
5107 v = extract_sample_sequence(tab, pos, len);
5108 v = isl_mat_vec_product(isl_mat_copy(trivial), v);
5109 is_trivial = isl_vec_is_zero(v);
5110 isl_vec_free(v);
5112 return is_trivial;
5115 /* Global internal data for isl_tab_basic_set_non_trivial_lexmin.
5117 * "n_op" is the number of initial coordinates to optimize,
5118 * as passed to isl_tab_basic_set_non_trivial_lexmin.
5119 * "region" is the "n_region"-sized array of regions passed
5120 * to isl_tab_basic_set_non_trivial_lexmin.
5122 * "tab" is the tableau that corresponds to the ILP problem.
5123 * "local" is an array of local data structure, one for each
5124 * (potential) level of the backtracking procedure of
5125 * isl_tab_basic_set_non_trivial_lexmin.
5126 * "v" is a pre-allocated vector that can be used for adding
5127 * constraints to the tableau.
5129 * "sol" contains the best solution found so far.
5130 * It is initialized to a vector of size zero.
5132 struct isl_lexmin_data {
5133 int n_op;
5134 int n_region;
5135 struct isl_trivial_region *region;
5137 struct isl_tab *tab;
5138 struct isl_local_region *local;
5139 isl_vec *v;
5141 isl_vec *sol;
5144 /* Return the index of the first trivial region, "n_region" if all regions
5145 * are non-trivial or -1 in case of error.
5147 static int first_trivial_region(struct isl_lexmin_data *data)
5149 int i;
5151 for (i = 0; i < data->n_region; ++i) {
5152 isl_bool trivial;
5153 trivial = region_is_trivial(data->tab, data->region[i].pos,
5154 data->region[i].trivial);
5155 if (trivial < 0)
5156 return -1;
5157 if (trivial)
5158 return i;
5161 return data->n_region;
5164 /* Check if the solution is optimal, i.e., whether the first
5165 * n_op entries are zero.
5167 static int is_optimal(__isl_keep isl_vec *sol, int n_op)
5169 int i;
5171 for (i = 0; i < n_op; ++i)
5172 if (!isl_int_is_zero(sol->el[1 + i]))
5173 return 0;
5174 return 1;
5177 /* Add constraints to "tab" that ensure that any solution is significantly
5178 * better than that represented by "sol". That is, find the first
5179 * relevant (within first n_op) non-zero coefficient and force it (along
5180 * with all previous coefficients) to be zero.
5181 * If the solution is already optimal (all relevant coefficients are zero),
5182 * then just mark the table as empty.
5183 * "n_zero" is the number of coefficients that have been forced zero
5184 * by previous calls to this function at the same level.
5185 * Return the updated number of forced zero coefficients or -1 on error.
5187 * This function assumes that at least 2 * (n_op - n_zero) more rows and
5188 * at least 2 * (n_op - n_zero) more elements in the constraint array
5189 * are available in the tableau.
5191 static int force_better_solution(struct isl_tab *tab,
5192 __isl_keep isl_vec *sol, int n_op, int n_zero)
5194 int i, n;
5195 isl_ctx *ctx;
5196 isl_vec *v = NULL;
5198 if (!sol)
5199 return -1;
5201 for (i = n_zero; i < n_op; ++i)
5202 if (!isl_int_is_zero(sol->el[1 + i]))
5203 break;
5205 if (i == n_op) {
5206 if (isl_tab_mark_empty(tab) < 0)
5207 return -1;
5208 return n_op;
5211 ctx = isl_vec_get_ctx(sol);
5212 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5213 if (!v)
5214 return -1;
5216 n = i + 1;
5217 for (; i >= n_zero; --i) {
5218 v = isl_vec_clr(v);
5219 isl_int_set_si(v->el[1 + i], -1);
5220 if (add_lexmin_eq(tab, v->el) < 0)
5221 goto error;
5224 isl_vec_free(v);
5225 return n;
5226 error:
5227 isl_vec_free(v);
5228 return -1;
5231 /* Fix triviality direction "dir" of the given region to zero.
5233 * This function assumes that at least two more rows and at least
5234 * two more elements in the constraint array are available in the tableau.
5236 static isl_stat fix_zero(struct isl_tab *tab, struct isl_trivial_region *region,
5237 int dir, struct isl_lexmin_data *data)
5239 int len;
5241 data->v = isl_vec_clr(data->v);
5242 if (!data->v)
5243 return isl_stat_error;
5244 len = isl_mat_cols(region->trivial);
5245 isl_seq_cpy(data->v->el + 1 + region->pos, region->trivial->row[dir],
5246 len);
5247 if (add_lexmin_eq(tab, data->v->el) < 0)
5248 return isl_stat_error;
5250 return isl_stat_ok;
5253 /* This function selects case "side" for non-triviality region "region",
5254 * assuming all the equality constraints have been imposed already.
5255 * In particular, the triviality direction side/2 is made positive
5256 * if side is even and made negative if side is odd.
5258 * This function assumes that at least one more row and at least
5259 * one more element in the constraint array are available in the tableau.
5261 static struct isl_tab *pos_neg(struct isl_tab *tab,
5262 struct isl_trivial_region *region,
5263 int side, struct isl_lexmin_data *data)
5265 int len;
5267 data->v = isl_vec_clr(data->v);
5268 if (!data->v)
5269 goto error;
5270 isl_int_set_si(data->v->el[0], -1);
5271 len = isl_mat_cols(region->trivial);
5272 if (side % 2 == 0)
5273 isl_seq_cpy(data->v->el + 1 + region->pos,
5274 region->trivial->row[side / 2], len);
5275 else
5276 isl_seq_neg(data->v->el + 1 + region->pos,
5277 region->trivial->row[side / 2], len);
5278 return add_lexmin_ineq(tab, data->v->el);
5279 error:
5280 isl_tab_free(tab);
5281 return NULL;
5284 /* Local data at each level of the backtracking procedure of
5285 * isl_tab_basic_set_non_trivial_lexmin.
5287 * "update" is set if a solution has been found in the current case
5288 * of this level, such that a better solution needs to be enforced
5289 * in the next case.
5290 * "n_zero" is the number of initial coordinates that have already
5291 * been forced to be zero at this level.
5292 * "region" is the non-triviality region considered at this level.
5293 * "side" is the index of the current case at this level.
5294 * "n" is the number of triviality directions.
5295 * "snap" is a snapshot of the tableau holding a state that needs
5296 * to be satisfied by all subsequent cases.
5298 struct isl_local_region {
5299 int update;
5300 int n_zero;
5301 int region;
5302 int side;
5303 int n;
5304 struct isl_tab_undo *snap;
5307 /* Initialize the global data structure "data" used while solving
5308 * the ILP problem "bset".
5310 static isl_stat init_lexmin_data(struct isl_lexmin_data *data,
5311 __isl_keep isl_basic_set *bset)
5313 isl_ctx *ctx;
5315 ctx = isl_basic_set_get_ctx(bset);
5317 data->tab = tab_for_lexmin(bset, NULL, 0, 0);
5318 if (!data->tab)
5319 return isl_stat_error;
5321 data->v = isl_vec_alloc(ctx, 1 + data->tab->n_var);
5322 if (!data->v)
5323 return isl_stat_error;
5324 data->local = isl_calloc_array(ctx, struct isl_local_region,
5325 data->n_region);
5326 if (data->n_region && !data->local)
5327 return isl_stat_error;
5329 data->sol = isl_vec_alloc(ctx, 0);
5331 return isl_stat_ok;
5334 /* Mark all outer levels as requiring a better solution
5335 * in the next cases.
5337 static void update_outer_levels(struct isl_lexmin_data *data, int level)
5339 int i;
5341 for (i = 0; i < level; ++i)
5342 data->local[i].update = 1;
5345 /* Initialize "local" to refer to region "region" and
5346 * to initiate processing at this level.
5348 static void init_local_region(struct isl_local_region *local, int region,
5349 struct isl_lexmin_data *data)
5351 local->n = isl_mat_rows(data->region[region].trivial);
5352 local->region = region;
5353 local->side = 0;
5354 local->update = 0;
5355 local->n_zero = 0;
5358 /* What to do next after entering a level of the backtracking procedure.
5360 * error: some error has occurred; abort
5361 * done: an optimal solution has been found; stop search
5362 * backtrack: backtrack to the previous level
5363 * handle: add the constraints for the current level and
5364 * move to the next level
5366 enum isl_next {
5367 isl_next_error = -1,
5368 isl_next_done,
5369 isl_next_backtrack,
5370 isl_next_handle,
5373 /* Have all cases of the current region been considered?
5374 * If there are n directions, then there are 2n cases.
5376 * The constraints in the current tableau are imposed
5377 * in all subsequent cases. This means that if the current
5378 * tableau is empty, then none of those cases should be considered
5379 * anymore and all cases have effectively been considered.
5381 static int finished_all_cases(struct isl_local_region *local,
5382 struct isl_lexmin_data *data)
5384 if (data->tab->empty)
5385 return 1;
5386 return local->side >= 2 * local->n;
5389 /* Enter level "level" of the backtracking search and figure out
5390 * what to do next. "init" is set if the level was entered
5391 * from a higher level and needs to be initialized.
5392 * Otherwise, the level is entered as a result of backtracking and
5393 * the tableau needs to be restored to a position that can
5394 * be used for the next case at this level.
5395 * The snapshot is assumed to have been saved in the previous case,
5396 * before the constraints specific to that case were added.
5398 * In the initialization case, the local region is initialized
5399 * to point to the first violated region.
5400 * If the constraints of all regions are satisfied by the current
5401 * sample of the tableau, then tell the caller to continue looking
5402 * for a better solution or to stop searching if an optimal solution
5403 * has been found.
5405 * If the tableau is empty or if all cases at the current level
5406 * have been considered, then the caller needs to backtrack as well.
5408 static enum isl_next enter_level(int level, int init,
5409 struct isl_lexmin_data *data)
5411 struct isl_local_region *local = &data->local[level];
5413 if (init) {
5414 int r;
5416 data->tab = cut_to_integer_lexmin(data->tab, CUT_ONE);
5417 if (!data->tab)
5418 return isl_next_error;
5419 if (data->tab->empty)
5420 return isl_next_backtrack;
5421 r = first_trivial_region(data);
5422 if (r < 0)
5423 return isl_next_error;
5424 if (r == data->n_region) {
5425 update_outer_levels(data, level);
5426 isl_vec_free(data->sol);
5427 data->sol = isl_tab_get_sample_value(data->tab);
5428 if (!data->sol)
5429 return isl_next_error;
5430 if (is_optimal(data->sol, data->n_op))
5431 return isl_next_done;
5432 return isl_next_backtrack;
5434 if (level >= data->n_region)
5435 isl_die(isl_vec_get_ctx(data->v), isl_error_internal,
5436 "nesting level too deep",
5437 return isl_next_error);
5438 init_local_region(local, r, data);
5439 if (isl_tab_extend_cons(data->tab,
5440 2 * local->n + 2 * data->n_op) < 0)
5441 return isl_next_error;
5442 } else {
5443 if (isl_tab_rollback(data->tab, local->snap) < 0)
5444 return isl_next_error;
5447 if (finished_all_cases(local, data))
5448 return isl_next_backtrack;
5449 return isl_next_handle;
5452 /* If a solution has been found in the previous case at this level
5453 * (marked by local->update being set), then add constraints
5454 * that enforce a better solution in the present and all following cases.
5455 * The constraints only need to be imposed once because they are
5456 * included in the snapshot (taken in pick_side) that will be used in
5457 * subsequent cases.
5459 static isl_stat better_next_side(struct isl_local_region *local,
5460 struct isl_lexmin_data *data)
5462 if (!local->update)
5463 return isl_stat_ok;
5465 local->n_zero = force_better_solution(data->tab,
5466 data->sol, data->n_op, local->n_zero);
5467 if (local->n_zero < 0)
5468 return isl_stat_error;
5470 local->update = 0;
5472 return isl_stat_ok;
5475 /* Add constraints to data->tab that select the current case (local->side)
5476 * at the current level.
5478 * If the linear combinations v should not be zero, then the cases are
5479 * v_0 >= 1
5480 * v_0 <= -1
5481 * v_0 = 0 and v_1 >= 1
5482 * v_0 = 0 and v_1 <= -1
5483 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5484 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5485 * ...
5486 * in this order.
5488 * A snapshot is taken after the equality constraint (if any) has been added
5489 * such that the next case can start off from this position.
5490 * The rollback to this position is performed in enter_level.
5492 static isl_stat pick_side(struct isl_local_region *local,
5493 struct isl_lexmin_data *data)
5495 struct isl_trivial_region *region;
5496 int side, base;
5498 region = &data->region[local->region];
5499 side = local->side;
5500 base = 2 * (side/2);
5502 if (side == base && base >= 2 &&
5503 fix_zero(data->tab, region, base / 2 - 1, data) < 0)
5504 return isl_stat_error;
5506 local->snap = isl_tab_snap(data->tab);
5507 if (isl_tab_push_basis(data->tab) < 0)
5508 return isl_stat_error;
5510 data->tab = pos_neg(data->tab, region, side, data);
5511 if (!data->tab)
5512 return isl_stat_error;
5513 return isl_stat_ok;
5516 /* Free the memory associated to "data".
5518 static void clear_lexmin_data(struct isl_lexmin_data *data)
5520 free(data->local);
5521 isl_vec_free(data->v);
5522 isl_tab_free(data->tab);
5525 /* Return the lexicographically smallest non-trivial solution of the
5526 * given ILP problem.
5528 * All variables are assumed to be non-negative.
5530 * n_op is the number of initial coordinates to optimize.
5531 * That is, once a solution has been found, we will only continue looking
5532 * for solutions that result in significantly better values for those
5533 * initial coordinates. That is, we only continue looking for solutions
5534 * that increase the number of initial zeros in this sequence.
5536 * A solution is non-trivial, if it is non-trivial on each of the
5537 * specified regions. Each region represents a sequence of
5538 * triviality directions on a sequence of variables that starts
5539 * at a given position. A solution is non-trivial on such a region if
5540 * at least one of the triviality directions is non-zero
5541 * on that sequence of variables.
5543 * Whenever a conflict is encountered, all constraints involved are
5544 * reported to the caller through a call to "conflict".
5546 * We perform a simple branch-and-bound backtracking search.
5547 * Each level in the search represents an initially trivial region
5548 * that is forced to be non-trivial.
5549 * At each level we consider 2 * n cases, where n
5550 * is the number of triviality directions.
5551 * In terms of those n directions v_i, we consider the cases
5552 * v_0 >= 1
5553 * v_0 <= -1
5554 * v_0 = 0 and v_1 >= 1
5555 * v_0 = 0 and v_1 <= -1
5556 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5557 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5558 * ...
5559 * in this order.
5561 __isl_give isl_vec *isl_tab_basic_set_non_trivial_lexmin(
5562 __isl_take isl_basic_set *bset, int n_op, int n_region,
5563 struct isl_trivial_region *region,
5564 int (*conflict)(int con, void *user), void *user)
5566 struct isl_lexmin_data data = { n_op, n_region, region };
5567 int level, init;
5569 if (!bset)
5570 return NULL;
5572 if (init_lexmin_data(&data, bset) < 0)
5573 goto error;
5574 data.tab->conflict = conflict;
5575 data.tab->conflict_user = user;
5577 level = 0;
5578 init = 1;
5580 while (level >= 0) {
5581 enum isl_next next;
5582 struct isl_local_region *local = &data.local[level];
5584 next = enter_level(level, init, &data);
5585 if (next < 0)
5586 goto error;
5587 if (next == isl_next_done)
5588 break;
5589 if (next == isl_next_backtrack) {
5590 level--;
5591 init = 0;
5592 continue;
5595 if (better_next_side(local, &data) < 0)
5596 goto error;
5597 if (pick_side(local, &data) < 0)
5598 goto error;
5600 local->side++;
5601 level++;
5602 init = 1;
5605 clear_lexmin_data(&data);
5606 isl_basic_set_free(bset);
5608 return data.sol;
5609 error:
5610 clear_lexmin_data(&data);
5611 isl_basic_set_free(bset);
5612 isl_vec_free(data.sol);
5613 return NULL;
5616 /* Wrapper for a tableau that is used for computing
5617 * the lexicographically smallest rational point of a non-negative set.
5618 * This point is represented by the sample value of "tab",
5619 * unless "tab" is empty.
5621 struct isl_tab_lexmin {
5622 isl_ctx *ctx;
5623 struct isl_tab *tab;
5626 /* Free "tl" and return NULL.
5628 __isl_null isl_tab_lexmin *isl_tab_lexmin_free(__isl_take isl_tab_lexmin *tl)
5630 if (!tl)
5631 return NULL;
5632 isl_ctx_deref(tl->ctx);
5633 isl_tab_free(tl->tab);
5634 free(tl);
5636 return NULL;
5639 /* Construct an isl_tab_lexmin for computing
5640 * the lexicographically smallest rational point in "bset",
5641 * assuming that all variables are non-negative.
5643 __isl_give isl_tab_lexmin *isl_tab_lexmin_from_basic_set(
5644 __isl_take isl_basic_set *bset)
5646 isl_ctx *ctx;
5647 isl_tab_lexmin *tl;
5649 if (!bset)
5650 return NULL;
5652 ctx = isl_basic_set_get_ctx(bset);
5653 tl = isl_calloc_type(ctx, struct isl_tab_lexmin);
5654 if (!tl)
5655 goto error;
5656 tl->ctx = ctx;
5657 isl_ctx_ref(ctx);
5658 tl->tab = tab_for_lexmin(bset, NULL, 0, 0);
5659 isl_basic_set_free(bset);
5660 if (!tl->tab)
5661 return isl_tab_lexmin_free(tl);
5662 return tl;
5663 error:
5664 isl_basic_set_free(bset);
5665 isl_tab_lexmin_free(tl);
5666 return NULL;
5669 /* Return the dimension of the set represented by "tl".
5671 int isl_tab_lexmin_dim(__isl_keep isl_tab_lexmin *tl)
5673 return tl ? tl->tab->n_var : -1;
5676 /* Add the equality with coefficients "eq" to "tl", updating the optimal
5677 * solution if needed.
5678 * The equality is added as two opposite inequality constraints.
5680 __isl_give isl_tab_lexmin *isl_tab_lexmin_add_eq(__isl_take isl_tab_lexmin *tl,
5681 isl_int *eq)
5683 unsigned n_var;
5685 if (!tl || !eq)
5686 return isl_tab_lexmin_free(tl);
5688 if (isl_tab_extend_cons(tl->tab, 2) < 0)
5689 return isl_tab_lexmin_free(tl);
5690 n_var = tl->tab->n_var;
5691 isl_seq_neg(eq, eq, 1 + n_var);
5692 tl->tab = add_lexmin_ineq(tl->tab, eq);
5693 isl_seq_neg(eq, eq, 1 + n_var);
5694 tl->tab = add_lexmin_ineq(tl->tab, eq);
5696 if (!tl->tab)
5697 return isl_tab_lexmin_free(tl);
5699 return tl;
5702 /* Add cuts to "tl" until the sample value reaches an integer value or
5703 * until the result becomes empty.
5705 __isl_give isl_tab_lexmin *isl_tab_lexmin_cut_to_integer(
5706 __isl_take isl_tab_lexmin *tl)
5708 if (!tl)
5709 return NULL;
5710 tl->tab = cut_to_integer_lexmin(tl->tab, CUT_ONE);
5711 if (!tl->tab)
5712 return isl_tab_lexmin_free(tl);
5713 return tl;
5716 /* Return the lexicographically smallest rational point in the basic set
5717 * from which "tl" was constructed.
5718 * If the original input was empty, then return a zero-length vector.
5720 __isl_give isl_vec *isl_tab_lexmin_get_solution(__isl_keep isl_tab_lexmin *tl)
5722 if (!tl)
5723 return NULL;
5724 if (tl->tab->empty)
5725 return isl_vec_alloc(tl->ctx, 0);
5726 else
5727 return isl_tab_get_sample_value(tl->tab);
5730 struct isl_sol_pma {
5731 struct isl_sol sol;
5732 isl_pw_multi_aff *pma;
5733 isl_set *empty;
5736 static void sol_pma_free(struct isl_sol *sol)
5738 struct isl_sol_pma *sol_pma = (struct isl_sol_pma *) sol;
5739 isl_pw_multi_aff_free(sol_pma->pma);
5740 isl_set_free(sol_pma->empty);
5743 /* This function is called for parts of the context where there is
5744 * no solution, with "bset" corresponding to the context tableau.
5745 * Simply add the basic set to the set "empty".
5747 static void sol_pma_add_empty(struct isl_sol_pma *sol,
5748 __isl_take isl_basic_set *bset)
5750 if (!bset || !sol->empty)
5751 goto error;
5753 sol->empty = isl_set_grow(sol->empty, 1);
5754 bset = isl_basic_set_simplify(bset);
5755 bset = isl_basic_set_finalize(bset);
5756 sol->empty = isl_set_add_basic_set(sol->empty, bset);
5757 if (!sol->empty)
5758 sol->sol.error = 1;
5759 return;
5760 error:
5761 isl_basic_set_free(bset);
5762 sol->sol.error = 1;
5765 /* Given a basic set "dom" that represents the context and a tuple of
5766 * affine expressions "maff" defined over this domain, construct
5767 * an isl_pw_multi_aff with a single cell corresponding to "dom" and
5768 * the affine expressions in "maff".
5770 static void sol_pma_add(struct isl_sol_pma *sol,
5771 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *maff)
5773 isl_pw_multi_aff *pma;
5775 dom = isl_basic_set_simplify(dom);
5776 dom = isl_basic_set_finalize(dom);
5777 pma = isl_pw_multi_aff_alloc(isl_set_from_basic_set(dom), maff);
5778 sol->pma = isl_pw_multi_aff_add_disjoint(sol->pma, pma);
5779 if (!sol->pma)
5780 sol->sol.error = 1;
5783 static void sol_pma_add_empty_wrap(struct isl_sol *sol,
5784 __isl_take isl_basic_set *bset)
5786 sol_pma_add_empty((struct isl_sol_pma *)sol, bset);
5789 static void sol_pma_add_wrap(struct isl_sol *sol,
5790 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
5792 sol_pma_add((struct isl_sol_pma *)sol, dom, ma);
5795 /* Construct an isl_sol_pma structure for accumulating the solution.
5796 * If track_empty is set, then we also keep track of the parts
5797 * of the context where there is no solution.
5798 * If max is set, then we are solving a maximization, rather than
5799 * a minimization problem, which means that the variables in the
5800 * tableau have value "M - x" rather than "M + x".
5802 static struct isl_sol *sol_pma_init(__isl_keep isl_basic_map *bmap,
5803 __isl_take isl_basic_set *dom, int track_empty, int max)
5805 struct isl_sol_pma *sol_pma = NULL;
5806 isl_space *space;
5808 if (!bmap)
5809 goto error;
5811 sol_pma = isl_calloc_type(bmap->ctx, struct isl_sol_pma);
5812 if (!sol_pma)
5813 goto error;
5815 sol_pma->sol.free = &sol_pma_free;
5816 if (sol_init(&sol_pma->sol, bmap, dom, max) < 0)
5817 goto error;
5818 sol_pma->sol.add = &sol_pma_add_wrap;
5819 sol_pma->sol.add_empty = track_empty ? &sol_pma_add_empty_wrap : NULL;
5820 space = isl_space_copy(sol_pma->sol.space);
5821 sol_pma->pma = isl_pw_multi_aff_empty(space);
5822 if (!sol_pma->pma)
5823 goto error;
5825 if (track_empty) {
5826 sol_pma->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
5827 1, ISL_SET_DISJOINT);
5828 if (!sol_pma->empty)
5829 goto error;
5832 isl_basic_set_free(dom);
5833 return &sol_pma->sol;
5834 error:
5835 isl_basic_set_free(dom);
5836 sol_free(&sol_pma->sol);
5837 return NULL;
5840 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
5841 * some obvious symmetries.
5843 * We call basic_map_partial_lexopt_base_sol and extract the results.
5845 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_base_pw_multi_aff(
5846 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5847 __isl_give isl_set **empty, int max)
5849 isl_pw_multi_aff *result = NULL;
5850 struct isl_sol *sol;
5851 struct isl_sol_pma *sol_pma;
5853 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
5854 &sol_pma_init);
5855 if (!sol)
5856 return NULL;
5857 sol_pma = (struct isl_sol_pma *) sol;
5859 result = isl_pw_multi_aff_copy(sol_pma->pma);
5860 if (empty)
5861 *empty = isl_set_copy(sol_pma->empty);
5862 sol_free(&sol_pma->sol);
5863 return result;
5866 /* Given that the last input variable of "maff" represents the minimum
5867 * of some bounds, check whether we need to plug in the expression
5868 * of the minimum.
5870 * In particular, check if the last input variable appears in any
5871 * of the expressions in "maff".
5873 static int need_substitution(__isl_keep isl_multi_aff *maff)
5875 int i;
5876 unsigned pos;
5878 pos = isl_multi_aff_dim(maff, isl_dim_in) - 1;
5880 for (i = 0; i < maff->n; ++i)
5881 if (isl_aff_involves_dims(maff->p[i], isl_dim_in, pos, 1))
5882 return 1;
5884 return 0;
5887 /* Given a set of upper bounds on the last "input" variable m,
5888 * construct a piecewise affine expression that selects
5889 * the minimal upper bound to m, i.e.,
5890 * divide the space into cells where one
5891 * of the upper bounds is smaller than all the others and select
5892 * this upper bound on that cell.
5894 * In particular, if there are n bounds b_i, then the result
5895 * consists of n cell, each one of the form
5897 * b_i <= b_j for j > i
5898 * b_i < b_j for j < i
5900 * The affine expression on this cell is
5902 * b_i
5904 static __isl_give isl_pw_aff *set_minimum_pa(__isl_take isl_space *space,
5905 __isl_take isl_mat *var)
5907 int i;
5908 isl_aff *aff = NULL;
5909 isl_basic_set *bset = NULL;
5910 isl_pw_aff *paff = NULL;
5911 isl_space *pw_space;
5912 isl_local_space *ls = NULL;
5914 if (!space || !var)
5915 goto error;
5917 ls = isl_local_space_from_space(isl_space_copy(space));
5918 pw_space = isl_space_copy(space);
5919 pw_space = isl_space_from_domain(pw_space);
5920 pw_space = isl_space_add_dims(pw_space, isl_dim_out, 1);
5921 paff = isl_pw_aff_alloc_size(pw_space, var->n_row);
5923 for (i = 0; i < var->n_row; ++i) {
5924 isl_pw_aff *paff_i;
5926 aff = isl_aff_alloc(isl_local_space_copy(ls));
5927 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
5928 0, var->n_row - 1);
5929 if (!aff || !bset)
5930 goto error;
5931 isl_int_set_si(aff->v->el[0], 1);
5932 isl_seq_cpy(aff->v->el + 1, var->row[i], var->n_col);
5933 isl_int_set_si(aff->v->el[1 + var->n_col], 0);
5934 bset = select_minimum(bset, var, i);
5935 paff_i = isl_pw_aff_alloc(isl_set_from_basic_set(bset), aff);
5936 paff = isl_pw_aff_add_disjoint(paff, paff_i);
5939 isl_local_space_free(ls);
5940 isl_space_free(space);
5941 isl_mat_free(var);
5942 return paff;
5943 error:
5944 isl_aff_free(aff);
5945 isl_basic_set_free(bset);
5946 isl_pw_aff_free(paff);
5947 isl_local_space_free(ls);
5948 isl_space_free(space);
5949 isl_mat_free(var);
5950 return NULL;
5953 /* Given a piecewise multi-affine expression of which the last input variable
5954 * is the minimum of the bounds in "cst", plug in the value of the minimum.
5955 * This minimum expression is given in "min_expr_pa".
5956 * The set "min_expr" contains the same information, but in the form of a set.
5957 * The variable is subsequently projected out.
5959 * The implementation is similar to those of "split" and "split_domain".
5960 * If the variable appears in a given expression, then minimum expression
5961 * is plugged in. Otherwise, if the variable appears in the constraints
5962 * and a split is required, then the domain is split. Otherwise, no split
5963 * is performed.
5965 static __isl_give isl_pw_multi_aff *split_domain_pma(
5966 __isl_take isl_pw_multi_aff *opt, __isl_take isl_pw_aff *min_expr_pa,
5967 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
5969 int n_in;
5970 int i;
5971 isl_space *space;
5972 isl_pw_multi_aff *res;
5974 if (!opt || !min_expr || !cst)
5975 goto error;
5977 n_in = isl_pw_multi_aff_dim(opt, isl_dim_in);
5978 space = isl_pw_multi_aff_get_space(opt);
5979 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
5980 res = isl_pw_multi_aff_empty(space);
5982 for (i = 0; i < opt->n; ++i) {
5983 isl_pw_multi_aff *pma;
5985 pma = isl_pw_multi_aff_alloc(isl_set_copy(opt->p[i].set),
5986 isl_multi_aff_copy(opt->p[i].maff));
5987 if (need_substitution(opt->p[i].maff))
5988 pma = isl_pw_multi_aff_substitute(pma,
5989 isl_dim_in, n_in - 1, min_expr_pa);
5990 else {
5991 isl_bool split;
5992 split = need_split_set(opt->p[i].set, cst);
5993 if (split < 0)
5994 pma = isl_pw_multi_aff_free(pma);
5995 else if (split)
5996 pma = isl_pw_multi_aff_intersect_domain(pma,
5997 isl_set_copy(min_expr));
5999 pma = isl_pw_multi_aff_project_out(pma,
6000 isl_dim_in, n_in - 1, 1);
6002 res = isl_pw_multi_aff_add_disjoint(res, pma);
6005 isl_pw_multi_aff_free(opt);
6006 isl_pw_aff_free(min_expr_pa);
6007 isl_set_free(min_expr);
6008 isl_mat_free(cst);
6009 return res;
6010 error:
6011 isl_pw_multi_aff_free(opt);
6012 isl_pw_aff_free(min_expr_pa);
6013 isl_set_free(min_expr);
6014 isl_mat_free(cst);
6015 return NULL;
6018 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pw_multi_aff(
6019 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
6020 __isl_give isl_set **empty, int max);
6022 /* This function is called from basic_map_partial_lexopt_symm.
6023 * The last variable of "bmap" and "dom" corresponds to the minimum
6024 * of the bounds in "cst". "map_space" is the space of the original
6025 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
6026 * is the space of the original domain.
6028 * We recursively call basic_map_partial_lexopt and then plug in
6029 * the definition of the minimum in the result.
6031 static __isl_give isl_pw_multi_aff *
6032 basic_map_partial_lexopt_symm_core_pw_multi_aff(
6033 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
6034 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
6035 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
6037 isl_pw_multi_aff *opt;
6038 isl_pw_aff *min_expr_pa;
6039 isl_set *min_expr;
6041 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
6042 min_expr_pa = set_minimum_pa(isl_basic_set_get_space(dom),
6043 isl_mat_copy(cst));
6045 opt = basic_map_partial_lexopt_pw_multi_aff(bmap, dom, empty, max);
6047 if (empty) {
6048 *empty = split(*empty,
6049 isl_set_copy(min_expr), isl_mat_copy(cst));
6050 *empty = isl_set_reset_space(*empty, set_space);
6053 opt = split_domain_pma(opt, min_expr_pa, min_expr, cst);
6054 opt = isl_pw_multi_aff_reset_space(opt, map_space);
6056 return opt;
6059 #undef TYPE
6060 #define TYPE isl_pw_multi_aff
6061 #undef SUFFIX
6062 #define SUFFIX _pw_multi_aff
6063 #include "isl_tab_lexopt_templ.c"