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 /** info about the current assignment for a register */
100 ir_node *value; /**< currently assigned value */
102 typedef struct assignment_t assignment_t;
104 /** currently active assignments (while processing a basic block) */
105 static assignment_t *assignments;
108 * allocation information: last_uses, register preferences
109 * the information is per firm-node.
111 struct allocation_info_t {
112 unsigned last_uses; /**< bitset indicating last uses (input pos) */
113 ir_node *current_value; /**< copy of the value that should be used */
114 ir_node *original_value; /**< for copies point to original value */
115 float prefs[0]; /**< register preferences */
117 typedef struct allocation_info_t allocation_info_t;
119 /** helper datastructure used when sorting register preferences */
124 typedef struct reg_pref_t reg_pref_t;
126 /** per basic-block information */
127 struct block_info_t {
128 bool processed; /**< indicate wether block is processed */
129 assignment_t assignments[0]; /**< register assignments at end of block */
131 typedef struct block_info_t block_info_t;
134 * Get the allocation info for a node.
135 * The info is allocated on the first visit of a node.
137 static allocation_info_t *get_allocation_info(ir_node *node)
139 allocation_info_t *info;
140 if (!irn_visited_else_mark(node)) {
141 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
142 info = obstack_alloc(&obst, size);
143 memset(info, 0, size);
144 info->current_value = node;
145 info->original_value = node;
146 set_irn_link(node, info);
148 info = get_irn_link(node);
155 * Get allocation information for a basic block
157 static block_info_t *get_block_info(ir_node *block)
161 assert(is_Block(block));
162 if (!irn_visited_else_mark(block)) {
163 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
164 info = obstack_alloc(&obst, size);
165 memset(info, 0, size);
166 set_irn_link(block, info);
168 info = get_irn_link(block);
175 * Get default register requirement for the current register class
177 static const arch_register_req_t *get_default_req_current_cls(void)
179 if (default_cls_req == NULL) {
180 struct obstack *obst = get_irg_obstack(irg);
181 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
182 memset(req, 0, sizeof(*req));
184 req->type = arch_register_req_type_normal;
187 default_cls_req = req;
189 return default_cls_req;
193 * Link the allocation info of a node to a copy.
194 * Afterwards, both nodes uses the same allocation info.
195 * Copy must not have an allocation info assigned yet.
197 * @param copy the node that gets the allocation info assigned
198 * @param value the original node
200 static void mark_as_copy_of(ir_node *copy, ir_node *value)
203 allocation_info_t *info = get_allocation_info(value);
204 allocation_info_t *copy_info = get_allocation_info(copy);
206 /* find original value */
207 original = info->original_value;
208 if (original != value) {
209 info = get_allocation_info(original);
212 assert(info->original_value == original);
213 info->current_value = copy;
215 /* the copy should not be linked to something else yet */
216 assert(copy_info->original_value == copy);
217 /* copy over allocation preferences */
218 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
219 copy_info->original_value = original;
223 * Calculate the penalties for every register on a node and its live neighbors.
225 * @param live_nodes the set of live nodes at the current position, may be NULL
226 * @param penalty the penalty to subtract from
227 * @param limited a raw bitset containing the limited set for the node
228 * @param node the node
230 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
231 float penalty, const unsigned* limited,
234 ir_nodeset_iterator_t iter;
236 allocation_info_t *info = get_allocation_info(node);
239 /* give penalty for all forbidden regs */
240 for (r = 0; r < n_regs; ++r) {
241 if (rbitset_is_set(limited, r))
244 info->prefs[r] -= penalty;
247 /* all other live values should get a penalty for allowed regs */
248 if (live_nodes == NULL)
251 /* TODO: reduce penalty if there are multiple allowed registers... */
252 penalty *= NEIGHBOR_FACTOR;
253 foreach_ir_nodeset(live_nodes, neighbor, iter) {
254 allocation_info_t *neighbor_info;
256 /* TODO: if op is used on multiple inputs we might not do a
258 if (neighbor == node)
261 neighbor_info = get_allocation_info(neighbor);
262 for (r = 0; r < n_regs; ++r) {
263 if (!rbitset_is_set(limited, r))
266 neighbor_info->prefs[r] -= penalty;
272 * Calculate the preferences of a definition for the current register class.
273 * If the definition uses a limited set of registers, reduce the preferences
274 * for the limited register on the node and its neighbors.
276 * @param live_nodes the set of live nodes at the current node
277 * @param weight the weight
278 * @param node the current node
280 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
283 const arch_register_req_t *req;
285 if (get_irn_mode(node) == mode_T) {
286 const ir_edge_t *edge;
287 foreach_out_edge(node, edge) {
288 ir_node *proj = get_edge_src_irn(edge);
289 check_defs(live_nodes, weight, proj);
294 if (!arch_irn_consider_in_reg_alloc(cls, node))
297 req = arch_get_register_req_out(node);
298 if (req->type & arch_register_req_type_limited) {
299 const unsigned *limited = req->limited;
300 float penalty = weight * DEF_FACTOR;
301 give_penalties_for_limits(live_nodes, penalty, limited, node);
304 if (req->type & arch_register_req_type_should_be_same) {
305 ir_node *insn = skip_Proj(node);
306 allocation_info_t *info = get_allocation_info(node);
307 int arity = get_irn_arity(insn);
310 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
311 for (i = 0; i < arity; ++i) {
314 allocation_info_t *op_info;
316 if (!rbitset_is_set(&req->other_same, i))
319 op = get_irn_n(insn, i);
321 /* if we the value at the should_be_same input doesn't die at the
322 * node, then it is no use to propagate the constraints (since a
323 * copy will emerge anyway) */
324 if (ir_nodeset_contains(live_nodes, op))
327 op_info = get_allocation_info(op);
328 for (r = 0; r < n_regs; ++r) {
329 op_info->prefs[r] += info->prefs[r] * factor;
336 * Walker: Runs an a block calculates the preferences for any
337 * node and every register from the considered register class.
339 static void analyze_block(ir_node *block, void *data)
341 float weight = get_block_execfreq(execfreqs, block);
342 ir_nodeset_t live_nodes;
346 ir_nodeset_init(&live_nodes);
347 be_liveness_end_of_block(lv, cls, block, &live_nodes);
349 sched_foreach_reverse(block, node) {
350 allocation_info_t *info;
357 check_defs(&live_nodes, weight, node);
360 arity = get_irn_arity(node);
362 /* the allocation info node currently only uses 1 unsigned value
363 to mark last used inputs. So we will fail for a node with more than
365 if (arity >= (int) sizeof(unsigned) * 8) {
366 panic("Node with more than %d inputs not supported yet",
367 (int) sizeof(unsigned) * 8);
370 info = get_allocation_info(node);
371 for (i = 0; i < arity; ++i) {
372 ir_node *op = get_irn_n(node, i);
373 if (!arch_irn_consider_in_reg_alloc(cls, op))
376 /* last usage of a value? */
377 if (!ir_nodeset_contains(&live_nodes, op)) {
378 rbitset_set(&info->last_uses, i);
382 be_liveness_transfer(cls, node, &live_nodes);
384 /* update weights based on usage constraints */
385 for (i = 0; i < arity; ++i) {
386 const arch_register_req_t *req;
387 const unsigned *limited;
388 ir_node *op = get_irn_n(node, i);
390 if (!arch_irn_consider_in_reg_alloc(cls, op))
393 req = arch_get_register_req(node, i);
394 if (!(req->type & arch_register_req_type_limited))
397 limited = req->limited;
398 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
403 ir_nodeset_destroy(&live_nodes);
407 * Assign register reg to the given node.
409 * @param node the node
410 * @param reg the register
412 static void use_reg(ir_node *node, const arch_register_t *reg)
414 unsigned r = arch_register_get_index(reg);
415 assignments[r].value = node;
416 arch_set_irn_register(node, reg);
419 static void free_reg_of_value(ir_node *node)
421 assignment_t *assignment;
422 const arch_register_t *reg;
425 if (!arch_irn_consider_in_reg_alloc(cls, node))
428 reg = arch_get_irn_register(node);
429 r = arch_register_get_index(reg);
430 assignment = &assignments[r];
431 /* assignment->value may be NULL if a value is used at 2 inputs
432 so it gets freed twice. */
433 assert(assignment->value == node || assignment->value == NULL);
434 assignment->value = NULL;
438 * Compare two register preferences in decreasing order.
440 static int compare_reg_pref(const void *e1, const void *e2)
442 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
443 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
444 if (rp1->pref < rp2->pref)
446 if (rp1->pref > rp2->pref)
451 static void fill_sort_candidates(reg_pref_t *regprefs,
452 const allocation_info_t *info)
456 for (r = 0; r < n_regs; ++r) {
457 float pref = info->prefs[r];
459 regprefs[r].pref = pref;
461 /* TODO: use a stable sort here to avoid unnecessary register jumping */
462 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
465 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
466 float pref, float pref_delta,
467 unsigned *output_regs)
469 const arch_register_t *reg;
474 allocation_info_t *info = get_allocation_info(to_split);
478 /* find the best free position where we could move to */
479 reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
480 fill_sort_candidates(prefs, info);
481 for (i = 0; i < n_regs; ++i) {
483 if (!rbitset_is_set(normal_regs, r))
485 if (rbitset_is_set(output_regs, r))
487 if (assignments[r].value == NULL)
493 /* TODO: use execfreq somehow... */
494 float delta = pref_delta + prefs[i].pref;
495 if (delta < SPLIT_DELTA) {
496 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
501 reg = arch_register_for_index(cls, r);
502 block = get_nodes_block(before);
503 copy = be_new_Copy(cls, block, to_split);
504 mark_as_copy_of(copy, to_split);
505 free_reg_of_value(to_split);
507 sched_add_before(before, copy);
510 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
511 copy, to_split, reg->name, before, delta));
516 * Determine and assign a register for node @p node
518 static void assign_reg(const ir_node *block, ir_node *node,
519 unsigned *output_regs)
521 const arch_register_t *reg;
522 allocation_info_t *info;
523 const arch_register_req_t *req;
524 reg_pref_t *reg_prefs;
527 const unsigned *allowed_regs;
529 assert(arch_irn_consider_in_reg_alloc(cls, node));
531 /* preassigned register? */
532 reg = arch_get_irn_register(node);
534 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
539 /* give should_be_same boni */
540 info = get_allocation_info(node);
541 req = arch_get_register_req_out(node);
543 in_node = skip_Proj(node);
544 if (req->type & arch_register_req_type_should_be_same) {
545 float weight = get_block_execfreq(execfreqs, block);
546 int arity = get_irn_arity(in_node);
549 assert(arity <= (int) sizeof(req->other_same) * 8);
550 for (i = 0; i < arity; ++i) {
552 const arch_register_t *reg;
554 if (!rbitset_is_set(&req->other_same, i))
557 in = get_irn_n(in_node, i);
558 reg = arch_get_irn_register(in);
560 r = arch_register_get_index(reg);
562 /* if the value didn't die here then we should not propagate the
563 * should_be_same info */
564 if (assignments[r].value == in)
567 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
571 /* create list of register candidates and sort by their preference */
572 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
573 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
574 fill_sort_candidates(reg_prefs, info);
575 for (i = 0; i < n_regs; ++i) {
576 unsigned num = reg_prefs[i].num;
577 if (!rbitset_is_set(normal_regs, num))
580 const arch_register_t *reg = arch_register_for_index(cls, num);
581 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
583 DB((dbg, LEVEL_2, "\n"));
585 allowed_regs = normal_regs;
586 if (req->type & arch_register_req_type_limited) {
587 allowed_regs = req->limited;
591 for (i = 0; i < n_regs; ++i) {
592 r = reg_prefs[i].num;
593 if (!rbitset_is_set(allowed_regs, r))
595 if (assignments[r].value == NULL)
598 float pref = reg_prefs[i].pref;
599 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
600 ir_node *before = skip_Proj(node);
601 bool res = try_optimistic_split(assignments[r].value, before,
609 panic("No register left for %+F\n", node);
612 reg = arch_register_for_index(cls, r);
613 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
618 * Add an permutation in front of a node and change the assignments
619 * due to this permutation.
621 * To understand this imagine a permutation like this:
631 * First we count how many destinations a single value has. At the same time
632 * we can be sure that each destination register has at most 1 source register
633 * (it can have 0 which means we don't care what value is in it).
634 * We ignore all fullfilled permuations (like 7->7)
635 * In a first pass we create as much copy instructions as possible as they
636 * are generally cheaper than exchanges. We do this by counting into how many
637 * destinations a register has to be copied (in the example it's 2 for register
638 * 3, or 1 for the registers 1,2,4 and 7).
639 * We can then create a copy into every destination register when the usecount
640 * of that register is 0 (= noone else needs the value in the register).
642 * After this step we should have cycles left. We implement a cyclic permutation
643 * of n registers with n-1 transpositions.
645 * @param live_nodes the set of live nodes, updated due to live range split
646 * @param before the node before we add the permutation
647 * @param permutation the permutation array indices are the destination
648 * registers, the values in the array are the source
651 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
652 unsigned *permutation)
654 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
658 /* determine how often each source register needs to be read */
659 for (r = 0; r < n_regs; ++r) {
660 unsigned old_reg = permutation[r];
663 value = assignments[old_reg].value;
665 /* nothing to do here, reg is not live. Mark it as fixpoint
666 * so we ignore it in the next steps */
674 block = get_nodes_block(before);
676 /* step1: create copies where immediately possible */
677 for (r = 0; r < n_regs; /* empty */) {
680 const arch_register_t *reg;
681 unsigned old_r = permutation[r];
683 /* - no need to do anything for fixed points.
684 - we can't copy if the value in the dest reg is still needed */
685 if (old_r == r || n_used[r] > 0) {
691 src = assignments[old_r].value;
692 copy = be_new_Copy(cls, block, src);
693 sched_add_before(before, copy);
694 reg = arch_register_for_index(cls, r);
695 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
696 copy, src, before, reg->name));
697 mark_as_copy_of(copy, src);
700 if (live_nodes != NULL) {
701 ir_nodeset_insert(live_nodes, copy);
704 /* old register has 1 user less, permutation is resolved */
705 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
708 assert(n_used[old_r] > 0);
710 if (n_used[old_r] == 0) {
711 if (live_nodes != NULL) {
712 ir_nodeset_remove(live_nodes, src);
714 free_reg_of_value(src);
717 /* advance or jump back (if this copy enabled another copy) */
718 if (old_r < r && n_used[old_r] == 0) {
725 /* at this point we only have "cycles" left which we have to resolve with
727 * TODO: if we have free registers left, then we should really use copy
728 * instructions for any cycle longer than 2 registers...
729 * (this is probably architecture dependent, there might be archs where
730 * copies are preferable even for 2-cycles) */
732 /* create perms with the rest */
733 for (r = 0; r < n_regs; /* empty */) {
734 const arch_register_t *reg;
735 unsigned old_r = permutation[r];
747 /* we shouldn't have copies from 1 value to multiple destinations left*/
748 assert(n_used[old_r] == 1);
750 /* exchange old_r and r2; after that old_r is a fixed point */
751 r2 = permutation[old_r];
753 in[0] = assignments[r2].value;
754 in[1] = assignments[old_r].value;
755 perm = be_new_Perm(cls, block, 2, in);
756 sched_add_before(before, perm);
757 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
758 perm, in[0], in[1], before));
760 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
761 mark_as_copy_of(proj0, in[0]);
762 reg = arch_register_for_index(cls, old_r);
765 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
766 mark_as_copy_of(proj1, in[1]);
767 reg = arch_register_for_index(cls, r2);
770 /* 1 value is now in the correct register */
771 permutation[old_r] = old_r;
772 /* the source of r changed to r2 */
775 /* if we have reached a fixpoint update data structures */
776 if (live_nodes != NULL) {
777 ir_nodeset_remove(live_nodes, in[0]);
778 ir_nodeset_remove(live_nodes, in[1]);
779 ir_nodeset_remove(live_nodes, proj0);
780 ir_nodeset_insert(live_nodes, proj1);
785 /* now we should only have fixpoints left */
786 for (r = 0; r < n_regs; ++r) {
787 assert(permutation[r] == r);
793 * Free regs for values last used.
795 * @param live_nodes set of live nodes, will be updated
796 * @param node the node to consider
798 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
800 allocation_info_t *info = get_allocation_info(node);
801 const unsigned *last_uses = &info->last_uses;
802 int arity = get_irn_arity(node);
805 for (i = 0; i < arity; ++i) {
808 /* check if one operand is the last use */
809 if (!rbitset_is_set(last_uses, i))
812 op = get_irn_n(node, i);
813 free_reg_of_value(op);
814 ir_nodeset_remove(live_nodes, op);
819 * change inputs of a node to the current value (copies/perms)
821 static void rewire_inputs(ir_node *node)
824 int arity = get_irn_arity(node);
826 for (i = 0; i < arity; ++i) {
827 ir_node *op = get_irn_n(node, i);
828 allocation_info_t *info;
830 if (!arch_irn_consider_in_reg_alloc(cls, op))
833 info = get_allocation_info(op);
834 info = get_allocation_info(info->original_value);
835 if (info->current_value != op) {
836 set_irn_n(node, i, info->current_value);
842 * Create a bitset of registers occupied with value living through an
845 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
847 const allocation_info_t *info = get_allocation_info(node);
852 /* mark all used registers as potentially live-through */
853 for (r = 0; r < n_regs; ++r) {
854 const assignment_t *assignment = &assignments[r];
855 if (assignment->value == NULL)
857 if (!rbitset_is_set(normal_regs, r))
860 rbitset_set(bitset, r);
863 /* remove registers of value dying at the instruction */
864 arity = get_irn_arity(node);
865 for (i = 0; i < arity; ++i) {
867 const arch_register_t *reg;
869 if (!rbitset_is_set(&info->last_uses, i))
872 op = get_irn_n(node, i);
873 reg = arch_get_irn_register(op);
874 rbitset_clear(bitset, arch_register_get_index(reg));
879 * Enforce constraints at a node by live range splits.
881 * @param live_nodes the set of live nodes, might be changed
882 * @param node the current node
884 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
885 unsigned *output_regs)
887 int arity = get_irn_arity(node);
889 hungarian_problem_t *bp;
891 unsigned *assignment;
893 /* construct a list of register occupied by live-through values */
894 unsigned *live_through_regs = NULL;
896 /* see if any use constraints are not met */
898 for (i = 0; i < arity; ++i) {
899 ir_node *op = get_irn_n(node, i);
900 const arch_register_t *reg;
901 const arch_register_req_t *req;
902 const unsigned *limited;
905 if (!arch_irn_consider_in_reg_alloc(cls, op))
908 /* are there any limitations for the i'th operand? */
909 req = arch_get_register_req(node, i);
910 if (!(req->type & arch_register_req_type_limited))
913 limited = req->limited;
914 reg = arch_get_irn_register(op);
915 r = arch_register_get_index(reg);
916 if (!rbitset_is_set(limited, r)) {
917 /* found an assignment outside the limited set */
923 /* is any of the live-throughs using a constrained output register? */
924 if (get_irn_mode(node) == mode_T) {
925 const ir_edge_t *edge;
927 foreach_out_edge(node, edge) {
928 ir_node *proj = get_edge_src_irn(edge);
929 const arch_register_req_t *req;
931 if (!arch_irn_consider_in_reg_alloc(cls, proj))
934 req = arch_get_register_req_out(proj);
935 if (!(req->type & arch_register_req_type_limited))
938 if (live_through_regs == NULL) {
939 rbitset_alloca(live_through_regs, n_regs);
940 determine_live_through_regs(live_through_regs, node);
943 rbitset_or(output_regs, req->limited, n_regs);
944 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
949 if (arch_irn_consider_in_reg_alloc(cls, node)) {
950 const arch_register_req_t *req = arch_get_register_req_out(node);
951 if (req->type & arch_register_req_type_limited) {
952 rbitset_alloca(live_through_regs, n_regs);
953 determine_live_through_regs(live_through_regs, node);
954 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
956 rbitset_or(output_regs, req->limited, n_regs);
965 /* create these arrays if we haven't yet */
966 if (live_through_regs == NULL) {
967 rbitset_alloca(live_through_regs, n_regs);
970 /* at this point we have to construct a bipartite matching problem to see
971 * which values should go to which registers
972 * Note: We're building the matrix in "reverse" - source registers are
973 * right, destinations left because this will produce the solution
974 * in the format required for permute_values.
976 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
978 /* add all combinations, then remove not allowed ones */
979 for (l = 0; l < n_regs; ++l) {
980 if (!rbitset_is_set(normal_regs, l)) {
981 hungarian_add(bp, l, l, 1);
985 for (r = 0; r < n_regs; ++r) {
986 if (!rbitset_is_set(normal_regs, r))
988 /* livethrough values may not use constrainted output registers */
989 if (rbitset_is_set(live_through_regs, l)
990 && rbitset_is_set(output_regs, r))
993 hungarian_add(bp, r, l, l == r ? 9 : 8);
997 for (i = 0; i < arity; ++i) {
998 ir_node *op = get_irn_n(node, i);
999 const arch_register_t *reg;
1000 const arch_register_req_t *req;
1001 const unsigned *limited;
1002 unsigned current_reg;
1004 if (!arch_irn_consider_in_reg_alloc(cls, op))
1007 req = arch_get_register_req(node, i);
1008 if (!(req->type & arch_register_req_type_limited))
1011 limited = req->limited;
1012 reg = arch_get_irn_register(op);
1013 current_reg = arch_register_get_index(reg);
1014 for (r = 0; r < n_regs; ++r) {
1015 if (rbitset_is_set(limited, r))
1017 hungarian_remv(bp, r, current_reg);
1021 //hungarian_print_costmatrix(bp, 1);
1022 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1024 assignment = ALLOCAN(unsigned, n_regs);
1025 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1029 fprintf(stderr, "Swap result:");
1030 for (i = 0; i < (int) n_regs; ++i) {
1031 fprintf(stderr, " %d", assignment[i]);
1033 fprintf(stderr, "\n");
1038 permute_values(live_nodes, node, assignment);
1041 /** test wether a node @p n is a copy of the value of node @p of */
1042 static bool is_copy_of(ir_node *value, ir_node *test_value)
1044 allocation_info_t *test_info;
1045 allocation_info_t *info;
1047 if (value == test_value)
1050 info = get_allocation_info(value);
1051 test_info = get_allocation_info(test_value);
1052 return test_info->original_value == info->original_value;
1056 * find a value in the end-assignment of a basic block
1057 * @returns the index into the assignment array if found
1060 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1063 assignment_t *assignments = info->assignments;
1064 for (r = 0; r < n_regs; ++r) {
1065 const assignment_t *assignment = &assignments[r];
1066 ir_node *a_value = assignment->value;
1068 if (a_value == NULL)
1070 if (is_copy_of(a_value, value))
1078 * Create the necessary permutations at the end of a basic block to fullfill
1079 * the register assignment for phi-nodes in the next block
1081 static void add_phi_permutations(ir_node *block, int p)
1084 unsigned *permutation;
1085 assignment_t *old_assignments;
1086 bool need_permutation;
1088 ir_node *pred = get_Block_cfgpred_block(block, p);
1090 block_info_t *pred_info = get_block_info(pred);
1092 /* predecessor not processed yet? nothing to do */
1093 if (!pred_info->processed)
1096 permutation = ALLOCAN(unsigned, n_regs);
1097 for (r = 0; r < n_regs; ++r) {
1101 /* check phi nodes */
1102 need_permutation = false;
1103 node = sched_first(block);
1104 for ( ; is_Phi(node); node = sched_next(node)) {
1105 const arch_register_t *reg;
1110 if (!arch_irn_consider_in_reg_alloc(cls, node))
1113 op = get_Phi_pred(node, p);
1114 if (!arch_irn_consider_in_reg_alloc(cls, op))
1117 a = find_value_in_block_info(pred_info, op);
1120 reg = arch_get_irn_register(node);
1121 regn = arch_register_get_index(reg);
1123 permutation[regn] = a;
1124 need_permutation = true;
1128 if (need_permutation) {
1129 /* permute values at end of predecessor */
1130 old_assignments = assignments;
1131 assignments = pred_info->assignments;
1132 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1134 assignments = old_assignments;
1137 /* change phi nodes to use the copied values */
1138 node = sched_first(block);
1139 for ( ; is_Phi(node); node = sched_next(node)) {
1143 if (!arch_irn_consider_in_reg_alloc(cls, node))
1146 op = get_Phi_pred(node, p);
1147 /* no need to do anything for Unknown inputs */
1148 if (!arch_irn_consider_in_reg_alloc(cls, op))
1151 /* we have permuted all values into the correct registers so we can
1152 simply query which value occupies the phis register in the
1154 a = arch_register_get_index(arch_get_irn_register(node));
1155 op = pred_info->assignments[a].value;
1156 set_Phi_pred(node, p, op);
1161 * Set preferences for a phis register based on the registers used on the
1164 static void adapt_phi_prefs(ir_node *phi)
1167 int arity = get_irn_arity(phi);
1168 ir_node *block = get_nodes_block(phi);
1169 allocation_info_t *info = get_allocation_info(phi);
1171 for (i = 0; i < arity; ++i) {
1172 ir_node *op = get_irn_n(phi, i);
1173 const arch_register_t *reg = arch_get_irn_register(op);
1175 ir_node *pred_block;
1176 block_info_t *pred_block_info;
1182 /* we only give the bonus if the predecessor already has register
1183 * assigned, otherwise we only see a dummy value
1184 * and any conclusions about its register are useless */
1185 pred_block = get_Block_cfgpred_block(block, i);
1186 pred_block_info = get_block_info(pred_block);
1187 if (!pred_block_info->processed)
1190 /* give bonus for already assigned register */
1191 pred = get_Block_cfgpred_block(block, i);
1192 weight = get_block_execfreq(execfreqs, pred);
1193 r = arch_register_get_index(reg);
1194 info->prefs[r] += weight * AFF_PHI;
1199 * After a phi has been assigned a register propagate preference inputs
1200 * to the phi inputs.
1202 static void propagate_phi_register(ir_node *phi)
1205 ir_node *block = get_nodes_block(phi);
1206 int arity = get_irn_arity(phi);
1207 const arch_register_t *reg = arch_get_irn_register(phi);
1208 unsigned r = arch_register_get_index(reg);
1210 for (i = 0; i < arity; ++i) {
1211 ir_node *op = get_Phi_pred(phi, i);
1212 allocation_info_t *info = get_allocation_info(op);
1216 /* already a register assigned? then we can't influence it anyway */
1217 /* TODO: what about splits which we might still do... */
1218 if (arch_get_irn_register(op) != NULL)
1221 pred = get_Block_cfgpred_block(block, i);
1222 weight = get_block_execfreq(execfreqs, pred);
1224 /* promote the prefered register */
1225 info->prefs[r] += AFF_PHI * weight;
1230 * Walker: assign registers to all nodes of a block that
1231 * need registers from the currently considered register class.
1233 static void allocate_coalesce_block(ir_node *block, void *data)
1236 ir_nodeset_t live_nodes;
1237 ir_nodeset_iterator_t iter;
1238 ir_node *node, *start;
1240 block_info_t *block_info;
1241 block_info_t **pred_block_infos;
1243 unsigned *output_regs; /**< collects registers which must not
1244 be used for optimistic splits */
1247 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1249 /* clear assignments */
1250 block_info = get_block_info(block);
1251 assignments = block_info->assignments;
1253 ir_nodeset_init(&live_nodes);
1255 /* gather regalloc infos of predecessor blocks */
1256 n_preds = get_Block_n_cfgpreds(block);
1257 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1258 for (i = 0; i < n_preds; ++i) {
1259 ir_node *pred = get_Block_cfgpred_block(block, i);
1260 block_info_t *pred_info = get_block_info(pred);
1261 pred_block_infos[i] = pred_info;
1264 phi_ins = ALLOCAN(ir_node*, n_preds);
1266 /* collect live-in nodes and preassigned values */
1267 be_lv_foreach(lv, block, be_lv_state_in, i) {
1268 const arch_register_t *reg;
1270 bool need_phi = false;
1272 node = be_lv_get_irn(lv, block, i);
1273 if (!arch_irn_consider_in_reg_alloc(cls, node))
1276 /* check all predecessors for this value, if it is not everywhere the
1277 same or unknown then we have to construct a phi
1278 (we collect the potential phi inputs here) */
1279 for (p = 0; p < n_preds; ++p) {
1280 block_info_t *pred_info = pred_block_infos[p];
1282 if (!pred_info->processed) {
1283 /* use node for now, it will get fixed later */
1287 int a = find_value_in_block_info(pred_info, node);
1289 /* must live out of predecessor */
1291 phi_ins[p] = pred_info->assignments[a].value;
1292 /* different value from last time? then we need a phi */
1293 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1300 ir_mode *mode = get_irn_mode(node);
1301 const arch_register_req_t *req = get_default_req_current_cls();
1305 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1306 be_set_phi_reg_req(phi, req);
1308 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1309 #ifdef DEBUG_libfirm
1310 for (i = 0; i < n_preds; ++i) {
1311 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1313 DB((dbg, LEVEL_3, "\n"));
1315 mark_as_copy_of(phi, node);
1316 sched_add_after(block, phi);
1320 allocation_info_t *info = get_allocation_info(node);
1321 info->current_value = phi_ins[0];
1323 /* Grab 1 of the inputs we constructed (might not be the same as
1324 * "node" as we could see the same copy of the value in all
1329 /* if the node already has a register assigned use it */
1330 reg = arch_get_irn_register(node);
1332 /* TODO: consult pred-block infos here. The value could be copied
1333 away in some/all predecessor blocks. We need to construct
1334 phi-nodes in this case.
1335 We even need to construct some Phi_0 like constructs in cases
1336 where the predecessor allocation is not determined yet. */
1340 /* remember that this node is live at the beginning of the block */
1341 ir_nodeset_insert(&live_nodes, node);
1344 rbitset_alloca(output_regs, n_regs);
1346 /* handle phis... */
1347 node = sched_first(block);
1348 for ( ; is_Phi(node); node = sched_next(node)) {
1349 const arch_register_t *reg;
1351 if (!arch_irn_consider_in_reg_alloc(cls, node))
1354 /* fill in regs already assigned */
1355 reg = arch_get_irn_register(node);
1359 adapt_phi_prefs(node);
1360 assign_reg(block, node, output_regs);
1361 propagate_phi_register(node);
1366 /* assign regs for live-in values */
1367 foreach_ir_nodeset(&live_nodes, node, iter) {
1368 const arch_register_t *reg = arch_get_irn_register(node);
1372 assign_reg(block, node, output_regs);
1373 /* shouldn't happen if we color in dominance order */
1374 assert (!is_Phi(node));
1377 /* assign instructions in the block */
1378 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1381 rewire_inputs(node);
1383 /* enforce use constraints */
1384 rbitset_clear_all(output_regs, n_regs);
1385 enforce_constraints(&live_nodes, node, output_regs);
1386 /* we may not use registers occupied here for optimistic splits */
1387 for (r = 0; r < n_regs; ++r) {
1388 if (assignments[r].value != NULL)
1389 rbitset_set(output_regs, r);
1392 rewire_inputs(node);
1394 /* free registers of values last used at this instruction */
1395 free_last_uses(&live_nodes, node);
1397 /* assign output registers */
1398 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1399 if (get_irn_mode(node) == mode_T) {
1400 const ir_edge_t *edge;
1401 foreach_out_edge(node, edge) {
1402 ir_node *proj = get_edge_src_irn(edge);
1403 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1405 assign_reg(block, proj, output_regs);
1407 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1408 assign_reg(block, node, output_regs);
1412 ir_nodeset_destroy(&live_nodes);
1415 block_info->processed = true;
1417 /* permute values at end of predecessor blocks in case of phi-nodes */
1420 for (p = 0; p < n_preds; ++p) {
1421 add_phi_permutations(block, p);
1425 /* if we have exactly 1 successor then we might be able to produce phi
1427 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1428 const ir_edge_t *edge
1429 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1430 ir_node *succ = get_edge_src_irn(edge);
1431 int p = get_edge_src_pos(edge);
1432 block_info_t *succ_info = get_block_info(succ);
1434 if (succ_info->processed) {
1435 add_phi_permutations(succ, p);
1441 * Run the register allocator for the current register class.
1443 static void be_straight_alloc_cls(void)
1445 lv = be_assure_liveness(birg);
1446 be_liveness_assure_sets(lv);
1447 be_liveness_assure_chk(lv);
1449 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1450 inc_irg_visited(irg);
1452 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1454 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1455 /* we need some dominance pre-order walk to ensure we see all
1456 * definitions/create copies before we encounter their users */
1457 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1459 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1462 static void dump(int mask, ir_graph *irg, const char *suffix,
1463 void (*dumper)(ir_graph *, const char *))
1465 if(birg->main_env->options->dump_flags & mask)
1466 be_dump(irg, suffix, dumper);
1470 * Run the spiller on the current graph.
1472 static void spill(void)
1474 /* make sure all nodes show their real register pressure */
1475 BE_TIMER_PUSH(t_ra_constr);
1476 be_pre_spill_prepare_constr(birg, cls);
1477 BE_TIMER_POP(t_ra_constr);
1479 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1482 BE_TIMER_PUSH(t_ra_spill);
1483 be_do_spill(birg, cls);
1484 BE_TIMER_POP(t_ra_spill);
1486 BE_TIMER_PUSH(t_ra_spill_apply);
1487 check_for_memory_operands(irg);
1488 BE_TIMER_POP(t_ra_spill_apply);
1490 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1494 * The straight register allocator for a whole procedure.
1496 static void be_straight_alloc(be_irg_t *new_birg)
1498 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1499 int n_cls = arch_env_get_n_reg_class(arch_env);
1502 obstack_init(&obst);
1505 irg = be_get_birg_irg(birg);
1506 execfreqs = birg->exec_freq;
1508 /* TODO: extract some of the stuff from bechordal allocator, like
1509 * statistics, time measurements, etc. and use them here too */
1511 for (c = 0; c < n_cls; ++c) {
1512 cls = arch_env_get_reg_class(arch_env, c);
1513 default_cls_req = NULL;
1514 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1517 stat_ev_ctx_push_str("regcls", cls->name);
1519 n_regs = arch_register_class_n_regs(cls);
1520 normal_regs = rbitset_malloc(n_regs);
1521 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1525 /* verify schedule and register pressure */
1526 BE_TIMER_PUSH(t_verify);
1527 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1528 be_verify_schedule(birg);
1529 be_verify_register_pressure(birg, cls, irg);
1530 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1531 assert(be_verify_schedule(birg) && "Schedule verification failed");
1532 assert(be_verify_register_pressure(birg, cls, irg)
1533 && "Register pressure verification failed");
1535 BE_TIMER_POP(t_verify);
1537 BE_TIMER_PUSH(t_ra_color);
1538 be_straight_alloc_cls();
1539 BE_TIMER_POP(t_ra_color);
1541 /* we most probably constructed new Phis so liveness info is invalid
1543 /* TODO: test liveness_introduce */
1544 be_liveness_invalidate(lv);
1547 stat_ev_ctx_pop("regcls");
1550 BE_TIMER_PUSH(t_ra_spill_apply);
1551 be_abi_fix_stack_nodes(birg->abi);
1552 BE_TIMER_POP(t_ra_spill_apply);
1554 BE_TIMER_PUSH(t_verify);
1555 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1556 be_verify_register_allocation(birg);
1557 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1558 assert(be_verify_register_allocation(birg)
1559 && "Register allocation invalid");
1561 BE_TIMER_POP(t_verify);
1563 obstack_free(&obst, NULL);
1567 * Initializes this module.
1569 void be_init_straight_alloc(void)
1571 static be_ra_t be_ra_straight = {
1575 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1577 be_register_allocator("straight", &be_ra_straight);
1580 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);