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