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