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