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