detect some modulo expressions when extracting a function
[isl.git] / isl_tab_pip.c
blobc9e348c1a3f5fe064946c49fc25401c9f15de3f7
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 /* Add equality constraint "eq" to the context of "sol".
217 * "check" is set if "eq" is not known to be a valid constraint.
218 * "update" is set if ineq_sign() may still get called on the context.
220 static void sol_context_add_eq(struct isl_sol *sol, isl_int *eq, int check,
221 int update)
223 sol->context->op->add_eq(sol->context, eq, check, update);
224 if (!sol->context->op->is_ok(sol->context))
225 sol->error = 1;
228 /* Add inequality constraint "ineq" to the context of "sol".
229 * "check" is set if "ineq" is not known to be a valid constraint.
230 * "update" is set if ineq_sign() may still get called on the context.
232 static void sol_context_add_ineq(struct isl_sol *sol, isl_int *ineq, int check,
233 int update)
235 if (sol->error)
236 return;
237 sol->context->op->add_ineq(sol->context, ineq, check, update);
238 if (!sol->context->op->is_ok(sol->context))
239 sol->error = 1;
242 /* Push a partial solution represented by a domain and function "ma"
243 * onto the stack of partial solutions.
244 * If "ma" is NULL, then "dom" represents a part of the domain
245 * with no solution.
247 static void sol_push_sol(struct isl_sol *sol,
248 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
250 struct isl_partial_sol *partial;
252 if (sol->error || !dom)
253 goto error;
255 partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
256 if (!partial)
257 goto error;
259 partial->level = sol->level;
260 partial->dom = dom;
261 partial->ma = ma;
262 partial->next = sol->partial;
264 sol->partial = partial;
266 return;
267 error:
268 isl_basic_set_free(dom);
269 isl_multi_aff_free(ma);
270 sol->error = 1;
273 /* Check that the final columns of "M", starting at "first", are zero.
275 static isl_stat check_final_columns_are_zero(__isl_keep isl_mat *M,
276 unsigned first)
278 int i;
279 isl_size rows, cols;
280 unsigned n;
282 rows = isl_mat_rows(M);
283 cols = isl_mat_cols(M);
284 if (rows < 0 || cols < 0)
285 return isl_stat_error;
286 n = cols - first;
287 for (i = 0; i < rows; ++i)
288 if (isl_seq_first_non_zero(M->row[i] + first, n) != -1)
289 isl_die(isl_mat_get_ctx(M), isl_error_internal,
290 "final columns should be zero",
291 return isl_stat_error);
292 return isl_stat_ok;
295 /* Set the affine expressions in "ma" according to the rows in "M", which
296 * are defined over the local space "ls".
297 * The matrix "M" may have extra (zero) columns beyond the number
298 * of variables in "ls".
300 static __isl_give isl_multi_aff *set_from_affine_matrix(
301 __isl_take isl_multi_aff *ma, __isl_take isl_local_space *ls,
302 __isl_take isl_mat *M)
304 int i;
305 isl_size dim;
306 isl_aff *aff;
308 dim = isl_local_space_dim(ls, isl_dim_all);
309 if (!ma || dim < 0 || !M)
310 goto error;
312 if (check_final_columns_are_zero(M, 1 + dim) < 0)
313 goto error;
314 for (i = 1; i < M->n_row; ++i) {
315 aff = isl_aff_alloc(isl_local_space_copy(ls));
316 if (aff) {
317 isl_int_set(aff->v->el[0], M->row[0][0]);
318 isl_seq_cpy(aff->v->el + 1, M->row[i], 1 + dim);
320 aff = isl_aff_normalize(aff);
321 ma = isl_multi_aff_set_aff(ma, i - 1, aff);
323 isl_local_space_free(ls);
324 isl_mat_free(M);
326 return ma;
327 error:
328 isl_local_space_free(ls);
329 isl_mat_free(M);
330 isl_multi_aff_free(ma);
331 return NULL;
334 /* Push a partial solution represented by a domain and mapping M
335 * onto the stack of partial solutions.
337 * The affine matrix "M" maps the dimensions of the context
338 * to the output variables. Convert it into an isl_multi_aff and
339 * then call sol_push_sol.
341 * Note that the description of the initial context may have involved
342 * existentially quantified variables, in which case they also appear
343 * in "dom". These need to be removed before creating the affine
344 * expression because an affine expression cannot be defined in terms
345 * of existentially quantified variables without a known representation.
346 * Since newly added integer divisions are inserted before these
347 * existentially quantified variables, they are still in the final
348 * positions and the corresponding final columns of "M" are zero
349 * because align_context_divs adds the existentially quantified
350 * variables of the context to the main tableau without any constraints and
351 * any equality constraints that are added later on can only serve
352 * to eliminate these existentially quantified variables.
354 static void sol_push_sol_mat(struct isl_sol *sol,
355 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
357 isl_local_space *ls;
358 isl_multi_aff *ma;
359 isl_size n_div;
360 int n_known;
362 n_div = isl_basic_set_dim(dom, isl_dim_div);
363 if (n_div < 0)
364 goto error;
365 n_known = n_div - sol->context->n_unknown;
367 ma = isl_multi_aff_alloc(isl_space_copy(sol->space));
368 ls = isl_basic_set_get_local_space(dom);
369 ls = isl_local_space_drop_dims(ls, isl_dim_div,
370 n_known, n_div - n_known);
371 ma = set_from_affine_matrix(ma, ls, M);
373 if (!ma)
374 dom = isl_basic_set_free(dom);
375 sol_push_sol(sol, dom, ma);
376 return;
377 error:
378 isl_basic_set_free(dom);
379 isl_mat_free(M);
380 sol_push_sol(sol, NULL, NULL);
383 /* Pop one partial solution from the partial solution stack and
384 * pass it on to sol->add or sol->add_empty.
386 static void sol_pop_one(struct isl_sol *sol)
388 struct isl_partial_sol *partial;
390 partial = sol->partial;
391 sol->partial = partial->next;
393 if (partial->ma)
394 sol->add(sol, partial->dom, partial->ma);
395 else
396 sol->add_empty(sol, partial->dom);
397 free(partial);
400 /* Return a fresh copy of the domain represented by the context tableau.
402 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
404 struct isl_basic_set *bset;
406 if (sol->error)
407 return NULL;
409 bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
410 bset = isl_basic_set_update_from_tab(bset,
411 sol->context->op->peek_tab(sol->context));
413 return bset;
416 /* Check whether two partial solutions have the same affine expressions.
418 static isl_bool same_solution(struct isl_partial_sol *s1,
419 struct isl_partial_sol *s2)
421 if (!s1->ma != !s2->ma)
422 return isl_bool_false;
423 if (!s1->ma)
424 return isl_bool_true;
426 return isl_multi_aff_plain_is_equal(s1->ma, s2->ma);
429 /* Swap the initial two partial solutions in "sol".
431 * That is, go from
433 * sol->partial = p1; p1->next = p2; p2->next = p3
435 * to
437 * sol->partial = p2; p2->next = p1; p1->next = p3
439 static void swap_initial(struct isl_sol *sol)
441 struct isl_partial_sol *partial;
443 partial = sol->partial;
444 sol->partial = partial->next;
445 partial->next = partial->next->next;
446 sol->partial->next = partial;
449 /* Combine the initial two partial solution of "sol" into
450 * a partial solution with the current context domain of "sol" and
451 * the function description of the second partial solution in the list.
452 * The level of the new partial solution is set to the current level.
454 * That is, the first two partial solutions (D1,M1) and (D2,M2) are
455 * replaced by (D,M2), where D is the domain of "sol", which is assumed
456 * to be the union of D1 and D2, while M1 is assumed to be equal to M2
457 * (at least on D1).
459 static isl_stat combine_initial_into_second(struct isl_sol *sol)
461 struct isl_partial_sol *partial;
462 isl_basic_set *bset;
464 partial = sol->partial;
466 bset = sol_domain(sol);
467 isl_basic_set_free(partial->next->dom);
468 partial->next->dom = bset;
469 partial->next->level = sol->level;
471 if (!bset)
472 return isl_stat_error;
474 sol->partial = partial->next;
475 isl_basic_set_free(partial->dom);
476 isl_multi_aff_free(partial->ma);
477 free(partial);
479 return isl_stat_ok;
482 /* Are "ma1" and "ma2" equal to each other on "dom"?
484 * Combine "ma1" and "ma2" with "dom" and check if the results are the same.
485 * "dom" may have existentially quantified variables. Eliminate them first
486 * as otherwise they would have to be eliminated twice, in a more complicated
487 * context.
489 static isl_bool equal_on_domain(__isl_keep isl_multi_aff *ma1,
490 __isl_keep isl_multi_aff *ma2, __isl_keep isl_basic_set *dom)
492 isl_set *set;
493 isl_pw_multi_aff *pma1, *pma2;
494 isl_bool equal;
496 set = isl_basic_set_compute_divs(isl_basic_set_copy(dom));
497 pma1 = isl_pw_multi_aff_alloc(isl_set_copy(set),
498 isl_multi_aff_copy(ma1));
499 pma2 = isl_pw_multi_aff_alloc(set, isl_multi_aff_copy(ma2));
500 equal = isl_pw_multi_aff_is_equal(pma1, pma2);
501 isl_pw_multi_aff_free(pma1);
502 isl_pw_multi_aff_free(pma2);
504 return equal;
507 /* The initial two partial solutions of "sol" are known to be at
508 * the same level.
509 * If they represent the same solution (on different parts of the domain),
510 * then combine them into a single solution at the current level.
511 * Otherwise, pop them both.
513 * Even if the two partial solution are not obviously the same,
514 * one may still be a simplification of the other over its own domain.
515 * Also check if the two sets of affine functions are equal when
516 * restricted to one of the domains. If so, combine the two
517 * using the set of affine functions on the other domain.
518 * That is, for two partial solutions (D1,M1) and (D2,M2),
519 * if M1 = M2 on D1, then the pair of partial solutions can
520 * be replaced by (D1+D2,M2) and similarly when M1 = M2 on D2.
522 static isl_stat combine_initial_if_equal(struct isl_sol *sol)
524 struct isl_partial_sol *partial;
525 isl_bool same;
527 partial = sol->partial;
529 same = same_solution(partial, partial->next);
530 if (same < 0)
531 return isl_stat_error;
532 if (same)
533 return combine_initial_into_second(sol);
534 if (partial->ma && partial->next->ma) {
535 same = equal_on_domain(partial->ma, partial->next->ma,
536 partial->dom);
537 if (same < 0)
538 return isl_stat_error;
539 if (same)
540 return combine_initial_into_second(sol);
541 same = equal_on_domain(partial->ma, partial->next->ma,
542 partial->next->dom);
543 if (same) {
544 swap_initial(sol);
545 return combine_initial_into_second(sol);
549 sol_pop_one(sol);
550 sol_pop_one(sol);
552 return isl_stat_ok;
555 /* Pop all solutions from the partial solution stack that were pushed onto
556 * the stack at levels that are deeper than the current level.
557 * If the two topmost elements on the stack have the same level
558 * and represent the same solution, then their domains are combined.
559 * This combined domain is the same as the current context domain
560 * as sol_pop is called each time we move back to a higher level.
561 * If the outer level (0) has been reached, then all partial solutions
562 * at the current level are also popped off.
564 static void sol_pop(struct isl_sol *sol)
566 struct isl_partial_sol *partial;
568 if (sol->error)
569 return;
571 partial = sol->partial;
572 if (!partial)
573 return;
575 if (partial->level == 0 && sol->level == 0) {
576 for (partial = sol->partial; partial; partial = sol->partial)
577 sol_pop_one(sol);
578 return;
581 if (partial->level <= sol->level)
582 return;
584 if (partial->next && partial->next->level == partial->level) {
585 if (combine_initial_if_equal(sol) < 0)
586 goto error;
587 } else
588 sol_pop_one(sol);
590 if (sol->level == 0) {
591 for (partial = sol->partial; partial; partial = sol->partial)
592 sol_pop_one(sol);
593 return;
596 if (0)
597 error: sol->error = 1;
600 static void sol_dec_level(struct isl_sol *sol)
602 if (sol->error)
603 return;
605 sol->level--;
607 sol_pop(sol);
610 static isl_stat sol_dec_level_wrap(struct isl_tab_callback *cb)
612 struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
614 sol_dec_level(callback->sol);
616 return callback->sol->error ? isl_stat_error : isl_stat_ok;
619 /* Move down to next level and push callback onto context tableau
620 * to decrease the level again when it gets rolled back across
621 * the current state. That is, dec_level will be called with
622 * the context tableau in the same state as it is when inc_level
623 * is called.
625 static void sol_inc_level(struct isl_sol *sol)
627 struct isl_tab *tab;
629 if (sol->error)
630 return;
632 sol->level++;
633 tab = sol->context->op->peek_tab(sol->context);
634 if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
635 sol->error = 1;
638 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
640 int i;
642 if (isl_int_is_one(m))
643 return;
645 for (i = 0; i < n_row; ++i)
646 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
649 /* Add the solution identified by the tableau and the context tableau.
651 * The layout of the variables is as follows.
652 * tab->n_var is equal to the total number of variables in the input
653 * map (including divs that were copied from the context)
654 * + the number of extra divs constructed
655 * Of these, the first tab->n_param and the last tab->n_div variables
656 * correspond to the variables in the context, i.e.,
657 * tab->n_param + tab->n_div = context_tab->n_var
658 * tab->n_param is equal to the number of parameters and input
659 * dimensions in the input map
660 * tab->n_div is equal to the number of divs in the context
662 * If there is no solution, then call add_empty with a basic set
663 * that corresponds to the context tableau. (If add_empty is NULL,
664 * then do nothing).
666 * If there is a solution, then first construct a matrix that maps
667 * all dimensions of the context to the output variables, i.e.,
668 * the output dimensions in the input map.
669 * The divs in the input map (if any) that do not correspond to any
670 * div in the context do not appear in the solution.
671 * The algorithm will make sure that they have an integer value,
672 * but these values themselves are of no interest.
673 * We have to be careful not to drop or rearrange any divs in the
674 * context because that would change the meaning of the matrix.
676 * To extract the value of the output variables, it should be noted
677 * that we always use a big parameter M in the main tableau and so
678 * the variable stored in this tableau is not an output variable x itself, but
679 * x' = M + x (in case of minimization)
680 * or
681 * x' = M - x (in case of maximization)
682 * If x' appears in a column, then its optimal value is zero,
683 * which means that the optimal value of x is an unbounded number
684 * (-M for minimization and M for maximization).
685 * We currently assume that the output dimensions in the original map
686 * are bounded, so this cannot occur.
687 * Similarly, when x' appears in a row, then the coefficient of M in that
688 * row is necessarily 1.
689 * If the row in the tableau represents
690 * d x' = c + d M + e(y)
691 * then, in case of minimization, the corresponding row in the matrix
692 * will be
693 * a c + a e(y)
694 * with a d = m, the (updated) common denominator of the matrix.
695 * In case of maximization, the row will be
696 * -a c - a e(y)
698 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
700 struct isl_basic_set *bset = NULL;
701 struct isl_mat *mat = NULL;
702 unsigned off;
703 int row;
704 isl_int m;
706 if (sol->error || !tab)
707 goto error;
709 if (tab->empty && !sol->add_empty)
710 return;
711 if (sol->context->op->is_empty(sol->context))
712 return;
714 bset = sol_domain(sol);
716 if (tab->empty) {
717 sol_push_sol(sol, bset, NULL);
718 return;
721 off = 2 + tab->M;
723 mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
724 1 + tab->n_param + tab->n_div);
725 if (!mat)
726 goto error;
728 isl_int_init(m);
730 isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
731 isl_int_set_si(mat->row[0][0], 1);
732 for (row = 0; row < sol->n_out; ++row) {
733 int i = tab->n_param + row;
734 int r, j;
736 isl_seq_clr(mat->row[1 + row], mat->n_col);
737 if (!tab->var[i].is_row) {
738 if (tab->M)
739 isl_die(mat->ctx, isl_error_invalid,
740 "unbounded optimum", goto error2);
741 continue;
744 r = tab->var[i].index;
745 if (tab->M &&
746 isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
747 isl_die(mat->ctx, isl_error_invalid,
748 "unbounded optimum", goto error2);
749 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
750 isl_int_divexact(m, tab->mat->row[r][0], m);
751 scale_rows(mat, m, 1 + row);
752 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
753 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
754 for (j = 0; j < tab->n_param; ++j) {
755 int col;
756 if (tab->var[j].is_row)
757 continue;
758 col = tab->var[j].index;
759 isl_int_mul(mat->row[1 + row][1 + j], m,
760 tab->mat->row[r][off + col]);
762 for (j = 0; j < tab->n_div; ++j) {
763 int col;
764 if (tab->var[tab->n_var - tab->n_div+j].is_row)
765 continue;
766 col = tab->var[tab->n_var - tab->n_div+j].index;
767 isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
768 tab->mat->row[r][off + col]);
770 if (sol->max)
771 isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
772 mat->n_col);
775 isl_int_clear(m);
777 sol_push_sol_mat(sol, bset, mat);
778 return;
779 error2:
780 isl_int_clear(m);
781 error:
782 isl_basic_set_free(bset);
783 isl_mat_free(mat);
784 sol->error = 1;
787 struct isl_sol_map {
788 struct isl_sol sol;
789 struct isl_map *map;
790 struct isl_set *empty;
793 static void sol_map_free(struct isl_sol *sol)
795 struct isl_sol_map *sol_map = (struct isl_sol_map *) sol;
796 isl_map_free(sol_map->map);
797 isl_set_free(sol_map->empty);
800 /* This function is called for parts of the context where there is
801 * no solution, with "bset" corresponding to the context tableau.
802 * Simply add the basic set to the set "empty".
804 static void sol_map_add_empty(struct isl_sol_map *sol,
805 struct isl_basic_set *bset)
807 if (!bset || !sol->empty)
808 goto error;
810 sol->empty = isl_set_grow(sol->empty, 1);
811 bset = isl_basic_set_simplify(bset);
812 bset = isl_basic_set_finalize(bset);
813 sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
814 if (!sol->empty)
815 goto error;
816 isl_basic_set_free(bset);
817 return;
818 error:
819 isl_basic_set_free(bset);
820 sol->sol.error = 1;
823 static void sol_map_add_empty_wrap(struct isl_sol *sol,
824 struct isl_basic_set *bset)
826 sol_map_add_empty((struct isl_sol_map *)sol, bset);
829 /* Given a basic set "dom" that represents the context and a tuple of
830 * affine expressions "ma" defined over this domain, construct a basic map
831 * that expresses this function on the domain.
833 static void sol_map_add(struct isl_sol_map *sol,
834 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
836 isl_basic_map *bmap;
838 if (sol->sol.error || !dom || !ma)
839 goto error;
841 bmap = isl_basic_map_from_multi_aff2(ma, sol->sol.rational);
842 bmap = isl_basic_map_intersect_domain(bmap, dom);
843 sol->map = isl_map_grow(sol->map, 1);
844 sol->map = isl_map_add_basic_map(sol->map, bmap);
845 if (!sol->map)
846 sol->sol.error = 1;
847 return;
848 error:
849 isl_basic_set_free(dom);
850 isl_multi_aff_free(ma);
851 sol->sol.error = 1;
854 static void sol_map_add_wrap(struct isl_sol *sol,
855 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
857 sol_map_add((struct isl_sol_map *)sol, dom, ma);
861 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
862 * i.e., the constant term and the coefficients of all variables that
863 * appear in the context tableau.
864 * Note that the coefficient of the big parameter M is NOT copied.
865 * The context tableau may not have a big parameter and even when it
866 * does, it is a different big parameter.
868 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
870 int i;
871 unsigned off = 2 + tab->M;
873 isl_int_set(line[0], tab->mat->row[row][1]);
874 for (i = 0; i < tab->n_param; ++i) {
875 if (tab->var[i].is_row)
876 isl_int_set_si(line[1 + i], 0);
877 else {
878 int col = tab->var[i].index;
879 isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
882 for (i = 0; i < tab->n_div; ++i) {
883 if (tab->var[tab->n_var - tab->n_div + i].is_row)
884 isl_int_set_si(line[1 + tab->n_param + i], 0);
885 else {
886 int col = tab->var[tab->n_var - tab->n_div + i].index;
887 isl_int_set(line[1 + tab->n_param + i],
888 tab->mat->row[row][off + col]);
893 /* Check if rows "row1" and "row2" have identical "parametric constants",
894 * as explained above.
895 * In this case, we also insist that the coefficients of the big parameter
896 * be the same as the values of the constants will only be the same
897 * if these coefficients are also the same.
899 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
901 int i;
902 unsigned off = 2 + tab->M;
904 if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
905 return 0;
907 if (tab->M && isl_int_ne(tab->mat->row[row1][2],
908 tab->mat->row[row2][2]))
909 return 0;
911 for (i = 0; i < tab->n_param + tab->n_div; ++i) {
912 int pos = i < tab->n_param ? i :
913 tab->n_var - tab->n_div + i - tab->n_param;
914 int col;
916 if (tab->var[pos].is_row)
917 continue;
918 col = tab->var[pos].index;
919 if (isl_int_ne(tab->mat->row[row1][off + col],
920 tab->mat->row[row2][off + col]))
921 return 0;
923 return 1;
926 /* Return an inequality that expresses that the "parametric constant"
927 * should be non-negative.
928 * This function is only called when the coefficient of the big parameter
929 * is equal to zero.
931 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
933 struct isl_vec *ineq;
935 ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
936 if (!ineq)
937 return NULL;
939 get_row_parameter_line(tab, row, ineq->el);
940 if (ineq)
941 ineq = isl_vec_normalize(ineq);
943 return ineq;
946 /* Normalize a div expression of the form
948 * [(g*f(x) + c)/(g * m)]
950 * with c the constant term and f(x) the remaining coefficients, to
952 * [(f(x) + [c/g])/m]
954 static void normalize_div(__isl_keep isl_vec *div)
956 isl_ctx *ctx = isl_vec_get_ctx(div);
957 int len = div->size - 2;
959 isl_seq_gcd(div->el + 2, len, &ctx->normalize_gcd);
960 isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, div->el[0]);
962 if (isl_int_is_one(ctx->normalize_gcd))
963 return;
965 isl_int_divexact(div->el[0], div->el[0], ctx->normalize_gcd);
966 isl_int_fdiv_q(div->el[1], div->el[1], ctx->normalize_gcd);
967 isl_seq_scale_down(div->el + 2, div->el + 2, ctx->normalize_gcd, len);
970 /* Return an integer division for use in a parametric cut based
971 * on the given row.
972 * In particular, let the parametric constant of the row be
974 * \sum_i a_i y_i
976 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
977 * The div returned is equal to
979 * floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
981 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
983 struct isl_vec *div;
985 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
986 if (!div)
987 return NULL;
989 isl_int_set(div->el[0], tab->mat->row[row][0]);
990 get_row_parameter_line(tab, row, div->el + 1);
991 isl_seq_neg(div->el + 1, div->el + 1, div->size - 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 /* Return an integer division for use in transferring an integrality constraint
999 * to the context.
1000 * In particular, let the parametric constant of the row be
1002 * \sum_i a_i y_i
1004 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
1005 * The the returned div is equal to
1007 * floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
1009 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
1011 struct isl_vec *div;
1013 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
1014 if (!div)
1015 return NULL;
1017 isl_int_set(div->el[0], tab->mat->row[row][0]);
1018 get_row_parameter_line(tab, row, div->el + 1);
1019 normalize_div(div);
1020 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
1022 return div;
1025 /* Construct and return an inequality that expresses an upper bound
1026 * on the given div.
1027 * In particular, if the div is given by
1029 * d = floor(e/m)
1031 * then the inequality expresses
1033 * m d <= e
1035 static __isl_give isl_vec *ineq_for_div(__isl_keep isl_basic_set *bset,
1036 unsigned div)
1038 isl_size total;
1039 unsigned div_pos;
1040 struct isl_vec *ineq;
1042 total = isl_basic_set_dim(bset, isl_dim_all);
1043 if (total < 0)
1044 return NULL;
1046 div_pos = 1 + total - bset->n_div + div;
1048 ineq = isl_vec_alloc(bset->ctx, 1 + total);
1049 if (!ineq)
1050 return NULL;
1052 isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
1053 isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
1054 return ineq;
1057 /* Given a row in the tableau and a div that was created
1058 * using get_row_split_div and that has been constrained to equality, i.e.,
1060 * d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
1062 * replace the expression "\sum_i {a_i} y_i" in the row by d,
1063 * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
1064 * The coefficients of the non-parameters in the tableau have been
1065 * verified to be integral. We can therefore simply replace coefficient b
1066 * by floor(b). For the coefficients of the parameters we have
1067 * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
1068 * floor(b) = b.
1070 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
1072 isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
1073 tab->mat->row[row][0], 1 + tab->M + tab->n_col);
1075 isl_int_set_si(tab->mat->row[row][0], 1);
1077 if (tab->var[tab->n_var - tab->n_div + div].is_row) {
1078 int drow = tab->var[tab->n_var - tab->n_div + div].index;
1080 isl_assert(tab->mat->ctx,
1081 isl_int_is_one(tab->mat->row[drow][0]), goto error);
1082 isl_seq_combine(tab->mat->row[row] + 1,
1083 tab->mat->ctx->one, tab->mat->row[row] + 1,
1084 tab->mat->ctx->one, tab->mat->row[drow] + 1,
1085 1 + tab->M + tab->n_col);
1086 } else {
1087 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
1089 isl_int_add_ui(tab->mat->row[row][2 + tab->M + dcol],
1090 tab->mat->row[row][2 + tab->M + dcol], 1);
1093 return tab;
1094 error:
1095 isl_tab_free(tab);
1096 return NULL;
1099 /* Check if the (parametric) constant of the given row is obviously
1100 * negative, meaning that we don't need to consult the context tableau.
1101 * If there is a big parameter and its coefficient is non-zero,
1102 * then this coefficient determines the outcome.
1103 * Otherwise, we check whether the constant is negative and
1104 * all non-zero coefficients of parameters are negative and
1105 * belong to non-negative parameters.
1107 static int is_obviously_neg(struct isl_tab *tab, int row)
1109 int i;
1110 int col;
1111 unsigned off = 2 + tab->M;
1113 if (tab->M) {
1114 if (isl_int_is_pos(tab->mat->row[row][2]))
1115 return 0;
1116 if (isl_int_is_neg(tab->mat->row[row][2]))
1117 return 1;
1120 if (isl_int_is_nonneg(tab->mat->row[row][1]))
1121 return 0;
1122 for (i = 0; i < tab->n_param; ++i) {
1123 /* Eliminated parameter */
1124 if (tab->var[i].is_row)
1125 continue;
1126 col = tab->var[i].index;
1127 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1128 continue;
1129 if (!tab->var[i].is_nonneg)
1130 return 0;
1131 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1132 return 0;
1134 for (i = 0; i < tab->n_div; ++i) {
1135 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1136 continue;
1137 col = tab->var[tab->n_var - tab->n_div + i].index;
1138 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1139 continue;
1140 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1141 return 0;
1142 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1143 return 0;
1145 return 1;
1148 /* Check if the (parametric) constant of the given row is obviously
1149 * non-negative, meaning that we don't need to consult the context tableau.
1150 * If there is a big parameter and its coefficient is non-zero,
1151 * then this coefficient determines the outcome.
1152 * Otherwise, we check whether the constant is non-negative and
1153 * all non-zero coefficients of parameters are positive and
1154 * belong to non-negative parameters.
1156 static int is_obviously_nonneg(struct isl_tab *tab, int row)
1158 int i;
1159 int col;
1160 unsigned off = 2 + tab->M;
1162 if (tab->M) {
1163 if (isl_int_is_pos(tab->mat->row[row][2]))
1164 return 1;
1165 if (isl_int_is_neg(tab->mat->row[row][2]))
1166 return 0;
1169 if (isl_int_is_neg(tab->mat->row[row][1]))
1170 return 0;
1171 for (i = 0; i < tab->n_param; ++i) {
1172 /* Eliminated parameter */
1173 if (tab->var[i].is_row)
1174 continue;
1175 col = tab->var[i].index;
1176 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1177 continue;
1178 if (!tab->var[i].is_nonneg)
1179 return 0;
1180 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1181 return 0;
1183 for (i = 0; i < tab->n_div; ++i) {
1184 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1185 continue;
1186 col = tab->var[tab->n_var - tab->n_div + i].index;
1187 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1188 continue;
1189 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1190 return 0;
1191 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1192 return 0;
1194 return 1;
1197 /* Given a row r and two columns, return the column that would
1198 * lead to the lexicographically smallest increment in the sample
1199 * solution when leaving the basis in favor of the row.
1200 * Pivoting with column c will increment the sample value by a non-negative
1201 * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
1202 * corresponding to the non-parametric variables.
1203 * If variable v appears in a column c_v, then a_{v,c} = 1 iff c = c_v,
1204 * with all other entries in this virtual row equal to zero.
1205 * If variable v appears in a row, then a_{v,c} is the element in column c
1206 * of that row.
1208 * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
1209 * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
1210 * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
1211 * increment. Otherwise, it's c2.
1213 static int lexmin_col_pair(struct isl_tab *tab,
1214 int row, int col1, int col2, isl_int tmp)
1216 int i;
1217 isl_int *tr;
1219 tr = tab->mat->row[row] + 2 + tab->M;
1221 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1222 int s1, s2;
1223 isl_int *r;
1225 if (!tab->var[i].is_row) {
1226 if (tab->var[i].index == col1)
1227 return col2;
1228 if (tab->var[i].index == col2)
1229 return col1;
1230 continue;
1233 if (tab->var[i].index == row)
1234 continue;
1236 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1237 s1 = isl_int_sgn(r[col1]);
1238 s2 = isl_int_sgn(r[col2]);
1239 if (s1 == 0 && s2 == 0)
1240 continue;
1241 if (s1 < s2)
1242 return col1;
1243 if (s2 < s1)
1244 return col2;
1246 isl_int_mul(tmp, r[col2], tr[col1]);
1247 isl_int_submul(tmp, r[col1], tr[col2]);
1248 if (isl_int_is_pos(tmp))
1249 return col1;
1250 if (isl_int_is_neg(tmp))
1251 return col2;
1253 return -1;
1256 /* Does the index into the tab->var or tab->con array "index"
1257 * correspond to a variable in the context tableau?
1258 * In particular, it needs to be an index into the tab->var array and
1259 * it needs to refer to either one of the first tab->n_param variables or
1260 * one of the last tab->n_div variables.
1262 static int is_parameter_var(struct isl_tab *tab, int index)
1264 if (index < 0)
1265 return 0;
1266 if (index < tab->n_param)
1267 return 1;
1268 if (index >= tab->n_var - tab->n_div)
1269 return 1;
1270 return 0;
1273 /* Does column "col" of "tab" refer to a variable in the context tableau?
1275 static int col_is_parameter_var(struct isl_tab *tab, int col)
1277 return is_parameter_var(tab, tab->col_var[col]);
1280 /* Does row "row" of "tab" refer to a variable in the context tableau?
1282 static int row_is_parameter_var(struct isl_tab *tab, int row)
1284 return is_parameter_var(tab, tab->row_var[row]);
1287 /* Given a row in the tableau, find and return the column that would
1288 * result in the lexicographically smallest, but positive, increment
1289 * in the sample point.
1290 * If there is no such column, then return tab->n_col.
1291 * If anything goes wrong, return -1.
1293 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1295 int j;
1296 int col = tab->n_col;
1297 isl_int *tr;
1298 isl_int tmp;
1300 tr = tab->mat->row[row] + 2 + tab->M;
1302 isl_int_init(tmp);
1304 for (j = tab->n_dead; j < tab->n_col; ++j) {
1305 if (col_is_parameter_var(tab, j))
1306 continue;
1308 if (!isl_int_is_pos(tr[j]))
1309 continue;
1311 if (col == tab->n_col)
1312 col = j;
1313 else
1314 col = lexmin_col_pair(tab, row, col, j, tmp);
1315 isl_assert(tab->mat->ctx, col >= 0, goto error);
1318 isl_int_clear(tmp);
1319 return col;
1320 error:
1321 isl_int_clear(tmp);
1322 return -1;
1325 /* Return the first known violated constraint, i.e., a non-negative
1326 * constraint that currently has an either obviously negative value
1327 * or a previously determined to be negative value.
1329 * If any constraint has a negative coefficient for the big parameter,
1330 * if any, then we return one of these first.
1332 static int first_neg(struct isl_tab *tab)
1334 int row;
1336 if (tab->M)
1337 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1338 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1339 continue;
1340 if (!isl_int_is_neg(tab->mat->row[row][2]))
1341 continue;
1342 if (tab->row_sign)
1343 tab->row_sign[row] = isl_tab_row_neg;
1344 return row;
1346 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1347 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1348 continue;
1349 if (tab->row_sign) {
1350 if (tab->row_sign[row] == 0 &&
1351 is_obviously_neg(tab, row))
1352 tab->row_sign[row] = isl_tab_row_neg;
1353 if (tab->row_sign[row] != isl_tab_row_neg)
1354 continue;
1355 } else if (!is_obviously_neg(tab, row))
1356 continue;
1357 return row;
1359 return -1;
1362 /* Check whether the invariant that all columns are lexico-positive
1363 * is satisfied. This function is not called from the current code
1364 * but is useful during debugging.
1366 static void check_lexpos(struct isl_tab *tab) __attribute__ ((unused));
1367 static void check_lexpos(struct isl_tab *tab)
1369 unsigned off = 2 + tab->M;
1370 int col;
1371 int var;
1372 int row;
1374 for (col = tab->n_dead; col < tab->n_col; ++col) {
1375 if (col_is_parameter_var(tab, col))
1376 continue;
1377 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1378 if (!tab->var[var].is_row) {
1379 if (tab->var[var].index == col)
1380 break;
1381 else
1382 continue;
1384 row = tab->var[var].index;
1385 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1386 continue;
1387 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1388 break;
1389 fprintf(stderr, "lexneg column %d (row %d)\n",
1390 col, row);
1392 if (var >= tab->n_var - tab->n_div)
1393 fprintf(stderr, "zero column %d\n", col);
1397 /* Report to the caller that the given constraint is part of an encountered
1398 * conflict.
1400 static int report_conflicting_constraint(struct isl_tab *tab, int con)
1402 return tab->conflict(con, tab->conflict_user);
1405 /* Given a conflicting row in the tableau, report all constraints
1406 * involved in the row to the caller. That is, the row itself
1407 * (if it represents a constraint) and all constraint columns with
1408 * non-zero (and therefore negative) coefficients.
1410 static int report_conflict(struct isl_tab *tab, int row)
1412 int j;
1413 isl_int *tr;
1415 if (!tab->conflict)
1416 return 0;
1418 if (tab->row_var[row] < 0 &&
1419 report_conflicting_constraint(tab, ~tab->row_var[row]) < 0)
1420 return -1;
1422 tr = tab->mat->row[row] + 2 + tab->M;
1424 for (j = tab->n_dead; j < tab->n_col; ++j) {
1425 if (col_is_parameter_var(tab, j))
1426 continue;
1428 if (!isl_int_is_neg(tr[j]))
1429 continue;
1431 if (tab->col_var[j] < 0 &&
1432 report_conflicting_constraint(tab, ~tab->col_var[j]) < 0)
1433 return -1;
1436 return 0;
1439 /* Resolve all known or obviously violated constraints through pivoting.
1440 * In particular, as long as we can find any violated constraint, we
1441 * look for a pivoting column that would result in the lexicographically
1442 * smallest increment in the sample point. If there is no such column
1443 * then the tableau is infeasible.
1445 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1446 static int restore_lexmin(struct isl_tab *tab)
1448 int row, col;
1450 if (!tab)
1451 return -1;
1452 if (tab->empty)
1453 return 0;
1454 while ((row = first_neg(tab)) != -1) {
1455 col = lexmin_pivot_col(tab, row);
1456 if (col >= tab->n_col) {
1457 if (report_conflict(tab, row) < 0)
1458 return -1;
1459 if (isl_tab_mark_empty(tab) < 0)
1460 return -1;
1461 return 0;
1463 if (col < 0)
1464 return -1;
1465 if (isl_tab_pivot(tab, row, col) < 0)
1466 return -1;
1468 return 0;
1471 /* Given a row that represents an equality, look for an appropriate
1472 * pivoting column.
1473 * In particular, if there are any non-zero coefficients among
1474 * the non-parameter variables, then we take the last of these
1475 * variables. Eliminating this variable in terms of the other
1476 * variables and/or parameters does not influence the property
1477 * that all column in the initial tableau are lexicographically
1478 * positive. The row corresponding to the eliminated variable
1479 * will only have non-zero entries below the diagonal of the
1480 * initial tableau. That is, we transform
1482 * I I
1483 * 1 into a
1484 * I I
1486 * If there is no such non-parameter variable, then we are dealing with
1487 * pure parameter equality and we pick any parameter with coefficient 1 or -1
1488 * for elimination. This will ensure that the eliminated parameter
1489 * always has an integer value whenever all the other parameters are integral.
1490 * If there is no such parameter then we return -1.
1492 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1494 unsigned off = 2 + tab->M;
1495 int i;
1497 for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1498 int col;
1499 if (tab->var[i].is_row)
1500 continue;
1501 col = tab->var[i].index;
1502 if (col <= tab->n_dead)
1503 continue;
1504 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1505 return col;
1507 for (i = tab->n_dead; i < tab->n_col; ++i) {
1508 if (isl_int_is_one(tab->mat->row[row][off + i]))
1509 return i;
1510 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1511 return i;
1513 return -1;
1516 /* Add an equality that is known to be valid to the tableau.
1517 * We first check if we can eliminate a variable or a parameter.
1518 * If not, we add the equality as two inequalities.
1519 * In this case, the equality was a pure parameter equality and there
1520 * is no need to resolve any constraint violations.
1522 * This function assumes that at least two more rows and at least
1523 * two more elements in the constraint array are available in the tableau.
1525 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1527 int i;
1528 int r;
1530 if (!tab)
1531 return NULL;
1532 r = isl_tab_add_row(tab, eq);
1533 if (r < 0)
1534 goto error;
1536 r = tab->con[r].index;
1537 i = last_var_col_or_int_par_col(tab, r);
1538 if (i < 0) {
1539 tab->con[r].is_nonneg = 1;
1540 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1541 goto error;
1542 isl_seq_neg(eq, eq, 1 + tab->n_var);
1543 r = isl_tab_add_row(tab, eq);
1544 if (r < 0)
1545 goto error;
1546 tab->con[r].is_nonneg = 1;
1547 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1548 goto error;
1549 } else {
1550 if (isl_tab_pivot(tab, r, i) < 0)
1551 goto error;
1552 if (isl_tab_kill_col(tab, i) < 0)
1553 goto error;
1554 tab->n_eq++;
1557 return tab;
1558 error:
1559 isl_tab_free(tab);
1560 return NULL;
1563 /* Check if the given row is a pure constant.
1565 static int is_constant(struct isl_tab *tab, int row)
1567 unsigned off = 2 + tab->M;
1569 return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1570 tab->n_col - tab->n_dead) == -1;
1573 /* Is the given row a parametric constant?
1574 * That is, does it only involve variables that also appear in the context?
1576 static int is_parametric_constant(struct isl_tab *tab, int row)
1578 unsigned off = 2 + tab->M;
1579 int col;
1581 for (col = tab->n_dead; col < tab->n_col; ++col) {
1582 if (col_is_parameter_var(tab, col))
1583 continue;
1584 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1585 continue;
1586 return 0;
1589 return 1;
1592 /* Add an equality that may or may not be valid to the tableau.
1593 * If the resulting row is a pure constant, then it must be zero.
1594 * Otherwise, the resulting tableau is empty.
1596 * If the row is not a pure constant, then we add two inequalities,
1597 * each time checking that they can be satisfied.
1598 * In the end we try to use one of the two constraints to eliminate
1599 * a column.
1601 * This function assumes that at least two more rows and at least
1602 * two more elements in the constraint array are available in the tableau.
1604 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1605 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1607 int r1, r2;
1608 int row;
1609 struct isl_tab_undo *snap;
1611 if (!tab)
1612 return -1;
1613 snap = isl_tab_snap(tab);
1614 r1 = isl_tab_add_row(tab, eq);
1615 if (r1 < 0)
1616 return -1;
1617 tab->con[r1].is_nonneg = 1;
1618 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1619 return -1;
1621 row = tab->con[r1].index;
1622 if (is_constant(tab, row)) {
1623 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1624 (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1625 if (isl_tab_mark_empty(tab) < 0)
1626 return -1;
1627 return 0;
1629 if (isl_tab_rollback(tab, snap) < 0)
1630 return -1;
1631 return 0;
1634 if (restore_lexmin(tab) < 0)
1635 return -1;
1636 if (tab->empty)
1637 return 0;
1639 isl_seq_neg(eq, eq, 1 + tab->n_var);
1641 r2 = isl_tab_add_row(tab, eq);
1642 if (r2 < 0)
1643 return -1;
1644 tab->con[r2].is_nonneg = 1;
1645 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1646 return -1;
1648 if (restore_lexmin(tab) < 0)
1649 return -1;
1650 if (tab->empty)
1651 return 0;
1653 if (!tab->con[r1].is_row) {
1654 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1655 return -1;
1656 } else if (!tab->con[r2].is_row) {
1657 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1658 return -1;
1661 if (tab->bmap) {
1662 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1663 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1664 return -1;
1665 isl_seq_neg(eq, eq, 1 + tab->n_var);
1666 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1667 isl_seq_neg(eq, eq, 1 + tab->n_var);
1668 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1669 return -1;
1670 if (!tab->bmap)
1671 return -1;
1674 return 0;
1677 /* Add an inequality to the tableau, resolving violations using
1678 * restore_lexmin.
1680 * This function assumes that at least one more row and at least
1681 * one more element in the constraint array are available in the tableau.
1683 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1685 int r;
1687 if (!tab)
1688 return NULL;
1689 if (tab->bmap) {
1690 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1691 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1692 goto error;
1693 if (!tab->bmap)
1694 goto error;
1696 r = isl_tab_add_row(tab, ineq);
1697 if (r < 0)
1698 goto error;
1699 tab->con[r].is_nonneg = 1;
1700 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1701 goto error;
1702 if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1703 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1704 goto error;
1705 return tab;
1708 if (restore_lexmin(tab) < 0)
1709 goto error;
1710 if (!tab->empty && tab->con[r].is_row &&
1711 isl_tab_row_is_redundant(tab, tab->con[r].index))
1712 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1713 goto error;
1714 return tab;
1715 error:
1716 isl_tab_free(tab);
1717 return NULL;
1720 /* Check if the coefficients of the parameters are all integral.
1722 static int integer_parameter(struct isl_tab *tab, int row)
1724 int i;
1725 int col;
1726 unsigned off = 2 + tab->M;
1728 for (i = 0; i < tab->n_param; ++i) {
1729 /* Eliminated parameter */
1730 if (tab->var[i].is_row)
1731 continue;
1732 col = tab->var[i].index;
1733 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1734 tab->mat->row[row][0]))
1735 return 0;
1737 for (i = 0; i < tab->n_div; ++i) {
1738 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1739 continue;
1740 col = tab->var[tab->n_var - tab->n_div + i].index;
1741 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1742 tab->mat->row[row][0]))
1743 return 0;
1745 return 1;
1748 /* Check if the coefficients of the non-parameter variables are all integral.
1750 static int integer_variable(struct isl_tab *tab, int row)
1752 int i;
1753 unsigned off = 2 + tab->M;
1755 for (i = tab->n_dead; i < tab->n_col; ++i) {
1756 if (col_is_parameter_var(tab, i))
1757 continue;
1758 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1759 tab->mat->row[row][0]))
1760 return 0;
1762 return 1;
1765 /* Check if the constant term is integral.
1767 static int integer_constant(struct isl_tab *tab, int row)
1769 return isl_int_is_divisible_by(tab->mat->row[row][1],
1770 tab->mat->row[row][0]);
1773 #define I_CST 1 << 0
1774 #define I_PAR 1 << 1
1775 #define I_VAR 1 << 2
1777 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1778 * that is non-integer and therefore requires a cut and return
1779 * the index of the variable.
1780 * For parametric tableaus, there are three parts in a row,
1781 * the constant, the coefficients of the parameters and the rest.
1782 * For each part, we check whether the coefficients in that part
1783 * are all integral and if so, set the corresponding flag in *f.
1784 * If the constant and the parameter part are integral, then the
1785 * current sample value is integral and no cut is required
1786 * (irrespective of whether the variable part is integral).
1788 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1790 var = var < 0 ? tab->n_param : var + 1;
1792 for (; var < tab->n_var - tab->n_div; ++var) {
1793 int flags = 0;
1794 int row;
1795 if (!tab->var[var].is_row)
1796 continue;
1797 row = tab->var[var].index;
1798 if (integer_constant(tab, row))
1799 ISL_FL_SET(flags, I_CST);
1800 if (integer_parameter(tab, row))
1801 ISL_FL_SET(flags, I_PAR);
1802 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1803 continue;
1804 if (integer_variable(tab, row))
1805 ISL_FL_SET(flags, I_VAR);
1806 *f = flags;
1807 return var;
1809 return -1;
1812 /* Check for first (non-parameter) variable that is non-integer and
1813 * therefore requires a cut and return the corresponding row.
1814 * For parametric tableaus, there are three parts in a row,
1815 * the constant, the coefficients of the parameters and the rest.
1816 * For each part, we check whether the coefficients in that part
1817 * are all integral and if so, set the corresponding flag in *f.
1818 * If the constant and the parameter part are integral, then the
1819 * current sample value is integral and no cut is required
1820 * (irrespective of whether the variable part is integral).
1822 static int first_non_integer_row(struct isl_tab *tab, int *f)
1824 int var = next_non_integer_var(tab, -1, f);
1826 return var < 0 ? -1 : tab->var[var].index;
1829 /* Add a (non-parametric) cut to cut away the non-integral sample
1830 * value of the given row.
1832 * If the row is given by
1834 * m r = f + \sum_i a_i y_i
1836 * then the cut is
1838 * c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1840 * The big parameter, if any, is ignored, since it is assumed to be big
1841 * enough to be divisible by any integer.
1842 * If the tableau is actually a parametric tableau, then this function
1843 * is only called when all coefficients of the parameters are integral.
1844 * The cut therefore has zero coefficients for the parameters.
1846 * The current value is known to be negative, so row_sign, if it
1847 * exists, is set accordingly.
1849 * Return the row of the cut or -1.
1851 static int add_cut(struct isl_tab *tab, int row)
1853 int i;
1854 int r;
1855 isl_int *r_row;
1856 unsigned off = 2 + tab->M;
1858 if (isl_tab_extend_cons(tab, 1) < 0)
1859 return -1;
1860 r = isl_tab_allocate_con(tab);
1861 if (r < 0)
1862 return -1;
1864 r_row = tab->mat->row[tab->con[r].index];
1865 isl_int_set(r_row[0], tab->mat->row[row][0]);
1866 isl_int_neg(r_row[1], tab->mat->row[row][1]);
1867 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1868 isl_int_neg(r_row[1], r_row[1]);
1869 if (tab->M)
1870 isl_int_set_si(r_row[2], 0);
1871 for (i = 0; i < tab->n_col; ++i)
1872 isl_int_fdiv_r(r_row[off + i],
1873 tab->mat->row[row][off + i], tab->mat->row[row][0]);
1875 tab->con[r].is_nonneg = 1;
1876 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1877 return -1;
1878 if (tab->row_sign)
1879 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1881 return tab->con[r].index;
1884 #define CUT_ALL 1
1885 #define CUT_ONE 0
1887 /* Given a non-parametric tableau, add cuts until an integer
1888 * sample point is obtained or until the tableau is determined
1889 * to be integer infeasible.
1890 * As long as there is any non-integer value in the sample point,
1891 * we add appropriate cuts, if possible, for each of these
1892 * non-integer values and then resolve the violated
1893 * cut constraints using restore_lexmin.
1894 * If one of the corresponding rows is equal to an integral
1895 * combination of variables/constraints plus a non-integral constant,
1896 * then there is no way to obtain an integer point and we return
1897 * a tableau that is marked empty.
1898 * The parameter cutting_strategy controls the strategy used when adding cuts
1899 * to remove non-integer points. CUT_ALL adds all possible cuts
1900 * before continuing the search. CUT_ONE adds only one cut at a time.
1902 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab,
1903 int cutting_strategy)
1905 int var;
1906 int row;
1907 int flags;
1909 if (!tab)
1910 return NULL;
1911 if (tab->empty)
1912 return tab;
1914 while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1915 do {
1916 if (ISL_FL_ISSET(flags, I_VAR)) {
1917 if (isl_tab_mark_empty(tab) < 0)
1918 goto error;
1919 return tab;
1921 row = tab->var[var].index;
1922 row = add_cut(tab, row);
1923 if (row < 0)
1924 goto error;
1925 if (cutting_strategy == CUT_ONE)
1926 break;
1927 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1928 if (restore_lexmin(tab) < 0)
1929 goto error;
1930 if (tab->empty)
1931 break;
1933 return tab;
1934 error:
1935 isl_tab_free(tab);
1936 return NULL;
1939 /* Check whether all the currently active samples also satisfy the inequality
1940 * "ineq" (treated as an equality if eq is set).
1941 * Remove those samples that do not.
1943 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1945 int i;
1946 isl_int v;
1948 if (!tab)
1949 return NULL;
1951 isl_assert(tab->mat->ctx, tab->bmap, goto error);
1952 isl_assert(tab->mat->ctx, tab->samples, goto error);
1953 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1955 isl_int_init(v);
1956 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1957 int sgn;
1958 isl_seq_inner_product(ineq, tab->samples->row[i],
1959 1 + tab->n_var, &v);
1960 sgn = isl_int_sgn(v);
1961 if (eq ? (sgn == 0) : (sgn >= 0))
1962 continue;
1963 tab = isl_tab_drop_sample(tab, i);
1964 if (!tab)
1965 break;
1967 isl_int_clear(v);
1969 return tab;
1970 error:
1971 isl_tab_free(tab);
1972 return NULL;
1975 /* Check whether the sample value of the tableau is finite,
1976 * i.e., either the tableau does not use a big parameter, or
1977 * all values of the variables are equal to the big parameter plus
1978 * some constant. This constant is the actual sample value.
1980 static int sample_is_finite(struct isl_tab *tab)
1982 int i;
1984 if (!tab->M)
1985 return 1;
1987 for (i = 0; i < tab->n_var; ++i) {
1988 int row;
1989 if (!tab->var[i].is_row)
1990 return 0;
1991 row = tab->var[i].index;
1992 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1993 return 0;
1995 return 1;
1998 /* Check if the context tableau of sol has any integer points.
1999 * Leave tab in empty state if no integer point can be found.
2000 * If an integer point can be found and if moreover it is finite,
2001 * then it is added to the list of sample values.
2003 * This function is only called when none of the currently active sample
2004 * values satisfies the most recently added constraint.
2006 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
2008 struct isl_tab_undo *snap;
2010 if (!tab)
2011 return NULL;
2013 snap = isl_tab_snap(tab);
2014 if (isl_tab_push_basis(tab) < 0)
2015 goto error;
2017 tab = cut_to_integer_lexmin(tab, CUT_ALL);
2018 if (!tab)
2019 goto error;
2021 if (!tab->empty && sample_is_finite(tab)) {
2022 struct isl_vec *sample;
2024 sample = isl_tab_get_sample_value(tab);
2026 if (isl_tab_add_sample(tab, sample) < 0)
2027 goto error;
2030 if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
2031 goto error;
2033 return tab;
2034 error:
2035 isl_tab_free(tab);
2036 return NULL;
2039 /* Check if any of the currently active sample values satisfies
2040 * the inequality "ineq" (an equality if eq is set).
2042 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
2044 int i;
2045 isl_int v;
2047 if (!tab)
2048 return -1;
2050 isl_assert(tab->mat->ctx, tab->bmap, return -1);
2051 isl_assert(tab->mat->ctx, tab->samples, return -1);
2052 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
2054 isl_int_init(v);
2055 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2056 int sgn;
2057 isl_seq_inner_product(ineq, tab->samples->row[i],
2058 1 + tab->n_var, &v);
2059 sgn = isl_int_sgn(v);
2060 if (eq ? (sgn == 0) : (sgn >= 0))
2061 break;
2063 isl_int_clear(v);
2065 return i < tab->n_sample;
2068 /* Insert a div specified by "div" to the tableau "tab" at position "pos" and
2069 * return isl_bool_true if the div is obviously non-negative.
2071 static isl_bool context_tab_insert_div(struct isl_tab *tab, int pos,
2072 __isl_keep isl_vec *div,
2073 isl_stat (*add_ineq)(void *user, isl_int *), void *user)
2075 int i;
2076 int r;
2077 struct isl_mat *samples;
2078 int nonneg;
2080 r = isl_tab_insert_div(tab, pos, div, add_ineq, user);
2081 if (r < 0)
2082 return isl_bool_error;
2083 nonneg = tab->var[r].is_nonneg;
2084 tab->var[r].frozen = 1;
2086 samples = isl_mat_extend(tab->samples,
2087 tab->n_sample, 1 + tab->n_var);
2088 tab->samples = samples;
2089 if (!samples)
2090 return isl_bool_error;
2091 for (i = tab->n_outside; i < samples->n_row; ++i) {
2092 isl_seq_inner_product(div->el + 1, samples->row[i],
2093 div->size - 1, &samples->row[i][samples->n_col - 1]);
2094 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
2095 samples->row[i][samples->n_col - 1], div->el[0]);
2097 tab->samples = isl_mat_move_cols(tab->samples, 1 + pos,
2098 1 + tab->n_var - 1, 1);
2099 if (!tab->samples)
2100 return isl_bool_error;
2102 return isl_bool_ok(nonneg);
2105 /* Add a div specified by "div" to both the main tableau and
2106 * the context tableau. In case of the main tableau, we only
2107 * need to add an extra div. In the context tableau, we also
2108 * need to express the meaning of the div.
2109 * Return the index of the div or -1 if anything went wrong.
2111 * The new integer division is added before any unknown integer
2112 * divisions in the context to ensure that it does not get
2113 * equated to some linear combination involving unknown integer
2114 * divisions.
2116 static int add_div(struct isl_tab *tab, struct isl_context *context,
2117 __isl_keep isl_vec *div)
2119 int r;
2120 int pos;
2121 isl_bool nonneg;
2122 struct isl_tab *context_tab = context->op->peek_tab(context);
2124 if (!tab || !context_tab)
2125 goto error;
2127 pos = context_tab->n_var - context->n_unknown;
2128 if ((nonneg = context->op->insert_div(context, pos, div)) < 0)
2129 goto error;
2131 if (!context->op->is_ok(context))
2132 goto error;
2134 pos = tab->n_var - context->n_unknown;
2135 if (isl_tab_extend_vars(tab, 1) < 0)
2136 goto error;
2137 r = isl_tab_insert_var(tab, pos);
2138 if (r < 0)
2139 goto error;
2140 if (nonneg)
2141 tab->var[r].is_nonneg = 1;
2142 tab->var[r].frozen = 1;
2143 tab->n_div++;
2145 return tab->n_div - 1 - context->n_unknown;
2146 error:
2147 context->op->invalidate(context);
2148 return -1;
2151 /* Return the position of the integer division that is equal to div/denom
2152 * if there is one. Otherwise, return a position beyond the integer divisions.
2154 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
2156 int i;
2157 isl_size total = isl_basic_map_dim(tab->bmap, isl_dim_all);
2158 isl_size n_div;
2160 n_div = isl_basic_map_dim(tab->bmap, isl_dim_div);
2161 if (total < 0 || n_div < 0)
2162 return -1;
2163 for (i = 0; i < n_div; ++i) {
2164 if (isl_int_ne(tab->bmap->div[i][0], denom))
2165 continue;
2166 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
2167 continue;
2168 return i;
2170 return n_div;
2173 /* Return the index of a div that corresponds to "div".
2174 * We first check if we already have such a div and if not, we create one.
2176 static int get_div(struct isl_tab *tab, struct isl_context *context,
2177 struct isl_vec *div)
2179 int d;
2180 struct isl_tab *context_tab = context->op->peek_tab(context);
2181 unsigned n_div;
2183 if (!context_tab)
2184 return -1;
2186 n_div = isl_basic_map_dim(context_tab->bmap, isl_dim_div);
2187 d = find_div(context_tab, div->el + 1, div->el[0]);
2188 if (d < 0)
2189 return -1;
2190 if (d < n_div)
2191 return d;
2193 return add_div(tab, context, div);
2196 /* Add a parametric cut to cut away the non-integral sample value
2197 * of the given row.
2198 * Let a_i be the coefficients of the constant term and the parameters
2199 * and let b_i be the coefficients of the variables or constraints
2200 * in basis of the tableau.
2201 * Let q be the div q = floor(\sum_i {-a_i} y_i).
2203 * The cut is expressed as
2205 * c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
2207 * If q did not already exist in the context tableau, then it is added first.
2208 * If q is in a column of the main tableau then the "+ q" can be accomplished
2209 * by setting the corresponding entry to the denominator of the constraint.
2210 * If q happens to be in a row of the main tableau, then the corresponding
2211 * row needs to be added instead (taking care of the denominators).
2212 * Note that this is very unlikely, but perhaps not entirely impossible.
2214 * The current value of the cut is known to be negative (or at least
2215 * non-positive), so row_sign is set accordingly.
2217 * Return the row of the cut or -1.
2219 static int add_parametric_cut(struct isl_tab *tab, int row,
2220 struct isl_context *context)
2222 struct isl_vec *div;
2223 int d;
2224 int i;
2225 int r;
2226 isl_int *r_row;
2227 int col;
2228 int n;
2229 unsigned off = 2 + tab->M;
2231 if (!context)
2232 return -1;
2234 div = get_row_parameter_div(tab, row);
2235 if (!div)
2236 return -1;
2238 n = tab->n_div - context->n_unknown;
2239 d = context->op->get_div(context, tab, div);
2240 isl_vec_free(div);
2241 if (d < 0)
2242 return -1;
2244 if (isl_tab_extend_cons(tab, 1) < 0)
2245 return -1;
2246 r = isl_tab_allocate_con(tab);
2247 if (r < 0)
2248 return -1;
2250 r_row = tab->mat->row[tab->con[r].index];
2251 isl_int_set(r_row[0], tab->mat->row[row][0]);
2252 isl_int_neg(r_row[1], tab->mat->row[row][1]);
2253 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
2254 isl_int_neg(r_row[1], r_row[1]);
2255 if (tab->M)
2256 isl_int_set_si(r_row[2], 0);
2257 for (i = 0; i < tab->n_param; ++i) {
2258 if (tab->var[i].is_row)
2259 continue;
2260 col = tab->var[i].index;
2261 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2262 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2263 tab->mat->row[row][0]);
2264 isl_int_neg(r_row[off + col], r_row[off + col]);
2266 for (i = 0; i < tab->n_div; ++i) {
2267 if (tab->var[tab->n_var - tab->n_div + i].is_row)
2268 continue;
2269 col = tab->var[tab->n_var - tab->n_div + i].index;
2270 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2271 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2272 tab->mat->row[row][0]);
2273 isl_int_neg(r_row[off + col], r_row[off + col]);
2275 for (i = 0; i < tab->n_col; ++i) {
2276 if (tab->col_var[i] >= 0 &&
2277 (tab->col_var[i] < tab->n_param ||
2278 tab->col_var[i] >= tab->n_var - tab->n_div))
2279 continue;
2280 isl_int_fdiv_r(r_row[off + i],
2281 tab->mat->row[row][off + i], tab->mat->row[row][0]);
2283 if (tab->var[tab->n_var - tab->n_div + d].is_row) {
2284 isl_int gcd;
2285 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
2286 isl_int_init(gcd);
2287 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
2288 isl_int_divexact(r_row[0], r_row[0], gcd);
2289 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
2290 isl_seq_combine(r_row + 1, gcd, r_row + 1,
2291 r_row[0], tab->mat->row[d_row] + 1,
2292 off - 1 + tab->n_col);
2293 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
2294 isl_int_clear(gcd);
2295 } else {
2296 col = tab->var[tab->n_var - tab->n_div + d].index;
2297 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
2300 tab->con[r].is_nonneg = 1;
2301 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
2302 return -1;
2303 if (tab->row_sign)
2304 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
2306 row = tab->con[r].index;
2308 if (d >= n && context->op->detect_equalities(context, tab) < 0)
2309 return -1;
2311 return row;
2314 /* Construct a tableau for bmap that can be used for computing
2315 * the lexicographic minimum (or maximum) of bmap.
2316 * If not NULL, then dom is the domain where the minimum
2317 * should be computed. In this case, we set up a parametric
2318 * tableau with row signs (initialized to "unknown").
2319 * If M is set, then the tableau will use a big parameter.
2320 * If max is set, then a maximum should be computed instead of a minimum.
2321 * This means that for each variable x, the tableau will contain the variable
2322 * x' = M - x, rather than x' = M + x. This in turn means that the coefficient
2323 * of the variables in all constraints are negated prior to adding them
2324 * to the tableau.
2326 static __isl_give struct isl_tab *tab_for_lexmin(__isl_keep isl_basic_map *bmap,
2327 __isl_keep isl_basic_set *dom, unsigned M, int max)
2329 int i;
2330 struct isl_tab *tab;
2331 unsigned n_var;
2332 unsigned o_var;
2333 isl_size total;
2335 total = isl_basic_map_dim(bmap, isl_dim_all);
2336 if (total < 0)
2337 return NULL;
2338 tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
2339 total, M);
2340 if (!tab)
2341 return NULL;
2343 tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
2344 if (dom) {
2345 isl_size dom_total;
2346 dom_total = isl_basic_set_dim(dom, isl_dim_all);
2347 if (dom_total < 0)
2348 goto error;
2349 tab->n_param = dom_total - dom->n_div;
2350 tab->n_div = dom->n_div;
2351 tab->row_sign = isl_calloc_array(bmap->ctx,
2352 enum isl_tab_row_sign, tab->mat->n_row);
2353 if (tab->mat->n_row && !tab->row_sign)
2354 goto error;
2356 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
2357 if (isl_tab_mark_empty(tab) < 0)
2358 goto error;
2359 return tab;
2362 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2363 tab->var[i].is_nonneg = 1;
2364 tab->var[i].frozen = 1;
2366 o_var = 1 + tab->n_param;
2367 n_var = tab->n_var - tab->n_param - tab->n_div;
2368 for (i = 0; i < bmap->n_eq; ++i) {
2369 if (max)
2370 isl_seq_neg(bmap->eq[i] + o_var,
2371 bmap->eq[i] + o_var, n_var);
2372 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2373 if (max)
2374 isl_seq_neg(bmap->eq[i] + o_var,
2375 bmap->eq[i] + o_var, n_var);
2376 if (!tab || tab->empty)
2377 return tab;
2379 if (bmap->n_eq && restore_lexmin(tab) < 0)
2380 goto error;
2381 for (i = 0; i < bmap->n_ineq; ++i) {
2382 if (max)
2383 isl_seq_neg(bmap->ineq[i] + o_var,
2384 bmap->ineq[i] + o_var, n_var);
2385 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2386 if (max)
2387 isl_seq_neg(bmap->ineq[i] + o_var,
2388 bmap->ineq[i] + o_var, n_var);
2389 if (!tab || tab->empty)
2390 return tab;
2392 return tab;
2393 error:
2394 isl_tab_free(tab);
2395 return NULL;
2398 /* Given a main tableau where more than one row requires a split,
2399 * determine and return the "best" row to split on.
2401 * If any of the rows requiring a split only involves
2402 * variables that also appear in the context tableau,
2403 * then the negative part is guaranteed not to have a solution.
2404 * It is therefore best to split on any of these rows first.
2406 * Otherwise,
2407 * given two rows in the main tableau, if the inequality corresponding
2408 * to the first row is redundant with respect to that of the second row
2409 * in the current tableau, then it is better to split on the second row,
2410 * since in the positive part, both rows will be positive.
2411 * (In the negative part a pivot will have to be performed and just about
2412 * anything can happen to the sign of the other row.)
2414 * As a simple heuristic, we therefore select the row that makes the most
2415 * of the other rows redundant.
2417 * Perhaps it would also be useful to look at the number of constraints
2418 * that conflict with any given constraint.
2420 * best is the best row so far (-1 when we have not found any row yet).
2421 * best_r is the number of other rows made redundant by row best.
2422 * When best is still -1, bset_r is meaningless, but it is initialized
2423 * to some arbitrary value (0) anyway. Without this redundant initialization
2424 * valgrind may warn about uninitialized memory accesses when isl
2425 * is compiled with some versions of gcc.
2427 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2429 struct isl_tab_undo *snap;
2430 int split;
2431 int row;
2432 int best = -1;
2433 int best_r = 0;
2435 if (isl_tab_extend_cons(context_tab, 2) < 0)
2436 return -1;
2438 snap = isl_tab_snap(context_tab);
2440 for (split = tab->n_redundant; split < tab->n_row; ++split) {
2441 struct isl_tab_undo *snap2;
2442 struct isl_vec *ineq = NULL;
2443 int r = 0;
2444 int ok;
2446 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2447 continue;
2448 if (tab->row_sign[split] != isl_tab_row_any)
2449 continue;
2451 if (is_parametric_constant(tab, split))
2452 return split;
2454 ineq = get_row_parameter_ineq(tab, split);
2455 if (!ineq)
2456 return -1;
2457 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2458 isl_vec_free(ineq);
2459 if (!ok)
2460 return -1;
2462 snap2 = isl_tab_snap(context_tab);
2464 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2465 struct isl_tab_var *var;
2467 if (row == split)
2468 continue;
2469 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2470 continue;
2471 if (tab->row_sign[row] != isl_tab_row_any)
2472 continue;
2474 ineq = get_row_parameter_ineq(tab, row);
2475 if (!ineq)
2476 return -1;
2477 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2478 isl_vec_free(ineq);
2479 if (!ok)
2480 return -1;
2481 var = &context_tab->con[context_tab->n_con - 1];
2482 if (!context_tab->empty &&
2483 !isl_tab_min_at_most_neg_one(context_tab, var))
2484 r++;
2485 if (isl_tab_rollback(context_tab, snap2) < 0)
2486 return -1;
2488 if (best == -1 || r > best_r) {
2489 best = split;
2490 best_r = r;
2492 if (isl_tab_rollback(context_tab, snap) < 0)
2493 return -1;
2496 return best;
2499 static struct isl_basic_set *context_lex_peek_basic_set(
2500 struct isl_context *context)
2502 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2503 if (!clex->tab)
2504 return NULL;
2505 return isl_tab_peek_bset(clex->tab);
2508 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2510 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2511 return clex->tab;
2514 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2515 int check, int update)
2517 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2518 if (isl_tab_extend_cons(clex->tab, 2) < 0)
2519 goto error;
2520 if (add_lexmin_eq(clex->tab, eq) < 0)
2521 goto error;
2522 if (check) {
2523 int v = tab_has_valid_sample(clex->tab, eq, 1);
2524 if (v < 0)
2525 goto error;
2526 if (!v)
2527 clex->tab = check_integer_feasible(clex->tab);
2529 if (update)
2530 clex->tab = check_samples(clex->tab, eq, 1);
2531 return;
2532 error:
2533 isl_tab_free(clex->tab);
2534 clex->tab = NULL;
2537 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2538 int check, int update)
2540 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2541 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2542 goto error;
2543 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2544 if (check) {
2545 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2546 if (v < 0)
2547 goto error;
2548 if (!v)
2549 clex->tab = check_integer_feasible(clex->tab);
2551 if (update)
2552 clex->tab = check_samples(clex->tab, ineq, 0);
2553 return;
2554 error:
2555 isl_tab_free(clex->tab);
2556 clex->tab = NULL;
2559 static isl_stat context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2561 struct isl_context *context = (struct isl_context *)user;
2562 context_lex_add_ineq(context, ineq, 0, 0);
2563 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
2566 /* Check which signs can be obtained by "ineq" on all the currently
2567 * active sample values. See row_sign for more information.
2569 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2570 int strict)
2572 int i;
2573 int sgn;
2574 isl_int tmp;
2575 enum isl_tab_row_sign res = isl_tab_row_unknown;
2577 isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2578 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2579 return isl_tab_row_unknown);
2581 isl_int_init(tmp);
2582 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2583 isl_seq_inner_product(tab->samples->row[i], ineq,
2584 1 + tab->n_var, &tmp);
2585 sgn = isl_int_sgn(tmp);
2586 if (sgn > 0 || (sgn == 0 && strict)) {
2587 if (res == isl_tab_row_unknown)
2588 res = isl_tab_row_pos;
2589 if (res == isl_tab_row_neg)
2590 res = isl_tab_row_any;
2592 if (sgn < 0) {
2593 if (res == isl_tab_row_unknown)
2594 res = isl_tab_row_neg;
2595 if (res == isl_tab_row_pos)
2596 res = isl_tab_row_any;
2598 if (res == isl_tab_row_any)
2599 break;
2601 isl_int_clear(tmp);
2603 return res;
2606 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2607 isl_int *ineq, int strict)
2609 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2610 return tab_ineq_sign(clex->tab, ineq, strict);
2613 /* Check whether "ineq" can be added to the tableau without rendering
2614 * it infeasible.
2616 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2618 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2619 struct isl_tab_undo *snap;
2620 int feasible;
2622 if (!clex->tab)
2623 return -1;
2625 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2626 return -1;
2628 snap = isl_tab_snap(clex->tab);
2629 if (isl_tab_push_basis(clex->tab) < 0)
2630 return -1;
2631 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2632 clex->tab = check_integer_feasible(clex->tab);
2633 if (!clex->tab)
2634 return -1;
2635 feasible = !clex->tab->empty;
2636 if (isl_tab_rollback(clex->tab, snap) < 0)
2637 return -1;
2639 return feasible;
2642 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2643 struct isl_vec *div)
2645 return get_div(tab, context, div);
2648 /* Insert a div specified by "div" to the context tableau at position "pos" and
2649 * return isl_bool_true if the div is obviously non-negative.
2650 * context_tab_add_div will always return isl_bool_true, because all variables
2651 * in a isl_context_lex tableau are non-negative.
2652 * However, if we are using a big parameter in the context, then this only
2653 * reflects the non-negativity of the variable used to _encode_ the
2654 * div, i.e., div' = M + div, so we can't draw any conclusions.
2656 static isl_bool context_lex_insert_div(struct isl_context *context, int pos,
2657 __isl_keep isl_vec *div)
2659 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2660 isl_bool nonneg;
2661 nonneg = context_tab_insert_div(clex->tab, pos, div,
2662 context_lex_add_ineq_wrap, context);
2663 if (nonneg < 0)
2664 return isl_bool_error;
2665 if (clex->tab->M)
2666 return isl_bool_false;
2667 return nonneg;
2670 static int context_lex_detect_equalities(struct isl_context *context,
2671 struct isl_tab *tab)
2673 return 0;
2676 static int context_lex_best_split(struct isl_context *context,
2677 struct isl_tab *tab)
2679 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2680 struct isl_tab_undo *snap;
2681 int r;
2683 snap = isl_tab_snap(clex->tab);
2684 if (isl_tab_push_basis(clex->tab) < 0)
2685 return -1;
2686 r = best_split(tab, clex->tab);
2688 if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2689 return -1;
2691 return r;
2694 static int context_lex_is_empty(struct isl_context *context)
2696 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2697 if (!clex->tab)
2698 return -1;
2699 return clex->tab->empty;
2702 static void *context_lex_save(struct isl_context *context)
2704 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2705 struct isl_tab_undo *snap;
2707 snap = isl_tab_snap(clex->tab);
2708 if (isl_tab_push_basis(clex->tab) < 0)
2709 return NULL;
2710 if (isl_tab_save_samples(clex->tab) < 0)
2711 return NULL;
2713 return snap;
2716 static void context_lex_restore(struct isl_context *context, void *save)
2718 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2719 if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2720 isl_tab_free(clex->tab);
2721 clex->tab = NULL;
2725 static void context_lex_discard(void *save)
2729 static int context_lex_is_ok(struct isl_context *context)
2731 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2732 return !!clex->tab;
2735 /* For each variable in the context tableau, check if the variable can
2736 * only attain non-negative values. If so, mark the parameter as non-negative
2737 * in the main tableau. This allows for a more direct identification of some
2738 * cases of violated constraints.
2740 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2741 struct isl_tab *context_tab)
2743 int i;
2744 struct isl_tab_undo *snap;
2745 struct isl_vec *ineq = NULL;
2746 struct isl_tab_var *var;
2747 int n;
2749 if (context_tab->n_var == 0)
2750 return tab;
2752 ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2753 if (!ineq)
2754 goto error;
2756 if (isl_tab_extend_cons(context_tab, 1) < 0)
2757 goto error;
2759 snap = isl_tab_snap(context_tab);
2761 n = 0;
2762 isl_seq_clr(ineq->el, ineq->size);
2763 for (i = 0; i < context_tab->n_var; ++i) {
2764 isl_int_set_si(ineq->el[1 + i], 1);
2765 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2766 goto error;
2767 var = &context_tab->con[context_tab->n_con - 1];
2768 if (!context_tab->empty &&
2769 !isl_tab_min_at_most_neg_one(context_tab, var)) {
2770 int j = i;
2771 if (i >= tab->n_param)
2772 j = i - tab->n_param + tab->n_var - tab->n_div;
2773 tab->var[j].is_nonneg = 1;
2774 n++;
2776 isl_int_set_si(ineq->el[1 + i], 0);
2777 if (isl_tab_rollback(context_tab, snap) < 0)
2778 goto error;
2781 if (context_tab->M && n == context_tab->n_var) {
2782 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2783 context_tab->M = 0;
2786 isl_vec_free(ineq);
2787 return tab;
2788 error:
2789 isl_vec_free(ineq);
2790 isl_tab_free(tab);
2791 return NULL;
2794 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2795 struct isl_context *context, struct isl_tab *tab)
2797 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2798 struct isl_tab_undo *snap;
2800 if (!tab)
2801 return NULL;
2803 snap = isl_tab_snap(clex->tab);
2804 if (isl_tab_push_basis(clex->tab) < 0)
2805 goto error;
2807 tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2809 if (isl_tab_rollback(clex->tab, snap) < 0)
2810 goto error;
2812 return tab;
2813 error:
2814 isl_tab_free(tab);
2815 return NULL;
2818 static void context_lex_invalidate(struct isl_context *context)
2820 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2821 isl_tab_free(clex->tab);
2822 clex->tab = NULL;
2825 static __isl_null struct isl_context *context_lex_free(
2826 struct isl_context *context)
2828 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2829 isl_tab_free(clex->tab);
2830 free(clex);
2832 return NULL;
2835 struct isl_context_op isl_context_lex_op = {
2836 context_lex_detect_nonnegative_parameters,
2837 context_lex_peek_basic_set,
2838 context_lex_peek_tab,
2839 context_lex_add_eq,
2840 context_lex_add_ineq,
2841 context_lex_ineq_sign,
2842 context_lex_test_ineq,
2843 context_lex_get_div,
2844 context_lex_insert_div,
2845 context_lex_detect_equalities,
2846 context_lex_best_split,
2847 context_lex_is_empty,
2848 context_lex_is_ok,
2849 context_lex_save,
2850 context_lex_restore,
2851 context_lex_discard,
2852 context_lex_invalidate,
2853 context_lex_free,
2856 static struct isl_tab *context_tab_for_lexmin(__isl_take isl_basic_set *bset)
2858 struct isl_tab *tab;
2860 if (!bset)
2861 return NULL;
2862 tab = tab_for_lexmin(bset_to_bmap(bset), NULL, 1, 0);
2863 if (isl_tab_track_bset(tab, bset) < 0)
2864 goto error;
2865 tab = isl_tab_init_samples(tab);
2866 return tab;
2867 error:
2868 isl_tab_free(tab);
2869 return NULL;
2872 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2874 struct isl_context_lex *clex;
2876 if (!dom)
2877 return NULL;
2879 clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2880 if (!clex)
2881 return NULL;
2883 clex->context.op = &isl_context_lex_op;
2885 clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2886 if (restore_lexmin(clex->tab) < 0)
2887 goto error;
2888 clex->tab = check_integer_feasible(clex->tab);
2889 if (!clex->tab)
2890 goto error;
2892 return &clex->context;
2893 error:
2894 clex->context.op->free(&clex->context);
2895 return NULL;
2898 /* Representation of the context when using generalized basis reduction.
2900 * "shifted" contains the offsets of the unit hypercubes that lie inside the
2901 * context. Any rational point in "shifted" can therefore be rounded
2902 * up to an integer point in the context.
2903 * If the context is constrained by any equality, then "shifted" is not used
2904 * as it would be empty.
2906 struct isl_context_gbr {
2907 struct isl_context context;
2908 struct isl_tab *tab;
2909 struct isl_tab *shifted;
2910 struct isl_tab *cone;
2913 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2914 struct isl_context *context, struct isl_tab *tab)
2916 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2917 if (!tab)
2918 return NULL;
2919 return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2922 static struct isl_basic_set *context_gbr_peek_basic_set(
2923 struct isl_context *context)
2925 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2926 if (!cgbr->tab)
2927 return NULL;
2928 return isl_tab_peek_bset(cgbr->tab);
2931 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2933 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2934 return cgbr->tab;
2937 /* Initialize the "shifted" tableau of the context, which
2938 * contains the constraints of the original tableau shifted
2939 * by the sum of all negative coefficients. This ensures
2940 * that any rational point in the shifted tableau can
2941 * be rounded up to yield an integer point in the original tableau.
2943 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2945 int i, j;
2946 struct isl_vec *cst;
2947 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2948 isl_size dim = isl_basic_set_dim(bset, isl_dim_all);
2950 if (dim < 0)
2951 return;
2952 cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2953 if (!cst)
2954 return;
2956 for (i = 0; i < bset->n_ineq; ++i) {
2957 isl_int_set(cst->el[i], bset->ineq[i][0]);
2958 for (j = 0; j < dim; ++j) {
2959 if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2960 continue;
2961 isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2962 bset->ineq[i][1 + j]);
2966 cgbr->shifted = isl_tab_from_basic_set(bset, 0);
2968 for (i = 0; i < bset->n_ineq; ++i)
2969 isl_int_set(bset->ineq[i][0], cst->el[i]);
2971 isl_vec_free(cst);
2974 /* Check if the shifted tableau is non-empty, and if so
2975 * use the sample point to construct an integer point
2976 * of the context tableau.
2978 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2980 struct isl_vec *sample;
2982 if (!cgbr->shifted)
2983 gbr_init_shifted(cgbr);
2984 if (!cgbr->shifted)
2985 return NULL;
2986 if (cgbr->shifted->empty)
2987 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2989 sample = isl_tab_get_sample_value(cgbr->shifted);
2990 sample = isl_vec_ceil(sample);
2992 return sample;
2995 static __isl_give isl_basic_set *drop_constant_terms(
2996 __isl_take isl_basic_set *bset)
2998 int i;
3000 if (!bset)
3001 return NULL;
3003 for (i = 0; i < bset->n_eq; ++i)
3004 isl_int_set_si(bset->eq[i][0], 0);
3006 for (i = 0; i < bset->n_ineq; ++i)
3007 isl_int_set_si(bset->ineq[i][0], 0);
3009 return bset;
3012 static int use_shifted(struct isl_context_gbr *cgbr)
3014 if (!cgbr->tab)
3015 return 0;
3016 return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
3019 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
3021 struct isl_basic_set *bset;
3022 struct isl_basic_set *cone;
3024 if (isl_tab_sample_is_integer(cgbr->tab))
3025 return isl_tab_get_sample_value(cgbr->tab);
3027 if (use_shifted(cgbr)) {
3028 struct isl_vec *sample;
3030 sample = gbr_get_shifted_sample(cgbr);
3031 if (!sample || sample->size > 0)
3032 return sample;
3034 isl_vec_free(sample);
3037 if (!cgbr->cone) {
3038 bset = isl_tab_peek_bset(cgbr->tab);
3039 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3040 if (!cgbr->cone)
3041 return NULL;
3042 if (isl_tab_track_bset(cgbr->cone,
3043 isl_basic_set_copy(bset)) < 0)
3044 return NULL;
3046 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3047 return NULL;
3049 if (cgbr->cone->n_dead == cgbr->cone->n_col) {
3050 struct isl_vec *sample;
3051 struct isl_tab_undo *snap;
3053 if (cgbr->tab->basis) {
3054 if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
3055 isl_mat_free(cgbr->tab->basis);
3056 cgbr->tab->basis = NULL;
3058 cgbr->tab->n_zero = 0;
3059 cgbr->tab->n_unbounded = 0;
3062 snap = isl_tab_snap(cgbr->tab);
3064 sample = isl_tab_sample(cgbr->tab);
3066 if (!sample || isl_tab_rollback(cgbr->tab, snap) < 0) {
3067 isl_vec_free(sample);
3068 return NULL;
3071 return sample;
3074 cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
3075 cone = drop_constant_terms(cone);
3076 cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
3077 cone = isl_basic_set_underlying_set(cone);
3078 cone = isl_basic_set_gauss(cone, NULL);
3080 bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
3081 bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
3082 bset = isl_basic_set_underlying_set(bset);
3083 bset = isl_basic_set_gauss(bset, NULL);
3085 return isl_basic_set_sample_with_cone(bset, cone);
3088 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
3090 struct isl_vec *sample;
3092 if (!cgbr->tab)
3093 return;
3095 if (cgbr->tab->empty)
3096 return;
3098 sample = gbr_get_sample(cgbr);
3099 if (!sample)
3100 goto error;
3102 if (sample->size == 0) {
3103 isl_vec_free(sample);
3104 if (isl_tab_mark_empty(cgbr->tab) < 0)
3105 goto error;
3106 return;
3109 if (isl_tab_add_sample(cgbr->tab, sample) < 0)
3110 goto error;
3112 return;
3113 error:
3114 isl_tab_free(cgbr->tab);
3115 cgbr->tab = NULL;
3118 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
3120 if (!tab)
3121 return NULL;
3123 if (isl_tab_extend_cons(tab, 2) < 0)
3124 goto error;
3126 if (isl_tab_add_eq(tab, eq) < 0)
3127 goto error;
3129 return tab;
3130 error:
3131 isl_tab_free(tab);
3132 return NULL;
3135 /* Add the equality described by "eq" to the context.
3136 * If "check" is set, then we check if the context is empty after
3137 * adding the equality.
3138 * If "update" is set, then we check if the samples are still valid.
3140 * We do not explicitly add shifted copies of the equality to
3141 * cgbr->shifted since they would conflict with each other.
3142 * Instead, we directly mark cgbr->shifted empty.
3144 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
3145 int check, int update)
3147 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3149 cgbr->tab = add_gbr_eq(cgbr->tab, eq);
3151 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3152 if (isl_tab_mark_empty(cgbr->shifted) < 0)
3153 goto error;
3156 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3157 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
3158 goto error;
3159 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
3160 goto error;
3163 if (check) {
3164 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
3165 if (v < 0)
3166 goto error;
3167 if (!v)
3168 check_gbr_integer_feasible(cgbr);
3170 if (update)
3171 cgbr->tab = check_samples(cgbr->tab, eq, 1);
3172 return;
3173 error:
3174 isl_tab_free(cgbr->tab);
3175 cgbr->tab = NULL;
3178 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
3180 if (!cgbr->tab)
3181 return;
3183 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3184 goto error;
3186 if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
3187 goto error;
3189 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3190 int i;
3191 isl_size dim;
3192 dim = isl_basic_map_dim(cgbr->tab->bmap, isl_dim_all);
3193 if (dim < 0)
3194 goto error;
3196 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
3197 goto error;
3199 for (i = 0; i < dim; ++i) {
3200 if (!isl_int_is_neg(ineq[1 + i]))
3201 continue;
3202 isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
3205 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
3206 goto error;
3208 for (i = 0; i < dim; ++i) {
3209 if (!isl_int_is_neg(ineq[1 + i]))
3210 continue;
3211 isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
3215 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3216 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
3217 goto error;
3218 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
3219 goto error;
3222 return;
3223 error:
3224 isl_tab_free(cgbr->tab);
3225 cgbr->tab = NULL;
3228 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
3229 int check, int update)
3231 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3233 add_gbr_ineq(cgbr, ineq);
3234 if (!cgbr->tab)
3235 return;
3237 if (check) {
3238 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
3239 if (v < 0)
3240 goto error;
3241 if (!v)
3242 check_gbr_integer_feasible(cgbr);
3244 if (update)
3245 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
3246 return;
3247 error:
3248 isl_tab_free(cgbr->tab);
3249 cgbr->tab = NULL;
3252 static isl_stat context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
3254 struct isl_context *context = (struct isl_context *)user;
3255 context_gbr_add_ineq(context, ineq, 0, 0);
3256 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
3259 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
3260 isl_int *ineq, int strict)
3262 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3263 return tab_ineq_sign(cgbr->tab, ineq, strict);
3266 /* Check whether "ineq" can be added to the tableau without rendering
3267 * it infeasible.
3269 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
3271 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3272 struct isl_tab_undo *snap;
3273 struct isl_tab_undo *shifted_snap = NULL;
3274 struct isl_tab_undo *cone_snap = NULL;
3275 int feasible;
3277 if (!cgbr->tab)
3278 return -1;
3280 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3281 return -1;
3283 snap = isl_tab_snap(cgbr->tab);
3284 if (cgbr->shifted)
3285 shifted_snap = isl_tab_snap(cgbr->shifted);
3286 if (cgbr->cone)
3287 cone_snap = isl_tab_snap(cgbr->cone);
3288 add_gbr_ineq(cgbr, ineq);
3289 check_gbr_integer_feasible(cgbr);
3290 if (!cgbr->tab)
3291 return -1;
3292 feasible = !cgbr->tab->empty;
3293 if (isl_tab_rollback(cgbr->tab, snap) < 0)
3294 return -1;
3295 if (shifted_snap) {
3296 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
3297 return -1;
3298 } else if (cgbr->shifted) {
3299 isl_tab_free(cgbr->shifted);
3300 cgbr->shifted = NULL;
3302 if (cone_snap) {
3303 if (isl_tab_rollback(cgbr->cone, cone_snap))
3304 return -1;
3305 } else if (cgbr->cone) {
3306 isl_tab_free(cgbr->cone);
3307 cgbr->cone = NULL;
3310 return feasible;
3313 /* Return the column of the last of the variables associated to
3314 * a column that has a non-zero coefficient.
3315 * This function is called in a context where only coefficients
3316 * of parameters or divs can be non-zero.
3318 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
3320 int i;
3321 int col;
3323 if (tab->n_var == 0)
3324 return -1;
3326 for (i = tab->n_var - 1; i >= 0; --i) {
3327 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
3328 continue;
3329 if (tab->var[i].is_row)
3330 continue;
3331 col = tab->var[i].index;
3332 if (!isl_int_is_zero(p[col]))
3333 return col;
3336 return -1;
3339 /* Look through all the recently added equalities in the context
3340 * to see if we can propagate any of them to the main tableau.
3342 * The newly added equalities in the context are encoded as pairs
3343 * of inequalities starting at inequality "first".
3345 * We tentatively add each of these equalities to the main tableau
3346 * and if this happens to result in a row with a final coefficient
3347 * that is one or negative one, we use it to kill a column
3348 * in the main tableau. Otherwise, we discard the tentatively
3349 * added row.
3350 * This tentative addition of equality constraints turns
3351 * on the undo facility of the tableau. Turn it off again
3352 * at the end, assuming it was turned off to begin with.
3354 * Return 0 on success and -1 on failure.
3356 static int propagate_equalities(struct isl_context_gbr *cgbr,
3357 struct isl_tab *tab, unsigned first)
3359 int i;
3360 struct isl_vec *eq = NULL;
3361 isl_bool needs_undo;
3363 needs_undo = isl_tab_need_undo(tab);
3364 if (needs_undo < 0)
3365 goto error;
3366 eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
3367 if (!eq)
3368 goto error;
3370 if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
3371 goto error;
3373 isl_seq_clr(eq->el + 1 + tab->n_param,
3374 tab->n_var - tab->n_param - tab->n_div);
3375 for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
3376 int j;
3377 int r;
3378 struct isl_tab_undo *snap;
3379 snap = isl_tab_snap(tab);
3381 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
3382 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
3383 cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
3384 tab->n_div);
3386 r = isl_tab_add_row(tab, eq->el);
3387 if (r < 0)
3388 goto error;
3389 r = tab->con[r].index;
3390 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
3391 if (j < 0 || j < tab->n_dead ||
3392 !isl_int_is_one(tab->mat->row[r][0]) ||
3393 (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
3394 !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
3395 if (isl_tab_rollback(tab, snap) < 0)
3396 goto error;
3397 continue;
3399 if (isl_tab_pivot(tab, r, j) < 0)
3400 goto error;
3401 if (isl_tab_kill_col(tab, j) < 0)
3402 goto error;
3404 if (restore_lexmin(tab) < 0)
3405 goto error;
3408 if (!needs_undo)
3409 isl_tab_clear_undo(tab);
3410 isl_vec_free(eq);
3412 return 0;
3413 error:
3414 isl_vec_free(eq);
3415 isl_tab_free(cgbr->tab);
3416 cgbr->tab = NULL;
3417 return -1;
3420 static int context_gbr_detect_equalities(struct isl_context *context,
3421 struct isl_tab *tab)
3423 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3424 unsigned n_ineq;
3426 if (!cgbr->cone) {
3427 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3428 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3429 if (!cgbr->cone)
3430 goto error;
3431 if (isl_tab_track_bset(cgbr->cone,
3432 isl_basic_set_copy(bset)) < 0)
3433 goto error;
3435 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3436 goto error;
3438 n_ineq = cgbr->tab->bmap->n_ineq;
3439 cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3440 if (!cgbr->tab)
3441 return -1;
3442 if (cgbr->tab->bmap->n_ineq > n_ineq &&
3443 propagate_equalities(cgbr, tab, n_ineq) < 0)
3444 return -1;
3446 return 0;
3447 error:
3448 isl_tab_free(cgbr->tab);
3449 cgbr->tab = NULL;
3450 return -1;
3453 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3454 struct isl_vec *div)
3456 return get_div(tab, context, div);
3459 static isl_bool context_gbr_insert_div(struct isl_context *context, int pos,
3460 __isl_keep isl_vec *div)
3462 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3463 if (cgbr->cone) {
3464 int r, o_div;
3465 isl_size n_div;
3467 n_div = isl_basic_map_dim(cgbr->cone->bmap, isl_dim_div);
3468 if (n_div < 0)
3469 return isl_bool_error;
3470 o_div = cgbr->cone->n_var - n_div;
3472 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3473 return isl_bool_error;
3474 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3475 return isl_bool_error;
3476 if ((r = isl_tab_insert_var(cgbr->cone, pos)) <0)
3477 return isl_bool_error;
3479 cgbr->cone->bmap = isl_basic_map_insert_div(cgbr->cone->bmap,
3480 r - o_div, div);
3481 if (!cgbr->cone->bmap)
3482 return isl_bool_error;
3483 if (isl_tab_push_var(cgbr->cone, isl_tab_undo_bmap_div,
3484 &cgbr->cone->var[r]) < 0)
3485 return isl_bool_error;
3487 return context_tab_insert_div(cgbr->tab, pos, div,
3488 context_gbr_add_ineq_wrap, context);
3491 static int context_gbr_best_split(struct isl_context *context,
3492 struct isl_tab *tab)
3494 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3495 struct isl_tab_undo *snap;
3496 int r;
3498 snap = isl_tab_snap(cgbr->tab);
3499 r = best_split(tab, cgbr->tab);
3501 if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3502 return -1;
3504 return r;
3507 static int context_gbr_is_empty(struct isl_context *context)
3509 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3510 if (!cgbr->tab)
3511 return -1;
3512 return cgbr->tab->empty;
3515 struct isl_gbr_tab_undo {
3516 struct isl_tab_undo *tab_snap;
3517 struct isl_tab_undo *shifted_snap;
3518 struct isl_tab_undo *cone_snap;
3521 static void *context_gbr_save(struct isl_context *context)
3523 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3524 struct isl_gbr_tab_undo *snap;
3526 if (!cgbr->tab)
3527 return NULL;
3529 snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3530 if (!snap)
3531 return NULL;
3533 snap->tab_snap = isl_tab_snap(cgbr->tab);
3534 if (isl_tab_save_samples(cgbr->tab) < 0)
3535 goto error;
3537 if (cgbr->shifted)
3538 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3539 else
3540 snap->shifted_snap = NULL;
3542 if (cgbr->cone)
3543 snap->cone_snap = isl_tab_snap(cgbr->cone);
3544 else
3545 snap->cone_snap = NULL;
3547 return snap;
3548 error:
3549 free(snap);
3550 return NULL;
3553 static void context_gbr_restore(struct isl_context *context, void *save)
3555 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3556 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3557 if (!snap)
3558 goto error;
3559 if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0)
3560 goto error;
3562 if (snap->shifted_snap) {
3563 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3564 goto error;
3565 } else if (cgbr->shifted) {
3566 isl_tab_free(cgbr->shifted);
3567 cgbr->shifted = NULL;
3570 if (snap->cone_snap) {
3571 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3572 goto error;
3573 } else if (cgbr->cone) {
3574 isl_tab_free(cgbr->cone);
3575 cgbr->cone = NULL;
3578 free(snap);
3580 return;
3581 error:
3582 free(snap);
3583 isl_tab_free(cgbr->tab);
3584 cgbr->tab = NULL;
3587 static void context_gbr_discard(void *save)
3589 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3590 free(snap);
3593 static int context_gbr_is_ok(struct isl_context *context)
3595 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3596 return !!cgbr->tab;
3599 static void context_gbr_invalidate(struct isl_context *context)
3601 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3602 isl_tab_free(cgbr->tab);
3603 cgbr->tab = NULL;
3606 static __isl_null struct isl_context *context_gbr_free(
3607 struct isl_context *context)
3609 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3610 isl_tab_free(cgbr->tab);
3611 isl_tab_free(cgbr->shifted);
3612 isl_tab_free(cgbr->cone);
3613 free(cgbr);
3615 return NULL;
3618 struct isl_context_op isl_context_gbr_op = {
3619 context_gbr_detect_nonnegative_parameters,
3620 context_gbr_peek_basic_set,
3621 context_gbr_peek_tab,
3622 context_gbr_add_eq,
3623 context_gbr_add_ineq,
3624 context_gbr_ineq_sign,
3625 context_gbr_test_ineq,
3626 context_gbr_get_div,
3627 context_gbr_insert_div,
3628 context_gbr_detect_equalities,
3629 context_gbr_best_split,
3630 context_gbr_is_empty,
3631 context_gbr_is_ok,
3632 context_gbr_save,
3633 context_gbr_restore,
3634 context_gbr_discard,
3635 context_gbr_invalidate,
3636 context_gbr_free,
3639 static struct isl_context *isl_context_gbr_alloc(__isl_keep isl_basic_set *dom)
3641 struct isl_context_gbr *cgbr;
3643 if (!dom)
3644 return NULL;
3646 cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3647 if (!cgbr)
3648 return NULL;
3650 cgbr->context.op = &isl_context_gbr_op;
3652 cgbr->shifted = NULL;
3653 cgbr->cone = NULL;
3654 cgbr->tab = isl_tab_from_basic_set(dom, 1);
3655 cgbr->tab = isl_tab_init_samples(cgbr->tab);
3656 if (!cgbr->tab)
3657 goto error;
3658 check_gbr_integer_feasible(cgbr);
3660 return &cgbr->context;
3661 error:
3662 cgbr->context.op->free(&cgbr->context);
3663 return NULL;
3666 /* Allocate a context corresponding to "dom".
3667 * The representation specific fields are initialized by
3668 * isl_context_lex_alloc or isl_context_gbr_alloc.
3669 * The shared "n_unknown" field is initialized to the number
3670 * of final unknown integer divisions in "dom".
3672 static struct isl_context *isl_context_alloc(__isl_keep isl_basic_set *dom)
3674 struct isl_context *context;
3675 int first;
3676 isl_size n_div;
3678 if (!dom)
3679 return NULL;
3681 if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3682 context = isl_context_lex_alloc(dom);
3683 else
3684 context = isl_context_gbr_alloc(dom);
3686 if (!context)
3687 return NULL;
3689 first = isl_basic_set_first_unknown_div(dom);
3690 n_div = isl_basic_set_dim(dom, isl_dim_div);
3691 if (first < 0 || n_div < 0)
3692 return context->op->free(context);
3693 context->n_unknown = n_div - first;
3695 return context;
3698 /* Initialize some common fields of "sol", which keeps track
3699 * of the solution of an optimization problem on "bmap" over
3700 * the domain "dom".
3701 * If "max" is set, then a maximization problem is being solved, rather than
3702 * a minimization problem, which means that the variables in the
3703 * tableau have value "M - x" rather than "M + x".
3705 static isl_stat sol_init(struct isl_sol *sol, __isl_keep isl_basic_map *bmap,
3706 __isl_keep isl_basic_set *dom, int max)
3708 sol->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3709 sol->dec_level.callback.run = &sol_dec_level_wrap;
3710 sol->dec_level.sol = sol;
3711 sol->max = max;
3712 sol->n_out = isl_basic_map_dim(bmap, isl_dim_out);
3713 sol->space = isl_basic_map_get_space(bmap);
3715 sol->context = isl_context_alloc(dom);
3716 if (sol->n_out < 0 || !sol->space || !sol->context)
3717 return isl_stat_error;
3719 return isl_stat_ok;
3722 /* Construct an isl_sol_map structure for accumulating the solution.
3723 * If track_empty is set, then we also keep track of the parts
3724 * of the context where there is no solution.
3725 * If max is set, then we are solving a maximization, rather than
3726 * a minimization problem, which means that the variables in the
3727 * tableau have value "M - x" rather than "M + x".
3729 static struct isl_sol *sol_map_init(__isl_keep isl_basic_map *bmap,
3730 __isl_take isl_basic_set *dom, int track_empty, int max)
3732 struct isl_sol_map *sol_map = NULL;
3733 isl_space *space;
3735 if (!bmap)
3736 goto error;
3738 sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3739 if (!sol_map)
3740 goto error;
3742 sol_map->sol.free = &sol_map_free;
3743 if (sol_init(&sol_map->sol, bmap, dom, max) < 0)
3744 goto error;
3745 sol_map->sol.add = &sol_map_add_wrap;
3746 sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3747 space = isl_space_copy(sol_map->sol.space);
3748 sol_map->map = isl_map_alloc_space(space, 1, ISL_MAP_DISJOINT);
3749 if (!sol_map->map)
3750 goto error;
3752 if (track_empty) {
3753 sol_map->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
3754 1, ISL_SET_DISJOINT);
3755 if (!sol_map->empty)
3756 goto error;
3759 isl_basic_set_free(dom);
3760 return &sol_map->sol;
3761 error:
3762 isl_basic_set_free(dom);
3763 sol_free(&sol_map->sol);
3764 return NULL;
3767 /* Check whether all coefficients of (non-parameter) variables
3768 * are non-positive, meaning that no pivots can be performed on the row.
3770 static int is_critical(struct isl_tab *tab, int row)
3772 int j;
3773 unsigned off = 2 + tab->M;
3775 for (j = tab->n_dead; j < tab->n_col; ++j) {
3776 if (col_is_parameter_var(tab, j))
3777 continue;
3779 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3780 return 0;
3783 return 1;
3786 /* Check whether the inequality represented by vec is strict over the integers,
3787 * i.e., there are no integer values satisfying the constraint with
3788 * equality. This happens if the gcd of the coefficients is not a divisor
3789 * of the constant term. If so, scale the constraint down by the gcd
3790 * of the coefficients.
3792 static int is_strict(struct isl_vec *vec)
3794 isl_int gcd;
3795 int strict = 0;
3797 isl_int_init(gcd);
3798 isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3799 if (!isl_int_is_one(gcd)) {
3800 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3801 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3802 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3804 isl_int_clear(gcd);
3806 return strict;
3809 /* Determine the sign of the given row of the main tableau.
3810 * The result is one of
3811 * isl_tab_row_pos: always non-negative; no pivot needed
3812 * isl_tab_row_neg: always non-positive; pivot
3813 * isl_tab_row_any: can be both positive and negative; split
3815 * We first handle some simple cases
3816 * - the row sign may be known already
3817 * - the row may be obviously non-negative
3818 * - the parametric constant may be equal to that of another row
3819 * for which we know the sign. This sign will be either "pos" or
3820 * "any". If it had been "neg" then we would have pivoted before.
3822 * If none of these cases hold, we check the value of the row for each
3823 * of the currently active samples. Based on the signs of these values
3824 * we make an initial determination of the sign of the row.
3826 * all zero -> unk(nown)
3827 * all non-negative -> pos
3828 * all non-positive -> neg
3829 * both negative and positive -> all
3831 * If we end up with "all", we are done.
3832 * Otherwise, we perform a check for positive and/or negative
3833 * values as follows.
3835 * samples neg unk pos
3836 * <0 ? Y N Y N
3837 * pos any pos
3838 * >0 ? Y N Y N
3839 * any neg any neg
3841 * There is no special sign for "zero", because we can usually treat zero
3842 * as either non-negative or non-positive, whatever works out best.
3843 * However, if the row is "critical", meaning that pivoting is impossible
3844 * then we don't want to limp zero with the non-positive case, because
3845 * then we we would lose the solution for those values of the parameters
3846 * where the value of the row is zero. Instead, we treat 0 as non-negative
3847 * ensuring a split if the row can attain both zero and negative values.
3848 * The same happens when the original constraint was one that could not
3849 * be satisfied with equality by any integer values of the parameters.
3850 * In this case, we normalize the constraint, but then a value of zero
3851 * for the normalized constraint is actually a positive value for the
3852 * original constraint, so again we need to treat zero as non-negative.
3853 * In both these cases, we have the following decision tree instead:
3855 * all non-negative -> pos
3856 * all negative -> neg
3857 * both negative and non-negative -> all
3859 * samples neg pos
3860 * <0 ? Y N
3861 * any pos
3862 * >=0 ? Y N
3863 * any neg
3865 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3866 struct isl_sol *sol, int row)
3868 struct isl_vec *ineq = NULL;
3869 enum isl_tab_row_sign res = isl_tab_row_unknown;
3870 int critical;
3871 int strict;
3872 int row2;
3874 if (tab->row_sign[row] != isl_tab_row_unknown)
3875 return tab->row_sign[row];
3876 if (is_obviously_nonneg(tab, row))
3877 return isl_tab_row_pos;
3878 for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3879 if (tab->row_sign[row2] == isl_tab_row_unknown)
3880 continue;
3881 if (identical_parameter_line(tab, row, row2))
3882 return tab->row_sign[row2];
3885 critical = is_critical(tab, row);
3887 ineq = get_row_parameter_ineq(tab, row);
3888 if (!ineq)
3889 goto error;
3891 strict = is_strict(ineq);
3893 res = sol->context->op->ineq_sign(sol->context, ineq->el,
3894 critical || strict);
3896 if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3897 /* test for negative values */
3898 int feasible;
3899 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3900 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3902 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3903 if (feasible < 0)
3904 goto error;
3905 if (!feasible)
3906 res = isl_tab_row_pos;
3907 else
3908 res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3909 : isl_tab_row_any;
3910 if (res == isl_tab_row_neg) {
3911 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3912 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3916 if (res == isl_tab_row_neg) {
3917 /* test for positive values */
3918 int feasible;
3919 if (!critical && !strict)
3920 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3922 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3923 if (feasible < 0)
3924 goto error;
3925 if (feasible)
3926 res = isl_tab_row_any;
3929 isl_vec_free(ineq);
3930 return res;
3931 error:
3932 isl_vec_free(ineq);
3933 return isl_tab_row_unknown;
3936 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3938 /* Find solutions for values of the parameters that satisfy the given
3939 * inequality.
3941 * We currently take a snapshot of the context tableau that is reset
3942 * when we return from this function, while we make a copy of the main
3943 * tableau, leaving the original main tableau untouched.
3944 * These are fairly arbitrary choices. Making a copy also of the context
3945 * tableau would obviate the need to undo any changes made to it later,
3946 * while taking a snapshot of the main tableau could reduce memory usage.
3947 * If we were to switch to taking a snapshot of the main tableau,
3948 * we would have to keep in mind that we need to save the row signs
3949 * and that we need to do this before saving the current basis
3950 * such that the basis has been restore before we restore the row signs.
3952 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3954 void *saved;
3956 if (!sol->context)
3957 goto error;
3959 tab = isl_tab_dup(tab);
3960 if (!tab)
3961 goto error;
3963 saved = sol->context->op->save(sol->context);
3965 sol_context_add_ineq(sol, ineq, 0, 1);
3967 find_solutions(sol, tab);
3969 if (!sol->error)
3970 sol->context->op->restore(sol->context, saved);
3971 else
3972 sol->context->op->discard(saved);
3973 return;
3974 error:
3975 sol->error = 1;
3978 /* Record the absence of solutions for those values of the parameters
3979 * that do not satisfy the given inequality with equality.
3981 static void no_sol_in_strict(struct isl_sol *sol,
3982 struct isl_tab *tab, struct isl_vec *ineq)
3984 int empty;
3985 void *saved;
3987 if (!sol->context || sol->error)
3988 goto error;
3989 saved = sol->context->op->save(sol->context);
3991 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3993 sol_context_add_ineq(sol, ineq->el, 1, 0);
3995 empty = tab->empty;
3996 tab->empty = 1;
3997 sol_add(sol, tab);
3998 tab->empty = empty;
4000 isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
4002 sol->context->op->restore(sol->context, saved);
4003 if (!sol->context->op->is_ok(sol->context))
4004 goto error;
4005 return;
4006 error:
4007 sol->error = 1;
4010 /* Reset all row variables that are marked to have a sign that may
4011 * be both positive and negative to have an unknown sign.
4013 static void reset_any_to_unknown(struct isl_tab *tab)
4015 int row;
4017 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4018 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
4019 continue;
4020 if (tab->row_sign[row] == isl_tab_row_any)
4021 tab->row_sign[row] = isl_tab_row_unknown;
4025 /* Compute the lexicographic minimum of the set represented by the main
4026 * tableau "tab" within the context "sol->context_tab".
4027 * On entry the sample value of the main tableau is lexicographically
4028 * less than or equal to this lexicographic minimum.
4029 * Pivots are performed until a feasible point is found, which is then
4030 * necessarily equal to the minimum, or until the tableau is found to
4031 * be infeasible. Some pivots may need to be performed for only some
4032 * feasible values of the context tableau. If so, the context tableau
4033 * is split into a part where the pivot is needed and a part where it is not.
4035 * Whenever we enter the main loop, the main tableau is such that no
4036 * "obvious" pivots need to be performed on it, where "obvious" means
4037 * that the given row can be seen to be negative without looking at
4038 * the context tableau. In particular, for non-parametric problems,
4039 * no pivots need to be performed on the main tableau.
4040 * The caller of find_solutions is responsible for making this property
4041 * hold prior to the first iteration of the loop, while restore_lexmin
4042 * is called before every other iteration.
4044 * Inside the main loop, we first examine the signs of the rows of
4045 * the main tableau within the context of the context tableau.
4046 * If we find a row that is always non-positive for all values of
4047 * the parameters satisfying the context tableau and negative for at
4048 * least one value of the parameters, we perform the appropriate pivot
4049 * and start over. An exception is the case where no pivot can be
4050 * performed on the row. In this case, we require that the sign of
4051 * the row is negative for all values of the parameters (rather than just
4052 * non-positive). This special case is handled inside row_sign, which
4053 * will say that the row can have any sign if it determines that it can
4054 * attain both negative and zero values.
4056 * If we can't find a row that always requires a pivot, but we can find
4057 * one or more rows that require a pivot for some values of the parameters
4058 * (i.e., the row can attain both positive and negative signs), then we split
4059 * the context tableau into two parts, one where we force the sign to be
4060 * non-negative and one where we force is to be negative.
4061 * The non-negative part is handled by a recursive call (through find_in_pos).
4062 * Upon returning from this call, we continue with the negative part and
4063 * perform the required pivot.
4065 * If no such rows can be found, all rows are non-negative and we have
4066 * found a (rational) feasible point. If we only wanted a rational point
4067 * then we are done.
4068 * Otherwise, we check if all values of the sample point of the tableau
4069 * are integral for the variables. If so, we have found the minimal
4070 * integral point and we are done.
4071 * If the sample point is not integral, then we need to make a distinction
4072 * based on whether the constant term is non-integral or the coefficients
4073 * of the parameters. Furthermore, in order to decide how to handle
4074 * the non-integrality, we also need to know whether the coefficients
4075 * of the other columns in the tableau are integral. This leads
4076 * to the following table. The first two rows do not correspond
4077 * to a non-integral sample point and are only mentioned for completeness.
4079 * constant parameters other
4081 * int int int |
4082 * int int rat | -> no problem
4084 * rat int int -> fail
4086 * rat int rat -> cut
4088 * int rat rat |
4089 * rat rat rat | -> parametric cut
4091 * int rat int |
4092 * rat rat int | -> split context
4094 * If the parametric constant is completely integral, then there is nothing
4095 * to be done. If the constant term is non-integral, but all the other
4096 * coefficient are integral, then there is nothing that can be done
4097 * and the tableau has no integral solution.
4098 * If, on the other hand, one or more of the other columns have rational
4099 * coefficients, but the parameter coefficients are all integral, then
4100 * we can perform a regular (non-parametric) cut.
4101 * Finally, if there is any parameter coefficient that is non-integral,
4102 * then we need to involve the context tableau. There are two cases here.
4103 * If at least one other column has a rational coefficient, then we
4104 * can perform a parametric cut in the main tableau by adding a new
4105 * integer division in the context tableau.
4106 * If all other columns have integral coefficients, then we need to
4107 * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
4108 * is always integral. We do this by introducing an integer division
4109 * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
4110 * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
4111 * Since q is expressed in the tableau as
4112 * c + \sum a_i y_i - m q >= 0
4113 * -c - \sum a_i y_i + m q + m - 1 >= 0
4114 * it is sufficient to add the inequality
4115 * -c - \sum a_i y_i + m q >= 0
4116 * In the part of the context where this inequality does not hold, the
4117 * main tableau is marked as being empty.
4119 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
4121 struct isl_context *context;
4122 int r;
4124 if (!tab || sol->error)
4125 goto error;
4127 context = sol->context;
4129 if (tab->empty)
4130 goto done;
4131 if (context->op->is_empty(context))
4132 goto done;
4134 for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
4135 int flags;
4136 int row;
4137 enum isl_tab_row_sign sgn;
4138 int split = -1;
4139 int n_split = 0;
4141 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4142 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
4143 continue;
4144 sgn = row_sign(tab, sol, row);
4145 if (!sgn)
4146 goto error;
4147 tab->row_sign[row] = sgn;
4148 if (sgn == isl_tab_row_any)
4149 n_split++;
4150 if (sgn == isl_tab_row_any && split == -1)
4151 split = row;
4152 if (sgn == isl_tab_row_neg)
4153 break;
4155 if (row < tab->n_row)
4156 continue;
4157 if (split != -1) {
4158 struct isl_vec *ineq;
4159 if (n_split != 1)
4160 split = context->op->best_split(context, tab);
4161 if (split < 0)
4162 goto error;
4163 ineq = get_row_parameter_ineq(tab, split);
4164 if (!ineq)
4165 goto error;
4166 is_strict(ineq);
4167 reset_any_to_unknown(tab);
4168 tab->row_sign[split] = isl_tab_row_pos;
4169 sol_inc_level(sol);
4170 find_in_pos(sol, tab, ineq->el);
4171 tab->row_sign[split] = isl_tab_row_neg;
4172 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4173 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
4174 sol_context_add_ineq(sol, ineq->el, 0, 1);
4175 isl_vec_free(ineq);
4176 if (sol->error)
4177 goto error;
4178 continue;
4180 if (tab->rational)
4181 break;
4182 row = first_non_integer_row(tab, &flags);
4183 if (row < 0)
4184 break;
4185 if (ISL_FL_ISSET(flags, I_PAR)) {
4186 if (ISL_FL_ISSET(flags, I_VAR)) {
4187 if (isl_tab_mark_empty(tab) < 0)
4188 goto error;
4189 break;
4191 row = add_cut(tab, row);
4192 } else if (ISL_FL_ISSET(flags, I_VAR)) {
4193 struct isl_vec *div;
4194 struct isl_vec *ineq;
4195 int d;
4196 div = get_row_split_div(tab, row);
4197 if (!div)
4198 goto error;
4199 d = context->op->get_div(context, tab, div);
4200 isl_vec_free(div);
4201 if (d < 0)
4202 goto error;
4203 ineq = ineq_for_div(context->op->peek_basic_set(context), d);
4204 if (!ineq)
4205 goto error;
4206 sol_inc_level(sol);
4207 no_sol_in_strict(sol, tab, ineq);
4208 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4209 sol_context_add_ineq(sol, ineq->el, 1, 1);
4210 isl_vec_free(ineq);
4211 if (sol->error || !context->op->is_ok(context))
4212 goto error;
4213 tab = set_row_cst_to_div(tab, row, d);
4214 if (context->op->is_empty(context))
4215 break;
4216 } else
4217 row = add_parametric_cut(tab, row, context);
4218 if (row < 0)
4219 goto error;
4221 if (r < 0)
4222 goto error;
4223 done:
4224 sol_add(sol, tab);
4225 isl_tab_free(tab);
4226 return;
4227 error:
4228 isl_tab_free(tab);
4229 sol->error = 1;
4232 /* Does "sol" contain a pair of partial solutions that could potentially
4233 * be merged?
4235 * We currently only check that "sol" is not in an error state
4236 * and that there are at least two partial solutions of which the final two
4237 * are defined at the same level.
4239 static int sol_has_mergeable_solutions(struct isl_sol *sol)
4241 if (sol->error)
4242 return 0;
4243 if (!sol->partial)
4244 return 0;
4245 if (!sol->partial->next)
4246 return 0;
4247 return sol->partial->level == sol->partial->next->level;
4250 /* Compute the lexicographic minimum of the set represented by the main
4251 * tableau "tab" within the context "sol->context_tab".
4253 * As a preprocessing step, we first transfer all the purely parametric
4254 * equalities from the main tableau to the context tableau, i.e.,
4255 * parameters that have been pivoted to a row.
4256 * These equalities are ignored by the main algorithm, because the
4257 * corresponding rows may not be marked as being non-negative.
4258 * In parts of the context where the added equality does not hold,
4259 * the main tableau is marked as being empty.
4261 * Before we embark on the actual computation, we save a copy
4262 * of the context. When we return, we check if there are any
4263 * partial solutions that can potentially be merged. If so,
4264 * we perform a rollback to the initial state of the context.
4265 * The merging of partial solutions happens inside calls to
4266 * sol_dec_level that are pushed onto the undo stack of the context.
4267 * If there are no partial solutions that can potentially be merged
4268 * then the rollback is skipped as it would just be wasted effort.
4270 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
4272 int row;
4273 void *saved;
4275 if (!tab)
4276 goto error;
4278 sol->level = 0;
4280 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4281 int p;
4282 struct isl_vec *eq;
4284 if (!row_is_parameter_var(tab, row))
4285 continue;
4286 if (tab->row_var[row] < tab->n_param)
4287 p = tab->row_var[row];
4288 else
4289 p = tab->row_var[row]
4290 + tab->n_param - (tab->n_var - tab->n_div);
4292 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
4293 if (!eq)
4294 goto error;
4295 get_row_parameter_line(tab, row, eq->el);
4296 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
4297 eq = isl_vec_normalize(eq);
4299 sol_inc_level(sol);
4300 no_sol_in_strict(sol, tab, eq);
4302 isl_seq_neg(eq->el, eq->el, eq->size);
4303 sol_inc_level(sol);
4304 no_sol_in_strict(sol, tab, eq);
4305 isl_seq_neg(eq->el, eq->el, eq->size);
4307 sol_context_add_eq(sol, eq->el, 1, 1);
4309 isl_vec_free(eq);
4311 if (isl_tab_mark_redundant(tab, row) < 0)
4312 goto error;
4314 if (sol->context->op->is_empty(sol->context))
4315 break;
4317 row = tab->n_redundant - 1;
4320 saved = sol->context->op->save(sol->context);
4322 find_solutions(sol, tab);
4324 if (sol_has_mergeable_solutions(sol))
4325 sol->context->op->restore(sol->context, saved);
4326 else
4327 sol->context->op->discard(saved);
4329 sol->level = 0;
4330 sol_pop(sol);
4332 return;
4333 error:
4334 isl_tab_free(tab);
4335 sol->error = 1;
4338 /* Check if integer division "div" of "dom" also occurs in "bmap".
4339 * If so, return its position within the divs.
4340 * Otherwise, return a position beyond the integer divisions.
4342 static int find_context_div(__isl_keep isl_basic_map *bmap,
4343 __isl_keep isl_basic_set *dom, unsigned div)
4345 int i;
4346 isl_size b_v_div, d_v_div;
4347 isl_size n_div;
4349 b_v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4350 d_v_div = isl_basic_set_var_offset(dom, isl_dim_div);
4351 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4352 if (b_v_div < 0 || d_v_div < 0 || n_div < 0)
4353 return -1;
4355 if (isl_int_is_zero(dom->div[div][0]))
4356 return n_div;
4357 if (isl_seq_first_non_zero(dom->div[div] + 2 + d_v_div,
4358 dom->n_div) != -1)
4359 return n_div;
4361 for (i = 0; i < n_div; ++i) {
4362 if (isl_int_is_zero(bmap->div[i][0]))
4363 continue;
4364 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_v_div,
4365 (b_v_div - d_v_div) + n_div) != -1)
4366 continue;
4367 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_v_div))
4368 return i;
4370 return n_div;
4373 /* The correspondence between the variables in the main tableau,
4374 * the context tableau, and the input map and domain is as follows.
4375 * The first n_param and the last n_div variables of the main tableau
4376 * form the variables of the context tableau.
4377 * In the basic map, these n_param variables correspond to the
4378 * parameters and the input dimensions. In the domain, they correspond
4379 * to the parameters and the set dimensions.
4380 * The n_div variables correspond to the integer divisions in the domain.
4381 * To ensure that everything lines up, we may need to copy some of the
4382 * integer divisions of the domain to the map. These have to be placed
4383 * in the same order as those in the context and they have to be placed
4384 * after any other integer divisions that the map may have.
4385 * This function performs the required reordering.
4387 static __isl_give isl_basic_map *align_context_divs(
4388 __isl_take isl_basic_map *bmap, __isl_keep isl_basic_set *dom)
4390 int i;
4391 int common = 0;
4392 int other;
4393 unsigned bmap_n_div;
4395 bmap_n_div = isl_basic_map_dim(bmap, isl_dim_div);
4397 for (i = 0; i < dom->n_div; ++i) {
4398 int pos;
4400 pos = find_context_div(bmap, dom, i);
4401 if (pos < 0)
4402 return isl_basic_map_free(bmap);
4403 if (pos < bmap_n_div)
4404 common++;
4406 other = bmap_n_div - common;
4407 if (dom->n_div - common > 0) {
4408 bmap = isl_basic_map_cow(bmap);
4409 bmap = isl_basic_map_extend(bmap, dom->n_div - common, 0, 0);
4410 if (!bmap)
4411 return NULL;
4413 for (i = 0; i < dom->n_div; ++i) {
4414 int pos = find_context_div(bmap, dom, i);
4415 if (pos < 0)
4416 bmap = isl_basic_map_free(bmap);
4417 if (pos >= bmap_n_div) {
4418 pos = isl_basic_map_alloc_div(bmap);
4419 if (pos < 0)
4420 goto error;
4421 isl_int_set_si(bmap->div[pos][0], 0);
4422 bmap_n_div++;
4424 if (pos != other + i)
4425 bmap = isl_basic_map_swap_div(bmap, pos, other + i);
4427 return bmap;
4428 error:
4429 isl_basic_map_free(bmap);
4430 return NULL;
4433 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4434 * some obvious symmetries.
4436 * We make sure the divs in the domain are properly ordered,
4437 * because they will be added one by one in the given order
4438 * during the construction of the solution map.
4439 * Furthermore, make sure that the known integer divisions
4440 * appear before any unknown integer division because the solution
4441 * may depend on the known integer divisions, while anything that
4442 * depends on any variable starting from the first unknown integer
4443 * division is ignored in sol_pma_add.
4445 static struct isl_sol *basic_map_partial_lexopt_base_sol(
4446 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4447 __isl_give isl_set **empty, int max,
4448 struct isl_sol *(*init)(__isl_keep isl_basic_map *bmap,
4449 __isl_take isl_basic_set *dom, int track_empty, int max))
4451 struct isl_tab *tab;
4452 struct isl_sol *sol = NULL;
4453 struct isl_context *context;
4455 if (dom->n_div) {
4456 dom = isl_basic_set_sort_divs(dom);
4457 bmap = align_context_divs(bmap, dom);
4459 sol = init(bmap, dom, !!empty, max);
4460 if (!sol)
4461 goto error;
4463 context = sol->context;
4464 if (isl_basic_set_plain_is_empty(context->op->peek_basic_set(context)))
4465 /* nothing */;
4466 else if (isl_basic_map_plain_is_empty(bmap)) {
4467 if (sol->add_empty)
4468 sol->add_empty(sol,
4469 isl_basic_set_copy(context->op->peek_basic_set(context)));
4470 } else {
4471 tab = tab_for_lexmin(bmap,
4472 context->op->peek_basic_set(context), 1, max);
4473 tab = context->op->detect_nonnegative_parameters(context, tab);
4474 find_solutions_main(sol, tab);
4476 if (sol->error)
4477 goto error;
4479 isl_basic_map_free(bmap);
4480 return sol;
4481 error:
4482 sol_free(sol);
4483 isl_basic_map_free(bmap);
4484 return NULL;
4487 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4488 * some obvious symmetries.
4490 * We call basic_map_partial_lexopt_base_sol and extract the results.
4492 static __isl_give isl_map *basic_map_partial_lexopt_base(
4493 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4494 __isl_give isl_set **empty, int max)
4496 isl_map *result = NULL;
4497 struct isl_sol *sol;
4498 struct isl_sol_map *sol_map;
4500 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
4501 &sol_map_init);
4502 if (!sol)
4503 return NULL;
4504 sol_map = (struct isl_sol_map *) sol;
4506 result = isl_map_copy(sol_map->map);
4507 if (empty)
4508 *empty = isl_set_copy(sol_map->empty);
4509 sol_free(&sol_map->sol);
4510 return result;
4513 /* Return a count of the number of occurrences of the "n" first
4514 * variables in the inequality constraints of "bmap".
4516 static __isl_give int *count_occurrences(__isl_keep isl_basic_map *bmap,
4517 int n)
4519 int i, j;
4520 isl_ctx *ctx;
4521 int *occurrences;
4523 if (!bmap)
4524 return NULL;
4525 ctx = isl_basic_map_get_ctx(bmap);
4526 occurrences = isl_calloc_array(ctx, int, n);
4527 if (!occurrences)
4528 return NULL;
4530 for (i = 0; i < bmap->n_ineq; ++i) {
4531 for (j = 0; j < n; ++j) {
4532 if (!isl_int_is_zero(bmap->ineq[i][1 + j]))
4533 occurrences[j]++;
4537 return occurrences;
4540 /* Do all of the "n" variables with non-zero coefficients in "c"
4541 * occur in exactly a single constraint.
4542 * "occurrences" is an array of length "n" containing the number
4543 * of occurrences of each of the variables in the inequality constraints.
4545 static int single_occurrence(int n, isl_int *c, int *occurrences)
4547 int i;
4549 for (i = 0; i < n; ++i) {
4550 if (isl_int_is_zero(c[i]))
4551 continue;
4552 if (occurrences[i] != 1)
4553 return 0;
4556 return 1;
4559 /* Do all of the "n" initial variables that occur in inequality constraint
4560 * "ineq" of "bmap" only occur in that constraint?
4562 static int all_single_occurrence(__isl_keep isl_basic_map *bmap, int ineq,
4563 int n)
4565 int i, j;
4567 for (i = 0; i < n; ++i) {
4568 if (isl_int_is_zero(bmap->ineq[ineq][1 + i]))
4569 continue;
4570 for (j = 0; j < bmap->n_ineq; ++j) {
4571 if (j == ineq)
4572 continue;
4573 if (!isl_int_is_zero(bmap->ineq[j][1 + i]))
4574 return 0;
4578 return 1;
4581 /* Structure used during detection of parallel constraints.
4582 * n_in: number of "input" variables: isl_dim_param + isl_dim_in
4583 * n_out: number of "output" variables: isl_dim_out + isl_dim_div
4584 * val: the coefficients of the output variables
4586 struct isl_constraint_equal_info {
4587 unsigned n_in;
4588 unsigned n_out;
4589 isl_int *val;
4592 /* Check whether the coefficients of the output variables
4593 * of the constraint in "entry" are equal to info->val.
4595 static isl_bool constraint_equal(const void *entry, const void *val)
4597 isl_int **row = (isl_int **)entry;
4598 const struct isl_constraint_equal_info *info = val;
4599 int eq;
4601 eq = isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
4602 return isl_bool_ok(eq);
4605 /* Check whether "bmap" has a pair of constraints that have
4606 * the same coefficients for the output variables.
4607 * Note that the coefficients of the existentially quantified
4608 * variables need to be zero since the existentially quantified
4609 * of the result are usually not the same as those of the input.
4610 * Furthermore, check that each of the input variables that occur
4611 * in those constraints does not occur in any other constraint.
4612 * If so, return true and return the row indices of the two constraints
4613 * in *first and *second.
4615 static isl_bool parallel_constraints(__isl_keep isl_basic_map *bmap,
4616 int *first, int *second)
4618 int i;
4619 isl_ctx *ctx;
4620 int *occurrences = NULL;
4621 struct isl_hash_table *table = NULL;
4622 struct isl_hash_table_entry *entry;
4623 struct isl_constraint_equal_info info;
4624 isl_size nparam, n_in, n_out, n_div;
4626 ctx = isl_basic_map_get_ctx(bmap);
4627 table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4628 if (!table)
4629 goto error;
4631 nparam = isl_basic_map_dim(bmap, isl_dim_param);
4632 n_in = isl_basic_map_dim(bmap, isl_dim_in);
4633 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4634 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4635 if (nparam < 0 || n_in < 0 || n_out < 0 || n_div < 0)
4636 goto error;
4637 info.n_in = nparam + n_in;
4638 occurrences = count_occurrences(bmap, info.n_in);
4639 if (info.n_in && !occurrences)
4640 goto error;
4641 info.n_out = n_out + n_div;
4642 for (i = 0; i < bmap->n_ineq; ++i) {
4643 uint32_t hash;
4645 info.val = bmap->ineq[i] + 1 + info.n_in;
4646 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4647 continue;
4648 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4649 continue;
4650 if (!single_occurrence(info.n_in, bmap->ineq[i] + 1,
4651 occurrences))
4652 continue;
4653 hash = isl_seq_get_hash(info.val, info.n_out);
4654 entry = isl_hash_table_find(ctx, table, hash,
4655 constraint_equal, &info, 1);
4656 if (!entry)
4657 goto error;
4658 if (entry->data)
4659 break;
4660 entry->data = &bmap->ineq[i];
4663 if (i < bmap->n_ineq) {
4664 *first = ((isl_int **)entry->data) - bmap->ineq;
4665 *second = i;
4668 isl_hash_table_free(ctx, table);
4669 free(occurrences);
4671 return isl_bool_ok(i < bmap->n_ineq);
4672 error:
4673 isl_hash_table_free(ctx, table);
4674 free(occurrences);
4675 return isl_bool_error;
4678 /* Given a set of upper bounds in "var", add constraints to "bset"
4679 * that make the i-th bound smallest.
4681 * In particular, if there are n bounds b_i, then add the constraints
4683 * b_i <= b_j for j > i
4684 * b_i < b_j for j < i
4686 static __isl_give isl_basic_set *select_minimum(__isl_take isl_basic_set *bset,
4687 __isl_keep isl_mat *var, int i)
4689 isl_ctx *ctx;
4690 int j, k;
4692 ctx = isl_mat_get_ctx(var);
4694 for (j = 0; j < var->n_row; ++j) {
4695 if (j == i)
4696 continue;
4697 k = isl_basic_set_alloc_inequality(bset);
4698 if (k < 0)
4699 goto error;
4700 isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4701 ctx->negone, var->row[i], var->n_col);
4702 isl_int_set_si(bset->ineq[k][var->n_col], 0);
4703 if (j < i)
4704 isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4707 bset = isl_basic_set_finalize(bset);
4709 return bset;
4710 error:
4711 isl_basic_set_free(bset);
4712 return NULL;
4715 /* Given a set of upper bounds on the last "input" variable m,
4716 * construct a set that assigns the minimal upper bound to m, i.e.,
4717 * construct a set that divides the space into cells where one
4718 * of the upper bounds is smaller than all the others and assign
4719 * this upper bound to m.
4721 * In particular, if there are n bounds b_i, then the result
4722 * consists of n basic sets, each one of the form
4724 * m = b_i
4725 * b_i <= b_j for j > i
4726 * b_i < b_j for j < i
4728 static __isl_give isl_set *set_minimum(__isl_take isl_space *space,
4729 __isl_take isl_mat *var)
4731 int i, k;
4732 isl_basic_set *bset = NULL;
4733 isl_set *set = NULL;
4735 if (!space || !var)
4736 goto error;
4738 set = isl_set_alloc_space(isl_space_copy(space),
4739 var->n_row, ISL_SET_DISJOINT);
4741 for (i = 0; i < var->n_row; ++i) {
4742 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
4743 1, var->n_row - 1);
4744 k = isl_basic_set_alloc_equality(bset);
4745 if (k < 0)
4746 goto error;
4747 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4748 isl_int_set_si(bset->eq[k][var->n_col], -1);
4749 bset = select_minimum(bset, var, i);
4750 set = isl_set_add_basic_set(set, bset);
4753 isl_space_free(space);
4754 isl_mat_free(var);
4755 return set;
4756 error:
4757 isl_basic_set_free(bset);
4758 isl_set_free(set);
4759 isl_space_free(space);
4760 isl_mat_free(var);
4761 return NULL;
4764 /* Given that the last input variable of "bmap" represents the minimum
4765 * of the bounds in "cst", check whether we need to split the domain
4766 * based on which bound attains the minimum.
4768 * A split is needed when the minimum appears in an integer division
4769 * or in an equality. Otherwise, it is only needed if it appears in
4770 * an upper bound that is different from the upper bounds on which it
4771 * is defined.
4773 static isl_bool need_split_basic_map(__isl_keep isl_basic_map *bmap,
4774 __isl_keep isl_mat *cst)
4776 int i, j;
4777 isl_bool involves;
4778 isl_size total;
4779 unsigned pos;
4781 pos = cst->n_col - 1;
4782 total = isl_basic_map_dim(bmap, isl_dim_all);
4783 if (total < 0)
4784 return isl_bool_error;
4786 involves = isl_basic_map_any_div_involves_vars(bmap, pos, 1);
4787 if (involves < 0 || involves)
4788 return involves;
4790 for (i = 0; i < bmap->n_eq; ++i)
4791 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4792 return isl_bool_true;
4794 for (i = 0; i < bmap->n_ineq; ++i) {
4795 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4796 continue;
4797 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4798 return isl_bool_true;
4799 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4800 total - pos - 1) >= 0)
4801 return isl_bool_true;
4803 for (j = 0; j < cst->n_row; ++j)
4804 if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4805 break;
4806 if (j >= cst->n_row)
4807 return isl_bool_true;
4810 return isl_bool_false;
4813 /* Given that the last set variable of "bset" represents the minimum
4814 * of the bounds in "cst", check whether we need to split the domain
4815 * based on which bound attains the minimum.
4817 * We simply call need_split_basic_map here. This is safe because
4818 * the position of the minimum is computed from "cst" and not
4819 * from "bmap".
4821 static isl_bool need_split_basic_set(__isl_keep isl_basic_set *bset,
4822 __isl_keep isl_mat *cst)
4824 return need_split_basic_map(bset_to_bmap(bset), cst);
4827 /* Given that the last set variable of "set" represents the minimum
4828 * of the bounds in "cst", check whether we need to split the domain
4829 * based on which bound attains the minimum.
4831 static isl_bool need_split_set(__isl_keep isl_set *set, __isl_keep isl_mat *cst)
4833 int i;
4835 for (i = 0; i < set->n; ++i) {
4836 isl_bool split;
4838 split = need_split_basic_set(set->p[i], cst);
4839 if (split < 0 || split)
4840 return split;
4843 return isl_bool_false;
4846 /* Given a map of which the last input variable is the minimum
4847 * of the bounds in "cst", split each basic set in the set
4848 * in pieces where one of the bounds is (strictly) smaller than the others.
4849 * This subdivision is given in "min_expr".
4850 * The variable is subsequently projected out.
4852 * We only do the split when it is needed.
4853 * For example if the last input variable m = min(a,b) and the only
4854 * constraints in the given basic set are lower bounds on m,
4855 * i.e., l <= m = min(a,b), then we can simply project out m
4856 * to obtain l <= a and l <= b, without having to split on whether
4857 * m is equal to a or b.
4859 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4860 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4862 isl_size n_in;
4863 int i;
4864 isl_space *space;
4865 isl_map *res;
4867 n_in = isl_map_dim(opt, isl_dim_in);
4868 if (n_in < 0 || !min_expr || !cst)
4869 goto error;
4871 space = isl_map_get_space(opt);
4872 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
4873 res = isl_map_empty(space);
4875 for (i = 0; i < opt->n; ++i) {
4876 isl_map *map;
4877 isl_bool split;
4879 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4880 split = need_split_basic_map(opt->p[i], cst);
4881 if (split < 0)
4882 map = isl_map_free(map);
4883 else if (split)
4884 map = isl_map_intersect_domain(map,
4885 isl_set_copy(min_expr));
4886 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4888 res = isl_map_union_disjoint(res, map);
4891 isl_map_free(opt);
4892 isl_set_free(min_expr);
4893 isl_mat_free(cst);
4894 return res;
4895 error:
4896 isl_map_free(opt);
4897 isl_set_free(min_expr);
4898 isl_mat_free(cst);
4899 return NULL;
4902 /* Given a set of which the last set variable is the minimum
4903 * of the bounds in "cst", split each basic set in the set
4904 * in pieces where one of the bounds is (strictly) smaller than the others.
4905 * This subdivision is given in "min_expr".
4906 * The variable is subsequently projected out.
4908 static __isl_give isl_set *split(__isl_take isl_set *empty,
4909 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4911 isl_map *map;
4913 map = isl_map_from_domain(empty);
4914 map = split_domain(map, min_expr, cst);
4915 empty = isl_map_domain(map);
4917 return empty;
4920 static __isl_give isl_map *basic_map_partial_lexopt(
4921 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4922 __isl_give isl_set **empty, int max);
4924 /* This function is called from basic_map_partial_lexopt_symm.
4925 * The last variable of "bmap" and "dom" corresponds to the minimum
4926 * of the bounds in "cst". "map_space" is the space of the original
4927 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
4928 * is the space of the original domain.
4930 * We recursively call basic_map_partial_lexopt and then plug in
4931 * the definition of the minimum in the result.
4933 static __isl_give isl_map *basic_map_partial_lexopt_symm_core(
4934 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4935 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
4936 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
4938 isl_map *opt;
4939 isl_set *min_expr;
4941 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
4943 opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4945 if (empty) {
4946 *empty = split(*empty,
4947 isl_set_copy(min_expr), isl_mat_copy(cst));
4948 *empty = isl_set_reset_space(*empty, set_space);
4951 opt = split_domain(opt, min_expr, cst);
4952 opt = isl_map_reset_space(opt, map_space);
4954 return opt;
4957 /* Extract a domain from "bmap" for the purpose of computing
4958 * a lexicographic optimum.
4960 * This function is only called when the caller wants to compute a full
4961 * lexicographic optimum, i.e., without specifying a domain. In this case,
4962 * the caller is not interested in the part of the domain space where
4963 * there is no solution and the domain can be initialized to those constraints
4964 * of "bmap" that only involve the parameters and the input dimensions.
4965 * This relieves the parametric programming engine from detecting those
4966 * inequalities and transferring them to the context. More importantly,
4967 * it ensures that those inequalities are transferred first and not
4968 * intermixed with inequalities that actually split the domain.
4970 * If the caller does not require the absence of existentially quantified
4971 * variables in the result (i.e., if ISL_OPT_QE is not set in "flags"),
4972 * then the actual domain of "bmap" can be used. This ensures that
4973 * the domain does not need to be split at all just to separate out
4974 * pieces of the domain that do not have a solution from piece that do.
4975 * This domain cannot be used in general because it may involve
4976 * (unknown) existentially quantified variables which will then also
4977 * appear in the solution.
4979 static __isl_give isl_basic_set *extract_domain(__isl_keep isl_basic_map *bmap,
4980 unsigned flags)
4982 isl_size n_div;
4983 isl_size n_out;
4985 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4986 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4987 if (n_div < 0 || n_out < 0)
4988 return NULL;
4989 bmap = isl_basic_map_copy(bmap);
4990 if (ISL_FL_ISSET(flags, ISL_OPT_QE)) {
4991 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4992 isl_dim_div, 0, n_div);
4993 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4994 isl_dim_out, 0, n_out);
4996 return isl_basic_map_domain(bmap);
4999 #undef TYPE
5000 #define TYPE isl_map
5001 #undef SUFFIX
5002 #define SUFFIX
5003 #include "isl_tab_lexopt_templ.c"
5005 /* Extract the subsequence of the sample value of "tab"
5006 * starting at "pos" and of length "len".
5008 static __isl_give isl_vec *extract_sample_sequence(struct isl_tab *tab,
5009 int pos, int len)
5011 int i;
5012 isl_ctx *ctx;
5013 isl_vec *v;
5015 ctx = isl_tab_get_ctx(tab);
5016 v = isl_vec_alloc(ctx, len);
5017 if (!v)
5018 return NULL;
5019 for (i = 0; i < len; ++i) {
5020 if (!tab->var[pos + i].is_row) {
5021 isl_int_set_si(v->el[i], 0);
5022 } else {
5023 int row;
5025 row = tab->var[pos + i].index;
5026 isl_int_divexact(v->el[i], tab->mat->row[row][1],
5027 tab->mat->row[row][0]);
5031 return v;
5034 /* Check if the sequence of variables starting at "pos"
5035 * represents a trivial solution according to "trivial".
5036 * That is, is the result of applying "trivial" to this sequence
5037 * equal to the zero vector?
5039 static isl_bool region_is_trivial(struct isl_tab *tab, int pos,
5040 __isl_keep isl_mat *trivial)
5042 isl_size n, len;
5043 isl_vec *v;
5044 isl_bool is_trivial;
5046 n = isl_mat_rows(trivial);
5047 if (n < 0)
5048 return isl_bool_error;
5050 if (n == 0)
5051 return isl_bool_false;
5053 len = isl_mat_cols(trivial);
5054 if (len < 0)
5055 return isl_bool_error;
5056 v = extract_sample_sequence(tab, pos, len);
5057 v = isl_mat_vec_product(isl_mat_copy(trivial), v);
5058 is_trivial = isl_vec_is_zero(v);
5059 isl_vec_free(v);
5061 return is_trivial;
5064 /* Global internal data for isl_tab_basic_set_non_trivial_lexmin.
5066 * "n_op" is the number of initial coordinates to optimize,
5067 * as passed to isl_tab_basic_set_non_trivial_lexmin.
5068 * "region" is the "n_region"-sized array of regions passed
5069 * to isl_tab_basic_set_non_trivial_lexmin.
5071 * "tab" is the tableau that corresponds to the ILP problem.
5072 * "local" is an array of local data structure, one for each
5073 * (potential) level of the backtracking procedure of
5074 * isl_tab_basic_set_non_trivial_lexmin.
5075 * "v" is a pre-allocated vector that can be used for adding
5076 * constraints to the tableau.
5078 * "sol" contains the best solution found so far.
5079 * It is initialized to a vector of size zero.
5081 struct isl_lexmin_data {
5082 int n_op;
5083 int n_region;
5084 struct isl_trivial_region *region;
5086 struct isl_tab *tab;
5087 struct isl_local_region *local;
5088 isl_vec *v;
5090 isl_vec *sol;
5093 /* Return the index of the first trivial region, "n_region" if all regions
5094 * are non-trivial or -1 in case of error.
5096 static int first_trivial_region(struct isl_lexmin_data *data)
5098 int i;
5100 for (i = 0; i < data->n_region; ++i) {
5101 isl_bool trivial;
5102 trivial = region_is_trivial(data->tab, data->region[i].pos,
5103 data->region[i].trivial);
5104 if (trivial < 0)
5105 return -1;
5106 if (trivial)
5107 return i;
5110 return data->n_region;
5113 /* Check if the solution is optimal, i.e., whether the first
5114 * n_op entries are zero.
5116 static int is_optimal(__isl_keep isl_vec *sol, int n_op)
5118 int i;
5120 for (i = 0; i < n_op; ++i)
5121 if (!isl_int_is_zero(sol->el[1 + i]))
5122 return 0;
5123 return 1;
5126 /* Add constraints to "tab" that ensure that any solution is significantly
5127 * better than that represented by "sol". That is, find the first
5128 * relevant (within first n_op) non-zero coefficient and force it (along
5129 * with all previous coefficients) to be zero.
5130 * If the solution is already optimal (all relevant coefficients are zero),
5131 * then just mark the table as empty.
5132 * "n_zero" is the number of coefficients that have been forced zero
5133 * by previous calls to this function at the same level.
5134 * Return the updated number of forced zero coefficients or -1 on error.
5136 * This function assumes that at least 2 * (n_op - n_zero) more rows and
5137 * at least 2 * (n_op - n_zero) more elements in the constraint array
5138 * are available in the tableau.
5140 static int force_better_solution(struct isl_tab *tab,
5141 __isl_keep isl_vec *sol, int n_op, int n_zero)
5143 int i, n;
5144 isl_ctx *ctx;
5145 isl_vec *v = NULL;
5147 if (!sol)
5148 return -1;
5150 for (i = n_zero; i < n_op; ++i)
5151 if (!isl_int_is_zero(sol->el[1 + i]))
5152 break;
5154 if (i == n_op) {
5155 if (isl_tab_mark_empty(tab) < 0)
5156 return -1;
5157 return n_op;
5160 ctx = isl_vec_get_ctx(sol);
5161 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5162 if (!v)
5163 return -1;
5165 n = i + 1;
5166 for (; i >= n_zero; --i) {
5167 v = isl_vec_clr(v);
5168 isl_int_set_si(v->el[1 + i], -1);
5169 if (add_lexmin_eq(tab, v->el) < 0)
5170 goto error;
5173 isl_vec_free(v);
5174 return n;
5175 error:
5176 isl_vec_free(v);
5177 return -1;
5180 /* Fix triviality direction "dir" of the given region to zero.
5182 * This function assumes that at least two more rows and at least
5183 * two more elements in the constraint array are available in the tableau.
5185 static isl_stat fix_zero(struct isl_tab *tab, struct isl_trivial_region *region,
5186 int dir, struct isl_lexmin_data *data)
5188 isl_size len;
5190 data->v = isl_vec_clr(data->v);
5191 if (!data->v)
5192 return isl_stat_error;
5193 len = isl_mat_cols(region->trivial);
5194 if (len < 0)
5195 return isl_stat_error;
5196 isl_seq_cpy(data->v->el + 1 + region->pos, region->trivial->row[dir],
5197 len);
5198 if (add_lexmin_eq(tab, data->v->el) < 0)
5199 return isl_stat_error;
5201 return isl_stat_ok;
5204 /* This function selects case "side" for non-triviality region "region",
5205 * assuming all the equality constraints have been imposed already.
5206 * In particular, the triviality direction side/2 is made positive
5207 * if side is even and made negative if side is odd.
5209 * This function assumes that at least one more row and at least
5210 * one more element in the constraint array are available in the tableau.
5212 static struct isl_tab *pos_neg(struct isl_tab *tab,
5213 struct isl_trivial_region *region,
5214 int side, struct isl_lexmin_data *data)
5216 isl_size len;
5218 data->v = isl_vec_clr(data->v);
5219 if (!data->v)
5220 goto error;
5221 isl_int_set_si(data->v->el[0], -1);
5222 len = isl_mat_cols(region->trivial);
5223 if (len < 0)
5224 goto error;
5225 if (side % 2 == 0)
5226 isl_seq_cpy(data->v->el + 1 + region->pos,
5227 region->trivial->row[side / 2], len);
5228 else
5229 isl_seq_neg(data->v->el + 1 + region->pos,
5230 region->trivial->row[side / 2], len);
5231 return add_lexmin_ineq(tab, data->v->el);
5232 error:
5233 isl_tab_free(tab);
5234 return NULL;
5237 /* Local data at each level of the backtracking procedure of
5238 * isl_tab_basic_set_non_trivial_lexmin.
5240 * "update" is set if a solution has been found in the current case
5241 * of this level, such that a better solution needs to be enforced
5242 * in the next case.
5243 * "n_zero" is the number of initial coordinates that have already
5244 * been forced to be zero at this level.
5245 * "region" is the non-triviality region considered at this level.
5246 * "side" is the index of the current case at this level.
5247 * "n" is the number of triviality directions.
5248 * "snap" is a snapshot of the tableau holding a state that needs
5249 * to be satisfied by all subsequent cases.
5251 struct isl_local_region {
5252 int update;
5253 int n_zero;
5254 int region;
5255 int side;
5256 int n;
5257 struct isl_tab_undo *snap;
5260 /* Initialize the global data structure "data" used while solving
5261 * the ILP problem "bset".
5263 static isl_stat init_lexmin_data(struct isl_lexmin_data *data,
5264 __isl_keep isl_basic_set *bset)
5266 isl_ctx *ctx;
5268 ctx = isl_basic_set_get_ctx(bset);
5270 data->tab = tab_for_lexmin(bset, NULL, 0, 0);
5271 if (!data->tab)
5272 return isl_stat_error;
5274 data->v = isl_vec_alloc(ctx, 1 + data->tab->n_var);
5275 if (!data->v)
5276 return isl_stat_error;
5277 data->local = isl_calloc_array(ctx, struct isl_local_region,
5278 data->n_region);
5279 if (data->n_region && !data->local)
5280 return isl_stat_error;
5282 data->sol = isl_vec_alloc(ctx, 0);
5284 return isl_stat_ok;
5287 /* Mark all outer levels as requiring a better solution
5288 * in the next cases.
5290 static void update_outer_levels(struct isl_lexmin_data *data, int level)
5292 int i;
5294 for (i = 0; i < level; ++i)
5295 data->local[i].update = 1;
5298 /* Initialize "local" to refer to region "region" and
5299 * to initiate processing at this level.
5301 static isl_stat init_local_region(struct isl_local_region *local, int region,
5302 struct isl_lexmin_data *data)
5304 isl_size n = isl_mat_rows(data->region[region].trivial);
5306 if (n < 0)
5307 return isl_stat_error;
5308 local->n = n;
5309 local->region = region;
5310 local->side = 0;
5311 local->update = 0;
5312 local->n_zero = 0;
5314 return isl_stat_ok;
5317 /* What to do next after entering a level of the backtracking procedure.
5319 * error: some error has occurred; abort
5320 * done: an optimal solution has been found; stop search
5321 * backtrack: backtrack to the previous level
5322 * handle: add the constraints for the current level and
5323 * move to the next level
5325 enum isl_next {
5326 isl_next_error = -1,
5327 isl_next_done,
5328 isl_next_backtrack,
5329 isl_next_handle,
5332 /* Have all cases of the current region been considered?
5333 * If there are n directions, then there are 2n cases.
5335 * The constraints in the current tableau are imposed
5336 * in all subsequent cases. This means that if the current
5337 * tableau is empty, then none of those cases should be considered
5338 * anymore and all cases have effectively been considered.
5340 static int finished_all_cases(struct isl_local_region *local,
5341 struct isl_lexmin_data *data)
5343 if (data->tab->empty)
5344 return 1;
5345 return local->side >= 2 * local->n;
5348 /* Enter level "level" of the backtracking search and figure out
5349 * what to do next. "init" is set if the level was entered
5350 * from a higher level and needs to be initialized.
5351 * Otherwise, the level is entered as a result of backtracking and
5352 * the tableau needs to be restored to a position that can
5353 * be used for the next case at this level.
5354 * The snapshot is assumed to have been saved in the previous case,
5355 * before the constraints specific to that case were added.
5357 * In the initialization case, the local region is initialized
5358 * to point to the first violated region.
5359 * If the constraints of all regions are satisfied by the current
5360 * sample of the tableau, then tell the caller to continue looking
5361 * for a better solution or to stop searching if an optimal solution
5362 * has been found.
5364 * If the tableau is empty or if all cases at the current level
5365 * have been considered, then the caller needs to backtrack as well.
5367 static enum isl_next enter_level(int level, int init,
5368 struct isl_lexmin_data *data)
5370 struct isl_local_region *local = &data->local[level];
5372 if (init) {
5373 int r;
5375 data->tab = cut_to_integer_lexmin(data->tab, CUT_ONE);
5376 if (!data->tab)
5377 return isl_next_error;
5378 if (data->tab->empty)
5379 return isl_next_backtrack;
5380 r = first_trivial_region(data);
5381 if (r < 0)
5382 return isl_next_error;
5383 if (r == data->n_region) {
5384 update_outer_levels(data, level);
5385 isl_vec_free(data->sol);
5386 data->sol = isl_tab_get_sample_value(data->tab);
5387 if (!data->sol)
5388 return isl_next_error;
5389 if (is_optimal(data->sol, data->n_op))
5390 return isl_next_done;
5391 return isl_next_backtrack;
5393 if (level >= data->n_region)
5394 isl_die(isl_vec_get_ctx(data->v), isl_error_internal,
5395 "nesting level too deep",
5396 return isl_next_error);
5397 if (init_local_region(local, r, data) < 0)
5398 return isl_next_error;
5399 if (isl_tab_extend_cons(data->tab,
5400 2 * local->n + 2 * data->n_op) < 0)
5401 return isl_next_error;
5402 } else {
5403 if (isl_tab_rollback(data->tab, local->snap) < 0)
5404 return isl_next_error;
5407 if (finished_all_cases(local, data))
5408 return isl_next_backtrack;
5409 return isl_next_handle;
5412 /* If a solution has been found in the previous case at this level
5413 * (marked by local->update being set), then add constraints
5414 * that enforce a better solution in the present and all following cases.
5415 * The constraints only need to be imposed once because they are
5416 * included in the snapshot (taken in pick_side) that will be used in
5417 * subsequent cases.
5419 static isl_stat better_next_side(struct isl_local_region *local,
5420 struct isl_lexmin_data *data)
5422 if (!local->update)
5423 return isl_stat_ok;
5425 local->n_zero = force_better_solution(data->tab,
5426 data->sol, data->n_op, local->n_zero);
5427 if (local->n_zero < 0)
5428 return isl_stat_error;
5430 local->update = 0;
5432 return isl_stat_ok;
5435 /* Add constraints to data->tab that select the current case (local->side)
5436 * at the current level.
5438 * If the linear combinations v should not be zero, then the cases are
5439 * v_0 >= 1
5440 * v_0 <= -1
5441 * v_0 = 0 and v_1 >= 1
5442 * v_0 = 0 and v_1 <= -1
5443 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5444 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5445 * ...
5446 * in this order.
5448 * A snapshot is taken after the equality constraint (if any) has been added
5449 * such that the next case can start off from this position.
5450 * The rollback to this position is performed in enter_level.
5452 static isl_stat pick_side(struct isl_local_region *local,
5453 struct isl_lexmin_data *data)
5455 struct isl_trivial_region *region;
5456 int side, base;
5458 region = &data->region[local->region];
5459 side = local->side;
5460 base = 2 * (side/2);
5462 if (side == base && base >= 2 &&
5463 fix_zero(data->tab, region, base / 2 - 1, data) < 0)
5464 return isl_stat_error;
5466 local->snap = isl_tab_snap(data->tab);
5467 if (isl_tab_push_basis(data->tab) < 0)
5468 return isl_stat_error;
5470 data->tab = pos_neg(data->tab, region, side, data);
5471 if (!data->tab)
5472 return isl_stat_error;
5473 return isl_stat_ok;
5476 /* Free the memory associated to "data".
5478 static void clear_lexmin_data(struct isl_lexmin_data *data)
5480 free(data->local);
5481 isl_vec_free(data->v);
5482 isl_tab_free(data->tab);
5485 /* Return the lexicographically smallest non-trivial solution of the
5486 * given ILP problem.
5488 * All variables are assumed to be non-negative.
5490 * n_op is the number of initial coordinates to optimize.
5491 * That is, once a solution has been found, we will only continue looking
5492 * for solutions that result in significantly better values for those
5493 * initial coordinates. That is, we only continue looking for solutions
5494 * that increase the number of initial zeros in this sequence.
5496 * A solution is non-trivial, if it is non-trivial on each of the
5497 * specified regions. Each region represents a sequence of
5498 * triviality directions on a sequence of variables that starts
5499 * at a given position. A solution is non-trivial on such a region if
5500 * at least one of the triviality directions is non-zero
5501 * on that sequence of variables.
5503 * Whenever a conflict is encountered, all constraints involved are
5504 * reported to the caller through a call to "conflict".
5506 * We perform a simple branch-and-bound backtracking search.
5507 * Each level in the search represents an initially trivial region
5508 * that is forced to be non-trivial.
5509 * At each level we consider 2 * n cases, where n
5510 * is the number of triviality directions.
5511 * In terms of those n directions v_i, we consider the cases
5512 * v_0 >= 1
5513 * v_0 <= -1
5514 * v_0 = 0 and v_1 >= 1
5515 * v_0 = 0 and v_1 <= -1
5516 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5517 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5518 * ...
5519 * in this order.
5521 __isl_give isl_vec *isl_tab_basic_set_non_trivial_lexmin(
5522 __isl_take isl_basic_set *bset, int n_op, int n_region,
5523 struct isl_trivial_region *region,
5524 int (*conflict)(int con, void *user), void *user)
5526 struct isl_lexmin_data data = { n_op, n_region, region };
5527 int level, init;
5529 if (!bset)
5530 return NULL;
5532 if (init_lexmin_data(&data, bset) < 0)
5533 goto error;
5534 data.tab->conflict = conflict;
5535 data.tab->conflict_user = user;
5537 level = 0;
5538 init = 1;
5540 while (level >= 0) {
5541 enum isl_next next;
5542 struct isl_local_region *local = &data.local[level];
5544 next = enter_level(level, init, &data);
5545 if (next < 0)
5546 goto error;
5547 if (next == isl_next_done)
5548 break;
5549 if (next == isl_next_backtrack) {
5550 level--;
5551 init = 0;
5552 continue;
5555 if (better_next_side(local, &data) < 0)
5556 goto error;
5557 if (pick_side(local, &data) < 0)
5558 goto error;
5560 local->side++;
5561 level++;
5562 init = 1;
5565 clear_lexmin_data(&data);
5566 isl_basic_set_free(bset);
5568 return data.sol;
5569 error:
5570 clear_lexmin_data(&data);
5571 isl_basic_set_free(bset);
5572 isl_vec_free(data.sol);
5573 return NULL;
5576 /* Wrapper for a tableau that is used for computing
5577 * the lexicographically smallest rational point of a non-negative set.
5578 * This point is represented by the sample value of "tab",
5579 * unless "tab" is empty.
5581 struct isl_tab_lexmin {
5582 isl_ctx *ctx;
5583 struct isl_tab *tab;
5586 /* Free "tl" and return NULL.
5588 __isl_null isl_tab_lexmin *isl_tab_lexmin_free(__isl_take isl_tab_lexmin *tl)
5590 if (!tl)
5591 return NULL;
5592 isl_ctx_deref(tl->ctx);
5593 isl_tab_free(tl->tab);
5594 free(tl);
5596 return NULL;
5599 /* Construct an isl_tab_lexmin for computing
5600 * the lexicographically smallest rational point in "bset",
5601 * assuming that all variables are non-negative.
5603 __isl_give isl_tab_lexmin *isl_tab_lexmin_from_basic_set(
5604 __isl_take isl_basic_set *bset)
5606 isl_ctx *ctx;
5607 isl_tab_lexmin *tl;
5609 if (!bset)
5610 return NULL;
5612 ctx = isl_basic_set_get_ctx(bset);
5613 tl = isl_calloc_type(ctx, struct isl_tab_lexmin);
5614 if (!tl)
5615 goto error;
5616 tl->ctx = ctx;
5617 isl_ctx_ref(ctx);
5618 tl->tab = tab_for_lexmin(bset, NULL, 0, 0);
5619 isl_basic_set_free(bset);
5620 if (!tl->tab)
5621 return isl_tab_lexmin_free(tl);
5622 return tl;
5623 error:
5624 isl_basic_set_free(bset);
5625 isl_tab_lexmin_free(tl);
5626 return NULL;
5629 /* Return the dimension of the set represented by "tl".
5631 int isl_tab_lexmin_dim(__isl_keep isl_tab_lexmin *tl)
5633 return tl ? tl->tab->n_var : -1;
5636 /* Add the equality with coefficients "eq" to "tl", updating the optimal
5637 * solution if needed.
5638 * The equality is added as two opposite inequality constraints.
5640 __isl_give isl_tab_lexmin *isl_tab_lexmin_add_eq(__isl_take isl_tab_lexmin *tl,
5641 isl_int *eq)
5643 unsigned n_var;
5645 if (!tl || !eq)
5646 return isl_tab_lexmin_free(tl);
5648 if (isl_tab_extend_cons(tl->tab, 2) < 0)
5649 return isl_tab_lexmin_free(tl);
5650 n_var = tl->tab->n_var;
5651 isl_seq_neg(eq, eq, 1 + n_var);
5652 tl->tab = add_lexmin_ineq(tl->tab, eq);
5653 isl_seq_neg(eq, eq, 1 + n_var);
5654 tl->tab = add_lexmin_ineq(tl->tab, eq);
5656 if (!tl->tab)
5657 return isl_tab_lexmin_free(tl);
5659 return tl;
5662 /* Add cuts to "tl" until the sample value reaches an integer value or
5663 * until the result becomes empty.
5665 __isl_give isl_tab_lexmin *isl_tab_lexmin_cut_to_integer(
5666 __isl_take isl_tab_lexmin *tl)
5668 if (!tl)
5669 return NULL;
5670 tl->tab = cut_to_integer_lexmin(tl->tab, CUT_ONE);
5671 if (!tl->tab)
5672 return isl_tab_lexmin_free(tl);
5673 return tl;
5676 /* Return the lexicographically smallest rational point in the basic set
5677 * from which "tl" was constructed.
5678 * If the original input was empty, then return a zero-length vector.
5680 __isl_give isl_vec *isl_tab_lexmin_get_solution(__isl_keep isl_tab_lexmin *tl)
5682 if (!tl)
5683 return NULL;
5684 if (tl->tab->empty)
5685 return isl_vec_alloc(tl->ctx, 0);
5686 else
5687 return isl_tab_get_sample_value(tl->tab);
5690 struct isl_sol_pma {
5691 struct isl_sol sol;
5692 isl_pw_multi_aff *pma;
5693 isl_set *empty;
5696 static void sol_pma_free(struct isl_sol *sol)
5698 struct isl_sol_pma *sol_pma = (struct isl_sol_pma *) sol;
5699 isl_pw_multi_aff_free(sol_pma->pma);
5700 isl_set_free(sol_pma->empty);
5703 /* This function is called for parts of the context where there is
5704 * no solution, with "bset" corresponding to the context tableau.
5705 * Simply add the basic set to the set "empty".
5707 static void sol_pma_add_empty(struct isl_sol_pma *sol,
5708 __isl_take isl_basic_set *bset)
5710 if (!bset || !sol->empty)
5711 goto error;
5713 sol->empty = isl_set_grow(sol->empty, 1);
5714 bset = isl_basic_set_simplify(bset);
5715 bset = isl_basic_set_finalize(bset);
5716 sol->empty = isl_set_add_basic_set(sol->empty, bset);
5717 if (!sol->empty)
5718 sol->sol.error = 1;
5719 return;
5720 error:
5721 isl_basic_set_free(bset);
5722 sol->sol.error = 1;
5725 /* Given a basic set "dom" that represents the context and a tuple of
5726 * affine expressions "maff" defined over this domain, construct
5727 * an isl_pw_multi_aff with a single cell corresponding to "dom" and
5728 * the affine expressions in "maff".
5730 static void sol_pma_add(struct isl_sol_pma *sol,
5731 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *maff)
5733 isl_pw_multi_aff *pma;
5735 dom = isl_basic_set_simplify(dom);
5736 dom = isl_basic_set_finalize(dom);
5737 pma = isl_pw_multi_aff_alloc(isl_set_from_basic_set(dom), maff);
5738 sol->pma = isl_pw_multi_aff_add_disjoint(sol->pma, pma);
5739 if (!sol->pma)
5740 sol->sol.error = 1;
5743 static void sol_pma_add_empty_wrap(struct isl_sol *sol,
5744 __isl_take isl_basic_set *bset)
5746 sol_pma_add_empty((struct isl_sol_pma *)sol, bset);
5749 static void sol_pma_add_wrap(struct isl_sol *sol,
5750 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
5752 sol_pma_add((struct isl_sol_pma *)sol, dom, ma);
5755 /* Construct an isl_sol_pma structure for accumulating the solution.
5756 * If track_empty is set, then we also keep track of the parts
5757 * of the context where there is no solution.
5758 * If max is set, then we are solving a maximization, rather than
5759 * a minimization problem, which means that the variables in the
5760 * tableau have value "M - x" rather than "M + x".
5762 static struct isl_sol *sol_pma_init(__isl_keep isl_basic_map *bmap,
5763 __isl_take isl_basic_set *dom, int track_empty, int max)
5765 struct isl_sol_pma *sol_pma = NULL;
5766 isl_space *space;
5768 if (!bmap)
5769 goto error;
5771 sol_pma = isl_calloc_type(bmap->ctx, struct isl_sol_pma);
5772 if (!sol_pma)
5773 goto error;
5775 sol_pma->sol.free = &sol_pma_free;
5776 if (sol_init(&sol_pma->sol, bmap, dom, max) < 0)
5777 goto error;
5778 sol_pma->sol.add = &sol_pma_add_wrap;
5779 sol_pma->sol.add_empty = track_empty ? &sol_pma_add_empty_wrap : NULL;
5780 space = isl_space_copy(sol_pma->sol.space);
5781 sol_pma->pma = isl_pw_multi_aff_empty(space);
5782 if (!sol_pma->pma)
5783 goto error;
5785 if (track_empty) {
5786 sol_pma->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
5787 1, ISL_SET_DISJOINT);
5788 if (!sol_pma->empty)
5789 goto error;
5792 isl_basic_set_free(dom);
5793 return &sol_pma->sol;
5794 error:
5795 isl_basic_set_free(dom);
5796 sol_free(&sol_pma->sol);
5797 return NULL;
5800 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
5801 * some obvious symmetries.
5803 * We call basic_map_partial_lexopt_base_sol and extract the results.
5805 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_base_pw_multi_aff(
5806 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5807 __isl_give isl_set **empty, int max)
5809 isl_pw_multi_aff *result = NULL;
5810 struct isl_sol *sol;
5811 struct isl_sol_pma *sol_pma;
5813 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
5814 &sol_pma_init);
5815 if (!sol)
5816 return NULL;
5817 sol_pma = (struct isl_sol_pma *) sol;
5819 result = isl_pw_multi_aff_copy(sol_pma->pma);
5820 if (empty)
5821 *empty = isl_set_copy(sol_pma->empty);
5822 sol_free(&sol_pma->sol);
5823 return result;
5826 /* Given that the last input variable of "maff" represents the minimum
5827 * of some bounds, check whether we need to plug in the expression
5828 * of the minimum.
5830 * In particular, check if the last input variable appears in any
5831 * of the expressions in "maff".
5833 static isl_bool need_substitution(__isl_keep isl_multi_aff *maff)
5835 int i;
5836 isl_size n_in;
5837 unsigned pos;
5839 n_in = isl_multi_aff_dim(maff, isl_dim_in);
5840 if (n_in < 0)
5841 return isl_bool_error;
5842 pos = n_in - 1;
5844 for (i = 0; i < maff->n; ++i) {
5845 isl_bool involves;
5847 involves = isl_aff_involves_dims(maff->u.p[i],
5848 isl_dim_in, pos, 1);
5849 if (involves < 0 || involves)
5850 return involves;
5853 return isl_bool_false;
5856 /* Given a set of upper bounds on the last "input" variable m,
5857 * construct a piecewise affine expression that selects
5858 * the minimal upper bound to m, i.e.,
5859 * divide the space into cells where one
5860 * of the upper bounds is smaller than all the others and select
5861 * this upper bound on that cell.
5863 * In particular, if there are n bounds b_i, then the result
5864 * consists of n cell, each one of the form
5866 * b_i <= b_j for j > i
5867 * b_i < b_j for j < i
5869 * The affine expression on this cell is
5871 * b_i
5873 static __isl_give isl_pw_aff *set_minimum_pa(__isl_take isl_space *space,
5874 __isl_take isl_mat *var)
5876 int i;
5877 isl_aff *aff = NULL;
5878 isl_basic_set *bset = NULL;
5879 isl_pw_aff *paff = NULL;
5880 isl_space *pw_space;
5881 isl_local_space *ls = NULL;
5883 if (!space || !var)
5884 goto error;
5886 ls = isl_local_space_from_space(isl_space_copy(space));
5887 pw_space = isl_space_copy(space);
5888 pw_space = isl_space_from_domain(pw_space);
5889 pw_space = isl_space_add_dims(pw_space, isl_dim_out, 1);
5890 paff = isl_pw_aff_alloc_size(pw_space, var->n_row);
5892 for (i = 0; i < var->n_row; ++i) {
5893 isl_pw_aff *paff_i;
5895 aff = isl_aff_alloc(isl_local_space_copy(ls));
5896 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
5897 0, var->n_row - 1);
5898 if (!aff || !bset)
5899 goto error;
5900 isl_int_set_si(aff->v->el[0], 1);
5901 isl_seq_cpy(aff->v->el + 1, var->row[i], var->n_col);
5902 isl_int_set_si(aff->v->el[1 + var->n_col], 0);
5903 bset = select_minimum(bset, var, i);
5904 paff_i = isl_pw_aff_alloc(isl_set_from_basic_set(bset), aff);
5905 paff = isl_pw_aff_add_disjoint(paff, paff_i);
5908 isl_local_space_free(ls);
5909 isl_space_free(space);
5910 isl_mat_free(var);
5911 return paff;
5912 error:
5913 isl_aff_free(aff);
5914 isl_basic_set_free(bset);
5915 isl_pw_aff_free(paff);
5916 isl_local_space_free(ls);
5917 isl_space_free(space);
5918 isl_mat_free(var);
5919 return NULL;
5922 /* Given a piecewise multi-affine expression of which the last input variable
5923 * is the minimum of the bounds in "cst", plug in the value of the minimum.
5924 * This minimum expression is given in "min_expr_pa".
5925 * The set "min_expr" contains the same information, but in the form of a set.
5926 * The variable is subsequently projected out.
5928 * The implementation is similar to those of "split" and "split_domain".
5929 * If the variable appears in a given expression, then minimum expression
5930 * is plugged in. Otherwise, if the variable appears in the constraints
5931 * and a split is required, then the domain is split. Otherwise, no split
5932 * is performed.
5934 static __isl_give isl_pw_multi_aff *split_domain_pma(
5935 __isl_take isl_pw_multi_aff *opt, __isl_take isl_pw_aff *min_expr_pa,
5936 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
5938 isl_size n_in;
5939 int i;
5940 isl_space *space;
5941 isl_pw_multi_aff *res;
5943 if (!opt || !min_expr || !cst)
5944 goto error;
5946 n_in = isl_pw_multi_aff_dim(opt, isl_dim_in);
5947 if (n_in < 0)
5948 goto error;
5949 space = isl_pw_multi_aff_get_space(opt);
5950 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
5951 res = isl_pw_multi_aff_empty(space);
5953 for (i = 0; i < opt->n; ++i) {
5954 isl_bool subs;
5955 isl_pw_multi_aff *pma;
5957 pma = isl_pw_multi_aff_alloc(isl_set_copy(opt->p[i].set),
5958 isl_multi_aff_copy(opt->p[i].maff));
5959 subs = need_substitution(opt->p[i].maff);
5960 if (subs < 0) {
5961 pma = isl_pw_multi_aff_free(pma);
5962 } else if (subs) {
5963 pma = isl_pw_multi_aff_substitute(pma,
5964 n_in - 1, min_expr_pa);
5965 } else {
5966 isl_bool split;
5967 split = need_split_set(opt->p[i].set, cst);
5968 if (split < 0)
5969 pma = isl_pw_multi_aff_free(pma);
5970 else if (split)
5971 pma = isl_pw_multi_aff_intersect_domain(pma,
5972 isl_set_copy(min_expr));
5974 pma = isl_pw_multi_aff_project_out(pma,
5975 isl_dim_in, n_in - 1, 1);
5977 res = isl_pw_multi_aff_add_disjoint(res, pma);
5980 isl_pw_multi_aff_free(opt);
5981 isl_pw_aff_free(min_expr_pa);
5982 isl_set_free(min_expr);
5983 isl_mat_free(cst);
5984 return res;
5985 error:
5986 isl_pw_multi_aff_free(opt);
5987 isl_pw_aff_free(min_expr_pa);
5988 isl_set_free(min_expr);
5989 isl_mat_free(cst);
5990 return NULL;
5993 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pw_multi_aff(
5994 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5995 __isl_give isl_set **empty, int max);
5997 /* This function is called from basic_map_partial_lexopt_symm.
5998 * The last variable of "bmap" and "dom" corresponds to the minimum
5999 * of the bounds in "cst". "map_space" is the space of the original
6000 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
6001 * is the space of the original domain.
6003 * We recursively call basic_map_partial_lexopt and then plug in
6004 * the definition of the minimum in the result.
6006 static __isl_give isl_pw_multi_aff *
6007 basic_map_partial_lexopt_symm_core_pw_multi_aff(
6008 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
6009 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
6010 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
6012 isl_pw_multi_aff *opt;
6013 isl_pw_aff *min_expr_pa;
6014 isl_set *min_expr;
6016 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
6017 min_expr_pa = set_minimum_pa(isl_basic_set_get_space(dom),
6018 isl_mat_copy(cst));
6020 opt = basic_map_partial_lexopt_pw_multi_aff(bmap, dom, empty, max);
6022 if (empty) {
6023 *empty = split(*empty,
6024 isl_set_copy(min_expr), isl_mat_copy(cst));
6025 *empty = isl_set_reset_space(*empty, set_space);
6028 opt = split_domain_pma(opt, min_expr_pa, min_expr, cst);
6029 opt = isl_pw_multi_aff_reset_space(opt, map_space);
6031 return opt;
6034 #undef TYPE
6035 #define TYPE isl_pw_multi_aff
6036 #undef SUFFIX
6037 #define SUFFIX _pw_multi_aff
6038 #include "isl_tab_lexopt_templ.c"