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"
63 #include "unionfind.h"
66 #include "bechordal_t.h"
75 #include "bespillutil.h"
78 #include "hungarian.h"
80 #define USE_FACTOR 1.0f
81 #define DEF_FACTOR 1.0f
82 #define NEIGHBOR_FACTOR 0.2f
83 #define AFF_SHOULD_BE_SAME 0.5f
85 #define SPLIT_DELTA 1.0f
87 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
89 static struct obstack obst;
90 static be_irg_t *birg;
92 static const arch_register_class_t *cls;
93 static const arch_register_req_t *default_cls_req;
95 static const ir_exec_freq *execfreqs;
96 static unsigned n_regs;
97 static unsigned *normal_regs;
98 static int *congruence_classes;
100 /** currently active assignments (while processing a basic block)
101 * maps registers to values(their current copies) */
102 static ir_node **assignments;
105 * allocation information: last_uses, register preferences
106 * the information is per firm-node.
108 struct allocation_info_t {
109 unsigned last_uses; /**< bitset indicating last uses (input pos) */
110 ir_node *current_value; /**< copy of the value that should be used */
111 ir_node *original_value; /**< for copies point to original value */
112 unsigned char should_be_same[2];
113 float prefs[0]; /**< register preferences */
115 typedef struct allocation_info_t allocation_info_t;
117 /** helper datastructure used when sorting register preferences */
122 typedef struct reg_pref_t reg_pref_t;
124 /** per basic-block information */
125 struct block_info_t {
126 bool processed; /**< indicate wether block is processed */
127 ir_node *assignments[0]; /**< register assignments at end of block */
129 typedef struct block_info_t block_info_t;
132 * Get the allocation info for a node.
133 * The info is allocated on the first visit of a node.
135 static allocation_info_t *get_allocation_info(ir_node *node)
137 allocation_info_t *info = get_irn_link(node);
139 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
140 info->current_value = node;
141 info->original_value = node;
142 set_irn_link(node, info);
149 * Get allocation information for a basic block
151 static block_info_t *get_block_info(ir_node *block)
153 block_info_t *info = get_irn_link(block);
155 assert(is_Block(block));
157 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
158 set_irn_link(block, info);
165 * Get default register requirement for the current register class
167 static const arch_register_req_t *get_default_req_current_cls(void)
169 if (default_cls_req == NULL) {
170 struct obstack *obst = get_irg_obstack(irg);
171 arch_register_req_t *req = OALLOCZ(obst, arch_register_req_t);
173 req->type = arch_register_req_type_normal;
176 default_cls_req = req;
178 return default_cls_req;
182 * Link the allocation info of a node to a copy.
183 * Afterwards, both nodes uses the same allocation info.
184 * Copy must not have an allocation info assigned yet.
186 * @param copy the node that gets the allocation info assigned
187 * @param value the original node
189 static void mark_as_copy_of(ir_node *copy, ir_node *value)
192 allocation_info_t *info = get_allocation_info(value);
193 allocation_info_t *copy_info = get_allocation_info(copy);
195 /* find original value */
196 original = info->original_value;
197 if (original != value) {
198 info = get_allocation_info(original);
201 assert(info->original_value == original);
202 info->current_value = copy;
204 /* the copy should not be linked to something else yet */
205 assert(copy_info->original_value == copy);
206 copy_info->original_value = original;
208 /* copy over allocation preferences */
209 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
213 * Calculate the penalties for every register on a node and its live neighbors.
215 * @param live_nodes the set of live nodes at the current position, may be NULL
216 * @param penalty the penalty to subtract from
217 * @param limited a raw bitset containing the limited set for the node
218 * @param node the node
220 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
221 float penalty, const unsigned* limited,
224 ir_nodeset_iterator_t iter;
226 allocation_info_t *info = get_allocation_info(node);
229 /* give penalty for all forbidden regs */
230 for (r = 0; r < n_regs; ++r) {
231 if (rbitset_is_set(limited, r))
234 info->prefs[r] -= penalty;
237 /* all other live values should get a penalty for allowed regs */
238 if (live_nodes == NULL)
241 /* TODO: reduce penalty if there are multiple allowed registers... */
242 penalty *= NEIGHBOR_FACTOR;
243 foreach_ir_nodeset(live_nodes, neighbor, iter) {
244 allocation_info_t *neighbor_info;
246 /* TODO: if op is used on multiple inputs we might not do a
248 if (neighbor == node)
251 neighbor_info = get_allocation_info(neighbor);
252 for (r = 0; r < n_regs; ++r) {
253 if (!rbitset_is_set(limited, r))
256 neighbor_info->prefs[r] -= penalty;
262 * Calculate the preferences of a definition for the current register class.
263 * If the definition uses a limited set of registers, reduce the preferences
264 * for the limited register on the node and its neighbors.
266 * @param live_nodes the set of live nodes at the current node
267 * @param weight the weight
268 * @param node the current node
270 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
273 const arch_register_req_t *req;
275 if (get_irn_mode(node) == mode_T) {
276 const ir_edge_t *edge;
277 foreach_out_edge(node, edge) {
278 ir_node *proj = get_edge_src_irn(edge);
279 check_defs(live_nodes, weight, proj);
284 if (!arch_irn_consider_in_reg_alloc(cls, node))
287 req = arch_get_register_req_out(node);
288 if (req->type & arch_register_req_type_limited) {
289 const unsigned *limited = req->limited;
290 float penalty = weight * DEF_FACTOR;
291 give_penalties_for_limits(live_nodes, penalty, limited, node);
294 if (req->type & arch_register_req_type_should_be_same) {
295 ir_node *insn = skip_Proj(node);
296 allocation_info_t *info = get_allocation_info(node);
297 int arity = get_irn_arity(insn);
300 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
301 for (i = 0; i < arity; ++i) {
304 allocation_info_t *op_info;
306 if (!rbitset_is_set(&req->other_same, i))
309 op = get_irn_n(insn, i);
311 /* if we the value at the should_be_same input doesn't die at the
312 * node, then it is no use to propagate the constraints (since a
313 * copy will emerge anyway) */
314 if (ir_nodeset_contains(live_nodes, op))
317 op_info = get_allocation_info(op);
318 for (r = 0; r < n_regs; ++r) {
319 op_info->prefs[r] += info->prefs[r] * factor;
326 * Walker: Runs an a block calculates the preferences for any
327 * node and every register from the considered register class.
329 static void analyze_block(ir_node *block, void *data)
331 float weight = get_block_execfreq(execfreqs, block);
332 ir_nodeset_t live_nodes;
336 ir_nodeset_init(&live_nodes);
337 be_liveness_end_of_block(lv, cls, block, &live_nodes);
339 sched_foreach_reverse(block, node) {
340 allocation_info_t *info;
347 check_defs(&live_nodes, weight, node);
350 arity = get_irn_arity(node);
352 /* the allocation info node currently only uses 1 unsigned value
353 to mark last used inputs. So we will fail for a node with more than
355 if (arity >= (int) sizeof(unsigned) * 8) {
356 panic("Node with more than %d inputs not supported yet",
357 (int) sizeof(unsigned) * 8);
360 info = get_allocation_info(node);
361 for (i = 0; i < arity; ++i) {
362 ir_node *op = get_irn_n(node, i);
363 if (!arch_irn_consider_in_reg_alloc(cls, op))
366 /* last usage of a value? */
367 if (!ir_nodeset_contains(&live_nodes, op)) {
368 rbitset_set(&info->last_uses, i);
372 be_liveness_transfer(cls, node, &live_nodes);
374 /* update weights based on usage constraints */
375 for (i = 0; i < arity; ++i) {
376 const arch_register_req_t *req;
377 const unsigned *limited;
378 ir_node *op = get_irn_n(node, i);
380 if (!arch_irn_consider_in_reg_alloc(cls, op))
383 req = arch_get_register_req(node, i);
384 if (!(req->type & arch_register_req_type_limited))
387 limited = req->limited;
388 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
393 ir_nodeset_destroy(&live_nodes);
396 static void create_congurence_class(ir_node *node, void *data)
401 int arity = get_irn_arity(node);
402 unsigned phi_idx = get_irn_idx(node);
403 phi_idx = uf_find(congruence_classes, phi_idx);
404 for (i = 0; i < arity; ++i) {
405 ir_node *op = get_Phi_pred(node, i);
406 int op_idx = get_irn_idx(op);
407 op_idx = uf_find(congruence_classes, op_idx);
408 phi_idx = uf_union(congruence_classes, phi_idx, op_idx);
412 /* should be same constraint? */
414 const arch_register_req_t *req = arch_get_register_req_out(node);
415 if (req->type & arch_register_req_type_should_be_same) {
416 ir_node *pred = get_Proj_pred(node);
417 int arity = get_irn_arity(pred);
419 unsigned node_idx = get_irn_idx(node);
420 node_idx = uf_find(congruence_classes, node_idx);
422 for (i = 0; i < arity; ++i) {
426 if (!rbitset_is_set(&req->other_same, i))
429 op = get_irn_n(pred, i);
430 op_idx = get_irn_idx(op);
431 op_idx = uf_find(congruence_classes, op_idx);
432 node_idx = uf_union(congruence_classes, node_idx, op_idx);
439 static void merge_congruence_prefs(ir_node *node, void *data)
441 allocation_info_t *info;
442 allocation_info_t *head_info;
443 unsigned node_idx = get_irn_idx(node);
444 unsigned node_set = uf_find(congruence_classes, node_idx);
449 /* head of congruence class or not in any class */
450 if (node_set == node_idx)
453 if (!arch_irn_consider_in_reg_alloc(cls, node))
456 head_info = get_allocation_info(get_idx_irn(irg, node_set));
457 info = get_allocation_info(node);
459 for (r = 0; r < n_regs; ++r) {
460 head_info->prefs[r] += info->prefs[r];
464 static void set_congruence_prefs(ir_node *node, void *data)
466 allocation_info_t *info;
467 allocation_info_t *head_info;
468 unsigned node_idx = get_irn_idx(node);
469 unsigned node_set = uf_find(congruence_classes, node_idx);
473 /* head of congruence class or not in any class */
474 if (node_set == node_idx)
477 if (!arch_irn_consider_in_reg_alloc(cls, node))
480 head_info = get_allocation_info(get_idx_irn(irg, node_set));
481 info = get_allocation_info(node);
483 memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
486 static void combine_congruence_classes(void)
488 size_t n = get_irg_last_idx(irg);
489 congruence_classes = XMALLOCN(int, n);
490 uf_init(congruence_classes, n);
492 /* create congruence classes */
493 irg_walk_graph(irg, create_congurence_class, NULL, NULL);
494 /* merge preferences */
495 irg_walk_graph(irg, merge_congruence_prefs, NULL, NULL);
496 irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
504 * Assign register reg to the given node.
506 * @param node the node
507 * @param reg the register
509 static void use_reg(ir_node *node, const arch_register_t *reg)
511 unsigned r = arch_register_get_index(reg);
512 assignments[r] = node;
513 arch_set_irn_register(node, reg);
516 static void free_reg_of_value(ir_node *node)
518 const arch_register_t *reg;
521 if (!arch_irn_consider_in_reg_alloc(cls, node))
524 reg = arch_get_irn_register(node);
525 r = arch_register_get_index(reg);
526 /* assignment->value may be NULL if a value is used at 2 inputs
527 so it gets freed twice. */
528 assert(assignments[r] == node || assignments[r] == NULL);
529 assignments[r] = NULL;
533 * Compare two register preferences in decreasing order.
535 static int compare_reg_pref(const void *e1, const void *e2)
537 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
538 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
539 if (rp1->pref < rp2->pref)
541 if (rp1->pref > rp2->pref)
546 static void fill_sort_candidates(reg_pref_t *regprefs,
547 const allocation_info_t *info)
551 for (r = 0; r < n_regs; ++r) {
552 float pref = info->prefs[r];
554 regprefs[r].pref = pref;
556 /* TODO: use a stable sort here to avoid unnecessary register jumping */
557 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
560 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
561 float pref, float pref_delta,
562 unsigned *output_regs)
564 const arch_register_t *reg;
565 ir_node *original_insn;
570 allocation_info_t *info = get_allocation_info(to_split);
573 float split_threshold;
577 /* stupid hack: don't optimisticallt split don't spill nodes...
578 * (so we don't split away the values produced because of
579 * must_be_different constraints) */
580 original_insn = skip_Proj(info->original_value);
581 if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
584 /* find the best free position where we could move to */
585 prefs = ALLOCAN(reg_pref_t, n_regs);
586 fill_sort_candidates(prefs, info);
587 for (i = 0; i < n_regs; ++i) {
589 if (!rbitset_is_set(normal_regs, r))
591 if (rbitset_is_set(output_regs, r))
593 if (assignments[r] == NULL)
599 /* TODO: use execfreq somehow... */
600 block = get_nodes_block(before);
601 delta = pref_delta + prefs[i].pref;
602 split_threshold = get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
603 if (delta < split_threshold) {
604 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
609 reg = arch_register_for_index(cls, r);
610 copy = be_new_Copy(cls, block, to_split);
611 mark_as_copy_of(copy, to_split);
612 free_reg_of_value(to_split);
614 sched_add_before(before, copy);
617 "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
618 copy, to_split, reg->name, before, delta));
623 * Determine and assign a register for node @p node
625 static void assign_reg(const ir_node *block, ir_node *node,
626 unsigned *output_regs)
628 const arch_register_t *reg;
629 allocation_info_t *info;
630 const arch_register_req_t *req;
631 reg_pref_t *reg_prefs;
634 const unsigned *allowed_regs;
637 assert(arch_irn_consider_in_reg_alloc(cls, node));
639 /* preassigned register? */
640 reg = arch_get_irn_register(node);
642 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
647 /* give should_be_same boni */
648 info = get_allocation_info(node);
649 req = arch_get_register_req_out(node);
651 in_node = skip_Proj(node);
652 if (req->type & arch_register_req_type_should_be_same) {
653 float weight = get_block_execfreq(execfreqs, block);
654 int arity = get_irn_arity(in_node);
657 assert(arity <= (int) sizeof(req->other_same) * 8);
658 for (i = 0; i < arity; ++i) {
660 const arch_register_t *reg;
662 if (!rbitset_is_set(&req->other_same, i))
665 in = get_irn_n(in_node, i);
666 reg = arch_get_irn_register(in);
668 r = arch_register_get_index(reg);
670 /* if the value didn't die here then we should not propagate the
671 * should_be_same info */
672 if (assignments[r] == in)
675 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
679 /* create list of register candidates and sort by their preference */
680 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
681 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
682 fill_sort_candidates(reg_prefs, info);
683 for (i = 0; i < n_regs; ++i) {
684 unsigned num = reg_prefs[i].num;
685 const arch_register_t *reg;
687 if (!rbitset_is_set(normal_regs, num))
690 reg = arch_register_for_index(cls, num);
691 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
693 DB((dbg, LEVEL_2, "\n"));
695 allowed_regs = normal_regs;
696 if (req->type & arch_register_req_type_limited) {
697 allowed_regs = req->limited;
700 for (i = 0; i < n_regs; ++i) {
701 r = reg_prefs[i].num;
702 if (!rbitset_is_set(allowed_regs, r))
704 if (assignments[r] == NULL)
707 float pref = reg_prefs[i].pref;
708 float delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
709 ir_node *before = skip_Proj(node);
710 bool res = try_optimistic_split(assignments[r], before,
718 panic("No register left for %+F\n", node);
721 reg = arch_register_for_index(cls, r);
722 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
727 * Add an permutation in front of a node and change the assignments
728 * due to this permutation.
730 * To understand this imagine a permutation like this:
740 * First we count how many destinations a single value has. At the same time
741 * we can be sure that each destination register has at most 1 source register
742 * (it can have 0 which means we don't care what value is in it).
743 * We ignore all fullfilled permuations (like 7->7)
744 * In a first pass we create as much copy instructions as possible as they
745 * are generally cheaper than exchanges. We do this by counting into how many
746 * destinations a register has to be copied (in the example it's 2 for register
747 * 3, or 1 for the registers 1,2,4 and 7).
748 * We can then create a copy into every destination register when the usecount
749 * of that register is 0 (= noone else needs the value in the register).
751 * After this step we should have cycles left. We implement a cyclic permutation
752 * of n registers with n-1 transpositions.
754 * @param live_nodes the set of live nodes, updated due to live range split
755 * @param before the node before we add the permutation
756 * @param permutation the permutation array indices are the destination
757 * registers, the values in the array are the source
760 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
761 unsigned *permutation)
763 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
767 /* determine how often each source register needs to be read */
768 for (r = 0; r < n_regs; ++r) {
769 unsigned old_reg = permutation[r];
772 value = assignments[old_reg];
774 /* nothing to do here, reg is not live. Mark it as fixpoint
775 * so we ignore it in the next steps */
783 block = get_nodes_block(before);
785 /* step1: create copies where immediately possible */
786 for (r = 0; r < n_regs; /* empty */) {
789 const arch_register_t *reg;
790 unsigned old_r = permutation[r];
792 /* - no need to do anything for fixed points.
793 - we can't copy if the value in the dest reg is still needed */
794 if (old_r == r || n_used[r] > 0) {
800 src = assignments[old_r];
801 copy = be_new_Copy(cls, block, src);
802 sched_add_before(before, copy);
803 reg = arch_register_for_index(cls, r);
804 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
805 copy, src, before, reg->name));
806 mark_as_copy_of(copy, src);
809 if (live_nodes != NULL) {
810 ir_nodeset_insert(live_nodes, copy);
813 /* old register has 1 user less, permutation is resolved */
814 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
817 assert(n_used[old_r] > 0);
819 if (n_used[old_r] == 0) {
820 if (live_nodes != NULL) {
821 ir_nodeset_remove(live_nodes, src);
823 free_reg_of_value(src);
826 /* advance or jump back (if this copy enabled another copy) */
827 if (old_r < r && n_used[old_r] == 0) {
834 /* at this point we only have "cycles" left which we have to resolve with
836 * TODO: if we have free registers left, then we should really use copy
837 * instructions for any cycle longer than 2 registers...
838 * (this is probably architecture dependent, there might be archs where
839 * copies are preferable even for 2-cycles) */
841 /* create perms with the rest */
842 for (r = 0; r < n_regs; /* empty */) {
843 const arch_register_t *reg;
844 unsigned old_r = permutation[r];
856 /* we shouldn't have copies from 1 value to multiple destinations left*/
857 assert(n_used[old_r] == 1);
859 /* exchange old_r and r2; after that old_r is a fixed point */
860 r2 = permutation[old_r];
862 in[0] = assignments[r2];
863 in[1] = assignments[old_r];
864 perm = be_new_Perm(cls, block, 2, in);
865 sched_add_before(before, perm);
866 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
867 perm, in[0], in[1], before));
869 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
870 mark_as_copy_of(proj0, in[0]);
871 reg = arch_register_for_index(cls, old_r);
874 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
875 mark_as_copy_of(proj1, in[1]);
876 reg = arch_register_for_index(cls, r2);
879 /* 1 value is now in the correct register */
880 permutation[old_r] = old_r;
881 /* the source of r changed to r2 */
884 /* if we have reached a fixpoint update data structures */
885 if (live_nodes != NULL) {
886 ir_nodeset_remove(live_nodes, in[0]);
887 ir_nodeset_remove(live_nodes, in[1]);
888 ir_nodeset_remove(live_nodes, proj0);
889 ir_nodeset_insert(live_nodes, proj1);
894 /* now we should only have fixpoints left */
895 for (r = 0; r < n_regs; ++r) {
896 assert(permutation[r] == r);
902 * Free regs for values last used.
904 * @param live_nodes set of live nodes, will be updated
905 * @param node the node to consider
907 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
909 allocation_info_t *info = get_allocation_info(node);
910 const unsigned *last_uses = &info->last_uses;
911 int arity = get_irn_arity(node);
914 for (i = 0; i < arity; ++i) {
917 /* check if one operand is the last use */
918 if (!rbitset_is_set(last_uses, i))
921 op = get_irn_n(node, i);
922 free_reg_of_value(op);
923 ir_nodeset_remove(live_nodes, op);
928 * change inputs of a node to the current value (copies/perms)
930 static void rewire_inputs(ir_node *node)
933 int arity = get_irn_arity(node);
935 for (i = 0; i < arity; ++i) {
936 ir_node *op = get_irn_n(node, i);
937 allocation_info_t *info;
939 if (!arch_irn_consider_in_reg_alloc(cls, op))
942 info = get_allocation_info(op);
943 info = get_allocation_info(info->original_value);
944 if (info->current_value != op) {
945 set_irn_n(node, i, info->current_value);
951 * Create a bitset of registers occupied with value living through an
954 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
956 const allocation_info_t *info = get_allocation_info(node);
961 /* mark all used registers as potentially live-through */
962 for (r = 0; r < n_regs; ++r) {
963 if (assignments[r] == NULL)
965 if (!rbitset_is_set(normal_regs, r))
968 rbitset_set(bitset, r);
971 /* remove registers of value dying at the instruction */
972 arity = get_irn_arity(node);
973 for (i = 0; i < arity; ++i) {
975 const arch_register_t *reg;
977 if (!rbitset_is_set(&info->last_uses, i))
980 op = get_irn_n(node, i);
981 reg = arch_get_irn_register(op);
982 rbitset_clear(bitset, arch_register_get_index(reg));
987 * Enforce constraints at a node by live range splits.
989 * @param live_nodes the set of live nodes, might be changed
990 * @param node the current node
992 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
993 unsigned *output_regs)
995 int arity = get_irn_arity(node);
997 hungarian_problem_t *bp;
999 unsigned *assignment;
1001 /* construct a list of register occupied by live-through values */
1002 unsigned *live_through_regs = NULL;
1004 /* see if any use constraints are not met */
1006 for (i = 0; i < arity; ++i) {
1007 ir_node *op = get_irn_n(node, i);
1008 const arch_register_t *reg;
1009 const arch_register_req_t *req;
1010 const unsigned *limited;
1013 if (!arch_irn_consider_in_reg_alloc(cls, op))
1016 /* are there any limitations for the i'th operand? */
1017 req = arch_get_register_req(node, i);
1018 if (!(req->type & arch_register_req_type_limited))
1021 limited = req->limited;
1022 reg = arch_get_irn_register(op);
1023 r = arch_register_get_index(reg);
1024 if (!rbitset_is_set(limited, r)) {
1025 /* found an assignment outside the limited set */
1031 /* is any of the live-throughs using a constrained output register? */
1032 if (get_irn_mode(node) == mode_T) {
1033 const ir_edge_t *edge;
1035 foreach_out_edge(node, edge) {
1036 ir_node *proj = get_edge_src_irn(edge);
1037 const arch_register_req_t *req;
1039 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1042 req = arch_get_register_req_out(proj);
1043 if (!(req->type & arch_register_req_type_limited))
1046 if (live_through_regs == NULL) {
1047 rbitset_alloca(live_through_regs, n_regs);
1048 determine_live_through_regs(live_through_regs, node);
1051 rbitset_or(output_regs, req->limited, n_regs);
1052 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1057 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1058 const arch_register_req_t *req = arch_get_register_req_out(node);
1059 if (req->type & arch_register_req_type_limited) {
1060 rbitset_alloca(live_through_regs, n_regs);
1061 determine_live_through_regs(live_through_regs, node);
1062 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1064 rbitset_or(output_regs, req->limited, n_regs);
1073 /* create these arrays if we haven't yet */
1074 if (live_through_regs == NULL) {
1075 rbitset_alloca(live_through_regs, n_regs);
1078 /* at this point we have to construct a bipartite matching problem to see
1079 * which values should go to which registers
1080 * Note: We're building the matrix in "reverse" - source registers are
1081 * right, destinations left because this will produce the solution
1082 * in the format required for permute_values.
1084 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1086 /* add all combinations, then remove not allowed ones */
1087 for (l = 0; l < n_regs; ++l) {
1088 if (!rbitset_is_set(normal_regs, l)) {
1089 hungarian_add(bp, l, l, 1);
1093 for (r = 0; r < n_regs; ++r) {
1094 if (!rbitset_is_set(normal_regs, r))
1096 /* livethrough values may not use constrainted output registers */
1097 if (rbitset_is_set(live_through_regs, l)
1098 && rbitset_is_set(output_regs, r))
1101 hungarian_add(bp, r, l, l == r ? 9 : 8);
1105 for (i = 0; i < arity; ++i) {
1106 ir_node *op = get_irn_n(node, i);
1107 const arch_register_t *reg;
1108 const arch_register_req_t *req;
1109 const unsigned *limited;
1110 unsigned current_reg;
1112 if (!arch_irn_consider_in_reg_alloc(cls, op))
1115 req = arch_get_register_req(node, i);
1116 if (!(req->type & arch_register_req_type_limited))
1119 limited = req->limited;
1120 reg = arch_get_irn_register(op);
1121 current_reg = arch_register_get_index(reg);
1122 for (r = 0; r < n_regs; ++r) {
1123 if (rbitset_is_set(limited, r))
1125 hungarian_remv(bp, r, current_reg);
1129 //hungarian_print_costmatrix(bp, 1);
1130 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1132 assignment = ALLOCAN(unsigned, n_regs);
1133 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1137 fprintf(stderr, "Swap result:");
1138 for (i = 0; i < (int) n_regs; ++i) {
1139 fprintf(stderr, " %d", assignment[i]);
1141 fprintf(stderr, "\n");
1146 permute_values(live_nodes, node, assignment);
1149 /** test wether a node @p n is a copy of the value of node @p of */
1150 static bool is_copy_of(ir_node *value, ir_node *test_value)
1152 allocation_info_t *test_info;
1153 allocation_info_t *info;
1155 if (value == test_value)
1158 info = get_allocation_info(value);
1159 test_info = get_allocation_info(test_value);
1160 return test_info->original_value == info->original_value;
1164 * find a value in the end-assignment of a basic block
1165 * @returns the index into the assignment array if found
1168 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1171 ir_node **assignments = info->assignments;
1172 for (r = 0; r < n_regs; ++r) {
1173 ir_node *a_value = assignments[r];
1175 if (a_value == NULL)
1177 if (is_copy_of(a_value, value))
1185 * Create the necessary permutations at the end of a basic block to fullfill
1186 * the register assignment for phi-nodes in the next block
1188 static void add_phi_permutations(ir_node *block, int p)
1191 unsigned *permutation;
1192 ir_node **old_assignments;
1193 bool need_permutation;
1195 ir_node *pred = get_Block_cfgpred_block(block, p);
1197 block_info_t *pred_info = get_block_info(pred);
1199 /* predecessor not processed yet? nothing to do */
1200 if (!pred_info->processed)
1203 permutation = ALLOCAN(unsigned, n_regs);
1204 for (r = 0; r < n_regs; ++r) {
1208 /* check phi nodes */
1209 need_permutation = false;
1210 node = sched_first(block);
1211 for ( ; is_Phi(node); node = sched_next(node)) {
1212 const arch_register_t *reg;
1217 if (!arch_irn_consider_in_reg_alloc(cls, node))
1220 op = get_Phi_pred(node, p);
1221 if (!arch_irn_consider_in_reg_alloc(cls, op))
1224 a = find_value_in_block_info(pred_info, op);
1227 reg = arch_get_irn_register(node);
1228 regn = arch_register_get_index(reg);
1230 permutation[regn] = a;
1231 need_permutation = true;
1235 if (need_permutation) {
1236 /* permute values at end of predecessor */
1237 old_assignments = assignments;
1238 assignments = pred_info->assignments;
1239 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1241 assignments = old_assignments;
1244 /* change phi nodes to use the copied values */
1245 node = sched_first(block);
1246 for ( ; is_Phi(node); node = sched_next(node)) {
1250 if (!arch_irn_consider_in_reg_alloc(cls, node))
1253 op = get_Phi_pred(node, p);
1254 /* no need to do anything for Unknown inputs */
1255 if (!arch_irn_consider_in_reg_alloc(cls, op))
1258 /* we have permuted all values into the correct registers so we can
1259 simply query which value occupies the phis register in the
1261 a = arch_register_get_index(arch_get_irn_register(node));
1262 op = pred_info->assignments[a];
1263 set_Phi_pred(node, p, op);
1268 * Set preferences for a phis register based on the registers used on the
1271 static void adapt_phi_prefs(ir_node *phi)
1274 int arity = get_irn_arity(phi);
1275 ir_node *block = get_nodes_block(phi);
1276 allocation_info_t *info = get_allocation_info(phi);
1278 for (i = 0; i < arity; ++i) {
1279 ir_node *op = get_irn_n(phi, i);
1280 const arch_register_t *reg = arch_get_irn_register(op);
1281 ir_node *pred_block;
1282 block_info_t *pred_block_info;
1288 /* we only give the bonus if the predecessor already has registers
1289 * assigned, otherwise we only see a dummy value
1290 * and any conclusions about its register are useless */
1291 pred_block = get_Block_cfgpred_block(block, i);
1292 pred_block_info = get_block_info(pred_block);
1293 if (!pred_block_info->processed)
1296 /* give bonus for already assigned register */
1297 weight = get_block_execfreq(execfreqs, pred_block);
1298 r = arch_register_get_index(reg);
1299 info->prefs[r] += weight * AFF_PHI;
1304 * After a phi has been assigned a register propagate preference inputs
1305 * to the phi inputs.
1307 static void propagate_phi_register(ir_node *phi, unsigned r)
1310 ir_node *block = get_nodes_block(phi);
1311 int arity = get_irn_arity(phi);
1313 for (i = 0; i < arity; ++i) {
1314 ir_node *op = get_Phi_pred(phi, i);
1315 allocation_info_t *info = get_allocation_info(op);
1316 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1318 = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1320 if (info->prefs[r] >= weight)
1323 /* promote the prefered register */
1324 info->prefs[r] = AFF_PHI * weight;
1326 propagate_phi_register(op, r);
1331 * Walker: assign registers to all nodes of a block that
1332 * need registers from the currently considered register class.
1334 static void allocate_coalesce_block(ir_node *block, void *data)
1337 ir_nodeset_t live_nodes;
1338 ir_nodeset_iterator_t iter;
1339 ir_node *node, *start;
1341 block_info_t *block_info;
1342 block_info_t **pred_block_infos;
1344 unsigned *output_regs; /**< collects registers which must not
1345 be used for optimistic splits */
1348 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1350 /* clear assignments */
1351 block_info = get_block_info(block);
1352 assignments = block_info->assignments;
1354 ir_nodeset_init(&live_nodes);
1356 /* gather regalloc infos of predecessor blocks */
1357 n_preds = get_Block_n_cfgpreds(block);
1358 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1359 for (i = 0; i < n_preds; ++i) {
1360 ir_node *pred = get_Block_cfgpred_block(block, i);
1361 block_info_t *pred_info = get_block_info(pred);
1362 pred_block_infos[i] = pred_info;
1365 phi_ins = ALLOCAN(ir_node*, n_preds);
1367 /* collect live-in nodes and preassigned values */
1368 be_lv_foreach(lv, block, be_lv_state_in, i) {
1369 const arch_register_t *reg;
1371 bool need_phi = false;
1373 node = be_lv_get_irn(lv, block, i);
1374 if (!arch_irn_consider_in_reg_alloc(cls, node))
1377 /* check all predecessors for this value, if it is not everywhere the
1378 same or unknown then we have to construct a phi
1379 (we collect the potential phi inputs here) */
1380 for (p = 0; p < n_preds; ++p) {
1381 block_info_t *pred_info = pred_block_infos[p];
1383 if (!pred_info->processed) {
1384 /* use node for now, it will get fixed later */
1388 int a = find_value_in_block_info(pred_info, node);
1390 /* must live out of predecessor */
1392 phi_ins[p] = pred_info->assignments[a];
1393 /* different value from last time? then we need a phi */
1394 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1401 ir_mode *mode = get_irn_mode(node);
1402 const arch_register_req_t *req = get_default_req_current_cls();
1406 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1407 be_set_phi_reg_req(phi, req);
1409 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1410 #ifdef DEBUG_libfirm
1411 for (i = 0; i < n_preds; ++i) {
1412 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1414 DB((dbg, LEVEL_3, "\n"));
1416 mark_as_copy_of(phi, node);
1417 sched_add_after(block, phi);
1421 allocation_info_t *info = get_allocation_info(node);
1422 info->current_value = phi_ins[0];
1424 /* Grab 1 of the inputs we constructed (might not be the same as
1425 * "node" as we could see the same copy of the value in all
1430 /* if the node already has a register assigned use it */
1431 reg = arch_get_irn_register(node);
1433 /* TODO: consult pred-block infos here. The value could be copied
1434 away in some/all predecessor blocks. We need to construct
1435 phi-nodes in this case.
1436 We even need to construct some Phi_0 like constructs in cases
1437 where the predecessor allocation is not determined yet. */
1441 /* remember that this node is live at the beginning of the block */
1442 ir_nodeset_insert(&live_nodes, node);
1445 rbitset_alloca(output_regs, n_regs);
1447 /* handle phis... */
1448 node = sched_first(block);
1449 for ( ; is_Phi(node); node = sched_next(node)) {
1450 const arch_register_t *reg;
1452 if (!arch_irn_consider_in_reg_alloc(cls, node))
1455 /* fill in regs already assigned */
1456 reg = arch_get_irn_register(node);
1460 adapt_phi_prefs(node);
1461 assign_reg(block, node, output_regs);
1463 reg = arch_get_irn_register(node);
1464 propagate_phi_register(node, arch_register_get_index(reg));
1469 /* assign regs for live-in values */
1470 foreach_ir_nodeset(&live_nodes, node, iter) {
1471 const arch_register_t *reg = arch_get_irn_register(node);
1475 assign_reg(block, node, output_regs);
1476 /* shouldn't happen if we color in dominance order */
1477 assert (!is_Phi(node));
1480 /* assign instructions in the block */
1481 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1484 rewire_inputs(node);
1486 /* enforce use constraints */
1487 rbitset_clear_all(output_regs, n_regs);
1488 enforce_constraints(&live_nodes, node, output_regs);
1489 /* we may not use registers occupied here for optimistic splits */
1490 for (r = 0; r < n_regs; ++r) {
1491 if (assignments[r] != NULL)
1492 rbitset_set(output_regs, r);
1495 rewire_inputs(node);
1497 /* free registers of values last used at this instruction */
1498 free_last_uses(&live_nodes, node);
1500 /* assign output registers */
1501 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1502 if (get_irn_mode(node) == mode_T) {
1503 const ir_edge_t *edge;
1504 foreach_out_edge(node, edge) {
1505 ir_node *proj = get_edge_src_irn(edge);
1506 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1508 assign_reg(block, proj, output_regs);
1510 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1511 assign_reg(block, node, output_regs);
1515 ir_nodeset_destroy(&live_nodes);
1518 block_info->processed = true;
1520 /* permute values at end of predecessor blocks in case of phi-nodes */
1523 for (p = 0; p < n_preds; ++p) {
1524 add_phi_permutations(block, p);
1528 /* if we have exactly 1 successor then we might be able to produce phi
1530 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1531 const ir_edge_t *edge
1532 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1533 ir_node *succ = get_edge_src_irn(edge);
1534 int p = get_edge_src_pos(edge);
1535 block_info_t *succ_info = get_block_info(succ);
1537 if (succ_info->processed) {
1538 add_phi_permutations(succ, p);
1544 * Run the register allocator for the current register class.
1546 static void be_straight_alloc_cls(void)
1548 lv = be_assure_liveness(birg);
1549 be_liveness_assure_sets(lv);
1550 be_liveness_assure_chk(lv);
1552 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1554 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1556 be_clear_links(irg);
1557 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1558 combine_congruence_classes();
1559 /* we need some dominance pre-order walk to ensure we see all
1560 * definitions/create copies before we encounter their users */
1561 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1563 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1566 static void dump(int mask, ir_graph *irg, const char *suffix,
1567 void (*dumper)(ir_graph *, const char *))
1569 if(birg->main_env->options->dump_flags & mask)
1570 be_dump(irg, suffix, dumper);
1574 * Run the spiller on the current graph.
1576 static void spill(void)
1578 /* make sure all nodes show their real register pressure */
1579 BE_TIMER_PUSH(t_ra_constr);
1580 be_pre_spill_prepare_constr(birg, cls);
1581 BE_TIMER_POP(t_ra_constr);
1583 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1586 BE_TIMER_PUSH(t_ra_spill);
1587 be_do_spill(birg, cls);
1588 BE_TIMER_POP(t_ra_spill);
1590 BE_TIMER_PUSH(t_ra_spill_apply);
1591 check_for_memory_operands(irg);
1592 BE_TIMER_POP(t_ra_spill_apply);
1594 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1598 * The straight register allocator for a whole procedure.
1600 static void be_straight_alloc(be_irg_t *new_birg)
1602 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1603 int n_cls = arch_env_get_n_reg_class(arch_env);
1606 obstack_init(&obst);
1609 irg = be_get_birg_irg(birg);
1610 execfreqs = birg->exec_freq;
1612 /* TODO: extract some of the stuff from bechordal allocator, like
1613 * statistics, time measurements, etc. and use them here too */
1615 for (c = 0; c < n_cls; ++c) {
1616 cls = arch_env_get_reg_class(arch_env, c);
1617 default_cls_req = NULL;
1618 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1621 stat_ev_ctx_push_str("regcls", cls->name);
1623 n_regs = arch_register_class_n_regs(cls);
1624 normal_regs = rbitset_malloc(n_regs);
1625 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1629 /* verify schedule and register pressure */
1630 BE_TIMER_PUSH(t_verify);
1631 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1632 be_verify_schedule(birg);
1633 be_verify_register_pressure(birg, cls, irg);
1634 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1635 assert(be_verify_schedule(birg) && "Schedule verification failed");
1636 assert(be_verify_register_pressure(birg, cls, irg)
1637 && "Register pressure verification failed");
1639 BE_TIMER_POP(t_verify);
1641 BE_TIMER_PUSH(t_ra_color);
1642 be_straight_alloc_cls();
1643 BE_TIMER_POP(t_ra_color);
1645 /* we most probably constructed new Phis so liveness info is invalid
1647 /* TODO: test liveness_introduce */
1648 be_liveness_invalidate(lv);
1651 stat_ev_ctx_pop("regcls");
1654 BE_TIMER_PUSH(t_ra_spill_apply);
1655 be_abi_fix_stack_nodes(birg->abi);
1656 BE_TIMER_POP(t_ra_spill_apply);
1658 BE_TIMER_PUSH(t_verify);
1659 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1660 be_verify_register_allocation(birg);
1661 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1662 assert(be_verify_register_allocation(birg)
1663 && "Register allocation invalid");
1665 BE_TIMER_POP(t_verify);
1667 obstack_free(&obst, NULL);
1671 * Initializes this module.
1673 void be_init_straight_alloc(void)
1675 static be_ra_t be_ra_straight = {
1679 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1681 be_register_allocator("straight", &be_ra_straight);
1684 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);