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