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