bechordal: Cleanup.
[libfirm] / ir / be / bechordal.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       Chordal register allocation.
23  * @author      Sebastian Hack
24  * @date        08.12.2004
25  */
26 #include "config.h"
27
28 #include "bechordal_common.h"
29 #include "bechordal_draw.h"
30 #include "bechordal_t.h"
31 #include "beinsn_t.h"
32 #include "beintlive_t.h"
33 #include "beirg.h"
34 #include "bemodule.h"
35 #include "debug.h"
36 #include "irdump.h"
37
38 #define USE_HUNGARIAN 0
39
40 #if USE_HUNGARIAN
41 #include "hungarian.h"
42 #else
43 #include "bipartite.h"
44 #endif
45
46 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
47
48 typedef struct be_chordal_alloc_env_t {
49         be_chordal_env_t *chordal_env;
50         bitset_t         *live;        /**< A liveness bitset. */
51         bitset_t         *tmp_colors;  /**< An auxiliary bitset which is as long as the number of colors in the class. */
52         bitset_t         *colors;      /**< The color mask. */
53 } be_chordal_alloc_env_t;
54
55 static int get_next_free_reg(be_chordal_alloc_env_t const *const alloc_env, bitset_t *const colors)
56 {
57         bitset_t *tmp = alloc_env->tmp_colors;
58         bitset_copy(tmp, colors);
59         bitset_flip_all(tmp);
60         bitset_and(tmp, alloc_env->chordal_env->allocatable_regs);
61         return bitset_next_set(tmp, 0);
62 }
63
64 static bitset_t const *get_decisive_partner_regs(be_operand_t const *const o1)
65 {
66         be_operand_t const *const o2 = o1->partner;
67         assert(!o2 || o1->req->cls == o2->req->cls);
68
69         if (!o2 || bitset_contains(o1->regs, o2->regs)) {
70                 return o1->regs;
71         } else if (bitset_contains(o2->regs, o1->regs)) {
72                 return o2->regs;
73         } else {
74                 return NULL;
75         }
76 }
77
78 static void pair_up_operands(be_chordal_env_t const *const env, be_insn_t *const insn)
79 {
80         /* For each out operand, try to find an in operand which can be assigned the
81          * same register as the out operand. */
82         int       const n_regs = env->cls->n_regs;
83         bitset_t *const bs     = bitset_alloca(n_regs);
84         be_lv_t  *const lv     = be_get_irg_liveness(env->irg);
85         for (int j = 0; j < insn->use_start; ++j) {
86                 /* Try to find an in operand which has ... */
87                 be_operand_t       *smallest        = NULL;
88                 int                 smallest_n_regs = n_regs + 1;
89                 be_operand_t *const out_op          = &insn->ops[j];
90                 for (int i = insn->use_start; i < insn->n_ops; ++i) {
91                         be_operand_t *const op = &insn->ops[i];
92                         if (op->partner || be_values_interfere(lv, op->irn, op->carrier))
93                                 continue;
94
95                         bitset_copy(bs, op->regs);
96                         bitset_and(bs, out_op->regs);
97                         int const n_total = bitset_popcount(op->regs);
98                         if (!bitset_is_empty(bs) && n_total < smallest_n_regs) {
99                                 smallest        = op;
100                                 smallest_n_regs = n_total;
101                         }
102                 }
103
104                 if (smallest != NULL) {
105                         for (int i = insn->use_start; i < insn->n_ops; ++i) {
106                                 if (insn->ops[i].carrier == smallest->carrier)
107                                         insn->ops[i].partner = out_op;
108                         }
109
110                         out_op->partner   = smallest;
111                         smallest->partner = out_op;
112                 }
113         }
114 }
115
116 static bool list_contains_irn(ir_node *const *const list, size_t const n, ir_node *const irn)
117 {
118         for (ir_node *const *i = list; i != list + n; ++i) {
119                 if (*i == irn)
120                         return true;
121         }
122         return false;
123 }
124
125 static void handle_constraints(be_chordal_alloc_env_t *const alloc_env, ir_node *const irn)
126 {
127         be_chordal_env_t *const env  = alloc_env->chordal_env;
128         void             *const base = obstack_base(env->obst);
129         be_insn_t              *insn = be_scan_insn(env, irn);
130
131         /* Perms inserted before the constraint handling phase are considered to be
132          * correctly precolored. These Perms arise during the ABI handling phase. */
133         if (!insn->has_constraints || is_Phi(irn))
134                 goto end;
135
136         /* Prepare the constraint handling of this node.
137          * Perms are constructed and Copies are created for constrained values
138          * interfering with the instruction. */
139         ir_node *const perm = pre_process_constraints(env, &insn);
140
141         /* find suitable in operands to the out operands of the node. */
142         pair_up_operands(env, insn);
143
144         /* Look at the in/out operands and add each operand (and its possible partner)
145          * to a bipartite graph (left: nodes with partners, right: admissible colors). */
146         int                        n_alloc     = 0;
147         int                  const n_regs      = env->cls->n_regs;
148         ir_node            **const alloc_nodes = ALLOCAN(ir_node*, n_regs);
149         pmap                *const partners    = pmap_create();
150 #if USE_HUNGARIAN
151         hungarian_problem_t *const bp          = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
152 #else
153         bipartite_t         *const bp          = bipartite_new(n_regs, n_regs);
154 #endif
155         for (int i = 0; i < insn->n_ops; ++i) {
156                 /* If the operand has no partner or the partner has not been marked
157                  * for allocation, determine the admissible registers and mark it
158                  * for allocation by associating the node and its partner with the
159                  * set of admissible registers via a bipartite graph. */
160                 be_operand_t *const op = &insn->ops[i];
161                 if (op->partner && pmap_contains(partners, op->partner->carrier))
162                         continue;
163
164                 ir_node *const partner = op->partner ? op->partner->carrier : NULL;
165                 pmap_insert(partners, op->carrier, partner);
166                 if (partner != NULL)
167                         pmap_insert(partners, partner, op->carrier);
168
169                 /* Don't insert a node twice. */
170                 if (list_contains_irn(alloc_nodes, n_alloc, op->carrier))
171                         continue;
172
173                 alloc_nodes[n_alloc] = op->carrier;
174
175                 DBG((dbg, LEVEL_2, "\tassociating %+F and %+F\n", op->carrier, partner));
176
177                 bitset_t const *const bs = get_decisive_partner_regs(op);
178                 if (bs) {
179                         DBG((dbg, LEVEL_2, "\tallowed registers for %+F: %B\n", op->carrier, bs));
180
181                         bitset_foreach(bs, col) {
182 #if USE_HUNGARIAN
183                                 hungarian_add(bp, n_alloc, col, 1);
184 #else
185                                 bipartite_add(bp, n_alloc, col);
186 #endif
187                         }
188                 } else {
189                         DBG((dbg, LEVEL_2, "\tallowed registers for %+F: none\n", op->carrier));
190                 }
191
192                 n_alloc++;
193         }
194
195         /* Put all nodes which live through the constrained instruction also to the
196          * allocation bipartite graph. They are considered unconstrained. */
197         if (perm != NULL) {
198                 be_lv_t *const lv = be_get_irg_liveness(env->irg);
199                 foreach_out_edge(perm, edge) {
200                         ir_node *const proj = get_edge_src_irn(edge);
201                         assert(is_Proj(proj));
202
203                         if (!be_values_interfere(lv, proj, irn) || pmap_contains(partners, proj))
204                                 continue;
205
206                         /* Don't insert a node twice. */
207                         if (list_contains_irn(alloc_nodes, n_alloc, proj))
208                                 continue;
209
210                         assert(n_alloc < n_regs);
211
212                         alloc_nodes[n_alloc] = proj;
213                         pmap_insert(partners, proj, NULL);
214
215                         bitset_foreach(env->allocatable_regs, col) {
216 #if USE_HUNGARIAN
217                                 hungarian_add(bp, n_alloc, col, 1);
218 #else
219                                 bipartite_add(bp, n_alloc, col);
220 #endif
221                         }
222
223                         n_alloc++;
224                 }
225         }
226
227         /* Compute a valid register allocation. */
228         int *const assignment = ALLOCAN(int, n_regs);
229 #if USE_HUNGARIAN
230         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
231         int const match_res = hungarian_solve(bp, assignment, NULL, 1);
232         assert(match_res == 0 && "matching failed");
233 #else
234         bipartite_matching(bp, assignment);
235 #endif
236
237         /* Assign colors obtained from the matching. */
238         for (int i = 0; i < n_alloc; ++i) {
239                 assert(assignment[i] >= 0 && "there must have been a register assigned (node not register pressure faithful?)");
240                 arch_register_t const *const reg = arch_register_for_index(env->cls, assignment[i]);
241
242                 ir_node *const irn = alloc_nodes[i];
243                 if (irn != NULL) {
244                         arch_set_irn_register(irn, reg);
245                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", irn, reg->name));
246                 }
247
248                 ir_node *const partner = pmap_get(ir_node, partners, alloc_nodes[i]);
249                 if (partner != NULL) {
250                         arch_set_irn_register(partner, reg);
251                         DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", partner, reg->name));
252                 }
253         }
254
255         /* Allocate the non-constrained Projs of the Perm. */
256         if (perm != NULL) {
257                 bitset_t *const bs = bitset_alloca(n_regs);
258
259                 /* Put the colors of all Projs in a bitset. */
260                 foreach_out_edge(perm, edge) {
261                         ir_node               *const proj = get_edge_src_irn(edge);
262                         arch_register_t const *const reg  = arch_get_irn_register(proj);
263                         if (reg != NULL)
264                                 bitset_set(bs, reg->index);
265                 }
266
267                 /* Assign the not yet assigned Projs of the Perm a suitable color. */
268                 foreach_out_edge(perm, edge) {
269                         ir_node               *const proj = get_edge_src_irn(edge);
270                         arch_register_t const *const reg  = arch_get_irn_register(proj);
271
272                         DBG((dbg, LEVEL_2, "\tchecking reg of %+F: %s\n", proj, reg ? reg->name : "<none>"));
273
274                         if (reg == NULL) {
275                                 size_t const col = get_next_free_reg(alloc_env, bs);
276                                 arch_register_t const *const new_reg = arch_register_for_index(env->cls, col);
277                                 bitset_set(bs, new_reg->index);
278                                 arch_set_irn_register(proj, new_reg);
279                                 DBG((dbg, LEVEL_2, "\tsetting %+F to register %s\n", proj, new_reg->name));
280                         }
281                 }
282         }
283
284 #if USE_HUNGARIAN
285         hungarian_free(bp);
286 #else
287         bipartite_free(bp);
288 #endif
289         pmap_destroy(partners);
290
291 end:
292         obstack_free(env->obst, base);
293 }
294
295 /**
296  * Handle constraint nodes in each basic block.
297  * handle_constraints() inserts Perm nodes which perm
298  * over all values live at the constrained node right in front
299  * of the constrained node. These Perms signal a constrained node.
300  * For further comments, refer to handle_constraints().
301  */
302 static void constraints(ir_node *const bl, void *const data)
303 {
304         be_chordal_alloc_env_t *const env = (be_chordal_alloc_env_t*)data;
305         for (ir_node *irn = sched_first(bl); !sched_is_end(irn);) {
306                 ir_node *const next = sched_next(irn);
307                 handle_constraints(env, irn);
308                 irn = next;
309         }
310 }
311
312 static void assign(ir_node *const block, void *const env_ptr)
313 {
314         be_chordal_alloc_env_t *const alloc_env = (be_chordal_alloc_env_t*)env_ptr;
315         be_chordal_env_t       *const env       = alloc_env->chordal_env;
316         bitset_t               *const live      = alloc_env->live;
317         bitset_t               *const colors    = alloc_env->colors;
318         struct list_head       *const head      = get_block_border_head(env, block);
319         be_lv_t                *const lv        = be_get_irg_liveness(env->irg);
320
321         bitset_clear_all(colors);
322         bitset_clear_all(live);
323
324         DBG((dbg, LEVEL_4, "Assigning colors for block %+F\n", block));
325         DBG((dbg, LEVEL_4, "\tusedef chain for block\n"));
326         foreach_border_head(head, b) {
327                 DBG((dbg, LEVEL_4, "\t%s %+F/%d\n", b->is_def ? "def" : "use",
328                                         b->irn, get_irn_idx(b->irn)));
329         }
330
331         /* Add initial defs for all values live in.
332          * Since their colors have already been assigned (The dominators were
333          * allocated before), we have to mark their colors as used also. */
334         be_lv_foreach(lv, block, be_lv_state_in, irn) {
335                 if (arch_irn_consider_in_reg_alloc(env->cls, irn)) {
336                         arch_register_t const *const reg = arch_get_irn_register(irn);
337
338                         assert(reg && "Node must have been assigned a register");
339                         DBG((dbg, LEVEL_4, "%+F has reg %s\n", irn, reg->name));
340
341                         /* Mark the color of the live in value as used. */
342                         bitset_set(colors, reg->index);
343
344                         /* Mark the value live in. */
345                         bitset_set(live, get_irn_idx(irn));
346                 }
347         }
348
349         /* Mind that the sequence of defs from back to front defines a perfect
350          * elimination order. So, coloring the definitions from first to last
351          * will work. */
352         foreach_border_head(head, b) {
353                 ir_node *const irn = b->irn;
354                 int      const nr  = get_irn_idx(irn);
355
356                 /* Assign a color, if it is a local def. Global defs already have a
357                  * color. */
358                 if (!b->is_def) {
359                         /* Clear the color upon a use. */
360                         arch_register_t const *const reg = arch_get_irn_register(irn);
361                         assert(reg && "Register must have been assigned");
362                         bitset_clear(colors, reg->index);
363                         bitset_clear(live, nr);
364                 } else if (!be_is_live_in(lv, block, irn)) {
365                         int                    col;
366                         arch_register_t const *reg = arch_get_irn_register(irn);
367                         if (reg) {
368                                 col = reg->index;
369                                 assert(!bitset_is_set(colors, col) && "pre-colored register must be free");
370                         } else {
371                                 assert(!arch_irn_is_ignore(irn));
372                                 col = get_next_free_reg(alloc_env, colors);
373                                 reg = arch_register_for_index(env->cls, col);
374                                 arch_set_irn_register(irn, reg);
375                         }
376                         bitset_set(colors, col);
377
378                         DBG((dbg, LEVEL_1, "\tassigning register %s(%d) to %+F\n", reg->name, col, irn));
379
380                         assert(!bitset_is_set(live, nr) && "Value's definition must not have been encountered");
381                         bitset_set(live, nr);
382                 }
383         }
384 }
385
386 static void be_ra_chordal_color(be_chordal_env_t *const chordal_env)
387 {
388         char            buf[256];
389         ir_graph *const irg = chordal_env->irg;
390         be_assure_live_sets(irg);
391         assure_doms(irg);
392
393         arch_register_class_t const *const cls      = chordal_env->cls;
394         int                          const colors_n = arch_register_class_n_regs(cls);
395         be_chordal_alloc_env_t             env;
396         env.chordal_env = chordal_env;
397         env.colors      = bitset_alloca(colors_n);
398         env.tmp_colors  = bitset_alloca(colors_n);
399
400         be_timer_push(T_SPLIT);
401         if (chordal_env->opts->dump_flags & BE_CH_DUMP_SPLIT) {
402                 snprintf(buf, sizeof(buf), "%s-split", cls->name);
403                 dump_ir_graph(irg, buf);
404         }
405         be_timer_pop(T_SPLIT);
406
407         be_timer_push(T_CONSTR);
408
409         /* Handle register targeting constraints */
410         dom_tree_walk_irg(irg, constraints, NULL, &env);
411
412         if (chordal_env->opts->dump_flags & BE_CH_DUMP_CONSTR) {
413                 snprintf(buf, sizeof(buf), "%s-constr", cls->name);
414                 dump_ir_graph(irg, buf);
415         }
416
417         be_timer_pop(T_CONSTR);
418
419         env.live = bitset_malloc(get_irg_last_idx(irg));
420
421         /* First, determine the pressure */
422         dom_tree_walk_irg(irg, create_borders, NULL, chordal_env);
423
424         /* Assign the colors */
425         dom_tree_walk_irg(irg, assign, NULL, &env);
426
427         if (chordal_env->opts->dump_flags & BE_CH_DUMP_TREE_INTV) {
428                 ir_snprintf(buf, sizeof(buf), "ifg_%s_%F.eps", cls->name, irg);
429                 plotter_t *const plotter = new_plotter_ps(buf);
430                 draw_interval_tree(&draw_chordal_def_opts, chordal_env, plotter);
431                 plotter_free(plotter);
432         }
433
434         bitset_free(env.live);
435 }
436
437 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_chordal)
438 void be_init_chordal(void)
439 {
440         static be_ra_chordal_coloring_t coloring = {
441                 be_ra_chordal_color
442         };
443         FIRM_DBG_REGISTER(dbg, "firm.be.chordal");
444
445         be_register_chordal_coloring("default", &coloring);
446 }