C99 features removed
[libfirm] / ir / be / becopyilp.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                17.05.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  * CVS-ID:      $Id$
7  */
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif
11 #ifdef HAVE_ALLOCA_H
12 #include <alloca.h>
13 #endif
14 #ifdef HAVE_MALLOC_H
15 #include <malloc.h>
16 #endif
17
18 #define PATH_CONSTRAINTS_FOR_CLASSES
19 #undef PRECOLOR_MAX_CLIQUE
20 #undef NO_NULL_COLORS
21 #undef NO_NULL_COLORS_EXTRA_CSTS
22 #undef NO_NULL_COLORS_WITH_COSTS
23 #if (defined(NO_NULL_COLORS_EXTRA_CSTS) || defined(NO_NULL_COLORS_WITH_COSTS)) && !defined(NO_NULL_COLORS)
24 #error Chose your weapon!
25 #endif
26
27 #include "irprog.h"
28
29 #include <lpp/lpp.h>
30 #include <lpp/lpp_net.h>
31 #include <lpp/lpp_cplex.h>
32 #include <lpp/lpp_remote.h>
33 #include "xmalloc.h"
34 #include "pset.h"
35 #include "irdom_t.h"
36 #include "iredges_t.h"
37 #include "bechordal_t.h"
38 #include "becopyopt.h"
39 #include "becopystat.h"
40 #include "besched_t.h"
41 #include "phiclass.h"
42
43 #define LPP_HOST "i44pc52"
44 #define LPP_SOLVER "cplex"
45
46 #undef DUMP_MPS
47 static firm_dbg_module_t *dbg = NULL;
48
49 #define MAX(a,b) ((a<b)?(b):(a))
50 #define MIN(a,b) ((a<b)?(a):(b))
51 #define EPSILON 0.00001
52 #define SLOTS_LIVING 32
53
54 typedef struct _simpl_t {
55         struct list_head chain;
56         if_node_t *ifn;
57 } simpl_t;
58
59 typedef struct _problem_instance_t {
60         const copy_opt_t *co;                   /** the copy_opt problem */
61         /* problem size reduction removing simple nodes */
62         struct list_head simplicials;   /**< holds all simpl_t's in right order to color*/
63         pset *removed;                                  /**< holds all removed simplicial irns */
64         /* lp problem */
65         lpp_t *curr_lp;                                 /**< points to the problem currently used */
66         lpp_t *dilp;                                    /**< problem formulation directly as milp */
67 #ifdef NO_NULL_COLORS_EXTRA_CSTS
68         int first_nnc_cst_idx;                  /**< the first index of a constraint belonging to no-null-colors stuff*/
69 #endif
70         int first_nnc_var_idx;                  /**< the first index of a constraint belonging to no-null-colors stuff*/
71
72         int cst_counter, first_x_var, last_x_var;
73         char buf[32];
74         int all_simplicial;
75         pset *done;
76 } problem_instance_t;
77
78 #define is_removed(irn) pset_find_ptr(pi->removed, irn)
79
80 #define is_color_possible(irn,color) arch_reg_is_allocatable(get_arch_env(pi->co), irn, arch_pos_make_out(0), arch_register_for_index(pi->co->chordal_env->cls, color))
81
82 /*
83  * Some stuff for variable name handling.
84  */
85 #define mangle_cst(buf, prefix, nr) \
86                         snprintf((buf), sizeof(buf), "%c%d", (prefix), (nr))
87
88 #define mangle_var1(buf, prefix, color) \
89                         snprintf((buf), sizeof(buf), "%c%d", (prefix), (color))
90
91 #define mangle_var2(buf, prefix, node_nr, color) \
92                         snprintf((buf), sizeof(buf), "%c%d_%d", (prefix), (node_nr), (color))
93
94 #define mangle_var3(buf, prefix, n1, n2, col) \
95                         snprintf((buf), sizeof(buf), "%c%d_%d_%d", (prefix), (n1), (n2), (col))
96
97 #define mangle_var_irn(buf, prefix, irn, color) \
98                         mangle_var2((buf), (prefix), get_irn_graph_nr(irn), (color))
99
100 #define split_var(var, nnr, col) \
101                         sscanf(var, "x%d_%d", (nnr), (col))
102
103
104 /**
105  * Checks if a node is simplicial in the graph
106  * heeding the already removed nodes.
107  */
108 static INLINE int pi_is_simplicial(problem_instance_t *pi, const if_node_t *ifn) {
109         int i, o, size = 0;
110         if_node_t **all, *curr;
111         all = alloca(ifn_get_degree(ifn) * sizeof(*all));
112
113         /* get all non-removed neighbors */
114         foreach_neighb(ifn, curr)
115                 if (!is_removed(curr))
116                         all[size++] = curr;
117
118         /* check if these form a clique */
119         for (i=0; i<size; ++i)
120                 for (o=i+1; o<size; ++o)
121                         if (!ifg_has_edge(pi->co->chordal_env, all[i], all[o]))
122                                 return 0;
123
124         /* all edges exist so this is a clique */
125         return 1;
126 }
127
128 /**
129  * Iterative finds and 'removes' from the graph all nodes which are
130  * simplicial AND not member of a equal-color-wish
131  */
132 static void pi_find_simplicials(problem_instance_t *pi) {
133         set *if_nodes;
134         if_node_t *ifn;
135         int redo = 1;
136
137         DBG((dbg, LEVEL_2, "Find simlicials...\n"));
138
139         if_nodes = be_ra_get_ifg_nodes(pi->co->chordal_env);
140         while (redo) {
141                 redo = 0;
142                 for (ifn = set_first(if_nodes); ifn; ifn = set_next(if_nodes)) {
143                         ir_node *irn = get_irn_for_graph_nr(get_irg(pi->co), ifn->nnr);
144                         if (!is_removed(irn) && !is_optimizable(get_arch_env(pi->co), irn) && !is_optimizable_arg(pi->co, irn)) {
145                         if (pi_is_simplicial(pi, ifn)) {
146                                         simpl_t *s = xmalloc(sizeof(*s));
147                                         s->ifn = ifn;
148                                         list_add(&s->chain, &pi->simplicials);
149                                         pset_insert_ptr(pi->removed, irn);
150                                         redo = 1;
151                                         DBG((dbg, LEVEL_2, " Removed %n %d\n", irn, get_irn_graph_nr(irn)));
152                         }
153                         }
154                 }
155         }
156         if (set_count(be_ra_get_ifg_nodes(pi->co->chordal_env)) == pset_count(pi->removed))
157                 pi->all_simplicial = 1;
158 }
159
160 #ifdef NO_NULL_COLORS
161 static void pi_add_constr_no_null_colors(problem_instance_t *pi) {
162         int cst_counter=0, col, var_idx, cst_idx;
163         int n_colors = pi->co->chordal_env->cls->n_regs;
164         char buf[40];
165
166         for (col = 0; col < n_colors; ++col) {
167                 mangle_var1(buf, 'u', col);
168 #ifdef NO_NULL_COLORS_WITH_COSTS
169                 var_idx = lpp_add_var(pi->curr_lp, buf, lpp_binary, 1.0 / (double) (1 << (col+1)) );
170 #else
171                 var_idx = lpp_add_var(pi->curr_lp, buf, lpp_binary, 1.0 / (2.0 * n_colors) );
172 #endif
173                 if (!pi->first_nnc_var_idx)
174                         pi->first_nnc_var_idx = var_idx;
175         }
176
177 #ifdef NO_NULL_COLORS_EXTRA_CSTS
178         for (col = 0; col < n_colors; ++col) {
179                 mangle_cst(buf, 'U', cst_counter++);
180                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_greater, 0);
181                 if (!pi->first_nnc_cst_idx)
182                         pi->first_nnc_cst_idx = cst_idx;
183                 lpp_set_factor_fast(pi->curr_lp, cst_idx, pi->first_nnc_var_idx+col, -1);
184         }
185 #endif
186
187 #ifndef NO_NULL_COLORS_WITH_COSTS
188         for (col = 0; col < n_colors - 1; ++col) {
189                 mangle_cst(buf, 'U', cst_counter++);
190                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_greater, 0);
191                 lpp_set_factor_fast(pi->curr_lp, cst_idx, pi->first_nnc_var_idx+col  ,  1);
192                 lpp_set_factor_fast(pi->curr_lp, cst_idx, pi->first_nnc_var_idx+col+1, -1);
193         }
194 #endif
195
196 }
197 #endif
198
199 /**
200  * Add coloring-force conditions
201  * Matrix A: knapsack constraint for each node
202  */
203 static void pi_add_constr_A(problem_instance_t *pi) {
204         pmap_entry *pme;
205
206         DBG((dbg, LEVEL_2, "Add A constraints...\n"));
207         /* iterate over all blocks */
208         pmap_foreach(pi->co->chordal_env->border_heads, pme) {
209                 struct list_head *head = pme->value;
210                 border_t *curr;
211                 bitset_t *pos_regs = bitset_alloca(pi->co->chordal_env->cls->n_regs);
212
213                 list_for_each_entry_reverse(border_t, curr, head, list)
214                         if (curr->is_def && curr->is_real && !is_removed(curr->irn)) {
215                                 int cst_idx, nnr, col;
216
217                                 nnr = get_irn_graph_nr(curr->irn);
218                                 mangle_cst(pi->buf, 'A', nnr);
219                                 cst_idx = lpp_add_cst(pi->curr_lp, pi->buf, lpp_equal, 1);
220
221                                 /* iterate over all possible colors in order */
222                                 bitset_clear_all(pos_regs);
223                                 arch_get_allocatable_regs(get_arch_env(pi->co), curr->irn, arch_pos_make_out(0), pi->co->chordal_env->cls, pos_regs);
224                                 bitset_foreach(pos_regs, col) {
225                                         int var_idx;
226                                         mangle_var2(pi->buf, 'x', nnr, col);
227                                         var_idx = lpp_add_var(pi->curr_lp, pi->buf, lpp_binary, 0);
228                                         if (!pi->first_x_var)
229                                                 pi->first_x_var = var_idx;
230                                         pi->last_x_var = var_idx;
231                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, var_idx, 1);
232 #ifdef NO_NULL_COLORS_EXTRA_CSTS
233                                         lpp_set_factor_fast(pi->curr_lp, pi->first_nnc_cst_idx+col, var_idx, 1);
234 #endif
235                                 }
236                         }
237         }
238 }
239
240 /**
241  * Checks if all nodes in @p living are live in in block @p block.
242  * @return 1 if all are live in
243  *         0 else
244  */
245 static INLINE int all_live_in(ir_node *block, pset *living) {
246         ir_node *n;
247         for (n = pset_first(living); n; n = pset_next(living))
248                 if (!is_live_in(block, n)) {
249                         pset_break(living);
250                         return 0;
251                 }
252         return 1;
253 }
254
255 /**
256  * Finds cliques in the interference graph, considering only nodes
257  * for which the color @p color is possible. Finds only 'maximal-cliques',
258  * viz cliques which are not contained in another one.
259  * Matrix B: interference constraints using cliques
260  */
261 static void pi_add_constr_B(problem_instance_t *pi, int color) {
262         enum phase_t {growing, shrinking} phase = growing;
263         border_t *b;
264         pmap_entry *pme;
265         pset *living = pset_new_ptr(SLOTS_LIVING);
266
267         DBG((dbg, LEVEL_2, "Add B constraints (col = %d)...\n", color));
268         /* iterate over all blocks */
269         pmap_foreach(pi->co->chordal_env->border_heads, pme) {
270                 ir_node *block = pme->key;
271                 struct list_head *head = pme->value;
272
273                 list_for_each_entry_reverse(border_t, b, head, list) {
274                         const ir_node *irn = b->irn;
275                         if (is_removed(irn) || !is_color_possible(irn, color))
276                                 continue;
277
278                         if (b->is_def) {
279                                 DBG((dbg, LEVEL_2, "Def %n\n", irn));
280                                 pset_insert_ptr(living, irn);
281                                 phase = growing;
282                         } else { /* is_use */
283                                 DBG((dbg, LEVEL_2, "Use %n\n", irn));
284
285                                 /* before shrinking the set, store the current 'maximum' clique;
286                                  * do NOT if clique is a single node
287                                  * do NOT if all values are live_in (in this case they were contained in a live-out clique elsewhere) */
288                                 if (phase == growing && pset_count(living) >= 2 && !all_live_in(block, living)) {
289                                         int cst_idx;
290                                         ir_node *n;
291                                         mangle_cst(pi->buf, 'B', pi->cst_counter);
292 #ifdef NO_NULL_COLORS
293                                         cst_idx = lpp_add_cst(pi->curr_lp, pi->buf, lpp_less, 0);
294 #else
295                                         cst_idx = lpp_add_cst(pi->curr_lp, pi->buf, lpp_less, 1);
296 #endif
297                                         for (n = pset_first(living); n; n = pset_next(living)) {
298                                                 int var_idx;
299                                                 mangle_var_irn(pi->buf, 'x', n, color);
300                                                 var_idx = lpp_get_var_idx(pi->curr_lp, pi->buf);
301                                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, var_idx, 1);
302                                         }
303 #ifdef NO_NULL_COLORS
304                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, pi->first_nnc_var_idx+color, -1.0);
305 #endif
306                                         pi->cst_counter++;
307                                 }
308                                 pset_remove_ptr(living, irn);
309                                 phase = shrinking;
310                         }
311                 }
312         }
313         assert(0 == pset_count(living));
314         del_pset(living);
315 }
316
317 /**
318  * Generates constraints which interrelate x with y variables.
319  * x1 and x2 have the different colors ==> y_12 = 1
320  */
321 static void pi_add_constr_E(problem_instance_t *pi) {
322         unit_t *curr;
323         bitset_t *root_regs, *arg_regs, *work_regs;
324         int cst_counter = 0;
325         unsigned nregs = pi->co->chordal_env->cls->n_regs;
326         root_regs = bitset_alloca(nregs);
327         arg_regs = bitset_alloca(nregs);
328         work_regs = bitset_alloca(nregs);
329
330         DBG((dbg, LEVEL_2, "Add E constraints...\n"));
331         /* for all roots of optimization units */
332         list_for_each_entry(unit_t, curr, &pi->co->units, units) {
333                 ir_node *root, *arg;
334                 int rootnr, argnr, color;
335                 int y_idx, i;
336                 char buf[32];
337
338                 root = curr->nodes[0];
339                 rootnr = get_irn_graph_nr(root);
340                 bitset_clear_all(root_regs);
341                 arch_get_allocatable_regs(get_arch_env(pi->co), root, arch_pos_make_out(0), pi->co->chordal_env->cls, root_regs);
342
343                 /* for all arguments of root */
344                 for (i = 1; i < curr->node_count; ++i) {
345                         arg = curr->nodes[i];
346                         argnr = get_irn_graph_nr(arg);
347                         bitset_clear_all(arg_regs);
348                         arch_get_allocatable_regs(get_arch_env(pi->co), arg, arch_pos_make_out(0), pi->co->chordal_env->cls, arg_regs);
349
350                         /* Introduce new variable and set factor in objective function */
351                         mangle_var2(buf, 'y', rootnr, argnr);
352                         y_idx = lpp_add_var(pi->curr_lp, buf, lpp_binary, curr->costs[i]);
353
354                         /* set starting value */
355                         lpp_set_start_value(pi->curr_lp, y_idx, (get_irn_col(pi->co, root) != get_irn_col(pi->co, arg)));
356
357                         /* For all colors root and arg have in common, add 2 constraints to E */
358                         bitset_copy(work_regs, root_regs);
359                         bitset_and(work_regs, arg_regs);
360                         bitset_foreach(work_regs, color) {
361                                 int root_idx, arg_idx, cst_idx;
362                                 mangle_var2(buf, 'x', rootnr, color);
363                                 root_idx = lpp_get_var_idx(pi->curr_lp, buf);
364                                 mangle_var2(buf, 'x', argnr, color);
365                                 arg_idx = lpp_get_var_idx(pi->curr_lp, buf);
366
367                                 /* add root-arg-y <= 0 */
368                                 mangle_cst(buf, 'E', cst_counter++);
369                                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_less, 0);
370                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, root_idx, 1);
371                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, arg_idx, -1);
372                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, -1);
373
374                                 /* add arg-root-y <= 0 */
375                                 mangle_cst(buf, 'E', cst_counter++);
376                                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_less, 0);
377                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, root_idx, -1);
378                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, arg_idx, 1);
379                                 lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, -1);
380                         }
381                         /* For all colors root and arg have "disjunct", add 1 constraints to E.
382                          * If root gets a color the arg is not possible to get then they will
383                          * definetly get different colors. So y has to be 1.
384                          * Vice versa for arg.
385                          */
386                         bitset_copy(work_regs, root_regs);
387                         bitset_xor(work_regs, arg_regs);
388                         bitset_foreach(work_regs, color) {
389                                 int root_idx, arg_idx, cst_idx;
390                                 mangle_var2(buf, 'x', rootnr, color);
391                                 root_idx = lpp_get_var_idx(pi->curr_lp, buf);
392                                 mangle_var2(buf, 'x', argnr, color);
393                                 arg_idx = lpp_get_var_idx(pi->curr_lp, buf);
394
395                                 mangle_cst(buf, 'E', cst_counter++);
396                                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_less, 0);
397                                 if (bitset_is_set(root_regs, color)) {
398                                         /* add root-y <= 0 */
399                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, root_idx, 1);
400                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, -1);
401                                 } else {
402                                         assert(bitset_is_set(arg_regs, color) && "bitset_xor is buggy");
403                                         /* add arg-y <= 0 */
404                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, arg_idx, 1);
405                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, -1);
406                                 }
407                         }
408                 }
409         }
410 }
411
412 static INLINE int get_costs(problem_instance_t *pi, ir_node *phi, ir_node *irn) {
413         int i;
414         unit_t *curr;
415         /* search optimization unit for phi */
416         list_for_each_entry(unit_t, curr, &pi->co->units, units)
417                 if (curr->nodes[0] == phi) {
418                         for (i=1; i<curr->node_count; ++i)
419                                 if (curr->nodes[i] == irn)
420                                         return curr->costs[i];
421                         assert(0 && "irn must occur in this ou");
422                 }
423         assert(0 && "phi must be found in a ou");
424         return 0;
425 }
426
427 static void clique_path_walker(ir_node *block, void *env) {
428         problem_instance_t *pi = env;
429         int count, arity, row, col, other_row, *costs;
430         ir_node **phis, *phi, *irn, **phi_matrix;
431         pset *done;
432         bitset_t *candidates;
433
434         /* Count all phi nodes of this block */
435         for (count=0, irn = sched_first(block); is_Phi(irn); irn = sched_next(irn))
436                 count++;
437
438         /* We at least 2 phi nodes for this class of inequalities */
439         if (count < 2)
440                 return;
441
442         /* Build the \Phi-Matrix */
443         arity = get_irn_arity(sched_first(block));
444         phis = alloca(count * sizeof(*phis));
445         costs = alloca(count * sizeof(costs));
446         phi_matrix = alloca(count*arity * sizeof(*phi_matrix));
447         candidates = bitset_alloca(count);
448
449         phi = sched_first(block);
450         for (row=0; row<count; ++row) {
451                 phis[row] = phi;
452                 for (col=0; col<arity; ++col) {
453                         ir_node *arg = get_irn_n(phi, col);
454                         /* Sort out all arguments interfering with its phi */
455                         if (nodes_interfere(pi->co->chordal_env, phi, arg)) {
456                                 phi_matrix[row*arity + col] =  NULL;
457                         } else
458                                 phi_matrix[row*arity + col] =  arg;
459                 }
460                 phi = sched_next(phi);
461         }
462
463         /* Now find the interesting patterns in the matrix:
464          * All nodes which are used at least twice in a column. */
465         /* columnwise ... */
466         for (col=0; col<arity; ++col) {
467                 done = pset_new_ptr_default();
468                 for (row=0; row<count; ++row) {
469                         irn = phi_matrix[row*arity + col];
470                         /*
471                          * is this an interfering arg (NULL)
472                          * or has the irn already been processed in this col?
473                          */
474                         if (!irn || pset_find_ptr(done, irn))
475                                 continue;
476                         else
477                                 pset_insert_ptr(done, irn);
478
479                         /* insert irn in candidates */
480                         bitset_clear_all(candidates);
481                         bitset_set(candidates, row);
482                         /* search the irn in the rows below */
483                         for (other_row = row+1; other_row<count; ++other_row)
484                                 if (irn == phi_matrix[other_row*arity + col]) {
485                                         /* found the irn in the same col in another row */
486                                         bitset_set(candidates, other_row);
487                                 }
488
489                         /* now we know all occurences of irn in this col */
490                         if (bitset_popcnt(candidates) < 2)
491                                 continue;
492
493                         /* generate an unequation finally.
494                          * phis are indexed in the bitset,
495                          * shared argument is irn
496                          * rhs is phi_count - 1 */
497                         {
498                                 char buf[32];
499                                 ir_node *root;
500                                 int pos, irnnr, rootnr, cst_idx, y_idx, cst_counter = 0;
501                                 int minimal_unequal_count = bitset_popcnt(candidates)-1;
502
503                                 irnnr = get_irn_graph_nr(irn);
504                                 mangle_cst(buf, 'M', cst_counter++);
505                                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_greater, minimal_unequal_count);
506
507                                 /* for all phis */
508                                 bitset_foreach(candidates, pos) {
509                                         root = phis[pos];
510                                         rootnr = get_irn_graph_nr(root);
511                                         mangle_var2(buf, 'y', rootnr, irnnr);
512                                         y_idx = lpp_get_var_idx(pi->curr_lp, buf);
513                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, 1);
514                                 }
515                         }
516                 }
517                 del_pset(done); /* clear set for next row */
518         } /*next col*/
519 }
520
521 /**
522  * Matrix M: Multi-Arg-Use. Interrelates different \phi-functions
523  * in the same block, iff they use the same arg at the same pos.
524  * Only one of the phis can get the arg.
525  */
526 static void pi_add_clique_path_cstr(problem_instance_t *pi) {
527         DBG((dbg, LEVEL_2, "Adding clique path constraints...\n"));
528         dom_tree_walk_irg(get_irg(pi->co), clique_path_walker, NULL, pi);
529 }
530
531 #ifndef PATH_CONSTRAINTS_FOR_CLASSES
532 /**
533  * Matrix P: Path contraints.
534  * If 2 nodes interfere and there is a path of equal-color-edges
535  * connecting them, then at least one of those equal-color-edges
536  * will break and cause some costs.
537  */
538 static void pi_add_path_cstr(problem_instance_t *pi) {
539         unit_t *curr;
540         int cst_counter = 0;
541         DBG((dbg, LEVEL_2, "Adding path constraints...\n"));
542
543         /* for all optimization units (only phis) */
544         list_for_each_entry(unit_t, curr, &pi->co->units, units) {
545                 int i, o, rootnr;
546
547                 if (curr->min_nodes_costs == 0)
548                         continue;
549
550                 rootnr = get_irn_graph_nr(curr->nodes[0]);
551                 /* check all argument pairs for interference */
552                 for (i=1; i<curr->node_count; ++i) {
553                         const ir_node *arg1 = curr->nodes[i];
554                         int arg1nr = get_irn_graph_nr(arg1);
555                         for (o=i+1; o<curr->node_count; ++o) {
556                                 const ir_node *arg2 = curr->nodes[o];
557                                 int arg2nr = get_irn_graph_nr(arg2);
558                                 if (nodes_interfere(pi->co->chordal_env, arg1, arg2)) {
559                                         int cst_idx, y_idx;
560                                         char buf[32];
561
562                                         mangle_cst(buf, 'P', cst_counter++);
563                                         cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_greater, 1);
564
565                                         mangle_var2(buf, 'y', rootnr, arg1nr);
566                                         y_idx = lpp_get_var_idx(pi->curr_lp, buf);
567                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, 1);
568
569                                         mangle_var2(buf, 'y', rootnr, arg2nr);
570                                         y_idx = lpp_get_var_idx(pi->curr_lp, buf);
571                                         lpp_set_factor_fast(pi->curr_lp, cst_idx, y_idx, 1);
572                                 }
573                         }
574                 }
575         }
576 }
577 #endif
578
579 #ifdef PATH_CONSTRAINTS_FOR_CLASSES
580 static INLINE int get_y_var_idx(problem_instance_t *pi, int nnr1, int nnr2) {
581         int res;
582         char buf[30];
583
584         mangle_var2(buf, 'y', nnr1, nnr2);
585         if ((res = lpp_get_var_idx(pi->curr_lp, buf)) != -1)
586                 return res;
587
588         mangle_var2(buf, 'y', nnr2, nnr1);
589         if ((res = lpp_get_var_idx(pi->curr_lp, buf)) != -1)
590                 return res;
591
592         assert(0 && "One of them must work");
593   return -1;
594 }
595
596 static void check_ecc_and_add_cut(problem_instance_t *pi, ir_node **path, int length, pset *remain, ir_node *tgt) {
597         if (path[length-1] == tgt) { /* we found a path */
598                 int cst_idx, var_idx, i, nnr1, nnr2;
599                 char buf[30];
600
601                 /* add cut to ilp */
602                 mangle_cst(buf, 'Q', pi->cst_counter++);
603                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_greater, 1);
604
605                 /* add all vars along the path */
606                 nnr2 = get_irn_graph_nr(path[0]);
607                 for (i=1; i<length; ++i) {
608                         nnr1 = nnr2;
609                         nnr2 = get_irn_graph_nr(path[i]);
610                         var_idx = get_y_var_idx(pi, nnr1, nnr2);
611                         lpp_set_factor_fast(pi->curr_lp, cst_idx, var_idx, 1);
612                 }
613         } else { /* try to extend the path */
614                 be_chordal_env_t *cenv = pi->co->chordal_env;
615                 const ir_edge_t *edge;
616                 ir_node *end = path[length-1];
617                 ir_node **next = alloca(pset_count(remain) * sizeof(*next));
618                 int i, o, max, next_pos = 0;
619                 pset *done = pset_new_ptr_default();
620
621                 /* find all potential next nodes on path */
622                 /*  args of phis */
623                 if (is_Phi(end))
624                         for(i=0, max=get_irn_arity(end); i<max; ++i) {
625                                 ir_node *arg = get_irn_n(end, i);
626                                 if (!pset_find_ptr(done, arg) && pset_find_ptr(remain, arg)) {
627                                         next[next_pos++] = arg;
628                                         pset_insert_ptr(done, arg);
629                                 }
630                         }
631                 /*  outs of phis and other nodes */
632                 foreach_out_edge(end, edge) {
633                         ir_node *user = edge->src;
634                         if (is_Phi(user) && !pset_find_ptr(done, user) && pset_find_ptr(remain, user)) {
635                                 next[next_pos++] = user;
636                                 pset_insert_ptr(done, user);
637                         }
638                 }
639                 del_pset(done);
640
641
642                 /* delete all potential nodes with interferences to other nodes in the path */
643                 for (i=0; i<next_pos; ++i) {
644                         ir_node *nn = next[i];
645
646                         /* if next is the tgt, it may interfere with path[0],
647                          * so skip the first check */
648                         o = (nn == tgt && length > 1) ? 1 : 0;
649
650                         for(; o<length; ++o)
651                                 if (nodes_interfere(cenv, nn, path[o])) {
652                                         next[i] = NULL;
653                                         break;
654                                 }
655                 }
656                 /* now we have all possible nodes in next; impossibles are NULL */
657
658                 /* try to finish path with all possible nodes */
659                 for (i=0; i<next_pos; ++i) {
660                         if (!next[i]) /* this was an impossible node */
661                                 continue;
662
663                         path[length] = next[i];
664                         pset_remove_ptr(remain, next[i]);
665                         check_ecc_and_add_cut(pi, path, length+1, remain, tgt);
666                         pset_insert_ptr(remain, next[i]);
667                 }
668         }
669 }
670
671 static void path_cstr_for_classes_walker(ir_node *irn, void *env) {
672         problem_instance_t *pi = env;
673         be_chordal_env_t *cenv;
674         int i, o, max;
675         ir_node *m, **cls;
676         pset *class = get_phi_class(irn);
677         if (!class || pset_find_ptr(pi->done, class))
678                 return;
679
680         pset_insert_ptr(pi->done, class);
681
682         /* pset to array */
683         max = pset_count(class);
684         cls = alloca(max * sizeof(*cls));
685         for(i=0, m = pset_first(class); m; i++, m = pset_next(class)) {
686                 DBG((dbg, LEVEL_1, " class member: %+F\n", m));
687                 cls[i] = m;
688         }
689
690         cenv = pi->co->chordal_env;
691         for(i=0; i<max; ++i) {
692                 ir_node **path = alloca(max * sizeof(*path));
693                 pset *remain = pset_new_ptr(8);
694                 pset_insert_pset_ptr(remain, class);
695
696                 /* add cls[i] to path and remove it from remainder */
697                 path[0] = cls[i];
698                 pset_remove_ptr(remain, cls[i]);
699
700                 for(o=i+1; o<max; ++o)
701                         if (nodes_interfere(cenv, cls[i], cls[o]))
702                                 check_ecc_and_add_cut(pi, path, 1, remain, cls[o]);
703
704                 /* insert back into remainder */
705                 pset_insert_ptr(remain, cls[i]);
706         }
707 }
708
709
710 /**
711  * Matrix P: Path contraints.
712  * If 2 nodes interfere and there is a path of equal-color-edges
713  * connecting them, then at least one of those equal-color-edges
714  * will break and cause some costs.
715  */
716 static void pi_add_path_cstr_for_classes(problem_instance_t *pi) {
717         DBG((dbg, LEVEL_2, "Adding path constraints for phi classes...\n"));
718         pi->cst_counter = 0;
719         pi->done = pset_new_ptr_default();
720         irg_walk_graph(get_irg(pi->co), path_cstr_for_classes_walker, NULL, pi);
721         del_pset(pi->done);
722 }
723 #endif
724
725 #ifdef PRECOLOR_MAX_CLIQUE
726 struct pre_col {
727         problem_instance_t *pi;
728         pset **clique;
729 };
730
731 #define has_reg_class(pi,irn) \
732   (arch_get_irn_reg_class(pi->co->chordal_env->session_env->main_env->arch_env, \
733                           irn, arch_pos_make_out(0)) == pi->co->chordal_env->cls)
734
735 static void preColoringWalker(ir_node *bl, void *env) {
736         struct pre_col *e = env;
737         pset **clique = e->clique;
738         pset *max_clique = clique ? *clique : NULL;
739         int max = max_clique ? pset_count(max_clique) : 0;
740         problem_instance_t *pi = e->pi;
741
742         int i, n;
743         pset *live       = pset_new_ptr_default();
744         ir_node *irn;
745         irn_live_t *li;
746
747         /* as always, bring the live end nodes to life here */
748         live_foreach(bl, li) {
749           if(live_is_end(li) && has_reg_class(pi, li->irn)) {
750             pset_insert_ptr(live, irn);
751           }
752         }
753
754         sched_foreach_reverse(bl, irn) {
755                 int pres = pset_count(live);
756
757                 if(pres > max) {
758                         max = pres;
759                         if(max_clique)
760                                 del_pset(max_clique);
761
762                         max_clique = pset_new_ptr_default();
763                         pset_insert_pset_ptr(max_clique, live);
764                 }
765
766
767
768                 if(has_reg_class(pi, irn))
769                         pset_remove_ptr(live, irn);
770
771                 for(i = 0, n = get_irn_arity(irn); i < n; ++i) {
772                         ir_node *op = get_irn_n(irn, i);
773                         if(has_reg_class(pi, op) && !is_Phi(irn))
774                                 pset_insert_ptr(live, op);
775                 }
776         }
777
778   del_pset(live);
779   *clique = max_clique;
780 }
781
782 static void pi_add_constr_preColoring(problem_instance_t *pi) {
783         ir_node *irn;
784         int cst_counter, color;
785         struct pre_col pre_col;
786
787         pre_col.clique = NULL;
788         pre_col.pi = pi;
789
790         dom_tree_walk_irg(get_irg(pi->co), preColoringWalker, NULL, &pre_col);
791
792         color = 0;
793         for (irn = pset_first(*pre_col.clique); irn; irn = pset_next(*pre_col.clique)) {
794                 int cst_idx, var_idx, nnr = get_irn_graph_nr(irn);
795                 char buf[100];
796
797                 mangle_cst(buf, 'K', cst_counter++);
798                 cst_idx = lpp_add_cst(pi->curr_lp, buf, lpp_equal, 1);
799
800                 mangle_var2(buf, 'x', nnr, color++);
801                 var_idx = lpp_get_var_idx(pi->curr_lp, buf);
802                 lpp_set_factor_fast(pi->curr_lp, cst_idx, var_idx, 1);
803         }
804 }
805 #endif
806
807 /**
808  * Generate the initial problem matrices and vectors.
809  */
810 static problem_instance_t *new_pi(const copy_opt_t *co) {
811         problem_instance_t *pi;
812         int col;
813
814         DBG((dbg, LEVEL_2, "Generating new instance...\n"));
815         pi = xcalloc(1, sizeof(*pi));
816         pi->co = co;
817         pi->removed = pset_new_ptr_default();
818         INIT_LIST_HEAD(&pi->simplicials);
819         pi->dilp     = new_lpp(co->name, lpp_minimize);
820
821         /* problem size reduction */
822         pi_find_simplicials(pi);
823         if (pi->all_simplicial)
824                 return pi;
825
826         /* built objective and constraints */
827         pi->curr_lp = pi->dilp;
828 #ifdef NO_NULL_COLORS
829         pi_add_constr_no_null_colors(pi);
830 #endif
831         pi_add_constr_A(pi);
832         for (col = 0; col < pi->co->chordal_env->cls->n_regs; ++col)
833                 pi_add_constr_B(pi, col);
834         pi_add_constr_E(pi);
835
836 #ifdef PATH_CONSTRAINTS_FOR_CLASSES
837         pi_add_path_cstr_for_classes(pi);
838 #else
839         pi_add_path_cstr(pi);
840 #endif
841         pi_add_clique_path_cstr(pi);
842 #ifdef PRECOLOR_MAX_CLIQUE
843         pi_add_constr_preColoring(pi);
844 #endif
845
846         return pi;
847 }
848
849 /**
850  * Clean the problem instance
851  */
852 static void free_pi(problem_instance_t *pi) {
853         simpl_t *simpl, *tmp;
854
855         DBG((dbg, LEVEL_2, "Free instance...\n"));
856         free_lpp(pi->dilp);
857         list_for_each_entry_safe(simpl_t, simpl, tmp, &pi->simplicials, chain)
858                 free(simpl);
859         del_pset(pi->removed);
860         free(pi);
861 }
862
863 /**
864  * Set starting values for the mip problem according
865  * to the current coloring of the graph.
866  */
867 static void pi_set_start_sol(problem_instance_t *pi) {
868         int i;
869         char var_name[64];
870         DBG((dbg, LEVEL_2, "Set start solution...\n"));
871         for (i=pi->first_x_var; i<=pi->last_x_var; ++i) {
872                 int nnr, col;
873                 double val;
874                 /* get variable name */
875                 lpp_get_var_name(pi->curr_lp, i, var_name, sizeof(var_name));
876                 /* split into components */
877                 if (split_var(var_name, &nnr, &col) == 2) {
878                         assert(get_irn_col(pi->co, get_irn_for_graph_nr(get_irg(pi->co), nnr)) != -1);
879                         val = (get_irn_col(pi->co, get_irn_for_graph_nr(get_irg(pi->co), nnr)) == col) ? 1 : 0;
880                         lpp_set_start_value(pi->curr_lp, i, val);
881                 } else {
882                         fprintf(stderr, "Variable name is: %s\n", var_name);
883                         assert(0 && "x vars always look like this 'x123_45'");
884                 }
885         }
886 }
887
888 /**
889  * Invoke a solver
890  */
891 static void pi_solve_ilp(problem_instance_t *pi) {
892   double lower_bound;
893
894         pi_set_start_sol(pi);
895         lower_bound = co_get_lower_bound(pi->co) - co_get_inevit_copy_costs(pi->co);
896         lpp_set_bound(pi->curr_lp, lower_bound);
897         lpp_solve_net(pi->curr_lp, LPP_HOST, LPP_SOLVER);
898 //      lpp_solve_cplex(pi->curr_lp);
899         DBG((dbg, LEVEL_1, "Solution time: %.2f\n", pi->curr_lp->sol_time));
900 }
901
902 /**
903  * Set the color of all simplicial nodes removed form
904  * the graph before transforming it to an ilp.
905  */
906 static void pi_set_simplicials(problem_instance_t *pi) {
907         simpl_t *simpl, *tmp;
908         bitset_t *used_cols = bitset_alloca(arch_register_class_n_regs(pi->co->chordal_env->cls));
909
910         DBG((dbg, LEVEL_2, "Set simplicials...\n"));
911         /* color the simplicial nodes in right order */
912         list_for_each_entry_safe(simpl_t, simpl, tmp, &pi->simplicials, chain) {
913                 int free_col;
914                 ir_node *other_irn, *irn;
915                 if_node_t *other, *ifn;
916
917                 /* get free color by inspecting all neighbors */
918                 ifn = simpl->ifn;
919                 irn = get_irn_for_graph_nr(get_irg(pi->co), ifn->nnr);
920                 bitset_clear_all(used_cols);
921                 foreach_neighb(ifn, other) {
922                         other_irn = get_irn_for_graph_nr(get_irg(pi->co), other->nnr);
923                         if (!is_removed(other_irn)) /* only inspect nodes which are in graph right now */
924                                 bitset_set(used_cols, get_irn_col(pi->co, other_irn));
925                 }
926
927                 /* now all bits not set are possible colors */
928                 free_col = bitset_next_clear(used_cols, 0);
929                 assert(free_col != -1 && "No free color found. This can not be.");
930                 set_irn_col(pi->co, irn, free_col);
931                 pset_remove_ptr(pi->removed, irn); /* irn is back in graph again */
932         }
933 }
934
935 /**
936  * Sets the colors of irns according to the values of variables
937  * provided by the solution of the solver.
938  */
939 static int pi_apply_solution(problem_instance_t *pi) {
940         int res = 1, i;
941         double *sol;
942         lpp_sol_state_t state;
943         DBG((dbg, LEVEL_2, "Applying solution...\n"));
944
945 #ifdef DO_STAT
946         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
947         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
948         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
949         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
950 #endif
951
952         sol = xmalloc((pi->last_x_var - pi->first_x_var + 1) * sizeof(*sol));
953         state = lpp_get_solution(pi->curr_lp, sol, pi->first_x_var, pi->last_x_var);
954         if (state != lpp_optimal) {
955                 printf("WARNING %s: Solution state is not 'optimal': %d\n", pi->co->name, state);
956                 assert(state >= lpp_feasible && "The solution should at least be feasible!");
957                 res = 0;
958         }
959         for (i=0; i<pi->last_x_var - pi->first_x_var + 1; ++i) {
960                 int nnr, col;
961                 char var_name[64];
962
963                 if (sol[i] > 1-EPSILON) { /* split varibale name into components */
964                         lpp_get_var_name(pi->curr_lp, pi->first_x_var+i, var_name, sizeof(var_name));
965                         if (split_var(var_name, &nnr, &col) == 2) {
966                                 DBG((dbg, LEVEL_2, "Irn %n  Idx %d  Var %s  Val %f\n", get_irn_for_graph_nr(get_irg(pi->co), nnr), i, var_name, sol[i]));
967                                 DBG((dbg, LEVEL_2, "x%d = %d\n", nnr, col));
968                                 set_irn_col(pi->co, get_irn_for_graph_nr(get_irg(pi->co), nnr), col);
969                         } else
970                                 assert(0 && "This should be a x-var");
971                 }
972         }
973         return res;
974 }
975
976 int co_ilp_opt(copy_opt_t *co, double time_limit) {
977         int res = 1;
978         problem_instance_t *pi;
979
980         dbg = firm_dbg_register("ir.be.copyoptilp");
981         if (!strcmp(co->name, DEBUG_IRG))
982                 firm_dbg_set_mask(dbg, DEBUG_IRG_LVL_ILP);
983         else
984                 firm_dbg_set_mask(dbg, DEBUG_LVL_ILP);
985
986         pi = new_pi(co);
987         if (!pi->all_simplicial) {
988 #ifdef DUMP_MPS
989                 char buf[512];
990                 snprintf(buf, sizeof(buf), "%s.mps", co->name);
991                 lpp_dump(pi->curr_lp, buf);
992 #endif
993                 lpp_set_time_limit(pi->curr_lp, time_limit);
994                 pi_solve_ilp(pi);
995                 res = pi_apply_solution(pi);
996                 pi_set_simplicials(pi);
997         }
998         free_pi(pi);
999         return res;
1000 }