- removed C99 features
[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
38  *    registers with high preferences. When register constraints are not met,
39  *    add copies and split live-ranges.
40  *
41  * TODO:
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
47  */
48 #include "config.h"
49
50 #include <float.h>
51 #include <stdbool.h>
52
53 #include "error.h"
54 #include "execfreq.h"
55 #include "ircons.h"
56 #include "irdom.h"
57 #include "iredges_t.h"
58 #include "irgraph_t.h"
59 #include "irgwalk.h"
60 #include "irnode_t.h"
61 #include "obst.h"
62 #include "raw_bitset.h"
63
64 #include "beabi.h"
65 #include "bechordal_t.h"
66 #include "be.h"
67 #include "beirg.h"
68 #include "belive_t.h"
69 #include "bemodule.h"
70 #include "benode_t.h"
71 #include "bera.h"
72 #include "besched.h"
73 #include "bespill.h"
74 #include "bespillutil.h"
75 #include "beverify.h"
76
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 AFF_SHOULD_BE_SAME 0.5f
83 #define AFF_PHI            1.0f
84 #define SPLIT_DELTA        1.0f
85
86 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
87
88 static struct obstack               obst;
89 static be_irg_t                    *birg;
90 static ir_graph                    *irg;
91 static const arch_register_class_t *cls;
92 static const arch_register_req_t   *default_cls_req;
93 static be_lv_t                     *lv;
94 static const ir_exec_freq          *execfreqs;
95 static unsigned                     n_regs;
96 static unsigned                    *normal_regs;
97
98 /** currently active assignments (while processing a basic block)
99  * maps registers to values(their current copies) */
100 static ir_node **assignments;
101
102 /**
103  * allocation information: last_uses, register preferences
104  * the information is per firm-node.
105  */
106 struct allocation_info_t {
107         unsigned  last_uses;      /**< bitset indicating last uses (input pos) */
108         ir_node  *current_value;  /**< copy of the value that should be used */
109         ir_node  *original_value; /**< for copies point to original value */
110         float     prefs[0];       /**< register preferences */
111 };
112 typedef struct allocation_info_t allocation_info_t;
113
114 /** helper datastructure used when sorting register preferences */
115 struct reg_pref_t {
116         unsigned num;
117         float    pref;
118 };
119 typedef struct reg_pref_t reg_pref_t;
120
121 /** per basic-block information */
122 struct block_info_t {
123         bool     processed;       /**< indicate wether block is processed */
124         ir_node *assignments[0];  /**< register assignments at end of block */
125 };
126 typedef struct block_info_t block_info_t;
127
128 /**
129  * Get the allocation info for a node.
130  * The info is allocated on the first visit of a node.
131  */
132 static allocation_info_t *get_allocation_info(ir_node *node)
133 {
134         allocation_info_t *info;
135         if (!irn_visited_else_mark(node)) {
136                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->prefs[0]);
137                 info = obstack_alloc(&obst, size);
138                 memset(info, 0, size);
139                 info->current_value  = node;
140                 info->original_value = node;
141                 set_irn_link(node, info);
142         } else {
143                 info = get_irn_link(node);
144         }
145
146         return info;
147 }
148
149 /**
150  * Get allocation information for a basic block
151  */
152 static block_info_t *get_block_info(ir_node *block)
153 {
154         block_info_t *info;
155
156         assert(is_Block(block));
157         if (!irn_visited_else_mark(block)) {
158                 size_t size = sizeof(info[0]) + n_regs * sizeof(info->assignments[0]);
159                 info = obstack_alloc(&obst, size);
160                 memset(info, 0, size);
161                 set_irn_link(block, info);
162         } else {
163                 info = get_irn_link(block);
164         }
165
166         return info;
167 }
168
169 /**
170  * Get default register requirement for the current register class
171  */
172 static const arch_register_req_t *get_default_req_current_cls(void)
173 {
174         if (default_cls_req == NULL) {
175                 struct obstack      *obst = get_irg_obstack(irg);
176                 arch_register_req_t *req  = obstack_alloc(obst, sizeof(*req));
177                 memset(req, 0, sizeof(*req));
178
179                 req->type = arch_register_req_type_normal;
180                 req->cls  = cls;
181
182                 default_cls_req = req;
183         }
184         return default_cls_req;
185 }
186
187 /**
188  * Link the allocation info of a node to a copy.
189  * Afterwards, both nodes uses the same allocation info.
190  * Copy must not have an allocation info assigned yet.
191  *
192  * @param copy   the node that gets the allocation info assigned
193  * @param value  the original node
194  */
195 static void mark_as_copy_of(ir_node *copy, ir_node *value)
196 {
197         ir_node           *original;
198         allocation_info_t *info      = get_allocation_info(value);
199         allocation_info_t *copy_info = get_allocation_info(copy);
200
201         /* find original value */
202         original = info->original_value;
203         if (original != value) {
204                 info = get_allocation_info(original);
205         }
206
207         assert(info->original_value == original);
208         info->current_value = copy;
209
210         /* the copy should not be linked to something else yet */
211         assert(copy_info->original_value == copy);
212         /* copy over allocation preferences */
213         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
214         copy_info->original_value = original;
215 }
216
217 /**
218  * Calculate the penalties for every register on a node and its live neighbors.
219  *
220  * @param live_nodes  the set of live nodes at the current position, may be NULL
221  * @param penalty     the penalty to subtract from
222  * @param limited     a raw bitset containing the limited set for the node
223  * @param node        the node
224  */
225 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
226                                       float penalty, const unsigned* limited,
227                                       ir_node *node)
228 {
229         ir_nodeset_iterator_t iter;
230         unsigned              r;
231         allocation_info_t     *info = get_allocation_info(node);
232         ir_node               *neighbor;
233
234         /* give penalty for all forbidden regs */
235         for (r = 0; r < n_regs; ++r) {
236                 if (rbitset_is_set(limited, r))
237                         continue;
238
239                 info->prefs[r] -= penalty;
240         }
241
242         /* all other live values should get a penalty for allowed regs */
243         if (live_nodes == NULL)
244                 return;
245
246         /* TODO: reduce penalty if there are multiple allowed registers... */
247         penalty *= NEIGHBOR_FACTOR;
248         foreach_ir_nodeset(live_nodes, neighbor, iter) {
249                 allocation_info_t *neighbor_info;
250
251                 /* TODO: if op is used on multiple inputs we might not do a
252                  * continue here */
253                 if (neighbor == node)
254                         continue;
255
256                 neighbor_info = get_allocation_info(neighbor);
257                 for (r = 0; r < n_regs; ++r) {
258                         if (!rbitset_is_set(limited, r))
259                                 continue;
260
261                         neighbor_info->prefs[r] -= penalty;
262                 }
263         }
264 }
265
266 /**
267  * Calculate the preferences of a definition for the current register class.
268  * If the definition uses a limited set of registers, reduce the preferences
269  * for the limited register on the node and its neighbors.
270  *
271  * @param live_nodes  the set of live nodes at the current node
272  * @param weight      the weight
273  * @param node        the current node
274  */
275 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
276                        ir_node *node)
277 {
278         const arch_register_req_t *req;
279
280         if (get_irn_mode(node) == mode_T) {
281                 const ir_edge_t *edge;
282                 foreach_out_edge(node, edge) {
283                         ir_node *proj = get_edge_src_irn(edge);
284                         check_defs(live_nodes, weight, proj);
285                 }
286                 return;
287         }
288
289         if (!arch_irn_consider_in_reg_alloc(cls, node))
290                 return;
291
292         req = arch_get_register_req_out(node);
293         if (req->type & arch_register_req_type_limited) {
294                 const unsigned *limited = req->limited;
295                 float           penalty = weight * DEF_FACTOR;
296                 give_penalties_for_limits(live_nodes, penalty, limited, node);
297         }
298
299         if (req->type & arch_register_req_type_should_be_same) {
300                 ir_node           *insn  = skip_Proj(node);
301                 allocation_info_t *info  = get_allocation_info(node);
302                 int                arity = get_irn_arity(insn);
303                 int                i;
304
305                 float factor = 1.0f / rbitset_popcnt(&req->other_same, arity);
306                 for (i = 0; i < arity; ++i) {
307                         ir_node           *op;
308                         unsigned           r;
309                         allocation_info_t *op_info;
310
311                         if (!rbitset_is_set(&req->other_same, i))
312                                 continue;
313
314                         op = get_irn_n(insn, i);
315
316                         /* if we the value at the should_be_same input doesn't die at the
317                          * node, then it is no use to propagate the constraints (since a
318                          * copy will emerge anyway) */
319                         if (ir_nodeset_contains(live_nodes, op))
320                                 continue;
321
322                         op_info = get_allocation_info(op);
323                         for (r = 0; r < n_regs; ++r) {
324                                 op_info->prefs[r] += info->prefs[r] * factor;
325                         }
326                 }
327         }
328 }
329
330 /**
331  * Walker: Runs an a block calculates the preferences for any
332  * node and every register from the considered register class.
333  */
334 static void analyze_block(ir_node *block, void *data)
335 {
336         float         weight = get_block_execfreq(execfreqs, block);
337         ir_nodeset_t  live_nodes;
338         ir_node      *node;
339         (void) data;
340
341         ir_nodeset_init(&live_nodes);
342         be_liveness_end_of_block(lv, cls, block, &live_nodes);
343
344         sched_foreach_reverse(block, node) {
345                 allocation_info_t *info;
346                 int                i;
347                 int                arity;
348
349                 if (is_Phi(node))
350                         break;
351
352                 check_defs(&live_nodes, weight, node);
353
354                 /* mark last uses */
355                 arity = get_irn_arity(node);
356
357                 /* the allocation info node currently only uses 1 unsigned value
358                    to mark last used inputs. So we will fail for a node with more than
359                    32 inputs. */
360                 if (arity >= (int) sizeof(unsigned) * 8) {
361                         panic("Node with more than %d inputs not supported yet",
362                                         (int) sizeof(unsigned) * 8);
363                 }
364
365                 info = get_allocation_info(node);
366                 for (i = 0; i < arity; ++i) {
367                         ir_node *op = get_irn_n(node, i);
368                         if (!arch_irn_consider_in_reg_alloc(cls, op))
369                                 continue;
370
371                         /* last usage of a value? */
372                         if (!ir_nodeset_contains(&live_nodes, op)) {
373                                 rbitset_set(&info->last_uses, i);
374                         }
375                 }
376
377                 be_liveness_transfer(cls, node, &live_nodes);
378
379                 /* update weights based on usage constraints */
380                 for (i = 0; i < arity; ++i) {
381                         const arch_register_req_t *req;
382                         const unsigned            *limited;
383                         ir_node                   *op = get_irn_n(node, i);
384
385                         if (!arch_irn_consider_in_reg_alloc(cls, op))
386                                 continue;
387
388                         req = arch_get_register_req(node, i);
389                         if (!(req->type & arch_register_req_type_limited))
390                                 continue;
391
392                         limited = req->limited;
393                         give_penalties_for_limits(&live_nodes, weight * USE_FACTOR, limited,
394                                                   op);
395                 }
396         }
397
398         ir_nodeset_destroy(&live_nodes);
399 }
400
401 /**
402  * Assign register reg to the given node.
403  *
404  * @param node  the node
405  * @param reg   the register
406  */
407 static void use_reg(ir_node *node, const arch_register_t *reg)
408 {
409         unsigned r = arch_register_get_index(reg);
410         assignments[r] = node;
411         arch_set_irn_register(node, reg);
412 }
413
414 static void free_reg_of_value(ir_node *node)
415 {
416         const arch_register_t *reg;
417         unsigned               r;
418
419         if (!arch_irn_consider_in_reg_alloc(cls, node))
420                 return;
421
422         reg        = arch_get_irn_register(node);
423         r          = arch_register_get_index(reg);
424         /* assignment->value may be NULL if a value is used at 2 inputs
425            so it gets freed twice. */
426         assert(assignments[r] == node || assignments[r] == NULL);
427         assignments[r] = NULL;
428 }
429
430 /**
431  * Compare two register preferences in decreasing order.
432  */
433 static int compare_reg_pref(const void *e1, const void *e2)
434 {
435         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
436         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
437         if (rp1->pref < rp2->pref)
438                 return 1;
439         if (rp1->pref > rp2->pref)
440                 return -1;
441         return 0;
442 }
443
444 static void fill_sort_candidates(reg_pref_t *regprefs,
445                                  const allocation_info_t *info)
446 {
447         unsigned r;
448
449         for (r = 0; r < n_regs; ++r) {
450                 float pref = info->prefs[r];
451                 regprefs[r].num  = r;
452                 regprefs[r].pref = pref;
453         }
454         /* TODO: use a stable sort here to avoid unnecessary register jumping */
455         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
456 }
457
458 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
459                                  float pref, float pref_delta,
460                                  unsigned *output_regs)
461 {
462         const arch_register_t *reg;
463         ir_node               *block;
464         ir_node               *copy;
465         unsigned               r;
466         unsigned               i;
467         allocation_info_t     *info = get_allocation_info(to_split);
468         reg_pref_t            *prefs;
469         float                  delta;
470
471         (void) pref;
472
473         /* find the best free position where we could move to */
474         prefs = ALLOCAN(reg_pref_t, n_regs);
475         fill_sort_candidates(prefs, info);
476         for (i = 0; i < n_regs; ++i) {
477                 r = prefs[i].num;
478                 if (!rbitset_is_set(normal_regs, r))
479                         continue;
480                 if (rbitset_is_set(output_regs, r))
481                         continue;
482                 if (assignments[r] == NULL)
483                         break;
484         }
485         if (i >= n_regs) {
486                 return false;
487         }
488         /* TODO: use execfreq somehow... */
489         delta = pref_delta + prefs[i].pref;
490         if (delta < SPLIT_DELTA) {
491                 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
492                     delta));
493                 return false;
494         }
495
496         reg   = arch_register_for_index(cls, r);
497         block = get_nodes_block(before);
498         copy = be_new_Copy(cls, block, to_split);
499         mark_as_copy_of(copy, to_split);
500         free_reg_of_value(to_split);
501         use_reg(copy, reg);
502         sched_add_before(before, copy);
503
504         DB((dbg, LEVEL_3,
505             "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
506             copy, to_split, reg->name, before, delta));
507         return true;
508 }
509
510 /**
511  * Determine and assign a register for node @p node
512  */
513 static void assign_reg(const ir_node *block, ir_node *node,
514                        unsigned *output_regs)
515 {
516         const arch_register_t     *reg;
517         allocation_info_t         *info;
518         const arch_register_req_t *req;
519         reg_pref_t                *reg_prefs;
520         ir_node                   *in_node;
521         unsigned                   i;
522         const unsigned            *allowed_regs;
523         unsigned                   r;
524
525         assert(arch_irn_consider_in_reg_alloc(cls, node));
526
527         /* preassigned register? */
528         reg = arch_get_irn_register(node);
529         if (reg != NULL) {
530                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
531                 use_reg(node, reg);
532                 return;
533         }
534
535         /* give should_be_same boni */
536         info = get_allocation_info(node);
537         req  = arch_get_register_req_out(node);
538
539         in_node = skip_Proj(node);
540         if (req->type & arch_register_req_type_should_be_same) {
541                 float weight = get_block_execfreq(execfreqs, block);
542                 int   arity  = get_irn_arity(in_node);
543                 int   i;
544
545                 assert(arity <= (int) sizeof(req->other_same) * 8);
546                 for (i = 0; i < arity; ++i) {
547                         ir_node               *in;
548                         const arch_register_t *reg;
549                         unsigned               r;
550                         if (!rbitset_is_set(&req->other_same, i))
551                                 continue;
552
553                         in  = get_irn_n(in_node, i);
554                         reg = arch_get_irn_register(in);
555                         assert(reg != NULL);
556                         r = arch_register_get_index(reg);
557
558                         /* if the value didn't die here then we should not propagate the
559                          * should_be_same info */
560                         if (assignments[r] == in)
561                                 continue;
562
563                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
564                 }
565         }
566
567         /* create list of register candidates and sort by their preference */
568         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
569         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
570         fill_sort_candidates(reg_prefs, info);
571         for (i = 0; i < n_regs; ++i) {
572                 unsigned num = reg_prefs[i].num;
573                 const arch_register_t *reg;
574
575                 if (!rbitset_is_set(normal_regs, num))
576                         continue;
577
578                 reg = arch_register_for_index(cls, num);
579                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
580         }
581         DB((dbg, LEVEL_2, "\n"));
582
583         allowed_regs = normal_regs;
584         if (req->type & arch_register_req_type_limited) {
585                 allowed_regs = req->limited;
586         }
587
588         for (i = 0; i < n_regs; ++i) {
589                 r = reg_prefs[i].num;
590                 if (!rbitset_is_set(allowed_regs, r))
591                         continue;
592                 if (assignments[r] == NULL)
593                         break;
594                 if (!is_Phi(node)) {
595                         float    pref   = reg_prefs[i].pref;
596                         float    delta  = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
597                         ir_node *before = skip_Proj(node);
598                         bool     res    = try_optimistic_split(assignments[r], before,
599                                                                pref, delta,
600                                                                output_regs);
601                         if (res)
602                                 break;
603                 }
604         }
605         if (i >= n_regs) {
606                 panic("No register left for %+F\n", node);
607         }
608
609         reg = arch_register_for_index(cls, r);
610         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
611         use_reg(node, reg);
612 }
613
614 /**
615  * Add an permutation in front of a node and change the assignments
616  * due to this permutation.
617  *
618  * To understand this imagine a permutation like this:
619  *
620  * 1 -> 2
621  * 2 -> 3
622  * 3 -> 1, 5
623  * 4 -> 6
624  * 5
625  * 6
626  * 7 -> 7
627  *
628  * First we count how many destinations a single value has. At the same time
629  * we can be sure that each destination register has at most 1 source register
630  * (it can have 0 which means we don't care what value is in it).
631  * We ignore all fullfilled permuations (like 7->7)
632  * In a first pass we create as much copy instructions as possible as they
633  * are generally cheaper than exchanges. We do this by counting into how many
634  * destinations a register has to be copied (in the example it's 2 for register
635  * 3, or 1 for the registers 1,2,4 and 7).
636  * We can then create a copy into every destination register when the usecount
637  * of that register is 0 (= noone else needs the value in the register).
638  *
639  * After this step we should have cycles left. We implement a cyclic permutation
640  * of n registers with n-1 transpositions.
641  *
642  * @param live_nodes   the set of live nodes, updated due to live range split
643  * @param before       the node before we add the permutation
644  * @param permutation  the permutation array indices are the destination
645  *                     registers, the values in the array are the source
646  *                     registers.
647  */
648 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
649                              unsigned *permutation)
650 {
651         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
652         ir_node   *block;
653         unsigned   r;
654
655         /* determine how often each source register needs to be read */
656         for (r = 0; r < n_regs; ++r) {
657                 unsigned  old_reg = permutation[r];
658                 ir_node  *value;
659
660                 value = assignments[old_reg];
661                 if (value == NULL) {
662                         /* nothing to do here, reg is not live. Mark it as fixpoint
663                          * so we ignore it in the next steps */
664                         permutation[r] = r;
665                         continue;
666                 }
667
668                 ++n_used[old_reg];
669         }
670
671         block = get_nodes_block(before);
672
673         /* step1: create copies where immediately possible */
674         for (r = 0; r < n_regs; /* empty */) {
675                 ir_node *copy;
676                 ir_node *src;
677                 const arch_register_t *reg;
678                 unsigned               old_r = permutation[r];
679
680                 /* - no need to do anything for fixed points.
681                    - we can't copy if the value in the dest reg is still needed */
682                 if (old_r == r || n_used[r] > 0) {
683                         ++r;
684                         continue;
685                 }
686
687                 /* create a copy */
688                 src  = assignments[old_r];
689                 copy = be_new_Copy(cls, block, src);
690                 sched_add_before(before, copy);
691                 reg = arch_register_for_index(cls, r);
692                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
693                     copy, src, before, reg->name));
694                 mark_as_copy_of(copy, src);
695                 use_reg(copy, reg);
696
697                 if (live_nodes != NULL) {
698                         ir_nodeset_insert(live_nodes, copy);
699                 }
700
701                 /* old register has 1 user less, permutation is resolved */
702                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
703                 permutation[r] = r;
704
705                 assert(n_used[old_r] > 0);
706                 --n_used[old_r];
707                 if (n_used[old_r] == 0) {
708                         if (live_nodes != NULL) {
709                                 ir_nodeset_remove(live_nodes, src);
710                         }
711                         free_reg_of_value(src);
712                 }
713
714                 /* advance or jump back (if this copy enabled another copy) */
715                 if (old_r < r && n_used[old_r] == 0) {
716                         r = old_r;
717                 } else {
718                         ++r;
719                 }
720         }
721
722         /* at this point we only have "cycles" left which we have to resolve with
723          * perm instructions
724          * TODO: if we have free registers left, then we should really use copy
725          * instructions for any cycle longer than 2 registers...
726          * (this is probably architecture dependent, there might be archs where
727          *  copies are preferable even for 2-cycles) */
728
729         /* create perms with the rest */
730         for (r = 0; r < n_regs; /* empty */) {
731                 const arch_register_t *reg;
732                 unsigned  old_r = permutation[r];
733                 unsigned  r2;
734                 ir_node  *in[2];
735                 ir_node  *perm;
736                 ir_node  *proj0;
737                 ir_node  *proj1;
738
739                 if (old_r == r) {
740                         ++r;
741                         continue;
742                 }
743
744                 /* we shouldn't have copies from 1 value to multiple destinations left*/
745                 assert(n_used[old_r] == 1);
746
747                 /* exchange old_r and r2; after that old_r is a fixed point */
748                 r2 = permutation[old_r];
749
750                 in[0] = assignments[r2];
751                 in[1] = assignments[old_r];
752                 perm = be_new_Perm(cls, block, 2, in);
753                 sched_add_before(before, perm);
754                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
755                     perm, in[0], in[1], before));
756
757                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
758                 mark_as_copy_of(proj0, in[0]);
759                 reg = arch_register_for_index(cls, old_r);
760                 use_reg(proj0, reg);
761
762                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
763                 mark_as_copy_of(proj1, in[1]);
764                 reg = arch_register_for_index(cls, r2);
765                 use_reg(proj1, reg);
766
767                 /* 1 value is now in the correct register */
768                 permutation[old_r] = old_r;
769                 /* the source of r changed to r2 */
770                 permutation[r] = r2;
771
772                 /* if we have reached a fixpoint update data structures */
773                 if (live_nodes != NULL) {
774                         ir_nodeset_remove(live_nodes, in[0]);
775                         ir_nodeset_remove(live_nodes, in[1]);
776                         ir_nodeset_remove(live_nodes, proj0);
777                         ir_nodeset_insert(live_nodes, proj1);
778                 }
779         }
780
781 #ifdef DEBUG_libfirm
782         /* now we should only have fixpoints left */
783         for (r = 0; r < n_regs; ++r) {
784                 assert(permutation[r] == r);
785         }
786 #endif
787 }
788
789 /**
790  * Free regs for values last used.
791  *
792  * @param live_nodes   set of live nodes, will be updated
793  * @param node         the node to consider
794  */
795 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
796 {
797         allocation_info_t     *info      = get_allocation_info(node);
798         const unsigned        *last_uses = &info->last_uses;
799         int                    arity     = get_irn_arity(node);
800         int                    i;
801
802         for (i = 0; i < arity; ++i) {
803                 ir_node *op;
804
805                 /* check if one operand is the last use */
806                 if (!rbitset_is_set(last_uses, i))
807                         continue;
808
809                 op = get_irn_n(node, i);
810                 free_reg_of_value(op);
811                 ir_nodeset_remove(live_nodes, op);
812         }
813 }
814
815 /**
816  * change inputs of a node to the current value (copies/perms)
817  */
818 static void rewire_inputs(ir_node *node)
819 {
820         int i;
821         int arity = get_irn_arity(node);
822
823         for (i = 0; i < arity; ++i) {
824                 ir_node           *op = get_irn_n(node, i);
825                 allocation_info_t *info;
826
827                 if (!arch_irn_consider_in_reg_alloc(cls, op))
828                         continue;
829
830                 info = get_allocation_info(op);
831                 info = get_allocation_info(info->original_value);
832                 if (info->current_value != op) {
833                         set_irn_n(node, i, info->current_value);
834                 }
835         }
836 }
837
838 /**
839  * Create a bitset of registers occupied with value living through an
840  * instruction
841  */
842 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
843 {
844         const allocation_info_t *info = get_allocation_info(node);
845         unsigned r;
846         int i;
847         int arity;
848
849         /* mark all used registers as potentially live-through */
850         for (r = 0; r < n_regs; ++r) {
851                 if (assignments[r] == NULL)
852                         continue;
853                 if (!rbitset_is_set(normal_regs, r))
854                         continue;
855
856                 rbitset_set(bitset, r);
857         }
858
859         /* remove registers of value dying at the instruction */
860         arity = get_irn_arity(node);
861         for (i = 0; i < arity; ++i) {
862                 ir_node               *op;
863                 const arch_register_t *reg;
864
865                 if (!rbitset_is_set(&info->last_uses, i))
866                         continue;
867
868                 op  = get_irn_n(node, i);
869                 reg = arch_get_irn_register(op);
870                 rbitset_clear(bitset, arch_register_get_index(reg));
871         }
872 }
873
874 /**
875  * Enforce constraints at a node by live range splits.
876  *
877  * @param  live_nodes  the set of live nodes, might be changed
878  * @param  node        the current node
879  */
880 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
881                                 unsigned *output_regs)
882 {
883         int arity = get_irn_arity(node);
884         int i, dummy, res;
885         hungarian_problem_t *bp;
886         unsigned l, r;
887         unsigned *assignment;
888
889         /* construct a list of register occupied by live-through values */
890         unsigned *live_through_regs = NULL;
891
892         /* see if any use constraints are not met */
893         bool good = true;
894         for (i = 0; i < arity; ++i) {
895                 ir_node                   *op = get_irn_n(node, i);
896                 const arch_register_t     *reg;
897                 const arch_register_req_t *req;
898                 const unsigned            *limited;
899                 unsigned                  r;
900
901                 if (!arch_irn_consider_in_reg_alloc(cls, op))
902                         continue;
903
904                 /* are there any limitations for the i'th operand? */
905                 req = arch_get_register_req(node, i);
906                 if (!(req->type & arch_register_req_type_limited))
907                         continue;
908
909                 limited = req->limited;
910                 reg     = arch_get_irn_register(op);
911                 r       = arch_register_get_index(reg);
912                 if (!rbitset_is_set(limited, r)) {
913                         /* found an assignment outside the limited set */
914                         good = false;
915                         break;
916                 }
917         }
918
919         /* is any of the live-throughs using a constrained output register? */
920         if (get_irn_mode(node) == mode_T) {
921                 const ir_edge_t *edge;
922
923                 foreach_out_edge(node, edge) {
924                         ir_node *proj = get_edge_src_irn(edge);
925                         const arch_register_req_t *req;
926
927                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
928                                 continue;
929
930                         req = arch_get_register_req_out(proj);
931                         if (!(req->type & arch_register_req_type_limited))
932                                 continue;
933
934                         if (live_through_regs == NULL) {
935                                 rbitset_alloca(live_through_regs, n_regs);
936                                 determine_live_through_regs(live_through_regs, node);
937                         }
938
939                         rbitset_or(output_regs, req->limited, n_regs);
940                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
941                                 good = false;
942                         }
943                 }
944         } else {
945                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
946                         const arch_register_req_t *req = arch_get_register_req_out(node);
947                         if (req->type & arch_register_req_type_limited) {
948                                 rbitset_alloca(live_through_regs, n_regs);
949                                 determine_live_through_regs(live_through_regs, node);
950                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
951                                         good = false;
952                                         rbitset_or(output_regs, req->limited, n_regs);
953                                 }
954                         }
955                 }
956         }
957
958         if (good)
959                 return;
960
961         /* create these arrays if we haven't yet */
962         if (live_through_regs == NULL) {
963                 rbitset_alloca(live_through_regs, n_regs);
964         }
965
966         /* at this point we have to construct a bipartite matching problem to see
967          * which values should go to which registers
968          * Note: We're building the matrix in "reverse" - source registers are
969          *       right, destinations left because this will produce the solution
970          *       in the format required for permute_values.
971          */
972         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
973
974         /* add all combinations, then remove not allowed ones */
975         for (l = 0; l < n_regs; ++l) {
976                 if (!rbitset_is_set(normal_regs, l)) {
977                         hungarian_add(bp, l, l, 1);
978                         continue;
979                 }
980
981                 for (r = 0; r < n_regs; ++r) {
982                         if (!rbitset_is_set(normal_regs, r))
983                                 continue;
984                         /* livethrough values may not use constrainted output registers */
985                         if (rbitset_is_set(live_through_regs, l)
986                                         && rbitset_is_set(output_regs, r))
987                                 continue;
988
989                         hungarian_add(bp, r, l, l == r ? 9 : 8);
990                 }
991         }
992
993         for (i = 0; i < arity; ++i) {
994                 ir_node                   *op = get_irn_n(node, i);
995                 const arch_register_t     *reg;
996                 const arch_register_req_t *req;
997                 const unsigned            *limited;
998                 unsigned                   current_reg;
999
1000                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1001                         continue;
1002
1003                 req = arch_get_register_req(node, i);
1004                 if (!(req->type & arch_register_req_type_limited))
1005                         continue;
1006
1007                 limited     = req->limited;
1008                 reg         = arch_get_irn_register(op);
1009                 current_reg = arch_register_get_index(reg);
1010                 for (r = 0; r < n_regs; ++r) {
1011                         if (rbitset_is_set(limited, r))
1012                                 continue;
1013                         hungarian_remv(bp, r, current_reg);
1014                 }
1015         }
1016
1017         //hungarian_print_costmatrix(bp, 1);
1018         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1019
1020         assignment = ALLOCAN(unsigned, n_regs);
1021         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1022         assert(res == 0);
1023
1024 #if 0
1025         fprintf(stderr, "Swap result:");
1026         for (i = 0; i < (int) n_regs; ++i) {
1027                 fprintf(stderr, " %d", assignment[i]);
1028         }
1029         fprintf(stderr, "\n");
1030 #endif
1031
1032         hungarian_free(bp);
1033
1034         permute_values(live_nodes, node, assignment);
1035 }
1036
1037 /** test wether a node @p n is a copy of the value of node @p of */
1038 static bool is_copy_of(ir_node *value, ir_node *test_value)
1039 {
1040         allocation_info_t *test_info;
1041         allocation_info_t *info;
1042
1043         if (value == test_value)
1044                 return true;
1045
1046         info      = get_allocation_info(value);
1047         test_info = get_allocation_info(test_value);
1048         return test_info->original_value == info->original_value;
1049 }
1050
1051 /**
1052  * find a value in the end-assignment of a basic block
1053  * @returns the index into the assignment array if found
1054  *          -1 if not found
1055  */
1056 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1057 {
1058         unsigned   r;
1059         ir_node  **assignments = info->assignments;
1060         for (r = 0; r < n_regs; ++r) {
1061                 ir_node *a_value = assignments[r];
1062
1063                 if (a_value == NULL)
1064                         continue;
1065                 if (is_copy_of(a_value, value))
1066                         return (int) r;
1067         }
1068
1069         return -1;
1070 }
1071
1072 /**
1073  * Create the necessary permutations at the end of a basic block to fullfill
1074  * the register assignment for phi-nodes in the next block
1075  */
1076 static void add_phi_permutations(ir_node *block, int p)
1077 {
1078         unsigned   r;
1079         unsigned  *permutation;
1080         ir_node  **old_assignments;
1081         bool       need_permutation;
1082         ir_node   *node;
1083         ir_node   *pred = get_Block_cfgpred_block(block, p);
1084
1085         block_info_t *pred_info = get_block_info(pred);
1086
1087         /* predecessor not processed yet? nothing to do */
1088         if (!pred_info->processed)
1089                 return;
1090
1091         permutation = ALLOCAN(unsigned, n_regs);
1092         for (r = 0; r < n_regs; ++r) {
1093                 permutation[r] = r;
1094         }
1095
1096         /* check phi nodes */
1097         need_permutation = false;
1098         node = sched_first(block);
1099         for ( ; is_Phi(node); node = sched_next(node)) {
1100                 const arch_register_t *reg;
1101                 int                    regn;
1102                 int                    a;
1103                 ir_node               *op;
1104
1105                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1106                         continue;
1107
1108                 op = get_Phi_pred(node, p);
1109                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1110                         continue;
1111
1112                 a  = find_value_in_block_info(pred_info, op);
1113                 assert(a >= 0);
1114
1115                 reg  = arch_get_irn_register(node);
1116                 regn = arch_register_get_index(reg);
1117                 if (regn != a) {
1118                         permutation[regn] = a;
1119                         need_permutation  = true;
1120                 }
1121         }
1122
1123         if (need_permutation) {
1124                 /* permute values at end of predecessor */
1125                 old_assignments = assignments;
1126                 assignments     = pred_info->assignments;
1127                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1128                                                  permutation);
1129                 assignments = old_assignments;
1130         }
1131
1132         /* change phi nodes to use the copied values */
1133         node = sched_first(block);
1134         for ( ; is_Phi(node); node = sched_next(node)) {
1135                 int      a;
1136                 ir_node *op;
1137
1138                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1139                         continue;
1140
1141                 op = get_Phi_pred(node, p);
1142                 /* no need to do anything for Unknown inputs */
1143                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1144                         continue;
1145
1146                 /* we have permuted all values into the correct registers so we can
1147                    simply query which value occupies the phis register in the
1148                    predecessor */
1149                 a  = arch_register_get_index(arch_get_irn_register(node));
1150                 op = pred_info->assignments[a];
1151                 set_Phi_pred(node, p, op);
1152         }
1153 }
1154
1155 /**
1156  * Set preferences for a phis register based on the registers used on the
1157  * phi inputs.
1158  */
1159 static void adapt_phi_prefs(ir_node *phi)
1160 {
1161         int i;
1162         int arity = get_irn_arity(phi);
1163         ir_node           *block = get_nodes_block(phi);
1164         allocation_info_t *info  = get_allocation_info(phi);
1165
1166         for (i = 0; i < arity; ++i) {
1167                 ir_node               *op  = get_irn_n(phi, i);
1168                 const arch_register_t *reg = arch_get_irn_register(op);
1169                 ir_node               *pred;
1170                 ir_node               *pred_block;
1171                 block_info_t          *pred_block_info;
1172                 float                  weight;
1173                 unsigned               r;
1174
1175                 if (reg == NULL)
1176                         continue;
1177                 /* we only give the bonus if the predecessor already has register
1178                  * assigned, otherwise we only see a dummy value
1179                  * and any conclusions about its register are useless */
1180                 pred_block = get_Block_cfgpred_block(block, i);
1181                 pred_block_info = get_block_info(pred_block);
1182                 if (!pred_block_info->processed)
1183                         continue;
1184
1185                 /* give bonus for already assigned register */
1186                 pred   = get_Block_cfgpred_block(block, i);
1187                 weight = get_block_execfreq(execfreqs, pred);
1188                 r      = arch_register_get_index(reg);
1189                 info->prefs[r] += weight * AFF_PHI;
1190         }
1191 }
1192
1193 /**
1194  * After a phi has been assigned a register propagate preference inputs
1195  * to the phi inputs.
1196  */
1197 static void propagate_phi_register(ir_node *phi, unsigned r)
1198 {
1199         int                    i;
1200         ir_node               *block = get_nodes_block(phi);
1201         int                    arity = get_irn_arity(phi);
1202
1203         for (i = 0; i < arity; ++i) {
1204                 ir_node           *op   = get_Phi_pred(phi, i);
1205                 allocation_info_t *info = get_allocation_info(op);
1206                 ir_node           *pred;
1207                 float              weight;
1208
1209                 pred   = get_Block_cfgpred_block(block, i);
1210                 weight = get_block_execfreq(execfreqs, pred);
1211                 weight *= AFF_PHI;
1212
1213                 if (info->prefs[r] >= weight)
1214                         continue;
1215
1216                 /* promote the prefered register */
1217                 info->prefs[r] += AFF_PHI * weight;
1218                 if (is_Phi(op))
1219                         propagate_phi_register(op, r);
1220         }
1221 }
1222
1223 /**
1224  * Walker: assign registers to all nodes of a block that
1225  * need registers from the currently considered register class.
1226  */
1227 static void allocate_coalesce_block(ir_node *block, void *data)
1228 {
1229         int                    i;
1230         ir_nodeset_t           live_nodes;
1231         ir_nodeset_iterator_t  iter;
1232         ir_node               *node, *start;
1233         int                    n_preds;
1234         block_info_t          *block_info;
1235         block_info_t         **pred_block_infos;
1236         ir_node              **phi_ins;
1237         unsigned              *output_regs; /**< collects registers which must not
1238                                                                                      be used for optimistic splits */
1239
1240         (void) data;
1241         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1242
1243         /* clear assignments */
1244         block_info  = get_block_info(block);
1245         assignments = block_info->assignments;
1246
1247         ir_nodeset_init(&live_nodes);
1248
1249         /* gather regalloc infos of predecessor blocks */
1250         n_preds             = get_Block_n_cfgpreds(block);
1251         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1252         for (i = 0; i < n_preds; ++i) {
1253                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1254                 block_info_t *pred_info = get_block_info(pred);
1255                 pred_block_infos[i]     = pred_info;
1256         }
1257
1258         phi_ins = ALLOCAN(ir_node*, n_preds);
1259
1260         /* collect live-in nodes and preassigned values */
1261         be_lv_foreach(lv, block, be_lv_state_in, i) {
1262                 const arch_register_t *reg;
1263                 int                    p;
1264                 bool                   need_phi = false;
1265
1266                 node = be_lv_get_irn(lv, block, i);
1267                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1268                         continue;
1269
1270                 /* check all predecessors for this value, if it is not everywhere the
1271                    same or unknown then we have to construct a phi
1272                    (we collect the potential phi inputs here) */
1273                 for (p = 0; p < n_preds; ++p) {
1274                         block_info_t *pred_info = pred_block_infos[p];
1275
1276                         if (!pred_info->processed) {
1277                                 /* use node for now, it will get fixed later */
1278                                 phi_ins[p] = node;
1279                                 need_phi   = true;
1280                         } else {
1281                                 int a = find_value_in_block_info(pred_info, node);
1282
1283                                 /* must live out of predecessor */
1284                                 assert(a >= 0);
1285                                 phi_ins[p] = pred_info->assignments[a];
1286                                 /* different value from last time? then we need a phi */
1287                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1288                                         need_phi = true;
1289                                 }
1290                         }
1291                 }
1292
1293                 if (need_phi) {
1294                         ir_mode                   *mode = get_irn_mode(node);
1295                         const arch_register_req_t *req  = get_default_req_current_cls();
1296                         ir_node                   *phi;
1297                         int                        i;
1298
1299                         phi = new_r_Phi(block, n_preds, phi_ins, mode);
1300                         be_set_phi_reg_req(phi, req);
1301
1302                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1303 #ifdef DEBUG_libfirm
1304                         for (i = 0; i < n_preds; ++i) {
1305                                 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1306                         }
1307                         DB((dbg, LEVEL_3, "\n"));
1308 #endif
1309                         mark_as_copy_of(phi, node);
1310                         sched_add_after(block, phi);
1311
1312                         node = phi;
1313                 } else {
1314                         allocation_info_t *info = get_allocation_info(node);
1315                         info->current_value = phi_ins[0];
1316
1317                         /* Grab 1 of the inputs we constructed (might not be the same as
1318                          * "node" as we could see the same copy of the value in all
1319                          * predecessors */
1320                         node = phi_ins[0];
1321                 }
1322
1323                 /* if the node already has a register assigned use it */
1324                 reg = arch_get_irn_register(node);
1325                 if (reg != NULL) {
1326                         /* TODO: consult pred-block infos here. The value could be copied
1327                            away in some/all predecessor blocks. We need to construct
1328                            phi-nodes in this case.
1329                            We even need to construct some Phi_0 like constructs in cases
1330                            where the predecessor allocation is not determined yet. */
1331                         use_reg(node, reg);
1332                 }
1333
1334                 /* remember that this node is live at the beginning of the block */
1335                 ir_nodeset_insert(&live_nodes, node);
1336         }
1337
1338         rbitset_alloca(output_regs, n_regs);
1339
1340         /* handle phis... */
1341         node = sched_first(block);
1342         for ( ; is_Phi(node); node = sched_next(node)) {
1343                 const arch_register_t *reg;
1344
1345                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1346                         continue;
1347
1348                 /* fill in regs already assigned */
1349                 reg = arch_get_irn_register(node);
1350                 if (reg != NULL) {
1351                         use_reg(node, reg);
1352                 } else {
1353                         adapt_phi_prefs(node);
1354                         assign_reg(block, node, output_regs);
1355
1356                         reg = arch_get_irn_register(node);
1357                         propagate_phi_register(node, arch_register_get_index(reg));
1358                 }
1359         }
1360         start = node;
1361
1362         /* assign regs for live-in values */
1363         foreach_ir_nodeset(&live_nodes, node, iter) {
1364                 const arch_register_t *reg = arch_get_irn_register(node);
1365                 if (reg != NULL)
1366                         continue;
1367
1368                 assign_reg(block, node, output_regs);
1369                 /* shouldn't happen if we color in dominance order */
1370                 assert (!is_Phi(node));
1371         }
1372
1373         /* assign instructions in the block */
1374         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1375                 unsigned r;
1376
1377                 rewire_inputs(node);
1378
1379                 /* enforce use constraints */
1380                 rbitset_clear_all(output_regs, n_regs);
1381                 enforce_constraints(&live_nodes, node, output_regs);
1382                 /* we may not use registers occupied here for optimistic splits */
1383                 for (r = 0; r < n_regs; ++r) {
1384                         if (assignments[r] != NULL)
1385                                 rbitset_set(output_regs, r);
1386                 }
1387
1388                 rewire_inputs(node);
1389
1390                 /* free registers of values last used at this instruction */
1391                 free_last_uses(&live_nodes, node);
1392
1393                 /* assign output registers */
1394                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1395                 if (get_irn_mode(node) == mode_T) {
1396                         const ir_edge_t *edge;
1397                         foreach_out_edge(node, edge) {
1398                                 ir_node *proj = get_edge_src_irn(edge);
1399                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1400                                         continue;
1401                                 assign_reg(block, proj, output_regs);
1402                         }
1403                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1404                         assign_reg(block, node, output_regs);
1405                 }
1406         }
1407
1408         ir_nodeset_destroy(&live_nodes);
1409         assignments = NULL;
1410
1411         block_info->processed = true;
1412
1413         /* permute values at end of predecessor blocks in case of phi-nodes */
1414         if (n_preds > 1) {
1415                 int p;
1416                 for (p = 0; p < n_preds; ++p) {
1417                         add_phi_permutations(block, p);
1418                 }
1419         }
1420
1421         /* if we have exactly 1 successor then we might be able to produce phi
1422            copies now */
1423         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1424                 const ir_edge_t *edge
1425                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1426                 ir_node      *succ      = get_edge_src_irn(edge);
1427                 int           p         = get_edge_src_pos(edge);
1428                 block_info_t *succ_info = get_block_info(succ);
1429
1430                 if (succ_info->processed) {
1431                         add_phi_permutations(succ, p);
1432                 }
1433         }
1434 }
1435
1436 /**
1437  * Run the register allocator for the current register class.
1438  */
1439 static void be_straight_alloc_cls(void)
1440 {
1441         lv = be_assure_liveness(birg);
1442         be_liveness_assure_sets(lv);
1443         be_liveness_assure_chk(lv);
1444
1445         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1446         inc_irg_visited(irg);
1447
1448         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1449
1450         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1451         /* we need some dominance pre-order walk to ensure we see all
1452          *  definitions/create copies before we encounter their users */
1453         dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1454
1455         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1456 }
1457
1458 static void dump(int mask, ir_graph *irg, const char *suffix,
1459                  void (*dumper)(ir_graph *, const char *))
1460 {
1461         if(birg->main_env->options->dump_flags & mask)
1462                 be_dump(irg, suffix, dumper);
1463 }
1464
1465 /**
1466  * Run the spiller on the current graph.
1467  */
1468 static void spill(void)
1469 {
1470         /* make sure all nodes show their real register pressure */
1471         BE_TIMER_PUSH(t_ra_constr);
1472         be_pre_spill_prepare_constr(birg, cls);
1473         BE_TIMER_POP(t_ra_constr);
1474
1475         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1476
1477         /* spill */
1478         BE_TIMER_PUSH(t_ra_spill);
1479         be_do_spill(birg, cls);
1480         BE_TIMER_POP(t_ra_spill);
1481
1482         BE_TIMER_PUSH(t_ra_spill_apply);
1483         check_for_memory_operands(irg);
1484         BE_TIMER_POP(t_ra_spill_apply);
1485
1486         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1487 }
1488
1489 /**
1490  * The straight register allocator for a whole procedure.
1491  */
1492 static void be_straight_alloc(be_irg_t *new_birg)
1493 {
1494         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1495         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1496         int   c;
1497
1498         obstack_init(&obst);
1499
1500         birg      = new_birg;
1501         irg       = be_get_birg_irg(birg);
1502         execfreqs = birg->exec_freq;
1503
1504         /* TODO: extract some of the stuff from bechordal allocator, like
1505          * statistics, time measurements, etc. and use them here too */
1506
1507         for (c = 0; c < n_cls; ++c) {
1508                 cls             = arch_env_get_reg_class(arch_env, c);
1509                 default_cls_req = NULL;
1510                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1511                         continue;
1512
1513                 stat_ev_ctx_push_str("regcls", cls->name);
1514
1515                 n_regs      = arch_register_class_n_regs(cls);
1516                 normal_regs = rbitset_malloc(n_regs);
1517                 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1518
1519                 spill();
1520
1521                 /* verify schedule and register pressure */
1522                 BE_TIMER_PUSH(t_verify);
1523                 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1524                         be_verify_schedule(birg);
1525                         be_verify_register_pressure(birg, cls, irg);
1526                 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1527                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1528                         assert(be_verify_register_pressure(birg, cls, irg)
1529                                 && "Register pressure verification failed");
1530                 }
1531                 BE_TIMER_POP(t_verify);
1532
1533                 BE_TIMER_PUSH(t_ra_color);
1534                 be_straight_alloc_cls();
1535                 BE_TIMER_POP(t_ra_color);
1536
1537                 /* we most probably constructed new Phis so liveness info is invalid
1538                  * now */
1539                 /* TODO: test liveness_introduce */
1540                 be_liveness_invalidate(lv);
1541                 free(normal_regs);
1542
1543                 stat_ev_ctx_pop("regcls");
1544         }
1545
1546         BE_TIMER_PUSH(t_ra_spill_apply);
1547         be_abi_fix_stack_nodes(birg->abi);
1548         BE_TIMER_POP(t_ra_spill_apply);
1549
1550         BE_TIMER_PUSH(t_verify);
1551         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1552                 be_verify_register_allocation(birg);
1553         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1554                 assert(be_verify_register_allocation(birg)
1555                                 && "Register allocation invalid");
1556         }
1557         BE_TIMER_POP(t_verify);
1558
1559         obstack_free(&obst, NULL);
1560 }
1561
1562 /**
1563  * Initializes this module.
1564  */
1565 void be_init_straight_alloc(void)
1566 {
1567         static be_ra_t be_ra_straight = {
1568                 be_straight_alloc,
1569         };
1570
1571         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1572
1573         be_register_allocator("straight", &be_ra_straight);
1574 }
1575
1576 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);