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 permutate_values code
43 * - We have to pessimistically construct Phi_0s when not all predecessors
44 * of a block are known.
45 * - Phi color assignment should give bonus points towards registers already
46 * assigned at predecessors.
47 * - think about a smarter sequence of visiting the blocks. Sorted by
48 * execfreq might be good, or looptree from inner to outermost loops going
49 * over blocks in a reverse postorder
58 #include "irgraph_t.h"
59 #include "iredges_t.h"
70 #include "bechordal_t.h"
75 #include "bespillutil.h"
78 #include "bipartite.h"
79 #include "hungarian.h"
81 #define USE_FACTOR 1.0f
82 #define DEF_FACTOR 1.0f
83 #define NEIGHBOR_FACTOR 0.2f
84 #define AFF_SHOULD_BE_SAME 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 bitset_t *ignore_regs;
99 /** info about the current assignment for a register */
100 struct assignment_t {
101 ir_node *value; /**< currently assigned value */
103 typedef struct assignment_t assignment_t;
105 /** currently active assignments (while processing a basic block) */
106 static assignment_t *assignments;
109 * allocation information: last_uses, register preferences
110 * the information is per firm-node.
112 struct allocation_info_t {
113 unsigned last_uses; /**< bitset indicating last uses (input pos) */
114 ir_node *current_value; /**< copy of the value that should be used */
115 ir_node *original_value; /**< for copies point to original value */
116 float prefs[0]; /**< register preferences */
118 typedef struct allocation_info_t allocation_info_t;
120 /** helper datastructure used when sorting register preferences */
125 typedef struct reg_pref_t reg_pref_t;
127 /** per basic-block information */
128 struct block_info_t {
129 bool processed; /**< indicate wether block is processed */
130 assignment_t assignments[0]; /**< register assignments at end of block */
132 typedef struct block_info_t block_info_t;
135 * Get the allocation info for a node.
136 * The info is allocated on the first visit of a node.
138 static allocation_info_t *get_allocation_info(ir_node *node)
140 allocation_info_t *info;
141 if (!irn_visited_else_mark(node)) {
142 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
143 info = obstack_alloc(&obst, size);
144 memset(info, 0, size);
145 info->current_value = node;
146 info->original_value = node;
147 set_irn_link(node, info);
149 info = get_irn_link(node);
156 * Get allocation information for a basic block
158 static block_info_t *get_block_info(ir_node *block)
162 assert(is_Block(block));
163 if (!irn_visited_else_mark(block)) {
164 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
165 info = obstack_alloc(&obst, size);
166 memset(info, 0, size);
167 set_irn_link(block, info);
169 info = get_irn_link(block);
176 * Get default register requirement for the current register class
178 static const arch_register_req_t *get_default_req_current_cls(void)
180 if (default_cls_req == NULL) {
181 struct obstack *obst = get_irg_obstack(irg);
182 arch_register_req_t *req = obstack_alloc(obst, sizeof(*req));
183 memset(req, 0, sizeof(*req));
185 req->type = arch_register_req_type_normal;
188 default_cls_req = req;
190 return default_cls_req;
194 * Link the allocation info of a node to a copy.
195 * Afterwards, both nodes uses the same allocation info.
196 * Copy must not have an allocation info assigned yet.
198 * @param copy the node that gets the allocation info assigned
199 * @param value the original node
201 static void mark_as_copy_of(ir_node *copy, ir_node *value)
204 allocation_info_t *info = get_allocation_info(value);
205 allocation_info_t *copy_info = get_allocation_info(copy);
207 /* find original value */
208 original = info->original_value;
209 if (original != value) {
210 info = get_allocation_info(original);
213 assert(info->original_value == original);
214 info->current_value = copy;
216 /* the copy should not be linked to something else yet */
217 assert(copy_info->original_value == copy);
218 /* copy over allocation preferences */
219 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
220 copy_info->original_value = original;
224 * Calculate the penalties for every register on a node and its live neighbors.
226 * @param live_nodes the set of live nodes at the current position, may be NULL
227 * @param penalty the penalty to subtract from
228 * @param limited a raw bitset containing the limited set for the node
229 * @param node the node
231 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
232 float penalty, const unsigned* limited,
235 ir_nodeset_iterator_t iter;
237 allocation_info_t *info = get_allocation_info(node);
240 /* give penalty for all forbidden regs */
241 for (r = 0; r < n_regs; ++r) {
242 if (rbitset_is_set(limited, r))
245 info->prefs[r] -= penalty;
248 /* all other live values should get a penalty for allowed regs */
249 if (live_nodes == NULL)
252 /* TODO: reduce penalty if there are multiple allowed registers... */
253 penalty *= NEIGHBOR_FACTOR;
254 foreach_ir_nodeset(live_nodes, neighbor, iter) {
255 allocation_info_t *neighbor_info;
257 /* TODO: if op is used on multiple inputs we might not do a
259 if (neighbor == node)
262 neighbor_info = get_allocation_info(neighbor);
263 for (r = 0; r < n_regs; ++r) {
264 if (!rbitset_is_set(limited, r))
267 neighbor_info->prefs[r] -= penalty;
273 * Calculate the preferences of a definition for the current register class.
274 * If the definition uses a limited set of registers, reduce the preferences
275 * for the limited register on the node and its neighbors.
277 * @param live_nodes the set of live nodes at the current node
278 * @param weight the weight
279 * @param node the current node
281 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
284 const arch_register_req_t *req;
286 if (get_irn_mode(node) == mode_T) {
287 const ir_edge_t *edge;
288 foreach_out_edge(node, edge) {
289 ir_node *proj = get_edge_src_irn(edge);
290 check_defs(live_nodes, weight, proj);
295 if (!arch_irn_consider_in_reg_alloc(cls, node))
298 req = arch_get_register_req_out(node);
299 if (req->type & arch_register_req_type_limited) {
300 const unsigned *limited = req->limited;
301 float penalty = weight * DEF_FACTOR;
302 give_penalties_for_limits(live_nodes, penalty, limited, node);
305 if (req->type & arch_register_req_type_should_be_same) {
306 ir_node *insn = skip_Proj(node);
307 allocation_info_t *info = get_allocation_info(node);
308 int arity = get_irn_arity(insn);
311 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
312 for (i = 0; i < arity; ++i) {
315 allocation_info_t *op_info;
317 if (!rbitset_is_set(&req->other_same, i))
320 op = get_irn_n(insn, i);
321 op_info = get_allocation_info(op);
322 for (r = 0; r < n_regs; ++r) {
323 if (bitset_is_set(ignore_regs, r))
325 op_info->prefs[r] += info->prefs[r] * factor;
332 * Walker: Runs an a block calculates the preferences for any
333 * node and every register from the considered register class.
335 static void analyze_block(ir_node *block, void *data)
337 float weight = get_block_execfreq(execfreqs, block);
338 ir_nodeset_t live_nodes;
342 ir_nodeset_init(&live_nodes);
343 be_liveness_end_of_block(lv, cls, block, &live_nodes);
345 sched_foreach_reverse(block, node) {
346 allocation_info_t *info;
353 /* TODO give/take penalties for should_be_same/different) */
354 check_defs(&live_nodes, weight, node);
357 arity = get_irn_arity(node);
359 /* the allocation info node currently only uses 1 unsigned value
360 to mark last used inputs. So we will fail for a node with more than
362 if (arity >= (int) sizeof(unsigned) * 8) {
363 panic("Node with more than %d inputs not supported yet",
364 (int) sizeof(unsigned) * 8);
367 info = get_allocation_info(node);
368 for (i = 0; i < arity; ++i) {
369 ir_node *op = get_irn_n(node, i);
370 if (!arch_irn_consider_in_reg_alloc(cls, op))
373 /* last usage of a value? */
374 if (!ir_nodeset_contains(&live_nodes, op)) {
375 rbitset_set(&info->last_uses, i);
379 be_liveness_transfer(cls, node, &live_nodes);
381 /* update weights based on usage constraints */
382 for (i = 0; i < arity; ++i) {
383 const arch_register_req_t *req;
384 const unsigned *limited;
385 ir_node *op = get_irn_n(node, i);
387 if (!arch_irn_consider_in_reg_alloc(cls, op))
390 req = arch_get_register_req(node, i);
391 if (!(req->type & arch_register_req_type_limited))
394 /* TODO: give penalties to neighbors for precolored nodes! */
396 limited = req->limited;
397 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
402 ir_nodeset_destroy(&live_nodes);
406 * Assign register reg to the given node.
408 * @param node the node
409 * @param reg the register
411 static void use_reg(ir_node *node, const arch_register_t *reg)
413 unsigned r = arch_register_get_index(reg);
414 assignment_t *assignment = &assignments[r];
416 assert(assignment->value == NULL);
417 assignment->value = node;
419 arch_set_irn_register(node, reg);
423 * Compare two register preferences in decreasing order.
425 static int compare_reg_pref(const void *e1, const void *e2)
427 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
428 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
429 if (rp1->pref < rp2->pref)
431 if (rp1->pref > rp2->pref)
436 static void fill_sort_candidates(reg_pref_t *regprefs,
437 const allocation_info_t *info)
441 for (r = 0; r < n_regs; ++r) {
442 float pref = info->prefs[r];
443 if (bitset_is_set(ignore_regs, r)) {
447 regprefs[r].pref = pref;
449 /* TODO: use a stable sort here to avoid unnecessary register jumping */
450 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
454 * Determine and assign a register for node @p node
456 static void assign_reg(const ir_node *block, ir_node *node)
458 const arch_register_t *reg;
459 allocation_info_t *info;
460 const arch_register_req_t *req;
461 reg_pref_t *reg_prefs;
465 assert(arch_irn_consider_in_reg_alloc(cls, node));
467 /* preassigned register? */
468 reg = arch_get_irn_register(node);
470 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
475 /* give should_be_same boni */
476 info = get_allocation_info(node);
477 req = arch_get_register_req_out(node);
479 in_node = skip_Proj(node);
480 if (req->type & arch_register_req_type_should_be_same) {
481 float weight = get_block_execfreq(execfreqs, block);
482 int arity = get_irn_arity(in_node);
485 assert(arity <= (int) sizeof(req->other_same) * 8);
486 for (i = 0; i < arity; ++i) {
488 const arch_register_t *reg;
490 if (!rbitset_is_set(&req->other_same, i))
493 in = get_irn_n(in_node, i);
494 reg = arch_get_irn_register(in);
496 r = arch_register_get_index(reg);
497 if (bitset_is_set(ignore_regs, r))
499 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
503 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
504 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
505 fill_sort_candidates(reg_prefs, info);
506 for (i = 0; i < n_regs; ++i) {
507 unsigned num = reg_prefs[i].num;
508 const arch_register_t *reg = arch_register_for_index(cls, num);
509 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
511 DB((dbg, LEVEL_2, "\n"));
513 for (i = 0; i < n_regs; ++i) {
514 unsigned r = reg_prefs[i].num;
515 /* ignores are last and we should have at least 1 non-ignore left */
516 assert(!bitset_is_set(ignore_regs, r));
518 TODO: It might be better to copy the value occupying the register
519 around here instead of trying the next one, find out when... */
520 if (assignments[r].value != NULL)
522 reg = arch_register_for_index(cls, r);
523 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
529 static void free_reg_of_value(ir_node *node)
531 assignment_t *assignment;
532 const arch_register_t *reg;
535 if (!arch_irn_consider_in_reg_alloc(cls, node))
538 reg = arch_get_irn_register(node);
539 r = arch_register_get_index(reg);
540 assignment = &assignments[r];
541 assert(assignment->value == node);
542 assignment->value = NULL;
546 * Add an permutation in front of a node and change the assignments
547 * due to this permutation.
549 * To understand this imagine a permutation like this:
559 * First we count how many destinations a single value has. At the same time
560 * we can be sure that each destination register has at most 1 source register
561 * (it can have 0 which means we don't care what value is in it).
562 * We ignore all fullfilled permuations (like 7->7)
563 * In a first pass we create as much copy instructions as possible as they
564 * are generally cheaper than exchanges. We do this by counting into how many
565 * destinations a register has to be copied (in the example it's 2 for register
566 * 3, or 1 for the registers 1,2,4 and 7).
567 * We can then create a copy into every destination register when the usecount
568 * of that register is 0 (= noone else needs the value in the register).
570 * After this step we should have cycles left. We implement a cyclic permutation
571 * of n registers with n-1 transpositions.
573 * @param live_nodes the set of live nodes, updated due to live range split
574 * @param before the node before we add the permutation
575 * @param permutation the permutation array indices are the destination
576 * registers, the values in the array are the source
579 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
580 unsigned *permutation)
583 ir_node **ins = ALLOCANZ(ir_node*, n_regs);
584 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
587 /* create a list of permutations. Leave out fix points. */
588 for (r = 0; r < n_regs; ++r) {
589 unsigned old_reg = permutation[r];
590 assignment_t *assignment;
593 /* no need to do anything for a fixpoint */
597 assignment = &assignments[old_reg];
598 value = assignment->value;
600 /* nothing to do here, reg is not live. Mark it as fixpoint
601 * so we ignore it in the next steps */
606 ins[old_reg] = value;
608 free_reg_of_value(value);
610 /* free occupation infos, we'll add the values back later */
611 if (live_nodes != NULL) {
612 ir_nodeset_remove(live_nodes, value);
616 block = get_nodes_block(before);
618 /* step1: create copies where immediately possible */
619 for (r = 0; r < n_regs; /* empty */) {
622 const arch_register_t *reg;
623 unsigned old_r = permutation[r];
625 /* - no need to do anything for fixed points.
626 - we can't copy if the value in the dest reg is still needed */
627 if (old_r == r || n_used[r] > 0) {
634 copy = be_new_Copy(cls, block, src);
635 sched_add_before(before, copy);
636 reg = arch_register_for_index(cls, r);
637 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
638 copy, src, before, reg->name));
639 mark_as_copy_of(copy, src);
642 if (live_nodes != NULL) {
643 ir_nodeset_insert(live_nodes, copy);
646 /* old register has 1 user less, permutation is resolved */
647 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
648 assert(n_used[old_r] > 0);
652 /* advance or jump back (if this copy enabled another copy) */
653 if (old_r < r && n_used[old_r] == 0) {
660 /* at this point we only have "cycles" left which we have to resolve with
662 * TODO: if we have free registers left, then we should really use copy
663 * instructions for any cycle longer than 2 registers...
664 * (this is probably architecture dependent, there might be archs where
665 * copies are preferable even for 2-cycles) */
667 /* create perms with the rest */
668 for (r = 0; r < n_regs; /* empty */) {
669 const arch_register_t *reg;
670 unsigned old_r = permutation[r];
682 /* we shouldn't have copies from 1 value to multiple destinations left*/
683 assert(n_used[old_r] == 1);
685 /* exchange old_r and r2; after that old_r is a fixed point */
686 r2 = permutation[old_r];
690 perm = be_new_Perm(cls, block, 2, in);
691 sched_add_before(before, perm);
692 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
693 perm, in[0], in[1], before));
695 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
696 mark_as_copy_of(proj0, in[0]);
697 reg = arch_register_for_index(cls, old_r);
699 if (live_nodes != NULL) {
700 ir_nodeset_insert(live_nodes, proj0);
703 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
705 /* 1 value is now in the correct register */
706 permutation[old_r] = old_r;
707 /* the source of r changed to r2 */
710 reg = arch_register_for_index(cls, r2);
712 /* if we have reached a fixpoint update data structures */
713 mark_as_copy_of(proj1, in[1]);
715 if (live_nodes != NULL) {
716 ir_nodeset_insert(live_nodes, proj1);
719 arch_set_irn_register(proj1, reg);
724 /* now we should only have fixpoints left */
725 for (r = 0; r < n_regs; ++r) {
726 assert(permutation[r] == r);
732 * Free regs for values last used.
734 * @param live_nodes set of live nodes, will be updated
735 * @param node the node to consider
737 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
739 allocation_info_t *info = get_allocation_info(node);
740 const unsigned *last_uses = &info->last_uses;
741 int arity = get_irn_arity(node);
743 for (i = 0; i < arity; ++i) {
746 /* check if one operand is the last use */
747 if (!rbitset_is_set(last_uses, i))
750 op = get_irn_n(node, i);
751 free_reg_of_value(op);
752 ir_nodeset_remove(live_nodes, op);
757 * Create a bitset of registers occupied with value living through an
760 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
762 const allocation_info_t *info = get_allocation_info(node);
767 /* mark all used registers as potentially live-through */
768 for (r = 0; r < n_regs; ++r) {
769 const assignment_t *assignment = &assignments[r];
770 if (assignment->value == NULL)
773 rbitset_set(bitset, r);
776 /* remove registers of value dying at the instruction */
777 arity = get_irn_arity(node);
778 for (i = 0; i < arity; ++i) {
780 const arch_register_t *reg;
782 if (!rbitset_is_set(&info->last_uses, i))
785 op = get_irn_n(node, i);
786 reg = arch_get_irn_register(op);
787 rbitset_clear(bitset, arch_register_get_index(reg));
792 * Enforce constraints at a node by live range splits.
794 * @param live_nodes the set of live nodes, might be changed
795 * @param node the current node
797 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
799 int arity = get_irn_arity(node);
801 hungarian_problem_t *bp;
803 unsigned *assignment;
805 /* see if any use constraints are not met */
807 for (i = 0; i < arity; ++i) {
808 ir_node *op = get_irn_n(node, i);
809 const arch_register_t *reg;
810 const arch_register_req_t *req;
811 const unsigned *limited;
814 if (!arch_irn_consider_in_reg_alloc(cls, op))
817 /* are there any limitations for the i'th operand? */
818 req = arch_get_register_req(node, i);
819 if (!(req->type & arch_register_req_type_limited))
822 limited = req->limited;
823 reg = arch_get_irn_register(op);
824 r = arch_register_get_index(reg);
825 if (!rbitset_is_set(limited, r)) {
826 /* found an assignement outside the limited set */
832 /* construct a list of register occupied by live-through values */
833 unsigned *live_through_regs = NULL;
834 unsigned *output_regs = NULL;
836 /* is any of the live-throughs using a constrainted output register? */
837 if (get_irn_mode(node) == mode_T) {
838 const ir_edge_t *edge;
840 foreach_out_edge(node, edge) {
841 ir_node *proj = get_edge_src_irn(edge);
842 const arch_register_req_t *req;
844 if (!arch_irn_consider_in_reg_alloc(cls, proj))
847 req = arch_get_register_req_out(proj);
848 if (!(req->type & arch_register_req_type_limited))
851 if (live_through_regs == NULL) {
852 rbitset_alloca(live_through_regs, n_regs);
853 determine_live_through_regs(live_through_regs, node);
855 rbitset_alloca(output_regs, n_regs);
858 rbitset_or(output_regs, req->limited, n_regs);
859 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
864 if (arch_irn_consider_in_reg_alloc(cls, node)) {
865 const arch_register_req_t *req = arch_get_register_req_out(node);
866 if (req->type & arch_register_req_type_limited) {
867 rbitset_alloca(live_through_regs, n_regs);
868 determine_live_through_regs(live_through_regs, node);
869 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
872 rbitset_alloca(output_regs, n_regs);
873 rbitset_or(output_regs, req->limited, n_regs);
882 /* create these arrays if we haven't yet */
883 if (output_regs == NULL) {
884 if (live_through_regs == NULL) {
885 rbitset_alloca(live_through_regs, n_regs);
887 rbitset_alloca(output_regs, n_regs);
890 /* at this point we have to construct a bipartite matching problem to see
891 which values should go to which registers */
892 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
894 /* add all combinations, then remove not allowed ones */
895 for (l = 0; l < n_regs; ++l) {
896 if (bitset_is_set(ignore_regs, l)) {
897 hungarian_add(bp, l, l, 1);
901 for (r = 0; r < n_regs; ++r) {
902 if (bitset_is_set(ignore_regs, r))
904 /* livethrough values may not use constrainted output registers */
905 if (rbitset_is_set(live_through_regs, l)
906 && rbitset_is_set(output_regs, r))
909 hungarian_add(bp, l, r, l == r ? 9 : 8);
913 for (i = 0; i < arity; ++i) {
914 ir_node *op = get_irn_n(node, i);
915 const arch_register_t *reg;
916 const arch_register_req_t *req;
917 const unsigned *limited;
918 unsigned current_reg;
920 if (!arch_irn_consider_in_reg_alloc(cls, op))
923 req = arch_get_register_req(node, i);
924 if (!(req->type & arch_register_req_type_limited))
927 limited = req->limited;
928 reg = arch_get_irn_register(op);
929 current_reg = arch_register_get_index(reg);
930 for (r = 0; r < n_regs; ++r) {
931 if (rbitset_is_set(limited, r))
933 hungarian_remv(bp, current_reg, r);
937 hungarian_print_costmatrix(bp, 1);
938 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
940 assignment = ALLOCAN(unsigned, n_regs);
941 res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
945 printf("Swap result:");
946 for (i = 0; i < (int) n_regs; ++i) {
947 printf(" %d", assignment[i]);
954 permutate_values(live_nodes, node, assignment);
957 /** test wether a node @p n is a copy of the value of node @p of */
958 static bool is_copy_of(ir_node *value, ir_node *test_value)
960 allocation_info_t *test_info;
964 if (value == test_value)
967 test_info = get_allocation_info(test_value);
968 return test_info->original_value == value;
972 * find a value in the end-assignment of a basic block
973 * @returns the index into the assignment array if found
976 static int find_value_in_block_info(block_info_t *info, ir_node *value)
979 assignment_t *assignments = info->assignments;
980 for (r = 0; r < n_regs; ++r) {
981 const assignment_t *assignment = &assignments[r];
982 if (is_copy_of(assignment->value, value))
990 * Create the necessary permutations at the end of a basic block to fullfill
991 * the register assignment for phi-nodes in the next block
993 static void add_phi_permutations(ir_node *block, int p)
996 unsigned *permutation;
997 assignment_t *old_assignments;
998 bool need_permutation;
1000 ir_node *pred = get_Block_cfgpred_block(block, p);
1002 block_info_t *pred_info = get_block_info(pred);
1004 /* predecessor not processed yet? nothing to do */
1005 if (!pred_info->processed)
1008 permutation = ALLOCAN(unsigned, n_regs);
1009 for (r = 0; r < n_regs; ++r) {
1013 /* check phi nodes */
1014 need_permutation = false;
1015 node = sched_first(block);
1016 for ( ; is_Phi(node); node = sched_next(node)) {
1017 const arch_register_t *reg;
1022 if (!arch_irn_consider_in_reg_alloc(cls, node))
1025 op = get_Phi_pred(node, p);
1026 a = find_value_in_block_info(pred_info, op);
1029 reg = arch_get_irn_register(node);
1030 regn = arch_register_get_index(reg);
1032 permutation[regn] = a;
1033 need_permutation = true;
1037 if (!need_permutation)
1040 /* permutate values at end of predecessor */
1041 old_assignments = assignments;
1042 assignments = pred_info->assignments;
1043 permutate_values(NULL, be_get_end_of_block_insertion_point(pred),
1045 assignments = old_assignments;
1047 /* change phi nodes to use the copied values */
1048 node = sched_first(block);
1049 for ( ; is_Phi(node); node = sched_next(node)) {
1053 if (!arch_irn_consider_in_reg_alloc(cls, node))
1056 /* we have permutated all values into the correct registers so we can
1057 simply query which value occupies the phis register in the
1059 a = arch_register_get_index(arch_get_irn_register(node));
1060 op = pred_info->assignments[a].value;
1061 set_Phi_pred(node, p, op);
1065 static void handle_phi_prefs(ir_node *phi)
1068 int arity = get_irn_arity(phi);
1069 ir_node *block = get_nodes_block(phi);
1070 allocation_info_t *info = get_allocation_info(phi);
1072 for (i = 0; i < arity; ++i) {
1073 ir_node *op = get_irn_n(phi, i);
1074 const arch_register_t *reg = arch_get_irn_register(op);
1082 /* give bonus for already assigned register */
1083 pred = get_Block_cfgpred_block(block, i);
1084 weight = get_block_execfreq(execfreqs, pred);
1085 r = arch_register_get_index(reg);
1086 info->prefs[r] += weight * AFF_PHI;
1091 * Walker: assign registers to all nodes of a block that
1092 * need registers from the currently considered register class.
1094 static void allocate_coalesce_block(ir_node *block, void *data)
1097 ir_nodeset_t live_nodes;
1098 ir_nodeset_iterator_t iter;
1099 ir_node *node, *start;
1101 block_info_t *block_info;
1102 block_info_t *processed_pred_info;
1103 block_info_t **pred_block_infos;
1104 bool all_preds_processed;
1107 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1109 /* clear assignments */
1110 block_info = get_block_info(block);
1111 assignments = block_info->assignments;
1113 ir_nodeset_init(&live_nodes);
1115 /* gather regalloc infos of predecessor blocks */
1116 n_preds = get_Block_n_cfgpreds(block);
1117 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1118 all_preds_processed = true;
1119 for (i = 0; i < n_preds; ++i) {
1120 ir_node *pred = get_Block_cfgpred_block(block, i);
1121 block_info_t *pred_info = get_block_info(pred);
1122 pred_block_infos[i] = pred_info;
1124 if (!pred_info->processed) {
1125 all_preds_processed = false;
1127 /* we need 1 (arbitrary) processed predecessor */
1128 processed_pred_info = pred_info;
1132 /* collect live-in nodes and preassigned values */
1133 be_lv_foreach(lv, block, be_lv_state_in, i) {
1134 const arch_register_t *reg;
1136 node = be_lv_get_irn(lv, block, i);
1137 if (!arch_irn_consider_in_reg_alloc(cls, node))
1140 /* if we don't know all predecessors, then we have no idea which values
1141 are copied, so we have to pessimistically construct phi-nodes for all
1143 if (!all_preds_processed) {
1144 ir_mode *mode = get_irn_mode(node);
1145 ir_node **ins = ALLOCAN(ir_node*, n_preds);
1146 const arch_register_req_t *req = get_default_req_current_cls();
1150 for (i2 = 0; i2 < n_preds; ++i2) {
1153 phi = new_r_Phi(block, n_preds, ins, mode);
1154 be_set_phi_reg_req(phi, req);
1156 DB((dbg, LEVEL_3, "Pessimistic Phi %+F (for %+F)\n", phi, node));
1158 /* TODO: if node had a register assigned use that as a strong
1160 mark_as_copy_of(phi, node);
1161 sched_add_after(block, phi);
1165 /* check wether the value is the same in all predecessors,
1166 if not construct a phi node */
1169 /* if the node already has a register assigned use it */
1170 reg = arch_get_irn_register(node);
1172 /* TODO: consult pred-block infos here. The value could be copied
1173 away in some/all predecessor blocks. We need to construct
1174 phi-nodes in this case.
1175 We even need to construct some Phi_0 like constructs in cases
1176 where the predecessor allocation is not determined yet. */
1180 /* remember that this node is live at the beginning of the block */
1181 ir_nodeset_insert(&live_nodes, node);
1184 /* handle phis... */
1185 node = sched_first(block);
1186 for ( ; is_Phi(node); node = sched_next(node)) {
1187 const arch_register_t *reg;
1189 if (!arch_irn_consider_in_reg_alloc(cls, node))
1192 /* fill in regs already assigned */
1193 reg = arch_get_irn_register(node);
1197 /* TODO: give boni for registers already assigned at the
1199 handle_phi_prefs(node);
1200 assign_reg(block, node);
1205 /* assign regs for live-in values */
1206 foreach_ir_nodeset(&live_nodes, node, iter) {
1207 const arch_register_t *reg = arch_get_irn_register(node);
1211 assign_reg(block, node);
1214 /* assign instructions in the block */
1215 for (node = start; !sched_is_end(node); node = sched_next(node)) {
1216 int arity = get_irn_arity(node);
1219 /* enforce use constraints */
1220 enforce_constraints(&live_nodes, node);
1222 /* exchange values to copied values where needed */
1223 for (i = 0; i < arity; ++i) {
1224 ir_node *op = get_irn_n(node, i);
1225 allocation_info_t *info;
1227 if (!arch_irn_consider_in_reg_alloc(cls, op))
1230 info = get_allocation_info(op);
1231 if (info->current_value != op) {
1232 set_irn_n(node, i, info->current_value);
1236 /* free registers of values last used at this instruction */
1237 free_last_uses(&live_nodes, node);
1239 /* assign output registers */
1240 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1241 if (get_irn_mode(node) == mode_T) {
1242 const ir_edge_t *edge;
1243 foreach_out_edge(node, edge) {
1244 ir_node *proj = get_edge_src_irn(edge);
1245 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1247 assign_reg(block, proj);
1249 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1250 assign_reg(block, node);
1254 ir_nodeset_destroy(&live_nodes);
1257 block_info->processed = true;
1259 /* permutate values at end of predecessor blocks in case of phi-nodes */
1262 for (p = 0; p < n_preds; ++p) {
1263 add_phi_permutations(block, p);
1267 /* if we have exactly 1 successor then we might be able to produce phi
1269 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1270 const ir_edge_t *edge
1271 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1272 ir_node *succ = get_edge_src_irn(edge);
1273 int p = get_edge_src_pos(edge);
1274 block_info_t *succ_info = get_block_info(succ);
1276 if (succ_info->processed) {
1277 add_phi_permutations(succ, p);
1283 * Run the register allocator for the current register class.
1285 static void be_straight_alloc_cls(void)
1287 lv = be_assure_liveness(birg);
1288 be_liveness_assure_sets(lv);
1289 be_liveness_assure_chk(lv);
1291 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1292 inc_irg_visited(irg);
1294 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1296 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1297 /* we need some dominance pre-order walk to ensure we see all
1298 * definitions/create copies before we encounter their users */
1299 dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1301 ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1304 static void dump(int mask, ir_graph *irg, const char *suffix,
1305 void (*dumper)(ir_graph *, const char *))
1307 if(birg->main_env->options->dump_flags & mask)
1308 be_dump(irg, suffix, dumper);
1312 * Run the spiller on the current graph.
1314 static void spill(void)
1316 /* make sure all nodes show their real register pressure */
1317 BE_TIMER_PUSH(t_ra_constr);
1318 be_pre_spill_prepare_constr(birg, cls);
1319 BE_TIMER_POP(t_ra_constr);
1321 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1324 BE_TIMER_PUSH(t_ra_spill);
1325 be_do_spill(birg, cls);
1326 BE_TIMER_POP(t_ra_spill);
1328 BE_TIMER_PUSH(t_ra_spill_apply);
1329 check_for_memory_operands(irg);
1330 BE_TIMER_POP(t_ra_spill_apply);
1332 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1336 * The straight register allocator for a whole procedure.
1338 static void be_straight_alloc(be_irg_t *new_birg)
1340 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1341 int n_cls = arch_env_get_n_reg_class(arch_env);
1344 obstack_init(&obst);
1347 irg = be_get_birg_irg(birg);
1348 execfreqs = birg->exec_freq;
1350 /* TODO: extract some of the stuff from bechordal allocator, like
1351 * statistics, time measurements, etc. and use them here too */
1353 for (c = 0; c < n_cls; ++c) {
1354 cls = arch_env_get_reg_class(arch_env, c);
1355 default_cls_req = NULL;
1356 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1359 stat_ev_ctx_push_str("regcls", cls->name);
1361 n_regs = arch_register_class_n_regs(cls);
1362 ignore_regs = bitset_malloc(n_regs);
1363 be_put_ignore_regs(birg, cls, ignore_regs);
1367 /* verify schedule and register pressure */
1368 BE_TIMER_PUSH(t_verify);
1369 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1370 be_verify_schedule(birg);
1371 be_verify_register_pressure(birg, cls, irg);
1372 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1373 assert(be_verify_schedule(birg) && "Schedule verification failed");
1374 assert(be_verify_register_pressure(birg, cls, irg)
1375 && "Register pressure verification failed");
1377 BE_TIMER_POP(t_verify);
1379 BE_TIMER_PUSH(t_ra_color);
1380 be_straight_alloc_cls();
1381 BE_TIMER_POP(t_ra_color);
1383 bitset_free(ignore_regs);
1385 stat_ev_ctx_pop("regcls");
1388 BE_TIMER_PUSH(t_verify);
1389 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
1390 be_verify_register_allocation(birg);
1391 } else if(birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
1392 assert(be_verify_register_allocation(birg)
1393 && "Register allocation invalid");
1395 BE_TIMER_POP(t_verify);
1397 obstack_free(&obst, NULL);
1401 * Initializes this module.
1403 void be_init_straight_alloc(void)
1405 static be_ra_t be_ra_straight = {
1409 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1411 be_register_allocator("straight", &be_ra_straight);
1414 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);