2 * Copyright (C) 1995-2011 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 Preference Guided Register Assignment
23 * @author Matthias Braun
26 * The idea is to allocate registers in 2 passes:
27 * 1. A first pass to determine "preferred" registers for live-ranges. This
28 * calculates for each register and each live-range a value indicating
29 * the usefulness. (You can roughly think of the value as the negative
30 * costs needed for copies when the value is in the specific registers...)
32 * 2. Walk blocks and assigns registers in a greedy fashion. Preferring
33 * registers with high preferences. When register constraints are not met,
34 * add copies and split live-ranges.
37 * - make use of free registers in the permute_values code
50 #include "iredges_t.h"
51 #include "irgraph_t.h"
59 #include "raw_bitset.h"
60 #include "unionfind.h"
62 #include "hungarian.h"
65 #include "bechordal_t.h"
74 #include "bespillutil.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
85 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
87 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
89 static struct obstack obst;
91 static const arch_register_class_t *cls;
93 static unsigned n_regs;
94 static unsigned *normal_regs;
95 static int *congruence_classes;
96 static ir_node **block_order;
97 static size_t n_block_order;
99 /** currently active assignments (while processing a basic block)
100 * maps registers to values(their current copies) */
101 static ir_node **assignments;
104 * allocation information: last_uses, register preferences
105 * the information is per firm-node.
107 struct allocation_info_t {
108 unsigned last_uses[2]; /**< bitset indicating last uses (input pos) */
109 ir_node *current_value; /**< copy of the value that should be used */
110 ir_node *original_value; /**< for copies point to original value */
111 float prefs[]; /**< register preferences */
113 typedef struct allocation_info_t allocation_info_t;
115 /** helper datastructure used when sorting register preferences */
120 typedef struct reg_pref_t reg_pref_t;
122 /** per basic-block information */
123 struct block_info_t {
124 bool processed; /**< indicate whether block is processed */
125 ir_node *assignments[]; /**< register assignments at end of block */
127 typedef struct block_info_t block_info_t;
130 * Get the allocation info for a node.
131 * The info is allocated on the first visit of a node.
133 static allocation_info_t *get_allocation_info(ir_node *node)
135 allocation_info_t *info = (allocation_info_t*)get_irn_link(node);
137 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
138 info->current_value = node;
139 info->original_value = node;
140 set_irn_link(node, info);
146 static allocation_info_t *try_get_allocation_info(const ir_node *node)
148 return (allocation_info_t*) get_irn_link(node);
152 * Get allocation information for a basic block
154 static block_info_t *get_block_info(ir_node *block)
156 block_info_t *info = (block_info_t*)get_irn_link(block);
158 assert(is_Block(block));
160 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
161 set_irn_link(block, info);
168 * Link the allocation info of a node to a copy.
169 * Afterwards, both nodes uses the same allocation info.
170 * Copy must not have an allocation info assigned yet.
172 * @param copy the node that gets the allocation info assigned
173 * @param value the original node
175 static void mark_as_copy_of(ir_node *copy, ir_node *value)
177 allocation_info_t *info = get_allocation_info(value);
178 allocation_info_t *copy_info = get_allocation_info(copy);
180 /* find original value */
181 ir_node *original = info->original_value;
182 if (original != value) {
183 info = get_allocation_info(original);
186 assert(info->original_value == original);
187 info->current_value = copy;
189 /* the copy should not be linked to something else yet */
190 assert(copy_info->original_value == copy);
191 copy_info->original_value = original;
193 /* copy over allocation preferences */
194 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
198 * Calculate the penalties for every register on a node and its live neighbors.
200 * @param live_nodes the set of live nodes at the current position, may be NULL
201 * @param penalty the penalty to subtract from
202 * @param limited a raw bitset containing the limited set for the node
203 * @param node the node
205 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
206 float penalty, const unsigned* limited,
209 allocation_info_t *info = get_allocation_info(node);
211 /* give penalty for all forbidden regs */
212 for (unsigned r = 0; r < n_regs; ++r) {
213 if (rbitset_is_set(limited, r))
216 info->prefs[r] -= penalty;
219 /* all other live values should get a penalty for allowed regs */
220 if (live_nodes == NULL)
223 penalty *= NEIGHBOR_FACTOR;
224 size_t n_allowed = rbitset_popcount(limited, n_regs);
226 /* only create a very weak penalty if multiple regs are allowed */
227 penalty = (penalty * 0.8f) / n_allowed;
229 foreach_ir_nodeset(live_nodes, neighbor, iter) {
230 allocation_info_t *neighbor_info;
232 /* TODO: if op is used on multiple inputs we might not do a
234 if (neighbor == node)
237 neighbor_info = get_allocation_info(neighbor);
238 for (unsigned r = 0; r < n_regs; ++r) {
239 if (!rbitset_is_set(limited, r))
242 neighbor_info->prefs[r] -= penalty;
248 * Calculate the preferences of a definition for the current register class.
249 * If the definition uses a limited set of registers, reduce the preferences
250 * for the limited register on the node and its neighbors.
252 * @param live_nodes the set of live nodes at the current node
253 * @param weight the weight
254 * @param node the current node
256 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
259 const arch_register_req_t *req = arch_get_irn_register_req(node);
260 if (req->type & arch_register_req_type_limited) {
261 const unsigned *limited = req->limited;
262 float penalty = weight * DEF_FACTOR;
263 give_penalties_for_limits(live_nodes, penalty, limited, node);
266 if (req->type & arch_register_req_type_should_be_same) {
267 ir_node *insn = skip_Proj(node);
268 allocation_info_t *info = get_allocation_info(node);
269 int arity = get_irn_arity(insn);
271 float factor = 1.0f / rbitset_popcount(&req->other_same, arity);
272 for (int i = 0; i < arity; ++i) {
273 if (!rbitset_is_set(&req->other_same, i))
276 ir_node *op = get_irn_n(insn, i);
278 /* if we the value at the should_be_same input doesn't die at the
279 * node, then it is no use to propagate the constraints (since a
280 * copy will emerge anyway) */
281 if (ir_nodeset_contains(live_nodes, op))
284 allocation_info_t *op_info = get_allocation_info(op);
285 for (unsigned r = 0; r < n_regs; ++r) {
286 op_info->prefs[r] += info->prefs[r] * factor;
293 * Walker: Runs an a block calculates the preferences for any
294 * node and every register from the considered register class.
296 static void analyze_block(ir_node *block, void *data)
298 float weight = (float)get_block_execfreq(block);
299 ir_nodeset_t live_nodes;
302 ir_nodeset_init(&live_nodes);
303 be_liveness_end_of_block(lv, cls, block, &live_nodes);
305 sched_foreach_reverse(block, node) {
310 be_foreach_definition(node, cls, value,
311 check_defs(&live_nodes, weight, value);
315 int arity = get_irn_arity(node);
317 /* the allocation info node currently only uses 1 unsigned value
318 to mark last used inputs. So we will fail for a node with more than
320 allocation_info_t *info = get_allocation_info(node);
321 if (arity >= (int) sizeof(info->last_uses) * 8) {
322 panic("Node with more than %d inputs not supported yet",
323 (int) sizeof(info->last_uses) * 8);
326 for (int i = 0; i < arity; ++i) {
327 ir_node *op = get_irn_n(node, i);
328 const arch_register_req_t *req = arch_get_irn_register_req(op);
332 /* last usage of a value? */
333 if (!ir_nodeset_contains(&live_nodes, op)) {
334 rbitset_set(info->last_uses, i);
338 be_liveness_transfer(cls, node, &live_nodes);
340 /* update weights based on usage constraints */
341 for (int i = 0; i < arity; ++i) {
342 ir_node *op = get_irn_n(node, i);
343 if (!arch_irn_consider_in_reg_alloc(cls, op))
346 const arch_register_req_t *req
347 = arch_get_irn_register_req_in(node, i);
348 if (!(req->type & arch_register_req_type_limited))
351 const unsigned *limited = req->limited;
352 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR,
357 ir_nodeset_destroy(&live_nodes);
360 static void congruence_def(ir_nodeset_t *live_nodes, const ir_node *node)
362 const arch_register_req_t *req = arch_get_irn_register_req(node);
364 /* should be same constraint? */
365 if (req->type & arch_register_req_type_should_be_same) {
366 const ir_node *insn = skip_Proj_const(node);
367 int arity = get_irn_arity(insn);
368 unsigned node_idx = get_irn_idx(node);
369 node_idx = uf_find(congruence_classes, node_idx);
371 for (int i = 0; i < arity; ++i) {
372 if (!rbitset_is_set(&req->other_same, i))
375 ir_node *op = get_irn_n(insn, i);
376 int op_idx = get_irn_idx(op);
377 op_idx = uf_find(congruence_classes, op_idx);
379 /* do we interfere with the value */
380 bool interferes = false;
381 foreach_ir_nodeset(live_nodes, live, iter) {
382 int lv_idx = get_irn_idx(live);
383 lv_idx = uf_find(congruence_classes, lv_idx);
384 if (lv_idx == op_idx) {
389 /* don't put in same affinity class if we interfere */
393 uf_union(congruence_classes, node_idx, op_idx);
394 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
396 /* one should_be_same is enough... */
402 static void create_congruence_class(ir_node *block, void *data)
404 ir_nodeset_t live_nodes;
407 ir_nodeset_init(&live_nodes);
408 be_liveness_end_of_block(lv, cls, block, &live_nodes);
410 /* check should be same constraints */
411 ir_node *last_phi = NULL;
412 sched_foreach_reverse(block, node) {
419 be_foreach_definition(node, cls, value,
420 congruence_def(&live_nodes, value);
422 be_liveness_transfer(cls, node, &live_nodes);
425 ir_nodeset_destroy(&live_nodes);
429 /* check phi congruence classes */
430 sched_foreach_reverse_from(last_phi, phi) {
433 if (!arch_irn_consider_in_reg_alloc(cls, phi))
436 int node_idx = get_irn_idx(phi);
437 node_idx = uf_find(congruence_classes, node_idx);
439 int arity = get_irn_arity(phi);
440 for (int i = 0; i < arity; ++i) {
441 ir_node *op = get_Phi_pred(phi, i);
442 int op_idx = get_irn_idx(op);
443 op_idx = uf_find(congruence_classes, op_idx);
445 /* do we interfere with the value */
446 bool interferes = false;
447 foreach_ir_nodeset(&live_nodes, live, iter) {
448 int lv_idx = get_irn_idx(live);
449 lv_idx = uf_find(congruence_classes, lv_idx);
450 if (lv_idx == op_idx) {
455 /* don't put in same affinity class if we interfere */
458 /* any other phi has the same input? */
459 sched_foreach(block, phi) {
464 if (!arch_irn_consider_in_reg_alloc(cls, phi))
466 oop = get_Phi_pred(phi, i);
469 oop_idx = get_irn_idx(oop);
470 oop_idx = uf_find(congruence_classes, oop_idx);
471 if (oop_idx == op_idx) {
479 /* merge the 2 congruence classes and sum up their preferences */
480 int old_node_idx = node_idx;
481 node_idx = uf_union(congruence_classes, node_idx, op_idx);
482 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
485 old_node_idx = node_idx == old_node_idx ? op_idx : old_node_idx;
486 allocation_info_t *head_info
487 = get_allocation_info(get_idx_irn(irg, node_idx));
488 allocation_info_t *other_info
489 = get_allocation_info(get_idx_irn(irg, old_node_idx));
490 for (unsigned r = 0; r < n_regs; ++r) {
491 head_info->prefs[r] += other_info->prefs[r];
495 ir_nodeset_destroy(&live_nodes);
498 static void set_congruence_prefs(ir_node *node, void *data)
501 unsigned node_idx = get_irn_idx(node);
502 unsigned node_set = uf_find(congruence_classes, node_idx);
504 /* head of congruence class or not in any class */
505 if (node_set == node_idx)
508 if (!arch_irn_consider_in_reg_alloc(cls, node))
511 ir_node *head = get_idx_irn(irg, node_set);
512 allocation_info_t *head_info = get_allocation_info(head);
513 allocation_info_t *info = get_allocation_info(node);
515 memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
518 static void combine_congruence_classes(void)
520 size_t n = get_irg_last_idx(irg);
521 congruence_classes = XMALLOCN(int, n);
522 uf_init(congruence_classes, n);
524 /* create congruence classes */
525 irg_block_walk_graph(irg, create_congruence_class, NULL, NULL);
526 /* merge preferences */
527 irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
528 free(congruence_classes);
534 * Assign register reg to the given node.
536 * @param node the node
537 * @param reg the register
539 static void use_reg(ir_node *node, const arch_register_t *reg, unsigned width)
541 unsigned r = arch_register_get_index(reg);
542 for (unsigned r0 = r; r0 < r + width; ++r0)
543 assignments[r0] = node;
544 arch_set_irn_register(node, reg);
547 static void free_reg_of_value(ir_node *node)
549 if (!arch_irn_consider_in_reg_alloc(cls, node))
552 const arch_register_t *reg = arch_get_irn_register(node);
553 const arch_register_req_t *req = arch_get_irn_register_req(node);
554 unsigned r = arch_register_get_index(reg);
555 /* assignment->value may be NULL if a value is used at 2 inputs
556 * so it gets freed twice. */
557 for (unsigned r0 = r; r0 < r + req->width; ++r0) {
558 assert(assignments[r0] == node || assignments[r0] == NULL);
559 assignments[r0] = NULL;
564 * Compare two register preferences in decreasing order.
566 static int compare_reg_pref(const void *e1, const void *e2)
568 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
569 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
570 if (rp1->pref < rp2->pref)
572 if (rp1->pref > rp2->pref)
577 static void fill_sort_candidates(reg_pref_t *regprefs,
578 const allocation_info_t *info)
580 for (unsigned r = 0; r < n_regs; ++r) {
581 float pref = info->prefs[r];
583 regprefs[r].pref = pref;
585 /* TODO: use a stable sort here to avoid unnecessary register jumping */
586 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
589 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
590 float pref, float pref_delta,
591 unsigned *forbidden_regs, int recursion)
595 allocation_info_t *info = get_allocation_info(to_split);
598 /* stupid hack: don't optimisticallt split don't spill nodes...
599 * (so we don't split away the values produced because of
600 * must_be_different constraints) */
601 ir_node *original_insn = skip_Proj(info->original_value);
602 if (arch_get_irn_flags(original_insn) & arch_irn_flags_dont_spill)
605 const arch_register_t *from_reg = arch_get_irn_register(to_split);
606 unsigned from_r = arch_register_get_index(from_reg);
607 ir_node *block = get_nodes_block(before);
608 float split_threshold = (float)get_block_execfreq(block) * SPLIT_DELTA;
610 if (pref_delta < split_threshold*0.5)
613 /* find the best free position where we could move to */
614 reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
615 fill_sort_candidates(prefs, info);
617 for (i = 0; i < n_regs; ++i) {
618 /* we need a normal register which is not an output register
619 an different from the current register of to_split */
621 if (!rbitset_is_set(normal_regs, r))
623 if (rbitset_is_set(forbidden_regs, r))
628 /* is the split worth it? */
629 delta = pref_delta + prefs[i].pref;
630 if (delta < split_threshold) {
631 DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
632 to_split, recursion, delta));
636 /* if the register is free then we can do the split */
637 if (assignments[r] == NULL)
640 /* otherwise we might try recursively calling optimistic_split */
641 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
644 float apref = prefs[i].pref;
645 float apref_delta = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
646 apref_delta += pref_delta - split_threshold;
648 /* our source register isn't a useful destination for recursive
650 bool old_source_state = rbitset_is_set(forbidden_regs, from_r);
651 rbitset_set(forbidden_regs, from_r);
652 /* try recursive split */
653 bool res = try_optimistic_split(assignments[r], before, apref,
654 apref_delta, forbidden_regs, recursion+1);
655 /* restore our destination */
656 if (old_source_state) {
657 rbitset_set(forbidden_regs, from_r);
659 rbitset_clear(forbidden_regs, from_r);
668 const arch_register_t *reg = arch_register_for_index(cls, r);
669 ir_node *copy = be_new_Copy(block, to_split);
671 mark_as_copy_of(copy, to_split);
672 /* hacky, but correct here */
673 if (assignments[arch_register_get_index(from_reg)] == to_split)
674 free_reg_of_value(to_split);
675 use_reg(copy, reg, width);
676 sched_add_before(before, copy);
679 "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
680 copy, to_split, from_reg->name, reg->name, before, delta, recursion));
685 * Determine and assign a register for node @p node
687 static void assign_reg(const ir_node *block, ir_node *node,
688 unsigned *forbidden_regs)
690 assert(!is_Phi(node));
691 /* preassigned register? */
692 const arch_register_t *final_reg = arch_get_irn_register(node);
693 const arch_register_req_t *req = arch_get_irn_register_req(node);
694 unsigned width = req->width;
695 if (final_reg != NULL) {
696 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, final_reg->name));
697 use_reg(node, final_reg, width);
701 /* ignore reqs must be preassigned */
702 assert (! (req->type & arch_register_req_type_ignore));
704 /* give should_be_same boni */
705 allocation_info_t *info = get_allocation_info(node);
706 ir_node *in_node = skip_Proj(node);
707 if (req->type & arch_register_req_type_should_be_same) {
708 float weight = (float)get_block_execfreq(block);
709 int arity = get_irn_arity(in_node);
711 assert(arity <= (int) sizeof(req->other_same) * 8);
712 for (int i = 0; i < arity; ++i) {
713 if (!rbitset_is_set(&req->other_same, i))
716 ir_node *in = get_irn_n(in_node, i);
717 const arch_register_t *reg = arch_get_irn_register(in);
718 unsigned reg_index = arch_register_get_index(reg);
720 /* if the value didn't die here then we should not propagate the
721 * should_be_same info */
722 if (assignments[reg_index] == in)
725 info->prefs[reg_index] += weight * AFF_SHOULD_BE_SAME;
729 /* create list of register candidates and sort by their preference */
730 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
731 reg_pref_t *reg_prefs = ALLOCAN(reg_pref_t, n_regs);
732 fill_sort_candidates(reg_prefs, info);
733 for (unsigned r = 0; r < n_regs; ++r) {
734 unsigned num = reg_prefs[r].num;
735 if (!rbitset_is_set(normal_regs, num))
737 const arch_register_t *reg = arch_register_for_index(cls, num);
738 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[r].pref));
740 DB((dbg, LEVEL_2, "\n"));
742 const unsigned *allowed_regs = normal_regs;
743 if (req->type & arch_register_req_type_limited) {
744 allowed_regs = req->limited;
747 unsigned final_reg_index = 0;
749 for (r = 0; r < n_regs; ++r) {
750 final_reg_index = reg_prefs[r].num;
751 if (!rbitset_is_set(allowed_regs, final_reg_index))
753 /* alignment constraint? */
755 if ((req->type & arch_register_req_type_aligned)
756 && (final_reg_index % width) != 0)
759 for (unsigned r0 = r+1; r0 < r+width; ++r0) {
760 if (assignments[r0] != NULL)
763 /* TODO: attempt optimistic split here */
768 if (assignments[final_reg_index] == NULL)
770 float pref = reg_prefs[r].pref;
771 float delta = r+1 < n_regs ? pref - reg_prefs[r+1].pref : 0;
772 ir_node *before = skip_Proj(node);
774 = try_optimistic_split(assignments[final_reg_index], before, pref,
775 delta, forbidden_regs, 0);
780 /* the common reason to hit this panic is when 1 of your nodes is not
781 * register pressure faithful */
782 panic("No register left for %+F\n", node);
785 final_reg = arch_register_for_index(cls, final_reg_index);
786 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, final_reg->name));
787 use_reg(node, final_reg, width);
791 * Add an permutation in front of a node and change the assignments
792 * due to this permutation.
794 * To understand this imagine a permutation like this:
804 * First we count how many destinations a single value has. At the same time
805 * we can be sure that each destination register has at most 1 source register
806 * (it can have 0 which means we don't care what value is in it).
807 * We ignore all fulfilled permuations (like 7->7)
808 * In a first pass we create as much copy instructions as possible as they
809 * are generally cheaper than exchanges. We do this by counting into how many
810 * destinations a register has to be copied (in the example it's 2 for register
811 * 3, or 1 for the registers 1,2,4 and 7).
812 * We can then create a copy into every destination register when the usecount
813 * of that register is 0 (= noone else needs the value in the register).
815 * After this step we should only have cycles left. We implement a cyclic
816 * permutation of n registers with n-1 transpositions.
818 * @param live_nodes the set of live nodes, updated due to live range split
819 * @param before the node before we add the permutation
820 * @param permutation the permutation array indices are the destination
821 * registers, the values in the array are the source
824 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
825 unsigned *permutation)
827 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
829 /* determine how often each source register needs to be read */
830 for (unsigned r = 0; r < n_regs; ++r) {
831 unsigned old_reg = permutation[r];
834 value = assignments[old_reg];
836 /* nothing to do here, reg is not live. Mark it as fixpoint
837 * so we ignore it in the next steps */
845 ir_node *block = get_nodes_block(before);
847 /* step1: create copies where immediately possible */
848 for (unsigned r = 0; r < n_regs; /* empty */) {
849 unsigned old_r = permutation[r];
851 /* - no need to do anything for fixed points.
852 - we can't copy if the value in the dest reg is still needed */
853 if (old_r == r || n_used[r] > 0) {
859 ir_node *src = assignments[old_r];
860 ir_node *copy = be_new_Copy(block, src);
861 sched_add_before(before, copy);
862 const arch_register_t *reg = arch_register_for_index(cls, r);
863 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
864 copy, src, before, reg->name));
865 mark_as_copy_of(copy, src);
866 unsigned width = 1; /* TODO */
867 use_reg(copy, reg, width);
869 if (live_nodes != NULL) {
870 ir_nodeset_insert(live_nodes, copy);
873 /* old register has 1 user less, permutation is resolved */
874 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
877 assert(n_used[old_r] > 0);
879 if (n_used[old_r] == 0) {
880 if (live_nodes != NULL) {
881 ir_nodeset_remove(live_nodes, src);
883 free_reg_of_value(src);
886 /* advance or jump back (if this copy enabled another copy) */
887 if (old_r < r && n_used[old_r] == 0) {
894 /* at this point we only have "cycles" left which we have to resolve with
896 * TODO: if we have free registers left, then we should really use copy
897 * instructions for any cycle longer than 2 registers...
898 * (this is probably architecture dependent, there might be archs where
899 * copies are preferable even for 2-cycles) */
901 /* create perms with the rest */
902 for (unsigned r = 0; r < n_regs; /* empty */) {
903 unsigned old_r = permutation[r];
910 /* we shouldn't have copies from 1 value to multiple destinations left*/
911 assert(n_used[old_r] == 1);
913 /* exchange old_r and r2; after that old_r is a fixed point */
914 unsigned r2 = permutation[old_r];
916 ir_node *in[2] = { assignments[r2], assignments[old_r] };
917 ir_node *perm = be_new_Perm(cls, block, 2, in);
918 sched_add_before(before, perm);
919 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
920 perm, in[0], in[1], before));
922 unsigned width = 1; /* TODO */
924 ir_node *proj0 = new_r_Proj(perm, get_irn_mode(in[0]), 0);
925 mark_as_copy_of(proj0, in[0]);
926 const arch_register_t *reg0 = arch_register_for_index(cls, old_r);
927 use_reg(proj0, reg0, width);
929 ir_node *proj1 = new_r_Proj(perm, get_irn_mode(in[1]), 1);
930 mark_as_copy_of(proj1, in[1]);
931 const arch_register_t *reg1 = arch_register_for_index(cls, r2);
932 use_reg(proj1, reg1, width);
934 /* 1 value is now in the correct register */
935 permutation[old_r] = old_r;
936 /* the source of r changed to r2 */
939 /* if we have reached a fixpoint update data structures */
940 if (live_nodes != NULL) {
941 ir_nodeset_remove(live_nodes, in[0]);
942 ir_nodeset_remove(live_nodes, in[1]);
943 ir_nodeset_remove(live_nodes, proj0);
944 ir_nodeset_insert(live_nodes, proj1);
949 /* now we should only have fixpoints left */
950 for (unsigned r = 0; r < n_regs; ++r) {
951 assert(permutation[r] == r);
957 * Free regs for values last used.
959 * @param live_nodes set of live nodes, will be updated
960 * @param node the node to consider
962 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
964 allocation_info_t *info = get_allocation_info(node);
965 const unsigned *last_uses = info->last_uses;
966 int arity = get_irn_arity(node);
968 for (int i = 0; i < arity; ++i) {
969 /* check if one operand is the last use */
970 if (!rbitset_is_set(last_uses, i))
973 ir_node *op = get_irn_n(node, i);
974 free_reg_of_value(op);
975 ir_nodeset_remove(live_nodes, op);
980 * change inputs of a node to the current value (copies/perms)
982 static void rewire_inputs(ir_node *node)
984 int arity = get_irn_arity(node);
985 for (int i = 0; i < arity; ++i) {
986 ir_node *op = get_irn_n(node, i);
987 allocation_info_t *info = try_get_allocation_info(op);
992 info = get_allocation_info(info->original_value);
993 if (info->current_value != op) {
994 set_irn_n(node, i, info->current_value);
1000 * Create a bitset of registers occupied with value living through an
1003 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1005 const allocation_info_t *info = get_allocation_info(node);
1007 /* mark all used registers as potentially live-through */
1008 for (unsigned r = 0; r < n_regs; ++r) {
1009 if (assignments[r] == NULL)
1011 if (!rbitset_is_set(normal_regs, r))
1014 rbitset_set(bitset, r);
1017 /* remove registers of value dying at the instruction */
1018 int arity = get_irn_arity(node);
1019 for (int i = 0; i < arity; ++i) {
1020 if (!rbitset_is_set(info->last_uses, i))
1023 ir_node *op = get_irn_n(node, i);
1024 const arch_register_t *reg = arch_get_irn_register(op);
1025 rbitset_clear(bitset, arch_register_get_index(reg));
1029 static void solve_lpp(ir_nodeset_t *live_nodes, ir_node *node,
1030 unsigned *forbidden_regs, unsigned *live_through_regs)
1032 unsigned *forbidden_edges = rbitset_malloc(n_regs * n_regs);
1033 int *lpp_vars = XMALLOCNZ(int, n_regs*n_regs);
1035 lpp_t *lpp = lpp_new("prefalloc", lpp_minimize);
1036 //lpp_set_time_limit(lpp, 20);
1037 lpp_set_log(lpp, stdout);
1039 /** mark some edges as forbidden */
1040 int arity = get_irn_arity(node);
1041 for (int i = 0; i < arity; ++i) {
1042 ir_node *op = get_irn_n(node, i);
1043 if (!arch_irn_consider_in_reg_alloc(cls, op))
1046 const arch_register_req_t *req = arch_get_irn_register_req_in(node, i);
1047 if (!(req->type & arch_register_req_type_limited))
1050 const unsigned *limited = req->limited;
1051 const arch_register_t *reg = arch_get_irn_register(op);
1052 unsigned current_reg = arch_register_get_index(reg);
1053 for (unsigned r = 0; r < n_regs; ++r) {
1054 if (rbitset_is_set(limited, r))
1057 rbitset_set(forbidden_edges, current_reg*n_regs + r);
1061 /* add all combinations, except for not allowed ones */
1062 for (unsigned l = 0; l < n_regs; ++l) {
1063 if (!rbitset_is_set(normal_regs, l)) {
1065 snprintf(name, sizeof(name), "%u_to_%u", l, l);
1066 lpp_vars[l*n_regs+l] = lpp_add_var(lpp, name, lpp_binary, 1);
1070 for (unsigned r = 0; r < n_regs; ++r) {
1071 if (!rbitset_is_set(normal_regs, r))
1073 if (rbitset_is_set(forbidden_edges, l*n_regs + r))
1075 /* livethrough values may not use constrained output registers */
1076 if (rbitset_is_set(live_through_regs, l)
1077 && rbitset_is_set(forbidden_regs, r))
1081 snprintf(name, sizeof(name), "%u_to_%u", l, r);
1083 double costs = l==r ? 9 : 8;
1084 lpp_vars[l*n_regs+r]
1085 = lpp_add_var(lpp, name, lpp_binary, costs);
1086 assert(lpp_vars[l*n_regs+r] > 0);
1089 /* add constraints */
1090 for (unsigned l = 0; l < n_regs; ++l) {
1091 /* only 1 destination per register */
1092 int constraint = -1;
1093 for (unsigned r = 0; r < n_regs; ++r) {
1094 int var = lpp_vars[l*n_regs+r];
1097 if (constraint < 0) {
1099 snprintf(name, sizeof(name), "%u_to_dest", l);
1100 constraint = lpp_add_cst(lpp, name, lpp_equal, 1);
1102 lpp_set_factor_fast(lpp, constraint, var, 1);
1104 /* each destination used by at most 1 value */
1106 for (unsigned r = 0; r < n_regs; ++r) {
1107 int var = lpp_vars[r*n_regs+l];
1110 if (constraint < 0) {
1112 snprintf(name, sizeof(name), "one_to_%u", l);
1113 constraint = lpp_add_cst(lpp, name, lpp_less_equal, 1);
1115 lpp_set_factor_fast(lpp, constraint, var, 1);
1119 lpp_dump_plain(lpp, fopen("lppdump.txt", "w"));
1122 lpp_solve(lpp, be_options.ilp_server, be_options.ilp_solver);
1123 if (!lpp_is_sol_valid(lpp))
1124 panic("ilp solution not valid!");
1126 unsigned *assignment = ALLOCAN(unsigned, n_regs);
1127 for (unsigned l = 0; l < n_regs; ++l) {
1128 unsigned dest_reg = (unsigned)-1;
1129 for (unsigned r = 0; r < n_regs; ++r) {
1130 int var = lpp_vars[l*n_regs+r];
1133 double val = lpp_get_var_sol(lpp, var);
1135 assert(dest_reg == (unsigned)-1);
1139 assert(dest_reg != (unsigned)-1);
1140 assignment[dest_reg] = l;
1143 fprintf(stderr, "Assignment: ");
1144 for (unsigned l = 0; l < n_regs; ++l) {
1145 fprintf(stderr, "%u ", assignment[l]);
1147 fprintf(stderr, "\n");
1149 permute_values(live_nodes, node, assignment);
1153 static bool is_aligned(unsigned num, unsigned alignment)
1155 unsigned mask = alignment-1;
1156 assert(is_po2(alignment));
1157 return (num&mask) == 0;
1161 * Enforce constraints at a node by live range splits.
1163 * @param live_nodes the set of live nodes, might be changed
1164 * @param node the current node
1166 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1167 unsigned *forbidden_regs)
1169 /* see if any use constraints are not met and whether double-width
1170 * values are involved */
1171 bool double_width = false;
1173 int arity = get_irn_arity(node);
1174 for (int i = 0; i < arity; ++i) {
1175 ir_node *op = get_irn_n(node, i);
1176 if (!arch_irn_consider_in_reg_alloc(cls, op))
1179 /* are there any limitations for the i'th operand? */
1180 const arch_register_req_t *req = arch_get_irn_register_req_in(node, i);
1182 double_width = true;
1183 const arch_register_t *reg = arch_get_irn_register(op);
1184 unsigned reg_index = arch_register_get_index(reg);
1185 if (req->type & arch_register_req_type_aligned) {
1186 if (!is_aligned(reg_index, req->width)) {
1191 if (!(req->type & arch_register_req_type_limited))
1194 const unsigned *limited = req->limited;
1195 if (!rbitset_is_set(limited, reg_index)) {
1196 /* found an assignment outside the limited set */
1202 /* is any of the live-throughs using a constrained output register? */
1204 unsigned *live_through_regs = NULL;
1205 be_foreach_definition(node, cls, value,
1206 if (req_->width > 1)
1207 double_width = true;
1208 if (! (req_->type & arch_register_req_type_limited))
1210 if (live_through_regs == NULL) {
1211 rbitset_alloca(live_through_regs, n_regs);
1212 determine_live_through_regs(live_through_regs, node);
1214 rbitset_or(forbidden_regs, req_->limited, n_regs);
1215 if (rbitsets_have_common(req_->limited, live_through_regs, n_regs))
1222 /* create these arrays if we haven't yet */
1223 if (live_through_regs == NULL) {
1224 rbitset_alloca(live_through_regs, n_regs);
1228 /* only the ILP variant can solve this yet */
1229 solve_lpp(live_nodes, node, forbidden_regs, live_through_regs);
1233 /* at this point we have to construct a bipartite matching problem to see
1234 * which values should go to which registers
1235 * Note: We're building the matrix in "reverse" - source registers are
1236 * right, destinations left because this will produce the solution
1237 * in the format required for permute_values.
1239 hungarian_problem_t *bp
1240 = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1242 /* add all combinations, then remove not allowed ones */
1243 for (unsigned l = 0; l < n_regs; ++l) {
1244 if (!rbitset_is_set(normal_regs, l)) {
1245 hungarian_add(bp, l, l, 1);
1249 for (unsigned r = 0; r < n_regs; ++r) {
1250 if (!rbitset_is_set(normal_regs, r))
1252 /* livethrough values may not use constrainted output registers */
1253 if (rbitset_is_set(live_through_regs, l)
1254 && rbitset_is_set(forbidden_regs, r))
1257 hungarian_add(bp, r, l, l == r ? 9 : 8);
1261 for (int i = 0; i < arity; ++i) {
1262 ir_node *op = get_irn_n(node, i);
1263 if (!arch_irn_consider_in_reg_alloc(cls, op))
1266 const arch_register_req_t *req = arch_get_irn_register_req_in(node, i);
1267 if (!(req->type & arch_register_req_type_limited))
1270 const unsigned *limited = req->limited;
1271 const arch_register_t *reg = arch_get_irn_register(op);
1272 unsigned current_reg = arch_register_get_index(reg);
1273 for (unsigned r = 0; r < n_regs; ++r) {
1274 if (rbitset_is_set(limited, r))
1276 hungarian_remove(bp, r, current_reg);
1280 //hungarian_print_cost_matrix(bp, 1);
1281 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1283 unsigned *assignment = ALLOCAN(unsigned, n_regs);
1284 int res = hungarian_solve(bp, assignment, NULL, 0);
1288 fprintf(stderr, "Swap result:");
1289 for (i = 0; i < (int) n_regs; ++i) {
1290 fprintf(stderr, " %d", assignment[i]);
1292 fprintf(stderr, "\n");
1297 permute_values(live_nodes, node, assignment);
1300 /** test whether a node @p n is a copy of the value of node @p of */
1301 static bool is_copy_of(ir_node *value, ir_node *test_value)
1303 if (value == test_value)
1306 allocation_info_t *info = get_allocation_info(value);
1307 allocation_info_t *test_info = get_allocation_info(test_value);
1308 return test_info->original_value == info->original_value;
1312 * find a value in the end-assignment of a basic block
1313 * @returns the index into the assignment array if found
1316 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1318 ir_node **end_assignments = info->assignments;
1319 for (unsigned r = 0; r < n_regs; ++r) {
1320 ir_node *a_value = end_assignments[r];
1322 if (a_value == NULL)
1324 if (is_copy_of(a_value, value))
1332 * Create the necessary permutations at the end of a basic block to fullfill
1333 * the register assignment for phi-nodes in the next block
1335 static void add_phi_permutations(ir_node *block, int p)
1337 ir_node *pred = get_Block_cfgpred_block(block, p);
1338 block_info_t *pred_info = get_block_info(pred);
1340 /* predecessor not processed yet? nothing to do */
1341 if (!pred_info->processed)
1344 unsigned *permutation = ALLOCAN(unsigned, n_regs);
1345 for (unsigned r = 0; r < n_regs; ++r) {
1349 /* check phi nodes */
1350 bool need_permutation = false;
1351 ir_node *phi = sched_first(block);
1352 for ( ; is_Phi(phi); phi = sched_next(phi)) {
1353 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1356 ir_node *phi_pred = get_Phi_pred(phi, p);
1357 int a = find_value_in_block_info(pred_info, phi_pred);
1360 const arch_register_t *reg = arch_get_irn_register(phi);
1361 int regn = arch_register_get_index(reg);
1362 /* same register? nothing to do */
1366 ir_node *op = pred_info->assignments[a];
1367 const arch_register_t *op_reg = arch_get_irn_register(op);
1368 /* virtual or joker registers are ok too */
1369 if ((op_reg->type & arch_register_type_joker)
1370 || (op_reg->type & arch_register_type_virtual))
1373 permutation[regn] = a;
1374 need_permutation = true;
1377 if (need_permutation) {
1378 /* permute values at end of predecessor */
1379 ir_node **old_assignments = assignments;
1380 assignments = pred_info->assignments;
1381 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1383 assignments = old_assignments;
1386 /* change phi nodes to use the copied values */
1387 phi = sched_first(block);
1388 for ( ; is_Phi(phi); phi = sched_next(phi)) {
1389 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1392 /* we have permuted all values into the correct registers so we can
1393 simply query which value occupies the phis register in the
1395 int a = arch_register_get_index(arch_get_irn_register(phi));
1396 ir_node *op = pred_info->assignments[a];
1397 set_Phi_pred(phi, p, op);
1402 * Set preferences for a phis register based on the registers used on the
1405 static void adapt_phi_prefs(ir_node *phi)
1407 ir_node *block = get_nodes_block(phi);
1408 allocation_info_t *info = get_allocation_info(phi);
1410 int arity = get_irn_arity(phi);
1411 for (int i = 0; i < arity; ++i) {
1412 ir_node *op = get_irn_n(phi, i);
1413 const arch_register_t *reg = arch_get_irn_register(op);
1417 /* we only give the bonus if the predecessor already has registers
1418 * assigned, otherwise we only see a dummy value
1419 * and any conclusions about its register are useless */
1420 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1421 block_info_t *pred_block_info = get_block_info(pred_block);
1422 if (!pred_block_info->processed)
1425 /* give bonus for already assigned register */
1426 float weight = (float)get_block_execfreq(pred_block);
1427 unsigned r = arch_register_get_index(reg);
1428 info->prefs[r] += weight * AFF_PHI;
1433 * After a phi has been assigned a register propagate preference inputs
1434 * to the phi inputs.
1436 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1438 ir_node *block = get_nodes_block(phi);
1440 int arity = get_irn_arity(phi);
1441 for (int i = 0; i < arity; ++i) {
1442 ir_node *op = get_Phi_pred(phi, i);
1443 allocation_info_t *info = get_allocation_info(op);
1444 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1446 = (float)get_block_execfreq(pred_block) * AFF_PHI;
1448 if (info->prefs[assigned_r] >= weight)
1451 /* promote the prefered register */
1452 for (unsigned r = 0; r < n_regs; ++r) {
1453 if (info->prefs[r] > -weight) {
1454 info->prefs[r] = -weight;
1457 info->prefs[assigned_r] = weight;
1460 propagate_phi_register(op, assigned_r);
1464 static void assign_phi_registers(ir_node *block)
1466 /* count phi nodes */
1468 sched_foreach(block, node) {
1471 if (!arch_irn_consider_in_reg_alloc(cls, node))
1479 /* build a bipartite matching problem for all phi nodes */
1480 hungarian_problem_t *bp
1481 = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1483 sched_foreach(block, node) {
1486 if (!arch_irn_consider_in_reg_alloc(cls, node))
1489 /* give boni for predecessor colorings */
1490 adapt_phi_prefs(node);
1491 /* add stuff to bipartite problem */
1492 allocation_info_t *info = get_allocation_info(node);
1493 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1494 for (unsigned r = 0; r < n_regs; ++r) {
1495 if (!rbitset_is_set(normal_regs, r))
1498 float costs = info->prefs[r];
1499 costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1502 hungarian_add(bp, n, r, (int)costs);
1503 DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1506 DB((dbg, LEVEL_3, "\n"));
1510 //hungarian_print_cost_matrix(bp, 7);
1511 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1513 unsigned *assignment = ALLOCAN(unsigned, n_regs);
1514 int res = hungarian_solve(bp, assignment, NULL, 0);
1519 sched_foreach(block, node) {
1522 if (!arch_irn_consider_in_reg_alloc(cls, node))
1524 const arch_register_req_t *req
1525 = arch_get_irn_register_req(node);
1527 unsigned r = assignment[n++];
1528 assert(rbitset_is_set(normal_regs, r));
1529 const arch_register_t *reg = arch_register_for_index(cls, r);
1530 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1531 use_reg(node, reg, req->width);
1533 /* adapt preferences for phi inputs */
1534 propagate_phi_register(node, r);
1538 static arch_register_req_t *allocate_reg_req(ir_graph *irg)
1540 struct obstack *obst = be_get_be_obst(irg);
1541 arch_register_req_t *req = OALLOCZ(obst, arch_register_req_t);
1546 * Walker: assign registers to all nodes of a block that
1547 * need registers from the currently considered register class.
1549 static void allocate_coalesce_block(ir_node *block, void *data)
1552 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1554 /* clear assignments */
1555 block_info_t *block_info = get_block_info(block);
1556 assignments = block_info->assignments;
1558 ir_nodeset_t live_nodes;
1559 ir_nodeset_init(&live_nodes);
1561 /* gather regalloc infos of predecessor blocks */
1562 int n_preds = get_Block_n_cfgpreds(block);
1563 block_info_t **pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1564 for (int i = 0; i < n_preds; ++i) {
1565 ir_node *pred = get_Block_cfgpred_block(block, i);
1566 block_info_t *pred_info = get_block_info(pred);
1567 pred_block_infos[i] = pred_info;
1570 ir_node **phi_ins = ALLOCAN(ir_node*, n_preds);
1572 /* collect live-in nodes and preassigned values */
1573 be_lv_foreach(lv, block, be_lv_state_in, node) {
1574 const arch_register_req_t *req = arch_get_irn_register_req(node);
1575 if (req->cls != cls)
1578 if (req->type & arch_register_req_type_ignore) {
1579 allocation_info_t *info = get_allocation_info(node);
1580 info->current_value = node;
1582 const arch_register_t *reg = arch_get_irn_register(node);
1583 assert(reg != NULL); /* ignore values must be preassigned */
1584 use_reg(node, reg, req->width);
1588 /* check all predecessors for this value, if it is not everywhere the
1589 same or unknown then we have to construct a phi
1590 (we collect the potential phi inputs here) */
1591 bool need_phi = false;
1592 for (int p = 0; p < n_preds; ++p) {
1593 block_info_t *pred_info = pred_block_infos[p];
1595 if (!pred_info->processed) {
1596 /* use node for now, it will get fixed later */
1600 int a = find_value_in_block_info(pred_info, node);
1602 /* must live out of predecessor */
1604 phi_ins[p] = pred_info->assignments[a];
1605 /* different value from last time? then we need a phi */
1606 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1613 ir_mode *mode = get_irn_mode(node);
1614 const arch_register_req_t *phi_req = cls->class_req;
1615 if (req->width > 1) {
1616 arch_register_req_t *new_req = allocate_reg_req(irg);
1618 new_req->type = req->type & arch_register_req_type_aligned;
1619 new_req->width = req->width;
1622 ir_node *phi = be_new_Phi(block, n_preds, phi_ins, mode,
1625 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1626 #ifdef DEBUG_libfirm
1627 for (int pi = 0; pi < n_preds; ++pi) {
1628 DB((dbg, LEVEL_3, " %+F", phi_ins[pi]));
1630 DB((dbg, LEVEL_3, "\n"));
1632 mark_as_copy_of(phi, node);
1633 sched_add_after(block, phi);
1637 allocation_info_t *info = get_allocation_info(node);
1638 info->current_value = phi_ins[0];
1640 /* Grab 1 of the inputs we constructed (might not be the same as
1641 * "node" as we could see the same copy of the value in all
1646 /* if the node already has a register assigned use it */
1647 const arch_register_t *reg = arch_get_irn_register(node);
1649 use_reg(node, reg, req->width);
1652 /* remember that this node is live at the beginning of the block */
1653 ir_nodeset_insert(&live_nodes, node);
1656 unsigned *forbidden_regs; /**< collects registers which must
1657 not be used for optimistic splits */
1658 rbitset_alloca(forbidden_regs, n_regs);
1660 /* handle phis... */
1661 assign_phi_registers(block);
1663 /* all live-ins must have a register */
1665 foreach_ir_nodeset(&live_nodes, node, iter) {
1666 const arch_register_t *reg = arch_get_irn_register(node);
1667 assert(reg != NULL);
1671 /* assign instructions in the block */
1672 sched_foreach(block, node) {
1673 /* phis are already assigned */
1677 rewire_inputs(node);
1679 /* enforce use constraints */
1680 rbitset_clear_all(forbidden_regs, n_regs);
1681 enforce_constraints(&live_nodes, node, forbidden_regs);
1683 rewire_inputs(node);
1685 /* we may not use registers used for inputs for optimistic splits */
1686 int arity = get_irn_arity(node);
1687 for (int i = 0; i < arity; ++i) {
1688 ir_node *op = get_irn_n(node, i);
1689 if (!arch_irn_consider_in_reg_alloc(cls, op))
1692 const arch_register_t *reg = arch_get_irn_register(op);
1693 rbitset_set(forbidden_regs, arch_register_get_index(reg));
1696 /* free registers of values last used at this instruction */
1697 free_last_uses(&live_nodes, node);
1699 /* assign output registers */
1701 be_foreach_definition_(node, cls, value,
1702 assign_reg(block, value, forbidden_regs);
1706 ir_nodeset_destroy(&live_nodes);
1709 block_info->processed = true;
1711 /* permute values at end of predecessor blocks in case of phi-nodes */
1713 for (int p = 0; p < n_preds; ++p) {
1714 add_phi_permutations(block, p);
1718 /* if we have exactly 1 successor then we might be able to produce phi
1720 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1721 const ir_edge_t *edge
1722 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1723 ir_node *succ = get_edge_src_irn(edge);
1724 int p = get_edge_src_pos(edge);
1725 block_info_t *succ_info = get_block_info(succ);
1727 if (succ_info->processed) {
1728 add_phi_permutations(succ, p);
1733 typedef struct block_costs_t block_costs_t;
1734 struct block_costs_t {
1735 float costs; /**< costs of the block */
1736 int dfs_num; /**< depth first search number (to detect backedges) */
1739 static int cmp_block_costs(const void *d1, const void *d2)
1741 const ir_node * const *block1 = (const ir_node**)d1;
1742 const ir_node * const *block2 = (const ir_node**)d2;
1743 const block_costs_t *info1 = (const block_costs_t*)get_irn_link(*block1);
1744 const block_costs_t *info2 = (const block_costs_t*)get_irn_link(*block2);
1745 return QSORT_CMP(info2->costs, info1->costs);
1748 static void determine_block_order(void)
1750 ir_node **blocklist = be_get_cfgpostorder(irg);
1751 size_t n_blocks = ARR_LEN(blocklist);
1753 pdeq *worklist = new_pdeq();
1754 ir_node **order = XMALLOCN(ir_node*, n_blocks);
1757 /* clear block links... */
1758 for (size_t p = 0; p < n_blocks; ++p) {
1759 ir_node *block = blocklist[p];
1760 set_irn_link(block, NULL);
1763 /* walk blocks in reverse postorder, the costs for each block are the
1764 * sum of the costs of its predecessors (excluding the costs on backedges
1765 * which we can't determine) */
1766 for (size_t p = n_blocks; p > 0;) {
1767 block_costs_t *cost_info;
1768 ir_node *block = blocklist[--p];
1770 float execfreq = (float)get_block_execfreq(block);
1771 float costs = execfreq;
1772 int n_cfgpreds = get_Block_n_cfgpreds(block);
1773 for (int p2 = 0; p2 < n_cfgpreds; ++p2) {
1774 ir_node *pred_block = get_Block_cfgpred_block(block, p2);
1775 block_costs_t *pred_costs = (block_costs_t*)get_irn_link(pred_block);
1776 /* we don't have any info for backedges */
1777 if (pred_costs == NULL)
1779 costs += pred_costs->costs;
1782 cost_info = OALLOCZ(&obst, block_costs_t);
1783 cost_info->costs = costs;
1784 cost_info->dfs_num = dfs_num++;
1785 set_irn_link(block, cost_info);
1788 /* sort array by block costs */
1789 qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1791 ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1792 inc_irg_block_visited(irg);
1794 for (size_t p = 0; p < n_blocks; ++p) {
1795 ir_node *block = blocklist[p];
1796 if (Block_block_visited(block))
1799 /* continually add predecessors with highest costs to worklist
1800 * (without using backedges) */
1802 block_costs_t *info = (block_costs_t*)get_irn_link(block);
1803 ir_node *best_pred = NULL;
1804 float best_costs = -1;
1805 int n_cfgpred = get_Block_n_cfgpreds(block);
1807 pdeq_putr(worklist, block);
1808 mark_Block_block_visited(block);
1809 for (int i = 0; i < n_cfgpred; ++i) {
1810 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1811 block_costs_t *pred_info = (block_costs_t*)get_irn_link(pred_block);
1813 /* ignore backedges */
1814 if (pred_info->dfs_num > info->dfs_num)
1817 if (info->costs > best_costs) {
1818 best_costs = info->costs;
1819 best_pred = pred_block;
1823 } while (block != NULL && !Block_block_visited(block));
1825 /* now put all nodes in the worklist in our final order */
1826 while (!pdeq_empty(worklist)) {
1827 ir_node *pblock = (ir_node*)pdeq_getr(worklist);
1828 assert(order_p < n_blocks);
1829 order[order_p++] = pblock;
1832 assert(order_p == n_blocks);
1835 ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1837 DEL_ARR_F(blocklist);
1839 obstack_free(&obst, NULL);
1840 obstack_init(&obst);
1842 block_order = order;
1843 n_block_order = n_blocks;
1846 static void free_block_order(void)
1852 * Run the register allocator for the current register class.
1854 static void be_pref_alloc_cls(void)
1856 be_assure_live_sets(irg);
1857 lv = be_get_irg_liveness(irg);
1859 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1861 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1863 be_clear_links(irg);
1865 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1866 combine_congruence_classes();
1868 for (size_t i = 0; i < n_block_order; ++i) {
1869 ir_node *block = block_order[i];
1870 allocate_coalesce_block(block, NULL);
1873 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1876 static void dump(int mask, ir_graph *irg, const char *suffix)
1878 if (be_options.dump_flags & mask)
1879 dump_ir_graph(irg, suffix);
1883 * Run the spiller on the current graph.
1885 static void spill(void)
1887 /* make sure all nodes show their real register pressure */
1888 be_timer_push(T_RA_CONSTR);
1889 be_pre_spill_prepare_constr(irg, cls);
1890 be_timer_pop(T_RA_CONSTR);
1892 dump(DUMP_RA, irg, "spillprepare");
1895 be_timer_push(T_RA_SPILL);
1896 be_do_spill(irg, cls);
1897 be_timer_pop(T_RA_SPILL);
1899 be_timer_push(T_RA_SPILL_APPLY);
1900 check_for_memory_operands(irg);
1901 be_timer_pop(T_RA_SPILL_APPLY);
1903 dump(DUMP_RA, irg, "spill");
1907 * The pref register allocator for a whole procedure.
1909 static void be_pref_alloc(ir_graph *new_irg)
1911 obstack_init(&obst);
1915 /* determine a good coloring order */
1916 determine_block_order();
1918 const arch_env_t *arch_env = be_get_irg_arch_env(new_irg);
1919 int n_cls = arch_env->n_register_classes;
1920 for (int c = 0; c < n_cls; ++c) {
1921 cls = &arch_env->register_classes[c];
1922 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1925 stat_ev_ctx_push_str("regcls", cls->name);
1927 n_regs = arch_register_class_n_regs(cls);
1928 normal_regs = rbitset_malloc(n_regs);
1929 be_set_allocatable_regs(irg, cls, normal_regs);
1933 /* verify schedule and register pressure */
1934 be_timer_push(T_VERIFY);
1935 if (be_options.verify_option == BE_VERIFY_WARN) {
1936 be_verify_schedule(irg);
1937 be_verify_register_pressure(irg, cls);
1938 } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
1939 assert(be_verify_schedule(irg) && "Schedule verification failed");
1940 assert(be_verify_register_pressure(irg, cls)
1941 && "Register pressure verification failed");
1943 be_timer_pop(T_VERIFY);
1945 be_timer_push(T_RA_COLOR);
1946 be_pref_alloc_cls();
1947 be_timer_pop(T_RA_COLOR);
1949 /* we most probably constructed new Phis so liveness info is invalid
1951 be_invalidate_live_sets(irg);
1954 stat_ev_ctx_pop("regcls");
1959 be_timer_push(T_RA_SPILL_APPLY);
1960 be_abi_fix_stack_nodes(irg);
1961 be_timer_pop(T_RA_SPILL_APPLY);
1963 be_timer_push(T_VERIFY);
1964 if (be_options.verify_option == BE_VERIFY_WARN) {
1965 be_verify_register_allocation(irg);
1966 } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
1967 assert(be_verify_register_allocation(irg)
1968 && "Register allocation invalid");
1970 be_timer_pop(T_VERIFY);
1972 obstack_free(&obst, NULL);
1975 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_pref_alloc)
1976 void be_init_pref_alloc(void)
1978 static be_ra_t be_ra_pref = { be_pref_alloc };
1979 be_register_allocator("pref", &be_ra_pref);
1980 FIRM_DBG_REGISTER(dbg, "firm.be.prefalloc");