isl_mat_extend: avoid memory leak when realloc fails
[isl.git] / polyhedron_minimize.c
blobf6c2dc95f33180dc1ef07ea0cd9614aa8ada5e0a
1 /*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
4 * Use of this software is governed by the GNU LGPLv2.1 license
6 * Written by Sven Verdoolaege, K.U.Leuven, Departement
7 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8 */
10 #include <assert.h>
11 #include <isl/set.h>
12 #include <isl/vec.h>
13 #include <isl/ilp.h>
14 #include <isl/seq.h>
16 /* The input of this program is the same as that of the "polytope_minimize"
17 * program from the barvinok distribution.
19 * Constraints of set is PolyLib format.
20 * Linear or affine objective function in PolyLib format.
23 static struct isl_vec *isl_vec_lin_to_aff(struct isl_vec *vec)
25 struct isl_vec *aff;
27 if (!vec)
28 return NULL;
29 aff = isl_vec_alloc(vec->ctx, 1 + vec->size);
30 if (!aff)
31 goto error;
32 isl_int_set_si(aff->el[0], 0);
33 isl_seq_cpy(aff->el + 1, vec->el, vec->size);
34 isl_vec_free(vec);
35 return aff;
36 error:
37 isl_vec_free(vec);
38 return NULL;
41 /* Rotate elements of vector right.
42 * In particular, move the constant term from the end of the
43 * vector to the start of the vector.
45 static struct isl_vec *vec_ror(struct isl_vec *vec)
47 int i;
49 if (!vec)
50 return NULL;
51 for (i = vec->size - 2; i >= 0; --i)
52 isl_int_swap(vec->el[i], vec->el[i + 1]);
53 return vec;
56 int main(int argc, char **argv)
58 struct isl_ctx *ctx = isl_ctx_alloc();
59 struct isl_basic_set *bset;
60 struct isl_vec *obj;
61 struct isl_vec *sol;
62 isl_int opt;
63 unsigned dim;
64 enum isl_lp_result res;
65 isl_printer *p;
67 isl_int_init(opt);
68 bset = isl_basic_set_read_from_file(ctx, stdin, 0);
69 assert(bset);
70 obj = isl_vec_read_from_file(ctx, stdin);
71 assert(obj);
72 dim = isl_basic_set_total_dim(bset);
73 assert(obj->size >= dim && obj->size <= dim + 1);
74 if (obj->size != dim + 1)
75 obj = isl_vec_lin_to_aff(obj);
76 else
77 obj = vec_ror(obj);
78 res = isl_basic_set_solve_ilp(bset, 0, obj->el, &opt, &sol);
79 switch (res) {
80 case isl_lp_error:
81 fprintf(stderr, "error\n");
82 return -1;
83 case isl_lp_empty:
84 fprintf(stdout, "empty\n");
85 break;
86 case isl_lp_unbounded:
87 fprintf(stdout, "unbounded\n");
88 break;
89 case isl_lp_ok:
90 p = isl_printer_to_file(ctx, stdout);
91 p = isl_printer_print_vec(p, sol);
92 p = isl_printer_end_line(p);
93 p = isl_printer_print_isl_int(p, opt);
94 p = isl_printer_end_line(p);
95 isl_printer_free(p);
97 isl_basic_set_free(bset);
98 isl_vec_free(obj);
99 isl_vec_free(sol);
100 isl_ctx_free(ctx);
101 isl_int_clear(opt);
103 return 0;