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
58 #include "iredges_t.h"
59 #include "irgraph_t.h"
64 #include "raw_bitset.h"
65 #include "unionfind.h"
67 #include "hungarian.h"
70 #include "bechordal_t.h"
79 #include "bespillutil.h"
83 #define USE_FACTOR 1.0f
84 #define DEF_FACTOR 1.0f
85 #define NEIGHBOR_FACTOR 0.2f
86 #define AFF_SHOULD_BE_SAME 0.5f
88 #define SPLIT_DELTA 1.0f
89 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
91 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
93 static struct obstack obst;
94 static be_irg_t *birg;
96 static const arch_register_class_t *cls;
97 static const arch_register_req_t *default_cls_req;
99 static const ir_exec_freq *execfreqs;
100 static unsigned n_regs;
101 static unsigned *normal_regs;
102 static int *congruence_classes;
103 static ir_node **block_order;
104 static int n_block_order;
105 static int create_preferences = true;
106 static int create_congruence_classes = true;
107 static int propagate_phi_registers = true;
109 static const lc_opt_table_entry_t options[] = {
110 LC_OPT_ENT_BOOL("prefs", "use preference based coloring", &create_preferences),
111 LC_OPT_ENT_BOOL("congruences", "create congruence classes", &create_congruence_classes),
112 LC_OPT_ENT_BOOL("prop_phi", "propagate phi registers", &propagate_phi_registers),
116 /** currently active assignments (while processing a basic block)
117 * maps registers to values(their current copies) */
118 static ir_node **assignments;
121 * allocation information: last_uses, register preferences
122 * the information is per firm-node.
124 struct allocation_info_t {
125 unsigned last_uses; /**< bitset indicating last uses (input pos) */
126 ir_node *current_value; /**< copy of the value that should be used */
127 ir_node *original_value; /**< for copies point to original value */
128 float prefs[0]; /**< register preferences */
130 typedef struct allocation_info_t allocation_info_t;
132 /** helper datastructure used when sorting register preferences */
137 typedef struct reg_pref_t reg_pref_t;
139 /** per basic-block information */
140 struct block_info_t {
141 bool processed; /**< indicate whether block is processed */
142 ir_node *assignments[0]; /**< register assignments at end of block */
144 typedef struct block_info_t block_info_t;
147 * Get the allocation info for a node.
148 * The info is allocated on the first visit of a node.
150 static allocation_info_t *get_allocation_info(ir_node *node)
152 allocation_info_t *info = get_irn_link(node);
154 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
155 info->current_value = node;
156 info->original_value = node;
157 set_irn_link(node, info);
163 static allocation_info_t *try_get_allocation_info(const ir_node *node)
165 return (allocation_info_t*) get_irn_link(node);
169 * Get allocation information for a basic block
171 static block_info_t *get_block_info(ir_node *block)
173 block_info_t *info = get_irn_link(block);
175 assert(is_Block(block));
177 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
178 set_irn_link(block, info);
185 * Get default register requirement for the current register class
187 static const arch_register_req_t *get_default_req_current_cls(void)
189 if (default_cls_req == NULL) {
190 struct obstack *obst = get_irg_obstack(irg);
191 arch_register_req_t *req = OALLOCZ(obst, arch_register_req_t);
193 req->type = arch_register_req_type_normal;
196 default_cls_req = req;
198 return default_cls_req;
202 * Link the allocation info of a node to a copy.
203 * Afterwards, both nodes uses the same allocation info.
204 * Copy must not have an allocation info assigned yet.
206 * @param copy the node that gets the allocation info assigned
207 * @param value the original node
209 static void mark_as_copy_of(ir_node *copy, ir_node *value)
212 allocation_info_t *info = get_allocation_info(value);
213 allocation_info_t *copy_info = get_allocation_info(copy);
215 /* find original value */
216 original = info->original_value;
217 if (original != value) {
218 info = get_allocation_info(original);
221 assert(info->original_value == original);
222 info->current_value = copy;
224 /* the copy should not be linked to something else yet */
225 assert(copy_info->original_value == copy);
226 copy_info->original_value = original;
228 /* copy over allocation preferences */
229 memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
233 * Calculate the penalties for every register on a node and its live neighbors.
235 * @param live_nodes the set of live nodes at the current position, may be NULL
236 * @param penalty the penalty to subtract from
237 * @param limited a raw bitset containing the limited set for the node
238 * @param node the node
240 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
241 float penalty, const unsigned* limited,
244 ir_nodeset_iterator_t iter;
247 allocation_info_t *info = get_allocation_info(node);
250 /* give penalty for all forbidden regs */
251 for (r = 0; r < n_regs; ++r) {
252 if (rbitset_is_set(limited, r))
255 info->prefs[r] -= penalty;
258 /* all other live values should get a penalty for allowed regs */
259 if (live_nodes == NULL)
262 penalty *= NEIGHBOR_FACTOR;
263 n_allowed = rbitset_popcnt(limited, n_regs);
265 /* only create a very weak penalty if multiple regs are allowed */
266 penalty = (penalty * 0.8f) / n_allowed;
268 foreach_ir_nodeset(live_nodes, neighbor, iter) {
269 allocation_info_t *neighbor_info;
271 /* TODO: if op is used on multiple inputs we might not do a
273 if (neighbor == node)
276 neighbor_info = get_allocation_info(neighbor);
277 for (r = 0; r < n_regs; ++r) {
278 if (!rbitset_is_set(limited, r))
281 neighbor_info->prefs[r] -= penalty;
287 * Calculate the preferences of a definition for the current register class.
288 * If the definition uses a limited set of registers, reduce the preferences
289 * for the limited register on the node and its neighbors.
291 * @param live_nodes the set of live nodes at the current node
292 * @param weight the weight
293 * @param node the current node
295 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
298 const arch_register_req_t *req;
300 if (get_irn_mode(node) == mode_T) {
301 const ir_edge_t *edge;
302 foreach_out_edge(node, edge) {
303 ir_node *proj = get_edge_src_irn(edge);
304 check_defs(live_nodes, weight, proj);
309 if (!arch_irn_consider_in_reg_alloc(cls, node))
312 req = arch_get_register_req_out(node);
313 if (req->type & arch_register_req_type_limited) {
314 const unsigned *limited = req->limited;
315 float penalty = weight * DEF_FACTOR;
316 give_penalties_for_limits(live_nodes, penalty, limited, node);
319 if (req->type & arch_register_req_type_should_be_same) {
320 ir_node *insn = skip_Proj(node);
321 allocation_info_t *info = get_allocation_info(node);
322 int arity = get_irn_arity(insn);
325 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
326 for (i = 0; i < arity; ++i) {
329 allocation_info_t *op_info;
331 if (!rbitset_is_set(&req->other_same, i))
334 op = get_irn_n(insn, i);
336 /* if we the value at the should_be_same input doesn't die at the
337 * node, then it is no use to propagate the constraints (since a
338 * copy will emerge anyway) */
339 if (ir_nodeset_contains(live_nodes, op))
342 op_info = get_allocation_info(op);
343 for (r = 0; r < n_regs; ++r) {
344 op_info->prefs[r] += info->prefs[r] * factor;
351 * Walker: Runs an a block calculates the preferences for any
352 * node and every register from the considered register class.
354 static void analyze_block(ir_node *block, void *data)
356 float weight = get_block_execfreq(execfreqs, block);
357 ir_nodeset_t live_nodes;
361 ir_nodeset_init(&live_nodes);
362 be_liveness_end_of_block(lv, cls, block, &live_nodes);
364 sched_foreach_reverse(block, node) {
365 allocation_info_t *info;
372 if (create_preferences)
373 check_defs(&live_nodes, weight, node);
376 arity = get_irn_arity(node);
378 /* the allocation info node currently only uses 1 unsigned value
379 to mark last used inputs. So we will fail for a node with more than
381 if (arity >= (int) sizeof(unsigned) * 8) {
382 panic("Node with more than %d inputs not supported yet",
383 (int) sizeof(unsigned) * 8);
386 info = get_allocation_info(node);
387 for (i = 0; i < arity; ++i) {
388 ir_node *op = get_irn_n(node, i);
389 if (!arch_irn_consider_in_reg_alloc(cls, op))
392 /* last usage of a value? */
393 if (!ir_nodeset_contains(&live_nodes, op)) {
394 rbitset_set(&info->last_uses, i);
398 be_liveness_transfer(cls, node, &live_nodes);
400 if (create_preferences) {
401 /* update weights based on usage constraints */
402 for (i = 0; i < arity; ++i) {
403 const arch_register_req_t *req;
404 const unsigned *limited;
405 ir_node *op = get_irn_n(node, i);
407 if (!arch_irn_consider_in_reg_alloc(cls, op))
410 req = arch_get_register_req(node, i);
411 if (!(req->type & arch_register_req_type_limited))
414 limited = req->limited;
415 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
421 ir_nodeset_destroy(&live_nodes);
424 static void congruence_def(ir_nodeset_t *live_nodes, ir_node *node)
426 const arch_register_req_t *req;
428 if (get_irn_mode(node) == mode_T) {
429 const ir_edge_t *edge;
430 foreach_out_edge(node, edge) {
431 ir_node *def = get_edge_src_irn(edge);
432 congruence_def(live_nodes, def);
437 if (!arch_irn_consider_in_reg_alloc(cls, node))
440 /* should be same constraint? */
441 req = arch_get_register_req_out(node);
442 if (req->type & arch_register_req_type_should_be_same) {
443 ir_node *insn = skip_Proj(node);
444 int arity = get_irn_arity(insn);
446 unsigned node_idx = get_irn_idx(node);
447 node_idx = uf_find(congruence_classes, node_idx);
449 for (i = 0; i < arity; ++i) {
453 ir_nodeset_iterator_t iter;
454 bool interferes = false;
456 if (!rbitset_is_set(&req->other_same, i))
459 op = get_irn_n(insn, i);
460 op_idx = get_irn_idx(op);
461 op_idx = uf_find(congruence_classes, op_idx);
463 /* do we interfere with the value */
464 foreach_ir_nodeset(live_nodes, live, iter) {
465 int lv_idx = get_irn_idx(live);
466 lv_idx = uf_find(congruence_classes, lv_idx);
467 if (lv_idx == op_idx) {
472 /* don't put in same affinity class if we interfere */
476 node_idx = uf_union(congruence_classes, node_idx, op_idx);
477 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
479 /* one should_be_same is enough... */
485 static void create_congruence_class(ir_node *block, void *data)
487 ir_nodeset_t live_nodes;
491 ir_nodeset_init(&live_nodes);
492 be_liveness_end_of_block(lv, cls, block, &live_nodes);
494 /* check should be same constraints */
495 sched_foreach_reverse(block, node) {
499 congruence_def(&live_nodes, node);
500 be_liveness_transfer(cls, node, &live_nodes);
503 /* check phi congruence classes */
504 sched_foreach_reverse_from(node, node) {
508 assert(is_Phi(node));
510 if (!arch_irn_consider_in_reg_alloc(cls, node))
513 node_idx = get_irn_idx(node);
514 node_idx = uf_find(congruence_classes, node_idx);
516 arity = get_irn_arity(node);
517 for (i = 0; i < arity; ++i) {
518 bool interferes = false;
519 ir_nodeset_iterator_t iter;
524 allocation_info_t *head_info;
525 allocation_info_t *other_info;
526 ir_node *op = get_Phi_pred(node, i);
527 int op_idx = get_irn_idx(op);
528 op_idx = uf_find(congruence_classes, op_idx);
530 /* do we interfere with the value */
531 foreach_ir_nodeset(&live_nodes, live, iter) {
532 int lv_idx = get_irn_idx(live);
533 lv_idx = uf_find(congruence_classes, lv_idx);
534 if (lv_idx == op_idx) {
539 /* don't put in same affinity class if we interfere */
542 /* any other phi has the same input? */
543 sched_foreach(block, phi) {
548 if (!arch_irn_consider_in_reg_alloc(cls, phi))
550 oop = get_Phi_pred(phi, i);
553 oop_idx = get_irn_idx(oop);
554 oop_idx = uf_find(congruence_classes, oop_idx);
555 if (oop_idx == op_idx) {
563 /* merge the 2 congruence classes and sum up their preferences */
564 old_node_idx = node_idx;
565 node_idx = uf_union(congruence_classes, node_idx, op_idx);
566 DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
569 old_node_idx = node_idx == old_node_idx ? op_idx : old_node_idx;
570 head_info = get_allocation_info(get_idx_irn(irg, node_idx));
571 other_info = get_allocation_info(get_idx_irn(irg, old_node_idx));
572 for (r = 0; r < n_regs; ++r) {
573 head_info->prefs[r] += other_info->prefs[r];
579 static void set_congruence_prefs(ir_node *node, void *data)
581 allocation_info_t *info;
582 allocation_info_t *head_info;
583 unsigned node_idx = get_irn_idx(node);
584 unsigned node_set = uf_find(congruence_classes, node_idx);
588 /* head of congruence class or not in any class */
589 if (node_set == node_idx)
592 if (!arch_irn_consider_in_reg_alloc(cls, node))
595 head_info = get_allocation_info(get_idx_irn(irg, node_set));
596 info = get_allocation_info(node);
598 memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
601 static void combine_congruence_classes(void)
603 size_t n = get_irg_last_idx(irg);
604 congruence_classes = XMALLOCN(int, n);
605 uf_init(congruence_classes, n);
607 /* create congruence classes */
608 irg_block_walk_graph(irg, create_congruence_class, NULL, NULL);
609 /* merge preferences */
610 irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
611 free(congruence_classes);
619 * Assign register reg to the given node.
621 * @param node the node
622 * @param reg the register
624 static void use_reg(ir_node *node, const arch_register_t *reg)
626 unsigned r = arch_register_get_index(reg);
627 assignments[r] = node;
628 arch_set_irn_register(node, reg);
631 static void free_reg_of_value(ir_node *node)
633 const arch_register_t *reg;
636 if (!arch_irn_consider_in_reg_alloc(cls, node))
639 reg = arch_get_irn_register(node);
640 r = arch_register_get_index(reg);
641 /* assignment->value may be NULL if a value is used at 2 inputs
642 so it gets freed twice. */
643 assert(assignments[r] == node || assignments[r] == NULL);
644 assignments[r] = NULL;
648 * Compare two register preferences in decreasing order.
650 static int compare_reg_pref(const void *e1, const void *e2)
652 const reg_pref_t *rp1 = (const reg_pref_t*) e1;
653 const reg_pref_t *rp2 = (const reg_pref_t*) e2;
654 if (rp1->pref < rp2->pref)
656 if (rp1->pref > rp2->pref)
661 static void fill_sort_candidates(reg_pref_t *regprefs,
662 const allocation_info_t *info)
666 for (r = 0; r < n_regs; ++r) {
667 float pref = info->prefs[r];
669 regprefs[r].pref = pref;
671 /* TODO: use a stable sort here to avoid unnecessary register jumping */
672 qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
675 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
676 float pref, float pref_delta,
677 unsigned *forbidden_regs, int recursion)
679 const arch_register_t *from_reg;
680 const arch_register_t *reg;
681 ir_node *original_insn;
687 allocation_info_t *info = get_allocation_info(to_split);
690 float split_threshold;
694 /* stupid hack: don't optimisticallt split don't spill nodes...
695 * (so we don't split away the values produced because of
696 * must_be_different constraints) */
697 original_insn = skip_Proj(info->original_value);
698 if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
701 from_reg = arch_get_irn_register(to_split);
702 from_r = arch_register_get_index(from_reg);
703 block = get_nodes_block(before);
704 split_threshold = get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
706 if (pref_delta < split_threshold*0.5)
709 /* find the best free position where we could move to */
710 prefs = ALLOCAN(reg_pref_t, n_regs);
711 fill_sort_candidates(prefs, info);
712 for (i = 0; i < n_regs; ++i) {
716 bool old_source_state;
718 /* we need a normal register which is not an output register
719 an different from the current register of to_split */
721 if (!rbitset_is_set(normal_regs, r))
723 if (rbitset_is_set(forbidden_regs, r))
728 /* is the split worth it? */
729 delta = pref_delta + prefs[i].pref;
730 if (delta < split_threshold) {
731 DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
732 to_split, recursion, delta));
736 /* if the register is free then we can do the split */
737 if (assignments[r] == NULL)
740 /* otherwise we might try recursively calling optimistic_split */
741 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
744 apref = prefs[i].pref;
745 apref_delta = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
746 apref_delta += pref_delta - split_threshold;
748 /* our source register isn't a usefull destination for recursive
750 old_source_state = rbitset_is_set(forbidden_regs, from_r);
751 rbitset_set(forbidden_regs, from_r);
752 /* try recursive split */
753 res = try_optimistic_split(assignments[r], before, apref,
754 apref_delta, forbidden_regs, recursion+1);
755 /* restore our destination */
756 if (old_source_state) {
757 rbitset_set(forbidden_regs, from_r);
759 rbitset_clear(forbidden_regs, from_r);
768 reg = arch_register_for_index(cls, r);
769 copy = be_new_Copy(cls, block, to_split);
770 mark_as_copy_of(copy, to_split);
771 /* hacky, but correct here */
772 if (assignments[arch_register_get_index(from_reg)] == to_split)
773 free_reg_of_value(to_split);
775 sched_add_before(before, copy);
778 "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
779 copy, to_split, from_reg->name, reg->name, before, delta, recursion));
784 * Determine and assign a register for node @p node
786 static void assign_reg(const ir_node *block, ir_node *node,
787 unsigned *forbidden_regs)
789 const arch_register_t *reg;
790 allocation_info_t *info;
791 const arch_register_req_t *req;
792 reg_pref_t *reg_prefs;
795 const unsigned *allowed_regs;
798 assert(!is_Phi(node));
799 assert(arch_irn_consider_in_reg_alloc(cls, node));
801 /* preassigned register? */
802 reg = arch_get_irn_register(node);
804 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
809 /* give should_be_same boni */
810 info = get_allocation_info(node);
811 req = arch_get_register_req_out(node);
813 in_node = skip_Proj(node);
814 if (req->type & arch_register_req_type_should_be_same) {
815 float weight = get_block_execfreq(execfreqs, block);
816 int arity = get_irn_arity(in_node);
819 assert(arity <= (int) sizeof(req->other_same) * 8);
820 for (i = 0; i < arity; ++i) {
822 const arch_register_t *reg;
824 if (!rbitset_is_set(&req->other_same, i))
827 in = get_irn_n(in_node, i);
828 reg = arch_get_irn_register(in);
830 r = arch_register_get_index(reg);
832 /* if the value didn't die here then we should not propagate the
833 * should_be_same info */
834 if (assignments[r] == in)
837 info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
841 /* create list of register candidates and sort by their preference */
842 DB((dbg, LEVEL_2, "Candidates for %+F:", node));
843 reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
844 fill_sort_candidates(reg_prefs, info);
845 for (i = 0; i < n_regs; ++i) {
846 unsigned num = reg_prefs[i].num;
847 const arch_register_t *reg;
849 if (!rbitset_is_set(normal_regs, num))
852 reg = arch_register_for_index(cls, num);
853 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
855 DB((dbg, LEVEL_2, "\n"));
857 allowed_regs = normal_regs;
858 if (req->type & arch_register_req_type_limited) {
859 allowed_regs = req->limited;
862 for (i = 0; i < n_regs; ++i) {
867 r = reg_prefs[i].num;
868 if (!rbitset_is_set(allowed_regs, r))
870 if (assignments[r] == NULL)
872 pref = reg_prefs[i].pref;
873 delta = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
874 before = skip_Proj(node);
875 res = try_optimistic_split(assignments[r], before,
876 pref, delta, forbidden_regs, 0);
881 panic("No register left for %+F\n", node);
884 reg = arch_register_for_index(cls, r);
885 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
890 * Add an permutation in front of a node and change the assignments
891 * due to this permutation.
893 * To understand this imagine a permutation like this:
903 * First we count how many destinations a single value has. At the same time
904 * we can be sure that each destination register has at most 1 source register
905 * (it can have 0 which means we don't care what value is in it).
906 * We ignore all fullfilled permuations (like 7->7)
907 * In a first pass we create as much copy instructions as possible as they
908 * are generally cheaper than exchanges. We do this by counting into how many
909 * destinations a register has to be copied (in the example it's 2 for register
910 * 3, or 1 for the registers 1,2,4 and 7).
911 * We can then create a copy into every destination register when the usecount
912 * of that register is 0 (= noone else needs the value in the register).
914 * After this step we should have cycles left. We implement a cyclic permutation
915 * of n registers with n-1 transpositions.
917 * @param live_nodes the set of live nodes, updated due to live range split
918 * @param before the node before we add the permutation
919 * @param permutation the permutation array indices are the destination
920 * registers, the values in the array are the source
923 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
924 unsigned *permutation)
926 unsigned *n_used = ALLOCANZ(unsigned, n_regs);
930 /* determine how often each source register needs to be read */
931 for (r = 0; r < n_regs; ++r) {
932 unsigned old_reg = permutation[r];
935 value = assignments[old_reg];
937 /* nothing to do here, reg is not live. Mark it as fixpoint
938 * so we ignore it in the next steps */
946 block = get_nodes_block(before);
948 /* step1: create copies where immediately possible */
949 for (r = 0; r < n_regs; /* empty */) {
952 const arch_register_t *reg;
953 unsigned old_r = permutation[r];
955 /* - no need to do anything for fixed points.
956 - we can't copy if the value in the dest reg is still needed */
957 if (old_r == r || n_used[r] > 0) {
963 src = assignments[old_r];
964 copy = be_new_Copy(cls, block, src);
965 sched_add_before(before, copy);
966 reg = arch_register_for_index(cls, r);
967 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
968 copy, src, before, reg->name));
969 mark_as_copy_of(copy, src);
972 if (live_nodes != NULL) {
973 ir_nodeset_insert(live_nodes, copy);
976 /* old register has 1 user less, permutation is resolved */
977 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
980 assert(n_used[old_r] > 0);
982 if (n_used[old_r] == 0) {
983 if (live_nodes != NULL) {
984 ir_nodeset_remove(live_nodes, src);
986 free_reg_of_value(src);
989 /* advance or jump back (if this copy enabled another copy) */
990 if (old_r < r && n_used[old_r] == 0) {
997 /* at this point we only have "cycles" left which we have to resolve with
999 * TODO: if we have free registers left, then we should really use copy
1000 * instructions for any cycle longer than 2 registers...
1001 * (this is probably architecture dependent, there might be archs where
1002 * copies are preferable even for 2-cycles) */
1004 /* create perms with the rest */
1005 for (r = 0; r < n_regs; /* empty */) {
1006 const arch_register_t *reg;
1007 unsigned old_r = permutation[r];
1019 /* we shouldn't have copies from 1 value to multiple destinations left*/
1020 assert(n_used[old_r] == 1);
1022 /* exchange old_r and r2; after that old_r is a fixed point */
1023 r2 = permutation[old_r];
1025 in[0] = assignments[r2];
1026 in[1] = assignments[old_r];
1027 perm = be_new_Perm(cls, block, 2, in);
1028 sched_add_before(before, perm);
1029 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
1030 perm, in[0], in[1], before));
1032 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
1033 mark_as_copy_of(proj0, in[0]);
1034 reg = arch_register_for_index(cls, old_r);
1035 use_reg(proj0, reg);
1037 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
1038 mark_as_copy_of(proj1, in[1]);
1039 reg = arch_register_for_index(cls, r2);
1040 use_reg(proj1, reg);
1042 /* 1 value is now in the correct register */
1043 permutation[old_r] = old_r;
1044 /* the source of r changed to r2 */
1045 permutation[r] = r2;
1047 /* if we have reached a fixpoint update data structures */
1048 if (live_nodes != NULL) {
1049 ir_nodeset_remove(live_nodes, in[0]);
1050 ir_nodeset_remove(live_nodes, in[1]);
1051 ir_nodeset_remove(live_nodes, proj0);
1052 ir_nodeset_insert(live_nodes, proj1);
1056 #ifdef DEBUG_libfirm
1057 /* now we should only have fixpoints left */
1058 for (r = 0; r < n_regs; ++r) {
1059 assert(permutation[r] == r);
1065 * Free regs for values last used.
1067 * @param live_nodes set of live nodes, will be updated
1068 * @param node the node to consider
1070 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
1072 allocation_info_t *info = get_allocation_info(node);
1073 const unsigned *last_uses = &info->last_uses;
1074 int arity = get_irn_arity(node);
1077 for (i = 0; i < arity; ++i) {
1080 /* check if one operand is the last use */
1081 if (!rbitset_is_set(last_uses, i))
1084 op = get_irn_n(node, i);
1085 free_reg_of_value(op);
1086 ir_nodeset_remove(live_nodes, op);
1091 * change inputs of a node to the current value (copies/perms)
1093 static void rewire_inputs(ir_node *node)
1096 int arity = get_irn_arity(node);
1098 for (i = 0; i < arity; ++i) {
1099 ir_node *op = get_irn_n(node, i);
1100 allocation_info_t *info = try_get_allocation_info(op);
1105 info = get_allocation_info(info->original_value);
1106 if (info->current_value != op) {
1107 set_irn_n(node, i, info->current_value);
1113 * Create a bitset of registers occupied with value living through an
1116 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1118 const allocation_info_t *info = get_allocation_info(node);
1123 /* mark all used registers as potentially live-through */
1124 for (r = 0; r < n_regs; ++r) {
1125 if (assignments[r] == NULL)
1127 if (!rbitset_is_set(normal_regs, r))
1130 rbitset_set(bitset, r);
1133 /* remove registers of value dying at the instruction */
1134 arity = get_irn_arity(node);
1135 for (i = 0; i < arity; ++i) {
1137 const arch_register_t *reg;
1139 if (!rbitset_is_set(&info->last_uses, i))
1142 op = get_irn_n(node, i);
1143 reg = arch_get_irn_register(op);
1144 rbitset_clear(bitset, arch_register_get_index(reg));
1149 * Enforce constraints at a node by live range splits.
1151 * @param live_nodes the set of live nodes, might be changed
1152 * @param node the current node
1154 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1155 unsigned *forbidden_regs)
1157 int arity = get_irn_arity(node);
1159 hungarian_problem_t *bp;
1161 unsigned *assignment;
1163 /* construct a list of register occupied by live-through values */
1164 unsigned *live_through_regs = NULL;
1166 /* see if any use constraints are not met */
1168 for (i = 0; i < arity; ++i) {
1169 ir_node *op = get_irn_n(node, i);
1170 const arch_register_t *reg;
1171 const arch_register_req_t *req;
1172 const unsigned *limited;
1175 if (!arch_irn_consider_in_reg_alloc(cls, op))
1178 /* are there any limitations for the i'th operand? */
1179 req = arch_get_register_req(node, i);
1180 if (!(req->type & arch_register_req_type_limited))
1183 limited = req->limited;
1184 reg = arch_get_irn_register(op);
1185 r = arch_register_get_index(reg);
1186 if (!rbitset_is_set(limited, r)) {
1187 /* found an assignment outside the limited set */
1193 /* is any of the live-throughs using a constrained output register? */
1194 if (get_irn_mode(node) == mode_T) {
1195 const ir_edge_t *edge;
1197 foreach_out_edge(node, edge) {
1198 ir_node *proj = get_edge_src_irn(edge);
1199 const arch_register_req_t *req;
1201 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1204 req = arch_get_register_req_out(proj);
1205 if (!(req->type & arch_register_req_type_limited))
1208 if (live_through_regs == NULL) {
1209 rbitset_alloca(live_through_regs, n_regs);
1210 determine_live_through_regs(live_through_regs, node);
1213 rbitset_or(forbidden_regs, req->limited, n_regs);
1214 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1219 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1220 const arch_register_req_t *req = arch_get_register_req_out(node);
1221 if (req->type & arch_register_req_type_limited) {
1222 rbitset_alloca(live_through_regs, n_regs);
1223 determine_live_through_regs(live_through_regs, node);
1224 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1226 rbitset_or(forbidden_regs, req->limited, n_regs);
1235 /* create these arrays if we haven't yet */
1236 if (live_through_regs == NULL) {
1237 rbitset_alloca(live_through_regs, n_regs);
1240 /* at this point we have to construct a bipartite matching problem to see
1241 * which values should go to which registers
1242 * Note: We're building the matrix in "reverse" - source registers are
1243 * right, destinations left because this will produce the solution
1244 * in the format required for permute_values.
1246 bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1248 /* add all combinations, then remove not allowed ones */
1249 for (l = 0; l < n_regs; ++l) {
1250 if (!rbitset_is_set(normal_regs, l)) {
1251 hungarian_add(bp, l, l, 1);
1255 for (r = 0; r < n_regs; ++r) {
1256 if (!rbitset_is_set(normal_regs, r))
1258 /* livethrough values may not use constrainted output registers */
1259 if (rbitset_is_set(live_through_regs, l)
1260 && rbitset_is_set(forbidden_regs, r))
1263 hungarian_add(bp, r, l, l == r ? 9 : 8);
1267 for (i = 0; i < arity; ++i) {
1268 ir_node *op = get_irn_n(node, i);
1269 const arch_register_t *reg;
1270 const arch_register_req_t *req;
1271 const unsigned *limited;
1272 unsigned current_reg;
1274 if (!arch_irn_consider_in_reg_alloc(cls, op))
1277 req = arch_get_register_req(node, i);
1278 if (!(req->type & arch_register_req_type_limited))
1281 limited = req->limited;
1282 reg = arch_get_irn_register(op);
1283 current_reg = arch_register_get_index(reg);
1284 for (r = 0; r < n_regs; ++r) {
1285 if (rbitset_is_set(limited, r))
1287 hungarian_remv(bp, r, current_reg);
1291 //hungarian_print_cost_matrix(bp, 1);
1292 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1294 assignment = ALLOCAN(unsigned, n_regs);
1295 res = hungarian_solve(bp, (int*) assignment, NULL, 0);
1299 fprintf(stderr, "Swap result:");
1300 for (i = 0; i < (int) n_regs; ++i) {
1301 fprintf(stderr, " %d", assignment[i]);
1303 fprintf(stderr, "\n");
1308 permute_values(live_nodes, node, assignment);
1311 /** test wether a node @p n is a copy of the value of node @p of */
1312 static bool is_copy_of(ir_node *value, ir_node *test_value)
1314 allocation_info_t *test_info;
1315 allocation_info_t *info;
1317 if (value == test_value)
1320 info = get_allocation_info(value);
1321 test_info = get_allocation_info(test_value);
1322 return test_info->original_value == info->original_value;
1326 * find a value in the end-assignment of a basic block
1327 * @returns the index into the assignment array if found
1330 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1333 ir_node **assignments = info->assignments;
1334 for (r = 0; r < n_regs; ++r) {
1335 ir_node *a_value = assignments[r];
1337 if (a_value == NULL)
1339 if (is_copy_of(a_value, value))
1347 * Create the necessary permutations at the end of a basic block to fullfill
1348 * the register assignment for phi-nodes in the next block
1350 static void add_phi_permutations(ir_node *block, int p)
1353 unsigned *permutation;
1354 ir_node **old_assignments;
1355 bool need_permutation;
1357 ir_node *pred = get_Block_cfgpred_block(block, p);
1359 block_info_t *pred_info = get_block_info(pred);
1361 /* predecessor not processed yet? nothing to do */
1362 if (!pred_info->processed)
1365 permutation = ALLOCAN(unsigned, n_regs);
1366 for (r = 0; r < n_regs; ++r) {
1370 /* check phi nodes */
1371 need_permutation = false;
1372 node = sched_first(block);
1373 for ( ; is_Phi(node); node = sched_next(node)) {
1374 const arch_register_t *reg;
1379 if (!arch_irn_consider_in_reg_alloc(cls, node))
1382 op = get_Phi_pred(node, p);
1383 if (!arch_irn_consider_in_reg_alloc(cls, op))
1386 a = find_value_in_block_info(pred_info, op);
1389 reg = arch_get_irn_register(node);
1390 regn = arch_register_get_index(reg);
1392 permutation[regn] = a;
1393 need_permutation = true;
1397 if (need_permutation) {
1398 /* permute values at end of predecessor */
1399 old_assignments = assignments;
1400 assignments = pred_info->assignments;
1401 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1403 assignments = old_assignments;
1406 /* change phi nodes to use the copied values */
1407 node = sched_first(block);
1408 for ( ; is_Phi(node); node = sched_next(node)) {
1412 if (!arch_irn_consider_in_reg_alloc(cls, node))
1415 op = get_Phi_pred(node, p);
1416 /* no need to do anything for Unknown inputs */
1417 if (!arch_irn_consider_in_reg_alloc(cls, op))
1420 /* we have permuted all values into the correct registers so we can
1421 simply query which value occupies the phis register in the
1423 a = arch_register_get_index(arch_get_irn_register(node));
1424 op = pred_info->assignments[a];
1425 set_Phi_pred(node, p, op);
1430 * Set preferences for a phis register based on the registers used on the
1433 static void adapt_phi_prefs(ir_node *phi)
1436 int arity = get_irn_arity(phi);
1437 ir_node *block = get_nodes_block(phi);
1438 allocation_info_t *info = get_allocation_info(phi);
1440 for (i = 0; i < arity; ++i) {
1441 ir_node *op = get_irn_n(phi, i);
1442 const arch_register_t *reg = arch_get_irn_register(op);
1443 ir_node *pred_block;
1444 block_info_t *pred_block_info;
1450 /* we only give the bonus if the predecessor already has registers
1451 * assigned, otherwise we only see a dummy value
1452 * and any conclusions about its register are useless */
1453 pred_block = get_Block_cfgpred_block(block, i);
1454 pred_block_info = get_block_info(pred_block);
1455 if (!pred_block_info->processed)
1458 /* give bonus for already assigned register */
1459 weight = get_block_execfreq(execfreqs, pred_block);
1460 r = arch_register_get_index(reg);
1461 info->prefs[r] += weight * AFF_PHI;
1466 * After a phi has been assigned a register propagate preference inputs
1467 * to the phi inputs.
1469 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1472 ir_node *block = get_nodes_block(phi);
1473 int arity = get_irn_arity(phi);
1475 for (i = 0; i < arity; ++i) {
1476 ir_node *op = get_Phi_pred(phi, i);
1477 allocation_info_t *info = get_allocation_info(op);
1478 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1481 = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1483 if (info->prefs[assigned_r] >= weight)
1486 /* promote the prefered register */
1487 for (r = 0; r < n_regs; ++r) {
1488 if (info->prefs[r] > -weight) {
1489 info->prefs[r] = -weight;
1492 info->prefs[assigned_r] = weight;
1495 propagate_phi_register(op, assigned_r);
1499 static void assign_phi_registers(ir_node *block)
1506 hungarian_problem_t *bp;
1508 /* count phi nodes */
1509 sched_foreach(block, node) {
1512 if (!arch_irn_consider_in_reg_alloc(cls, node))
1520 /* build a bipartite matching problem for all phi nodes */
1521 bp = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1523 sched_foreach(block, node) {
1526 allocation_info_t *info;
1529 if (!arch_irn_consider_in_reg_alloc(cls, node))
1532 /* give boni for predecessor colorings */
1533 adapt_phi_prefs(node);
1534 /* add stuff to bipartite problem */
1535 info = get_allocation_info(node);
1536 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1537 for (r = 0; r < n_regs; ++r) {
1540 if (!rbitset_is_set(normal_regs, r))
1543 costs = info->prefs[r];
1544 costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1547 hungarian_add(bp, n, r, costs);
1548 DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1551 DB((dbg, LEVEL_3, "\n"));
1555 //hungarian_print_cost_matrix(bp, 7);
1556 hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1558 assignment = ALLOCAN(int, n_regs);
1559 res = hungarian_solve(bp, assignment, NULL, 0);
1564 sched_foreach(block, node) {
1566 const arch_register_t *reg;
1570 if (!arch_irn_consider_in_reg_alloc(cls, node))
1573 r = assignment[n++];
1574 assert(rbitset_is_set(normal_regs, r));
1575 reg = arch_register_for_index(cls, r);
1576 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1579 /* adapt preferences for phi inputs */
1580 if (propagate_phi_registers)
1581 propagate_phi_register(node, r);
1586 * Walker: assign registers to all nodes of a block that
1587 * need registers from the currently considered register class.
1589 static void allocate_coalesce_block(ir_node *block, void *data)
1592 ir_nodeset_t live_nodes;
1595 block_info_t *block_info;
1596 block_info_t **pred_block_infos;
1598 unsigned *forbidden_regs; /**< collects registers which must
1599 not be used for optimistic splits */
1602 DB((dbg, LEVEL_2, "* Block %+F\n", block));
1604 /* clear assignments */
1605 block_info = get_block_info(block);
1606 assignments = block_info->assignments;
1608 ir_nodeset_init(&live_nodes);
1610 /* gather regalloc infos of predecessor blocks */
1611 n_preds = get_Block_n_cfgpreds(block);
1612 pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1613 for (i = 0; i < n_preds; ++i) {
1614 ir_node *pred = get_Block_cfgpred_block(block, i);
1615 block_info_t *pred_info = get_block_info(pred);
1616 pred_block_infos[i] = pred_info;
1619 phi_ins = ALLOCAN(ir_node*, n_preds);
1621 /* collect live-in nodes and preassigned values */
1622 be_lv_foreach(lv, block, be_lv_state_in, i) {
1623 const arch_register_t *reg;
1625 bool need_phi = false;
1627 node = be_lv_get_irn(lv, block, i);
1628 if (!arch_irn_consider_in_reg_alloc(cls, node))
1631 /* check all predecessors for this value, if it is not everywhere the
1632 same or unknown then we have to construct a phi
1633 (we collect the potential phi inputs here) */
1634 for (p = 0; p < n_preds; ++p) {
1635 block_info_t *pred_info = pred_block_infos[p];
1637 if (!pred_info->processed) {
1638 /* use node for now, it will get fixed later */
1642 int a = find_value_in_block_info(pred_info, node);
1644 /* must live out of predecessor */
1646 phi_ins[p] = pred_info->assignments[a];
1647 /* different value from last time? then we need a phi */
1648 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1655 ir_mode *mode = get_irn_mode(node);
1656 const arch_register_req_t *req = get_default_req_current_cls();
1659 phi = new_r_Phi(block, n_preds, phi_ins, mode);
1660 be_set_phi_reg_req(phi, req);
1662 DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1663 #ifdef DEBUG_libfirm
1666 for (i = 0; i < n_preds; ++i) {
1667 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1669 DB((dbg, LEVEL_3, "\n"));
1672 mark_as_copy_of(phi, node);
1673 sched_add_after(block, phi);
1677 allocation_info_t *info = get_allocation_info(node);
1678 info->current_value = phi_ins[0];
1680 /* Grab 1 of the inputs we constructed (might not be the same as
1681 * "node" as we could see the same copy of the value in all
1686 /* if the node already has a register assigned use it */
1687 reg = arch_get_irn_register(node);
1692 /* remember that this node is live at the beginning of the block */
1693 ir_nodeset_insert(&live_nodes, node);
1696 rbitset_alloca(forbidden_regs, n_regs);
1698 /* handle phis... */
1699 assign_phi_registers(block);
1701 /* all live-ins must have a register */
1702 #ifdef DEBUG_libfirm
1704 ir_nodeset_iterator_t iter;
1705 foreach_ir_nodeset(&live_nodes, node, iter) {
1706 const arch_register_t *reg = arch_get_irn_register(node);
1707 assert(reg != NULL);
1712 /* assign instructions in the block */
1713 sched_foreach(block, node) {
1717 /* phis are already assigned */
1721 rewire_inputs(node);
1723 /* enforce use constraints */
1724 rbitset_clear_all(forbidden_regs, n_regs);
1725 enforce_constraints(&live_nodes, node, forbidden_regs);
1727 rewire_inputs(node);
1729 /* we may not use registers used for inputs for optimistic splits */
1730 arity = get_irn_arity(node);
1731 for (i = 0; i < arity; ++i) {
1732 ir_node *op = get_irn_n(node, i);
1733 const arch_register_t *reg;
1734 if (!arch_irn_consider_in_reg_alloc(cls, op))
1737 reg = arch_get_irn_register(op);
1738 rbitset_set(forbidden_regs, arch_register_get_index(reg));
1741 /* free registers of values last used at this instruction */
1742 free_last_uses(&live_nodes, node);
1744 /* assign output registers */
1745 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1746 if (get_irn_mode(node) == mode_T) {
1747 const ir_edge_t *edge;
1748 foreach_out_edge(node, edge) {
1749 ir_node *proj = get_edge_src_irn(edge);
1750 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1752 assign_reg(block, proj, forbidden_regs);
1754 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1755 assign_reg(block, node, forbidden_regs);
1759 ir_nodeset_destroy(&live_nodes);
1762 block_info->processed = true;
1764 /* permute values at end of predecessor blocks in case of phi-nodes */
1767 for (p = 0; p < n_preds; ++p) {
1768 add_phi_permutations(block, p);
1772 /* if we have exactly 1 successor then we might be able to produce phi
1774 if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1775 const ir_edge_t *edge
1776 = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1777 ir_node *succ = get_edge_src_irn(edge);
1778 int p = get_edge_src_pos(edge);
1779 block_info_t *succ_info = get_block_info(succ);
1781 if (succ_info->processed) {
1782 add_phi_permutations(succ, p);
1787 typedef struct block_costs_t block_costs_t;
1788 struct block_costs_t {
1789 float costs; /**< costs of the block */
1790 int dfs_num; /**< depth first search number (to detect backedges) */
1793 static int cmp_block_costs(const void *d1, const void *d2)
1795 const ir_node * const *block1 = d1;
1796 const ir_node * const *block2 = d2;
1797 const block_costs_t *info1 = get_irn_link(*block1);
1798 const block_costs_t *info2 = get_irn_link(*block2);
1799 return QSORT_CMP(info2->costs, info1->costs);
1802 static void determine_block_order(void)
1805 ir_node **blocklist = be_get_cfgpostorder(irg);
1806 int n_blocks = ARR_LEN(blocklist);
1808 pdeq *worklist = new_pdeq();
1809 ir_node **order = XMALLOCN(ir_node*, n_blocks);
1812 /* clear block links... */
1813 for (i = 0; i < n_blocks; ++i) {
1814 ir_node *block = blocklist[i];
1815 set_irn_link(block, NULL);
1818 /* walk blocks in reverse postorder, the costs for each block are the
1819 * sum of the costs of its predecessors (excluding the costs on backedges
1820 * which we can't determine) */
1821 for (i = n_blocks-1; i >= 0; --i) {
1822 block_costs_t *cost_info;
1823 ir_node *block = blocklist[i];
1825 float execfreq = get_block_execfreq(execfreqs, block);
1826 float costs = execfreq;
1827 int n_cfgpreds = get_Block_n_cfgpreds(block);
1829 for (p = 0; p < n_cfgpreds; ++p) {
1830 ir_node *pred_block = get_Block_cfgpred_block(block, p);
1831 block_costs_t *pred_costs = get_irn_link(pred_block);
1832 /* we don't have any info for backedges */
1833 if (pred_costs == NULL)
1835 costs += pred_costs->costs;
1838 cost_info = OALLOCZ(&obst, block_costs_t);
1839 cost_info->costs = costs;
1840 cost_info->dfs_num = dfs_num++;
1841 set_irn_link(block, cost_info);
1844 /* sort array by block costs */
1845 qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1847 ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1848 inc_irg_block_visited(irg);
1850 for (i = 0; i < n_blocks; ++i) {
1851 ir_node *block = blocklist[i];
1852 if (Block_block_visited(block))
1855 /* continually add predecessors with highest costs to worklist
1856 * (without using backedges) */
1858 block_costs_t *info = get_irn_link(block);
1859 ir_node *best_pred = NULL;
1860 float best_costs = -1;
1861 int n_cfgpred = get_Block_n_cfgpreds(block);
1864 pdeq_putr(worklist, block);
1865 mark_Block_block_visited(block);
1866 for (i = 0; i < n_cfgpred; ++i) {
1867 ir_node *pred_block = get_Block_cfgpred_block(block, i);
1868 block_costs_t *pred_info = get_irn_link(pred_block);
1870 /* ignore backedges */
1871 if (pred_info->dfs_num > info->dfs_num)
1874 if (info->costs > best_costs) {
1875 best_costs = info->costs;
1876 best_pred = pred_block;
1880 } while(block != NULL && !Block_block_visited(block));
1882 /* now put all nodes in the worklist in our final order */
1883 while (!pdeq_empty(worklist)) {
1884 ir_node *pblock = pdeq_getr(worklist);
1885 assert(order_p < n_blocks);
1886 order[order_p++] = pblock;
1889 assert(order_p == n_blocks);
1892 ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1894 DEL_ARR_F(blocklist);
1896 obstack_free(&obst, NULL);
1897 obstack_init(&obst);
1899 block_order = order;
1900 n_block_order = n_blocks;
1904 * Run the register allocator for the current register class.
1906 static void be_straight_alloc_cls(void)
1910 lv = be_assure_liveness(birg);
1911 be_liveness_assure_sets(lv);
1913 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1915 DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1917 be_clear_links(irg);
1919 irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1920 if (create_congruence_classes)
1921 combine_congruence_classes();
1923 for (i = 0; i < n_block_order; ++i) {
1924 ir_node *block = block_order[i];
1925 allocate_coalesce_block(block, NULL);
1928 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1931 static void dump(int mask, ir_graph *irg, const char *suffix,
1932 void (*dumper)(ir_graph *, const char *))
1934 if(birg->main_env->options->dump_flags & mask)
1935 be_dump(irg, suffix, dumper);
1939 * Run the spiller on the current graph.
1941 static void spill(void)
1943 /* make sure all nodes show their real register pressure */
1944 BE_TIMER_PUSH(t_ra_constr);
1945 be_pre_spill_prepare_constr(birg, cls);
1946 BE_TIMER_POP(t_ra_constr);
1948 dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1951 BE_TIMER_PUSH(t_ra_spill);
1952 be_do_spill(birg, cls);
1953 BE_TIMER_POP(t_ra_spill);
1955 BE_TIMER_PUSH(t_ra_spill_apply);
1956 check_for_memory_operands(irg);
1957 BE_TIMER_POP(t_ra_spill_apply);
1959 dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1963 * The straight register allocator for a whole procedure.
1965 static void be_straight_alloc(be_irg_t *new_birg)
1967 const arch_env_t *arch_env = new_birg->main_env->arch_env;
1968 int n_cls = arch_env_get_n_reg_class(arch_env);
1971 obstack_init(&obst);
1974 irg = be_get_birg_irg(birg);
1975 execfreqs = birg->exec_freq;
1977 /* determine a good coloring order */
1978 determine_block_order();
1980 for (c = 0; c < n_cls; ++c) {
1981 cls = arch_env_get_reg_class(arch_env, c);
1982 default_cls_req = NULL;
1983 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1986 stat_ev_ctx_push_str("regcls", cls->name);
1988 n_regs = arch_register_class_n_regs(cls);
1989 normal_regs = rbitset_malloc(n_regs);
1990 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1994 /* verify schedule and register pressure */
1995 BE_TIMER_PUSH(t_verify);
1996 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1997 be_verify_schedule(birg);
1998 be_verify_register_pressure(birg, cls, irg);
1999 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2000 assert(be_verify_schedule(birg) && "Schedule verification failed");
2001 assert(be_verify_register_pressure(birg, cls, irg)
2002 && "Register pressure verification failed");
2004 BE_TIMER_POP(t_verify);
2006 BE_TIMER_PUSH(t_ra_color);
2007 be_straight_alloc_cls();
2008 BE_TIMER_POP(t_ra_color);
2010 /* we most probably constructed new Phis so liveness info is invalid
2012 /* TODO: test liveness_introduce */
2013 be_liveness_invalidate(lv);
2016 stat_ev_ctx_pop("regcls");
2019 BE_TIMER_PUSH(t_ra_spill_apply);
2020 be_abi_fix_stack_nodes(birg->abi);
2021 BE_TIMER_POP(t_ra_spill_apply);
2023 BE_TIMER_PUSH(t_verify);
2024 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
2025 be_verify_register_allocation(birg);
2026 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
2027 assert(be_verify_register_allocation(birg)
2028 && "Register allocation invalid");
2030 BE_TIMER_POP(t_verify);
2032 obstack_free(&obst, NULL);
2036 * Initializes this module.
2038 void be_init_straight_alloc(void)
2040 static be_ra_t be_ra_straight = {
2043 lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
2044 lc_opt_entry_t *straightalloc_group = lc_opt_get_grp(be_grp, "straightalloc");
2045 lc_opt_add_table(straightalloc_group, options);
2047 be_register_allocator("straight", &be_ra_straight);
2048 FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
2051 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);