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