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