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