fix a few bugs in benewalloc, split codegen timer in 2
[libfirm] / ir / be / benewalloc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
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.
10  *
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.
14  *
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
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       New approach to allocation and copy coalescing
23  * @author      Matthias Braun
24  * @date        14.2.2009
25  * @version     $Id$
26  *
27  * ... WE NEED A NAME FOR THIS ...
28  *
29  * Only a proof of concept at this moment...
30  *
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...)
36  *
37  * 2. Walk blocks and assigns registers in a greedy fashion. Preferring registers
38  *    with high preferences. When register constraints are not met, add copies
39  *    and split live-ranges.
40  *
41  * TODO:
42  *  - output constraints are not ensured. The algorithm fails to copy values
43  *    away, so the registers for constrained outputs are free.
44  *  - must_be_different constraint is not respected
45  *  - No parallel copies at basic block borders are created, no additional phis
46  *    created after copies have been inserted.
47  *  - Phi color assignment should give bonus points towards registers already
48  *    assigned at predecessors.
49  *  - think about a smarter sequence of visiting the blocks. Sorted by
50  *    execfreq might be good, or looptree from inner to outermost loops going
51  *    over blocks in a reverse postorder
52  */
53 #include "config.h"
54
55 #include <float.h>
56
57 #include "obst.h"
58 #include "irnode_t.h"
59 #include "irgraph_t.h"
60 #include "iredges_t.h"
61 #include "ircons.h"
62 #include "irgwalk.h"
63 #include "execfreq.h"
64
65 #include "be.h"
66 #include "bera.h"
67 #include "belive_t.h"
68 #include "bemodule.h"
69 #include "bechordal_t.h"
70 #include "besched_t.h"
71 #include "beirg_t.h"
72 #include "benode_t.h"
73 #include "bespilloptions.h"
74 #include "beverify.h"
75
76 #include "bipartite.h"
77 #include "hungarian.h"
78
79 #define USE_FACTOR       1.0f
80 #define DEF_FACTOR       1.0f
81 #define NEIGHBOR_FACTOR  0.2f
82 #define SHOULD_BE_SAME   1.0f
83
84 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
85
86 static struct obstack               obst;
87 static be_irg_t                    *birg;
88 static ir_graph                    *irg;
89 static const arch_register_class_t *cls;
90 static be_lv_t                     *lv;
91 static const ir_exec_freq          *execfreqs;
92 static unsigned                     n_regs;
93 static bitset_t                    *ignore_regs;
94
95 typedef struct assignment_t assignment_t;
96 struct assignment_t {
97         ir_node *value;            /**< currently assigned value */
98 };
99
100 static assignment_t *assignments;
101
102 typedef struct allocation_info_t allocation_info_t;
103 struct allocation_info_t {
104         unsigned      last_uses;   /**< bitset indicating last uses (input pos) */
105         assignment_t *current_assignment;
106         float         prefs[0];    /**< register preferences */
107 };
108
109 typedef struct reg_pref_t reg_pref_t;
110 struct reg_pref_t {
111         unsigned num;
112         float    pref;
113 };
114
115 /**
116  * Get the allocation info for a node.
117  * The info is allocated on the first visit of a node.
118  */
119 static allocation_info_t *get_allocation_info(ir_node *node)
120 {
121         allocation_info_t *info;
122         if (!irn_visited(node)) {
123                 size_t size = sizeof(info[0]) + n_regs * sizeof(float);
124                 info = obstack_alloc(&obst, size);
125                 memset(info, 0, size);
126                 set_irn_link(node, info);
127                 mark_irn_visited(node);
128         } else {
129                 info = get_irn_link(node);
130         }
131
132         return info;
133 }
134
135 /**
136  * Link the allocation info of a node to a copy.
137  * Afterwards, both nodes uses the same allocation info.
138  * Copy must not have an allocation info assigned yet.
139  *
140  * @param copy   the node that gets the allocation info assigned
141  * @param value  the original node
142  */
143 static void link_to(ir_node *copy, ir_node *value)
144 {
145         allocation_info_t *info = get_allocation_info(value);
146         assert(!irn_visited(copy));
147         set_irn_link(copy, info);
148         mark_irn_visited(copy);
149 }
150
151 /**
152  * Calculate the penalties for every register on a node and its live neighbors.
153  *
154  * @param live_nodes   the set of live nodes at the current position, may be NULL
155  * @param penalty      the penalty to subtract from
156  * @param limited      a raw bitset containing the limited set for the node
157  * @param node         the node
158  */
159 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
160                                       float penalty, const unsigned* limited,
161                                                                           ir_node *node)
162 {
163         ir_nodeset_iterator_t iter;
164         unsigned              r;
165         allocation_info_t     *info = get_allocation_info(node);
166         ir_node               *neighbor;
167
168         /* give penalty for all forbidden regs */
169         for (r = 0; r < n_regs; ++r) {
170                 if (rbitset_is_set(limited, r))
171                         continue;
172
173                 info->prefs[r] -= penalty;
174         }
175
176         /* all other live values should get a penalty for allowed regs */
177         if (live_nodes == NULL)
178                 return;
179
180         /* TODO: reduce penalty if there are multiple allowed registers... */
181         penalty *= NEIGHBOR_FACTOR;
182         foreach_ir_nodeset(live_nodes, neighbor, iter) {
183                 allocation_info_t *neighbor_info;
184
185                 /* TODO: if op is used on multiple inputs we might not do a
186                  * continue here */
187                 if (neighbor == node)
188                         continue;
189
190                 neighbor_info = get_allocation_info(neighbor);
191                 for (r = 0; r < n_regs; ++r) {
192                         if (!rbitset_is_set(limited, r))
193                                 continue;
194
195                         neighbor_info->prefs[r] -= penalty;
196                 }
197         }
198 }
199
200 /**
201  * Calculate the preferences of a definition for the current register class.
202  * If the definition uses a limited set of registers, reduce the preferences
203  * for the limited register on the node and its neighbors.
204  *
205  * @param live_nodes  the set of live nodes at the current node
206  * @param weight      the weight
207  * @param node        the current node
208  */
209 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
210                        ir_node *node)
211 {
212         const arch_register_req_t *req;
213
214         if (get_irn_mode(node) == mode_T) {
215                 const ir_edge_t *edge;
216                 foreach_out_edge(node, edge) {
217                         ir_node *proj = get_edge_src_irn(edge);
218                         check_defs(live_nodes, weight, proj);
219                 }
220                 return;
221         }
222
223         if (!arch_irn_consider_in_reg_alloc(cls, node))
224                 return;
225
226         req = arch_get_register_req_out(node);
227         if (req->type & arch_register_req_type_limited) {
228                 const unsigned *limited = req->limited;
229                 float           penalty = weight * DEF_FACTOR;
230                 give_penalties_for_limits(live_nodes, penalty, limited, node);
231         }
232
233         if (req->type & arch_register_req_type_should_be_same) {
234                 ir_node           *insn  = skip_Proj(node);
235                 allocation_info_t *info  = get_allocation_info(node);
236                 int                arity = get_irn_arity(insn);
237                 int                i;
238
239                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
240                 for (i = 0; i < arity; ++i) {
241                         ir_node           *op;
242                         unsigned          r;
243                         allocation_info_t *op_info;
244
245                         if (!rbitset_is_set(&req->other_same, i))
246                                 continue;
247
248                         op      = get_irn_n(insn, i);
249                         op_info = get_allocation_info(op);
250                         for (r = 0; r < n_regs; ++r) {
251                                 if (bitset_is_set(ignore_regs, r))
252                                         continue;
253                                 op_info->prefs[r] += info->prefs[r] * factor;
254                         }
255                 }
256         }
257 }
258
259 /**
260  * Walker: Runs an a block calculates the preferences for any
261  * node and every register from the considered register class.
262  */
263 static void analyze_block(ir_node *block, void *data)
264 {
265         float         weight = get_block_execfreq(execfreqs, block);
266         ir_nodeset_t  live_nodes;
267         ir_node      *node;
268         (void) data;
269
270         ir_nodeset_init(&live_nodes);
271         be_liveness_end_of_block(lv, cls, block, &live_nodes);
272
273         sched_foreach_reverse(block, node) {
274                 allocation_info_t *info;
275                 int               i, arity;
276
277                 if (is_Phi(node)) {
278                         /* TODO: handle constrained phi-nodes */
279                         break;
280                 }
281
282                 /* TODO give/take penalties for should_be_same/different) */
283                 check_defs(&live_nodes, weight, node);
284
285                 /* mark last uses */
286                 arity = get_irn_arity(node);
287                 /* I was lazy, and only allocated 1 unsigned
288                    => maximum of 32 uses per node (rewrite if necessary) */
289                 assert(arity <= (int) sizeof(unsigned) * 8);
290
291                 info = get_allocation_info(node);
292                 for (i = 0; i < arity; ++i) {
293                         ir_node *op = get_irn_n(node, i);
294                         if (!arch_irn_consider_in_reg_alloc(cls, op))
295                                 continue;
296
297                         /* last usage of a value? */
298                         if (!ir_nodeset_contains(&live_nodes, op)) {
299                                 rbitset_set(&info->last_uses, i);
300                         }
301                 }
302
303                 be_liveness_transfer(cls, node, &live_nodes);
304
305                 /* update weights based on usage constraints */
306                 for (i = 0; i < arity; ++i) {
307                         const arch_register_req_t *req;
308                         const unsigned            *limited;
309                         ir_node                   *op = get_irn_n(node, i);
310
311                         if (!arch_irn_consider_in_reg_alloc(cls, op))
312                                 continue;
313
314                         req = arch_get_register_req(node, i);
315                         if ((req->type & arch_register_req_type_limited) == 0)
316                                 continue;
317
318                         /* TODO: give penalties to neighbors for precolored nodes! */
319
320                         limited = req->limited;
321                         give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
322                                                   op);
323                 }
324         }
325
326         ir_nodeset_destroy(&live_nodes);
327 }
328
329 /**
330  * Assign register reg to the given node.
331  *
332  * @param node  the node
333  * @param reg   the register
334  */
335 static void use_reg(ir_node *node, const arch_register_t *reg)
336 {
337         unsigned           r          = arch_register_get_index(reg);
338         assignment_t      *assignment = &assignments[r];
339         allocation_info_t *info;
340
341         assert(assignment->value == NULL);
342         assignment->value = node;
343
344         info = get_allocation_info(node);
345         info->current_assignment = assignment;
346
347         arch_set_irn_register(node, reg);
348 }
349
350 /**
351  * Compare two register preferences in decreasing order.
352  */
353 static int compare_reg_pref(const void *e1, const void *e2)
354 {
355         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
356         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
357         if (rp1->pref < rp2->pref)
358                 return 1;
359         if (rp1->pref > rp2->pref)
360                 return -1;
361         return 0;
362 }
363
364 static void fill_sort_candidates(reg_pref_t *regprefs,
365                                  const allocation_info_t *info)
366 {
367         unsigned r;
368
369         for (r = 0; r < n_regs; ++r) {
370                 float pref = info->prefs[r];
371                 if (bitset_is_set(ignore_regs, r)) {
372                         pref = -10000;
373                 }
374                 regprefs[r].num  = r;
375                 regprefs[r].pref = pref;
376         }
377         /* TODO: use a stable sort here to avoid unnecessary register jumping */
378         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
379 }
380
381 static void assign_reg(const ir_node *block, ir_node *node)
382 {
383         const arch_register_t     *reg;
384         allocation_info_t         *info;
385         const arch_register_req_t *req;
386         reg_pref_t                *reg_prefs;
387         ir_node                   *in_node;
388         unsigned                  i;
389
390         assert(arch_irn_consider_in_reg_alloc(cls, node));
391
392         /* preassigned register? */
393         reg = arch_get_irn_register(node);
394         if (reg != NULL) {
395                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
396                 use_reg(node, reg);
397                 return;
398         }
399
400         /* give should_be_same boni */
401         info = get_allocation_info(node);
402         req  = arch_get_register_req_out(node);
403
404         in_node = skip_Proj(node);
405         if (req->type & arch_register_req_type_should_be_same) {
406                 float weight = get_block_execfreq(execfreqs, block);
407                 int   arity  = get_irn_arity(in_node);
408                 int   i;
409
410                 assert(arity <= (int) sizeof(req->other_same) * 8);
411                 for (i = 0; i < arity; ++i) {
412                         ir_node               *in;
413                         const arch_register_t *reg;
414                         unsigned               r;
415                         if (!rbitset_is_set(&req->other_same, i))
416                                 continue;
417
418                         in  = get_irn_n(in_node, i);
419                         reg = arch_get_irn_register(in);
420                         assert(reg != NULL);
421                         r = arch_register_get_index(reg);
422                         if (bitset_is_set(ignore_regs, r))
423                                 continue;
424                         info->prefs[r] += weight * SHOULD_BE_SAME;
425                 }
426         }
427
428         /* TODO: handle must_be_different */
429
430         /*  */
431         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
432         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
433         fill_sort_candidates(reg_prefs, info);
434         for (i = 0; i < n_regs; ++i) {
435                 unsigned               num = reg_prefs[i].num;
436                 const arch_register_t *reg = arch_register_for_index(cls, num);
437                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
438         }
439         DB((dbg, LEVEL_2, "\n"));
440
441         for (i = 0; i < n_regs; ++i) {
442                 unsigned r = reg_prefs[i].num;
443                 /* ignores should be last and we should have a non-ignore left */
444                 assert(!bitset_is_set(ignore_regs, r));
445                 /* already used? TODO: It might be better to copy the value occupying the register around here, find out when... */
446                 if (assignments[r].value != NULL)
447                         continue;
448                 reg = arch_register_for_index(cls, r);
449                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
450                 use_reg(node, reg);
451                 break;
452         }
453 }
454
455 static void free_reg_of_value(ir_node *node)
456 {
457         allocation_info_t *info;
458         assignment_t      *assignment;
459         unsigned          r;
460
461         if (!arch_irn_consider_in_reg_alloc(cls, node))
462                 return;
463
464         info       = get_allocation_info(node);
465         assignment = info->current_assignment;
466
467         assert(assignment != NULL);
468
469         r = assignment - assignments;
470         DB((dbg, LEVEL_2, "Value %+F ended, freeing %s\n",
471                 node, arch_register_for_index(cls, r)->name));
472         assignment->value        = NULL;
473         info->current_assignment = NULL;
474 }
475
476 /**
477  * Return the index of the currently assigned register of a node.
478  */
479 static unsigned get_current_reg(ir_node *node)
480 {
481         allocation_info_t *info       = get_allocation_info(node);
482         assignment_t      *assignment = info->current_assignment;
483         return assignment - assignments;
484 }
485
486 /**
487  * Return the currently assigned assignment of a node.
488  */
489 static assignment_t *get_current_assignment(ir_node *node)
490 {
491         allocation_info_t *info = get_allocation_info(node);
492         return info->current_assignment;
493 }
494
495 /**
496  * Add an permutation in front of a node and change the assignments
497  * due to this permutation.
498  *
499  * @param live_nodes   the set of live nodes, updated due to live range split
500  * @param before       the node before we add the permutation
501  * @param permutation  the permutation array (map indexes to indexes)
502  */
503 static void permutate_values(ir_nodeset_t *live_nodes, ir_node *before,
504                              unsigned *permutation)
505 {
506         ir_node  *block;
507         ir_node **srcs   = ALLOCANZ(ir_node*, n_regs);
508         unsigned *n_used = ALLOCANZ(unsigned, n_regs);
509         unsigned  r;
510
511         /* create a list of values which really need to be "permed" */
512         for (r = 0; r < n_regs; ++r) {
513                 unsigned      new_reg = permutation[r];
514                 assignment_t *assignment;
515                 ir_node      *value;
516
517                 if (new_reg == r)
518                         continue;
519
520                 assignment = &assignments[r];
521                 value      = assignment->value;
522                 if (value == NULL) {
523                         /* nothing to do here, reg is not live */
524                         permutation[r] = r;
525                         continue;
526                 }
527
528                 assert(srcs[new_reg] == NULL);
529                 srcs[new_reg] = value;
530                 n_used[r]++;
531
532                 free_reg_of_value(value);
533                 ir_nodeset_remove(live_nodes, value);
534         }
535
536         block = get_nodes_block(before);
537
538         /* step1: create copies where immediately possible */
539         for (r = 0; r < n_regs; /* empty */) {
540                 ir_node *copy;
541                 ir_node *src = srcs[r];
542                 unsigned old_r;
543                 const arch_register_t *reg;
544
545                 if (src == NULL || n_used[r] > 0) {
546                         ++r;
547                         continue;
548                 }
549
550                 /* create a copy */
551                 copy = be_new_Copy(cls, block, src);
552                 reg = arch_register_for_index(cls, r);
553                 DB((dbg, LEVEL_2, "Copy %+F (from %+F) -> %s\n", copy, src, reg->name));
554                 link_to(copy, src);
555                 use_reg(copy, reg);
556                 sched_add_before(before, copy);
557
558                 /* old register has 1 user less */
559                 reg = arch_get_irn_register(src);
560                 old_r = arch_register_get_index(reg);
561                 assert(n_used[old_r] > 0);
562                 --n_used[old_r];
563                 srcs[r] = NULL;
564
565                 /* advance */
566                 if (old_r < r)
567                         r = old_r;
568                 else
569                         ++r;
570         }
571
572         /* create perms with the rest */
573         for (r = 0; r < n_regs; ++r) {
574                 if (srcs[r] != NULL) {
575                         assert (false && "perm creation not implemented yet");
576                 }
577         }
578 }
579
580 /**
581  * Free regs for values last used.
582  *
583  * @param live_nodes   set of live nodes, will be updated
584  * @param node         the node to consider
585  */
586 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
587 {
588         allocation_info_t *info  = get_allocation_info(node);
589         int                arity = get_irn_arity(node);
590         int                i;
591         for (i = 0; i < arity; ++i) {
592                 ir_node *op;
593
594                 /* check if one operand is the last use */
595                 if (!rbitset_is_set(&info->last_uses, i))
596                         continue;
597
598                 op = get_irn_n(node, i);
599                 free_reg_of_value(op);
600                 ir_nodeset_remove(live_nodes, op);
601         }
602 }
603
604 /**
605  * Enforce constraints at a node by live range splits.
606  *
607  * @param live_nodes  the set of live nodes, might be changed
608  * @param node        the current node
609  */
610 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node)
611 {
612         int arity = get_irn_arity(node);
613         int i, dummy, res;
614         hungarian_problem_t *bp;
615         unsigned l, r, p;
616         unsigned *assignment;
617
618         /* see if any use constraints are not met */
619         bool good = true;
620         for (i = 0; i < arity; ++i) {
621                 ir_node                   *op = get_irn_n(node, i);
622                 const arch_register_req_t *req;
623                 const unsigned            *limited;
624                 unsigned                  r;
625
626                 if (!arch_irn_consider_in_reg_alloc(cls, op))
627                         continue;
628
629                 /* are there any limitations for the i'th operand? */
630                 req = arch_get_register_req(node, i);
631                 if ((req->type & arch_register_req_type_limited) == 0)
632                         continue;
633
634                 limited = req->limited;
635                 r       = get_current_reg(op);
636                 if (!rbitset_is_set(limited, r)) {
637                         /* found an assignement outside the limited set */
638                         good = false;
639                         break;
640                 }
641         }
642
643         if (good)
644                 return;
645
646         /* swap values around */
647         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
648
649         /* add all combinations, then remove not allowed ones */
650         for (l = 0; l < n_regs; ++l) {
651                 if (bitset_is_set(ignore_regs, l)) {
652                         hungarian_add(bp, l, l, 90);
653                         continue;
654                 }
655
656                 for (r = 0; r < n_regs; ++r) {
657                         if (bitset_is_set(ignore_regs, r))
658                                 continue;
659
660                         hungarian_add(bp, l, r, l == r ? 90 : 89);
661                 }
662         }
663
664         for (i = 0; i < arity; ++i) {
665                 ir_node                   *op = get_irn_n(node, i);
666                 const arch_register_req_t *req;
667                 const unsigned            *limited;
668                 unsigned                  current_reg;
669
670                 if (!arch_irn_consider_in_reg_alloc(cls, op))
671                         continue;
672
673                 req = arch_get_register_req(node, i);
674                 if ((req->type & arch_register_req_type_limited) == 0)
675                         continue;
676
677                 limited     = req->limited;
678                 current_reg = get_current_reg(op);
679                 for (r = 0; r < n_regs; ++r) {
680                         if (rbitset_is_set(limited, r))
681                                 continue;
682                         hungarian_remv(bp, current_reg, r);
683                 }
684         }
685
686         hungarian_print_costmatrix(bp, 1);
687         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
688
689         assignment = ALLOCAN(unsigned, n_regs);
690         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
691         assert(res == 0);
692
693         printf("Swap result:");
694         for (p = 0; p < n_regs; ++p) {
695                 printf(" %d", assignment[p]);
696         }
697         printf("\n");
698
699         hungarian_free(bp);
700
701         permutate_values(live_nodes, node, assignment);
702 }
703
704 /**
705  * Walker: assign registers to all nodes of a block that
706  * needs registers from the currently considered register class.
707  */
708 static void allocate_coalesce_block(ir_node *block, void *data)
709 {
710         int                   i;
711         ir_nodeset_t          live_nodes;
712         ir_nodeset_iterator_t iter;
713         ir_node               *node, *start;
714
715         DB((dbg, LEVEL_2, "Allocating in block %+F\n",
716                 block));
717
718         /* clear assignments */
719         memset(assignments, 0, n_regs * sizeof(assignments[0]));
720         ir_nodeset_init(&live_nodes);
721
722         (void) data;
723
724         /* collect live-in nodes and preassigned values */
725         be_lv_foreach(lv, block, be_lv_state_in, i) {
726                 const arch_register_t *reg;
727
728                 node = be_lv_get_irn(lv, block, i);
729                 if (!arch_irn_consider_in_reg_alloc(cls, node))
730                         continue;
731
732                 /* remember that this node is live at the beginning of the block */
733                 ir_nodeset_insert(&live_nodes, node);
734
735                 /* if the node already has a register assigned use it */
736                 /* TODO: the value could already be copied away at this point and be in
737                    another register */
738                 reg = arch_get_irn_register(node);
739                 if (reg != NULL) {
740                         use_reg(node, reg);
741                 }
742         }
743
744         /* handle phis... */
745         node = sched_first(block);
746         for ( ; is_Phi(node); node = sched_next(node)) {
747                 const arch_register_t *reg;
748
749                 if (!arch_irn_consider_in_reg_alloc(cls, node))
750                         continue;
751
752                 /* fill in regs already assigned */
753                 reg = arch_get_irn_register(node);
754                 if (reg != NULL) {
755                         use_reg(node, reg);
756                 } else {
757                         /* TODO: give boni for registers already assigned at the
758                            predecessors */
759                 }
760         }
761         start = node;
762
763         /* assign regs for live-in values */
764         foreach_ir_nodeset(&live_nodes, node, iter) {
765                 const arch_register_t *reg;
766                 reg = arch_get_irn_register(node);
767                 if (reg != NULL)
768                         continue;
769
770                 assign_reg(block, node);
771         }
772
773         /* assign instructions in the block */
774         for (node = start; !sched_is_end(node); node = sched_next(node)) {
775                 int arity = get_irn_arity(node);
776                 int i;
777
778                 /* enforce use constraints */
779                 enforce_constraints(&live_nodes, node);
780
781                 /* exchange values to copied values where needed */
782                 for (i = 0; i < arity; ++i) {
783                         ir_node      *op = get_irn_n(node, i);
784                         assignment_t *assignment;
785
786                         if (!arch_irn_consider_in_reg_alloc(cls, op))
787                                 continue;
788                         assignment = get_current_assignment(op);
789                         assert(assignment != NULL);
790                         if (op != assignment->value) {
791                                 set_irn_n(node, i, assignment->value);
792                         }
793                 }
794
795                 free_last_uses(&live_nodes, node);
796
797                 /* assign output registers */
798                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
799                 if (get_irn_mode(node) == mode_T) {
800                         const ir_edge_t *edge;
801                         foreach_out_edge(node, edge) {
802                                 ir_node *proj = get_edge_src_irn(edge);
803                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
804                                         continue;
805                                 assign_reg(block, proj);
806                         }
807                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
808                         assign_reg(block, node);
809                 }
810         }
811
812         foreach_ir_nodeset(&live_nodes, node, iter) {
813                 free_reg_of_value(node);
814         }
815
816         ir_nodeset_destroy(&live_nodes);
817 }
818
819 /**
820  * Run the register allocator for the current register class.
821  */
822 static void be_straight_alloc_cls(void)
823 {
824         n_regs         = arch_register_class_n_regs(cls);
825         lv             = be_assure_liveness(birg);
826         be_liveness_assure_sets(lv);
827         be_liveness_assure_chk(lv);
828
829         assignments = obstack_alloc(&obst, n_regs * sizeof(assignments[0]));
830
831         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
832         inc_irg_visited(irg);
833
834         DB((dbg, LEVEL_2, "=== Registers in %s ===\n", cls->name));
835
836         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
837         irg_block_walk_graph(irg, NULL, allocate_coalesce_block, NULL);
838
839         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
840 }
841
842 /**
843  * Run the spiller on the current graph.
844  */
845 static void spill(void)
846 {
847         /* make sure all nodes show their real register pressure */
848         BE_TIMER_PUSH(t_ra_constr);
849         be_pre_spill_prepare_constr(birg, cls);
850         BE_TIMER_POP(t_ra_constr);
851
852         /* spill */
853         BE_TIMER_PUSH(t_ra_spill);
854         be_do_spill(birg, cls);
855         BE_TIMER_POP(t_ra_spill);
856
857         BE_TIMER_PUSH(t_ra_spill_apply);
858         check_for_memory_operands(irg);
859         BE_TIMER_POP(t_ra_spill_apply);
860 }
861
862 /**
863  * The straight register allocator for a whole procedure.
864  */
865 static void be_straight_alloc(be_irg_t *new_birg)
866 {
867         const arch_env_t *arch_env = new_birg->main_env->arch_env;
868         int   n_cls                = arch_env_get_n_reg_class(arch_env);
869         int   c;
870
871         obstack_init(&obst);
872
873         birg      = new_birg;
874         irg       = be_get_birg_irg(birg);
875         execfreqs = birg->exec_freq;
876
877         /* TODO: extract some of the stuff from bechordal allocator, like
878          * statistics, time measurements, etc. and use them here too */
879
880         for (c = 0; c < n_cls; ++c) {
881                 cls = arch_env_get_reg_class(arch_env, c);
882                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
883                         continue;
884
885                 stat_ev_ctx_push_str("bestraight_cls", cls->name);
886
887                 n_regs      = cls->n_regs;
888                 ignore_regs = bitset_malloc(n_regs);
889                 be_put_ignore_regs(birg, cls, ignore_regs);
890
891                 spill();
892
893                 /* verify schedule and register pressure */
894                 BE_TIMER_PUSH(t_verify);
895                 if (birg->main_env->options->vrfy_option == BE_CH_VRFY_WARN) {
896                         be_verify_schedule(birg);
897                         be_verify_register_pressure(birg, cls, irg);
898                 } else if (birg->main_env->options->vrfy_option == BE_CH_VRFY_ASSERT) {
899                         assert(be_verify_schedule(birg) && "Schedule verification failed");
900                         assert(be_verify_register_pressure(birg, cls, irg)
901                                 && "Register pressure verification failed");
902                 }
903                 BE_TIMER_POP(t_verify);
904
905                 BE_TIMER_PUSH(t_ra_color);
906                 be_straight_alloc_cls();
907                 BE_TIMER_POP(t_ra_color);
908
909                 bitset_free(ignore_regs);
910
911                 /* TODO: dump intermediate results */
912
913                 stat_ev_ctx_pop("bestraight_cls");
914         }
915
916         obstack_free(&obst, NULL);
917 }
918
919 static be_ra_t be_ra_straight = {
920         be_straight_alloc,
921 };
922
923 /**
924  * Initializes this module.
925  */
926 void be_init_straight_alloc(void)
927 {
928         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
929
930         be_register_allocator("straight", &be_ra_straight);
931 }
932
933 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);