Added a set_break()
[libfirm] / ir / be / becopyilp2.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                28.02.2006
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  *
7  *
8  * ILP formalization using G=(V, E, Q):
9  *  - 2 class of variables: coloring vars x_ic   and   equal color vars y_ij
10  *  - Path constraints
11  *  - Clique-star constraints
12  *
13  *
14  *      \min \sum_{ (i,j) \in Q }  w_ij y_ij
15  *
16  *              \sum_c x_nc                     =  1                    n \in N, c \in C
17  *
18  *              x_nc                            =  0                    n \in N, c \not\in C(n)
19  *
20  *              \sum x_nc                       <= 1                    x_nc \in Clique \in AllCliques,  c \in C
21  *
22  *              \sum_{e \in p} y_e      >= 1                    p \in P         path constraints
23  *
24  *              \sum_{e \in cs} y_e     >= |cs| - 1             cs \in CP       clique-star constraints
25  *
26  *              x_nc, y_ij \in N,   w_ij \in R^+
27  */
28
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif /* HAVE_CONFIG_H */
32
33 #ifdef WITH_ILP
34
35 #include <bitset.h>
36 #include "pdeq.h"
37
38 #include "irtools.h"
39 #include "irgwalk.h"
40 #include "becopyilp_t.h"
41 #include "beifg_t.h"
42 #include "besched_t.h"
43 #include "benodesets.h"
44
45 #define DEBUG_LVL 1
46
47 typedef struct _local_env_t {
48         double time_limit;
49         int first_x_var, last_x_var;
50         pmap *nr_2_irn;
51         DEBUG_ONLY(firm_dbg_module_t *dbg;)
52 } local_env_t;
53
54 static void build_coloring_cstr(ilp_env_t *ienv) {
55         be_ifg_t *ifg = ienv->co->cenv->ifg;
56         void *iter = be_ifg_nodes_iter_alloca(ifg);
57         bitset_t *colors;
58         ir_node *irn;
59         char buf[16];
60
61         colors = bitset_alloca(arch_register_class_n_regs(ienv->co->cls));
62
63         be_ifg_foreach_node(ifg, iter, irn)
64                 if (!sr_is_removed(ienv->sr, irn)) {
65                         int col, cst_idx;
66                         arch_register_req_t req;
67                         int curr_node_color = get_irn_col(ienv->co, irn);
68                         int node_nr = (int)get_irn_node_nr(irn);
69                         local_env_t *lenv = ienv->env;
70
71                         pmap_insert(lenv->nr_2_irn, INT_TO_PTR(node_nr), irn);
72
73                         arch_get_register_req(ienv->co->aenv, &req, irn, -1);
74
75                         /* get assignable colors */
76                         if (arch_register_req_is(&req, limited))
77                                 req.limited(req.limited_env, colors);
78                         else {
79                                 arch_register_class_put(req.cls, colors);
80                                 // bitset_andnot(colors, ienv->co->cenv->ignore_colors);
81                         }
82
83                         /* add the coloring constraint */
84                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
85
86                         bitset_foreach(colors, col) {
87                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
88                                 lpp_set_start_value(ienv->lp, var_idx, (col == curr_node_color) ? 1.0 : 0.0);
89                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
90
91                                 lenv->last_x_var = var_idx;
92                                 if (lenv->first_x_var == -1)
93                                         lenv->first_x_var = var_idx;
94                         }
95
96                         /* add register constraint constraints */
97                         bitset_foreach_clear(colors, col) {
98                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
99                                 int var_idx = lpp_add_var(ienv->lp, name_cdd(buf, 'x', node_nr, col), lpp_binary, 0.0);
100                                 lpp_set_start_value(ienv->lp, var_idx, 0.0);
101                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
102
103                                 lenv->last_x_var = var_idx;
104                         }
105                 }
106 }
107
108 static void build_interference_cstr(ilp_env_t *ienv) {
109         lpp_t *lpp = ienv->lp;
110         be_ifg_t *ifg = ienv->co->cenv->ifg;
111         int n_colors = arch_register_class_n_regs(ienv->co->cls);
112         int i, col;
113
114         void *iter = be_ifg_cliques_iter_alloca(ifg);
115         ir_node **clique = alloca(sizeof(*clique) * n_colors);
116         int size;
117
118         char buf[16];
119
120         /* for each maximal clique */
121         be_ifg_foreach_clique(ifg, iter, clique, &size) {
122                 int realsize = 0;
123
124                 for (i=0; i<size; ++i)
125                         if (!sr_is_removed(ienv->sr, clique[i]))
126                                 ++realsize;
127
128                 if (realsize < 2)
129                         continue;
130
131                 /* for all colors */
132                 for (col=0; col<n_colors; ++col) {
133                         int cst_idx = lpp_add_cst(lpp, NULL, lpp_less, 1.0);
134
135                         /* for each member of this clique */
136                         for (i=0; i<size; ++i) {
137                                 ir_node *irn = clique[i];
138
139                                 if (!sr_is_removed(ienv->sr, irn)) {
140                                         int var_idx = lpp_get_var_idx(lpp, name_cdd(buf, 'x', (int)get_irn_node_nr(irn), col));
141                                         lpp_set_factor_fast(lpp, cst_idx, var_idx, 1);
142                                 }
143                         }
144                 }
145         }
146 }
147
148
149 /**
150  * TODO: Remove the dependency of the opt-units data structure
151  *       by walking over all affinity edges. Graph structure
152  *       does not provide this walker, yet.
153  */
154 static void build_affinity_cstr(ilp_env_t *ienv) {
155         unit_t *curr;
156         int n_colors = arch_register_class_n_regs(ienv->co->cls);
157
158         /* for all optimization units */
159         list_for_each_entry(unit_t, curr, &ienv->co->units, units) {
160                 ir_node *root, *arg;
161                 int root_nr, arg_nr, i, col, y_idx, root_idx, arg_idx;
162                 char buf[16];
163                 int root_col, arg_col;
164
165                 root = curr->nodes[0];
166                 root_nr = (int) get_irn_node_nr(root);
167                 root_col = get_irn_col(ienv->co, root);
168
169                 for (i = 1; i < curr->node_count; ++i) {
170                         arg = curr->nodes[i];
171                         arg_nr = (int) get_irn_node_nr(arg);
172                         arg_col = get_irn_col(ienv->co, arg);
173
174                         /* add a new affinity variable */
175                         y_idx = lpp_add_var(ienv->lp, name_cdd_sorted(buf, 'y', root_nr, arg_nr), lpp_binary, curr->costs[i]);
176                         lpp_set_start_value(ienv->lp, y_idx, (root_col==arg_col) ? 0.0 : 1.0);
177
178                         /* add constraints relating the affinity var to the color vars */
179                         for (col=0; col<n_colors; ++col) {
180                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_less, 0.0);
181                                 root_idx = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', root_nr, col));
182                                 arg_idx  = lpp_get_var_idx(ienv->lp, name_cdd(buf, 'x', arg_nr,  col));
183
184                                 lpp_set_factor_fast(ienv->lp, cst_idx, root_idx,  1.0);
185                                 lpp_set_factor_fast(ienv->lp, cst_idx, arg_idx,  -1.0);
186                                 lpp_set_factor_fast(ienv->lp, cst_idx, y_idx, -1.0);
187                         }
188                 }
189         }
190 }
191
192 /**
193  * Helping stuff for build_clique_star_cstr
194  */
195 typedef struct _edge_t {
196         ir_node *n1, *n2;
197 } edge_t;
198
199 static int compare_edge_t(const void *k1, const void *k2, size_t size) {
200         const edge_t *e1 = k1;
201         const edge_t *e2 = k2;
202
203         return ! (e1->n1 == e2->n1   &&   e1->n2 == e2->n2);
204 }
205
206 #define HASH_EDGE(e) (nodeset_hash((e)->n1) ^ nodeset_hash((e)->n2))
207
208 static INLINE edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
209         edge_t new_edge;
210
211         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
212                 new_edge.n1 = n1;
213                 new_edge.n2 = n2;
214         } else {
215                 new_edge.n1 = n2;
216                 new_edge.n2 = n1;
217         }
218         (*counter)++;
219         return set_insert(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
220 }
221
222 static INLINE edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2) {
223         edge_t new_edge;
224
225         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
226                 new_edge.n1 = n1;
227                 new_edge.n2 = n2;
228         } else {
229                 new_edge.n1 = n2;
230                 new_edge.n2 = n1;
231         }
232         return set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
233 }
234
235 static INLINE void remove_edge(set *edges, ir_node *n1, ir_node *n2, int *counter) {
236         edge_t new_edge, *e;
237
238         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
239                 new_edge.n1 = n1;
240                 new_edge.n2 = n2;
241         } else {
242                 new_edge.n1 = n2;
243                 new_edge.n2 = n1;
244         }
245         e = set_find(edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
246         if (e) {
247                 e->n1 = NULL;
248                 e->n2 = NULL;
249                 (*counter)--;
250         }
251 }
252
253 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
254
255 /**
256  * Search for an interference clique and an external node
257  * with affinity edges to all nodes of the clique.
258  * At most 1 node of the clique can be colored equally with the external node.
259  */
260 static void build_clique_star_cstr(ilp_env_t *ienv) {
261         affinity_node_t *aff;
262
263         /* for each node with affinity edges */
264         co_gs_foreach_aff_node(ienv->co, aff) {
265                 struct obstack ob;
266                 neighb_t *nbr;
267                 ir_node *center = aff->irn;
268                 ir_node **nodes;
269                 set *edges;
270                 int i, o, n_nodes, n_edges;
271
272                 obstack_init(&ob);
273                 edges = new_set(compare_edge_t, 8);
274
275                 /* get all affinity neighbours */
276                 n_nodes = 0;
277                 co_gs_foreach_neighb(aff, nbr) {
278                         obstack_ptr_grow(&ob, nbr->irn);
279                         ++n_nodes;
280                 }
281                 nodes = obstack_finish(&ob);
282
283                 /* get all interference edges between these */
284                 n_edges = 0;
285                 for (i=0; i<n_nodes; ++i)
286                         for (o=0; o<i; ++o)
287                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
288                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
289
290                 /* cover all these interference edges with maximal cliques */
291                 while (n_edges) {
292                         edge_t *e;
293                         pset *clique = pset_new_ptr(8);
294                         int growed;
295
296                         /* get 2 starting nodes to form a clique */
297                         for (e=set_first(edges); !e->n1; e=set_next(edges))
298                                 /*nothing*/ ;
299
300                         /* we could be stepped out of the loop before the set iterated to the end */
301                         set_break(edges);
302
303                         pset_insert_ptr(clique, e->n1);
304                         pset_insert_ptr(clique, e->n2);
305                         remove_edge(edges, e->n1, e->n2, &n_edges);
306
307                         /* while the clique is growing */
308                         do {
309                                 growed = 0;
310
311                                 /* search for a candidate to extend the clique */
312                                 for (i=0; i<n_nodes; ++i) {
313                                         ir_node *member, *cand = nodes[i];
314                                         int is_cand;
315
316                                         /* if its already in the clique try the next */
317                                         if (pset_find_ptr(clique, cand))
318                                                 continue;
319
320                                         /* are there all necessary interferences? */
321                                         is_cand = 1;
322                                         pset_foreach(clique, member) {
323                                                 if (!find_edge(edges, cand, member)) {
324                                                         is_cand = 0;
325                                                         pset_break(clique);
326                                                         break;
327                                                 }
328                                         }
329
330                                         /* now we know if we have a clique extender */
331                                         if (is_cand) {
332                                                 /* first remove all covered edges */
333                                                 pset_foreach(clique, member)
334                                                         remove_edge(edges, cand, member, &n_edges);
335
336                                                 /* insert into clique */
337                                                 pset_insert_ptr(clique, cand);
338                                                 growed = 1;
339                                                 break;
340                                         }
341                                 }
342                         } while (growed);
343
344                         /* now the clique is maximal. Finally add the constraint */
345                         {
346                                 ir_node *member;
347                                 int var_idx, cst_idx, center_nr, member_nr;
348                                 char buf[16];
349
350                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, pset_count(clique)-1);
351                                 center_nr = get_irn_node_nr(center);
352
353                                 pset_foreach(clique, member) {
354                                         member_nr = get_irn_node_nr(member);
355                                         var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', center_nr, member_nr));
356                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
357                                 }
358                         }
359
360                         del_pset(clique);
361                 }
362
363                 del_set(edges);
364                 obstack_free(&ob, NULL);
365         }
366 }
367
368
369 static void extend_path(ilp_env_t *ienv, pdeq *path, ir_node *irn) {
370         be_ifg_t *ifg = ienv->co->cenv->ifg;
371         int i, len;
372         ir_node **curr_path;
373         affinity_node_t *aff;
374         neighb_t *nbr;
375
376         /* do not walk backwards or in circles */
377         if (pdeq_contains(path, irn))
378                 return;
379
380         /* insert the new irn */
381         pdeq_putr(path, irn);
382
383
384
385         /* check for forbidden interferences */
386         len = pdeq_len(path);
387         curr_path = alloca(len * sizeof(*curr_path));
388         pdeq_copyl(path, (const void **)curr_path);
389
390         for (i=1; i<len; ++i)
391                 if (be_ifg_connected(ifg, irn, curr_path[i]))
392                         goto end;
393
394
395
396         /* check for terminating interference */
397         if (be_ifg_connected(ifg, irn, curr_path[0])) {
398
399                 /* One node is not a path. */
400                 /* And a path of length 2 is covered by a clique star constraint. */
401                 if (len > 2) {
402                         /* finally build the constraint */
403                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater, 1.0);
404                         for (i=1; i<len; ++i) {
405                                 char buf[16];
406                                 int nr_1    = get_irn_node_nr(curr_path[i-1]);
407                                 int nr_2    = get_irn_node_nr(curr_path[i]);
408                                 int var_idx = lpp_get_var_idx(ienv->lp, name_cdd_sorted(buf, 'y', nr_1, nr_2));
409                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
410                         }
411                 }
412
413                 /* this path cannot be extended anymore */
414                 goto end;
415         }
416
417
418
419         /* recursively extend the path */
420         aff = get_affinity_info(ienv->co, irn);
421         co_gs_foreach_neighb(aff, nbr)
422                 extend_path(ienv, path, nbr->irn);
423
424
425 end:
426         /* remove the irn */
427         pdeq_getr(path);
428
429 }
430
431 /**
432  *  Search a path of affinity edges, whose ends are connected
433  *  by an interference edge and there are no other interference
434  *  edges in between.
435  *  Then at least one of these affinity edges must break.
436  */
437 static void build_path_cstr(ilp_env_t *ienv) {
438         affinity_node_t *aff_info;
439
440         /* for each node with affinity edges */
441         co_gs_foreach_aff_node(ienv->co, aff_info) {
442                 pdeq *path = new_pdeq();
443
444                 extend_path(ienv, path, aff_info->irn);
445
446                 del_pdeq(path);
447         }
448 }
449
450 static void ilp2_build(ilp_env_t *ienv) {
451         local_env_t *lenv = ienv->env;
452         int lower_bound;
453
454         ienv->lp = new_lpp(ienv->co->name, lpp_minimize);
455         build_coloring_cstr(ienv);
456         build_interference_cstr(ienv);
457         build_affinity_cstr(ienv);
458         build_clique_star_cstr(ienv);
459         build_path_cstr(ienv);
460
461         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
462         lpp_set_bound(ienv->lp, lower_bound);
463         lpp_set_time_limit(ienv->lp, lenv->time_limit);
464 }
465
466 static void ilp2_apply(ilp_env_t *ienv) {
467         local_env_t *lenv = ienv->env;
468         double *sol;
469         lpp_sol_state_t state;
470         int i, count;
471
472         /* first check if there was sth. to optimize */
473         if (lenv->first_x_var >= 0) {
474
475                 count = lenv->last_x_var - lenv->first_x_var + 1;
476                 sol = xmalloc(count * sizeof(sol[0]));
477                 state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
478                 if (state != lpp_optimal) {
479                         printf("WARNING %s: Solution state is not 'optimal': %d\n", ienv->co->name, state);
480                         assert(state >= lpp_feasible && "The solution should at least be feasible!");
481                 }
482
483                 for (i=0; i<count; ++i) {
484                         int nodenr, color;
485                         char var_name[16];
486
487                         if (sol[i] > 1-EPSILON) { /* split variable name into components */
488                                 lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
489
490                                 if (sscanf(var_name, "x_%d_%d", &nodenr, &color) == 2) {
491                                         ir_node *irn = pmap_get(lenv->nr_2_irn, INT_TO_PTR(nodenr));
492                                         assert(irn && "This node number must be present in the map");
493
494                                         set_irn_col(ienv->co, irn, color);
495                                 } else
496                                         assert(0 && "This should be a x-var");
497                         }
498                 }
499         }
500
501 #ifdef COPYOPT_STAT
502         /* TODO adapt to multiple possible ILPs */
503         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
504         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
505         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
506         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
507 #endif
508 }
509
510 int co_solve_ilp2(copy_opt_t *co) {
511         lpp_sol_state_t sol_state;
512         ilp_env_t *ienv;
513         local_env_t my;
514
515         ASSERT_OU_AVAIL(co); //See build_clique_st
516         ASSERT_GS_AVAIL(co);
517
518         my.time_limit  = 0;
519         my.first_x_var = -1;
520         my.last_x_var  = -1;
521         my.nr_2_irn    = pmap_create();
522         FIRM_DBG_REGISTER(my.dbg, "firm.be.coilp2");
523
524         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
525
526         sol_state = ilp_go(ienv);
527
528         pmap_destroy(my.nr_2_irn);
529         free_ilp_env(ienv);
530
531         return sol_state == lpp_optimal;
532 }
533
534 #else /* WITH_ILP */
535
536 static void only_that_you_can_compile_without_WITH_ILP_defined(void) {
537 }
538
539 #endif /* WITH_ILP */