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