beifg: Let be_ifg_foreach_node() declare the node variable.
[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 "be_t.h"
49 #include "bitset.h"
50 #include "error.h"
51 #include "raw_bitset.h"
52 #include "pdeq.h"
53
54 #include "util.h"
55 #include "irgwalk.h"
56 #include "becopyilp_t.h"
57 #include "beifg.h"
58 #include "besched.h"
59 #include "bemodule.h"
60
61 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
62
63 typedef struct local_env_t {
64         int             first_x_var;
65         int             last_x_var;
66         const unsigned *allocatable_colors;
67 } local_env_t;
68
69 static unsigned check_alignment_constraints(ir_node *node)
70 {
71         const arch_register_req_t *req = arch_get_irn_register_req(node);
72         // For larger than 1 variables, support only aligned constraints
73         assert((arch_register_req_is(req, aligned) || req->width == 1) && "Unaligned large (width > 1) variables not supported");
74         return arch_register_req_is(req, aligned) && req->width > 1;
75 }
76
77 static void make_color_var_name(char *buf, size_t buf_size,
78                                 const ir_node *node, unsigned color)
79 {
80         unsigned node_idx = get_irn_idx(node);
81         snprintf(buf, buf_size, "x_%u_%u", node_idx, color);
82 }
83
84 static void build_coloring_cstr(ilp_env_t *ienv)
85 {
86         local_env_t    *lenv   = (local_env_t*)ienv->env;
87         be_ifg_t       *ifg    = ienv->co->cenv->ifg;
88         unsigned        n_regs = arch_register_class_n_regs(ienv->co->cls);
89         const unsigned *allocatable_colors = lenv->allocatable_colors;
90         nodes_iter_t    iter;
91         char            buf[32];
92
93         unsigned *const colors = rbitset_alloca(n_regs);
94         be_ifg_foreach_node(ifg, &iter, irn) {
95                 const arch_register_req_t *req;
96                 unsigned                   col;
97                 int                        cst_idx;
98                 unsigned                   curr_node_color;
99                 unsigned                   has_alignment_cstr;
100
101                 if (sr_is_removed(ienv->sr, irn))
102                         continue;
103
104                 has_alignment_cstr = check_alignment_constraints(irn);
105
106                 req = arch_get_irn_register_req(irn);
107
108                 /* get assignable colors */
109                 if (arch_register_req_is(req, limited)) {
110                         rbitset_copy(colors, req->limited, n_regs);
111                 } else {
112                         rbitset_copy(colors, allocatable_colors, n_regs);
113                 }
114
115                 /* add the coloring constraint */
116                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 1.0);
117
118                 curr_node_color = get_irn_col(irn);
119                 for (col = 0; col < n_regs; ++col) {
120                         int    var_idx;
121                         double val;
122                         if (!rbitset_is_set(colors, col)
123                                 || (has_alignment_cstr && ((col % req->width) != 0)))
124                                 continue;
125
126                         make_color_var_name(buf, sizeof(buf), irn, col);
127                         var_idx = lpp_add_var(ienv->lp, buf, lpp_binary, 0.0);
128                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
129
130                         val = (col == curr_node_color) ? 1.0 : 0.0;
131                         lpp_set_start_value(ienv->lp, var_idx, val);
132
133                         lenv->last_x_var = var_idx;
134                         if (lenv->first_x_var == -1)
135                                 lenv->first_x_var = var_idx;
136                 }
137
138                 /* add register constraint constraints */
139                 for (col = 0; col < n_regs; ++col) {
140                         int cst_idx;
141                         int var_idx;
142                         if (rbitset_is_set(colors, col)
143                                 // for aligned variable, we set the unaligned part to 0
144                                 && (!has_alignment_cstr || ((col % req->width) == 0)))
145                                 continue;
146
147                         make_color_var_name(buf, sizeof(buf), irn, col);
148                         cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_equal, 0.0);
149                         var_idx = lpp_add_var(ienv->lp, buf, lpp_binary, 0.0);
150                         lpp_set_start_value(ienv->lp, var_idx, 0.0);
151                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1);
152
153                         lenv->last_x_var = var_idx;
154                 }
155         }
156 }
157
158 static void build_interference_cstr(ilp_env_t *ienv)
159 {
160         lpp_t          *lpp      = ienv->lp;
161         local_env_t    *lenv     = (local_env_t*)ienv->env;
162         be_ifg_t       *ifg      = ienv->co->cenv->ifg;
163         unsigned        n_colors = arch_register_class_n_regs(ienv->co->cls);
164         ir_node       **clique   = ALLOCAN(ir_node*, n_colors);
165         const unsigned *allocatable_colors = lenv->allocatable_colors;
166         cliques_iter_t iter;
167         int            size;
168         unsigned       col;
169         int            i;
170
171         /* for each maximal clique */
172         be_ifg_foreach_clique(ifg, &iter, clique, &size) {
173                 unsigned realsize = 0;
174
175                 for (i=0; i<size; ++i) {
176                         if (!sr_is_removed(ienv->sr, clique[i]))
177                                 ++realsize;
178                 }
179
180                 if (realsize < 2)
181                         continue;
182
183                 /* for all colors */
184                 for (col=0; col<n_colors; ++col) {
185                         int cst_idx;
186                         if (!rbitset_is_set(allocatable_colors, col))
187                                 continue;
188
189                         cst_idx = lpp_add_cst(lpp, NULL, lpp_less_equal, 1.0);
190
191                         /* for each member of this clique */
192                         for (i=0; i<size; ++i) {
193                                 ir_node *irn = clique[i];
194                                 char     buf[32];
195                                 int      var_idx;
196                                 unsigned aligment_offset = 0;
197
198                                 if (sr_is_removed(ienv->sr, irn))
199                                         continue;
200
201                                 // Use the first part of the large registers for all
202                                 // interference, since it is the only colorable one.
203                                 if (check_alignment_constraints(irn)) {
204                                         const arch_register_req_t *req
205                                                 = arch_get_irn_register_req(irn);
206                                         aligment_offset = col % req->width;
207                                 }
208
209                                 make_color_var_name(buf, sizeof(buf), irn,
210                                                                         col - aligment_offset);
211                                 var_idx = lpp_get_var_idx(lpp, buf);
212                                 lpp_set_factor_fast(lpp, cst_idx, var_idx, 1);
213                         }
214                 }
215         }
216 }
217
218 static void make_affinity_var_name(char *buf, size_t buf_size,
219                                    const ir_node *node1, const ir_node *node2)
220 {
221         unsigned n1 = get_irn_idx(node1);
222         unsigned n2 = get_irn_idx(node2);
223         if (n1 < n2) {
224                 snprintf(buf, buf_size, "y_%u_%u", n1, n2);
225         } else {
226                 snprintf(buf, buf_size, "y_%u_%u", n2, n1);
227         }
228 }
229
230
231 /**
232  * TODO: Remove the dependency of the opt-units data structure
233  *       by walking over all affinity edges. Graph structure
234  *       does not provide this walker, yet.
235  */
236 static void build_affinity_cstr(ilp_env_t *ienv)
237 {
238         unsigned  n_colors = arch_register_class_n_regs(ienv->co->cls);
239
240         /* for all optimization units */
241         list_for_each_entry(unit_t, curr, &ienv->co->units, units) {
242                 ir_node *root     = curr->nodes[0];
243                 unsigned root_col = get_irn_col(root);
244                 int      i;
245
246                 for (i = 1; i < curr->node_count; ++i) {
247                         ir_node *arg     = curr->nodes[i];
248                         unsigned arg_col = get_irn_col(arg);
249                         double   val;
250                         char     buf[32];
251                         unsigned col;
252                         int      y_idx;
253
254                         /* add a new affinity variable */
255                         make_affinity_var_name(buf, sizeof(buf), arg, root);
256                         y_idx = lpp_add_var(ienv->lp, buf, lpp_binary, curr->costs[i]);
257                         val   = (root_col == arg_col) ? 0.0 : 1.0;
258                         lpp_set_start_value(ienv->lp, y_idx, val);
259
260                         /* add constraints relating the affinity var to the color vars */
261                         for (col=0; col<n_colors; ++col) {
262                                 int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_less_equal, 0.0);
263                                 int root_idx;
264                                 int arg_idx;
265
266                                 make_color_var_name(buf, sizeof(buf), root, col);
267                                 root_idx = lpp_get_var_idx(ienv->lp, buf);
268                                 make_color_var_name(buf, sizeof(buf), arg, col);
269                                 arg_idx  = lpp_get_var_idx(ienv->lp, buf);
270
271                                 lpp_set_factor_fast(ienv->lp, cst_idx, root_idx,  1.0);
272                                 lpp_set_factor_fast(ienv->lp, cst_idx, arg_idx,  -1.0);
273                                 lpp_set_factor_fast(ienv->lp, cst_idx, y_idx, -1.0);
274                         }
275                 }
276         }
277 }
278
279 /**
280  * Helping stuff for build_clique_star_cstr
281  */
282 typedef struct edge_t {
283         ir_node *n1;
284         ir_node *n2;
285 } edge_t;
286
287 static int compare_edge_t(const void *k1, const void *k2, size_t size)
288 {
289         const edge_t *e1 = (const edge_t*)k1;
290         const edge_t *e2 = (const edge_t*)k2;
291         (void) size;
292
293         return ! (e1->n1 == e2->n1 && e1->n2 == e2->n2);
294 }
295
296 #define HASH_EDGE(e) (hash_irn((e)->n1) ^ hash_irn((e)->n2))
297
298 static inline edge_t *add_edge(set *edges, ir_node *n1, ir_node *n2, size_t *counter)
299 {
300         edge_t new_edge;
301
302         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
303                 new_edge.n1 = n1;
304                 new_edge.n2 = n2;
305         } else {
306                 new_edge.n1 = n2;
307                 new_edge.n2 = n1;
308         }
309         (*counter)++;
310         return set_insert(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
311 }
312
313 static inline edge_t *find_edge(set *edges, ir_node *n1, ir_node *n2)
314 {
315         edge_t new_edge;
316
317         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
318                 new_edge.n1 = n1;
319                 new_edge.n2 = n2;
320         } else {
321                 new_edge.n1 = n2;
322                 new_edge.n2 = n1;
323         }
324         return set_find(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
325 }
326
327 static inline void remove_edge(set *edges, ir_node *n1, ir_node *n2, size_t *counter)
328 {
329         edge_t new_edge, *e;
330
331         if (PTR_TO_INT(n1) < PTR_TO_INT(n2)) {
332                 new_edge.n1 = n1;
333                 new_edge.n2 = n2;
334         } else {
335                 new_edge.n1 = n2;
336                 new_edge.n2 = n1;
337         }
338         e = set_find(edge_t, edges, &new_edge, sizeof(new_edge), HASH_EDGE(&new_edge));
339         if (e) {
340                 e->n1 = NULL;
341                 e->n2 = NULL;
342                 (*counter)--;
343         }
344 }
345
346 #define pset_foreach(pset, irn) foreach_pset((pset), ir_node, (irn))
347
348 /**
349  * Search for an interference clique and an external node
350  * with affinity edges to all nodes of the clique.
351  * At most 1 node of the clique can be colored equally with the external node.
352  */
353 static void build_clique_star_cstr(ilp_env_t *ienv)
354 {
355         /* for each node with affinity edges */
356         co_gs_foreach_aff_node(ienv->co, aff) {
357                 struct obstack ob;
358                 const ir_node *center = aff->irn;
359                 ir_node **nodes;
360                 set *edges;
361                 int i, o, n_nodes;
362                 size_t n_edges;
363
364                 if (arch_irn_is_ignore(aff->irn))
365                         continue;
366
367                 obstack_init(&ob);
368                 edges = new_set(compare_edge_t, 8);
369
370                 /* get all affinity neighbours */
371                 n_nodes = 0;
372                 co_gs_foreach_neighb(aff, nbr) {
373                         if (!arch_irn_is_ignore(nbr->irn)) {
374                                 obstack_ptr_grow(&ob, nbr->irn);
375                                 ++n_nodes;
376                         }
377                 }
378                 nodes = (ir_node**)obstack_finish(&ob);
379
380                 /* get all interference edges between these */
381                 n_edges = 0;
382                 for (i=0; i<n_nodes; ++i) {
383                         for (o=0; o<i; ++o) {
384                                 if (be_ifg_connected(ienv->co->cenv->ifg, nodes[i], nodes[o]))
385                                         add_edge(edges, nodes[i], nodes[o], &n_edges);
386                         }
387                 }
388
389                 /* cover all these interference edges with maximal cliques */
390                 while (n_edges) {
391                         edge_t *e;
392                         pset   *clique = pset_new_ptr(8);
393                         bool    growed;
394
395                         /* get 2 starting nodes to form a clique */
396                         for (e = set_first(edge_t, edges); !e->n1; e = set_next(edge_t, edges)) {}
397
398                         /* we could be stepped out of the loop before the set iterated to the end */
399                         set_break(edges);
400
401                         pset_insert_ptr(clique, e->n1);
402                         pset_insert_ptr(clique, e->n2);
403                         remove_edge(edges, e->n1, e->n2, &n_edges);
404
405                         /* while the clique is growing */
406                         do {
407                                 growed = false;
408
409                                 /* search for a candidate to extend the clique */
410                                 for (i=0; i<n_nodes; ++i) {
411                                         ir_node *cand = nodes[i];
412                                         bool     is_cand;
413
414                                         /* if its already in the clique try the next */
415                                         if (pset_find_ptr(clique, cand))
416                                                 continue;
417
418                                         /* are there all necessary interferences? */
419                                         is_cand = true;
420                                         pset_foreach(clique, member) {
421                                                 if (!find_edge(edges, cand, member)) {
422                                                         is_cand = false;
423                                                         pset_break(clique);
424                                                         break;
425                                                 }
426                                         }
427
428                                         /* now we know if we have a clique extender */
429                                         if (is_cand) {
430                                                 /* first remove all covered edges */
431                                                 pset_foreach(clique, member)
432                                                         remove_edge(edges, cand, member, &n_edges);
433
434                                                 /* insert into clique */
435                                                 pset_insert_ptr(clique, cand);
436                                                 growed = true;
437                                                 break;
438                                         }
439                                 }
440                         } while (growed);
441
442                         /* now the clique is maximal. Finally add the constraint */
443                         {
444                                 int  var_idx;
445                                 int  cst_idx;
446                                 char buf[32];
447
448                                 cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater_equal, pset_count(clique)-1);
449
450                                 pset_foreach(clique, member) {
451                                         make_affinity_var_name(buf, sizeof(buf), center, member);
452                                         var_idx = lpp_get_var_idx(ienv->lp, buf);
453                                         lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
454                                 }
455                         }
456
457                         del_pset(clique);
458                 }
459
460                 del_set(edges);
461                 obstack_free(&ob, NULL);
462         }
463 }
464
465 static void extend_path(ilp_env_t *ienv, pdeq *path, const ir_node *irn)
466 {
467         be_ifg_t *ifg = ienv->co->cenv->ifg;
468         int i, len;
469         ir_node **curr_path;
470         affinity_node_t *aff;
471
472         /* do not walk backwards or in circles */
473         if (pdeq_contains(path, irn))
474                 return;
475
476         if (arch_irn_is_ignore(irn))
477                 return;
478
479         /* insert the new irn */
480         pdeq_putr(path, irn);
481
482         /* check for forbidden interferences */
483         len       = pdeq_len(path);
484         curr_path = ALLOCAN(ir_node*, len);
485         pdeq_copyl(path, (const void **)curr_path);
486
487         for (i=1; i<len; ++i) {
488                 if (be_ifg_connected(ifg, irn, curr_path[i]))
489                         goto end;
490         }
491
492         /* check for terminating interference */
493         if (be_ifg_connected(ifg, irn, curr_path[0])) {
494                 /* One node is not a path. */
495                 /* And a path of length 2 is covered by a clique star constraint. */
496                 if (len > 2) {
497                         /* finally build the constraint */
498                         int cst_idx = lpp_add_cst(ienv->lp, NULL, lpp_greater_equal, 1.0);
499                         for (i=1; i<len; ++i) {
500                                 char buf[32];
501                                 int  var_idx;
502
503                                 make_affinity_var_name(buf, sizeof(buf), curr_path[i-1], curr_path[i]);
504                                 var_idx = lpp_get_var_idx(ienv->lp, buf);
505                                 lpp_set_factor_fast(ienv->lp, cst_idx, var_idx, 1.0);
506                         }
507                 }
508
509                 /* this path cannot be extended anymore */
510                 goto end;
511         }
512
513         /* recursively extend the path */
514         aff = get_affinity_info(ienv->co, irn);
515         co_gs_foreach_neighb(aff, nbr) {
516                 extend_path(ienv, path, nbr->irn);
517         }
518
519 end:
520         /* remove the irn */
521         pdeq_getr(path);
522 }
523
524 /**
525  * Search a path of affinity edges, whose ends are connected
526  * by an interference edge and there are no other interference
527  * edges in between.
528  * Then at least one of these affinity edges must break.
529  */
530 static void build_path_cstr(ilp_env_t *ienv)
531 {
532         /* for each node with affinity edges */
533         co_gs_foreach_aff_node(ienv->co, aff_info) {
534                 pdeq *path = new_pdeq();
535
536                 extend_path(ienv, path, aff_info->irn);
537
538                 del_pdeq(path);
539         }
540 }
541
542 static void ilp2_build(ilp_env_t *ienv)
543 {
544         int lower_bound;
545
546         ienv->lp = lpp_new(ienv->co->name, lpp_minimize);
547         build_coloring_cstr(ienv);
548         build_interference_cstr(ienv);
549         build_affinity_cstr(ienv);
550         build_clique_star_cstr(ienv);
551         build_path_cstr(ienv);
552
553         lower_bound = co_get_lower_bound(ienv->co) - co_get_inevit_copy_costs(ienv->co);
554         lpp_set_bound(ienv->lp, lower_bound);
555 }
556
557 static void ilp2_apply(ilp_env_t *ienv)
558 {
559         local_env_t *lenv = (local_env_t*)ienv->env;
560         ir_graph    *irg  = ienv->co->irg;
561
562         /* first check if there was sth. to optimize */
563         if (lenv->first_x_var >= 0) {
564                 int              count = lenv->last_x_var - lenv->first_x_var + 1;
565                 double          *sol   = XMALLOCN(double, count);
566                 lpp_sol_state_t  state = lpp_get_solution(ienv->lp, sol, lenv->first_x_var, lenv->last_x_var);
567                 int              i;
568
569                 if (state != lpp_optimal) {
570                         printf("WARNING %s: Solution state is not 'optimal': %d\n",
571                                ienv->co->name, (int)state);
572                         if (state < lpp_feasible) {
573                                 panic("Copy coalescing solution not feasible!");
574                         }
575                 }
576
577                 for (i=0; i<count; ++i) {
578                         unsigned nodenr;
579                         unsigned color;
580                         char     var_name[32];
581                         if (sol[i] <= 1-EPSILON)
582                                 continue;
583                         /* split variable name into components */
584                         lpp_get_var_name(ienv->lp, lenv->first_x_var+i, var_name, sizeof(var_name));
585
586                         if (sscanf(var_name, "x_%u_%u", &nodenr, &color) == 2) {
587                                 ir_node *irn = get_idx_irn(irg, nodenr);
588                                 set_irn_col(ienv->co->cls, irn, color);
589                         } else {
590                                 panic("This should be a x-var");
591                         }
592                 }
593
594                 xfree(sol);
595         }
596
597 #ifdef COPYOPT_STAT
598         /* TODO adapt to multiple possible ILPs */
599         copystat_add_ilp_time((int)(1000.0*lpp_get_sol_time(pi->curr_lp)));  //now we have ms
600         copystat_add_ilp_vars(lpp_get_var_count(pi->curr_lp));
601         copystat_add_ilp_csts(lpp_get_cst_count(pi->curr_lp));
602         copystat_add_ilp_iter(lpp_get_iter_cnt(pi->curr_lp));
603 #endif
604 }
605
606 /**
607  * Solves the problem using mixed integer programming
608  * @returns 1 iff solution state was optimal
609  * Uses the OU and the GRAPH data structure
610  * Dependency of the OU structure can be removed
611  */
612 static int co_solve_ilp2(copy_opt_t *co)
613 {
614         unsigned        n_regs = arch_register_class_n_regs(co->cls);
615         lpp_sol_state_t sol_state;
616         ilp_env_t      *ienv;
617         local_env_t     my;
618
619         ASSERT_OU_AVAIL(co); //See build_clique_st
620         ASSERT_GS_AVAIL(co);
621
622         my.first_x_var = -1;
623         my.last_x_var  = -1;
624         FIRM_DBG_REGISTER(dbg, "firm.be.coilp2");
625
626         unsigned *const allocatable_colors = rbitset_alloca(n_regs);
627         be_set_allocatable_regs(co->irg, co->cls, allocatable_colors);
628         my.allocatable_colors = allocatable_colors;
629
630         ienv = new_ilp_env(co, ilp2_build, ilp2_apply, &my);
631
632         sol_state = ilp_go(ienv);
633
634         free_ilp_env(ienv);
635
636         return sol_state == lpp_optimal;
637 }
638
639 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyilp2)
640 void be_init_copyilp2(void)
641 {
642         static co_algo_info copyheur = {
643                 co_solve_ilp2, 1
644         };
645
646         be_register_copyopt("ilp", &copyheur);
647 }