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);
471 /* find the best free position where we could move to */
472 reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
473 fill_sort_candidates(prefs, info);
474 for (i = 0; i < n_regs; ++i) {
476 if (!rbitset_is_set(normal_regs, r))
478 if (rbitset_is_set(output_regs, r))
480 if (assignments[r] == NULL)
486 /* TODO: use execfreq somehow... */
487 float delta = pref_delta + prefs[i].pref;
488 if (delta < SPLIT_DELTA) {
489 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
494 reg = arch_register_for_index(cls, r);
495 block = get_nodes_block(before);
496 copy = be_new_Copy(cls, block, to_split);
497 mark_as_copy_of(copy, to_split);
498 free_reg_of_value(to_split);
500 sched_add_before(before, copy);
503 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
504 copy, to_split, reg->name, before, delta));
509 * Determine and assign a register for node @p node
511 static void assign_reg(const ir_node *block, ir_node *node,
512 unsigned *output_regs)
514 const arch_register_t *reg;
515 allocation_info_t *info;
516 const arch_register_req_t *req;
517 reg_pref_t *reg_prefs;
520 const unsigned *allowed_regs;
522 assert(arch_irn_consider_in_reg_alloc(cls, node));
524 /* preassigned register? */
525 reg = arch_get_irn_register(node);
527 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
532 /* give should_be_same boni */
533 info = get_allocation_info(node);
534 req = arch_get_register_req_out(node);
536 in_node = skip_Proj(node);
537 if (req->type & arch_register_req_type_should_be_same) {
538 float weight = get_block_execfreq(execfreqs, block);
539 int arity = get_irn_arity(in_node);
542 assert(arity <= (int) sizeof(req->other_same) * 8);
543 for (i = 0; i < arity; ++i) {
545 const arch_register_t *reg;
547 if (!rbitset_is_set(&req->other_same, i))
550 in = get_irn_n(in_node, i);
551 reg = arch_get_irn_register(in);
553 r = arch_register_get_index(reg);
555 /* if the value didn't die here then we should not propagate the
556 * should_be_same info */
557 if (assignments[r] == in)
560 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
564 /* create list of register candidates and sort by their preference */
565 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
566 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
567 fill_sort_candidates(reg_prefs, info);
568 for (i = 0; i < n_regs; ++i) {
569 unsigned num = reg_prefs[i].num;
570 if (!rbitset_is_set(normal_regs, num))
573 const arch_register_t *reg = arch_register_for_index(cls, num);
574 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
576 DB((dbg, LEVEL_2, "\n"));
578 allowed_regs = normal_regs;
579 if (req->type & arch_register_req_type_limited) {
580 allowed_regs = req->limited;
584 for (i = 0; i < n_regs; ++i) {
585 r = reg_prefs[i].num;
586 if (!rbitset_is_set(allowed_regs, r))
588 if (assignments[r] == NULL)
591 float pref = reg_prefs[i].pref;
592 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
593 ir_node *before = skip_Proj(node);
594 bool res = try_optimistic_split(assignments[r], before,
602 panic("No register left for %+F\n", node);
605 reg = arch_register_for_index(cls, r);
606 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
611 * Add an permutation in front of a node and change the assignments
612 * due to this permutation.
614 * To understand this imagine a permutation like this:
624 * First we count how many destinations a single value has. At the same time
625 * we can be sure that each destination register has at most 1 source register
626 * (it can have 0 which means we don't care what value is in it).
627 * We ignore all fullfilled permuations (like 7->7)
628 * In a first pass we create as much copy instructions as possible as they
629 * are generally cheaper than exchanges. We do this by counting into how many
630 * destinations a register has to be copied (in the example it's 2 for register
631 * 3, or 1 for the registers 1,2,4 and 7).
632 * We can then create a copy into every destination register when the usecount
633 * of that register is 0 (= noone else needs the value in the register).
635 * After this step we should have cycles left. We implement a cyclic permutation
636 * of n registers with n-1 transpositions.
638 * @param live_nodes the set of live nodes, updated due to live range split
639 * @param before the node before we add the permutation
640 * @param permutation the permutation array indices are the destination
641 * registers, the values in the array are the source
644 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
645 unsigned *permutation)
647 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
651 /* determine how often each source register needs to be read */
652 for (r = 0; r < n_regs; ++r) {
653 unsigned old_reg = permutation[r];
656 value = assignments[old_reg];
658 /* nothing to do here, reg is not live. Mark it as fixpoint
659 * so we ignore it in the next steps */
667 block = get_nodes_block(before);
669 /* step1: create copies where immediately possible */
670 for (r = 0; r < n_regs; /* empty */) {
673 const arch_register_t *reg;
674 unsigned old_r = permutation[r];
676 /* - no need to do anything for fixed points.
677 - we can't copy if the value in the dest reg is still needed */
678 if (old_r == r || n_used[r] > 0) {
684 src = assignments[old_r];
685 copy = be_new_Copy(cls, block, src);
686 sched_add_before(before, copy);
687 reg = arch_register_for_index(cls, r);
688 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
689 copy, src, before, reg->name));
690 mark_as_copy_of(copy, src);
693 if (live_nodes != NULL) {
694 ir_nodeset_insert(live_nodes, copy);
697 /* old register has 1 user less, permutation is resolved */
698 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
701 assert(n_used[old_r] > 0);
703 if (n_used[old_r] == 0) {
704 if (live_nodes != NULL) {
705 ir_nodeset_remove(live_nodes, src);
707 free_reg_of_value(src);
710 /* advance or jump back (if this copy enabled another copy) */
711 if (old_r < r && n_used[old_r] == 0) {
718 /* at this point we only have "cycles" left which we have to resolve with
720 * TODO: if we have free registers left, then we should really use copy
721 * instructions for any cycle longer than 2 registers...
722 * (this is probably architecture dependent, there might be archs where
723 * copies are preferable even for 2-cycles) */
725 /* create perms with the rest */
726 for (r = 0; r < n_regs; /* empty */) {
727 const arch_register_t *reg;
728 unsigned old_r = permutation[r];
740 /* we shouldn't have copies from 1 value to multiple destinations left*/
741 assert(n_used[old_r] == 1);
743 /* exchange old_r and r2; after that old_r is a fixed point */
744 r2 = permutation[old_r];
746 in[0] = assignments[r2];
747 in[1] = assignments[old_r];
748 perm = be_new_Perm(cls, block, 2, in);
749 sched_add_before(before, perm);
750 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
751 perm, in[0], in[1], before));
753 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
754 mark_as_copy_of(proj0, in[0]);
755 reg = arch_register_for_index(cls, old_r);
758 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
759 mark_as_copy_of(proj1, in[1]);
760 reg = arch_register_for_index(cls, r2);
763 /* 1 value is now in the correct register */
764 permutation[old_r] = old_r;
765 /* the source of r changed to r2 */
768 /* if we have reached a fixpoint update data structures */
769 if (live_nodes != NULL) {
770 ir_nodeset_remove(live_nodes, in[0]);
771 ir_nodeset_remove(live_nodes, in[1]);
772 ir_nodeset_remove(live_nodes, proj0);
773 ir_nodeset_insert(live_nodes, proj1);
778 /* now we should only have fixpoints left */
779 for (r = 0; r < n_regs; ++r) {
780 assert(permutation[r] == r);
786 * Free regs for values last used.
788 * @param live_nodes set of live nodes, will be updated
789 * @param node the node to consider
791 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
793 allocation_info_t *info = get_allocation_info(node);
794 const unsigned *last_uses = &info->last_uses;
795 int arity = get_irn_arity(node);
798 for (i = 0; i < arity; ++i) {
801 /* check if one operand is the last use */
802 if (!rbitset_is_set(last_uses, i))
805 op = get_irn_n(node, i);
806 free_reg_of_value(op);
807 ir_nodeset_remove(live_nodes, op);
812 * change inputs of a node to the current value (copies/perms)
814 static void rewire_inputs(ir_node *node)
817 int arity = get_irn_arity(node);
819 for (i = 0; i < arity; ++i) {
820 ir_node *op = get_irn_n(node, i);
821 allocation_info_t *info;
823 if (!arch_irn_consider_in_reg_alloc(cls, op))
826 info = get_allocation_info(op);
827 info = get_allocation_info(info->original_value);
828 if (info->current_value != op) {
829 set_irn_n(node, i, info->current_value);
835 * Create a bitset of registers occupied with value living through an
838 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
840 const allocation_info_t *info = get_allocation_info(node);
845 /* mark all used registers as potentially live-through */
846 for (r = 0; r < n_regs; ++r) {
847 if (assignments[r] == NULL)
849 if (!rbitset_is_set(normal_regs, r))
852 rbitset_set(bitset, r);
855 /* remove registers of value dying at the instruction */
856 arity = get_irn_arity(node);
857 for (i = 0; i < arity; ++i) {
859 const arch_register_t *reg;
861 if (!rbitset_is_set(&info->last_uses, i))
864 op = get_irn_n(node, i);
865 reg = arch_get_irn_register(op);
866 rbitset_clear(bitset, arch_register_get_index(reg));
871 * Enforce constraints at a node by live range splits.
873 * @param live_nodes the set of live nodes, might be changed
874 * @param node the current node
876 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
877 unsigned *output_regs)
879 int arity = get_irn_arity(node);
881 hungarian_problem_t *bp;
883 unsigned *assignment;
885 /* construct a list of register occupied by live-through values */
886 unsigned *live_through_regs = NULL;
888 /* see if any use constraints are not met */
890 for (i = 0; i < arity; ++i) {
891 ir_node *op = get_irn_n(node, i);
892 const arch_register_t *reg;
893 const arch_register_req_t *req;
894 const unsigned *limited;
897 if (!arch_irn_consider_in_reg_alloc(cls, op))
900 /* are there any limitations for the i'th operand? */
901 req = arch_get_register_req(node, i);
902 if (!(req->type & arch_register_req_type_limited))
905 limited = req->limited;
906 reg = arch_get_irn_register(op);
907 r = arch_register_get_index(reg);
908 if (!rbitset_is_set(limited, r)) {
909 /* found an assignment outside the limited set */
915 /* is any of the live-throughs using a constrained output register? */
916 if (get_irn_mode(node) == mode_T) {
917 const ir_edge_t *edge;
919 foreach_out_edge(node, edge) {
920 ir_node *proj = get_edge_src_irn(edge);
921 const arch_register_req_t *req;
923 if (!arch_irn_consider_in_reg_alloc(cls, proj))
926 req = arch_get_register_req_out(proj);
927 if (!(req->type & arch_register_req_type_limited))
930 if (live_through_regs == NULL) {
931 rbitset_alloca(live_through_regs, n_regs);
932 determine_live_through_regs(live_through_regs, node);
935 rbitset_or(output_regs, req->limited, n_regs);
936 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
941 if (arch_irn_consider_in_reg_alloc(cls, node)) {
942 const arch_register_req_t *req = arch_get_register_req_out(node);
943 if (req->type & arch_register_req_type_limited) {
944 rbitset_alloca(live_through_regs, n_regs);
945 determine_live_through_regs(live_through_regs, node);
946 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
948 rbitset_or(output_regs, req->limited, n_regs);
957 /* create these arrays if we haven't yet */
958 if (live_through_regs == NULL) {
959 rbitset_alloca(live_through_regs, n_regs);
962 /* at this point we have to construct a bipartite matching problem to see
963 * which values should go to which registers
964 * Note: We're building the matrix in "reverse" - source registers are
965 * right, destinations left because this will produce the solution
966 * in the format required for permute_values.
968 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
970 /* add all combinations, then remove not allowed ones */
971 for (l = 0; l < n_regs; ++l) {
972 if (!rbitset_is_set(normal_regs, l)) {
973 hungarian_add(bp, l, l, 1);
977 for (r = 0; r < n_regs; ++r) {
978 if (!rbitset_is_set(normal_regs, r))
980 /* livethrough values may not use constrainted output registers */
981 if (rbitset_is_set(live_through_regs, l)
982 && rbitset_is_set(output_regs, r))
985 hungarian_add(bp, r, l, l == r ? 9 : 8);
989 for (i = 0; i < arity; ++i) {
990 ir_node *op = get_irn_n(node, i);
991 const arch_register_t *reg;
992 const arch_register_req_t *req;
993 const unsigned *limited;
994 unsigned current_reg;
996 if (!arch_irn_consider_in_reg_alloc(cls, op))
999 req = arch_get_register_req(node, i);
1000 if (!(req->type & arch_register_req_type_limited))
1003 limited = req->limited;
1004 reg = arch_get_irn_register(op);
1005 current_reg = arch_register_get_index(reg);
1006 for (r = 0; r < n_regs; ++r) {
1007 if (rbitset_is_set(limited, r))
1009 hungarian_remv(bp, r, current_reg);
1013 //hungarian_print_costmatrix(bp, 1);
1014 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1016 assignment = ALLOCAN(unsigned, n_regs);
1017 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1021 fprintf(stderr, "Swap result:");
1022 for (i = 0; i < (int) n_regs; ++i) {
1023 fprintf(stderr, " %d", assignment[i]);
1025 fprintf(stderr, "\n");
1030 permute_values(live_nodes, node, assignment);
1033 /** test wether a node @p n is a copy of the value of node @p of */
1034 static bool is_copy_of(ir_node *value, ir_node *test_value)
1036 allocation_info_t *test_info;
1037 allocation_info_t *info;
1039 if (value == test_value)
1042 info = get_allocation_info(value);
1043 test_info = get_allocation_info(test_value);
1044 return test_info->original_value == info->original_value;
1048 * find a value in the end-assignment of a basic block
1049 * @returns the index into the assignment array if found
1052 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1055 ir_node **assignments = info->assignments;
1056 for (r = 0; r < n_regs; ++r) {
1057 ir_node *a_value = assignments[r];
1059 if (a_value == NULL)
1061 if (is_copy_of(a_value, value))
1069 * Create the necessary permutations at the end of a basic block to fullfill
1070 * the register assignment for phi-nodes in the next block
1072 static void add_phi_permutations(ir_node *block, int p)
1075 unsigned *permutation;
1076 ir_node **old_assignments;
1077 bool need_permutation;
1079 ir_node *pred = get_Block_cfgpred_block(block, p);
1081 block_info_t *pred_info = get_block_info(pred);
1083 /* predecessor not processed yet? nothing to do */
1084 if (!pred_info->processed)
1087 permutation = ALLOCAN(unsigned, n_regs);
1088 for (r = 0; r < n_regs; ++r) {
1092 /* check phi nodes */
1093 need_permutation = false;
1094 node = sched_first(block);
1095 for ( ; is_Phi(node); node = sched_next(node)) {
1096 const arch_register_t *reg;
1101 if (!arch_irn_consider_in_reg_alloc(cls, node))
1104 op = get_Phi_pred(node, p);
1105 if (!arch_irn_consider_in_reg_alloc(cls, op))
1108 a = find_value_in_block_info(pred_info, op);
1111 reg = arch_get_irn_register(node);
1112 regn = arch_register_get_index(reg);
1114 permutation[regn] = a;
1115 need_permutation = true;
1119 if (need_permutation) {
1120 /* permute values at end of predecessor */
1121 old_assignments = assignments;
1122 assignments = pred_info->assignments;
1123 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1125 assignments = old_assignments;
1128 /* change phi nodes to use the copied values */
1129 node = sched_first(block);
1130 for ( ; is_Phi(node); node = sched_next(node)) {
1134 if (!arch_irn_consider_in_reg_alloc(cls, node))
1137 op = get_Phi_pred(node, p);
1138 /* no need to do anything for Unknown inputs */
1139 if (!arch_irn_consider_in_reg_alloc(cls, op))
1142 /* we have permuted all values into the correct registers so we can
1143 simply query which value occupies the phis register in the
1145 a = arch_register_get_index(arch_get_irn_register(node));
1146 op = pred_info->assignments[a];
1147 set_Phi_pred(node, p, op);
1152 * Set preferences for a phis register based on the registers used on the
1155 static void adapt_phi_prefs(ir_node *phi)
1158 int arity = get_irn_arity(phi);
1159 ir_node *block = get_nodes_block(phi);
1160 allocation_info_t *info = get_allocation_info(phi);
1162 for (i = 0; i < arity; ++i) {
1163 ir_node *op = get_irn_n(phi, i);
1164 const arch_register_t *reg = arch_get_irn_register(op);
1166 ir_node *pred_block;
1167 block_info_t *pred_block_info;
1173 /* we only give the bonus if the predecessor already has register
1174 * assigned, otherwise we only see a dummy value
1175 * and any conclusions about its register are useless */
1176 pred_block = get_Block_cfgpred_block(block, i);
1177 pred_block_info = get_block_info(pred_block);
1178 if (!pred_block_info->processed)
1181 /* give bonus for already assigned register */
1182 pred = get_Block_cfgpred_block(block, i);
1183 weight = get_block_execfreq(execfreqs, pred);
1184 r = arch_register_get_index(reg);
1185 info->prefs[r] += weight * AFF_PHI;
1190 * After a phi has been assigned a register propagate preference inputs
1191 * to the phi inputs.
1193 static void propagate_phi_register(ir_node *phi, unsigned r)
1196 ir_node *block = get_nodes_block(phi);
1197 int arity = get_irn_arity(phi);
1199 for (i = 0; i < arity; ++i) {
1200 ir_node *op = get_Phi_pred(phi, i);
1201 allocation_info_t *info = get_allocation_info(op);
1205 pred = get_Block_cfgpred_block(block, i);
1206 weight = get_block_execfreq(execfreqs, pred);
1209 if (info->prefs[r] >= weight)
1212 /* promote the prefered register */
1213 info->prefs[r] += AFF_PHI * weight;
1215 propagate_phi_register(op, r);
1220 * Walker: assign registers to all nodes of a block that
1221 * need registers from the currently considered register class.
1223 static void allocate_coalesce_block(ir_node *block, void *data)
1226 ir_nodeset_t live_nodes;
1227 ir_nodeset_iterator_t iter;
1228 ir_node *node, *start;
1230 block_info_t *block_info;
1231 block_info_t **pred_block_infos;
1233 unsigned *output_regs; /**< collects registers which must not
1234 be used for optimistic splits */
1237 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1239 /* clear assignments */
1240 block_info = get_block_info(block);
1241 assignments = block_info->assignments;
1243 ir_nodeset_init(&live_nodes);
1245 /* gather regalloc infos of predecessor blocks */
1246 n_preds = get_Block_n_cfgpreds(block);
1247 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1248 for (i = 0; i < n_preds; ++i) {
1249 ir_node *pred = get_Block_cfgpred_block(block, i);
1250 block_info_t *pred_info = get_block_info(pred);
1251 pred_block_infos[i] = pred_info;
1254 phi_ins = ALLOCAN(ir_node*, n_preds);
1256 /* collect live-in nodes and preassigned values */
1257 be_lv_foreach(lv, block, be_lv_state_in, i) {
1258 const arch_register_t *reg;
1260 bool need_phi = false;
1262 node = be_lv_get_irn(lv, block, i);
1263 if (!arch_irn_consider_in_reg_alloc(cls, node))
1266 /* check all predecessors for this value, if it is not everywhere the
1267 same or unknown then we have to construct a phi
1268 (we collect the potential phi inputs here) */
1269 for (p = 0; p < n_preds; ++p) {
1270 block_info_t *pred_info = pred_block_infos[p];
1272 if (!pred_info->processed) {
1273 /* use node for now, it will get fixed later */
1277 int a = find_value_in_block_info(pred_info, node);
1279 /* must live out of predecessor */
1281 phi_ins[p] = pred_info->assignments[a];
1282 /* different value from last time? then we need a phi */
1283 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1290 ir_mode *mode = get_irn_mode(node);
1291 const arch_register_req_t *req = get_default_req_current_cls();
1295 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1296 be_set_phi_reg_req(phi, req);
1298 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1299 #ifdef DEBUG_libfirm
1300 for (i = 0; i < n_preds; ++i) {
1301 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1303 DB((dbg, LEVEL_3, "\n"));
1305 mark_as_copy_of(phi, node);
1306 sched_add_after(block, phi);
1310 allocation_info_t *info = get_allocation_info(node);
1311 info->current_value = phi_ins[0];
1313 /* Grab 1 of the inputs we constructed (might not be the same as
1314 * "node" as we could see the same copy of the value in all
1319 /* if the node already has a register assigned use it */
1320 reg = arch_get_irn_register(node);
1322 /* TODO: consult pred-block infos here. The value could be copied
1323 away in some/all predecessor blocks. We need to construct
1324 phi-nodes in this case.
1325 We even need to construct some Phi_0 like constructs in cases
1326 where the predecessor allocation is not determined yet. */
1330 /* remember that this node is live at the beginning of the block */
1331 ir_nodeset_insert(&live_nodes, node);
1334 rbitset_alloca(output_regs, n_regs);
1336 /* handle phis... */
1337 node = sched_first(block);
1338 for ( ; is_Phi(node); node = sched_next(node)) {
1339 const arch_register_t *reg;
1341 if (!arch_irn_consider_in_reg_alloc(cls, node))
1344 /* fill in regs already assigned */
1345 reg = arch_get_irn_register(node);
1349 adapt_phi_prefs(node);
1350 assign_reg(block, node, output_regs);
1352 reg = arch_get_irn_register(node);
1353 propagate_phi_register(node, arch_register_get_index(reg));
1358 /* assign regs for live-in values */
1359 foreach_ir_nodeset(&live_nodes, node, iter) {
1360 const arch_register_t *reg = arch_get_irn_register(node);
1364 assign_reg(block, node, output_regs);
1365 /* shouldn't happen if we color in dominance order */
1366 assert (!is_Phi(node));
1369 /* assign instructions in the block */
1370 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1373 rewire_inputs(node);
1375 /* enforce use constraints */
1376 rbitset_clear_all(output_regs, n_regs);
1377 enforce_constraints(&live_nodes, node, output_regs);
1378 /* we may not use registers occupied here for optimistic splits */
1379 for (r = 0; r < n_regs; ++r) {
1380 if (assignments[r] != NULL)
1381 rbitset_set(output_regs, r);
1384 rewire_inputs(node);
1386 /* free registers of values last used at this instruction */
1387 free_last_uses(&live_nodes, node);
1389 /* assign output registers */
1390 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1391 if (get_irn_mode(node) == mode_T) {
1392 const ir_edge_t *edge;
1393 foreach_out_edge(node, edge) {
1394 ir_node *proj = get_edge_src_irn(edge);
1395 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1397 assign_reg(block, proj, output_regs);
1399 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1400 assign_reg(block, node, output_regs);
1404 ir_nodeset_destroy(&live_nodes);
1407 block_info->processed = true;
1409 /* permute values at end of predecessor blocks in case of phi-nodes */
1412 for (p = 0; p < n_preds; ++p) {
1413 add_phi_permutations(block, p);
1417 /* if we have exactly 1 successor then we might be able to produce phi
1419 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1420 const ir_edge_t *edge
1421 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1422 ir_node *succ = get_edge_src_irn(edge);
1423 int p = get_edge_src_pos(edge);
1424 block_info_t *succ_info = get_block_info(succ);
1426 if (succ_info->processed) {
1427 add_phi_permutations(succ, p);
1433 * Run the register allocator for the current register class.
1435 static void be_straight_alloc_cls(void)
1437 lv = be_assure_liveness(birg);
1438 be_liveness_assure_sets(lv);
1439 be_liveness_assure_chk(lv);
1441 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1442 inc_irg_visited(irg);
1444 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1446 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1447 /* we need some dominance pre-order walk to ensure we see all
1448 * definitions/create copies before we encounter their users */
1449 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1451 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1454 static void dump(int mask, ir_graph *irg, const char *suffix,
1455 void (*dumper)(ir_graph *, const char *))
1457 if(birg->main_env->options->dump_flags & mask)
1458 be_dump(irg, suffix, dumper);
1462 * Run the spiller on the current graph.
1464 static void spill(void)
1466 /* make sure all nodes show their real register pressure */
1467 BE_TIMER_PUSH(t_ra_constr);
1468 be_pre_spill_prepare_constr(birg, cls);
1469 BE_TIMER_POP(t_ra_constr);
1471 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1474 BE_TIMER_PUSH(t_ra_spill);
1475 be_do_spill(birg, cls);
1476 BE_TIMER_POP(t_ra_spill);
1478 BE_TIMER_PUSH(t_ra_spill_apply);
1479 check_for_memory_operands(irg);
1480 BE_TIMER_POP(t_ra_spill_apply);
1482 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1486 * The straight register allocator for a whole procedure.
1488 static void be_straight_alloc(be_irg_t *new_birg)
1490 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1491 int n_cls = arch_env_get_n_reg_class(arch_env);
1494 obstack_init(&obst);
1497 irg = be_get_birg_irg(birg);
1498 execfreqs = birg->exec_freq;
1500 /* TODO: extract some of the stuff from bechordal allocator, like
1501 * statistics, time measurements, etc. and use them here too */
1503 for (c = 0; c < n_cls; ++c) {
1504 cls = arch_env_get_reg_class(arch_env, c);
1505 default_cls_req = NULL;
1506 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1509 stat_ev_ctx_push_str("regcls", cls->name);
1511 n_regs = arch_register_class_n_regs(cls);
1512 normal_regs = rbitset_malloc(n_regs);
1513 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1517 /* verify schedule and register pressure */
1518 BE_TIMER_PUSH(t_verify);
1519 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1520 be_verify_schedule(birg);
1521 be_verify_register_pressure(birg, cls, irg);
1522 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1523 assert(be_verify_schedule(birg) && "Schedule verification failed");
1524 assert(be_verify_register_pressure(birg, cls, irg)
1525 && "Register pressure verification failed");
1527 BE_TIMER_POP(t_verify);
1529 BE_TIMER_PUSH(t_ra_color);
1530 be_straight_alloc_cls();
1531 BE_TIMER_POP(t_ra_color);
1533 /* we most probably constructed new Phis so liveness info is invalid
1535 /* TODO: test liveness_introduce */
1536 be_liveness_invalidate(lv);
1539 stat_ev_ctx_pop("regcls");
1542 BE_TIMER_PUSH(t_ra_spill_apply);
1543 be_abi_fix_stack_nodes(birg->abi);
1544 BE_TIMER_POP(t_ra_spill_apply);
1546 BE_TIMER_PUSH(t_verify);
1547 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1548 be_verify_register_allocation(birg);
1549 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1550 assert(be_verify_register_allocation(birg)
1551 && "Register allocation invalid");
1553 BE_TIMER_POP(t_verify);
1555 obstack_free(&obst, NULL);
1559 * Initializes this module.
1561 void be_init_straight_alloc(void)
1563 static be_ra_t be_ra_straight = {
1567 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1569 be_register_allocator("straight", &be_ra_straight);
1572 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);