3ba94e750a87a2dc107530452825b54aa5a6ad09
[libfirm] / ir / be / becopyilp.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                12.04.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6
7  * Minimizing copies with an exact algorithm using mixed integer programming (MIP).
8  * Problem statement as a 'quadratic 0-1 program with linear constraints' with
9  * n binary variables. Constraints are knapsack (enforce color for each node) and
10  * cliques of ifg (interference constraints).
11  * Transformation into a 'mixed integer program' with n binary variables and
12  * additional 2n real variables. Constraints are the above the transformed
13  * objective function and 'complementary conditions' for two var classes.
14  * @author Daniel Grund
15  *
16  * NOTE:
17  * MPS means NOT the old-style, fixed-column format. Some white spaces are
18  * important. In general spaces are separators, MARKER-lines are used in COLUMN
19  * section to define binaries. BETTER use last 2 fields in COLUMNS section.
20  * See MPS docu for details
21  *
22  * Unfortunately no good solver is available locally (or even for linking)
23  * We use CPLEX 9.0 which runs on a machine residing at the Rechenzentrum.
24  */
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #ifdef HAVE_ALLOCA_H
30 #include <alloca.h>
31 #endif
32 #ifdef HAVE_MALLOC_H
33 #include <malloc.h>
34 #endif
35
36 #include <sys/types.h>
37 #include <sys/stat.h>
38
39 #include "xmalloc.h"
40 #include "becopyopt.h"
41 #include "becopystat.h"
42
43 #undef DUMP_MATRICES            /**< dumps all matrices completely. only recommended for small problems */
44 #undef DUMP_Q2ILP                       /**< see function pi_dump_q2ilp */
45 #define DUMP_DILP                       /**< see function pi_dump_dilp */
46 #define DUMP_MST                        /**< see function pi_dump_start_sol */
47 #define DO_SOLVE                        /**< solve the MPS output with CPLEX */
48 #undef DELETE_FILES             /**< deletes all dumped files after use. Files on server are always deleted. */
49
50 /* CPLEX-account related stuff */
51 #define SSH_USER_HOST "kb61@sp-smp.rz.uni-karlsruhe.de"
52 #define SSH_PASSWD_FILE "/ben/daniel/.smppw"
53 #define EXPECT_FILENAME "runme" /* name of the expect-script */
54
55 #define DEBUG_LVL SET_LEVEL_1
56 static firm_dbg_module_t *dbg = NULL;
57
58 #define SLOTS_NUM2POS 256
59 #define SLOTS_LIVING 32
60
61 /* get_weight represents the _gain_ if node n and m have the same color. */
62 #define get_weight(n,m) 1
63
64 /**
65  * A type storing names of the x variables in the form x[NUMBER]_[COLOR]
66  */
67 typedef struct _x_name_t {
68         int n, c;
69 } x_name_t;
70
71 /**
72  * For each node taking part in the opt-problem its position in the
73  * x-variable-vector is stored in a set. This set maps the node-nr (given by
74  * benumb) to the position in the vector.
75  */
76 typedef struct _num2pos_t {
77         int num, pos;
78 } num2pos_t;
79
80 typedef struct _simpl_t {
81         struct list_head chain;
82         if_node_t *ifn;
83 } simpl_t;
84
85 /**
86  * A type storing the unmodified '0-1 quadratic program' of the form
87  * min f = xQx
88  * udN:  Ax  = e
89  *       Bx <= e
90  *        x \in {0, 1}
91  *
92  * This problem is called the original problem
93  */
94 typedef struct _problem_instance_t {
95         const copy_opt_t *co;                   /** the original copy_opt problem */
96         int x_dim, A_dim, B_dim, E_dim, c_dim;          /**< number of: x variables (equals Q_dim), rows in A, rows in B */
97         sp_matrix_t *Q, *A, *B, *E, *c;         /**< the (sparse) matrices of this problem */
98         x_name_t *x;                                    /**< stores the names of the x variables. all possible colors for a node are ordered and occupy consecutive entries. lives in obstack ob. */
99         set *num2pos;                                   /**< maps node numbers to positions in x. */
100
101         /* problem size reduction removing simple nodes */
102         struct list_head simplicials;   /**< holds all simpl_t's in right order to color*/
103         pset *removed;                                  /**< holds all removed simplicial irns */
104
105         /* needed for linearization */
106         int bigM, maxQij, minQij;
107
108         /* overhead needed to build this */
109         struct obstack ob;
110         int curr_color;
111         int curr_row;
112 } problem_instance_t;
113
114 #define is_removed(irn) pset_find_ptr(pi->removed, irn)
115
116 /* Nodes have consecutive numbers so this hash shoud be fine */
117 #define HASH_NUM(num) num
118
119 static int set_cmp_num2pos(const void *x, const void *y, size_t size) {
120         return ((num2pos_t *)x)->num != ((num2pos_t *)y)->num;
121 }
122
123 /**
124  * Sets the first position of node with number num to pos.
125  * See x_name_t *x in _problem_instance_t.
126  */
127 static INLINE void pi_set_first_pos(problem_instance_t *pi, int num, int pos) {
128         num2pos_t find;
129         find.num = num;
130         find.pos = pos;
131         set_insert(pi->num2pos, &find, sizeof(find), HASH_NUM(num));
132 }
133
134 /**
135  * Get position by number. (First possible color)
136  * returns -1 if not found.
137  */
138 static INLINE int pi_get_first_pos(problem_instance_t *pi, int num) {
139         num2pos_t find, *found;
140         find.num = num;
141         found = set_find(pi->num2pos, &find, sizeof(find), HASH_NUM(num));
142         if (found) {
143                 assert(pi->x[found->pos].n == num && (found->pos == 0 || pi->x[found->pos-1].n != num) && "pi->num2pos is broken!");
144                 return found->pos;
145         } else
146                 return -1;
147 }
148
149 /**
150  * Get position by number and color.
151  * returns -1 if not found.
152  */
153 static INLINE int pi_get_pos(problem_instance_t *pi, int num, int col) {
154         num2pos_t find, *found;
155         int pos;
156
157         find.num = num;
158         found = set_find(pi->num2pos, &find, sizeof(find), HASH_NUM(num));
159         if (!found)
160                 return -1;
161         pos = found->pos;
162         while (pos < pi->x_dim && pi->x[pos].n == num && pi->x[pos].c < col)
163                 pos++;
164
165         if (pi->x[pos].n == num && pi->x[pos].c == col)
166                 return pos;
167         else
168                 return -1;
169 }
170
171 /**
172  * Collects all irns in currently processed register class
173  */
174 static void pi_collect_x_names(ir_node *block, void *env) {
175         problem_instance_t *pi = env;
176         struct list_head *head = &get_ra_block_info(block)->border_head;
177         border_t *curr;
178         bitset_t *pos_regs = bitset_alloca(pi->co->cls->n_regs);
179
180         list_for_each_entry_reverse(border_t, curr, head, list)
181                 if (curr->is_def && curr->is_real && !is_removed(curr->irn)) {
182                         x_name_t xx;
183                         pi->A_dim++;                    /* one knapsack constraint for each node */
184
185                         xx.n = get_irn_graph_nr(curr->irn);
186                         pi_set_first_pos(pi, xx.n, pi->x_dim);
187
188                         // iterate over all possible colors in order
189                         bitset_clear_all(pos_regs);
190                         arch_get_allocatable_regs(pi->co->env, curr->irn, arch_pos_make_out(0), pi->co->cls, pos_regs);
191                         bitset_foreach(pos_regs, xx.c) {
192                                 DBG((dbg, LEVEL_2, "Adding %n %d\n", curr->irn, xx.c));
193                                 obstack_grow(&pi->ob, &xx, sizeof(xx));
194                                 pi->x_dim++;            /* one x variable for each node and color */
195                         }
196                 }
197 }
198
199 /**
200  * Checks if all nodes in living are live_out in block block.
201  */
202 static INLINE int all_live_in(ir_node *block, pset *living) {
203         ir_node *n;
204         for (n = pset_first(living); n; n = pset_next(living))
205                 if (!is_live_in(block, n)) {
206                         pset_break(living);
207                         return 0;
208                 }
209         return 1;
210 }
211
212 /**
213  * Finds cliques in the interference graph, considering only nodes
214  * for which the color pi->curr_color is possible. Finds only 'maximal-cliques',
215  * viz cliques which are not conatained in another one.
216  * This is used for the matrix B.
217  */
218 static void pi_clique_finder(ir_node *block, void *env) {
219         problem_instance_t *pi = env;
220         enum phase_t {growing, shrinking} phase = growing;
221         struct list_head *head = &get_ra_block_info(block)->border_head;
222         border_t *b;
223         pset *living = pset_new_ptr(SLOTS_LIVING);
224
225         list_for_each_entry_reverse(border_t, b, head, list) {
226                 const ir_node *irn = b->irn;
227                 if (is_removed(irn))
228                         continue;
229
230                 if (b->is_def) {
231                         DBG((dbg, LEVEL_2, "Def %n\n", irn));
232                         pset_insert_ptr(living, irn);
233                         phase = growing;
234                 } else { /* is_use */
235                         DBG((dbg, LEVEL_2, "Use %n\n", irn));
236
237                         /* before shrinking the set, store the current 'maximum' clique;
238                          * do NOT if clique is a single node
239                          * do NOT if all values are live_in (in this case they were contained in a live-out clique elsewhere) */
240                         if (phase == growing && pset_count(living) >= 2 && !all_live_in(block, living)) {
241                                 ir_node *n;
242                                 for (n = pset_first(living); n; n = pset_next(living)) {
243                                         int pos = pi_get_pos(pi, get_irn_graph_nr(n), pi->curr_color);
244                                         matrix_set(pi->B, pi->curr_row, pos, 1);
245                                         DBG((dbg, LEVEL_2, "B[%d, %d] := %d\n", pi->curr_row, pos, 1));
246                                 }
247                                 pi->curr_row++;
248                         }
249                         pset_remove_ptr(living, irn);
250                         phase = shrinking;
251                 }
252         }
253
254         del_pset(living);
255 }
256
257 static INLINE int pi_is_simplicial(problem_instance_t *pi, const if_node_t *ifn) {
258         int i, o, size = 0;
259         if_node_t **all, *curr;
260         all = alloca(ifn_get_degree(ifn) * sizeof(*all));
261
262         /* get all non-removed neighbors */
263         foreach_neighb(ifn, curr)
264                 if (!is_removed(curr))
265                         all[size++] = curr;
266
267         /* check if these form a clique */
268         for (i=0; i<size; ++i)
269                 for (o=i+1; o<size; ++o)
270                         if (!ifg_has_edge(pi->co->irg, all[i], all[o]))
271                                 return 0;
272
273         /* all edges exist so this is a clique */
274         return 1;
275 }
276
277 static void pi_find_simplicials(problem_instance_t *pi) {
278         set *if_nodes;
279         if_node_t *ifn;
280         int redo = 1;
281
282         if_nodes = be_ra_get_ifg_nodes(pi->co->irg);
283         while (redo) {
284                 redo = 0;
285                 for (ifn = set_first(if_nodes); ifn; ifn = set_next(if_nodes)) {
286                         ir_node *irn = get_irn_for_graph_nr(pi->co->irg, ifn->nnr);
287                         if (!is_removed(irn) && !is_optimizable(irn) && !is_optimizable_arg(irn) && pi_is_simplicial(pi, ifn)) {
288                                 simpl_t *s = xmalloc(sizeof(*s));
289                                 s->ifn = ifn;
290                                 list_add(&s->chain, &pi->simplicials);
291                                 pset_insert_ptr(pi->removed, irn);
292                                 redo = 1;
293                                 DBG((dbg, LEVEL_1, " Removed %n\n", irn));
294                         }
295                 }
296         }
297 }
298
299 /**
300  * Generate the initial problem matrices and vectors.
301  */
302 static problem_instance_t *new_pi(const copy_opt_t *co) {
303         DBG((dbg, LEVEL_1, "Generating new instance...\n"));
304         problem_instance_t *pi = xcalloc(1, sizeof(*pi));
305         pi->co = co;
306         pi->num2pos = new_set(set_cmp_num2pos, SLOTS_NUM2POS);
307         pi->bigM = 1;
308         pi->removed = pset_new_ptr_default();
309         INIT_LIST_HEAD(&pi->simplicials);
310
311         /* problem size reduction */
312         pi_find_simplicials(pi);
313         //TODO dump_ifg_wo_removed
314
315         /* Vector x
316          * one entry per node and possible color */
317         obstack_init(&pi->ob);
318         dom_tree_walk_irg(co->irg, pi_collect_x_names, NULL, pi);
319         pi->x = obstack_finish(&pi->ob);
320
321         /* Matrix Q and E
322          * weights for the 'same-color-optimization' target */
323         {
324                 unit_t *curr;
325                 pi->Q = new_matrix(pi->x_dim, pi->x_dim);
326                 pi->E = new_matrix(pi->x_dim, pi->x_dim);
327                 pi->c = new_matrix(1, pi->x_dim);
328
329                 list_for_each_entry(unit_t, curr, &co->units, units) {
330                         const ir_node *root, *arg;
331                         int rootnr, argnr;
332                         unsigned save_rootpos, rootpos, argpos;
333                         int i;
334
335                         root = curr->nodes[0];
336                         rootnr = get_irn_graph_nr(root);
337                         save_rootpos = pi_get_first_pos(pi, rootnr);
338                         for (i = 1; i < curr->node_count; ++i) {
339                                 int weight;
340                                 rootpos = save_rootpos;
341                                 arg = curr->nodes[i];
342                                 argnr = get_irn_graph_nr(arg);
343                                 argpos = pi_get_first_pos(pi, argnr);
344                                 weight = -get_weight(root, arg);
345
346                                 DBG((dbg, LEVEL_2, "Q[%n, %n] := %d\n", root, arg, weight));
347                                 /* for all colors root and arg have in common, set the weight for
348                                  * this pair in the objective function matrix Q */
349                                 while (rootpos < pi->x_dim && argpos < pi->x_dim &&
350                                                 pi->x[rootpos].n == rootnr && pi->x[argpos].n == argnr) {
351                                         if (pi->x[rootpos].c < pi->x[argpos].c)
352                                                 ++rootpos;
353                                         else if (pi->x[rootpos].c > pi->x[argpos].c)
354                                                 ++argpos;
355                                         else {
356                                                 /* E */
357                                                 matrix_set(pi->E, pi->E_dim, rootpos, +1);
358                                                 matrix_set(pi->E, pi->E_dim, argpos,  -1);
359                                                 matrix_set(pi->E, pi->E_dim, pi->x_dim + pi->c_dim, 1);
360                                                 pi->E_dim++;
361                                                 matrix_set(pi->E, pi->E_dim, rootpos, -1);
362                                                 matrix_set(pi->E, pi->E_dim, argpos,  +1);
363                                                 matrix_set(pi->E, pi->E_dim, pi->x_dim + pi->c_dim, 1);
364                                                 pi->E_dim++;
365
366                                                 /* Q */
367                                                 matrix_set(pi->Q, rootpos, argpos, weight + matrix_get(pi->Q, rootpos, argpos));
368                                                 rootpos++;
369                                                 argpos++;
370                                                 if (weight < pi->minQij) {
371                                                         DBG((dbg, LEVEL_2, "minQij = %d\n", weight));
372                                                         pi->minQij = weight;
373                                                 }
374                                                 if (weight > pi->maxQij) {
375                                                         DBG((dbg, LEVEL_2, "maxQij = %d\n", weight));
376                                                         pi->maxQij = weight;
377                                                 }
378                                         }
379                                 }
380
381                                 /* E */
382                                 matrix_set(pi->c, 1, pi->c_dim++, -weight);
383                         }
384                 }
385         }
386
387         /* Matrix A
388          * knapsack constraint for each node */
389         {
390                 int row = 0, col = 0;
391                 pi->A = new_matrix(pi->A_dim, pi->x_dim);
392                 while (col < pi->x_dim) {
393                         int curr_n = pi->x[col].n;
394                         while (col < pi->x_dim && pi->x[col].n == curr_n) {
395                                 DBG((dbg, LEVEL_2, "A[%d, %d] := %d\n", row, col, 1));
396                                 matrix_set(pi->A, row, col++, 1);
397                         }
398                         ++row;
399                 }
400                 assert(row == pi->A_dim);
401         }
402
403         /* Matrix B
404          * interference constraints using exactly those cliques not contained in others. */
405         {
406                 int color, expected_clipques = pi->A_dim/4 * pi->co->cls->n_regs;
407                 pi->B = new_matrix(expected_clipques, pi->x_dim);
408                 for (color = 0; color < pi->co->cls->n_regs; ++color) {
409                         pi->curr_color = color;
410                         dom_tree_walk_irg(pi->co->irg, pi_clique_finder, NULL, pi);
411                 }
412                 pi->B_dim = matrix_get_rowcount(pi->B);
413         }
414
415         return pi;
416 }
417
418 /**
419  * clean the problem instance
420  */
421 static void free_pi(problem_instance_t *pi) {
422         DBG((dbg, LEVEL_1, "Free instance...\n"));
423         del_matrix(pi->Q);
424         del_matrix(pi->A);
425         del_matrix(pi->B);
426         del_matrix(pi->E);
427         del_matrix(pi->c);
428         del_set(pi->num2pos);
429         del_pset(pi->removed);
430         obstack_free(&pi->ob, NULL);
431         free(pi);
432 }
433
434 #ifdef DUMP_MATRICES
435 /**
436  * Dump the raw matrices of the problem to a file for debugging.
437  */
438 static void pi_dump_matrices(problem_instance_t *pi) {
439         int i;
440         FILE *out = ffopen(pi->co->name, "matrix", "wt");
441
442         DBG((dbg, LEVEL_1, "Dumping raw...\n"));
443         fprintf(out, "\n\nx-names =\n");
444         for (i=0; i<pi->x_dim; ++i)
445                 fprintf(out, "%5d %2d\n", pi->x[i].n, pi->x[i].c);
446
447         fprintf(out, "\n\n-Q =\n");
448         matrix_dump(pi->Q, out, -1);
449
450         fprintf(out, "\n\nA =\n");
451         matrix_dump(pi->A, out, 1);
452
453         fprintf(out, "\n\nB =\n");
454         matrix_dump(pi->B, out, 1);
455
456         fprintf(out, "\n\nE =\n");
457         matrix_dump(pi->E, out, 1);
458
459         fprintf(out, "\n\nc =\n");
460         matrix_dump(pi->c, out, 1);
461
462         fclose(out);
463 }
464 #endif
465
466 #ifdef DUMP_Q2ILP
467 /**
468  * Dumps an mps file representing the problem using a linearization of the
469  * quadratic programming problem.
470  */
471 static void pi_dump_q2ilp(problem_instance_t *pi) {
472         int i, max_abs_Qij;
473         const matrix_elem_t *e;
474         FILE *out;
475         bitset_t *good_row;
476         DBG((dbg, LEVEL_1, "Dumping q2ilp...\n"));
477
478         max_abs_Qij = pi->maxQij;
479         if (-pi->minQij > max_abs_Qij)
480                 max_abs_Qij = -pi->minQij;
481         pi->bigM = pi->A_dim * max_abs_Qij;
482         DBG((dbg, LEVEL_2, "BigM = %d\n", pi->bigM));
483
484         matrix_optimize(pi->Q);
485         good_row = bitset_alloca(pi->x_dim);
486         for (i=0; i<pi->x_dim; ++i)
487                 if (matrix_row_first(pi->Q, i))
488                         bitset_set(good_row, i);
489
490     out = ffopen(pi->co->name, "q2ilp", "wt");
491         fprintf(out, "NAME %s\n", pi->co->name);
492
493         fprintf(out, "ROWS\n");
494         fprintf(out, " N obj\n");
495         for (i=0; i<pi->x_dim; ++i)
496                 if (bitset_is_set(good_row, i))
497                         fprintf(out, " E cQ%d\n", i);
498         for (i=0; i<pi->A_dim; ++i)
499                 fprintf(out, " E cA%d\n", i);
500         for (i=0; i<pi->B_dim; ++i)
501                 fprintf(out, " L cB%d\n", i);
502         for (i=0; i<pi->x_dim; ++i)
503                 if (bitset_is_set(good_row, i))
504                         fprintf(out, " L cy%d\n", i);
505
506         fprintf(out, "COLUMNS\n");
507         /* the x vars come first */
508         /* mark them as binaries */
509         fprintf(out, "    MARKI0\t'MARKER'\t'INTORG'\n");
510         for (i=0; i<pi->x_dim; ++i) {
511                 /* participation in objective */
512                 if (bitset_is_set(good_row, i))
513                         fprintf(out, "    x%d_%d\tobj\t%d\n", pi->x[i].n, pi->x[i].c, -pi->bigM);
514                 /* in Q */
515                 matrix_foreach_in_col(pi->Q, i, e)
516                         fprintf(out, "    x%d_%d\tcQ%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
517                 /* in A */
518                 matrix_foreach_in_col(pi->A, i, e)
519                         fprintf(out, "    x%d_%d\tcA%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
520                 /* in B */
521                 matrix_foreach_in_col(pi->B, i, e)
522                         fprintf(out, "    x%d_%d\tcB%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
523                 /* in y */
524                 if (bitset_is_set(good_row, i))
525                         fprintf(out, "    x%d_%d\tcy%d\t%d\n", pi->x[i].n, pi->x[i].c, i, 2*pi->bigM);
526         }
527
528         fprintf(out, "    MARKI1\t'MARKER'\t'INTEND'\n"); /* end of marking */
529
530         /* next the s vars */
531         for (i=0; i<pi->x_dim; ++i)
532                 if (bitset_is_set(good_row, i)) {
533                         /* participation in objective */
534                         fprintf(out, "    s%d_%d\tobj\t%d\n", pi->x[i].n, pi->x[i].c, 1);
535                         /* in Q */
536                         fprintf(out, "    s%d_%d\tcQ%d\t%d\n", pi->x[i].n, pi->x[i].c, i, -1);
537                 }
538
539         /* next the y vars */
540         for (i=0; i<pi->x_dim; ++i)
541                 if (bitset_is_set(good_row, i)) {
542                         /* in Q */
543                         fprintf(out, "    y%d_%d\tcQ%d\t%d\n", pi->x[i].n, pi->x[i].c, i, -1);
544                         /* in y */
545                         fprintf(out, "    y%d_%d\tcy%d\t%d\n", pi->x[i].n, pi->x[i].c, i, 1);
546                 }
547
548         fprintf(out, "RHS\n");
549         for (i=0; i<pi->x_dim; ++i)
550                 if (bitset_is_set(good_row, i))
551                         fprintf(out, "    rhs\tcQ%d\t%d\n", i, -pi->bigM);
552         for (i=0; i<pi->A_dim; ++i)
553                 fprintf(out, "    rhs\tcA%d\t%d\n", i, 1);
554         for (i=0; i<pi->B_dim; ++i)
555                 fprintf(out, "    rhs\tcB%d\t%d\n", i, 1);
556         for (i=0; i<pi->x_dim; ++i)
557                 if (bitset_is_set(good_row, i))
558                         fprintf(out, "    rhs\tcy%d\t%d\n", i, 2*pi->bigM);
559
560         fprintf(out, "ENDATA\n");
561         fclose(out);
562 }
563 #endif
564
565 #ifdef DUMP_DILP
566 /**
567  * Dumps an mps file representing the problem using directly a formalization as ILP.
568  */
569 static void pi_dump_dilp(problem_instance_t *pi) {
570         int i;
571         const matrix_elem_t *e;
572         FILE *out;
573         DBG((dbg, LEVEL_1, "Dumping dilp...\n"));
574
575         out = ffopen(pi->co->name, "dilp", "wt");
576         fprintf(out, "NAME %s\n", pi->co->name);
577         fprintf(out, "OBJSENSE\n   MAX\n");
578
579         fprintf(out, "ROWS\n");
580         fprintf(out, " N obj\n");
581         for (i=0; i<pi->A_dim; ++i)
582                 fprintf(out, " E cA%d\n", i);
583         for (i=0; i<pi->B_dim; ++i)
584                 fprintf(out, " L cB%d\n", i);
585         for (i=0; i<pi->E_dim; ++i)
586                 fprintf(out, " L cE%d\n", i);
587
588         fprintf(out, "COLUMNS\n");
589         /* the x vars come first */
590         /* mark them as binaries */
591         fprintf(out, "    MARKI0\t'MARKER'\t'INTORG'\n");
592         for (i=0; i<pi->x_dim; ++i) {
593                 /* in A */
594                 matrix_foreach_in_col(pi->A, i, e)
595                         fprintf(out, "    x%d_%d\tcA%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
596                 /* in B */
597                 matrix_foreach_in_col(pi->B, i, e)
598                         fprintf(out, "    x%d_%d\tcB%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
599                 /* in E */
600                 matrix_foreach_in_col(pi->E, i, e)
601                         fprintf(out, "    x%d_%d\tcE%d\t%d\n", pi->x[i].n, pi->x[i].c, e->row, e->val);
602         }
603         fprintf(out, "    MARKI1\t'MARKER'\t'INTEND'\n"); /* end of marking */
604
605         /* next the y vars */
606         for (i=0; i<pi->c_dim; ++i) {
607                 /* in Objective */
608                 fprintf(out, "    y%d\tobj\t%d\n", i, matrix_get(pi->c, 1, i));
609                 /* in E */
610                 matrix_foreach_in_col(pi->E, pi->x_dim+i, e)
611                         fprintf(out, "    y%d\tcE%d\t%d\n", i, e->row, e->val);
612         }
613
614         fprintf(out, "RHS\n");
615         for (i=0; i<pi->A_dim; ++i)
616                 fprintf(out, "    rhs\tcA%d\t%d\n", i, 1);
617         for (i=0; i<pi->B_dim; ++i)
618                 fprintf(out, "    rhs\tcB%d\t%d\n", i, 1);
619         for (i=0; i<pi->E_dim; ++i)
620                 fprintf(out, "    rhs\tcE%d\t%d\n", i, 1);
621
622         fprintf(out, "ENDATA\n");
623         fclose(out);
624 }
625 #endif
626
627 #ifdef DUMP_MST
628 /**
629  * Dumps the known solution to a file to make use of it
630  * as a starting solution respectively as a bound
631  */
632 static void pi_dump_start_sol(problem_instance_t *pi) {
633         int i;
634         FILE *out = ffopen(pi->co->name, "mst", "wt");
635         fprintf(out, "NAME\n");
636         for (i=0; i<pi->x_dim; ++i) {
637                 int val, n, c;
638                 n = pi->x[i].n;
639                 c = pi->x[i].c;
640                 if (get_irn_col(pi->co, get_irn_for_graph_nr(pi->co->irg, n)) == c)
641                         val = 1;
642                 else
643                         val = 0;
644                 fprintf(out, "    x%d_%d\t%d\n", n, c, val);
645         }
646         fprintf(out, "ENDATA\n");
647         fclose(out);
648 }
649 #endif
650
651 #ifdef DO_SOLVE
652 /**
653  * Invoke an external solver
654  */
655 static void pi_solve_ilp(problem_instance_t *pi) {
656         FILE *out, *pwfile;
657         char passwd[128];
658
659         DBG((dbg, LEVEL_1, "Solving with CPLEX@RZ...\n"));
660         /* write command file for CPLEX */
661         out = ffopen(pi->co->name, "cmd", "wt");
662         fprintf(out, "set logfile %s.sol\n", pi->co->name);
663         fprintf(out, "set mip strategy mipstart 1\n");
664         fprintf(out, "set mip emphasis 3\n"); /* moving best bound */
665         fprintf(out, "set mip strategy variableselect 3\n"); /* strong branching */
666 //      fprintf(out, "set mip strategy branch 1\n"); /* branch up first */
667 #ifdef DUMP_Q2ILP
668         fprintf(out, "read %s.q2ilp mps\n", pi->co->name);
669 #endif
670 #ifdef DUMP_DILP
671         fprintf(out, "read %s.dilp mps\n", pi->co->name);
672 #endif
673         fprintf(out, "read %s.mst\n", pi->co->name);
674         fprintf(out, "optimize\n");
675         fprintf(out, "display solution variables 1-%d\n", pi->x_dim);
676         fprintf(out, "quit\n");
677         fclose(out);
678
679         /* write expect-file for copying problem to RZ */
680         pwfile = fopen(SSH_PASSWD_FILE, "rt");
681         fgets(passwd, sizeof(passwd), pwfile);
682         fclose(pwfile);
683
684         out = ffopen(EXPECT_FILENAME, "exp", "wt");
685         fprintf(out, "#! /usr/bin/expect\n");
686         fprintf(out, "spawn scp %s.dilp %s.q2ilp %s.mst %s.cmd %s:\n", pi->co->name, pi->co->name, pi->co->name, pi->co->name, SSH_USER_HOST); /* copy problem files */
687         fprintf(out, "expect \"word:\"\nsend \"%s\\n\"\ninteract\n", passwd);
688
689         fprintf(out, "spawn ssh %s \"./cplex90 < %s.cmd\"\n", SSH_USER_HOST, pi->co->name); /* solve */
690         fprintf(out, "expect \"word:\"\nsend \"%s\\n\"\ninteract\n", passwd);
691
692         fprintf(out, "spawn scp %s:%s.sol .\n", SSH_USER_HOST, pi->co->name); /*copy back solution */
693         fprintf(out, "expect \"word:\"\nsend \"%s\\n\"\ninteract\n", passwd);
694
695         fprintf(out, "spawn ssh %s ./dell\n", SSH_USER_HOST); /* clean files on server */
696         fprintf(out, "expect \"word:\"\nsend \"%s\\n\"\ninteract\n", passwd);
697
698         fclose(out);
699
700         /* call the expect script */
701         chmod(EXPECT_FILENAME ".exp", 0700);
702         system(EXPECT_FILENAME ".exp");
703 }
704
705 static void pi_set_simplicials(problem_instance_t *pi) {
706         simpl_t *simpl, *tmp;
707         bitset_t *used_cols = bitset_alloca(arch_register_class_n_regs(pi->co->cls));
708
709         /* color the simplicial nodes in right order */
710         list_for_each_entry_safe(simpl_t, simpl, tmp, &pi->simplicials, chain) {
711                 int free_col;
712                 ir_node *other_irn, *irn;
713                 if_node_t *other, *ifn;
714
715                 /* get free color by inspecting all neighbors */
716                 ifn = simpl->ifn;
717                 irn = get_irn_for_graph_nr(pi->co->irg, ifn->nnr);
718                 bitset_clear_all(used_cols);
719                 foreach_neighb(ifn, other) {
720                         other_irn = get_irn_for_graph_nr(pi->co->irg, other->nnr);
721                         if (!is_removed(other_irn)) /* only inspect nodes which are in graph right now */
722                                 bitset_set(used_cols, get_irn_col(pi->co, other_irn));
723                 }
724
725                 /* now all bits not set are possible colors */
726                 free_col = bitset_next_clear(used_cols, 0);
727                 assert(free_col != -1 && "No free color found. This can not be.");
728                 set_irn_col(pi->co, irn, free_col);
729                 pset_remove_ptr(pi->removed, irn); /* irn is back in graph again */
730                 free(simpl);
731         }
732 }
733
734 /**
735  * Sets the colors of irns according to the values of variables found in the
736  * output file of the solver.
737  */
738 static void pi_apply_solution(problem_instance_t *pi) {
739         FILE *in ;
740
741         if (!(in = ffopen(pi->co->name, "sol", "rt")))
742                 return;
743         DBG((dbg, LEVEL_1, "Applying solution...\n"));
744         while (!feof(in)) {
745                 char buf[1024];
746                 int num = -1, col = -1, val = -1;
747
748                 fgets(buf, sizeof(buf), in);
749                 DBG((dbg, LEVEL_3, "Line: %s", buf));
750
751                 if (strcmp(buf, "No integer feasible solution exists.") == 0)
752                         assert(0 && "CPLEX says: No integer feasible solution exists!");
753
754                 if (strcmp(buf, "TODO Out of memory") == 0) {}
755
756 #ifdef DO_STAT
757                 {
758                         /* solution time */
759                         float sol_time;
760                         int iter;
761                         if (sscanf(buf, "Solution time = %f sec. Iterations = %d", &sol_time, &iter) == 2) {
762                                 DBG((dbg, LEVEL_2, " Time: %f Iter: %d\n", sol_time, iter));
763                                 curr_vals[I_ILP_TIME] += 10 * sol_time;
764                                 curr_vals[I_ILP_ITER] += iter;
765                         }
766                 }
767 #endif
768
769                 /* variable value */
770                 if (sscanf(buf, "x%d_%d %d", &num, &col, &val) == 3 && val == 1) {
771                         DBG((dbg, LEVEL_2, " x%d_%d = %d\n", num, col, val));
772                         set_irn_col(pi->co, get_irn_for_graph_nr(pi->co->irg, num), col);
773                 }
774         }
775         fclose(in);
776         pi_set_simplicials(pi);
777 }
778 #endif /* DO_SOLVE */
779
780 #ifdef DELETE_FILES
781 static void pi_delete_files(problem_instance_t *pi) {
782         char buf[1024];
783         int end = snprintf(buf, sizeof(buf), "%s", pi->co->name);
784         DBG((dbg, LEVEL_1, "Deleting files...\n"));
785 #ifdef DUMP_MATRICES
786         snprintf(buf+end, sizeof(buf)-end, ".matrix");
787         remove(buf);
788 #endif
789 #ifdef DUMP_Q2ILP
790         snprintf(buf+end, sizeof(buf)-end, ".q2ilp");
791         remove(buf);
792 #endif
793 #ifdef DUMP_DILP
794         snprintf(buf+end, sizeof(buf)-end, ".dilp");
795         remove(buf);
796 #endif
797 #ifdef DO_SOLVE
798         snprintf(buf+end, sizeof(buf)-end, ".cmd");
799         remove(buf);
800         snprintf(buf+end, sizeof(buf)-end, ".mst");
801         remove(buf);
802         snprintf(buf+end, sizeof(buf)-end, ".sol");
803         remove(buf);
804         remove(EXPECT_FILENAME ".exp");
805 #endif
806 }
807 #endif
808
809 void co_ilp_opt(copy_opt_t *co) {
810         problem_instance_t *pi;
811
812         dbg = firm_dbg_register("ir.be.copyoptilp");
813         firm_dbg_set_mask(dbg, DEBUG_LVL);
814         if (!strcmp(co->name, DEBUG_IRG))
815                 firm_dbg_set_mask(dbg, -1);
816
817         pi = new_pi(co);
818         DBG((dbg, 0, "\t\t\t %5d %5d %5d\n", pi->x_dim, pi->A_dim, pi->B_dim));
819
820         if (pi->x_dim > 0) {
821 #ifdef DUMP_MATRICES
822         pi_dump_matrices(pi);
823 #endif
824
825 #ifdef DUMP_Q2ILP
826         pi_dump_q2ilp(pi);
827 #endif
828
829 #ifdef DUMP_DILP
830         pi_dump_dilp(pi);
831 #endif
832
833 #ifdef DUMP_MST
834         pi_dump_start_sol(pi);
835 #endif
836 #ifdef DO_SOLVE
837         pi_solve_ilp(pi);
838         pi_apply_solution(pi);
839 #endif
840
841 #ifdef DELETE_FILES
842         pi_delete_files(pi);
843 #endif
844         }
845         free_pi(pi);
846 }