isl_val_n_abs_num_chunks: return isl_size
[isl.git] / isl_tab_pip.c
blob8842c8fddb7f7eea784dad0f277add9257f7cefb
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 two 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, and
180 * isl_sol_pma, which collects an isl_pw_multi_aff instead.
182 struct isl_sol {
183 int error;
184 int rational;
185 int level;
186 int max;
187 isl_size n_out;
188 isl_space *space;
189 struct isl_context *context;
190 struct isl_partial_sol *partial;
191 void (*add)(struct isl_sol *sol,
192 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma);
193 void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
194 void (*free)(struct isl_sol *sol);
195 struct isl_sol_callback dec_level;
198 static void sol_free(struct isl_sol *sol)
200 struct isl_partial_sol *partial, *next;
201 if (!sol)
202 return;
203 for (partial = sol->partial; partial; partial = next) {
204 next = partial->next;
205 isl_basic_set_free(partial->dom);
206 isl_multi_aff_free(partial->ma);
207 free(partial);
209 isl_space_free(sol->space);
210 if (sol->context)
211 sol->context->op->free(sol->context);
212 sol->free(sol);
213 free(sol);
216 /* Push a partial solution represented by a domain and function "ma"
217 * onto the stack of partial solutions.
218 * If "ma" is NULL, then "dom" represents a part of the domain
219 * with no solution.
221 static void sol_push_sol(struct isl_sol *sol,
222 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
224 struct isl_partial_sol *partial;
226 if (sol->error || !dom)
227 goto error;
229 partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
230 if (!partial)
231 goto error;
233 partial->level = sol->level;
234 partial->dom = dom;
235 partial->ma = ma;
236 partial->next = sol->partial;
238 sol->partial = partial;
240 return;
241 error:
242 isl_basic_set_free(dom);
243 isl_multi_aff_free(ma);
244 sol->error = 1;
247 /* Check that the final columns of "M", starting at "first", are zero.
249 static isl_stat check_final_columns_are_zero(__isl_keep isl_mat *M,
250 unsigned first)
252 int i;
253 unsigned rows, cols, n;
255 if (!M)
256 return isl_stat_error;
257 rows = isl_mat_rows(M);
258 cols = isl_mat_cols(M);
259 n = cols - first;
260 for (i = 0; i < rows; ++i)
261 if (isl_seq_first_non_zero(M->row[i] + first, n) != -1)
262 isl_die(isl_mat_get_ctx(M), isl_error_internal,
263 "final columns should be zero",
264 return isl_stat_error);
265 return isl_stat_ok;
268 /* Set the affine expressions in "ma" according to the rows in "M", which
269 * are defined over the local space "ls".
270 * The matrix "M" may have extra (zero) columns beyond the number
271 * of variables in "ls".
273 static __isl_give isl_multi_aff *set_from_affine_matrix(
274 __isl_take isl_multi_aff *ma, __isl_take isl_local_space *ls,
275 __isl_take isl_mat *M)
277 int i;
278 isl_size dim;
279 isl_aff *aff;
281 dim = isl_local_space_dim(ls, isl_dim_all);
282 if (!ma || dim < 0 || !M)
283 goto error;
285 if (check_final_columns_are_zero(M, 1 + dim) < 0)
286 goto error;
287 for (i = 1; i < M->n_row; ++i) {
288 aff = isl_aff_alloc(isl_local_space_copy(ls));
289 if (aff) {
290 isl_int_set(aff->v->el[0], M->row[0][0]);
291 isl_seq_cpy(aff->v->el + 1, M->row[i], 1 + dim);
293 aff = isl_aff_normalize(aff);
294 ma = isl_multi_aff_set_aff(ma, i - 1, aff);
296 isl_local_space_free(ls);
297 isl_mat_free(M);
299 return ma;
300 error:
301 isl_local_space_free(ls);
302 isl_mat_free(M);
303 isl_multi_aff_free(ma);
304 return NULL;
307 /* Push a partial solution represented by a domain and mapping M
308 * onto the stack of partial solutions.
310 * The affine matrix "M" maps the dimensions of the context
311 * to the output variables. Convert it into an isl_multi_aff and
312 * then call sol_push_sol.
314 * Note that the description of the initial context may have involved
315 * existentially quantified variables, in which case they also appear
316 * in "dom". These need to be removed before creating the affine
317 * expression because an affine expression cannot be defined in terms
318 * of existentially quantified variables without a known representation.
319 * Since newly added integer divisions are inserted before these
320 * existentially quantified variables, they are still in the final
321 * positions and the corresponding final columns of "M" are zero
322 * because align_context_divs adds the existentially quantified
323 * variables of the context to the main tableau without any constraints and
324 * any equality constraints that are added later on can only serve
325 * to eliminate these existentially quantified variables.
327 static void sol_push_sol_mat(struct isl_sol *sol,
328 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
330 isl_local_space *ls;
331 isl_multi_aff *ma;
332 isl_size n_div;
333 int n_known;
335 n_div = isl_basic_set_dim(dom, isl_dim_div);
336 if (n_div < 0)
337 goto error;
338 n_known = n_div - sol->context->n_unknown;
340 ma = isl_multi_aff_alloc(isl_space_copy(sol->space));
341 ls = isl_basic_set_get_local_space(dom);
342 ls = isl_local_space_drop_dims(ls, isl_dim_div,
343 n_known, n_div - n_known);
344 ma = set_from_affine_matrix(ma, ls, M);
346 if (!ma)
347 dom = isl_basic_set_free(dom);
348 sol_push_sol(sol, dom, ma);
349 return;
350 error:
351 isl_basic_set_free(dom);
352 isl_mat_free(M);
353 sol_push_sol(sol, NULL, NULL);
356 /* Pop one partial solution from the partial solution stack and
357 * pass it on to sol->add or sol->add_empty.
359 static void sol_pop_one(struct isl_sol *sol)
361 struct isl_partial_sol *partial;
363 partial = sol->partial;
364 sol->partial = partial->next;
366 if (partial->ma)
367 sol->add(sol, partial->dom, partial->ma);
368 else
369 sol->add_empty(sol, partial->dom);
370 free(partial);
373 /* Return a fresh copy of the domain represented by the context tableau.
375 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
377 struct isl_basic_set *bset;
379 if (sol->error)
380 return NULL;
382 bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
383 bset = isl_basic_set_update_from_tab(bset,
384 sol->context->op->peek_tab(sol->context));
386 return bset;
389 /* Check whether two partial solutions have the same affine expressions.
391 static isl_bool same_solution(struct isl_partial_sol *s1,
392 struct isl_partial_sol *s2)
394 if (!s1->ma != !s2->ma)
395 return isl_bool_false;
396 if (!s1->ma)
397 return isl_bool_true;
399 return isl_multi_aff_plain_is_equal(s1->ma, s2->ma);
402 /* Swap the initial two partial solutions in "sol".
404 * That is, go from
406 * sol->partial = p1; p1->next = p2; p2->next = p3
408 * to
410 * sol->partial = p2; p2->next = p1; p1->next = p3
412 static void swap_initial(struct isl_sol *sol)
414 struct isl_partial_sol *partial;
416 partial = sol->partial;
417 sol->partial = partial->next;
418 partial->next = partial->next->next;
419 sol->partial->next = partial;
422 /* Combine the initial two partial solution of "sol" into
423 * a partial solution with the current context domain of "sol" and
424 * the function description of the second partial solution in the list.
425 * The level of the new partial solution is set to the current level.
427 * That is, the first two partial solutions (D1,M1) and (D2,M2) are
428 * replaced by (D,M2), where D is the domain of "sol", which is assumed
429 * to be the union of D1 and D2, while M1 is assumed to be equal to M2
430 * (at least on D1).
432 static isl_stat combine_initial_into_second(struct isl_sol *sol)
434 struct isl_partial_sol *partial;
435 isl_basic_set *bset;
437 partial = sol->partial;
439 bset = sol_domain(sol);
440 isl_basic_set_free(partial->next->dom);
441 partial->next->dom = bset;
442 partial->next->level = sol->level;
444 if (!bset)
445 return isl_stat_error;
447 sol->partial = partial->next;
448 isl_basic_set_free(partial->dom);
449 isl_multi_aff_free(partial->ma);
450 free(partial);
452 return isl_stat_ok;
455 /* Are "ma1" and "ma2" equal to each other on "dom"?
457 * Combine "ma1" and "ma2" with "dom" and check if the results are the same.
458 * "dom" may have existentially quantified variables. Eliminate them first
459 * as otherwise they would have to be eliminated twice, in a more complicated
460 * context.
462 static isl_bool equal_on_domain(__isl_keep isl_multi_aff *ma1,
463 __isl_keep isl_multi_aff *ma2, __isl_keep isl_basic_set *dom)
465 isl_set *set;
466 isl_pw_multi_aff *pma1, *pma2;
467 isl_bool equal;
469 set = isl_basic_set_compute_divs(isl_basic_set_copy(dom));
470 pma1 = isl_pw_multi_aff_alloc(isl_set_copy(set),
471 isl_multi_aff_copy(ma1));
472 pma2 = isl_pw_multi_aff_alloc(set, isl_multi_aff_copy(ma2));
473 equal = isl_pw_multi_aff_is_equal(pma1, pma2);
474 isl_pw_multi_aff_free(pma1);
475 isl_pw_multi_aff_free(pma2);
477 return equal;
480 /* The initial two partial solutions of "sol" are known to be at
481 * the same level.
482 * If they represent the same solution (on different parts of the domain),
483 * then combine them into a single solution at the current level.
484 * Otherwise, pop them both.
486 * Even if the two partial solution are not obviously the same,
487 * one may still be a simplification of the other over its own domain.
488 * Also check if the two sets of affine functions are equal when
489 * restricted to one of the domains. If so, combine the two
490 * using the set of affine functions on the other domain.
491 * That is, for two partial solutions (D1,M1) and (D2,M2),
492 * if M1 = M2 on D1, then the pair of partial solutions can
493 * be replaced by (D1+D2,M2) and similarly when M1 = M2 on D2.
495 static isl_stat combine_initial_if_equal(struct isl_sol *sol)
497 struct isl_partial_sol *partial;
498 isl_bool same;
500 partial = sol->partial;
502 same = same_solution(partial, partial->next);
503 if (same < 0)
504 return isl_stat_error;
505 if (same)
506 return combine_initial_into_second(sol);
507 if (partial->ma && partial->next->ma) {
508 same = equal_on_domain(partial->ma, partial->next->ma,
509 partial->dom);
510 if (same < 0)
511 return isl_stat_error;
512 if (same)
513 return combine_initial_into_second(sol);
514 same = equal_on_domain(partial->ma, partial->next->ma,
515 partial->next->dom);
516 if (same) {
517 swap_initial(sol);
518 return combine_initial_into_second(sol);
522 sol_pop_one(sol);
523 sol_pop_one(sol);
525 return isl_stat_ok;
528 /* Pop all solutions from the partial solution stack that were pushed onto
529 * the stack at levels that are deeper than the current level.
530 * If the two topmost elements on the stack have the same level
531 * and represent the same solution, then their domains are combined.
532 * This combined domain is the same as the current context domain
533 * as sol_pop is called each time we move back to a higher level.
534 * If the outer level (0) has been reached, then all partial solutions
535 * at the current level are also popped off.
537 static void sol_pop(struct isl_sol *sol)
539 struct isl_partial_sol *partial;
541 if (sol->error)
542 return;
544 partial = sol->partial;
545 if (!partial)
546 return;
548 if (partial->level == 0 && sol->level == 0) {
549 for (partial = sol->partial; partial; partial = sol->partial)
550 sol_pop_one(sol);
551 return;
554 if (partial->level <= sol->level)
555 return;
557 if (partial->next && partial->next->level == partial->level) {
558 if (combine_initial_if_equal(sol) < 0)
559 goto error;
560 } else
561 sol_pop_one(sol);
563 if (sol->level == 0) {
564 for (partial = sol->partial; partial; partial = sol->partial)
565 sol_pop_one(sol);
566 return;
569 if (0)
570 error: sol->error = 1;
573 static void sol_dec_level(struct isl_sol *sol)
575 if (sol->error)
576 return;
578 sol->level--;
580 sol_pop(sol);
583 static isl_stat sol_dec_level_wrap(struct isl_tab_callback *cb)
585 struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
587 sol_dec_level(callback->sol);
589 return callback->sol->error ? isl_stat_error : isl_stat_ok;
592 /* Move down to next level and push callback onto context tableau
593 * to decrease the level again when it gets rolled back across
594 * the current state. That is, dec_level will be called with
595 * the context tableau in the same state as it is when inc_level
596 * is called.
598 static void sol_inc_level(struct isl_sol *sol)
600 struct isl_tab *tab;
602 if (sol->error)
603 return;
605 sol->level++;
606 tab = sol->context->op->peek_tab(sol->context);
607 if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
608 sol->error = 1;
611 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
613 int i;
615 if (isl_int_is_one(m))
616 return;
618 for (i = 0; i < n_row; ++i)
619 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
622 /* Add the solution identified by the tableau and the context tableau.
624 * The layout of the variables is as follows.
625 * tab->n_var is equal to the total number of variables in the input
626 * map (including divs that were copied from the context)
627 * + the number of extra divs constructed
628 * Of these, the first tab->n_param and the last tab->n_div variables
629 * correspond to the variables in the context, i.e.,
630 * tab->n_param + tab->n_div = context_tab->n_var
631 * tab->n_param is equal to the number of parameters and input
632 * dimensions in the input map
633 * tab->n_div is equal to the number of divs in the context
635 * If there is no solution, then call add_empty with a basic set
636 * that corresponds to the context tableau. (If add_empty is NULL,
637 * then do nothing).
639 * If there is a solution, then first construct a matrix that maps
640 * all dimensions of the context to the output variables, i.e.,
641 * the output dimensions in the input map.
642 * The divs in the input map (if any) that do not correspond to any
643 * div in the context do not appear in the solution.
644 * The algorithm will make sure that they have an integer value,
645 * but these values themselves are of no interest.
646 * We have to be careful not to drop or rearrange any divs in the
647 * context because that would change the meaning of the matrix.
649 * To extract the value of the output variables, it should be noted
650 * that we always use a big parameter M in the main tableau and so
651 * the variable stored in this tableau is not an output variable x itself, but
652 * x' = M + x (in case of minimization)
653 * or
654 * x' = M - x (in case of maximization)
655 * If x' appears in a column, then its optimal value is zero,
656 * which means that the optimal value of x is an unbounded number
657 * (-M for minimization and M for maximization).
658 * We currently assume that the output dimensions in the original map
659 * are bounded, so this cannot occur.
660 * Similarly, when x' appears in a row, then the coefficient of M in that
661 * row is necessarily 1.
662 * If the row in the tableau represents
663 * d x' = c + d M + e(y)
664 * then, in case of minimization, the corresponding row in the matrix
665 * will be
666 * a c + a e(y)
667 * with a d = m, the (updated) common denominator of the matrix.
668 * In case of maximization, the row will be
669 * -a c - a e(y)
671 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
673 struct isl_basic_set *bset = NULL;
674 struct isl_mat *mat = NULL;
675 unsigned off;
676 int row;
677 isl_int m;
679 if (sol->error || !tab)
680 goto error;
682 if (tab->empty && !sol->add_empty)
683 return;
684 if (sol->context->op->is_empty(sol->context))
685 return;
687 bset = sol_domain(sol);
689 if (tab->empty) {
690 sol_push_sol(sol, bset, NULL);
691 return;
694 off = 2 + tab->M;
696 mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
697 1 + tab->n_param + tab->n_div);
698 if (!mat)
699 goto error;
701 isl_int_init(m);
703 isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
704 isl_int_set_si(mat->row[0][0], 1);
705 for (row = 0; row < sol->n_out; ++row) {
706 int i = tab->n_param + row;
707 int r, j;
709 isl_seq_clr(mat->row[1 + row], mat->n_col);
710 if (!tab->var[i].is_row) {
711 if (tab->M)
712 isl_die(mat->ctx, isl_error_invalid,
713 "unbounded optimum", goto error2);
714 continue;
717 r = tab->var[i].index;
718 if (tab->M &&
719 isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
720 isl_die(mat->ctx, isl_error_invalid,
721 "unbounded optimum", goto error2);
722 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
723 isl_int_divexact(m, tab->mat->row[r][0], m);
724 scale_rows(mat, m, 1 + row);
725 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
726 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
727 for (j = 0; j < tab->n_param; ++j) {
728 int col;
729 if (tab->var[j].is_row)
730 continue;
731 col = tab->var[j].index;
732 isl_int_mul(mat->row[1 + row][1 + j], m,
733 tab->mat->row[r][off + col]);
735 for (j = 0; j < tab->n_div; ++j) {
736 int col;
737 if (tab->var[tab->n_var - tab->n_div+j].is_row)
738 continue;
739 col = tab->var[tab->n_var - tab->n_div+j].index;
740 isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
741 tab->mat->row[r][off + col]);
743 if (sol->max)
744 isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
745 mat->n_col);
748 isl_int_clear(m);
750 sol_push_sol_mat(sol, bset, mat);
751 return;
752 error2:
753 isl_int_clear(m);
754 error:
755 isl_basic_set_free(bset);
756 isl_mat_free(mat);
757 sol->error = 1;
760 struct isl_sol_map {
761 struct isl_sol sol;
762 struct isl_map *map;
763 struct isl_set *empty;
766 static void sol_map_free(struct isl_sol *sol)
768 struct isl_sol_map *sol_map = (struct isl_sol_map *) sol;
769 isl_map_free(sol_map->map);
770 isl_set_free(sol_map->empty);
773 /* This function is called for parts of the context where there is
774 * no solution, with "bset" corresponding to the context tableau.
775 * Simply add the basic set to the set "empty".
777 static void sol_map_add_empty(struct isl_sol_map *sol,
778 struct isl_basic_set *bset)
780 if (!bset || !sol->empty)
781 goto error;
783 sol->empty = isl_set_grow(sol->empty, 1);
784 bset = isl_basic_set_simplify(bset);
785 bset = isl_basic_set_finalize(bset);
786 sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
787 if (!sol->empty)
788 goto error;
789 isl_basic_set_free(bset);
790 return;
791 error:
792 isl_basic_set_free(bset);
793 sol->sol.error = 1;
796 static void sol_map_add_empty_wrap(struct isl_sol *sol,
797 struct isl_basic_set *bset)
799 sol_map_add_empty((struct isl_sol_map *)sol, bset);
802 /* Given a basic set "dom" that represents the context and a tuple of
803 * affine expressions "ma" defined over this domain, construct a basic map
804 * that expresses this function on the domain.
806 static void sol_map_add(struct isl_sol_map *sol,
807 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
809 isl_basic_map *bmap;
811 if (sol->sol.error || !dom || !ma)
812 goto error;
814 bmap = isl_basic_map_from_multi_aff2(ma, sol->sol.rational);
815 bmap = isl_basic_map_intersect_domain(bmap, dom);
816 sol->map = isl_map_grow(sol->map, 1);
817 sol->map = isl_map_add_basic_map(sol->map, bmap);
818 if (!sol->map)
819 sol->sol.error = 1;
820 return;
821 error:
822 isl_basic_set_free(dom);
823 isl_multi_aff_free(ma);
824 sol->sol.error = 1;
827 static void sol_map_add_wrap(struct isl_sol *sol,
828 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
830 sol_map_add((struct isl_sol_map *)sol, dom, ma);
834 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
835 * i.e., the constant term and the coefficients of all variables that
836 * appear in the context tableau.
837 * Note that the coefficient of the big parameter M is NOT copied.
838 * The context tableau may not have a big parameter and even when it
839 * does, it is a different big parameter.
841 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
843 int i;
844 unsigned off = 2 + tab->M;
846 isl_int_set(line[0], tab->mat->row[row][1]);
847 for (i = 0; i < tab->n_param; ++i) {
848 if (tab->var[i].is_row)
849 isl_int_set_si(line[1 + i], 0);
850 else {
851 int col = tab->var[i].index;
852 isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
855 for (i = 0; i < tab->n_div; ++i) {
856 if (tab->var[tab->n_var - tab->n_div + i].is_row)
857 isl_int_set_si(line[1 + tab->n_param + i], 0);
858 else {
859 int col = tab->var[tab->n_var - tab->n_div + i].index;
860 isl_int_set(line[1 + tab->n_param + i],
861 tab->mat->row[row][off + col]);
866 /* Check if rows "row1" and "row2" have identical "parametric constants",
867 * as explained above.
868 * In this case, we also insist that the coefficients of the big parameter
869 * be the same as the values of the constants will only be the same
870 * if these coefficients are also the same.
872 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
874 int i;
875 unsigned off = 2 + tab->M;
877 if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
878 return 0;
880 if (tab->M && isl_int_ne(tab->mat->row[row1][2],
881 tab->mat->row[row2][2]))
882 return 0;
884 for (i = 0; i < tab->n_param + tab->n_div; ++i) {
885 int pos = i < tab->n_param ? i :
886 tab->n_var - tab->n_div + i - tab->n_param;
887 int col;
889 if (tab->var[pos].is_row)
890 continue;
891 col = tab->var[pos].index;
892 if (isl_int_ne(tab->mat->row[row1][off + col],
893 tab->mat->row[row2][off + col]))
894 return 0;
896 return 1;
899 /* Return an inequality that expresses that the "parametric constant"
900 * should be non-negative.
901 * This function is only called when the coefficient of the big parameter
902 * is equal to zero.
904 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
906 struct isl_vec *ineq;
908 ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
909 if (!ineq)
910 return NULL;
912 get_row_parameter_line(tab, row, ineq->el);
913 if (ineq)
914 ineq = isl_vec_normalize(ineq);
916 return ineq;
919 /* Normalize a div expression of the form
921 * [(g*f(x) + c)/(g * m)]
923 * with c the constant term and f(x) the remaining coefficients, to
925 * [(f(x) + [c/g])/m]
927 static void normalize_div(__isl_keep isl_vec *div)
929 isl_ctx *ctx = isl_vec_get_ctx(div);
930 int len = div->size - 2;
932 isl_seq_gcd(div->el + 2, len, &ctx->normalize_gcd);
933 isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, div->el[0]);
935 if (isl_int_is_one(ctx->normalize_gcd))
936 return;
938 isl_int_divexact(div->el[0], div->el[0], ctx->normalize_gcd);
939 isl_int_fdiv_q(div->el[1], div->el[1], ctx->normalize_gcd);
940 isl_seq_scale_down(div->el + 2, div->el + 2, ctx->normalize_gcd, len);
943 /* Return an integer division for use in a parametric cut based
944 * on the given row.
945 * In particular, let the parametric constant of the row be
947 * \sum_i a_i y_i
949 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
950 * The div returned is equal to
952 * floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
954 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
956 struct isl_vec *div;
958 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
959 if (!div)
960 return NULL;
962 isl_int_set(div->el[0], tab->mat->row[row][0]);
963 get_row_parameter_line(tab, row, div->el + 1);
964 isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
965 normalize_div(div);
966 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
968 return div;
971 /* Return an integer division for use in transferring an integrality constraint
972 * to the context.
973 * In particular, let the parametric constant of the row be
975 * \sum_i a_i y_i
977 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
978 * The the returned div is equal to
980 * floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
982 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
984 struct isl_vec *div;
986 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
987 if (!div)
988 return NULL;
990 isl_int_set(div->el[0], tab->mat->row[row][0]);
991 get_row_parameter_line(tab, row, div->el + 1);
992 normalize_div(div);
993 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
995 return div;
998 /* Construct and return an inequality that expresses an upper bound
999 * on the given div.
1000 * In particular, if the div is given by
1002 * d = floor(e/m)
1004 * then the inequality expresses
1006 * m d <= e
1008 static __isl_give isl_vec *ineq_for_div(__isl_keep isl_basic_set *bset,
1009 unsigned div)
1011 isl_size total;
1012 unsigned div_pos;
1013 struct isl_vec *ineq;
1015 total = isl_basic_set_dim(bset, isl_dim_all);
1016 if (total < 0)
1017 return NULL;
1019 div_pos = 1 + total - bset->n_div + div;
1021 ineq = isl_vec_alloc(bset->ctx, 1 + total);
1022 if (!ineq)
1023 return NULL;
1025 isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
1026 isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
1027 return ineq;
1030 /* Given a row in the tableau and a div that was created
1031 * using get_row_split_div and that has been constrained to equality, i.e.,
1033 * d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
1035 * replace the expression "\sum_i {a_i} y_i" in the row by d,
1036 * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
1037 * The coefficients of the non-parameters in the tableau have been
1038 * verified to be integral. We can therefore simply replace coefficient b
1039 * by floor(b). For the coefficients of the parameters we have
1040 * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
1041 * floor(b) = b.
1043 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
1045 isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
1046 tab->mat->row[row][0], 1 + tab->M + tab->n_col);
1048 isl_int_set_si(tab->mat->row[row][0], 1);
1050 if (tab->var[tab->n_var - tab->n_div + div].is_row) {
1051 int drow = tab->var[tab->n_var - tab->n_div + div].index;
1053 isl_assert(tab->mat->ctx,
1054 isl_int_is_one(tab->mat->row[drow][0]), goto error);
1055 isl_seq_combine(tab->mat->row[row] + 1,
1056 tab->mat->ctx->one, tab->mat->row[row] + 1,
1057 tab->mat->ctx->one, tab->mat->row[drow] + 1,
1058 1 + tab->M + tab->n_col);
1059 } else {
1060 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
1062 isl_int_add_ui(tab->mat->row[row][2 + tab->M + dcol],
1063 tab->mat->row[row][2 + tab->M + dcol], 1);
1066 return tab;
1067 error:
1068 isl_tab_free(tab);
1069 return NULL;
1072 /* Check if the (parametric) constant of the given row is obviously
1073 * negative, meaning that we don't need to consult the context tableau.
1074 * If there is a big parameter and its coefficient is non-zero,
1075 * then this coefficient determines the outcome.
1076 * Otherwise, we check whether the constant is negative and
1077 * all non-zero coefficients of parameters are negative and
1078 * belong to non-negative parameters.
1080 static int is_obviously_neg(struct isl_tab *tab, int row)
1082 int i;
1083 int col;
1084 unsigned off = 2 + tab->M;
1086 if (tab->M) {
1087 if (isl_int_is_pos(tab->mat->row[row][2]))
1088 return 0;
1089 if (isl_int_is_neg(tab->mat->row[row][2]))
1090 return 1;
1093 if (isl_int_is_nonneg(tab->mat->row[row][1]))
1094 return 0;
1095 for (i = 0; i < tab->n_param; ++i) {
1096 /* Eliminated parameter */
1097 if (tab->var[i].is_row)
1098 continue;
1099 col = tab->var[i].index;
1100 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1101 continue;
1102 if (!tab->var[i].is_nonneg)
1103 return 0;
1104 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1105 return 0;
1107 for (i = 0; i < tab->n_div; ++i) {
1108 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1109 continue;
1110 col = tab->var[tab->n_var - tab->n_div + i].index;
1111 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1112 continue;
1113 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1114 return 0;
1115 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1116 return 0;
1118 return 1;
1121 /* Check if the (parametric) constant of the given row is obviously
1122 * non-negative, meaning that we don't need to consult the context tableau.
1123 * If there is a big parameter and its coefficient is non-zero,
1124 * then this coefficient determines the outcome.
1125 * Otherwise, we check whether the constant is non-negative and
1126 * all non-zero coefficients of parameters are positive and
1127 * belong to non-negative parameters.
1129 static int is_obviously_nonneg(struct isl_tab *tab, int row)
1131 int i;
1132 int col;
1133 unsigned off = 2 + tab->M;
1135 if (tab->M) {
1136 if (isl_int_is_pos(tab->mat->row[row][2]))
1137 return 1;
1138 if (isl_int_is_neg(tab->mat->row[row][2]))
1139 return 0;
1142 if (isl_int_is_neg(tab->mat->row[row][1]))
1143 return 0;
1144 for (i = 0; i < tab->n_param; ++i) {
1145 /* Eliminated parameter */
1146 if (tab->var[i].is_row)
1147 continue;
1148 col = tab->var[i].index;
1149 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1150 continue;
1151 if (!tab->var[i].is_nonneg)
1152 return 0;
1153 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1154 return 0;
1156 for (i = 0; i < tab->n_div; ++i) {
1157 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1158 continue;
1159 col = tab->var[tab->n_var - tab->n_div + i].index;
1160 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1161 continue;
1162 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1163 return 0;
1164 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1165 return 0;
1167 return 1;
1170 /* Given a row r and two columns, return the column that would
1171 * lead to the lexicographically smallest increment in the sample
1172 * solution when leaving the basis in favor of the row.
1173 * Pivoting with column c will increment the sample value by a non-negative
1174 * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
1175 * corresponding to the non-parametric variables.
1176 * If variable v appears in a column c_v, then a_{v,c} = 1 iff c = c_v,
1177 * with all other entries in this virtual row equal to zero.
1178 * If variable v appears in a row, then a_{v,c} is the element in column c
1179 * of that row.
1181 * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
1182 * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
1183 * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
1184 * increment. Otherwise, it's c2.
1186 static int lexmin_col_pair(struct isl_tab *tab,
1187 int row, int col1, int col2, isl_int tmp)
1189 int i;
1190 isl_int *tr;
1192 tr = tab->mat->row[row] + 2 + tab->M;
1194 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1195 int s1, s2;
1196 isl_int *r;
1198 if (!tab->var[i].is_row) {
1199 if (tab->var[i].index == col1)
1200 return col2;
1201 if (tab->var[i].index == col2)
1202 return col1;
1203 continue;
1206 if (tab->var[i].index == row)
1207 continue;
1209 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1210 s1 = isl_int_sgn(r[col1]);
1211 s2 = isl_int_sgn(r[col2]);
1212 if (s1 == 0 && s2 == 0)
1213 continue;
1214 if (s1 < s2)
1215 return col1;
1216 if (s2 < s1)
1217 return col2;
1219 isl_int_mul(tmp, r[col2], tr[col1]);
1220 isl_int_submul(tmp, r[col1], tr[col2]);
1221 if (isl_int_is_pos(tmp))
1222 return col1;
1223 if (isl_int_is_neg(tmp))
1224 return col2;
1226 return -1;
1229 /* Does the index into the tab->var or tab->con array "index"
1230 * correspond to a variable in the context tableau?
1231 * In particular, it needs to be an index into the tab->var array and
1232 * it needs to refer to either one of the first tab->n_param variables or
1233 * one of the last tab->n_div variables.
1235 static int is_parameter_var(struct isl_tab *tab, int index)
1237 if (index < 0)
1238 return 0;
1239 if (index < tab->n_param)
1240 return 1;
1241 if (index >= tab->n_var - tab->n_div)
1242 return 1;
1243 return 0;
1246 /* Does column "col" of "tab" refer to a variable in the context tableau?
1248 static int col_is_parameter_var(struct isl_tab *tab, int col)
1250 return is_parameter_var(tab, tab->col_var[col]);
1253 /* Does row "row" of "tab" refer to a variable in the context tableau?
1255 static int row_is_parameter_var(struct isl_tab *tab, int row)
1257 return is_parameter_var(tab, tab->row_var[row]);
1260 /* Given a row in the tableau, find and return the column that would
1261 * result in the lexicographically smallest, but positive, increment
1262 * in the sample point.
1263 * If there is no such column, then return tab->n_col.
1264 * If anything goes wrong, return -1.
1266 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1268 int j;
1269 int col = tab->n_col;
1270 isl_int *tr;
1271 isl_int tmp;
1273 tr = tab->mat->row[row] + 2 + tab->M;
1275 isl_int_init(tmp);
1277 for (j = tab->n_dead; j < tab->n_col; ++j) {
1278 if (col_is_parameter_var(tab, j))
1279 continue;
1281 if (!isl_int_is_pos(tr[j]))
1282 continue;
1284 if (col == tab->n_col)
1285 col = j;
1286 else
1287 col = lexmin_col_pair(tab, row, col, j, tmp);
1288 isl_assert(tab->mat->ctx, col >= 0, goto error);
1291 isl_int_clear(tmp);
1292 return col;
1293 error:
1294 isl_int_clear(tmp);
1295 return -1;
1298 /* Return the first known violated constraint, i.e., a non-negative
1299 * constraint that currently has an either obviously negative value
1300 * or a previously determined to be negative value.
1302 * If any constraint has a negative coefficient for the big parameter,
1303 * if any, then we return one of these first.
1305 static int first_neg(struct isl_tab *tab)
1307 int row;
1309 if (tab->M)
1310 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1311 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1312 continue;
1313 if (!isl_int_is_neg(tab->mat->row[row][2]))
1314 continue;
1315 if (tab->row_sign)
1316 tab->row_sign[row] = isl_tab_row_neg;
1317 return row;
1319 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1320 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1321 continue;
1322 if (tab->row_sign) {
1323 if (tab->row_sign[row] == 0 &&
1324 is_obviously_neg(tab, row))
1325 tab->row_sign[row] = isl_tab_row_neg;
1326 if (tab->row_sign[row] != isl_tab_row_neg)
1327 continue;
1328 } else if (!is_obviously_neg(tab, row))
1329 continue;
1330 return row;
1332 return -1;
1335 /* Check whether the invariant that all columns are lexico-positive
1336 * is satisfied. This function is not called from the current code
1337 * but is useful during debugging.
1339 static void check_lexpos(struct isl_tab *tab) __attribute__ ((unused));
1340 static void check_lexpos(struct isl_tab *tab)
1342 unsigned off = 2 + tab->M;
1343 int col;
1344 int var;
1345 int row;
1347 for (col = tab->n_dead; col < tab->n_col; ++col) {
1348 if (col_is_parameter_var(tab, col))
1349 continue;
1350 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1351 if (!tab->var[var].is_row) {
1352 if (tab->var[var].index == col)
1353 break;
1354 else
1355 continue;
1357 row = tab->var[var].index;
1358 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1359 continue;
1360 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1361 break;
1362 fprintf(stderr, "lexneg column %d (row %d)\n",
1363 col, row);
1365 if (var >= tab->n_var - tab->n_div)
1366 fprintf(stderr, "zero column %d\n", col);
1370 /* Report to the caller that the given constraint is part of an encountered
1371 * conflict.
1373 static int report_conflicting_constraint(struct isl_tab *tab, int con)
1375 return tab->conflict(con, tab->conflict_user);
1378 /* Given a conflicting row in the tableau, report all constraints
1379 * involved in the row to the caller. That is, the row itself
1380 * (if it represents a constraint) and all constraint columns with
1381 * non-zero (and therefore negative) coefficients.
1383 static int report_conflict(struct isl_tab *tab, int row)
1385 int j;
1386 isl_int *tr;
1388 if (!tab->conflict)
1389 return 0;
1391 if (tab->row_var[row] < 0 &&
1392 report_conflicting_constraint(tab, ~tab->row_var[row]) < 0)
1393 return -1;
1395 tr = tab->mat->row[row] + 2 + tab->M;
1397 for (j = tab->n_dead; j < tab->n_col; ++j) {
1398 if (col_is_parameter_var(tab, j))
1399 continue;
1401 if (!isl_int_is_neg(tr[j]))
1402 continue;
1404 if (tab->col_var[j] < 0 &&
1405 report_conflicting_constraint(tab, ~tab->col_var[j]) < 0)
1406 return -1;
1409 return 0;
1412 /* Resolve all known or obviously violated constraints through pivoting.
1413 * In particular, as long as we can find any violated constraint, we
1414 * look for a pivoting column that would result in the lexicographically
1415 * smallest increment in the sample point. If there is no such column
1416 * then the tableau is infeasible.
1418 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1419 static int restore_lexmin(struct isl_tab *tab)
1421 int row, col;
1423 if (!tab)
1424 return -1;
1425 if (tab->empty)
1426 return 0;
1427 while ((row = first_neg(tab)) != -1) {
1428 col = lexmin_pivot_col(tab, row);
1429 if (col >= tab->n_col) {
1430 if (report_conflict(tab, row) < 0)
1431 return -1;
1432 if (isl_tab_mark_empty(tab) < 0)
1433 return -1;
1434 return 0;
1436 if (col < 0)
1437 return -1;
1438 if (isl_tab_pivot(tab, row, col) < 0)
1439 return -1;
1441 return 0;
1444 /* Given a row that represents an equality, look for an appropriate
1445 * pivoting column.
1446 * In particular, if there are any non-zero coefficients among
1447 * the non-parameter variables, then we take the last of these
1448 * variables. Eliminating this variable in terms of the other
1449 * variables and/or parameters does not influence the property
1450 * that all column in the initial tableau are lexicographically
1451 * positive. The row corresponding to the eliminated variable
1452 * will only have non-zero entries below the diagonal of the
1453 * initial tableau. That is, we transform
1455 * I I
1456 * 1 into a
1457 * I I
1459 * If there is no such non-parameter variable, then we are dealing with
1460 * pure parameter equality and we pick any parameter with coefficient 1 or -1
1461 * for elimination. This will ensure that the eliminated parameter
1462 * always has an integer value whenever all the other parameters are integral.
1463 * If there is no such parameter then we return -1.
1465 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1467 unsigned off = 2 + tab->M;
1468 int i;
1470 for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1471 int col;
1472 if (tab->var[i].is_row)
1473 continue;
1474 col = tab->var[i].index;
1475 if (col <= tab->n_dead)
1476 continue;
1477 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1478 return col;
1480 for (i = tab->n_dead; i < tab->n_col; ++i) {
1481 if (isl_int_is_one(tab->mat->row[row][off + i]))
1482 return i;
1483 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1484 return i;
1486 return -1;
1489 /* Add an equality that is known to be valid to the tableau.
1490 * We first check if we can eliminate a variable or a parameter.
1491 * If not, we add the equality as two inequalities.
1492 * In this case, the equality was a pure parameter equality and there
1493 * is no need to resolve any constraint violations.
1495 * This function assumes that at least two more rows and at least
1496 * two more elements in the constraint array are available in the tableau.
1498 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1500 int i;
1501 int r;
1503 if (!tab)
1504 return NULL;
1505 r = isl_tab_add_row(tab, eq);
1506 if (r < 0)
1507 goto error;
1509 r = tab->con[r].index;
1510 i = last_var_col_or_int_par_col(tab, r);
1511 if (i < 0) {
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 isl_seq_neg(eq, eq, 1 + tab->n_var);
1516 r = isl_tab_add_row(tab, eq);
1517 if (r < 0)
1518 goto error;
1519 tab->con[r].is_nonneg = 1;
1520 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1521 goto error;
1522 } else {
1523 if (isl_tab_pivot(tab, r, i) < 0)
1524 goto error;
1525 if (isl_tab_kill_col(tab, i) < 0)
1526 goto error;
1527 tab->n_eq++;
1530 return tab;
1531 error:
1532 isl_tab_free(tab);
1533 return NULL;
1536 /* Check if the given row is a pure constant.
1538 static int is_constant(struct isl_tab *tab, int row)
1540 unsigned off = 2 + tab->M;
1542 return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1543 tab->n_col - tab->n_dead) == -1;
1546 /* Is the given row a parametric constant?
1547 * That is, does it only involve variables that also appear in the context?
1549 static int is_parametric_constant(struct isl_tab *tab, int row)
1551 unsigned off = 2 + tab->M;
1552 int col;
1554 for (col = tab->n_dead; col < tab->n_col; ++col) {
1555 if (col_is_parameter_var(tab, col))
1556 continue;
1557 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1558 continue;
1559 return 0;
1562 return 1;
1565 /* Add an equality that may or may not be valid to the tableau.
1566 * If the resulting row is a pure constant, then it must be zero.
1567 * Otherwise, the resulting tableau is empty.
1569 * If the row is not a pure constant, then we add two inequalities,
1570 * each time checking that they can be satisfied.
1571 * In the end we try to use one of the two constraints to eliminate
1572 * a column.
1574 * This function assumes that at least two more rows and at least
1575 * two more elements in the constraint array are available in the tableau.
1577 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1578 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1580 int r1, r2;
1581 int row;
1582 struct isl_tab_undo *snap;
1584 if (!tab)
1585 return -1;
1586 snap = isl_tab_snap(tab);
1587 r1 = isl_tab_add_row(tab, eq);
1588 if (r1 < 0)
1589 return -1;
1590 tab->con[r1].is_nonneg = 1;
1591 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1592 return -1;
1594 row = tab->con[r1].index;
1595 if (is_constant(tab, row)) {
1596 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1597 (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1598 if (isl_tab_mark_empty(tab) < 0)
1599 return -1;
1600 return 0;
1602 if (isl_tab_rollback(tab, snap) < 0)
1603 return -1;
1604 return 0;
1607 if (restore_lexmin(tab) < 0)
1608 return -1;
1609 if (tab->empty)
1610 return 0;
1612 isl_seq_neg(eq, eq, 1 + tab->n_var);
1614 r2 = isl_tab_add_row(tab, eq);
1615 if (r2 < 0)
1616 return -1;
1617 tab->con[r2].is_nonneg = 1;
1618 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1619 return -1;
1621 if (restore_lexmin(tab) < 0)
1622 return -1;
1623 if (tab->empty)
1624 return 0;
1626 if (!tab->con[r1].is_row) {
1627 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1628 return -1;
1629 } else if (!tab->con[r2].is_row) {
1630 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1631 return -1;
1634 if (tab->bmap) {
1635 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1636 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1637 return -1;
1638 isl_seq_neg(eq, eq, 1 + tab->n_var);
1639 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1640 isl_seq_neg(eq, eq, 1 + tab->n_var);
1641 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1642 return -1;
1643 if (!tab->bmap)
1644 return -1;
1647 return 0;
1650 /* Add an inequality to the tableau, resolving violations using
1651 * restore_lexmin.
1653 * This function assumes that at least one more row and at least
1654 * one more element in the constraint array are available in the tableau.
1656 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1658 int r;
1660 if (!tab)
1661 return NULL;
1662 if (tab->bmap) {
1663 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1664 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1665 goto error;
1666 if (!tab->bmap)
1667 goto error;
1669 r = isl_tab_add_row(tab, ineq);
1670 if (r < 0)
1671 goto error;
1672 tab->con[r].is_nonneg = 1;
1673 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1674 goto error;
1675 if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1676 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1677 goto error;
1678 return tab;
1681 if (restore_lexmin(tab) < 0)
1682 goto error;
1683 if (!tab->empty && tab->con[r].is_row &&
1684 isl_tab_row_is_redundant(tab, tab->con[r].index))
1685 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1686 goto error;
1687 return tab;
1688 error:
1689 isl_tab_free(tab);
1690 return NULL;
1693 /* Check if the coefficients of the parameters are all integral.
1695 static int integer_parameter(struct isl_tab *tab, int row)
1697 int i;
1698 int col;
1699 unsigned off = 2 + tab->M;
1701 for (i = 0; i < tab->n_param; ++i) {
1702 /* Eliminated parameter */
1703 if (tab->var[i].is_row)
1704 continue;
1705 col = tab->var[i].index;
1706 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1707 tab->mat->row[row][0]))
1708 return 0;
1710 for (i = 0; i < tab->n_div; ++i) {
1711 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1712 continue;
1713 col = tab->var[tab->n_var - tab->n_div + i].index;
1714 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1715 tab->mat->row[row][0]))
1716 return 0;
1718 return 1;
1721 /* Check if the coefficients of the non-parameter variables are all integral.
1723 static int integer_variable(struct isl_tab *tab, int row)
1725 int i;
1726 unsigned off = 2 + tab->M;
1728 for (i = tab->n_dead; i < tab->n_col; ++i) {
1729 if (col_is_parameter_var(tab, i))
1730 continue;
1731 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1732 tab->mat->row[row][0]))
1733 return 0;
1735 return 1;
1738 /* Check if the constant term is integral.
1740 static int integer_constant(struct isl_tab *tab, int row)
1742 return isl_int_is_divisible_by(tab->mat->row[row][1],
1743 tab->mat->row[row][0]);
1746 #define I_CST 1 << 0
1747 #define I_PAR 1 << 1
1748 #define I_VAR 1 << 2
1750 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1751 * that is non-integer and therefore requires a cut and return
1752 * the index of the variable.
1753 * For parametric tableaus, there are three parts in a row,
1754 * the constant, the coefficients of the parameters and the rest.
1755 * For each part, we check whether the coefficients in that part
1756 * are all integral and if so, set the corresponding flag in *f.
1757 * If the constant and the parameter part are integral, then the
1758 * current sample value is integral and no cut is required
1759 * (irrespective of whether the variable part is integral).
1761 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1763 var = var < 0 ? tab->n_param : var + 1;
1765 for (; var < tab->n_var - tab->n_div; ++var) {
1766 int flags = 0;
1767 int row;
1768 if (!tab->var[var].is_row)
1769 continue;
1770 row = tab->var[var].index;
1771 if (integer_constant(tab, row))
1772 ISL_FL_SET(flags, I_CST);
1773 if (integer_parameter(tab, row))
1774 ISL_FL_SET(flags, I_PAR);
1775 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1776 continue;
1777 if (integer_variable(tab, row))
1778 ISL_FL_SET(flags, I_VAR);
1779 *f = flags;
1780 return var;
1782 return -1;
1785 /* Check for first (non-parameter) variable that is non-integer and
1786 * therefore requires a cut and return the corresponding row.
1787 * For parametric tableaus, there are three parts in a row,
1788 * the constant, the coefficients of the parameters and the rest.
1789 * For each part, we check whether the coefficients in that part
1790 * are all integral and if so, set the corresponding flag in *f.
1791 * If the constant and the parameter part are integral, then the
1792 * current sample value is integral and no cut is required
1793 * (irrespective of whether the variable part is integral).
1795 static int first_non_integer_row(struct isl_tab *tab, int *f)
1797 int var = next_non_integer_var(tab, -1, f);
1799 return var < 0 ? -1 : tab->var[var].index;
1802 /* Add a (non-parametric) cut to cut away the non-integral sample
1803 * value of the given row.
1805 * If the row is given by
1807 * m r = f + \sum_i a_i y_i
1809 * then the cut is
1811 * c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1813 * The big parameter, if any, is ignored, since it is assumed to be big
1814 * enough to be divisible by any integer.
1815 * If the tableau is actually a parametric tableau, then this function
1816 * is only called when all coefficients of the parameters are integral.
1817 * The cut therefore has zero coefficients for the parameters.
1819 * The current value is known to be negative, so row_sign, if it
1820 * exists, is set accordingly.
1822 * Return the row of the cut or -1.
1824 static int add_cut(struct isl_tab *tab, int row)
1826 int i;
1827 int r;
1828 isl_int *r_row;
1829 unsigned off = 2 + tab->M;
1831 if (isl_tab_extend_cons(tab, 1) < 0)
1832 return -1;
1833 r = isl_tab_allocate_con(tab);
1834 if (r < 0)
1835 return -1;
1837 r_row = tab->mat->row[tab->con[r].index];
1838 isl_int_set(r_row[0], tab->mat->row[row][0]);
1839 isl_int_neg(r_row[1], tab->mat->row[row][1]);
1840 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1841 isl_int_neg(r_row[1], r_row[1]);
1842 if (tab->M)
1843 isl_int_set_si(r_row[2], 0);
1844 for (i = 0; i < tab->n_col; ++i)
1845 isl_int_fdiv_r(r_row[off + i],
1846 tab->mat->row[row][off + i], tab->mat->row[row][0]);
1848 tab->con[r].is_nonneg = 1;
1849 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1850 return -1;
1851 if (tab->row_sign)
1852 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1854 return tab->con[r].index;
1857 #define CUT_ALL 1
1858 #define CUT_ONE 0
1860 /* Given a non-parametric tableau, add cuts until an integer
1861 * sample point is obtained or until the tableau is determined
1862 * to be integer infeasible.
1863 * As long as there is any non-integer value in the sample point,
1864 * we add appropriate cuts, if possible, for each of these
1865 * non-integer values and then resolve the violated
1866 * cut constraints using restore_lexmin.
1867 * If one of the corresponding rows is equal to an integral
1868 * combination of variables/constraints plus a non-integral constant,
1869 * then there is no way to obtain an integer point and we return
1870 * a tableau that is marked empty.
1871 * The parameter cutting_strategy controls the strategy used when adding cuts
1872 * to remove non-integer points. CUT_ALL adds all possible cuts
1873 * before continuing the search. CUT_ONE adds only one cut at a time.
1875 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab,
1876 int cutting_strategy)
1878 int var;
1879 int row;
1880 int flags;
1882 if (!tab)
1883 return NULL;
1884 if (tab->empty)
1885 return tab;
1887 while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1888 do {
1889 if (ISL_FL_ISSET(flags, I_VAR)) {
1890 if (isl_tab_mark_empty(tab) < 0)
1891 goto error;
1892 return tab;
1894 row = tab->var[var].index;
1895 row = add_cut(tab, row);
1896 if (row < 0)
1897 goto error;
1898 if (cutting_strategy == CUT_ONE)
1899 break;
1900 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1901 if (restore_lexmin(tab) < 0)
1902 goto error;
1903 if (tab->empty)
1904 break;
1906 return tab;
1907 error:
1908 isl_tab_free(tab);
1909 return NULL;
1912 /* Check whether all the currently active samples also satisfy the inequality
1913 * "ineq" (treated as an equality if eq is set).
1914 * Remove those samples that do not.
1916 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1918 int i;
1919 isl_int v;
1921 if (!tab)
1922 return NULL;
1924 isl_assert(tab->mat->ctx, tab->bmap, goto error);
1925 isl_assert(tab->mat->ctx, tab->samples, goto error);
1926 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1928 isl_int_init(v);
1929 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1930 int sgn;
1931 isl_seq_inner_product(ineq, tab->samples->row[i],
1932 1 + tab->n_var, &v);
1933 sgn = isl_int_sgn(v);
1934 if (eq ? (sgn == 0) : (sgn >= 0))
1935 continue;
1936 tab = isl_tab_drop_sample(tab, i);
1937 if (!tab)
1938 break;
1940 isl_int_clear(v);
1942 return tab;
1943 error:
1944 isl_tab_free(tab);
1945 return NULL;
1948 /* Check whether the sample value of the tableau is finite,
1949 * i.e., either the tableau does not use a big parameter, or
1950 * all values of the variables are equal to the big parameter plus
1951 * some constant. This constant is the actual sample value.
1953 static int sample_is_finite(struct isl_tab *tab)
1955 int i;
1957 if (!tab->M)
1958 return 1;
1960 for (i = 0; i < tab->n_var; ++i) {
1961 int row;
1962 if (!tab->var[i].is_row)
1963 return 0;
1964 row = tab->var[i].index;
1965 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1966 return 0;
1968 return 1;
1971 /* Check if the context tableau of sol has any integer points.
1972 * Leave tab in empty state if no integer point can be found.
1973 * If an integer point can be found and if moreover it is finite,
1974 * then it is added to the list of sample values.
1976 * This function is only called when none of the currently active sample
1977 * values satisfies the most recently added constraint.
1979 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1981 struct isl_tab_undo *snap;
1983 if (!tab)
1984 return NULL;
1986 snap = isl_tab_snap(tab);
1987 if (isl_tab_push_basis(tab) < 0)
1988 goto error;
1990 tab = cut_to_integer_lexmin(tab, CUT_ALL);
1991 if (!tab)
1992 goto error;
1994 if (!tab->empty && sample_is_finite(tab)) {
1995 struct isl_vec *sample;
1997 sample = isl_tab_get_sample_value(tab);
1999 if (isl_tab_add_sample(tab, sample) < 0)
2000 goto error;
2003 if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
2004 goto error;
2006 return tab;
2007 error:
2008 isl_tab_free(tab);
2009 return NULL;
2012 /* Check if any of the currently active sample values satisfies
2013 * the inequality "ineq" (an equality if eq is set).
2015 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
2017 int i;
2018 isl_int v;
2020 if (!tab)
2021 return -1;
2023 isl_assert(tab->mat->ctx, tab->bmap, return -1);
2024 isl_assert(tab->mat->ctx, tab->samples, return -1);
2025 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
2027 isl_int_init(v);
2028 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2029 int sgn;
2030 isl_seq_inner_product(ineq, tab->samples->row[i],
2031 1 + tab->n_var, &v);
2032 sgn = isl_int_sgn(v);
2033 if (eq ? (sgn == 0) : (sgn >= 0))
2034 break;
2036 isl_int_clear(v);
2038 return i < tab->n_sample;
2041 /* Insert a div specified by "div" to the tableau "tab" at position "pos" and
2042 * return isl_bool_true if the div is obviously non-negative.
2044 static isl_bool context_tab_insert_div(struct isl_tab *tab, int pos,
2045 __isl_keep isl_vec *div,
2046 isl_stat (*add_ineq)(void *user, isl_int *), void *user)
2048 int i;
2049 int r;
2050 struct isl_mat *samples;
2051 int nonneg;
2053 r = isl_tab_insert_div(tab, pos, div, add_ineq, user);
2054 if (r < 0)
2055 return isl_bool_error;
2056 nonneg = tab->var[r].is_nonneg;
2057 tab->var[r].frozen = 1;
2059 samples = isl_mat_extend(tab->samples,
2060 tab->n_sample, 1 + tab->n_var);
2061 tab->samples = samples;
2062 if (!samples)
2063 return isl_bool_error;
2064 for (i = tab->n_outside; i < samples->n_row; ++i) {
2065 isl_seq_inner_product(div->el + 1, samples->row[i],
2066 div->size - 1, &samples->row[i][samples->n_col - 1]);
2067 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
2068 samples->row[i][samples->n_col - 1], div->el[0]);
2070 tab->samples = isl_mat_move_cols(tab->samples, 1 + pos,
2071 1 + tab->n_var - 1, 1);
2072 if (!tab->samples)
2073 return isl_bool_error;
2075 return nonneg;
2078 /* Add a div specified by "div" to both the main tableau and
2079 * the context tableau. In case of the main tableau, we only
2080 * need to add an extra div. In the context tableau, we also
2081 * need to express the meaning of the div.
2082 * Return the index of the div or -1 if anything went wrong.
2084 * The new integer division is added before any unknown integer
2085 * divisions in the context to ensure that it does not get
2086 * equated to some linear combination involving unknown integer
2087 * divisions.
2089 static int add_div(struct isl_tab *tab, struct isl_context *context,
2090 __isl_keep isl_vec *div)
2092 int r;
2093 int pos;
2094 isl_bool nonneg;
2095 struct isl_tab *context_tab = context->op->peek_tab(context);
2097 if (!tab || !context_tab)
2098 goto error;
2100 pos = context_tab->n_var - context->n_unknown;
2101 if ((nonneg = context->op->insert_div(context, pos, div)) < 0)
2102 goto error;
2104 if (!context->op->is_ok(context))
2105 goto error;
2107 pos = tab->n_var - context->n_unknown;
2108 if (isl_tab_extend_vars(tab, 1) < 0)
2109 goto error;
2110 r = isl_tab_insert_var(tab, pos);
2111 if (r < 0)
2112 goto error;
2113 if (nonneg)
2114 tab->var[r].is_nonneg = 1;
2115 tab->var[r].frozen = 1;
2116 tab->n_div++;
2118 return tab->n_div - 1 - context->n_unknown;
2119 error:
2120 context->op->invalidate(context);
2121 return -1;
2124 /* Return the position of the integer division that is equal to div/denom
2125 * if there is one. Otherwise, return a position beyond the integer divisions.
2127 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
2129 int i;
2130 isl_size total = isl_basic_map_dim(tab->bmap, isl_dim_all);
2131 isl_size n_div;
2133 n_div = isl_basic_map_dim(tab->bmap, isl_dim_div);
2134 if (total < 0 || n_div < 0)
2135 return -1;
2136 for (i = 0; i < n_div; ++i) {
2137 if (isl_int_ne(tab->bmap->div[i][0], denom))
2138 continue;
2139 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
2140 continue;
2141 return i;
2143 return n_div;
2146 /* Return the index of a div that corresponds to "div".
2147 * We first check if we already have such a div and if not, we create one.
2149 static int get_div(struct isl_tab *tab, struct isl_context *context,
2150 struct isl_vec *div)
2152 int d;
2153 struct isl_tab *context_tab = context->op->peek_tab(context);
2154 unsigned n_div;
2156 if (!context_tab)
2157 return -1;
2159 n_div = isl_basic_map_dim(context_tab->bmap, isl_dim_div);
2160 d = find_div(context_tab, div->el + 1, div->el[0]);
2161 if (d < 0)
2162 return -1;
2163 if (d < n_div)
2164 return d;
2166 return add_div(tab, context, div);
2169 /* Add a parametric cut to cut away the non-integral sample value
2170 * of the given row.
2171 * Let a_i be the coefficients of the constant term and the parameters
2172 * and let b_i be the coefficients of the variables or constraints
2173 * in basis of the tableau.
2174 * Let q be the div q = floor(\sum_i {-a_i} y_i).
2176 * The cut is expressed as
2178 * c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
2180 * If q did not already exist in the context tableau, then it is added first.
2181 * If q is in a column of the main tableau then the "+ q" can be accomplished
2182 * by setting the corresponding entry to the denominator of the constraint.
2183 * If q happens to be in a row of the main tableau, then the corresponding
2184 * row needs to be added instead (taking care of the denominators).
2185 * Note that this is very unlikely, but perhaps not entirely impossible.
2187 * The current value of the cut is known to be negative (or at least
2188 * non-positive), so row_sign is set accordingly.
2190 * Return the row of the cut or -1.
2192 static int add_parametric_cut(struct isl_tab *tab, int row,
2193 struct isl_context *context)
2195 struct isl_vec *div;
2196 int d;
2197 int i;
2198 int r;
2199 isl_int *r_row;
2200 int col;
2201 int n;
2202 unsigned off = 2 + tab->M;
2204 if (!context)
2205 return -1;
2207 div = get_row_parameter_div(tab, row);
2208 if (!div)
2209 return -1;
2211 n = tab->n_div - context->n_unknown;
2212 d = context->op->get_div(context, tab, div);
2213 isl_vec_free(div);
2214 if (d < 0)
2215 return -1;
2217 if (isl_tab_extend_cons(tab, 1) < 0)
2218 return -1;
2219 r = isl_tab_allocate_con(tab);
2220 if (r < 0)
2221 return -1;
2223 r_row = tab->mat->row[tab->con[r].index];
2224 isl_int_set(r_row[0], tab->mat->row[row][0]);
2225 isl_int_neg(r_row[1], tab->mat->row[row][1]);
2226 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
2227 isl_int_neg(r_row[1], r_row[1]);
2228 if (tab->M)
2229 isl_int_set_si(r_row[2], 0);
2230 for (i = 0; i < tab->n_param; ++i) {
2231 if (tab->var[i].is_row)
2232 continue;
2233 col = tab->var[i].index;
2234 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2235 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2236 tab->mat->row[row][0]);
2237 isl_int_neg(r_row[off + col], r_row[off + col]);
2239 for (i = 0; i < tab->n_div; ++i) {
2240 if (tab->var[tab->n_var - tab->n_div + i].is_row)
2241 continue;
2242 col = tab->var[tab->n_var - tab->n_div + i].index;
2243 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2244 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2245 tab->mat->row[row][0]);
2246 isl_int_neg(r_row[off + col], r_row[off + col]);
2248 for (i = 0; i < tab->n_col; ++i) {
2249 if (tab->col_var[i] >= 0 &&
2250 (tab->col_var[i] < tab->n_param ||
2251 tab->col_var[i] >= tab->n_var - tab->n_div))
2252 continue;
2253 isl_int_fdiv_r(r_row[off + i],
2254 tab->mat->row[row][off + i], tab->mat->row[row][0]);
2256 if (tab->var[tab->n_var - tab->n_div + d].is_row) {
2257 isl_int gcd;
2258 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
2259 isl_int_init(gcd);
2260 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
2261 isl_int_divexact(r_row[0], r_row[0], gcd);
2262 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
2263 isl_seq_combine(r_row + 1, gcd, r_row + 1,
2264 r_row[0], tab->mat->row[d_row] + 1,
2265 off - 1 + tab->n_col);
2266 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
2267 isl_int_clear(gcd);
2268 } else {
2269 col = tab->var[tab->n_var - tab->n_div + d].index;
2270 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
2273 tab->con[r].is_nonneg = 1;
2274 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
2275 return -1;
2276 if (tab->row_sign)
2277 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
2279 row = tab->con[r].index;
2281 if (d >= n && context->op->detect_equalities(context, tab) < 0)
2282 return -1;
2284 return row;
2287 /* Construct a tableau for bmap that can be used for computing
2288 * the lexicographic minimum (or maximum) of bmap.
2289 * If not NULL, then dom is the domain where the minimum
2290 * should be computed. In this case, we set up a parametric
2291 * tableau with row signs (initialized to "unknown").
2292 * If M is set, then the tableau will use a big parameter.
2293 * If max is set, then a maximum should be computed instead of a minimum.
2294 * This means that for each variable x, the tableau will contain the variable
2295 * x' = M - x, rather than x' = M + x. This in turn means that the coefficient
2296 * of the variables in all constraints are negated prior to adding them
2297 * to the tableau.
2299 static __isl_give struct isl_tab *tab_for_lexmin(__isl_keep isl_basic_map *bmap,
2300 __isl_keep isl_basic_set *dom, unsigned M, int max)
2302 int i;
2303 struct isl_tab *tab;
2304 unsigned n_var;
2305 unsigned o_var;
2306 isl_size total;
2308 total = isl_basic_map_dim(bmap, isl_dim_all);
2309 if (total < 0)
2310 return NULL;
2311 tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
2312 total, M);
2313 if (!tab)
2314 return NULL;
2316 tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
2317 if (dom) {
2318 isl_size dom_total;
2319 dom_total = isl_basic_set_dim(dom, isl_dim_all);
2320 if (dom_total < 0)
2321 goto error;
2322 tab->n_param = dom_total - dom->n_div;
2323 tab->n_div = dom->n_div;
2324 tab->row_sign = isl_calloc_array(bmap->ctx,
2325 enum isl_tab_row_sign, tab->mat->n_row);
2326 if (tab->mat->n_row && !tab->row_sign)
2327 goto error;
2329 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
2330 if (isl_tab_mark_empty(tab) < 0)
2331 goto error;
2332 return tab;
2335 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2336 tab->var[i].is_nonneg = 1;
2337 tab->var[i].frozen = 1;
2339 o_var = 1 + tab->n_param;
2340 n_var = tab->n_var - tab->n_param - tab->n_div;
2341 for (i = 0; i < bmap->n_eq; ++i) {
2342 if (max)
2343 isl_seq_neg(bmap->eq[i] + o_var,
2344 bmap->eq[i] + o_var, n_var);
2345 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2346 if (max)
2347 isl_seq_neg(bmap->eq[i] + o_var,
2348 bmap->eq[i] + o_var, n_var);
2349 if (!tab || tab->empty)
2350 return tab;
2352 if (bmap->n_eq && restore_lexmin(tab) < 0)
2353 goto error;
2354 for (i = 0; i < bmap->n_ineq; ++i) {
2355 if (max)
2356 isl_seq_neg(bmap->ineq[i] + o_var,
2357 bmap->ineq[i] + o_var, n_var);
2358 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2359 if (max)
2360 isl_seq_neg(bmap->ineq[i] + o_var,
2361 bmap->ineq[i] + o_var, n_var);
2362 if (!tab || tab->empty)
2363 return tab;
2365 return tab;
2366 error:
2367 isl_tab_free(tab);
2368 return NULL;
2371 /* Given a main tableau where more than one row requires a split,
2372 * determine and return the "best" row to split on.
2374 * If any of the rows requiring a split only involves
2375 * variables that also appear in the context tableau,
2376 * then the negative part is guaranteed not to have a solution.
2377 * It is therefore best to split on any of these rows first.
2379 * Otherwise,
2380 * given two rows in the main tableau, if the inequality corresponding
2381 * to the first row is redundant with respect to that of the second row
2382 * in the current tableau, then it is better to split on the second row,
2383 * since in the positive part, both rows will be positive.
2384 * (In the negative part a pivot will have to be performed and just about
2385 * anything can happen to the sign of the other row.)
2387 * As a simple heuristic, we therefore select the row that makes the most
2388 * of the other rows redundant.
2390 * Perhaps it would also be useful to look at the number of constraints
2391 * that conflict with any given constraint.
2393 * best is the best row so far (-1 when we have not found any row yet).
2394 * best_r is the number of other rows made redundant by row best.
2395 * When best is still -1, bset_r is meaningless, but it is initialized
2396 * to some arbitrary value (0) anyway. Without this redundant initialization
2397 * valgrind may warn about uninitialized memory accesses when isl
2398 * is compiled with some versions of gcc.
2400 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2402 struct isl_tab_undo *snap;
2403 int split;
2404 int row;
2405 int best = -1;
2406 int best_r = 0;
2408 if (isl_tab_extend_cons(context_tab, 2) < 0)
2409 return -1;
2411 snap = isl_tab_snap(context_tab);
2413 for (split = tab->n_redundant; split < tab->n_row; ++split) {
2414 struct isl_tab_undo *snap2;
2415 struct isl_vec *ineq = NULL;
2416 int r = 0;
2417 int ok;
2419 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2420 continue;
2421 if (tab->row_sign[split] != isl_tab_row_any)
2422 continue;
2424 if (is_parametric_constant(tab, split))
2425 return split;
2427 ineq = get_row_parameter_ineq(tab, split);
2428 if (!ineq)
2429 return -1;
2430 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2431 isl_vec_free(ineq);
2432 if (!ok)
2433 return -1;
2435 snap2 = isl_tab_snap(context_tab);
2437 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2438 struct isl_tab_var *var;
2440 if (row == split)
2441 continue;
2442 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2443 continue;
2444 if (tab->row_sign[row] != isl_tab_row_any)
2445 continue;
2447 ineq = get_row_parameter_ineq(tab, row);
2448 if (!ineq)
2449 return -1;
2450 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2451 isl_vec_free(ineq);
2452 if (!ok)
2453 return -1;
2454 var = &context_tab->con[context_tab->n_con - 1];
2455 if (!context_tab->empty &&
2456 !isl_tab_min_at_most_neg_one(context_tab, var))
2457 r++;
2458 if (isl_tab_rollback(context_tab, snap2) < 0)
2459 return -1;
2461 if (best == -1 || r > best_r) {
2462 best = split;
2463 best_r = r;
2465 if (isl_tab_rollback(context_tab, snap) < 0)
2466 return -1;
2469 return best;
2472 static struct isl_basic_set *context_lex_peek_basic_set(
2473 struct isl_context *context)
2475 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2476 if (!clex->tab)
2477 return NULL;
2478 return isl_tab_peek_bset(clex->tab);
2481 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2483 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2484 return clex->tab;
2487 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2488 int check, int update)
2490 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2491 if (isl_tab_extend_cons(clex->tab, 2) < 0)
2492 goto error;
2493 if (add_lexmin_eq(clex->tab, eq) < 0)
2494 goto error;
2495 if (check) {
2496 int v = tab_has_valid_sample(clex->tab, eq, 1);
2497 if (v < 0)
2498 goto error;
2499 if (!v)
2500 clex->tab = check_integer_feasible(clex->tab);
2502 if (update)
2503 clex->tab = check_samples(clex->tab, eq, 1);
2504 return;
2505 error:
2506 isl_tab_free(clex->tab);
2507 clex->tab = NULL;
2510 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2511 int check, int update)
2513 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2514 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2515 goto error;
2516 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2517 if (check) {
2518 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2519 if (v < 0)
2520 goto error;
2521 if (!v)
2522 clex->tab = check_integer_feasible(clex->tab);
2524 if (update)
2525 clex->tab = check_samples(clex->tab, ineq, 0);
2526 return;
2527 error:
2528 isl_tab_free(clex->tab);
2529 clex->tab = NULL;
2532 static isl_stat context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2534 struct isl_context *context = (struct isl_context *)user;
2535 context_lex_add_ineq(context, ineq, 0, 0);
2536 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
2539 /* Check which signs can be obtained by "ineq" on all the currently
2540 * active sample values. See row_sign for more information.
2542 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2543 int strict)
2545 int i;
2546 int sgn;
2547 isl_int tmp;
2548 enum isl_tab_row_sign res = isl_tab_row_unknown;
2550 isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2551 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2552 return isl_tab_row_unknown);
2554 isl_int_init(tmp);
2555 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2556 isl_seq_inner_product(tab->samples->row[i], ineq,
2557 1 + tab->n_var, &tmp);
2558 sgn = isl_int_sgn(tmp);
2559 if (sgn > 0 || (sgn == 0 && strict)) {
2560 if (res == isl_tab_row_unknown)
2561 res = isl_tab_row_pos;
2562 if (res == isl_tab_row_neg)
2563 res = isl_tab_row_any;
2565 if (sgn < 0) {
2566 if (res == isl_tab_row_unknown)
2567 res = isl_tab_row_neg;
2568 if (res == isl_tab_row_pos)
2569 res = isl_tab_row_any;
2571 if (res == isl_tab_row_any)
2572 break;
2574 isl_int_clear(tmp);
2576 return res;
2579 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2580 isl_int *ineq, int strict)
2582 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2583 return tab_ineq_sign(clex->tab, ineq, strict);
2586 /* Check whether "ineq" can be added to the tableau without rendering
2587 * it infeasible.
2589 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2591 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2592 struct isl_tab_undo *snap;
2593 int feasible;
2595 if (!clex->tab)
2596 return -1;
2598 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2599 return -1;
2601 snap = isl_tab_snap(clex->tab);
2602 if (isl_tab_push_basis(clex->tab) < 0)
2603 return -1;
2604 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2605 clex->tab = check_integer_feasible(clex->tab);
2606 if (!clex->tab)
2607 return -1;
2608 feasible = !clex->tab->empty;
2609 if (isl_tab_rollback(clex->tab, snap) < 0)
2610 return -1;
2612 return feasible;
2615 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2616 struct isl_vec *div)
2618 return get_div(tab, context, div);
2621 /* Insert a div specified by "div" to the context tableau at position "pos" and
2622 * return isl_bool_true if the div is obviously non-negative.
2623 * context_tab_add_div will always return isl_bool_true, because all variables
2624 * in a isl_context_lex tableau are non-negative.
2625 * However, if we are using a big parameter in the context, then this only
2626 * reflects the non-negativity of the variable used to _encode_ the
2627 * div, i.e., div' = M + div, so we can't draw any conclusions.
2629 static isl_bool context_lex_insert_div(struct isl_context *context, int pos,
2630 __isl_keep isl_vec *div)
2632 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2633 isl_bool nonneg;
2634 nonneg = context_tab_insert_div(clex->tab, pos, div,
2635 context_lex_add_ineq_wrap, context);
2636 if (nonneg < 0)
2637 return isl_bool_error;
2638 if (clex->tab->M)
2639 return isl_bool_false;
2640 return nonneg;
2643 static int context_lex_detect_equalities(struct isl_context *context,
2644 struct isl_tab *tab)
2646 return 0;
2649 static int context_lex_best_split(struct isl_context *context,
2650 struct isl_tab *tab)
2652 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2653 struct isl_tab_undo *snap;
2654 int r;
2656 snap = isl_tab_snap(clex->tab);
2657 if (isl_tab_push_basis(clex->tab) < 0)
2658 return -1;
2659 r = best_split(tab, clex->tab);
2661 if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2662 return -1;
2664 return r;
2667 static int context_lex_is_empty(struct isl_context *context)
2669 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2670 if (!clex->tab)
2671 return -1;
2672 return clex->tab->empty;
2675 static void *context_lex_save(struct isl_context *context)
2677 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2678 struct isl_tab_undo *snap;
2680 snap = isl_tab_snap(clex->tab);
2681 if (isl_tab_push_basis(clex->tab) < 0)
2682 return NULL;
2683 if (isl_tab_save_samples(clex->tab) < 0)
2684 return NULL;
2686 return snap;
2689 static void context_lex_restore(struct isl_context *context, void *save)
2691 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2692 if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2693 isl_tab_free(clex->tab);
2694 clex->tab = NULL;
2698 static void context_lex_discard(void *save)
2702 static int context_lex_is_ok(struct isl_context *context)
2704 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2705 return !!clex->tab;
2708 /* For each variable in the context tableau, check if the variable can
2709 * only attain non-negative values. If so, mark the parameter as non-negative
2710 * in the main tableau. This allows for a more direct identification of some
2711 * cases of violated constraints.
2713 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2714 struct isl_tab *context_tab)
2716 int i;
2717 struct isl_tab_undo *snap;
2718 struct isl_vec *ineq = NULL;
2719 struct isl_tab_var *var;
2720 int n;
2722 if (context_tab->n_var == 0)
2723 return tab;
2725 ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2726 if (!ineq)
2727 goto error;
2729 if (isl_tab_extend_cons(context_tab, 1) < 0)
2730 goto error;
2732 snap = isl_tab_snap(context_tab);
2734 n = 0;
2735 isl_seq_clr(ineq->el, ineq->size);
2736 for (i = 0; i < context_tab->n_var; ++i) {
2737 isl_int_set_si(ineq->el[1 + i], 1);
2738 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2739 goto error;
2740 var = &context_tab->con[context_tab->n_con - 1];
2741 if (!context_tab->empty &&
2742 !isl_tab_min_at_most_neg_one(context_tab, var)) {
2743 int j = i;
2744 if (i >= tab->n_param)
2745 j = i - tab->n_param + tab->n_var - tab->n_div;
2746 tab->var[j].is_nonneg = 1;
2747 n++;
2749 isl_int_set_si(ineq->el[1 + i], 0);
2750 if (isl_tab_rollback(context_tab, snap) < 0)
2751 goto error;
2754 if (context_tab->M && n == context_tab->n_var) {
2755 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2756 context_tab->M = 0;
2759 isl_vec_free(ineq);
2760 return tab;
2761 error:
2762 isl_vec_free(ineq);
2763 isl_tab_free(tab);
2764 return NULL;
2767 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2768 struct isl_context *context, struct isl_tab *tab)
2770 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2771 struct isl_tab_undo *snap;
2773 if (!tab)
2774 return NULL;
2776 snap = isl_tab_snap(clex->tab);
2777 if (isl_tab_push_basis(clex->tab) < 0)
2778 goto error;
2780 tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2782 if (isl_tab_rollback(clex->tab, snap) < 0)
2783 goto error;
2785 return tab;
2786 error:
2787 isl_tab_free(tab);
2788 return NULL;
2791 static void context_lex_invalidate(struct isl_context *context)
2793 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2794 isl_tab_free(clex->tab);
2795 clex->tab = NULL;
2798 static __isl_null struct isl_context *context_lex_free(
2799 struct isl_context *context)
2801 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2802 isl_tab_free(clex->tab);
2803 free(clex);
2805 return NULL;
2808 struct isl_context_op isl_context_lex_op = {
2809 context_lex_detect_nonnegative_parameters,
2810 context_lex_peek_basic_set,
2811 context_lex_peek_tab,
2812 context_lex_add_eq,
2813 context_lex_add_ineq,
2814 context_lex_ineq_sign,
2815 context_lex_test_ineq,
2816 context_lex_get_div,
2817 context_lex_insert_div,
2818 context_lex_detect_equalities,
2819 context_lex_best_split,
2820 context_lex_is_empty,
2821 context_lex_is_ok,
2822 context_lex_save,
2823 context_lex_restore,
2824 context_lex_discard,
2825 context_lex_invalidate,
2826 context_lex_free,
2829 static struct isl_tab *context_tab_for_lexmin(__isl_take isl_basic_set *bset)
2831 struct isl_tab *tab;
2833 if (!bset)
2834 return NULL;
2835 tab = tab_for_lexmin(bset_to_bmap(bset), NULL, 1, 0);
2836 if (isl_tab_track_bset(tab, bset) < 0)
2837 goto error;
2838 tab = isl_tab_init_samples(tab);
2839 return tab;
2840 error:
2841 isl_tab_free(tab);
2842 return NULL;
2845 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2847 struct isl_context_lex *clex;
2849 if (!dom)
2850 return NULL;
2852 clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2853 if (!clex)
2854 return NULL;
2856 clex->context.op = &isl_context_lex_op;
2858 clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2859 if (restore_lexmin(clex->tab) < 0)
2860 goto error;
2861 clex->tab = check_integer_feasible(clex->tab);
2862 if (!clex->tab)
2863 goto error;
2865 return &clex->context;
2866 error:
2867 clex->context.op->free(&clex->context);
2868 return NULL;
2871 /* Representation of the context when using generalized basis reduction.
2873 * "shifted" contains the offsets of the unit hypercubes that lie inside the
2874 * context. Any rational point in "shifted" can therefore be rounded
2875 * up to an integer point in the context.
2876 * If the context is constrained by any equality, then "shifted" is not used
2877 * as it would be empty.
2879 struct isl_context_gbr {
2880 struct isl_context context;
2881 struct isl_tab *tab;
2882 struct isl_tab *shifted;
2883 struct isl_tab *cone;
2886 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2887 struct isl_context *context, struct isl_tab *tab)
2889 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2890 if (!tab)
2891 return NULL;
2892 return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2895 static struct isl_basic_set *context_gbr_peek_basic_set(
2896 struct isl_context *context)
2898 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2899 if (!cgbr->tab)
2900 return NULL;
2901 return isl_tab_peek_bset(cgbr->tab);
2904 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2906 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2907 return cgbr->tab;
2910 /* Initialize the "shifted" tableau of the context, which
2911 * contains the constraints of the original tableau shifted
2912 * by the sum of all negative coefficients. This ensures
2913 * that any rational point in the shifted tableau can
2914 * be rounded up to yield an integer point in the original tableau.
2916 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2918 int i, j;
2919 struct isl_vec *cst;
2920 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2921 isl_size dim = isl_basic_set_dim(bset, isl_dim_all);
2923 if (dim < 0)
2924 return;
2925 cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2926 if (!cst)
2927 return;
2929 for (i = 0; i < bset->n_ineq; ++i) {
2930 isl_int_set(cst->el[i], bset->ineq[i][0]);
2931 for (j = 0; j < dim; ++j) {
2932 if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2933 continue;
2934 isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2935 bset->ineq[i][1 + j]);
2939 cgbr->shifted = isl_tab_from_basic_set(bset, 0);
2941 for (i = 0; i < bset->n_ineq; ++i)
2942 isl_int_set(bset->ineq[i][0], cst->el[i]);
2944 isl_vec_free(cst);
2947 /* Check if the shifted tableau is non-empty, and if so
2948 * use the sample point to construct an integer point
2949 * of the context tableau.
2951 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2953 struct isl_vec *sample;
2955 if (!cgbr->shifted)
2956 gbr_init_shifted(cgbr);
2957 if (!cgbr->shifted)
2958 return NULL;
2959 if (cgbr->shifted->empty)
2960 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2962 sample = isl_tab_get_sample_value(cgbr->shifted);
2963 sample = isl_vec_ceil(sample);
2965 return sample;
2968 static __isl_give isl_basic_set *drop_constant_terms(
2969 __isl_take isl_basic_set *bset)
2971 int i;
2973 if (!bset)
2974 return NULL;
2976 for (i = 0; i < bset->n_eq; ++i)
2977 isl_int_set_si(bset->eq[i][0], 0);
2979 for (i = 0; i < bset->n_ineq; ++i)
2980 isl_int_set_si(bset->ineq[i][0], 0);
2982 return bset;
2985 static int use_shifted(struct isl_context_gbr *cgbr)
2987 if (!cgbr->tab)
2988 return 0;
2989 return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2992 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2994 struct isl_basic_set *bset;
2995 struct isl_basic_set *cone;
2997 if (isl_tab_sample_is_integer(cgbr->tab))
2998 return isl_tab_get_sample_value(cgbr->tab);
3000 if (use_shifted(cgbr)) {
3001 struct isl_vec *sample;
3003 sample = gbr_get_shifted_sample(cgbr);
3004 if (!sample || sample->size > 0)
3005 return sample;
3007 isl_vec_free(sample);
3010 if (!cgbr->cone) {
3011 bset = isl_tab_peek_bset(cgbr->tab);
3012 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3013 if (!cgbr->cone)
3014 return NULL;
3015 if (isl_tab_track_bset(cgbr->cone,
3016 isl_basic_set_copy(bset)) < 0)
3017 return NULL;
3019 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3020 return NULL;
3022 if (cgbr->cone->n_dead == cgbr->cone->n_col) {
3023 struct isl_vec *sample;
3024 struct isl_tab_undo *snap;
3026 if (cgbr->tab->basis) {
3027 if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
3028 isl_mat_free(cgbr->tab->basis);
3029 cgbr->tab->basis = NULL;
3031 cgbr->tab->n_zero = 0;
3032 cgbr->tab->n_unbounded = 0;
3035 snap = isl_tab_snap(cgbr->tab);
3037 sample = isl_tab_sample(cgbr->tab);
3039 if (!sample || isl_tab_rollback(cgbr->tab, snap) < 0) {
3040 isl_vec_free(sample);
3041 return NULL;
3044 return sample;
3047 cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
3048 cone = drop_constant_terms(cone);
3049 cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
3050 cone = isl_basic_set_underlying_set(cone);
3051 cone = isl_basic_set_gauss(cone, NULL);
3053 bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
3054 bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
3055 bset = isl_basic_set_underlying_set(bset);
3056 bset = isl_basic_set_gauss(bset, NULL);
3058 return isl_basic_set_sample_with_cone(bset, cone);
3061 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
3063 struct isl_vec *sample;
3065 if (!cgbr->tab)
3066 return;
3068 if (cgbr->tab->empty)
3069 return;
3071 sample = gbr_get_sample(cgbr);
3072 if (!sample)
3073 goto error;
3075 if (sample->size == 0) {
3076 isl_vec_free(sample);
3077 if (isl_tab_mark_empty(cgbr->tab) < 0)
3078 goto error;
3079 return;
3082 if (isl_tab_add_sample(cgbr->tab, sample) < 0)
3083 goto error;
3085 return;
3086 error:
3087 isl_tab_free(cgbr->tab);
3088 cgbr->tab = NULL;
3091 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
3093 if (!tab)
3094 return NULL;
3096 if (isl_tab_extend_cons(tab, 2) < 0)
3097 goto error;
3099 if (isl_tab_add_eq(tab, eq) < 0)
3100 goto error;
3102 return tab;
3103 error:
3104 isl_tab_free(tab);
3105 return NULL;
3108 /* Add the equality described by "eq" to the context.
3109 * If "check" is set, then we check if the context is empty after
3110 * adding the equality.
3111 * If "update" is set, then we check if the samples are still valid.
3113 * We do not explicitly add shifted copies of the equality to
3114 * cgbr->shifted since they would conflict with each other.
3115 * Instead, we directly mark cgbr->shifted empty.
3117 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
3118 int check, int update)
3120 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3122 cgbr->tab = add_gbr_eq(cgbr->tab, eq);
3124 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3125 if (isl_tab_mark_empty(cgbr->shifted) < 0)
3126 goto error;
3129 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3130 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
3131 goto error;
3132 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
3133 goto error;
3136 if (check) {
3137 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
3138 if (v < 0)
3139 goto error;
3140 if (!v)
3141 check_gbr_integer_feasible(cgbr);
3143 if (update)
3144 cgbr->tab = check_samples(cgbr->tab, eq, 1);
3145 return;
3146 error:
3147 isl_tab_free(cgbr->tab);
3148 cgbr->tab = NULL;
3151 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
3153 if (!cgbr->tab)
3154 return;
3156 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3157 goto error;
3159 if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
3160 goto error;
3162 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3163 int i;
3164 isl_size dim;
3165 dim = isl_basic_map_dim(cgbr->tab->bmap, isl_dim_all);
3166 if (dim < 0)
3167 goto error;
3169 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
3170 goto error;
3172 for (i = 0; i < dim; ++i) {
3173 if (!isl_int_is_neg(ineq[1 + i]))
3174 continue;
3175 isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
3178 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
3179 goto error;
3181 for (i = 0; i < dim; ++i) {
3182 if (!isl_int_is_neg(ineq[1 + i]))
3183 continue;
3184 isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
3188 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3189 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
3190 goto error;
3191 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
3192 goto error;
3195 return;
3196 error:
3197 isl_tab_free(cgbr->tab);
3198 cgbr->tab = NULL;
3201 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
3202 int check, int update)
3204 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3206 add_gbr_ineq(cgbr, ineq);
3207 if (!cgbr->tab)
3208 return;
3210 if (check) {
3211 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
3212 if (v < 0)
3213 goto error;
3214 if (!v)
3215 check_gbr_integer_feasible(cgbr);
3217 if (update)
3218 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
3219 return;
3220 error:
3221 isl_tab_free(cgbr->tab);
3222 cgbr->tab = NULL;
3225 static isl_stat context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
3227 struct isl_context *context = (struct isl_context *)user;
3228 context_gbr_add_ineq(context, ineq, 0, 0);
3229 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
3232 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
3233 isl_int *ineq, int strict)
3235 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3236 return tab_ineq_sign(cgbr->tab, ineq, strict);
3239 /* Check whether "ineq" can be added to the tableau without rendering
3240 * it infeasible.
3242 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
3244 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3245 struct isl_tab_undo *snap;
3246 struct isl_tab_undo *shifted_snap = NULL;
3247 struct isl_tab_undo *cone_snap = NULL;
3248 int feasible;
3250 if (!cgbr->tab)
3251 return -1;
3253 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3254 return -1;
3256 snap = isl_tab_snap(cgbr->tab);
3257 if (cgbr->shifted)
3258 shifted_snap = isl_tab_snap(cgbr->shifted);
3259 if (cgbr->cone)
3260 cone_snap = isl_tab_snap(cgbr->cone);
3261 add_gbr_ineq(cgbr, ineq);
3262 check_gbr_integer_feasible(cgbr);
3263 if (!cgbr->tab)
3264 return -1;
3265 feasible = !cgbr->tab->empty;
3266 if (isl_tab_rollback(cgbr->tab, snap) < 0)
3267 return -1;
3268 if (shifted_snap) {
3269 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
3270 return -1;
3271 } else if (cgbr->shifted) {
3272 isl_tab_free(cgbr->shifted);
3273 cgbr->shifted = NULL;
3275 if (cone_snap) {
3276 if (isl_tab_rollback(cgbr->cone, cone_snap))
3277 return -1;
3278 } else if (cgbr->cone) {
3279 isl_tab_free(cgbr->cone);
3280 cgbr->cone = NULL;
3283 return feasible;
3286 /* Return the column of the last of the variables associated to
3287 * a column that has a non-zero coefficient.
3288 * This function is called in a context where only coefficients
3289 * of parameters or divs can be non-zero.
3291 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
3293 int i;
3294 int col;
3296 if (tab->n_var == 0)
3297 return -1;
3299 for (i = tab->n_var - 1; i >= 0; --i) {
3300 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
3301 continue;
3302 if (tab->var[i].is_row)
3303 continue;
3304 col = tab->var[i].index;
3305 if (!isl_int_is_zero(p[col]))
3306 return col;
3309 return -1;
3312 /* Look through all the recently added equalities in the context
3313 * to see if we can propagate any of them to the main tableau.
3315 * The newly added equalities in the context are encoded as pairs
3316 * of inequalities starting at inequality "first".
3318 * We tentatively add each of these equalities to the main tableau
3319 * and if this happens to result in a row with a final coefficient
3320 * that is one or negative one, we use it to kill a column
3321 * in the main tableau. Otherwise, we discard the tentatively
3322 * added row.
3323 * This tentative addition of equality constraints turns
3324 * on the undo facility of the tableau. Turn it off again
3325 * at the end, assuming it was turned off to begin with.
3327 * Return 0 on success and -1 on failure.
3329 static int propagate_equalities(struct isl_context_gbr *cgbr,
3330 struct isl_tab *tab, unsigned first)
3332 int i;
3333 struct isl_vec *eq = NULL;
3334 isl_bool needs_undo;
3336 needs_undo = isl_tab_need_undo(tab);
3337 if (needs_undo < 0)
3338 goto error;
3339 eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
3340 if (!eq)
3341 goto error;
3343 if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
3344 goto error;
3346 isl_seq_clr(eq->el + 1 + tab->n_param,
3347 tab->n_var - tab->n_param - tab->n_div);
3348 for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
3349 int j;
3350 int r;
3351 struct isl_tab_undo *snap;
3352 snap = isl_tab_snap(tab);
3354 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
3355 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
3356 cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
3357 tab->n_div);
3359 r = isl_tab_add_row(tab, eq->el);
3360 if (r < 0)
3361 goto error;
3362 r = tab->con[r].index;
3363 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
3364 if (j < 0 || j < tab->n_dead ||
3365 !isl_int_is_one(tab->mat->row[r][0]) ||
3366 (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
3367 !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
3368 if (isl_tab_rollback(tab, snap) < 0)
3369 goto error;
3370 continue;
3372 if (isl_tab_pivot(tab, r, j) < 0)
3373 goto error;
3374 if (isl_tab_kill_col(tab, j) < 0)
3375 goto error;
3377 if (restore_lexmin(tab) < 0)
3378 goto error;
3381 if (!needs_undo)
3382 isl_tab_clear_undo(tab);
3383 isl_vec_free(eq);
3385 return 0;
3386 error:
3387 isl_vec_free(eq);
3388 isl_tab_free(cgbr->tab);
3389 cgbr->tab = NULL;
3390 return -1;
3393 static int context_gbr_detect_equalities(struct isl_context *context,
3394 struct isl_tab *tab)
3396 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3397 unsigned n_ineq;
3399 if (!cgbr->cone) {
3400 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3401 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3402 if (!cgbr->cone)
3403 goto error;
3404 if (isl_tab_track_bset(cgbr->cone,
3405 isl_basic_set_copy(bset)) < 0)
3406 goto error;
3408 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3409 goto error;
3411 n_ineq = cgbr->tab->bmap->n_ineq;
3412 cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3413 if (!cgbr->tab)
3414 return -1;
3415 if (cgbr->tab->bmap->n_ineq > n_ineq &&
3416 propagate_equalities(cgbr, tab, n_ineq) < 0)
3417 return -1;
3419 return 0;
3420 error:
3421 isl_tab_free(cgbr->tab);
3422 cgbr->tab = NULL;
3423 return -1;
3426 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3427 struct isl_vec *div)
3429 return get_div(tab, context, div);
3432 static isl_bool context_gbr_insert_div(struct isl_context *context, int pos,
3433 __isl_keep isl_vec *div)
3435 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3436 if (cgbr->cone) {
3437 int r, o_div;
3438 isl_size n_div;
3440 n_div = isl_basic_map_dim(cgbr->cone->bmap, isl_dim_div);
3441 if (n_div < 0)
3442 return isl_bool_error;
3443 o_div = cgbr->cone->n_var - n_div;
3445 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3446 return isl_bool_error;
3447 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3448 return isl_bool_error;
3449 if ((r = isl_tab_insert_var(cgbr->cone, pos)) <0)
3450 return isl_bool_error;
3452 cgbr->cone->bmap = isl_basic_map_insert_div(cgbr->cone->bmap,
3453 r - o_div, div);
3454 if (!cgbr->cone->bmap)
3455 return isl_bool_error;
3456 if (isl_tab_push_var(cgbr->cone, isl_tab_undo_bmap_div,
3457 &cgbr->cone->var[r]) < 0)
3458 return isl_bool_error;
3460 return context_tab_insert_div(cgbr->tab, pos, div,
3461 context_gbr_add_ineq_wrap, context);
3464 static int context_gbr_best_split(struct isl_context *context,
3465 struct isl_tab *tab)
3467 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3468 struct isl_tab_undo *snap;
3469 int r;
3471 snap = isl_tab_snap(cgbr->tab);
3472 r = best_split(tab, cgbr->tab);
3474 if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3475 return -1;
3477 return r;
3480 static int context_gbr_is_empty(struct isl_context *context)
3482 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3483 if (!cgbr->tab)
3484 return -1;
3485 return cgbr->tab->empty;
3488 struct isl_gbr_tab_undo {
3489 struct isl_tab_undo *tab_snap;
3490 struct isl_tab_undo *shifted_snap;
3491 struct isl_tab_undo *cone_snap;
3494 static void *context_gbr_save(struct isl_context *context)
3496 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3497 struct isl_gbr_tab_undo *snap;
3499 if (!cgbr->tab)
3500 return NULL;
3502 snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3503 if (!snap)
3504 return NULL;
3506 snap->tab_snap = isl_tab_snap(cgbr->tab);
3507 if (isl_tab_save_samples(cgbr->tab) < 0)
3508 goto error;
3510 if (cgbr->shifted)
3511 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3512 else
3513 snap->shifted_snap = NULL;
3515 if (cgbr->cone)
3516 snap->cone_snap = isl_tab_snap(cgbr->cone);
3517 else
3518 snap->cone_snap = NULL;
3520 return snap;
3521 error:
3522 free(snap);
3523 return NULL;
3526 static void context_gbr_restore(struct isl_context *context, void *save)
3528 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3529 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3530 if (!snap)
3531 goto error;
3532 if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0)
3533 goto error;
3535 if (snap->shifted_snap) {
3536 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3537 goto error;
3538 } else if (cgbr->shifted) {
3539 isl_tab_free(cgbr->shifted);
3540 cgbr->shifted = NULL;
3543 if (snap->cone_snap) {
3544 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3545 goto error;
3546 } else if (cgbr->cone) {
3547 isl_tab_free(cgbr->cone);
3548 cgbr->cone = NULL;
3551 free(snap);
3553 return;
3554 error:
3555 free(snap);
3556 isl_tab_free(cgbr->tab);
3557 cgbr->tab = NULL;
3560 static void context_gbr_discard(void *save)
3562 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3563 free(snap);
3566 static int context_gbr_is_ok(struct isl_context *context)
3568 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3569 return !!cgbr->tab;
3572 static void context_gbr_invalidate(struct isl_context *context)
3574 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3575 isl_tab_free(cgbr->tab);
3576 cgbr->tab = NULL;
3579 static __isl_null struct isl_context *context_gbr_free(
3580 struct isl_context *context)
3582 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3583 isl_tab_free(cgbr->tab);
3584 isl_tab_free(cgbr->shifted);
3585 isl_tab_free(cgbr->cone);
3586 free(cgbr);
3588 return NULL;
3591 struct isl_context_op isl_context_gbr_op = {
3592 context_gbr_detect_nonnegative_parameters,
3593 context_gbr_peek_basic_set,
3594 context_gbr_peek_tab,
3595 context_gbr_add_eq,
3596 context_gbr_add_ineq,
3597 context_gbr_ineq_sign,
3598 context_gbr_test_ineq,
3599 context_gbr_get_div,
3600 context_gbr_insert_div,
3601 context_gbr_detect_equalities,
3602 context_gbr_best_split,
3603 context_gbr_is_empty,
3604 context_gbr_is_ok,
3605 context_gbr_save,
3606 context_gbr_restore,
3607 context_gbr_discard,
3608 context_gbr_invalidate,
3609 context_gbr_free,
3612 static struct isl_context *isl_context_gbr_alloc(__isl_keep isl_basic_set *dom)
3614 struct isl_context_gbr *cgbr;
3616 if (!dom)
3617 return NULL;
3619 cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3620 if (!cgbr)
3621 return NULL;
3623 cgbr->context.op = &isl_context_gbr_op;
3625 cgbr->shifted = NULL;
3626 cgbr->cone = NULL;
3627 cgbr->tab = isl_tab_from_basic_set(dom, 1);
3628 cgbr->tab = isl_tab_init_samples(cgbr->tab);
3629 if (!cgbr->tab)
3630 goto error;
3631 check_gbr_integer_feasible(cgbr);
3633 return &cgbr->context;
3634 error:
3635 cgbr->context.op->free(&cgbr->context);
3636 return NULL;
3639 /* Allocate a context corresponding to "dom".
3640 * The representation specific fields are initialized by
3641 * isl_context_lex_alloc or isl_context_gbr_alloc.
3642 * The shared "n_unknown" field is initialized to the number
3643 * of final unknown integer divisions in "dom".
3645 static struct isl_context *isl_context_alloc(__isl_keep isl_basic_set *dom)
3647 struct isl_context *context;
3648 int first;
3649 isl_size n_div;
3651 if (!dom)
3652 return NULL;
3654 if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3655 context = isl_context_lex_alloc(dom);
3656 else
3657 context = isl_context_gbr_alloc(dom);
3659 if (!context)
3660 return NULL;
3662 first = isl_basic_set_first_unknown_div(dom);
3663 n_div = isl_basic_set_dim(dom, isl_dim_div);
3664 if (first < 0 || n_div < 0)
3665 return context->op->free(context);
3666 context->n_unknown = n_div - first;
3668 return context;
3671 /* Initialize some common fields of "sol", which keeps track
3672 * of the solution of an optimization problem on "bmap" over
3673 * the domain "dom".
3674 * If "max" is set, then a maximization problem is being solved, rather than
3675 * a minimization problem, which means that the variables in the
3676 * tableau have value "M - x" rather than "M + x".
3678 static isl_stat sol_init(struct isl_sol *sol, __isl_keep isl_basic_map *bmap,
3679 __isl_keep isl_basic_set *dom, int max)
3681 sol->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3682 sol->dec_level.callback.run = &sol_dec_level_wrap;
3683 sol->dec_level.sol = sol;
3684 sol->max = max;
3685 sol->n_out = isl_basic_map_dim(bmap, isl_dim_out);
3686 sol->space = isl_basic_map_get_space(bmap);
3688 sol->context = isl_context_alloc(dom);
3689 if (sol->n_out < 0 || !sol->space || !sol->context)
3690 return isl_stat_error;
3692 return isl_stat_ok;
3695 /* Construct an isl_sol_map structure for accumulating the solution.
3696 * If track_empty is set, then we also keep track of the parts
3697 * of the context where there is no solution.
3698 * If max is set, then we are solving a maximization, rather than
3699 * a minimization problem, which means that the variables in the
3700 * tableau have value "M - x" rather than "M + x".
3702 static struct isl_sol *sol_map_init(__isl_keep isl_basic_map *bmap,
3703 __isl_take isl_basic_set *dom, int track_empty, int max)
3705 struct isl_sol_map *sol_map = NULL;
3706 isl_space *space;
3708 if (!bmap)
3709 goto error;
3711 sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3712 if (!sol_map)
3713 goto error;
3715 sol_map->sol.free = &sol_map_free;
3716 if (sol_init(&sol_map->sol, bmap, dom, max) < 0)
3717 goto error;
3718 sol_map->sol.add = &sol_map_add_wrap;
3719 sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3720 space = isl_space_copy(sol_map->sol.space);
3721 sol_map->map = isl_map_alloc_space(space, 1, ISL_MAP_DISJOINT);
3722 if (!sol_map->map)
3723 goto error;
3725 if (track_empty) {
3726 sol_map->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
3727 1, ISL_SET_DISJOINT);
3728 if (!sol_map->empty)
3729 goto error;
3732 isl_basic_set_free(dom);
3733 return &sol_map->sol;
3734 error:
3735 isl_basic_set_free(dom);
3736 sol_free(&sol_map->sol);
3737 return NULL;
3740 /* Check whether all coefficients of (non-parameter) variables
3741 * are non-positive, meaning that no pivots can be performed on the row.
3743 static int is_critical(struct isl_tab *tab, int row)
3745 int j;
3746 unsigned off = 2 + tab->M;
3748 for (j = tab->n_dead; j < tab->n_col; ++j) {
3749 if (col_is_parameter_var(tab, j))
3750 continue;
3752 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3753 return 0;
3756 return 1;
3759 /* Check whether the inequality represented by vec is strict over the integers,
3760 * i.e., there are no integer values satisfying the constraint with
3761 * equality. This happens if the gcd of the coefficients is not a divisor
3762 * of the constant term. If so, scale the constraint down by the gcd
3763 * of the coefficients.
3765 static int is_strict(struct isl_vec *vec)
3767 isl_int gcd;
3768 int strict = 0;
3770 isl_int_init(gcd);
3771 isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3772 if (!isl_int_is_one(gcd)) {
3773 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3774 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3775 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3777 isl_int_clear(gcd);
3779 return strict;
3782 /* Determine the sign of the given row of the main tableau.
3783 * The result is one of
3784 * isl_tab_row_pos: always non-negative; no pivot needed
3785 * isl_tab_row_neg: always non-positive; pivot
3786 * isl_tab_row_any: can be both positive and negative; split
3788 * We first handle some simple cases
3789 * - the row sign may be known already
3790 * - the row may be obviously non-negative
3791 * - the parametric constant may be equal to that of another row
3792 * for which we know the sign. This sign will be either "pos" or
3793 * "any". If it had been "neg" then we would have pivoted before.
3795 * If none of these cases hold, we check the value of the row for each
3796 * of the currently active samples. Based on the signs of these values
3797 * we make an initial determination of the sign of the row.
3799 * all zero -> unk(nown)
3800 * all non-negative -> pos
3801 * all non-positive -> neg
3802 * both negative and positive -> all
3804 * If we end up with "all", we are done.
3805 * Otherwise, we perform a check for positive and/or negative
3806 * values as follows.
3808 * samples neg unk pos
3809 * <0 ? Y N Y N
3810 * pos any pos
3811 * >0 ? Y N Y N
3812 * any neg any neg
3814 * There is no special sign for "zero", because we can usually treat zero
3815 * as either non-negative or non-positive, whatever works out best.
3816 * However, if the row is "critical", meaning that pivoting is impossible
3817 * then we don't want to limp zero with the non-positive case, because
3818 * then we we would lose the solution for those values of the parameters
3819 * where the value of the row is zero. Instead, we treat 0 as non-negative
3820 * ensuring a split if the row can attain both zero and negative values.
3821 * The same happens when the original constraint was one that could not
3822 * be satisfied with equality by any integer values of the parameters.
3823 * In this case, we normalize the constraint, but then a value of zero
3824 * for the normalized constraint is actually a positive value for the
3825 * original constraint, so again we need to treat zero as non-negative.
3826 * In both these cases, we have the following decision tree instead:
3828 * all non-negative -> pos
3829 * all negative -> neg
3830 * both negative and non-negative -> all
3832 * samples neg pos
3833 * <0 ? Y N
3834 * any pos
3835 * >=0 ? Y N
3836 * any neg
3838 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3839 struct isl_sol *sol, int row)
3841 struct isl_vec *ineq = NULL;
3842 enum isl_tab_row_sign res = isl_tab_row_unknown;
3843 int critical;
3844 int strict;
3845 int row2;
3847 if (tab->row_sign[row] != isl_tab_row_unknown)
3848 return tab->row_sign[row];
3849 if (is_obviously_nonneg(tab, row))
3850 return isl_tab_row_pos;
3851 for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3852 if (tab->row_sign[row2] == isl_tab_row_unknown)
3853 continue;
3854 if (identical_parameter_line(tab, row, row2))
3855 return tab->row_sign[row2];
3858 critical = is_critical(tab, row);
3860 ineq = get_row_parameter_ineq(tab, row);
3861 if (!ineq)
3862 goto error;
3864 strict = is_strict(ineq);
3866 res = sol->context->op->ineq_sign(sol->context, ineq->el,
3867 critical || strict);
3869 if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3870 /* test for negative values */
3871 int feasible;
3872 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3873 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3875 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3876 if (feasible < 0)
3877 goto error;
3878 if (!feasible)
3879 res = isl_tab_row_pos;
3880 else
3881 res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3882 : isl_tab_row_any;
3883 if (res == isl_tab_row_neg) {
3884 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3885 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3889 if (res == isl_tab_row_neg) {
3890 /* test for positive values */
3891 int feasible;
3892 if (!critical && !strict)
3893 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3895 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3896 if (feasible < 0)
3897 goto error;
3898 if (feasible)
3899 res = isl_tab_row_any;
3902 isl_vec_free(ineq);
3903 return res;
3904 error:
3905 isl_vec_free(ineq);
3906 return isl_tab_row_unknown;
3909 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3911 /* Find solutions for values of the parameters that satisfy the given
3912 * inequality.
3914 * We currently take a snapshot of the context tableau that is reset
3915 * when we return from this function, while we make a copy of the main
3916 * tableau, leaving the original main tableau untouched.
3917 * These are fairly arbitrary choices. Making a copy also of the context
3918 * tableau would obviate the need to undo any changes made to it later,
3919 * while taking a snapshot of the main tableau could reduce memory usage.
3920 * If we were to switch to taking a snapshot of the main tableau,
3921 * we would have to keep in mind that we need to save the row signs
3922 * and that we need to do this before saving the current basis
3923 * such that the basis has been restore before we restore the row signs.
3925 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3927 void *saved;
3929 if (!sol->context)
3930 goto error;
3931 saved = sol->context->op->save(sol->context);
3933 tab = isl_tab_dup(tab);
3934 if (!tab)
3935 goto error;
3937 sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3939 find_solutions(sol, tab);
3941 if (!sol->error)
3942 sol->context->op->restore(sol->context, saved);
3943 else
3944 sol->context->op->discard(saved);
3945 return;
3946 error:
3947 sol->error = 1;
3950 /* Record the absence of solutions for those values of the parameters
3951 * that do not satisfy the given inequality with equality.
3953 static void no_sol_in_strict(struct isl_sol *sol,
3954 struct isl_tab *tab, struct isl_vec *ineq)
3956 int empty;
3957 void *saved;
3959 if (!sol->context || sol->error)
3960 goto error;
3961 saved = sol->context->op->save(sol->context);
3963 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3965 sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3966 if (!sol->context)
3967 goto error;
3969 empty = tab->empty;
3970 tab->empty = 1;
3971 sol_add(sol, tab);
3972 tab->empty = empty;
3974 isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3976 sol->context->op->restore(sol->context, saved);
3977 return;
3978 error:
3979 sol->error = 1;
3982 /* Reset all row variables that are marked to have a sign that may
3983 * be both positive and negative to have an unknown sign.
3985 static void reset_any_to_unknown(struct isl_tab *tab)
3987 int row;
3989 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3990 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3991 continue;
3992 if (tab->row_sign[row] == isl_tab_row_any)
3993 tab->row_sign[row] = isl_tab_row_unknown;
3997 /* Compute the lexicographic minimum of the set represented by the main
3998 * tableau "tab" within the context "sol->context_tab".
3999 * On entry the sample value of the main tableau is lexicographically
4000 * less than or equal to this lexicographic minimum.
4001 * Pivots are performed until a feasible point is found, which is then
4002 * necessarily equal to the minimum, or until the tableau is found to
4003 * be infeasible. Some pivots may need to be performed for only some
4004 * feasible values of the context tableau. If so, the context tableau
4005 * is split into a part where the pivot is needed and a part where it is not.
4007 * Whenever we enter the main loop, the main tableau is such that no
4008 * "obvious" pivots need to be performed on it, where "obvious" means
4009 * that the given row can be seen to be negative without looking at
4010 * the context tableau. In particular, for non-parametric problems,
4011 * no pivots need to be performed on the main tableau.
4012 * The caller of find_solutions is responsible for making this property
4013 * hold prior to the first iteration of the loop, while restore_lexmin
4014 * is called before every other iteration.
4016 * Inside the main loop, we first examine the signs of the rows of
4017 * the main tableau within the context of the context tableau.
4018 * If we find a row that is always non-positive for all values of
4019 * the parameters satisfying the context tableau and negative for at
4020 * least one value of the parameters, we perform the appropriate pivot
4021 * and start over. An exception is the case where no pivot can be
4022 * performed on the row. In this case, we require that the sign of
4023 * the row is negative for all values of the parameters (rather than just
4024 * non-positive). This special case is handled inside row_sign, which
4025 * will say that the row can have any sign if it determines that it can
4026 * attain both negative and zero values.
4028 * If we can't find a row that always requires a pivot, but we can find
4029 * one or more rows that require a pivot for some values of the parameters
4030 * (i.e., the row can attain both positive and negative signs), then we split
4031 * the context tableau into two parts, one where we force the sign to be
4032 * non-negative and one where we force is to be negative.
4033 * The non-negative part is handled by a recursive call (through find_in_pos).
4034 * Upon returning from this call, we continue with the negative part and
4035 * perform the required pivot.
4037 * If no such rows can be found, all rows are non-negative and we have
4038 * found a (rational) feasible point. If we only wanted a rational point
4039 * then we are done.
4040 * Otherwise, we check if all values of the sample point of the tableau
4041 * are integral for the variables. If so, we have found the minimal
4042 * integral point and we are done.
4043 * If the sample point is not integral, then we need to make a distinction
4044 * based on whether the constant term is non-integral or the coefficients
4045 * of the parameters. Furthermore, in order to decide how to handle
4046 * the non-integrality, we also need to know whether the coefficients
4047 * of the other columns in the tableau are integral. This leads
4048 * to the following table. The first two rows do not correspond
4049 * to a non-integral sample point and are only mentioned for completeness.
4051 * constant parameters other
4053 * int int int |
4054 * int int rat | -> no problem
4056 * rat int int -> fail
4058 * rat int rat -> cut
4060 * int rat rat |
4061 * rat rat rat | -> parametric cut
4063 * int rat int |
4064 * rat rat int | -> split context
4066 * If the parametric constant is completely integral, then there is nothing
4067 * to be done. If the constant term is non-integral, but all the other
4068 * coefficient are integral, then there is nothing that can be done
4069 * and the tableau has no integral solution.
4070 * If, on the other hand, one or more of the other columns have rational
4071 * coefficients, but the parameter coefficients are all integral, then
4072 * we can perform a regular (non-parametric) cut.
4073 * Finally, if there is any parameter coefficient that is non-integral,
4074 * then we need to involve the context tableau. There are two cases here.
4075 * If at least one other column has a rational coefficient, then we
4076 * can perform a parametric cut in the main tableau by adding a new
4077 * integer division in the context tableau.
4078 * If all other columns have integral coefficients, then we need to
4079 * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
4080 * is always integral. We do this by introducing an integer division
4081 * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
4082 * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
4083 * Since q is expressed in the tableau as
4084 * c + \sum a_i y_i - m q >= 0
4085 * -c - \sum a_i y_i + m q + m - 1 >= 0
4086 * it is sufficient to add the inequality
4087 * -c - \sum a_i y_i + m q >= 0
4088 * In the part of the context where this inequality does not hold, the
4089 * main tableau is marked as being empty.
4091 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
4093 struct isl_context *context;
4094 int r;
4096 if (!tab || sol->error)
4097 goto error;
4099 context = sol->context;
4101 if (tab->empty)
4102 goto done;
4103 if (context->op->is_empty(context))
4104 goto done;
4106 for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
4107 int flags;
4108 int row;
4109 enum isl_tab_row_sign sgn;
4110 int split = -1;
4111 int n_split = 0;
4113 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4114 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
4115 continue;
4116 sgn = row_sign(tab, sol, row);
4117 if (!sgn)
4118 goto error;
4119 tab->row_sign[row] = sgn;
4120 if (sgn == isl_tab_row_any)
4121 n_split++;
4122 if (sgn == isl_tab_row_any && split == -1)
4123 split = row;
4124 if (sgn == isl_tab_row_neg)
4125 break;
4127 if (row < tab->n_row)
4128 continue;
4129 if (split != -1) {
4130 struct isl_vec *ineq;
4131 if (n_split != 1)
4132 split = context->op->best_split(context, tab);
4133 if (split < 0)
4134 goto error;
4135 ineq = get_row_parameter_ineq(tab, split);
4136 if (!ineq)
4137 goto error;
4138 is_strict(ineq);
4139 reset_any_to_unknown(tab);
4140 tab->row_sign[split] = isl_tab_row_pos;
4141 sol_inc_level(sol);
4142 find_in_pos(sol, tab, ineq->el);
4143 tab->row_sign[split] = isl_tab_row_neg;
4144 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4145 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
4146 if (!sol->error)
4147 context->op->add_ineq(context, ineq->el, 0, 1);
4148 isl_vec_free(ineq);
4149 if (sol->error)
4150 goto error;
4151 continue;
4153 if (tab->rational)
4154 break;
4155 row = first_non_integer_row(tab, &flags);
4156 if (row < 0)
4157 break;
4158 if (ISL_FL_ISSET(flags, I_PAR)) {
4159 if (ISL_FL_ISSET(flags, I_VAR)) {
4160 if (isl_tab_mark_empty(tab) < 0)
4161 goto error;
4162 break;
4164 row = add_cut(tab, row);
4165 } else if (ISL_FL_ISSET(flags, I_VAR)) {
4166 struct isl_vec *div;
4167 struct isl_vec *ineq;
4168 int d;
4169 div = get_row_split_div(tab, row);
4170 if (!div)
4171 goto error;
4172 d = context->op->get_div(context, tab, div);
4173 isl_vec_free(div);
4174 if (d < 0)
4175 goto error;
4176 ineq = ineq_for_div(context->op->peek_basic_set(context), d);
4177 if (!ineq)
4178 goto error;
4179 sol_inc_level(sol);
4180 no_sol_in_strict(sol, tab, ineq);
4181 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4182 context->op->add_ineq(context, ineq->el, 1, 1);
4183 isl_vec_free(ineq);
4184 if (sol->error || !context->op->is_ok(context))
4185 goto error;
4186 tab = set_row_cst_to_div(tab, row, d);
4187 if (context->op->is_empty(context))
4188 break;
4189 } else
4190 row = add_parametric_cut(tab, row, context);
4191 if (row < 0)
4192 goto error;
4194 if (r < 0)
4195 goto error;
4196 done:
4197 sol_add(sol, tab);
4198 isl_tab_free(tab);
4199 return;
4200 error:
4201 isl_tab_free(tab);
4202 sol->error = 1;
4205 /* Does "sol" contain a pair of partial solutions that could potentially
4206 * be merged?
4208 * We currently only check that "sol" is not in an error state
4209 * and that there are at least two partial solutions of which the final two
4210 * are defined at the same level.
4212 static int sol_has_mergeable_solutions(struct isl_sol *sol)
4214 if (sol->error)
4215 return 0;
4216 if (!sol->partial)
4217 return 0;
4218 if (!sol->partial->next)
4219 return 0;
4220 return sol->partial->level == sol->partial->next->level;
4223 /* Compute the lexicographic minimum of the set represented by the main
4224 * tableau "tab" within the context "sol->context_tab".
4226 * As a preprocessing step, we first transfer all the purely parametric
4227 * equalities from the main tableau to the context tableau, i.e.,
4228 * parameters that have been pivoted to a row.
4229 * These equalities are ignored by the main algorithm, because the
4230 * corresponding rows may not be marked as being non-negative.
4231 * In parts of the context where the added equality does not hold,
4232 * the main tableau is marked as being empty.
4234 * Before we embark on the actual computation, we save a copy
4235 * of the context. When we return, we check if there are any
4236 * partial solutions that can potentially be merged. If so,
4237 * we perform a rollback to the initial state of the context.
4238 * The merging of partial solutions happens inside calls to
4239 * sol_dec_level that are pushed onto the undo stack of the context.
4240 * If there are no partial solutions that can potentially be merged
4241 * then the rollback is skipped as it would just be wasted effort.
4243 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
4245 int row;
4246 void *saved;
4248 if (!tab)
4249 goto error;
4251 sol->level = 0;
4253 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4254 int p;
4255 struct isl_vec *eq;
4257 if (!row_is_parameter_var(tab, row))
4258 continue;
4259 if (tab->row_var[row] < tab->n_param)
4260 p = tab->row_var[row];
4261 else
4262 p = tab->row_var[row]
4263 + tab->n_param - (tab->n_var - tab->n_div);
4265 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
4266 if (!eq)
4267 goto error;
4268 get_row_parameter_line(tab, row, eq->el);
4269 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
4270 eq = isl_vec_normalize(eq);
4272 sol_inc_level(sol);
4273 no_sol_in_strict(sol, tab, eq);
4275 isl_seq_neg(eq->el, eq->el, eq->size);
4276 sol_inc_level(sol);
4277 no_sol_in_strict(sol, tab, eq);
4278 isl_seq_neg(eq->el, eq->el, eq->size);
4280 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
4282 isl_vec_free(eq);
4284 if (isl_tab_mark_redundant(tab, row) < 0)
4285 goto error;
4287 if (sol->context->op->is_empty(sol->context))
4288 break;
4290 row = tab->n_redundant - 1;
4293 saved = sol->context->op->save(sol->context);
4295 find_solutions(sol, tab);
4297 if (sol_has_mergeable_solutions(sol))
4298 sol->context->op->restore(sol->context, saved);
4299 else
4300 sol->context->op->discard(saved);
4302 sol->level = 0;
4303 sol_pop(sol);
4305 return;
4306 error:
4307 isl_tab_free(tab);
4308 sol->error = 1;
4311 /* Check if integer division "div" of "dom" also occurs in "bmap".
4312 * If so, return its position within the divs.
4313 * Otherwise, return a position beyond the integer divisions.
4315 static int find_context_div(__isl_keep isl_basic_map *bmap,
4316 __isl_keep isl_basic_set *dom, unsigned div)
4318 int i;
4319 int b_v_div, d_v_div;
4320 isl_size n_div;
4322 b_v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4323 d_v_div = isl_basic_set_var_offset(dom, isl_dim_div);
4324 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4325 if (b_v_div < 0 || d_v_div < 0 || n_div < 0)
4326 return -1;
4328 if (isl_int_is_zero(dom->div[div][0]))
4329 return n_div;
4330 if (isl_seq_first_non_zero(dom->div[div] + 2 + d_v_div,
4331 dom->n_div) != -1)
4332 return n_div;
4334 for (i = 0; i < n_div; ++i) {
4335 if (isl_int_is_zero(bmap->div[i][0]))
4336 continue;
4337 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_v_div,
4338 (b_v_div - d_v_div) + n_div) != -1)
4339 continue;
4340 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_v_div))
4341 return i;
4343 return n_div;
4346 /* The correspondence between the variables in the main tableau,
4347 * the context tableau, and the input map and domain is as follows.
4348 * The first n_param and the last n_div variables of the main tableau
4349 * form the variables of the context tableau.
4350 * In the basic map, these n_param variables correspond to the
4351 * parameters and the input dimensions. In the domain, they correspond
4352 * to the parameters and the set dimensions.
4353 * The n_div variables correspond to the integer divisions in the domain.
4354 * To ensure that everything lines up, we may need to copy some of the
4355 * integer divisions of the domain to the map. These have to be placed
4356 * in the same order as those in the context and they have to be placed
4357 * after any other integer divisions that the map may have.
4358 * This function performs the required reordering.
4360 static __isl_give isl_basic_map *align_context_divs(
4361 __isl_take isl_basic_map *bmap, __isl_keep isl_basic_set *dom)
4363 int i;
4364 int common = 0;
4365 int other;
4366 unsigned bmap_n_div;
4368 bmap_n_div = isl_basic_map_dim(bmap, isl_dim_div);
4370 for (i = 0; i < dom->n_div; ++i) {
4371 int pos;
4373 pos = find_context_div(bmap, dom, i);
4374 if (pos < 0)
4375 return isl_basic_map_free(bmap);
4376 if (pos < bmap_n_div)
4377 common++;
4379 other = bmap_n_div - common;
4380 if (dom->n_div - common > 0) {
4381 bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
4382 dom->n_div - common, 0, 0);
4383 if (!bmap)
4384 return NULL;
4386 for (i = 0; i < dom->n_div; ++i) {
4387 int pos = find_context_div(bmap, dom, i);
4388 if (pos < 0)
4389 bmap = isl_basic_map_free(bmap);
4390 if (pos >= bmap_n_div) {
4391 pos = isl_basic_map_alloc_div(bmap);
4392 if (pos < 0)
4393 goto error;
4394 isl_int_set_si(bmap->div[pos][0], 0);
4395 bmap_n_div++;
4397 if (pos != other + i)
4398 bmap = isl_basic_map_swap_div(bmap, pos, other + i);
4400 return bmap;
4401 error:
4402 isl_basic_map_free(bmap);
4403 return NULL;
4406 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4407 * some obvious symmetries.
4409 * We make sure the divs in the domain are properly ordered,
4410 * because they will be added one by one in the given order
4411 * during the construction of the solution map.
4412 * Furthermore, make sure that the known integer divisions
4413 * appear before any unknown integer division because the solution
4414 * may depend on the known integer divisions, while anything that
4415 * depends on any variable starting from the first unknown integer
4416 * division is ignored in sol_pma_add.
4418 static struct isl_sol *basic_map_partial_lexopt_base_sol(
4419 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4420 __isl_give isl_set **empty, int max,
4421 struct isl_sol *(*init)(__isl_keep isl_basic_map *bmap,
4422 __isl_take isl_basic_set *dom, int track_empty, int max))
4424 struct isl_tab *tab;
4425 struct isl_sol *sol = NULL;
4426 struct isl_context *context;
4428 if (dom->n_div) {
4429 dom = isl_basic_set_sort_divs(dom);
4430 bmap = align_context_divs(bmap, dom);
4432 sol = init(bmap, dom, !!empty, max);
4433 if (!sol)
4434 goto error;
4436 context = sol->context;
4437 if (isl_basic_set_plain_is_empty(context->op->peek_basic_set(context)))
4438 /* nothing */;
4439 else if (isl_basic_map_plain_is_empty(bmap)) {
4440 if (sol->add_empty)
4441 sol->add_empty(sol,
4442 isl_basic_set_copy(context->op->peek_basic_set(context)));
4443 } else {
4444 tab = tab_for_lexmin(bmap,
4445 context->op->peek_basic_set(context), 1, max);
4446 tab = context->op->detect_nonnegative_parameters(context, tab);
4447 find_solutions_main(sol, tab);
4449 if (sol->error)
4450 goto error;
4452 isl_basic_map_free(bmap);
4453 return sol;
4454 error:
4455 sol_free(sol);
4456 isl_basic_map_free(bmap);
4457 return NULL;
4460 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4461 * some obvious symmetries.
4463 * We call basic_map_partial_lexopt_base_sol and extract the results.
4465 static __isl_give isl_map *basic_map_partial_lexopt_base(
4466 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4467 __isl_give isl_set **empty, int max)
4469 isl_map *result = NULL;
4470 struct isl_sol *sol;
4471 struct isl_sol_map *sol_map;
4473 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
4474 &sol_map_init);
4475 if (!sol)
4476 return NULL;
4477 sol_map = (struct isl_sol_map *) sol;
4479 result = isl_map_copy(sol_map->map);
4480 if (empty)
4481 *empty = isl_set_copy(sol_map->empty);
4482 sol_free(&sol_map->sol);
4483 return result;
4486 /* Return a count of the number of occurrences of the "n" first
4487 * variables in the inequality constraints of "bmap".
4489 static __isl_give int *count_occurrences(__isl_keep isl_basic_map *bmap,
4490 int n)
4492 int i, j;
4493 isl_ctx *ctx;
4494 int *occurrences;
4496 if (!bmap)
4497 return NULL;
4498 ctx = isl_basic_map_get_ctx(bmap);
4499 occurrences = isl_calloc_array(ctx, int, n);
4500 if (!occurrences)
4501 return NULL;
4503 for (i = 0; i < bmap->n_ineq; ++i) {
4504 for (j = 0; j < n; ++j) {
4505 if (!isl_int_is_zero(bmap->ineq[i][1 + j]))
4506 occurrences[j]++;
4510 return occurrences;
4513 /* Do all of the "n" variables with non-zero coefficients in "c"
4514 * occur in exactly a single constraint.
4515 * "occurrences" is an array of length "n" containing the number
4516 * of occurrences of each of the variables in the inequality constraints.
4518 static int single_occurrence(int n, isl_int *c, int *occurrences)
4520 int i;
4522 for (i = 0; i < n; ++i) {
4523 if (isl_int_is_zero(c[i]))
4524 continue;
4525 if (occurrences[i] != 1)
4526 return 0;
4529 return 1;
4532 /* Do all of the "n" initial variables that occur in inequality constraint
4533 * "ineq" of "bmap" only occur in that constraint?
4535 static int all_single_occurrence(__isl_keep isl_basic_map *bmap, int ineq,
4536 int n)
4538 int i, j;
4540 for (i = 0; i < n; ++i) {
4541 if (isl_int_is_zero(bmap->ineq[ineq][1 + i]))
4542 continue;
4543 for (j = 0; j < bmap->n_ineq; ++j) {
4544 if (j == ineq)
4545 continue;
4546 if (!isl_int_is_zero(bmap->ineq[j][1 + i]))
4547 return 0;
4551 return 1;
4554 /* Structure used during detection of parallel constraints.
4555 * n_in: number of "input" variables: isl_dim_param + isl_dim_in
4556 * n_out: number of "output" variables: isl_dim_out + isl_dim_div
4557 * val: the coefficients of the output variables
4559 struct isl_constraint_equal_info {
4560 unsigned n_in;
4561 unsigned n_out;
4562 isl_int *val;
4565 /* Check whether the coefficients of the output variables
4566 * of the constraint in "entry" are equal to info->val.
4568 static int constraint_equal(const void *entry, const void *val)
4570 isl_int **row = (isl_int **)entry;
4571 const struct isl_constraint_equal_info *info = val;
4573 return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
4576 /* Check whether "bmap" has a pair of constraints that have
4577 * the same coefficients for the output variables.
4578 * Note that the coefficients of the existentially quantified
4579 * variables need to be zero since the existentially quantified
4580 * of the result are usually not the same as those of the input.
4581 * Furthermore, check that each of the input variables that occur
4582 * in those constraints does not occur in any other constraint.
4583 * If so, return true and return the row indices of the two constraints
4584 * in *first and *second.
4586 static isl_bool parallel_constraints(__isl_keep isl_basic_map *bmap,
4587 int *first, int *second)
4589 int i;
4590 isl_ctx *ctx;
4591 int *occurrences = NULL;
4592 struct isl_hash_table *table = NULL;
4593 struct isl_hash_table_entry *entry;
4594 struct isl_constraint_equal_info info;
4595 isl_size nparam, n_in, n_out, n_div;
4597 ctx = isl_basic_map_get_ctx(bmap);
4598 table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4599 if (!table)
4600 goto error;
4602 nparam = isl_basic_map_dim(bmap, isl_dim_param);
4603 n_in = isl_basic_map_dim(bmap, isl_dim_in);
4604 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4605 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4606 if (nparam < 0 || n_in < 0 || n_out < 0 || n_div < 0)
4607 goto error;
4608 info.n_in = nparam + n_in;
4609 occurrences = count_occurrences(bmap, info.n_in);
4610 if (info.n_in && !occurrences)
4611 goto error;
4612 info.n_out = n_out + n_div;
4613 for (i = 0; i < bmap->n_ineq; ++i) {
4614 uint32_t hash;
4616 info.val = bmap->ineq[i] + 1 + info.n_in;
4617 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4618 continue;
4619 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4620 continue;
4621 if (!single_occurrence(info.n_in, bmap->ineq[i] + 1,
4622 occurrences))
4623 continue;
4624 hash = isl_seq_get_hash(info.val, info.n_out);
4625 entry = isl_hash_table_find(ctx, table, hash,
4626 constraint_equal, &info, 1);
4627 if (!entry)
4628 goto error;
4629 if (entry->data)
4630 break;
4631 entry->data = &bmap->ineq[i];
4634 if (i < bmap->n_ineq) {
4635 *first = ((isl_int **)entry->data) - bmap->ineq;
4636 *second = i;
4639 isl_hash_table_free(ctx, table);
4640 free(occurrences);
4642 return i < bmap->n_ineq;
4643 error:
4644 isl_hash_table_free(ctx, table);
4645 free(occurrences);
4646 return isl_bool_error;
4649 /* Given a set of upper bounds in "var", add constraints to "bset"
4650 * that make the i-th bound smallest.
4652 * In particular, if there are n bounds b_i, then add the constraints
4654 * b_i <= b_j for j > i
4655 * b_i < b_j for j < i
4657 static __isl_give isl_basic_set *select_minimum(__isl_take isl_basic_set *bset,
4658 __isl_keep isl_mat *var, int i)
4660 isl_ctx *ctx;
4661 int j, k;
4663 ctx = isl_mat_get_ctx(var);
4665 for (j = 0; j < var->n_row; ++j) {
4666 if (j == i)
4667 continue;
4668 k = isl_basic_set_alloc_inequality(bset);
4669 if (k < 0)
4670 goto error;
4671 isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4672 ctx->negone, var->row[i], var->n_col);
4673 isl_int_set_si(bset->ineq[k][var->n_col], 0);
4674 if (j < i)
4675 isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4678 bset = isl_basic_set_finalize(bset);
4680 return bset;
4681 error:
4682 isl_basic_set_free(bset);
4683 return NULL;
4686 /* Given a set of upper bounds on the last "input" variable m,
4687 * construct a set that assigns the minimal upper bound to m, i.e.,
4688 * construct a set that divides the space into cells where one
4689 * of the upper bounds is smaller than all the others and assign
4690 * this upper bound to m.
4692 * In particular, if there are n bounds b_i, then the result
4693 * consists of n basic sets, each one of the form
4695 * m = b_i
4696 * b_i <= b_j for j > i
4697 * b_i < b_j for j < i
4699 static __isl_give isl_set *set_minimum(__isl_take isl_space *space,
4700 __isl_take isl_mat *var)
4702 int i, k;
4703 isl_basic_set *bset = NULL;
4704 isl_set *set = NULL;
4706 if (!space || !var)
4707 goto error;
4709 set = isl_set_alloc_space(isl_space_copy(space),
4710 var->n_row, ISL_SET_DISJOINT);
4712 for (i = 0; i < var->n_row; ++i) {
4713 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
4714 1, var->n_row - 1);
4715 k = isl_basic_set_alloc_equality(bset);
4716 if (k < 0)
4717 goto error;
4718 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4719 isl_int_set_si(bset->eq[k][var->n_col], -1);
4720 bset = select_minimum(bset, var, i);
4721 set = isl_set_add_basic_set(set, bset);
4724 isl_space_free(space);
4725 isl_mat_free(var);
4726 return set;
4727 error:
4728 isl_basic_set_free(bset);
4729 isl_set_free(set);
4730 isl_space_free(space);
4731 isl_mat_free(var);
4732 return NULL;
4735 /* Given that the last input variable of "bmap" represents the minimum
4736 * of the bounds in "cst", check whether we need to split the domain
4737 * based on which bound attains the minimum.
4739 * A split is needed when the minimum appears in an integer division
4740 * or in an equality. Otherwise, it is only needed if it appears in
4741 * an upper bound that is different from the upper bounds on which it
4742 * is defined.
4744 static isl_bool need_split_basic_map(__isl_keep isl_basic_map *bmap,
4745 __isl_keep isl_mat *cst)
4747 int i, j;
4748 isl_size total;
4749 unsigned pos;
4751 pos = cst->n_col - 1;
4752 total = isl_basic_map_dim(bmap, isl_dim_all);
4753 if (total < 0)
4754 return isl_bool_error;
4756 for (i = 0; i < bmap->n_div; ++i)
4757 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4758 return isl_bool_true;
4760 for (i = 0; i < bmap->n_eq; ++i)
4761 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4762 return isl_bool_true;
4764 for (i = 0; i < bmap->n_ineq; ++i) {
4765 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4766 continue;
4767 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4768 return isl_bool_true;
4769 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4770 total - pos - 1) >= 0)
4771 return isl_bool_true;
4773 for (j = 0; j < cst->n_row; ++j)
4774 if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4775 break;
4776 if (j >= cst->n_row)
4777 return isl_bool_true;
4780 return isl_bool_false;
4783 /* Given that the last set variable of "bset" represents the minimum
4784 * of the bounds in "cst", check whether we need to split the domain
4785 * based on which bound attains the minimum.
4787 * We simply call need_split_basic_map here. This is safe because
4788 * the position of the minimum is computed from "cst" and not
4789 * from "bmap".
4791 static isl_bool need_split_basic_set(__isl_keep isl_basic_set *bset,
4792 __isl_keep isl_mat *cst)
4794 return need_split_basic_map(bset_to_bmap(bset), cst);
4797 /* Given that the last set variable of "set" represents the minimum
4798 * of the bounds in "cst", check whether we need to split the domain
4799 * based on which bound attains the minimum.
4801 static isl_bool need_split_set(__isl_keep isl_set *set, __isl_keep isl_mat *cst)
4803 int i;
4805 for (i = 0; i < set->n; ++i) {
4806 isl_bool split;
4808 split = need_split_basic_set(set->p[i], cst);
4809 if (split < 0 || split)
4810 return split;
4813 return isl_bool_false;
4816 /* Given a map of which the last input variable is the minimum
4817 * of the bounds in "cst", split each basic set in the set
4818 * in pieces where one of the bounds is (strictly) smaller than the others.
4819 * This subdivision is given in "min_expr".
4820 * The variable is subsequently projected out.
4822 * We only do the split when it is needed.
4823 * For example if the last input variable m = min(a,b) and the only
4824 * constraints in the given basic set are lower bounds on m,
4825 * i.e., l <= m = min(a,b), then we can simply project out m
4826 * to obtain l <= a and l <= b, without having to split on whether
4827 * m is equal to a or b.
4829 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4830 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4832 isl_size n_in;
4833 int i;
4834 isl_space *space;
4835 isl_map *res;
4837 n_in = isl_map_dim(opt, isl_dim_in);
4838 if (n_in < 0 || !min_expr || !cst)
4839 goto error;
4841 space = isl_map_get_space(opt);
4842 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
4843 res = isl_map_empty(space);
4845 for (i = 0; i < opt->n; ++i) {
4846 isl_map *map;
4847 isl_bool split;
4849 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4850 split = need_split_basic_map(opt->p[i], cst);
4851 if (split < 0)
4852 map = isl_map_free(map);
4853 else if (split)
4854 map = isl_map_intersect_domain(map,
4855 isl_set_copy(min_expr));
4856 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4858 res = isl_map_union_disjoint(res, map);
4861 isl_map_free(opt);
4862 isl_set_free(min_expr);
4863 isl_mat_free(cst);
4864 return res;
4865 error:
4866 isl_map_free(opt);
4867 isl_set_free(min_expr);
4868 isl_mat_free(cst);
4869 return NULL;
4872 /* Given a set of which the last set variable is the minimum
4873 * of the bounds in "cst", split each basic set in the set
4874 * in pieces where one of the bounds is (strictly) smaller than the others.
4875 * This subdivision is given in "min_expr".
4876 * The variable is subsequently projected out.
4878 static __isl_give isl_set *split(__isl_take isl_set *empty,
4879 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4881 isl_map *map;
4883 map = isl_map_from_domain(empty);
4884 map = split_domain(map, min_expr, cst);
4885 empty = isl_map_domain(map);
4887 return empty;
4890 static __isl_give isl_map *basic_map_partial_lexopt(
4891 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4892 __isl_give isl_set **empty, int max);
4894 /* This function is called from basic_map_partial_lexopt_symm.
4895 * The last variable of "bmap" and "dom" corresponds to the minimum
4896 * of the bounds in "cst". "map_space" is the space of the original
4897 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
4898 * is the space of the original domain.
4900 * We recursively call basic_map_partial_lexopt and then plug in
4901 * the definition of the minimum in the result.
4903 static __isl_give isl_map *basic_map_partial_lexopt_symm_core(
4904 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4905 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
4906 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
4908 isl_map *opt;
4909 isl_set *min_expr;
4911 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
4913 opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4915 if (empty) {
4916 *empty = split(*empty,
4917 isl_set_copy(min_expr), isl_mat_copy(cst));
4918 *empty = isl_set_reset_space(*empty, set_space);
4921 opt = split_domain(opt, min_expr, cst);
4922 opt = isl_map_reset_space(opt, map_space);
4924 return opt;
4927 /* Extract a domain from "bmap" for the purpose of computing
4928 * a lexicographic optimum.
4930 * This function is only called when the caller wants to compute a full
4931 * lexicographic optimum, i.e., without specifying a domain. In this case,
4932 * the caller is not interested in the part of the domain space where
4933 * there is no solution and the domain can be initialized to those constraints
4934 * of "bmap" that only involve the parameters and the input dimensions.
4935 * This relieves the parametric programming engine from detecting those
4936 * inequalities and transferring them to the context. More importantly,
4937 * it ensures that those inequalities are transferred first and not
4938 * intermixed with inequalities that actually split the domain.
4940 * If the caller does not require the absence of existentially quantified
4941 * variables in the result (i.e., if ISL_OPT_QE is not set in "flags"),
4942 * then the actual domain of "bmap" can be used. This ensures that
4943 * the domain does not need to be split at all just to separate out
4944 * pieces of the domain that do not have a solution from piece that do.
4945 * This domain cannot be used in general because it may involve
4946 * (unknown) existentially quantified variables which will then also
4947 * appear in the solution.
4949 static __isl_give isl_basic_set *extract_domain(__isl_keep isl_basic_map *bmap,
4950 unsigned flags)
4952 isl_size n_div;
4953 isl_size n_out;
4955 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4956 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4957 if (n_div < 0 || n_out < 0)
4958 return NULL;
4959 bmap = isl_basic_map_copy(bmap);
4960 if (ISL_FL_ISSET(flags, ISL_OPT_QE)) {
4961 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4962 isl_dim_div, 0, n_div);
4963 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4964 isl_dim_out, 0, n_out);
4966 return isl_basic_map_domain(bmap);
4969 #undef TYPE
4970 #define TYPE isl_map
4971 #undef SUFFIX
4972 #define SUFFIX
4973 #include "isl_tab_lexopt_templ.c"
4975 /* Extract the subsequence of the sample value of "tab"
4976 * starting at "pos" and of length "len".
4978 static __isl_give isl_vec *extract_sample_sequence(struct isl_tab *tab,
4979 int pos, int len)
4981 int i;
4982 isl_ctx *ctx;
4983 isl_vec *v;
4985 ctx = isl_tab_get_ctx(tab);
4986 v = isl_vec_alloc(ctx, len);
4987 if (!v)
4988 return NULL;
4989 for (i = 0; i < len; ++i) {
4990 if (!tab->var[pos + i].is_row) {
4991 isl_int_set_si(v->el[i], 0);
4992 } else {
4993 int row;
4995 row = tab->var[pos + i].index;
4996 isl_int_divexact(v->el[i], tab->mat->row[row][1],
4997 tab->mat->row[row][0]);
5001 return v;
5004 /* Check if the sequence of variables starting at "pos"
5005 * represents a trivial solution according to "trivial".
5006 * That is, is the result of applying "trivial" to this sequence
5007 * equal to the zero vector?
5009 static isl_bool region_is_trivial(struct isl_tab *tab, int pos,
5010 __isl_keep isl_mat *trivial)
5012 int n, len;
5013 isl_vec *v;
5014 isl_bool is_trivial;
5016 if (!trivial)
5017 return isl_bool_error;
5019 n = isl_mat_rows(trivial);
5020 if (n == 0)
5021 return isl_bool_false;
5023 len = isl_mat_cols(trivial);
5024 v = extract_sample_sequence(tab, pos, len);
5025 v = isl_mat_vec_product(isl_mat_copy(trivial), v);
5026 is_trivial = isl_vec_is_zero(v);
5027 isl_vec_free(v);
5029 return is_trivial;
5032 /* Global internal data for isl_tab_basic_set_non_trivial_lexmin.
5034 * "n_op" is the number of initial coordinates to optimize,
5035 * as passed to isl_tab_basic_set_non_trivial_lexmin.
5036 * "region" is the "n_region"-sized array of regions passed
5037 * to isl_tab_basic_set_non_trivial_lexmin.
5039 * "tab" is the tableau that corresponds to the ILP problem.
5040 * "local" is an array of local data structure, one for each
5041 * (potential) level of the backtracking procedure of
5042 * isl_tab_basic_set_non_trivial_lexmin.
5043 * "v" is a pre-allocated vector that can be used for adding
5044 * constraints to the tableau.
5046 * "sol" contains the best solution found so far.
5047 * It is initialized to a vector of size zero.
5049 struct isl_lexmin_data {
5050 int n_op;
5051 int n_region;
5052 struct isl_trivial_region *region;
5054 struct isl_tab *tab;
5055 struct isl_local_region *local;
5056 isl_vec *v;
5058 isl_vec *sol;
5061 /* Return the index of the first trivial region, "n_region" if all regions
5062 * are non-trivial or -1 in case of error.
5064 static int first_trivial_region(struct isl_lexmin_data *data)
5066 int i;
5068 for (i = 0; i < data->n_region; ++i) {
5069 isl_bool trivial;
5070 trivial = region_is_trivial(data->tab, data->region[i].pos,
5071 data->region[i].trivial);
5072 if (trivial < 0)
5073 return -1;
5074 if (trivial)
5075 return i;
5078 return data->n_region;
5081 /* Check if the solution is optimal, i.e., whether the first
5082 * n_op entries are zero.
5084 static int is_optimal(__isl_keep isl_vec *sol, int n_op)
5086 int i;
5088 for (i = 0; i < n_op; ++i)
5089 if (!isl_int_is_zero(sol->el[1 + i]))
5090 return 0;
5091 return 1;
5094 /* Add constraints to "tab" that ensure that any solution is significantly
5095 * better than that represented by "sol". That is, find the first
5096 * relevant (within first n_op) non-zero coefficient and force it (along
5097 * with all previous coefficients) to be zero.
5098 * If the solution is already optimal (all relevant coefficients are zero),
5099 * then just mark the table as empty.
5100 * "n_zero" is the number of coefficients that have been forced zero
5101 * by previous calls to this function at the same level.
5102 * Return the updated number of forced zero coefficients or -1 on error.
5104 * This function assumes that at least 2 * (n_op - n_zero) more rows and
5105 * at least 2 * (n_op - n_zero) more elements in the constraint array
5106 * are available in the tableau.
5108 static int force_better_solution(struct isl_tab *tab,
5109 __isl_keep isl_vec *sol, int n_op, int n_zero)
5111 int i, n;
5112 isl_ctx *ctx;
5113 isl_vec *v = NULL;
5115 if (!sol)
5116 return -1;
5118 for (i = n_zero; i < n_op; ++i)
5119 if (!isl_int_is_zero(sol->el[1 + i]))
5120 break;
5122 if (i == n_op) {
5123 if (isl_tab_mark_empty(tab) < 0)
5124 return -1;
5125 return n_op;
5128 ctx = isl_vec_get_ctx(sol);
5129 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5130 if (!v)
5131 return -1;
5133 n = i + 1;
5134 for (; i >= n_zero; --i) {
5135 v = isl_vec_clr(v);
5136 isl_int_set_si(v->el[1 + i], -1);
5137 if (add_lexmin_eq(tab, v->el) < 0)
5138 goto error;
5141 isl_vec_free(v);
5142 return n;
5143 error:
5144 isl_vec_free(v);
5145 return -1;
5148 /* Fix triviality direction "dir" of the given region to zero.
5150 * This function assumes that at least two more rows and at least
5151 * two more elements in the constraint array are available in the tableau.
5153 static isl_stat fix_zero(struct isl_tab *tab, struct isl_trivial_region *region,
5154 int dir, struct isl_lexmin_data *data)
5156 int len;
5158 data->v = isl_vec_clr(data->v);
5159 if (!data->v)
5160 return isl_stat_error;
5161 len = isl_mat_cols(region->trivial);
5162 isl_seq_cpy(data->v->el + 1 + region->pos, region->trivial->row[dir],
5163 len);
5164 if (add_lexmin_eq(tab, data->v->el) < 0)
5165 return isl_stat_error;
5167 return isl_stat_ok;
5170 /* This function selects case "side" for non-triviality region "region",
5171 * assuming all the equality constraints have been imposed already.
5172 * In particular, the triviality direction side/2 is made positive
5173 * if side is even and made negative if side is odd.
5175 * This function assumes that at least one more row and at least
5176 * one more element in the constraint array are available in the tableau.
5178 static struct isl_tab *pos_neg(struct isl_tab *tab,
5179 struct isl_trivial_region *region,
5180 int side, struct isl_lexmin_data *data)
5182 int len;
5184 data->v = isl_vec_clr(data->v);
5185 if (!data->v)
5186 goto error;
5187 isl_int_set_si(data->v->el[0], -1);
5188 len = isl_mat_cols(region->trivial);
5189 if (side % 2 == 0)
5190 isl_seq_cpy(data->v->el + 1 + region->pos,
5191 region->trivial->row[side / 2], len);
5192 else
5193 isl_seq_neg(data->v->el + 1 + region->pos,
5194 region->trivial->row[side / 2], len);
5195 return add_lexmin_ineq(tab, data->v->el);
5196 error:
5197 isl_tab_free(tab);
5198 return NULL;
5201 /* Local data at each level of the backtracking procedure of
5202 * isl_tab_basic_set_non_trivial_lexmin.
5204 * "update" is set if a solution has been found in the current case
5205 * of this level, such that a better solution needs to be enforced
5206 * in the next case.
5207 * "n_zero" is the number of initial coordinates that have already
5208 * been forced to be zero at this level.
5209 * "region" is the non-triviality region considered at this level.
5210 * "side" is the index of the current case at this level.
5211 * "n" is the number of triviality directions.
5212 * "snap" is a snapshot of the tableau holding a state that needs
5213 * to be satisfied by all subsequent cases.
5215 struct isl_local_region {
5216 int update;
5217 int n_zero;
5218 int region;
5219 int side;
5220 int n;
5221 struct isl_tab_undo *snap;
5224 /* Initialize the global data structure "data" used while solving
5225 * the ILP problem "bset".
5227 static isl_stat init_lexmin_data(struct isl_lexmin_data *data,
5228 __isl_keep isl_basic_set *bset)
5230 isl_ctx *ctx;
5232 ctx = isl_basic_set_get_ctx(bset);
5234 data->tab = tab_for_lexmin(bset, NULL, 0, 0);
5235 if (!data->tab)
5236 return isl_stat_error;
5238 data->v = isl_vec_alloc(ctx, 1 + data->tab->n_var);
5239 if (!data->v)
5240 return isl_stat_error;
5241 data->local = isl_calloc_array(ctx, struct isl_local_region,
5242 data->n_region);
5243 if (data->n_region && !data->local)
5244 return isl_stat_error;
5246 data->sol = isl_vec_alloc(ctx, 0);
5248 return isl_stat_ok;
5251 /* Mark all outer levels as requiring a better solution
5252 * in the next cases.
5254 static void update_outer_levels(struct isl_lexmin_data *data, int level)
5256 int i;
5258 for (i = 0; i < level; ++i)
5259 data->local[i].update = 1;
5262 /* Initialize "local" to refer to region "region" and
5263 * to initiate processing at this level.
5265 static isl_stat init_local_region(struct isl_local_region *local, int region,
5266 struct isl_lexmin_data *data)
5268 local->n = isl_mat_rows(data->region[region].trivial);
5269 local->region = region;
5270 local->side = 0;
5271 local->update = 0;
5272 local->n_zero = 0;
5274 return isl_stat_ok;
5277 /* What to do next after entering a level of the backtracking procedure.
5279 * error: some error has occurred; abort
5280 * done: an optimal solution has been found; stop search
5281 * backtrack: backtrack to the previous level
5282 * handle: add the constraints for the current level and
5283 * move to the next level
5285 enum isl_next {
5286 isl_next_error = -1,
5287 isl_next_done,
5288 isl_next_backtrack,
5289 isl_next_handle,
5292 /* Have all cases of the current region been considered?
5293 * If there are n directions, then there are 2n cases.
5295 * The constraints in the current tableau are imposed
5296 * in all subsequent cases. This means that if the current
5297 * tableau is empty, then none of those cases should be considered
5298 * anymore and all cases have effectively been considered.
5300 static int finished_all_cases(struct isl_local_region *local,
5301 struct isl_lexmin_data *data)
5303 if (data->tab->empty)
5304 return 1;
5305 return local->side >= 2 * local->n;
5308 /* Enter level "level" of the backtracking search and figure out
5309 * what to do next. "init" is set if the level was entered
5310 * from a higher level and needs to be initialized.
5311 * Otherwise, the level is entered as a result of backtracking and
5312 * the tableau needs to be restored to a position that can
5313 * be used for the next case at this level.
5314 * The snapshot is assumed to have been saved in the previous case,
5315 * before the constraints specific to that case were added.
5317 * In the initialization case, the local region is initialized
5318 * to point to the first violated region.
5319 * If the constraints of all regions are satisfied by the current
5320 * sample of the tableau, then tell the caller to continue looking
5321 * for a better solution or to stop searching if an optimal solution
5322 * has been found.
5324 * If the tableau is empty or if all cases at the current level
5325 * have been considered, then the caller needs to backtrack as well.
5327 static enum isl_next enter_level(int level, int init,
5328 struct isl_lexmin_data *data)
5330 struct isl_local_region *local = &data->local[level];
5332 if (init) {
5333 int r;
5335 data->tab = cut_to_integer_lexmin(data->tab, CUT_ONE);
5336 if (!data->tab)
5337 return isl_next_error;
5338 if (data->tab->empty)
5339 return isl_next_backtrack;
5340 r = first_trivial_region(data);
5341 if (r < 0)
5342 return isl_next_error;
5343 if (r == data->n_region) {
5344 update_outer_levels(data, level);
5345 isl_vec_free(data->sol);
5346 data->sol = isl_tab_get_sample_value(data->tab);
5347 if (!data->sol)
5348 return isl_next_error;
5349 if (is_optimal(data->sol, data->n_op))
5350 return isl_next_done;
5351 return isl_next_backtrack;
5353 if (level >= data->n_region)
5354 isl_die(isl_vec_get_ctx(data->v), isl_error_internal,
5355 "nesting level too deep",
5356 return isl_next_error);
5357 if (init_local_region(local, r, data) < 0)
5358 return isl_next_error;
5359 if (isl_tab_extend_cons(data->tab,
5360 2 * local->n + 2 * data->n_op) < 0)
5361 return isl_next_error;
5362 } else {
5363 if (isl_tab_rollback(data->tab, local->snap) < 0)
5364 return isl_next_error;
5367 if (finished_all_cases(local, data))
5368 return isl_next_backtrack;
5369 return isl_next_handle;
5372 /* If a solution has been found in the previous case at this level
5373 * (marked by local->update being set), then add constraints
5374 * that enforce a better solution in the present and all following cases.
5375 * The constraints only need to be imposed once because they are
5376 * included in the snapshot (taken in pick_side) that will be used in
5377 * subsequent cases.
5379 static isl_stat better_next_side(struct isl_local_region *local,
5380 struct isl_lexmin_data *data)
5382 if (!local->update)
5383 return isl_stat_ok;
5385 local->n_zero = force_better_solution(data->tab,
5386 data->sol, data->n_op, local->n_zero);
5387 if (local->n_zero < 0)
5388 return isl_stat_error;
5390 local->update = 0;
5392 return isl_stat_ok;
5395 /* Add constraints to data->tab that select the current case (local->side)
5396 * at the current level.
5398 * If the linear combinations v should not be zero, then the cases are
5399 * v_0 >= 1
5400 * v_0 <= -1
5401 * v_0 = 0 and v_1 >= 1
5402 * v_0 = 0 and v_1 <= -1
5403 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5404 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5405 * ...
5406 * in this order.
5408 * A snapshot is taken after the equality constraint (if any) has been added
5409 * such that the next case can start off from this position.
5410 * The rollback to this position is performed in enter_level.
5412 static isl_stat pick_side(struct isl_local_region *local,
5413 struct isl_lexmin_data *data)
5415 struct isl_trivial_region *region;
5416 int side, base;
5418 region = &data->region[local->region];
5419 side = local->side;
5420 base = 2 * (side/2);
5422 if (side == base && base >= 2 &&
5423 fix_zero(data->tab, region, base / 2 - 1, data) < 0)
5424 return isl_stat_error;
5426 local->snap = isl_tab_snap(data->tab);
5427 if (isl_tab_push_basis(data->tab) < 0)
5428 return isl_stat_error;
5430 data->tab = pos_neg(data->tab, region, side, data);
5431 if (!data->tab)
5432 return isl_stat_error;
5433 return isl_stat_ok;
5436 /* Free the memory associated to "data".
5438 static void clear_lexmin_data(struct isl_lexmin_data *data)
5440 free(data->local);
5441 isl_vec_free(data->v);
5442 isl_tab_free(data->tab);
5445 /* Return the lexicographically smallest non-trivial solution of the
5446 * given ILP problem.
5448 * All variables are assumed to be non-negative.
5450 * n_op is the number of initial coordinates to optimize.
5451 * That is, once a solution has been found, we will only continue looking
5452 * for solutions that result in significantly better values for those
5453 * initial coordinates. That is, we only continue looking for solutions
5454 * that increase the number of initial zeros in this sequence.
5456 * A solution is non-trivial, if it is non-trivial on each of the
5457 * specified regions. Each region represents a sequence of
5458 * triviality directions on a sequence of variables that starts
5459 * at a given position. A solution is non-trivial on such a region if
5460 * at least one of the triviality directions is non-zero
5461 * on that sequence of variables.
5463 * Whenever a conflict is encountered, all constraints involved are
5464 * reported to the caller through a call to "conflict".
5466 * We perform a simple branch-and-bound backtracking search.
5467 * Each level in the search represents an initially trivial region
5468 * that is forced to be non-trivial.
5469 * At each level we consider 2 * n cases, where n
5470 * is the number of triviality directions.
5471 * In terms of those n directions v_i, we consider the cases
5472 * v_0 >= 1
5473 * v_0 <= -1
5474 * v_0 = 0 and v_1 >= 1
5475 * v_0 = 0 and v_1 <= -1
5476 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5477 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5478 * ...
5479 * in this order.
5481 __isl_give isl_vec *isl_tab_basic_set_non_trivial_lexmin(
5482 __isl_take isl_basic_set *bset, int n_op, int n_region,
5483 struct isl_trivial_region *region,
5484 int (*conflict)(int con, void *user), void *user)
5486 struct isl_lexmin_data data = { n_op, n_region, region };
5487 int level, init;
5489 if (!bset)
5490 return NULL;
5492 if (init_lexmin_data(&data, bset) < 0)
5493 goto error;
5494 data.tab->conflict = conflict;
5495 data.tab->conflict_user = user;
5497 level = 0;
5498 init = 1;
5500 while (level >= 0) {
5501 enum isl_next next;
5502 struct isl_local_region *local = &data.local[level];
5504 next = enter_level(level, init, &data);
5505 if (next < 0)
5506 goto error;
5507 if (next == isl_next_done)
5508 break;
5509 if (next == isl_next_backtrack) {
5510 level--;
5511 init = 0;
5512 continue;
5515 if (better_next_side(local, &data) < 0)
5516 goto error;
5517 if (pick_side(local, &data) < 0)
5518 goto error;
5520 local->side++;
5521 level++;
5522 init = 1;
5525 clear_lexmin_data(&data);
5526 isl_basic_set_free(bset);
5528 return data.sol;
5529 error:
5530 clear_lexmin_data(&data);
5531 isl_basic_set_free(bset);
5532 isl_vec_free(data.sol);
5533 return NULL;
5536 /* Wrapper for a tableau that is used for computing
5537 * the lexicographically smallest rational point of a non-negative set.
5538 * This point is represented by the sample value of "tab",
5539 * unless "tab" is empty.
5541 struct isl_tab_lexmin {
5542 isl_ctx *ctx;
5543 struct isl_tab *tab;
5546 /* Free "tl" and return NULL.
5548 __isl_null isl_tab_lexmin *isl_tab_lexmin_free(__isl_take isl_tab_lexmin *tl)
5550 if (!tl)
5551 return NULL;
5552 isl_ctx_deref(tl->ctx);
5553 isl_tab_free(tl->tab);
5554 free(tl);
5556 return NULL;
5559 /* Construct an isl_tab_lexmin for computing
5560 * the lexicographically smallest rational point in "bset",
5561 * assuming that all variables are non-negative.
5563 __isl_give isl_tab_lexmin *isl_tab_lexmin_from_basic_set(
5564 __isl_take isl_basic_set *bset)
5566 isl_ctx *ctx;
5567 isl_tab_lexmin *tl;
5569 if (!bset)
5570 return NULL;
5572 ctx = isl_basic_set_get_ctx(bset);
5573 tl = isl_calloc_type(ctx, struct isl_tab_lexmin);
5574 if (!tl)
5575 goto error;
5576 tl->ctx = ctx;
5577 isl_ctx_ref(ctx);
5578 tl->tab = tab_for_lexmin(bset, NULL, 0, 0);
5579 isl_basic_set_free(bset);
5580 if (!tl->tab)
5581 return isl_tab_lexmin_free(tl);
5582 return tl;
5583 error:
5584 isl_basic_set_free(bset);
5585 isl_tab_lexmin_free(tl);
5586 return NULL;
5589 /* Return the dimension of the set represented by "tl".
5591 int isl_tab_lexmin_dim(__isl_keep isl_tab_lexmin *tl)
5593 return tl ? tl->tab->n_var : -1;
5596 /* Add the equality with coefficients "eq" to "tl", updating the optimal
5597 * solution if needed.
5598 * The equality is added as two opposite inequality constraints.
5600 __isl_give isl_tab_lexmin *isl_tab_lexmin_add_eq(__isl_take isl_tab_lexmin *tl,
5601 isl_int *eq)
5603 unsigned n_var;
5605 if (!tl || !eq)
5606 return isl_tab_lexmin_free(tl);
5608 if (isl_tab_extend_cons(tl->tab, 2) < 0)
5609 return isl_tab_lexmin_free(tl);
5610 n_var = tl->tab->n_var;
5611 isl_seq_neg(eq, eq, 1 + n_var);
5612 tl->tab = add_lexmin_ineq(tl->tab, eq);
5613 isl_seq_neg(eq, eq, 1 + n_var);
5614 tl->tab = add_lexmin_ineq(tl->tab, eq);
5616 if (!tl->tab)
5617 return isl_tab_lexmin_free(tl);
5619 return tl;
5622 /* Add cuts to "tl" until the sample value reaches an integer value or
5623 * until the result becomes empty.
5625 __isl_give isl_tab_lexmin *isl_tab_lexmin_cut_to_integer(
5626 __isl_take isl_tab_lexmin *tl)
5628 if (!tl)
5629 return NULL;
5630 tl->tab = cut_to_integer_lexmin(tl->tab, CUT_ONE);
5631 if (!tl->tab)
5632 return isl_tab_lexmin_free(tl);
5633 return tl;
5636 /* Return the lexicographically smallest rational point in the basic set
5637 * from which "tl" was constructed.
5638 * If the original input was empty, then return a zero-length vector.
5640 __isl_give isl_vec *isl_tab_lexmin_get_solution(__isl_keep isl_tab_lexmin *tl)
5642 if (!tl)
5643 return NULL;
5644 if (tl->tab->empty)
5645 return isl_vec_alloc(tl->ctx, 0);
5646 else
5647 return isl_tab_get_sample_value(tl->tab);
5650 struct isl_sol_pma {
5651 struct isl_sol sol;
5652 isl_pw_multi_aff *pma;
5653 isl_set *empty;
5656 static void sol_pma_free(struct isl_sol *sol)
5658 struct isl_sol_pma *sol_pma = (struct isl_sol_pma *) sol;
5659 isl_pw_multi_aff_free(sol_pma->pma);
5660 isl_set_free(sol_pma->empty);
5663 /* This function is called for parts of the context where there is
5664 * no solution, with "bset" corresponding to the context tableau.
5665 * Simply add the basic set to the set "empty".
5667 static void sol_pma_add_empty(struct isl_sol_pma *sol,
5668 __isl_take isl_basic_set *bset)
5670 if (!bset || !sol->empty)
5671 goto error;
5673 sol->empty = isl_set_grow(sol->empty, 1);
5674 bset = isl_basic_set_simplify(bset);
5675 bset = isl_basic_set_finalize(bset);
5676 sol->empty = isl_set_add_basic_set(sol->empty, bset);
5677 if (!sol->empty)
5678 sol->sol.error = 1;
5679 return;
5680 error:
5681 isl_basic_set_free(bset);
5682 sol->sol.error = 1;
5685 /* Given a basic set "dom" that represents the context and a tuple of
5686 * affine expressions "maff" defined over this domain, construct
5687 * an isl_pw_multi_aff with a single cell corresponding to "dom" and
5688 * the affine expressions in "maff".
5690 static void sol_pma_add(struct isl_sol_pma *sol,
5691 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *maff)
5693 isl_pw_multi_aff *pma;
5695 dom = isl_basic_set_simplify(dom);
5696 dom = isl_basic_set_finalize(dom);
5697 pma = isl_pw_multi_aff_alloc(isl_set_from_basic_set(dom), maff);
5698 sol->pma = isl_pw_multi_aff_add_disjoint(sol->pma, pma);
5699 if (!sol->pma)
5700 sol->sol.error = 1;
5703 static void sol_pma_add_empty_wrap(struct isl_sol *sol,
5704 __isl_take isl_basic_set *bset)
5706 sol_pma_add_empty((struct isl_sol_pma *)sol, bset);
5709 static void sol_pma_add_wrap(struct isl_sol *sol,
5710 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
5712 sol_pma_add((struct isl_sol_pma *)sol, dom, ma);
5715 /* Construct an isl_sol_pma structure for accumulating the solution.
5716 * If track_empty is set, then we also keep track of the parts
5717 * of the context where there is no solution.
5718 * If max is set, then we are solving a maximization, rather than
5719 * a minimization problem, which means that the variables in the
5720 * tableau have value "M - x" rather than "M + x".
5722 static struct isl_sol *sol_pma_init(__isl_keep isl_basic_map *bmap,
5723 __isl_take isl_basic_set *dom, int track_empty, int max)
5725 struct isl_sol_pma *sol_pma = NULL;
5726 isl_space *space;
5728 if (!bmap)
5729 goto error;
5731 sol_pma = isl_calloc_type(bmap->ctx, struct isl_sol_pma);
5732 if (!sol_pma)
5733 goto error;
5735 sol_pma->sol.free = &sol_pma_free;
5736 if (sol_init(&sol_pma->sol, bmap, dom, max) < 0)
5737 goto error;
5738 sol_pma->sol.add = &sol_pma_add_wrap;
5739 sol_pma->sol.add_empty = track_empty ? &sol_pma_add_empty_wrap : NULL;
5740 space = isl_space_copy(sol_pma->sol.space);
5741 sol_pma->pma = isl_pw_multi_aff_empty(space);
5742 if (!sol_pma->pma)
5743 goto error;
5745 if (track_empty) {
5746 sol_pma->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
5747 1, ISL_SET_DISJOINT);
5748 if (!sol_pma->empty)
5749 goto error;
5752 isl_basic_set_free(dom);
5753 return &sol_pma->sol;
5754 error:
5755 isl_basic_set_free(dom);
5756 sol_free(&sol_pma->sol);
5757 return NULL;
5760 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
5761 * some obvious symmetries.
5763 * We call basic_map_partial_lexopt_base_sol and extract the results.
5765 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_base_pw_multi_aff(
5766 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5767 __isl_give isl_set **empty, int max)
5769 isl_pw_multi_aff *result = NULL;
5770 struct isl_sol *sol;
5771 struct isl_sol_pma *sol_pma;
5773 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
5774 &sol_pma_init);
5775 if (!sol)
5776 return NULL;
5777 sol_pma = (struct isl_sol_pma *) sol;
5779 result = isl_pw_multi_aff_copy(sol_pma->pma);
5780 if (empty)
5781 *empty = isl_set_copy(sol_pma->empty);
5782 sol_free(&sol_pma->sol);
5783 return result;
5786 /* Given that the last input variable of "maff" represents the minimum
5787 * of some bounds, check whether we need to plug in the expression
5788 * of the minimum.
5790 * In particular, check if the last input variable appears in any
5791 * of the expressions in "maff".
5793 static isl_bool need_substitution(__isl_keep isl_multi_aff *maff)
5795 int i;
5796 isl_size n_in;
5797 unsigned pos;
5799 n_in = isl_multi_aff_dim(maff, isl_dim_in);
5800 if (n_in < 0)
5801 return isl_bool_error;
5802 pos = n_in - 1;
5804 for (i = 0; i < maff->n; ++i) {
5805 isl_bool involves;
5807 involves = isl_aff_involves_dims(maff->u.p[i],
5808 isl_dim_in, pos, 1);
5809 if (involves < 0 || involves)
5810 return involves;
5813 return isl_bool_false;
5816 /* Given a set of upper bounds on the last "input" variable m,
5817 * construct a piecewise affine expression that selects
5818 * the minimal upper bound to m, i.e.,
5819 * divide the space into cells where one
5820 * of the upper bounds is smaller than all the others and select
5821 * this upper bound on that cell.
5823 * In particular, if there are n bounds b_i, then the result
5824 * consists of n cell, each one of the form
5826 * b_i <= b_j for j > i
5827 * b_i < b_j for j < i
5829 * The affine expression on this cell is
5831 * b_i
5833 static __isl_give isl_pw_aff *set_minimum_pa(__isl_take isl_space *space,
5834 __isl_take isl_mat *var)
5836 int i;
5837 isl_aff *aff = NULL;
5838 isl_basic_set *bset = NULL;
5839 isl_pw_aff *paff = NULL;
5840 isl_space *pw_space;
5841 isl_local_space *ls = NULL;
5843 if (!space || !var)
5844 goto error;
5846 ls = isl_local_space_from_space(isl_space_copy(space));
5847 pw_space = isl_space_copy(space);
5848 pw_space = isl_space_from_domain(pw_space);
5849 pw_space = isl_space_add_dims(pw_space, isl_dim_out, 1);
5850 paff = isl_pw_aff_alloc_size(pw_space, var->n_row);
5852 for (i = 0; i < var->n_row; ++i) {
5853 isl_pw_aff *paff_i;
5855 aff = isl_aff_alloc(isl_local_space_copy(ls));
5856 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
5857 0, var->n_row - 1);
5858 if (!aff || !bset)
5859 goto error;
5860 isl_int_set_si(aff->v->el[0], 1);
5861 isl_seq_cpy(aff->v->el + 1, var->row[i], var->n_col);
5862 isl_int_set_si(aff->v->el[1 + var->n_col], 0);
5863 bset = select_minimum(bset, var, i);
5864 paff_i = isl_pw_aff_alloc(isl_set_from_basic_set(bset), aff);
5865 paff = isl_pw_aff_add_disjoint(paff, paff_i);
5868 isl_local_space_free(ls);
5869 isl_space_free(space);
5870 isl_mat_free(var);
5871 return paff;
5872 error:
5873 isl_aff_free(aff);
5874 isl_basic_set_free(bset);
5875 isl_pw_aff_free(paff);
5876 isl_local_space_free(ls);
5877 isl_space_free(space);
5878 isl_mat_free(var);
5879 return NULL;
5882 /* Given a piecewise multi-affine expression of which the last input variable
5883 * is the minimum of the bounds in "cst", plug in the value of the minimum.
5884 * This minimum expression is given in "min_expr_pa".
5885 * The set "min_expr" contains the same information, but in the form of a set.
5886 * The variable is subsequently projected out.
5888 * The implementation is similar to those of "split" and "split_domain".
5889 * If the variable appears in a given expression, then minimum expression
5890 * is plugged in. Otherwise, if the variable appears in the constraints
5891 * and a split is required, then the domain is split. Otherwise, no split
5892 * is performed.
5894 static __isl_give isl_pw_multi_aff *split_domain_pma(
5895 __isl_take isl_pw_multi_aff *opt, __isl_take isl_pw_aff *min_expr_pa,
5896 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
5898 isl_size n_in;
5899 int i;
5900 isl_space *space;
5901 isl_pw_multi_aff *res;
5903 if (!opt || !min_expr || !cst)
5904 goto error;
5906 n_in = isl_pw_multi_aff_dim(opt, isl_dim_in);
5907 if (n_in < 0)
5908 goto error;
5909 space = isl_pw_multi_aff_get_space(opt);
5910 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
5911 res = isl_pw_multi_aff_empty(space);
5913 for (i = 0; i < opt->n; ++i) {
5914 isl_bool subs;
5915 isl_pw_multi_aff *pma;
5917 pma = isl_pw_multi_aff_alloc(isl_set_copy(opt->p[i].set),
5918 isl_multi_aff_copy(opt->p[i].maff));
5919 subs = need_substitution(opt->p[i].maff);
5920 if (subs < 0) {
5921 pma = isl_pw_multi_aff_free(pma);
5922 } else if (subs) {
5923 pma = isl_pw_multi_aff_substitute(pma,
5924 isl_dim_in, n_in - 1, min_expr_pa);
5925 } else {
5926 isl_bool split;
5927 split = need_split_set(opt->p[i].set, cst);
5928 if (split < 0)
5929 pma = isl_pw_multi_aff_free(pma);
5930 else if (split)
5931 pma = isl_pw_multi_aff_intersect_domain(pma,
5932 isl_set_copy(min_expr));
5934 pma = isl_pw_multi_aff_project_out(pma,
5935 isl_dim_in, n_in - 1, 1);
5937 res = isl_pw_multi_aff_add_disjoint(res, pma);
5940 isl_pw_multi_aff_free(opt);
5941 isl_pw_aff_free(min_expr_pa);
5942 isl_set_free(min_expr);
5943 isl_mat_free(cst);
5944 return res;
5945 error:
5946 isl_pw_multi_aff_free(opt);
5947 isl_pw_aff_free(min_expr_pa);
5948 isl_set_free(min_expr);
5949 isl_mat_free(cst);
5950 return NULL;
5953 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pw_multi_aff(
5954 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5955 __isl_give isl_set **empty, int max);
5957 /* This function is called from basic_map_partial_lexopt_symm.
5958 * The last variable of "bmap" and "dom" corresponds to the minimum
5959 * of the bounds in "cst". "map_space" is the space of the original
5960 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
5961 * is the space of the original domain.
5963 * We recursively call basic_map_partial_lexopt and then plug in
5964 * the definition of the minimum in the result.
5966 static __isl_give isl_pw_multi_aff *
5967 basic_map_partial_lexopt_symm_core_pw_multi_aff(
5968 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5969 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
5970 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
5972 isl_pw_multi_aff *opt;
5973 isl_pw_aff *min_expr_pa;
5974 isl_set *min_expr;
5976 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
5977 min_expr_pa = set_minimum_pa(isl_basic_set_get_space(dom),
5978 isl_mat_copy(cst));
5980 opt = basic_map_partial_lexopt_pw_multi_aff(bmap, dom, empty, max);
5982 if (empty) {
5983 *empty = split(*empty,
5984 isl_set_copy(min_expr), isl_mat_copy(cst));
5985 *empty = isl_set_reset_space(*empty, set_space);
5988 opt = split_domain_pma(opt, min_expr_pa, min_expr, cst);
5989 opt = isl_pw_multi_aff_reset_space(opt, map_space);
5991 return opt;
5994 #undef TYPE
5995 #define TYPE isl_pw_multi_aff
5996 #undef SUFFIX
5997 #define SUFFIX _pw_multi_aff
5998 #include "isl_tab_lexopt_templ.c"