2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief New approach to allocation and copy coalescing
23 * @author Matthias Braun
27 * ... WE NEED A NAME FOR THIS ...
29 * Only a proof of concept at this moment...
31 * The idea is to allocate registers in 2 passes:
32 * 1. A first pass to determine "prefered" registers for live-ranges. This
33 * calculates for each register and each live-range a value indicating
34 * the usefullness. (You can roughly think of the value as the negative
35 * costs needed for copies when the value is in the specific registers...)
37 * 2. Walk blocks and assigns registers in a greedy fashion. Prefering registers
38 * with high preferences. When register constraints are not met, add copies
39 * and split live-ranges.
42 * - output constraints are not ensured. The algorithm fails to copy values
43 * away, so the registers for constrained outputs are free.
44 * - must_be_different constraint is not respected
45 * - No parallel copies at basic block borders are created, no additional phis
46 * created after copies have been inserted.
47 * - Phi color assignment should give bonus points towards registers already
48 * assigned at predecessors.
49 * - think about a smarter sequence of visiting the blocks. Sorted by
50 * execfreq might be good, or looptree from inner to outermost loops going
51 * over blocks in a reverse postorder
59 #include "irgraph_t.h"
60 #include "iredges_t.h"
69 #include "bechordal_t.h"
70 #include "besched_t.h"
73 #include "bespilloptions.h"
76 #include "bipartite.h"
77 #include "hungarian.h"
79 #define USE_FACTOR 1.0f
80 #define DEF_FACTOR 1.0f
81 #define NEIGHBOR_FACTOR 0.2f
82 #define SHOULD_BE_SAME 1.0f
84 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
86 static struct obstack obst;
87 static be_irg_t *birg;
89 static const arch_register_class_t *cls;
91 static const ir_exec_freq *execfreqs;
92 static unsigned n_regs;
93 static bitset_t *ignore_regs;
95 typedef struct assignment_t assignment_t;
97 ir_node *value; /**< currently assigned value */
100 static assignment_t *assignments;
102 typedef struct allocation_info_t allocation_info_t;
103 struct allocation_info_t {
104 unsigned last_uses; /**< bitset indicating last uses (input pos) */
105 assignment_t *current_assignment;
106 float prefs[0]; /**< register preferences */
109 typedef struct reg_pref_t reg_pref_t;
115 static allocation_info_t *get_allocation_info(ir_node *node)
117 allocation_info_t *info;
118 if (!irn_visited(node)) {
119 size_t size = sizeof(info[0]) + n_regs * sizeof(float);
120 info = obstack_alloc(&obst, size);
121 memset(info, 0, size);
122 set_irn_link(node, info);
123 mark_irn_visited(node);
125 info = get_irn_link(node);
131 static void link_to(ir_node *copy, ir_node *value)
133 allocation_info_t *info = get_allocation_info(value);
134 assert(!irn_visited(copy));
135 set_irn_link(copy, info);
136 mark_irn_visited(copy);
139 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
140 float penalty, const unsigned* limited,
143 ir_nodeset_iterator_t iter;
145 allocation_info_t *info = get_allocation_info(node);
148 /* give penalty for all forbidden regs */
149 for (r = 0; r < n_regs; ++r) {
150 if (rbitset_is_set(limited, r))
153 info->prefs[r] -= penalty;
156 /* all other live values should get a penalty for allowed regs */
157 if (live_nodes == NULL)
160 /* TODO: reduce penalty if there are multiple allowed registers... */
161 penalty *= NEIGHBOR_FACTOR;
162 foreach_ir_nodeset(live_nodes, neighbor, iter) {
163 allocation_info_t *neighbor_info;
165 /* TODO: if op is used on multiple inputs we might not do a
167 if (neighbor == node)
170 neighbor_info = get_allocation_info(neighbor);
171 for (r = 0; r < n_regs; ++r) {
172 if (!rbitset_is_set(limited, r))
175 neighbor_info->prefs[r] -= penalty;
180 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
183 const arch_register_req_t *req;
185 if (get_irn_mode(node) == mode_T) {
186 const ir_edge_t *edge;
187 foreach_out_edge(node, edge) {
188 ir_node *proj = get_edge_src_irn(edge);
189 check_defs(live_nodes, weight, proj);
194 if (!arch_irn_consider_in_reg_alloc(cls, node))
197 req = arch_get_register_req_out(node);
198 if (req->type & arch_register_req_type_limited) {
199 const unsigned *limited = req->limited;
200 float penalty = weight * DEF_FACTOR;
201 give_penalties_for_limits(live_nodes, penalty, limited, node);
204 if (req->type & arch_register_req_type_should_be_same) {
205 ir_node *insn = skip_Proj(node);
206 allocation_info_t *info = get_allocation_info(node);
207 int arity = get_irn_arity(insn);
210 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
211 for (i = 0; i < arity; ++i) {
214 allocation_info_t *op_info;
216 if (!rbitset_is_set(&req->other_same, i))
219 op = get_irn_n(insn, i);
220 op_info = get_allocation_info(op);
221 for (r = 0; r < n_regs; ++r) {
222 if (bitset_is_set(ignore_regs, r))
224 op_info->prefs[r] += info->prefs[r] * factor;
230 static void analyze_block(ir_node *block, void *data)
232 float weight = get_block_execfreq(execfreqs, block);
233 ir_nodeset_t live_nodes;
237 ir_nodeset_init(&live_nodes);
238 be_liveness_end_of_block(lv, cls, block, &live_nodes);
240 sched_foreach_reverse(block, node) {
241 allocation_info_t *info;
245 /* TODO: handle constrained phi-nodes */
249 /* TODO give/take penalties for should_be_same/different) */
250 check_defs(&live_nodes, weight, node);
253 arity = get_irn_arity(node);
254 /* I was lazy, and only allocated 1 unsigned
255 => maximum of 32 uses per node (rewrite if necessary) */
256 assert(arity <= (int) sizeof(unsigned) * 8);
258 info = get_allocation_info(node);
259 for (i = 0; i < arity; ++i) {
260 ir_node *op = get_irn_n(node, i);
261 if (!arch_irn_consider_in_reg_alloc(cls, op))
264 /* last usage of a value? */
265 if (!ir_nodeset_contains(&live_nodes, op)) {
266 rbitset_set(&info->last_uses, i);
270 be_liveness_transfer(cls, node, &live_nodes);
272 /* update weights based on usage constraints */
273 for (i = 0; i < arity; ++i) {
274 const arch_register_req_t *req;
275 const unsigned *limited;
276 ir_node *op = get_irn_n(node, i);
278 if (!arch_irn_consider_in_reg_alloc(cls, op))
281 req = arch_get_register_req(node, i);
282 if ((req->type & arch_register_req_type_limited) == 0)
285 /* TODO: give penalties to neighbors for precolored nodes! */
287 limited = req->limited;
288 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
293 ir_nodeset_destroy(&live_nodes);
296 static void use_reg(ir_node *node, const arch_register_t *reg)
298 unsigned r = arch_register_get_index(reg);
299 assignment_t *assignment = &assignments[r];
300 allocation_info_t *info;
302 assert(assignment->value == NULL);
303 assignment->value = node;
305 info = get_allocation_info(node);
306 info->current_assignment = assignment;
308 arch_set_irn_register(node, reg);
311 static int compare_reg_pref(const void *e1, const void *e2)
313 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
314 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
315 if (rp1->pref < rp2->pref)
317 if (rp1->pref > rp2->pref)
322 static void fill_sort_candidates(reg_pref_t *regprefs,
323 const allocation_info_t *info)
327 for (r = 0; r < n_regs; ++r) {
328 float pref = info->prefs[r];
329 if (bitset_is_set(ignore_regs, r)) {
333 regprefs[r].pref = pref;
335 /* TODO: use a stable sort here to avoid unnecessary register jumping */
336 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
339 static void assign_reg(const ir_node *block, ir_node *node)
341 const arch_register_t *reg;
342 allocation_info_t *info;
343 const arch_register_req_t *req;
344 reg_pref_t *reg_prefs;
347 assert(arch_irn_consider_in_reg_alloc(cls, node));
349 /* preassigned register? */
350 reg = arch_get_irn_register(node);
352 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
357 /* give should_be_same boni */
358 info = get_allocation_info(node);
359 req = arch_get_register_req_out(node);
360 if (req->type & arch_register_req_type_should_be_same) {
361 float weight = get_block_execfreq(execfreqs, block);
362 int arity = get_irn_arity(node);
365 assert(arity <= (int) sizeof(req->other_same) * 8);
366 for (i = 0; i < arity; ++i) {
368 const arch_register_t *reg;
370 if (!rbitset_is_set(&req->other_same, i))
373 in = get_irn_n(node, i);
374 reg = arch_get_irn_register(in);
376 r = arch_register_get_index(reg);
377 if (bitset_is_set(ignore_regs, r))
379 info->prefs[r] += weight * SHOULD_BE_SAME;
383 /* TODO: handle must_be_different */
386 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
387 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
388 fill_sort_candidates(reg_prefs, info);
389 for (i = 0; i < n_regs; ++i) {
390 unsigned num = reg_prefs[i].num;
391 const arch_register_t *reg = arch_register_for_index(cls, num);
392 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
394 DB((dbg, LEVEL_2, "\n"));
396 for (i = 0; i < n_regs; ++i) {
397 unsigned r = reg_prefs[i].num;
398 /* ignores should be last and we should have a non-ignore left */
399 assert(!bitset_is_set(ignore_regs, r));
400 /* already used? TODO: It might be better to copy the value occupying the register around here, find out when... */
401 if (assignments[r].value != NULL)
403 use_reg(node, arch_register_for_index(cls, r));
408 static void free_reg_of_value(ir_node *node)
410 allocation_info_t *info;
411 assignment_t *assignment;
414 if (!arch_irn_consider_in_reg_alloc(cls, node))
417 info = get_allocation_info(node);
418 assignment = info->current_assignment;
420 assert(assignment != NULL);
422 r = assignment - assignments;
423 DB((dbg, LEVEL_2, "Value %+F ended, freeing %s\n",
424 node, arch_register_for_index(cls, r)->name));
425 assignment->value = NULL;
426 info->current_assignment = NULL;
429 static unsigned get_current_reg(ir_node *node)
431 allocation_info_t *info = get_allocation_info(node);
432 assignment_t *assignment = info->current_assignment;
433 return assignment - assignments;
436 static assignment_t *get_current_assignment(ir_node *node)
438 allocation_info_t *info = get_allocation_info(node);
439 return info->current_assignment;
442 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
443 unsigned *permutation)
445 ir_node *block, *perm;
446 ir_node **in = ALLOCAN(ir_node*, n_regs);
450 for (r = 0; r < n_regs; ++r) {
451 unsigned new_reg = permutation[r];
452 assignment_t *assignment;
458 assignment = &assignments[r];
459 value = assignment->value;
461 /* nothing to do here, reg is not live */
468 free_reg_of_value(value);
469 ir_nodeset_remove(live_nodes, value);
472 block = get_nodes_block(before);
473 perm = be_new_Perm(cls, irg, block, i, in);
475 sched_add_before(before, perm);
478 for (r = 0; r < n_regs; ++r) {
479 unsigned new_reg = permutation[r];
483 const arch_register_t *reg;
489 mode = get_irn_mode(value);
490 proj = new_r_Proj(irg, block, perm, mode, i);
492 reg = arch_register_for_index(cls, new_reg);
494 link_to(proj, value);
496 ir_nodeset_insert(live_nodes, proj);
502 /* free regs for values last used */
503 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
505 allocation_info_t *info = get_allocation_info(node);
506 int arity = get_irn_arity(node);
508 for (i = 0; i < arity; ++i) {
511 if (!rbitset_is_set(&info->last_uses, i))
514 op = get_irn_n(node, i);
515 free_reg_of_value(op);
516 ir_nodeset_remove(live_nodes, op);
520 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
522 int arity = get_irn_arity(node);
524 hungarian_problem_t *bp;
526 unsigned *assignment;
528 /* see if any use constraints are not met */
530 for (i = 0; i < arity; ++i) {
531 ir_node *op = get_irn_n(node, i);
532 const arch_register_req_t *req;
533 const unsigned *limited;
536 if (!arch_irn_consider_in_reg_alloc(cls, op))
539 req = arch_get_register_req(node, i);
540 if ((req->type & arch_register_req_type_limited) == 0)
543 limited = req->limited;
544 r = get_current_reg(op);
545 if (!rbitset_is_set(limited, r)) {
554 /* swap values around */
555 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
557 /* add all combinations, then remove not allowed ones */
558 for (l = 0; l < n_regs; ++l) {
559 if (bitset_is_set(ignore_regs, l)) {
560 hungarian_add(bp, l, l, 90);
564 for (r = 0; r < n_regs; ++r) {
565 if (bitset_is_set(ignore_regs, r))
568 hungarian_add(bp, l, r, l == r ? 90 : 89);
572 for (i = 0; i < arity; ++i) {
573 ir_node *op = get_irn_n(node, i);
574 const arch_register_req_t *req;
575 const unsigned *limited;
576 unsigned current_reg;
578 if (!arch_irn_consider_in_reg_alloc(cls, op))
581 req = arch_get_register_req(node, i);
582 if ((req->type & arch_register_req_type_limited) == 0)
585 limited = req->limited;
586 current_reg = get_current_reg(op);
587 for (r = 0; r < n_regs; ++r) {
588 if (rbitset_is_set(limited, r))
590 hungarian_remv(bp, current_reg, r);
594 hungarian_print_costmatrix(bp, 1);
595 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
597 assignment = ALLOCAN(unsigned, n_regs);
598 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
601 printf("Swap result:");
602 for (p = 0; p < n_regs; ++p) {
603 printf(" %d", assignment[p]);
609 permutate_values(live_nodes, node, assignment);
612 static void allocate_coalesce_block(ir_node *block, void *data)
615 ir_nodeset_t live_nodes;
616 ir_nodeset_iterator_t iter;
617 ir_node *node, *start;
619 /* clear assignments */
620 memset(assignments, 0, n_regs * sizeof(assignments[0]));
624 /* collect live-in nodes and preassigned values */
625 ir_nodeset_init(&live_nodes);
626 be_lv_foreach(lv, block, be_lv_state_in, i) {
627 const arch_register_t *reg;
629 node = be_lv_get_irn(lv, block, i);
630 if (!arch_irn_consider_in_reg_alloc(cls, node))
633 ir_nodeset_insert(&live_nodes, node);
635 /* fill in regs already assigned */
636 reg = arch_get_irn_register(node);
643 node = sched_first(block);
644 for ( ; is_Phi(node); node = sched_next(node)) {
645 const arch_register_t *reg;
647 if (!arch_irn_consider_in_reg_alloc(cls, node))
650 /* fill in regs already assigned */
651 reg = arch_get_irn_register(node);
655 /* TODO: give boni for registers already assigned at the
661 /* assign regs for live-in values */
662 foreach_ir_nodeset(&live_nodes, node, iter) {
663 assign_reg(block, node);
666 /* assign instructions in the block */
667 for (node = start; !sched_is_end(node); node = sched_next(node)) {
668 int arity = get_irn_arity(node);
671 /* enforce use constraints */
672 enforce_constraints(&live_nodes, node);
674 /* exchange values to copied values where needed */
675 for (i = 0; i < arity; ++i) {
676 ir_node *op = get_irn_n(node, i);
677 assignment_t *assignment;
679 if (!arch_irn_consider_in_reg_alloc(cls, op))
681 assignment = get_current_assignment(op);
682 assert(assignment != NULL);
683 if (op != assignment->value) {
684 set_irn_n(node, i, assignment->value);
688 free_last_uses(&live_nodes, node);
690 /* assign output registers */
691 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
692 if (get_irn_mode(node) == mode_T) {
693 const ir_edge_t *edge;
694 foreach_out_edge(node, edge) {
695 ir_node *proj = get_edge_src_irn(edge);
696 if (!arch_irn_consider_in_reg_alloc(cls, proj))
698 assign_reg(block, proj);
700 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
701 assign_reg(block, node);
705 foreach_ir_nodeset(&live_nodes, node, iter) {
706 free_reg_of_value(node);
709 ir_nodeset_destroy(&live_nodes);
712 void be_straight_alloc_cls(void)
714 n_regs = arch_register_class_n_regs(cls);
715 lv = be_assure_liveness(birg);
716 be_liveness_assure_sets(lv);
717 be_liveness_assure_chk(lv);
719 assignments = obstack_alloc(&obst, n_regs * sizeof(assignments[0]));
721 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
722 inc_irg_visited(irg);
724 irg_block_walk_graph(irg, analyze_block, NULL, NULL);
725 irg_block_walk_graph(irg, allocate_coalesce_block, NULL, NULL);
727 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
730 static void spill(void)
732 /* TODO: rewrite pre_spill_prepare to work without chordal_env... */
733 be_chordal_env_t cenv;
734 memset(&cenv, 0, sizeof(cenv));
739 cenv.ignore_colors = ignore_regs;
741 /* make sure all nodes show their real register pressure */
742 be_pre_spill_prepare_constr(&cenv);
745 be_do_spill(birg, cls);
747 check_for_memory_operands(irg);
750 static void be_straight_alloc(be_irg_t *new_birg)
752 const arch_env_t *arch_env = new_birg->main_env->arch_env;
753 int n_cls = arch_env_get_n_reg_class(arch_env);
759 irg = be_get_birg_irg(birg);
760 execfreqs = birg->exec_freq;
762 /* TODO: extract some of the stuff from bechordal allocator, like
763 * statistics, time measurements, etc. and use them here too */
765 for (c = 0; c < n_cls; ++c) {
766 cls = arch_env_get_reg_class(arch_env, c);
767 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
770 stat_ev_ctx_push_str("bestraight_cls", cls->name);
772 n_regs = cls->n_regs;
773 ignore_regs = bitset_malloc(n_regs);
774 be_put_ignore_regs(birg, cls, ignore_regs);
778 /* verify schedule and register pressure */
779 BE_TIMER_PUSH(t_verify);
780 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
781 be_verify_schedule(birg);
782 be_verify_register_pressure(birg, cls, irg);
783 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
784 assert(be_verify_schedule(birg) && "Schedule verification failed");
785 assert(be_verify_register_pressure(birg, cls, irg)
786 && "Register pressure verification failed");
788 BE_TIMER_POP(t_verify);
790 BE_TIMER_PUSH(t_ra_color);
791 be_straight_alloc_cls();
792 BE_TIMER_POP(t_ra_color);
794 bitset_free(ignore_regs);
796 /* TODO: dump intermediate results */
798 stat_ev_ctx_pop("bestraight_cls");
801 obstack_free(&obst, NULL);
804 static be_ra_t be_ra_straight = {
808 void be_init_straight_alloc(void)
810 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
812 be_register_allocator("straight", &be_ra_straight);
815 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);