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 "preferred" registers for live-ranges. This
33 * calculates for each register and each live-range a value indicating
34 * the usefulness. (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. Preferring
38 * registers with high preferences. When register constraints are not met,
39 * add copies and split live-ranges.
42 * - make use of free registers in the permute_values code
43 * - think about a smarter sequence of visiting the blocks. Sorted by
44 * execfreq might be good, or looptree from inner to outermost loops going
45 * over blocks in a reverse postorder
46 * - propagate preferences through Phis
57 #include "iredges_t.h"
58 #include "irgraph_t.h"
62 #include "raw_bitset.h"
65 #include "bechordal_t.h"
74 #include "bespillutil.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 AFF_SHOULD_BE_SAME 0.5f
84 #define SPLIT_DELTA 1.0f
86 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
88 static struct obstack obst;
89 static be_irg_t *birg;
91 static const arch_register_class_t *cls;
92 static const arch_register_req_t *default_cls_req;
94 static const ir_exec_freq *execfreqs;
95 static unsigned n_regs;
96 static unsigned *normal_regs;
98 /** currently active assignments (while processing a basic block)
99 * maps registers to values(their current copies) */
100 static ir_node **assignments;
103 * allocation information: last_uses, register preferences
104 * the information is per firm-node.
106 struct allocation_info_t {
107 unsigned last_uses; /**< bitset indicating last uses (input pos) */
108 ir_node *current_value; /**< copy of the value that should be used */
109 ir_node *original_value; /**< for copies point to original value */
110 float prefs[0]; /**< register preferences */
112 typedef struct allocation_info_t allocation_info_t;
114 /** helper datastructure used when sorting register preferences */
119 typedef struct reg_pref_t reg_pref_t;
121 /** per basic-block information */
122 struct block_info_t {
123 bool processed; /**< indicate wether block is processed */
124 ir_node *assignments[0]; /**< register assignments at end of block */
126 typedef struct block_info_t block_info_t;
129 * Get the allocation info for a node.
130 * The info is allocated on the first visit of a node.
132 static allocation_info_t *get_allocation_info(ir_node *node)
134 allocation_info_t *info;
135 if (!irn_visited_else_mark(node)) {
136 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
137 info = obstack_alloc(&obst, size);
138 memset(info, 0, size);
139 info->current_value = node;
140 info->original_value = node;
141 set_irn_link(node, info);
143 info = get_irn_link(node);
150 * Get allocation information for a basic block
152 static block_info_t *get_block_info(ir_node *block)
156 assert(is_Block(block));
157 if (!irn_visited_else_mark(block)) {
158 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
159 info = obstack_alloc(&obst, size);
160 memset(info, 0, size);
161 set_irn_link(block, info);
163 info = get_irn_link(block);
170 * Get default register requirement for the current register class
172 static const arch_register_req_t *get_default_req_current_cls(void)
174 if (default_cls_req == NULL) {
175 struct obstack *obst = get_irg_obstack(irg);
176 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
177 memset(req, 0, sizeof(*req));
179 req->type = arch_register_req_type_normal;
182 default_cls_req = req;
184 return default_cls_req;
188 * Link the allocation info of a node to a copy.
189 * Afterwards, both nodes uses the same allocation info.
190 * Copy must not have an allocation info assigned yet.
192 * @param copy the node that gets the allocation info assigned
193 * @param value the original node
195 static void mark_as_copy_of(ir_node *copy, ir_node *value)
198 allocation_info_t *info = get_allocation_info(value);
199 allocation_info_t *copy_info = get_allocation_info(copy);
201 /* find original value */
202 original = info->original_value;
203 if (original != value) {
204 info = get_allocation_info(original);
207 assert(info->original_value == original);
208 info->current_value = copy;
210 /* the copy should not be linked to something else yet */
211 assert(copy_info->original_value == copy);
212 /* copy over allocation preferences */
213 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
214 copy_info->original_value = original;
218 * Calculate the penalties for every register on a node and its live neighbors.
220 * @param live_nodes the set of live nodes at the current position, may be NULL
221 * @param penalty the penalty to subtract from
222 * @param limited a raw bitset containing the limited set for the node
223 * @param node the node
225 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
226 float penalty, const unsigned* limited,
229 ir_nodeset_iterator_t iter;
231 allocation_info_t *info = get_allocation_info(node);
234 /* give penalty for all forbidden regs */
235 for (r = 0; r < n_regs; ++r) {
236 if (rbitset_is_set(limited, r))
239 info->prefs[r] -= penalty;
242 /* all other live values should get a penalty for allowed regs */
243 if (live_nodes == NULL)
246 /* TODO: reduce penalty if there are multiple allowed registers... */
247 penalty *= NEIGHBOR_FACTOR;
248 foreach_ir_nodeset(live_nodes, neighbor, iter) {
249 allocation_info_t *neighbor_info;
251 /* TODO: if op is used on multiple inputs we might not do a
253 if (neighbor == node)
256 neighbor_info = get_allocation_info(neighbor);
257 for (r = 0; r < n_regs; ++r) {
258 if (!rbitset_is_set(limited, r))
261 neighbor_info->prefs[r] -= penalty;
267 * Calculate the preferences of a definition for the current register class.
268 * If the definition uses a limited set of registers, reduce the preferences
269 * for the limited register on the node and its neighbors.
271 * @param live_nodes the set of live nodes at the current node
272 * @param weight the weight
273 * @param node the current node
275 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
278 const arch_register_req_t *req;
280 if (get_irn_mode(node) == mode_T) {
281 const ir_edge_t *edge;
282 foreach_out_edge(node, edge) {
283 ir_node *proj = get_edge_src_irn(edge);
284 check_defs(live_nodes, weight, proj);
289 if (!arch_irn_consider_in_reg_alloc(cls, node))
292 req = arch_get_register_req_out(node);
293 if (req->type & arch_register_req_type_limited) {
294 const unsigned *limited = req->limited;
295 float penalty = weight * DEF_FACTOR;
296 give_penalties_for_limits(live_nodes, penalty, limited, node);
299 if (req->type & arch_register_req_type_should_be_same) {
300 ir_node *insn = skip_Proj(node);
301 allocation_info_t *info = get_allocation_info(node);
302 int arity = get_irn_arity(insn);
305 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
306 for (i = 0; i < arity; ++i) {
309 allocation_info_t *op_info;
311 if (!rbitset_is_set(&req->other_same, i))
314 op = get_irn_n(insn, i);
316 /* if we the value at the should_be_same input doesn't die at the
317 * node, then it is no use to propagate the constraints (since a
318 * copy will emerge anyway) */
319 if (ir_nodeset_contains(live_nodes, op))
322 op_info = get_allocation_info(op);
323 for (r = 0; r < n_regs; ++r) {
324 op_info->prefs[r] += info->prefs[r] * factor;
331 * Walker: Runs an a block calculates the preferences for any
332 * node and every register from the considered register class.
334 static void analyze_block(ir_node *block, void *data)
336 float weight = get_block_execfreq(execfreqs, block);
337 ir_nodeset_t live_nodes;
341 ir_nodeset_init(&live_nodes);
342 be_liveness_end_of_block(lv, cls, block, &live_nodes);
344 sched_foreach_reverse(block, node) {
345 allocation_info_t *info;
352 check_defs(&live_nodes, weight, node);
355 arity = get_irn_arity(node);
357 /* the allocation info node currently only uses 1 unsigned value
358 to mark last used inputs. So we will fail for a node with more than
360 if (arity >= (int) sizeof(unsigned) * 8) {
361 panic("Node with more than %d inputs not supported yet",
362 (int) sizeof(unsigned) * 8);
365 info = get_allocation_info(node);
366 for (i = 0; i < arity; ++i) {
367 ir_node *op = get_irn_n(node, i);
368 if (!arch_irn_consider_in_reg_alloc(cls, op))
371 /* last usage of a value? */
372 if (!ir_nodeset_contains(&live_nodes, op)) {
373 rbitset_set(&info->last_uses, i);
377 be_liveness_transfer(cls, node, &live_nodes);
379 /* update weights based on usage constraints */
380 for (i = 0; i < arity; ++i) {
381 const arch_register_req_t *req;
382 const unsigned *limited;
383 ir_node *op = get_irn_n(node, i);
385 if (!arch_irn_consider_in_reg_alloc(cls, op))
388 req = arch_get_register_req(node, i);
389 if (!(req->type & arch_register_req_type_limited))
392 limited = req->limited;
393 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
398 ir_nodeset_destroy(&live_nodes);
402 * Assign register reg to the given node.
404 * @param node the node
405 * @param reg the register
407 static void use_reg(ir_node *node, const arch_register_t *reg)
409 unsigned r = arch_register_get_index(reg);
410 assignments[r] = node;
411 arch_set_irn_register(node, reg);
414 static void free_reg_of_value(ir_node *node)
416 const arch_register_t *reg;
419 if (!arch_irn_consider_in_reg_alloc(cls, node))
422 reg = arch_get_irn_register(node);
423 r = arch_register_get_index(reg);
424 /* assignment->value may be NULL if a value is used at 2 inputs
425 so it gets freed twice. */
426 assert(assignments[r] == node || assignments[r] == NULL);
427 assignments[r] = NULL;
431 * Compare two register preferences in decreasing order.
433 static int compare_reg_pref(const void *e1, const void *e2)
435 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
436 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
437 if (rp1->pref < rp2->pref)
439 if (rp1->pref > rp2->pref)
444 static void fill_sort_candidates(reg_pref_t *regprefs,
445 const allocation_info_t *info)
449 for (r = 0; r < n_regs; ++r) {
450 float pref = info->prefs[r];
452 regprefs[r].pref = pref;
454 /* TODO: use a stable sort here to avoid unnecessary register jumping */
455 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
458 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
459 float pref, float pref_delta,
460 unsigned *output_regs)
462 const arch_register_t *reg;
467 allocation_info_t *info = get_allocation_info(to_split);
473 /* find the best free position where we could move to */
474 prefs = ALLOCAN(reg_pref_t, n_regs);
475 fill_sort_candidates(prefs, info);
476 for (i = 0; i < n_regs; ++i) {
478 if (!rbitset_is_set(normal_regs, r))
480 if (rbitset_is_set(output_regs, r))
482 if (assignments[r] == NULL)
488 /* TODO: use execfreq somehow... */
489 delta = pref_delta + prefs[i].pref;
490 if (delta < SPLIT_DELTA) {
491 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
496 reg = arch_register_for_index(cls, r);
497 block = get_nodes_block(before);
498 copy = be_new_Copy(cls, block, to_split);
499 mark_as_copy_of(copy, to_split);
500 free_reg_of_value(to_split);
502 sched_add_before(before, copy);
505 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
506 copy, to_split, reg->name, before, delta));
511 * Determine and assign a register for node @p node
513 static void assign_reg(const ir_node *block, ir_node *node,
514 unsigned *output_regs)
516 const arch_register_t *reg;
517 allocation_info_t *info;
518 const arch_register_req_t *req;
519 reg_pref_t *reg_prefs;
522 const unsigned *allowed_regs;
525 assert(arch_irn_consider_in_reg_alloc(cls, node));
527 /* preassigned register? */
528 reg = arch_get_irn_register(node);
530 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
535 /* give should_be_same boni */
536 info = get_allocation_info(node);
537 req = arch_get_register_req_out(node);
539 in_node = skip_Proj(node);
540 if (req->type & arch_register_req_type_should_be_same) {
541 float weight = get_block_execfreq(execfreqs, block);
542 int arity = get_irn_arity(in_node);
545 assert(arity <= (int) sizeof(req->other_same) * 8);
546 for (i = 0; i < arity; ++i) {
548 const arch_register_t *reg;
550 if (!rbitset_is_set(&req->other_same, i))
553 in = get_irn_n(in_node, i);
554 reg = arch_get_irn_register(in);
556 r = arch_register_get_index(reg);
558 /* if the value didn't die here then we should not propagate the
559 * should_be_same info */
560 if (assignments[r] == in)
563 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
567 /* create list of register candidates and sort by their preference */
568 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
569 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
570 fill_sort_candidates(reg_prefs, info);
571 for (i = 0; i < n_regs; ++i) {
572 unsigned num = reg_prefs[i].num;
573 const arch_register_t *reg;
575 if (!rbitset_is_set(normal_regs, num))
578 reg = arch_register_for_index(cls, num);
579 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
581 DB((dbg, LEVEL_2, "\n"));
583 allowed_regs = normal_regs;
584 if (req->type & arch_register_req_type_limited) {
585 allowed_regs = req->limited;
588 for (i = 0; i < n_regs; ++i) {
589 r = reg_prefs[i].num;
590 if (!rbitset_is_set(allowed_regs, r))
592 if (assignments[r] == NULL)
595 float pref = reg_prefs[i].pref;
596 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
597 ir_node *before = skip_Proj(node);
598 bool res = try_optimistic_split(assignments[r], before,
606 panic("No register left for %+F\n", node);
609 reg = arch_register_for_index(cls, r);
610 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
615 * Add an permutation in front of a node and change the assignments
616 * due to this permutation.
618 * To understand this imagine a permutation like this:
628 * First we count how many destinations a single value has. At the same time
629 * we can be sure that each destination register has at most 1 source register
630 * (it can have 0 which means we don't care what value is in it).
631 * We ignore all fullfilled permuations (like 7->7)
632 * In a first pass we create as much copy instructions as possible as they
633 * are generally cheaper than exchanges. We do this by counting into how many
634 * destinations a register has to be copied (in the example it's 2 for register
635 * 3, or 1 for the registers 1,2,4 and 7).
636 * We can then create a copy into every destination register when the usecount
637 * of that register is 0 (= noone else needs the value in the register).
639 * After this step we should have cycles left. We implement a cyclic permutation
640 * of n registers with n-1 transpositions.
642 * @param live_nodes the set of live nodes, updated due to live range split
643 * @param before the node before we add the permutation
644 * @param permutation the permutation array indices are the destination
645 * registers, the values in the array are the source
648 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
649 unsigned *permutation)
651 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
655 /* determine how often each source register needs to be read */
656 for (r = 0; r < n_regs; ++r) {
657 unsigned old_reg = permutation[r];
660 value = assignments[old_reg];
662 /* nothing to do here, reg is not live. Mark it as fixpoint
663 * so we ignore it in the next steps */
671 block = get_nodes_block(before);
673 /* step1: create copies where immediately possible */
674 for (r = 0; r < n_regs; /* empty */) {
677 const arch_register_t *reg;
678 unsigned old_r = permutation[r];
680 /* - no need to do anything for fixed points.
681 - we can't copy if the value in the dest reg is still needed */
682 if (old_r == r || n_used[r] > 0) {
688 src = assignments[old_r];
689 copy = be_new_Copy(cls, block, src);
690 sched_add_before(before, copy);
691 reg = arch_register_for_index(cls, r);
692 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
693 copy, src, before, reg->name));
694 mark_as_copy_of(copy, src);
697 if (live_nodes != NULL) {
698 ir_nodeset_insert(live_nodes, copy);
701 /* old register has 1 user less, permutation is resolved */
702 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
705 assert(n_used[old_r] > 0);
707 if (n_used[old_r] == 0) {
708 if (live_nodes != NULL) {
709 ir_nodeset_remove(live_nodes, src);
711 free_reg_of_value(src);
714 /* advance or jump back (if this copy enabled another copy) */
715 if (old_r < r && n_used[old_r] == 0) {
722 /* at this point we only have "cycles" left which we have to resolve with
724 * TODO: if we have free registers left, then we should really use copy
725 * instructions for any cycle longer than 2 registers...
726 * (this is probably architecture dependent, there might be archs where
727 * copies are preferable even for 2-cycles) */
729 /* create perms with the rest */
730 for (r = 0; r < n_regs; /* empty */) {
731 const arch_register_t *reg;
732 unsigned old_r = permutation[r];
744 /* we shouldn't have copies from 1 value to multiple destinations left*/
745 assert(n_used[old_r] == 1);
747 /* exchange old_r and r2; after that old_r is a fixed point */
748 r2 = permutation[old_r];
750 in[0] = assignments[r2];
751 in[1] = assignments[old_r];
752 perm = be_new_Perm(cls, block, 2, in);
753 sched_add_before(before, perm);
754 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
755 perm, in[0], in[1], before));
757 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
758 mark_as_copy_of(proj0, in[0]);
759 reg = arch_register_for_index(cls, old_r);
762 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
763 mark_as_copy_of(proj1, in[1]);
764 reg = arch_register_for_index(cls, r2);
767 /* 1 value is now in the correct register */
768 permutation[old_r] = old_r;
769 /* the source of r changed to r2 */
772 /* if we have reached a fixpoint update data structures */
773 if (live_nodes != NULL) {
774 ir_nodeset_remove(live_nodes, in[0]);
775 ir_nodeset_remove(live_nodes, in[1]);
776 ir_nodeset_remove(live_nodes, proj0);
777 ir_nodeset_insert(live_nodes, proj1);
782 /* now we should only have fixpoints left */
783 for (r = 0; r < n_regs; ++r) {
784 assert(permutation[r] == r);
790 * Free regs for values last used.
792 * @param live_nodes set of live nodes, will be updated
793 * @param node the node to consider
795 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
797 allocation_info_t *info = get_allocation_info(node);
798 const unsigned *last_uses = &info->last_uses;
799 int arity = get_irn_arity(node);
802 for (i = 0; i < arity; ++i) {
805 /* check if one operand is the last use */
806 if (!rbitset_is_set(last_uses, i))
809 op = get_irn_n(node, i);
810 free_reg_of_value(op);
811 ir_nodeset_remove(live_nodes, op);
816 * change inputs of a node to the current value (copies/perms)
818 static void rewire_inputs(ir_node *node)
821 int arity = get_irn_arity(node);
823 for (i = 0; i < arity; ++i) {
824 ir_node *op = get_irn_n(node, i);
825 allocation_info_t *info;
827 if (!arch_irn_consider_in_reg_alloc(cls, op))
830 info = get_allocation_info(op);
831 info = get_allocation_info(info->original_value);
832 if (info->current_value != op) {
833 set_irn_n(node, i, info->current_value);
839 * Create a bitset of registers occupied with value living through an
842 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
844 const allocation_info_t *info = get_allocation_info(node);
849 /* mark all used registers as potentially live-through */
850 for (r = 0; r < n_regs; ++r) {
851 if (assignments[r] == NULL)
853 if (!rbitset_is_set(normal_regs, r))
856 rbitset_set(bitset, r);
859 /* remove registers of value dying at the instruction */
860 arity = get_irn_arity(node);
861 for (i = 0; i < arity; ++i) {
863 const arch_register_t *reg;
865 if (!rbitset_is_set(&info->last_uses, i))
868 op = get_irn_n(node, i);
869 reg = arch_get_irn_register(op);
870 rbitset_clear(bitset, arch_register_get_index(reg));
875 * Enforce constraints at a node by live range splits.
877 * @param live_nodes the set of live nodes, might be changed
878 * @param node the current node
880 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
881 unsigned *output_regs)
883 int arity = get_irn_arity(node);
885 hungarian_problem_t *bp;
887 unsigned *assignment;
889 /* construct a list of register occupied by live-through values */
890 unsigned *live_through_regs = NULL;
892 /* see if any use constraints are not met */
894 for (i = 0; i < arity; ++i) {
895 ir_node *op = get_irn_n(node, i);
896 const arch_register_t *reg;
897 const arch_register_req_t *req;
898 const unsigned *limited;
901 if (!arch_irn_consider_in_reg_alloc(cls, op))
904 /* are there any limitations for the i'th operand? */
905 req = arch_get_register_req(node, i);
906 if (!(req->type & arch_register_req_type_limited))
909 limited = req->limited;
910 reg = arch_get_irn_register(op);
911 r = arch_register_get_index(reg);
912 if (!rbitset_is_set(limited, r)) {
913 /* found an assignment outside the limited set */
919 /* is any of the live-throughs using a constrained output register? */
920 if (get_irn_mode(node) == mode_T) {
921 const ir_edge_t *edge;
923 foreach_out_edge(node, edge) {
924 ir_node *proj = get_edge_src_irn(edge);
925 const arch_register_req_t *req;
927 if (!arch_irn_consider_in_reg_alloc(cls, proj))
930 req = arch_get_register_req_out(proj);
931 if (!(req->type & arch_register_req_type_limited))
934 if (live_through_regs == NULL) {
935 rbitset_alloca(live_through_regs, n_regs);
936 determine_live_through_regs(live_through_regs, node);
939 rbitset_or(output_regs, req->limited, n_regs);
940 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
945 if (arch_irn_consider_in_reg_alloc(cls, node)) {
946 const arch_register_req_t *req = arch_get_register_req_out(node);
947 if (req->type & arch_register_req_type_limited) {
948 rbitset_alloca(live_through_regs, n_regs);
949 determine_live_through_regs(live_through_regs, node);
950 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
952 rbitset_or(output_regs, req->limited, n_regs);
961 /* create these arrays if we haven't yet */
962 if (live_through_regs == NULL) {
963 rbitset_alloca(live_through_regs, n_regs);
966 /* at this point we have to construct a bipartite matching problem to see
967 * which values should go to which registers
968 * Note: We're building the matrix in "reverse" - source registers are
969 * right, destinations left because this will produce the solution
970 * in the format required for permute_values.
972 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
974 /* add all combinations, then remove not allowed ones */
975 for (l = 0; l < n_regs; ++l) {
976 if (!rbitset_is_set(normal_regs, l)) {
977 hungarian_add(bp, l, l, 1);
981 for (r = 0; r < n_regs; ++r) {
982 if (!rbitset_is_set(normal_regs, r))
984 /* livethrough values may not use constrainted output registers */
985 if (rbitset_is_set(live_through_regs, l)
986 && rbitset_is_set(output_regs, r))
989 hungarian_add(bp, r, l, l == r ? 9 : 8);
993 for (i = 0; i < arity; ++i) {
994 ir_node *op = get_irn_n(node, i);
995 const arch_register_t *reg;
996 const arch_register_req_t *req;
997 const unsigned *limited;
998 unsigned current_reg;
1000 if (!arch_irn_consider_in_reg_alloc(cls, op))
1003 req = arch_get_register_req(node, i);
1004 if (!(req->type & arch_register_req_type_limited))
1007 limited = req->limited;
1008 reg = arch_get_irn_register(op);
1009 current_reg = arch_register_get_index(reg);
1010 for (r = 0; r < n_regs; ++r) {
1011 if (rbitset_is_set(limited, r))
1013 hungarian_remv(bp, r, current_reg);
1017 //hungarian_print_costmatrix(bp, 1);
1018 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1020 assignment = ALLOCAN(unsigned, n_regs);
1021 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1025 fprintf(stderr, "Swap result:");
1026 for (i = 0; i < (int) n_regs; ++i) {
1027 fprintf(stderr, " %d", assignment[i]);
1029 fprintf(stderr, "\n");
1034 permute_values(live_nodes, node, assignment);
1037 /** test wether a node @p n is a copy of the value of node @p of */
1038 static bool is_copy_of(ir_node *value, ir_node *test_value)
1040 allocation_info_t *test_info;
1041 allocation_info_t *info;
1043 if (value == test_value)
1046 info = get_allocation_info(value);
1047 test_info = get_allocation_info(test_value);
1048 return test_info->original_value == info->original_value;
1052 * find a value in the end-assignment of a basic block
1053 * @returns the index into the assignment array if found
1056 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1059 ir_node **assignments = info->assignments;
1060 for (r = 0; r < n_regs; ++r) {
1061 ir_node *a_value = assignments[r];
1063 if (a_value == NULL)
1065 if (is_copy_of(a_value, value))
1073 * Create the necessary permutations at the end of a basic block to fullfill
1074 * the register assignment for phi-nodes in the next block
1076 static void add_phi_permutations(ir_node *block, int p)
1079 unsigned *permutation;
1080 ir_node **old_assignments;
1081 bool need_permutation;
1083 ir_node *pred = get_Block_cfgpred_block(block, p);
1085 block_info_t *pred_info = get_block_info(pred);
1087 /* predecessor not processed yet? nothing to do */
1088 if (!pred_info->processed)
1091 permutation = ALLOCAN(unsigned, n_regs);
1092 for (r = 0; r < n_regs; ++r) {
1096 /* check phi nodes */
1097 need_permutation = false;
1098 node = sched_first(block);
1099 for ( ; is_Phi(node); node = sched_next(node)) {
1100 const arch_register_t *reg;
1105 if (!arch_irn_consider_in_reg_alloc(cls, node))
1108 op = get_Phi_pred(node, p);
1109 if (!arch_irn_consider_in_reg_alloc(cls, op))
1112 a = find_value_in_block_info(pred_info, op);
1115 reg = arch_get_irn_register(node);
1116 regn = arch_register_get_index(reg);
1118 permutation[regn] = a;
1119 need_permutation = true;
1123 if (need_permutation) {
1124 /* permute values at end of predecessor */
1125 old_assignments = assignments;
1126 assignments = pred_info->assignments;
1127 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1129 assignments = old_assignments;
1132 /* change phi nodes to use the copied values */
1133 node = sched_first(block);
1134 for ( ; is_Phi(node); node = sched_next(node)) {
1138 if (!arch_irn_consider_in_reg_alloc(cls, node))
1141 op = get_Phi_pred(node, p);
1142 /* no need to do anything for Unknown inputs */
1143 if (!arch_irn_consider_in_reg_alloc(cls, op))
1146 /* we have permuted all values into the correct registers so we can
1147 simply query which value occupies the phis register in the
1149 a = arch_register_get_index(arch_get_irn_register(node));
1150 op = pred_info->assignments[a];
1151 set_Phi_pred(node, p, op);
1156 * Set preferences for a phis register based on the registers used on the
1159 static void adapt_phi_prefs(ir_node *phi)
1162 int arity = get_irn_arity(phi);
1163 ir_node *block = get_nodes_block(phi);
1164 allocation_info_t *info = get_allocation_info(phi);
1166 for (i = 0; i < arity; ++i) {
1167 ir_node *op = get_irn_n(phi, i);
1168 const arch_register_t *reg = arch_get_irn_register(op);
1170 ir_node *pred_block;
1171 block_info_t *pred_block_info;
1177 /* we only give the bonus if the predecessor already has register
1178 * assigned, otherwise we only see a dummy value
1179 * and any conclusions about its register are useless */
1180 pred_block = get_Block_cfgpred_block(block, i);
1181 pred_block_info = get_block_info(pred_block);
1182 if (!pred_block_info->processed)
1185 /* give bonus for already assigned register */
1186 pred = get_Block_cfgpred_block(block, i);
1187 weight = get_block_execfreq(execfreqs, pred);
1188 r = arch_register_get_index(reg);
1189 info->prefs[r] += weight * AFF_PHI;
1194 * After a phi has been assigned a register propagate preference inputs
1195 * to the phi inputs.
1197 static void propagate_phi_register(ir_node *phi, unsigned r)
1200 ir_node *block = get_nodes_block(phi);
1201 int arity = get_irn_arity(phi);
1203 for (i = 0; i < arity; ++i) {
1204 ir_node *op = get_Phi_pred(phi, i);
1205 allocation_info_t *info = get_allocation_info(op);
1209 pred = get_Block_cfgpred_block(block, i);
1210 weight = get_block_execfreq(execfreqs, pred);
1213 if (info->prefs[r] >= weight)
1216 /* promote the prefered register */
1217 info->prefs[r] += AFF_PHI * weight;
1219 propagate_phi_register(op, r);
1224 * Walker: assign registers to all nodes of a block that
1225 * need registers from the currently considered register class.
1227 static void allocate_coalesce_block(ir_node *block, void *data)
1230 ir_nodeset_t live_nodes;
1231 ir_nodeset_iterator_t iter;
1232 ir_node *node, *start;
1234 block_info_t *block_info;
1235 block_info_t **pred_block_infos;
1237 unsigned *output_regs; /**< collects registers which must not
1238 be used for optimistic splits */
1241 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1243 /* clear assignments */
1244 block_info = get_block_info(block);
1245 assignments = block_info->assignments;
1247 ir_nodeset_init(&live_nodes);
1249 /* gather regalloc infos of predecessor blocks */
1250 n_preds = get_Block_n_cfgpreds(block);
1251 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1252 for (i = 0; i < n_preds; ++i) {
1253 ir_node *pred = get_Block_cfgpred_block(block, i);
1254 block_info_t *pred_info = get_block_info(pred);
1255 pred_block_infos[i] = pred_info;
1258 phi_ins = ALLOCAN(ir_node*, n_preds);
1260 /* collect live-in nodes and preassigned values */
1261 be_lv_foreach(lv, block, be_lv_state_in, i) {
1262 const arch_register_t *reg;
1264 bool need_phi = false;
1266 node = be_lv_get_irn(lv, block, i);
1267 if (!arch_irn_consider_in_reg_alloc(cls, node))
1270 /* check all predecessors for this value, if it is not everywhere the
1271 same or unknown then we have to construct a phi
1272 (we collect the potential phi inputs here) */
1273 for (p = 0; p < n_preds; ++p) {
1274 block_info_t *pred_info = pred_block_infos[p];
1276 if (!pred_info->processed) {
1277 /* use node for now, it will get fixed later */
1281 int a = find_value_in_block_info(pred_info, node);
1283 /* must live out of predecessor */
1285 phi_ins[p] = pred_info->assignments[a];
1286 /* different value from last time? then we need a phi */
1287 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1294 ir_mode *mode = get_irn_mode(node);
1295 const arch_register_req_t *req = get_default_req_current_cls();
1299 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1300 be_set_phi_reg_req(phi, req);
1302 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1303 #ifdef DEBUG_libfirm
1304 for (i = 0; i < n_preds; ++i) {
1305 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1307 DB((dbg, LEVEL_3, "\n"));
1309 mark_as_copy_of(phi, node);
1310 sched_add_after(block, phi);
1314 allocation_info_t *info = get_allocation_info(node);
1315 info->current_value = phi_ins[0];
1317 /* Grab 1 of the inputs we constructed (might not be the same as
1318 * "node" as we could see the same copy of the value in all
1323 /* if the node already has a register assigned use it */
1324 reg = arch_get_irn_register(node);
1326 /* TODO: consult pred-block infos here. The value could be copied
1327 away in some/all predecessor blocks. We need to construct
1328 phi-nodes in this case.
1329 We even need to construct some Phi_0 like constructs in cases
1330 where the predecessor allocation is not determined yet. */
1334 /* remember that this node is live at the beginning of the block */
1335 ir_nodeset_insert(&live_nodes, node);
1338 rbitset_alloca(output_regs, n_regs);
1340 /* handle phis... */
1341 node = sched_first(block);
1342 for ( ; is_Phi(node); node = sched_next(node)) {
1343 const arch_register_t *reg;
1345 if (!arch_irn_consider_in_reg_alloc(cls, node))
1348 /* fill in regs already assigned */
1349 reg = arch_get_irn_register(node);
1353 adapt_phi_prefs(node);
1354 assign_reg(block, node, output_regs);
1356 reg = arch_get_irn_register(node);
1357 propagate_phi_register(node, arch_register_get_index(reg));
1362 /* assign regs for live-in values */
1363 foreach_ir_nodeset(&live_nodes, node, iter) {
1364 const arch_register_t *reg = arch_get_irn_register(node);
1368 assign_reg(block, node, output_regs);
1369 /* shouldn't happen if we color in dominance order */
1370 assert (!is_Phi(node));
1373 /* assign instructions in the block */
1374 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1377 rewire_inputs(node);
1379 /* enforce use constraints */
1380 rbitset_clear_all(output_regs, n_regs);
1381 enforce_constraints(&live_nodes, node, output_regs);
1382 /* we may not use registers occupied here for optimistic splits */
1383 for (r = 0; r < n_regs; ++r) {
1384 if (assignments[r] != NULL)
1385 rbitset_set(output_regs, r);
1388 rewire_inputs(node);
1390 /* free registers of values last used at this instruction */
1391 free_last_uses(&live_nodes, node);
1393 /* assign output registers */
1394 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1395 if (get_irn_mode(node) == mode_T) {
1396 const ir_edge_t *edge;
1397 foreach_out_edge(node, edge) {
1398 ir_node *proj = get_edge_src_irn(edge);
1399 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1401 assign_reg(block, proj, output_regs);
1403 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1404 assign_reg(block, node, output_regs);
1408 ir_nodeset_destroy(&live_nodes);
1411 block_info->processed = true;
1413 /* permute values at end of predecessor blocks in case of phi-nodes */
1416 for (p = 0; p < n_preds; ++p) {
1417 add_phi_permutations(block, p);
1421 /* if we have exactly 1 successor then we might be able to produce phi
1423 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1424 const ir_edge_t *edge
1425 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1426 ir_node *succ = get_edge_src_irn(edge);
1427 int p = get_edge_src_pos(edge);
1428 block_info_t *succ_info = get_block_info(succ);
1430 if (succ_info->processed) {
1431 add_phi_permutations(succ, p);
1437 * Run the register allocator for the current register class.
1439 static void be_straight_alloc_cls(void)
1441 lv = be_assure_liveness(birg);
1442 be_liveness_assure_sets(lv);
1443 be_liveness_assure_chk(lv);
1445 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1446 inc_irg_visited(irg);
1448 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1450 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1451 /* we need some dominance pre-order walk to ensure we see all
1452 * definitions/create copies before we encounter their users */
1453 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1455 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1458 static void dump(int mask, ir_graph *irg, const char *suffix,
1459 void (*dumper)(ir_graph *, const char *))
1461 if(birg->main_env->options->dump_flags & mask)
1462 be_dump(irg, suffix, dumper);
1466 * Run the spiller on the current graph.
1468 static void spill(void)
1470 /* make sure all nodes show their real register pressure */
1471 BE_TIMER_PUSH(t_ra_constr);
1472 be_pre_spill_prepare_constr(birg, cls);
1473 BE_TIMER_POP(t_ra_constr);
1475 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1478 BE_TIMER_PUSH(t_ra_spill);
1479 be_do_spill(birg, cls);
1480 BE_TIMER_POP(t_ra_spill);
1482 BE_TIMER_PUSH(t_ra_spill_apply);
1483 check_for_memory_operands(irg);
1484 BE_TIMER_POP(t_ra_spill_apply);
1486 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1490 * The straight register allocator for a whole procedure.
1492 static void be_straight_alloc(be_irg_t *new_birg)
1494 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1495 int n_cls = arch_env_get_n_reg_class(arch_env);
1498 obstack_init(&obst);
1501 irg = be_get_birg_irg(birg);
1502 execfreqs = birg->exec_freq;
1504 /* TODO: extract some of the stuff from bechordal allocator, like
1505 * statistics, time measurements, etc. and use them here too */
1507 for (c = 0; c < n_cls; ++c) {
1508 cls = arch_env_get_reg_class(arch_env, c);
1509 default_cls_req = NULL;
1510 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1513 stat_ev_ctx_push_str("regcls", cls->name);
1515 n_regs = arch_register_class_n_regs(cls);
1516 normal_regs = rbitset_malloc(n_regs);
1517 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1521 /* verify schedule and register pressure */
1522 BE_TIMER_PUSH(t_verify);
1523 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1524 be_verify_schedule(birg);
1525 be_verify_register_pressure(birg, cls, irg);
1526 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1527 assert(be_verify_schedule(birg) && "Schedule verification failed");
1528 assert(be_verify_register_pressure(birg, cls, irg)
1529 && "Register pressure verification failed");
1531 BE_TIMER_POP(t_verify);
1533 BE_TIMER_PUSH(t_ra_color);
1534 be_straight_alloc_cls();
1535 BE_TIMER_POP(t_ra_color);
1537 /* we most probably constructed new Phis so liveness info is invalid
1539 /* TODO: test liveness_introduce */
1540 be_liveness_invalidate(lv);
1543 stat_ev_ctx_pop("regcls");
1546 BE_TIMER_PUSH(t_ra_spill_apply);
1547 be_abi_fix_stack_nodes(birg->abi);
1548 BE_TIMER_POP(t_ra_spill_apply);
1550 BE_TIMER_PUSH(t_verify);
1551 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1552 be_verify_register_allocation(birg);
1553 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1554 assert(be_verify_register_allocation(birg)
1555 && "Register allocation invalid");
1557 BE_TIMER_POP(t_verify);
1559 obstack_free(&obst, NULL);
1563 * Initializes this module.
1565 void be_init_straight_alloc(void)
1567 static be_ra_t be_ra_straight = {
1571 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1573 be_register_allocator("straight", &be_ra_straight);
1576 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);