clarify comment
[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
469         (void) pref;
470
471         /* find the best free position where we could move to */
472         reg_pref_t *prefs = ALLOCAN(reg_pref_t, n_regs);
473         fill_sort_candidates(prefs, info);
474         for (i = 0; i < n_regs; ++i) {
475                 r = prefs[i].num;
476                 if (!rbitset_is_set(normal_regs, r))
477                         continue;
478                 if (rbitset_is_set(output_regs, r))
479                         continue;
480                 if (assignments[r] == NULL)
481                         break;
482         }
483         if (i >= n_regs) {
484                 return false;
485         }
486         /* TODO: use execfreq somehow... */
487         float delta = pref_delta + prefs[i].pref;
488         if (delta < SPLIT_DELTA) {
489                 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
490                     delta));
491                 return false;
492         }
493
494         reg   = arch_register_for_index(cls, r);
495         block = get_nodes_block(before);
496         copy = be_new_Copy(cls, block, to_split);
497         mark_as_copy_of(copy, to_split);
498         free_reg_of_value(to_split);
499         use_reg(copy, reg);
500         sched_add_before(before, copy);
501
502         DB((dbg, LEVEL_3,
503             "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
504             copy, to_split, reg->name, before, delta));
505         return true;
506 }
507
508 /**
509  * Determine and assign a register for node @p node
510  */
511 static void assign_reg(const ir_node *block, ir_node *node,
512                        unsigned *output_regs)
513 {
514         const arch_register_t     *reg;
515         allocation_info_t         *info;
516         const arch_register_req_t *req;
517         reg_pref_t                *reg_prefs;
518         ir_node                   *in_node;
519         unsigned                   i;
520         const unsigned            *allowed_regs;
521
522         assert(arch_irn_consider_in_reg_alloc(cls, node));
523
524         /* preassigned register? */
525         reg = arch_get_irn_register(node);
526         if (reg != NULL) {
527                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
528                 use_reg(node, reg);
529                 return;
530         }
531
532         /* give should_be_same boni */
533         info = get_allocation_info(node);
534         req  = arch_get_register_req_out(node);
535
536         in_node = skip_Proj(node);
537         if (req->type & arch_register_req_type_should_be_same) {
538                 float weight = get_block_execfreq(execfreqs, block);
539                 int   arity  = get_irn_arity(in_node);
540                 int   i;
541
542                 assert(arity <= (int) sizeof(req->other_same) * 8);
543                 for (i = 0; i < arity; ++i) {
544                         ir_node               *in;
545                         const arch_register_t *reg;
546                         unsigned               r;
547                         if (!rbitset_is_set(&req->other_same, i))
548                                 continue;
549
550                         in  = get_irn_n(in_node, i);
551                         reg = arch_get_irn_register(in);
552                         assert(reg != NULL);
553                         r = arch_register_get_index(reg);
554
555                         /* if the value didn't die here then we should not propagate the
556                          * should_be_same info */
557                         if (assignments[r] == in)
558                                 continue;
559
560                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
561                 }
562         }
563
564         /* create list of register candidates and sort by their preference */
565         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
566         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
567         fill_sort_candidates(reg_prefs, info);
568         for (i = 0; i < n_regs; ++i) {
569                 unsigned num = reg_prefs[i].num;
570                 if (!rbitset_is_set(normal_regs, num))
571                         continue;
572
573                 const arch_register_t *reg = arch_register_for_index(cls, num);
574                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
575         }
576         DB((dbg, LEVEL_2, "\n"));
577
578         allowed_regs = normal_regs;
579         if (req->type & arch_register_req_type_limited) {
580                 allowed_regs = req->limited;
581         }
582
583         unsigned r;
584         for (i = 0; i < n_regs; ++i) {
585                 r = reg_prefs[i].num;
586                 if (!rbitset_is_set(allowed_regs, r))
587                         continue;
588                 if (assignments[r] == NULL)
589                         break;
590                 if (!is_Phi(node)) {
591                         float    pref   = reg_prefs[i].pref;
592                         float    delta  = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
593                         ir_node *before = skip_Proj(node);
594                         bool     res    = try_optimistic_split(assignments[r], before,
595                                                                pref, delta,
596                                                                output_regs);
597                         if (res)
598                                 break;
599                 }
600         }
601         if (i >= n_regs) {
602                 panic("No register left for %+F\n", node);
603         }
604
605         reg = arch_register_for_index(cls, r);
606         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
607         use_reg(node, reg);
608 }
609
610 /**
611  * Add an permutation in front of a node and change the assignments
612  * due to this permutation.
613  *
614  * To understand this imagine a permutation like this:
615  *
616  * 1 -> 2
617  * 2 -> 3
618  * 3 -> 1, 5
619  * 4 -> 6
620  * 5
621  * 6
622  * 7 -> 7
623  *
624  * First we count how many destinations a single value has. At the same time
625  * we can be sure that each destination register has at most 1 source register
626  * (it can have 0 which means we don't care what value is in it).
627  * We ignore all fullfilled permuations (like 7->7)
628  * In a first pass we create as much copy instructions as possible as they
629  * are generally cheaper than exchanges. We do this by counting into how many
630  * destinations a register has to be copied (in the example it's 2 for register
631  * 3, or 1 for the registers 1,2,4 and 7).
632  * We can then create a copy into every destination register when the usecount
633  * of that register is 0 (= noone else needs the value in the register).
634  *
635  * After this step we should have cycles left. We implement a cyclic permutation
636  * of n registers with n-1 transpositions.
637  *
638  * @param live_nodes   the set of live nodes, updated due to live range split
639  * @param before       the node before we add the permutation
640  * @param permutation  the permutation array indices are the destination
641  *                     registers, the values in the array are the source
642  *                     registers.
643  */
644 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
645                              unsigned *permutation)
646 {
647         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
648         ir_node   *block;
649         unsigned   r;
650
651         /* determine how often each source register needs to be read */
652         for (r = 0; r < n_regs; ++r) {
653                 unsigned  old_reg = permutation[r];
654                 ir_node  *value;
655
656                 value = assignments[old_reg];
657                 if (value == NULL) {
658                         /* nothing to do here, reg is not live. Mark it as fixpoint
659                          * so we ignore it in the next steps */
660                         permutation[r] = r;
661                         continue;
662                 }
663
664                 ++n_used[old_reg];
665         }
666
667         block = get_nodes_block(before);
668
669         /* step1: create copies where immediately possible */
670         for (r = 0; r < n_regs; /* empty */) {
671                 ir_node *copy;
672                 ir_node *src;
673                 const arch_register_t *reg;
674                 unsigned               old_r = permutation[r];
675
676                 /* - no need to do anything for fixed points.
677                    - we can't copy if the value in the dest reg is still needed */
678                 if (old_r == r || n_used[r] > 0) {
679                         ++r;
680                         continue;
681                 }
682
683                 /* create a copy */
684                 src  = assignments[old_r];
685                 copy = be_new_Copy(cls, block, src);
686                 sched_add_before(before, copy);
687                 reg = arch_register_for_index(cls, r);
688                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
689                     copy, src, before, reg->name));
690                 mark_as_copy_of(copy, src);
691                 use_reg(copy, reg);
692
693                 if (live_nodes != NULL) {
694                         ir_nodeset_insert(live_nodes, copy);
695                 }
696
697                 /* old register has 1 user less, permutation is resolved */
698                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
699                 permutation[r] = r;
700
701                 assert(n_used[old_r] > 0);
702                 --n_used[old_r];
703                 if (n_used[old_r] == 0) {
704                         if (live_nodes != NULL) {
705                                 ir_nodeset_remove(live_nodes, src);
706                         }
707                         free_reg_of_value(src);
708                 }
709
710                 /* advance or jump back (if this copy enabled another copy) */
711                 if (old_r < r && n_used[old_r] == 0) {
712                         r = old_r;
713                 } else {
714                         ++r;
715                 }
716         }
717
718         /* at this point we only have "cycles" left which we have to resolve with
719          * perm instructions
720          * TODO: if we have free registers left, then we should really use copy
721          * instructions for any cycle longer than 2 registers...
722          * (this is probably architecture dependent, there might be archs where
723          *  copies are preferable even for 2-cycles) */
724
725         /* create perms with the rest */
726         for (r = 0; r < n_regs; /* empty */) {
727                 const arch_register_t *reg;
728                 unsigned  old_r = permutation[r];
729                 unsigned  r2;
730                 ir_node  *in[2];
731                 ir_node  *perm;
732                 ir_node  *proj0;
733                 ir_node  *proj1;
734
735                 if (old_r == r) {
736                         ++r;
737                         continue;
738                 }
739
740                 /* we shouldn't have copies from 1 value to multiple destinations left*/
741                 assert(n_used[old_r] == 1);
742
743                 /* exchange old_r and r2; after that old_r is a fixed point */
744                 r2 = permutation[old_r];
745
746                 in[0] = assignments[r2];
747                 in[1] = assignments[old_r];
748                 perm = be_new_Perm(cls, block, 2, in);
749                 sched_add_before(before, perm);
750                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
751                     perm, in[0], in[1], before));
752
753                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
754                 mark_as_copy_of(proj0, in[0]);
755                 reg = arch_register_for_index(cls, old_r);
756                 use_reg(proj0, reg);
757
758                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
759                 mark_as_copy_of(proj1, in[1]);
760                 reg = arch_register_for_index(cls, r2);
761                 use_reg(proj1, reg);
762
763                 /* 1 value is now in the correct register */
764                 permutation[old_r] = old_r;
765                 /* the source of r changed to r2 */
766                 permutation[r] = r2;
767
768                 /* if we have reached a fixpoint update data structures */
769                 if (live_nodes != NULL) {
770                         ir_nodeset_remove(live_nodes, in[0]);
771                         ir_nodeset_remove(live_nodes, in[1]);
772                         ir_nodeset_remove(live_nodes, proj0);
773                         ir_nodeset_insert(live_nodes, proj1);
774                 }
775         }
776
777 #ifdef DEBUG_libfirm
778         /* now we should only have fixpoints left */
779         for (r = 0; r < n_regs; ++r) {
780                 assert(permutation[r] == r);
781         }
782 #endif
783 }
784
785 /**
786  * Free regs for values last used.
787  *
788  * @param live_nodes   set of live nodes, will be updated
789  * @param node         the node to consider
790  */
791 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
792 {
793         allocation_info_t     *info      = get_allocation_info(node);
794         const unsigned        *last_uses = &info->last_uses;
795         int                    arity     = get_irn_arity(node);
796         int                    i;
797
798         for (i = 0; i < arity; ++i) {
799                 ir_node *op;
800
801                 /* check if one operand is the last use */
802                 if (!rbitset_is_set(last_uses, i))
803                         continue;
804
805                 op = get_irn_n(node, i);
806                 free_reg_of_value(op);
807                 ir_nodeset_remove(live_nodes, op);
808         }
809 }
810
811 /**
812  * change inputs of a node to the current value (copies/perms)
813  */
814 static void rewire_inputs(ir_node *node)
815 {
816         int i;
817         int arity = get_irn_arity(node);
818
819         for (i = 0; i < arity; ++i) {
820                 ir_node           *op = get_irn_n(node, i);
821                 allocation_info_t *info;
822
823                 if (!arch_irn_consider_in_reg_alloc(cls, op))
824                         continue;
825
826                 info = get_allocation_info(op);
827                 info = get_allocation_info(info->original_value);
828                 if (info->current_value != op) {
829                         set_irn_n(node, i, info->current_value);
830                 }
831         }
832 }
833
834 /**
835  * Create a bitset of registers occupied with value living through an
836  * instruction
837  */
838 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
839 {
840         const allocation_info_t *info = get_allocation_info(node);
841         unsigned r;
842         int i;
843         int arity;
844
845         /* mark all used registers as potentially live-through */
846         for (r = 0; r < n_regs; ++r) {
847                 if (assignments[r] == NULL)
848                         continue;
849                 if (!rbitset_is_set(normal_regs, r))
850                         continue;
851
852                 rbitset_set(bitset, r);
853         }
854
855         /* remove registers of value dying at the instruction */
856         arity = get_irn_arity(node);
857         for (i = 0; i < arity; ++i) {
858                 ir_node               *op;
859                 const arch_register_t *reg;
860
861                 if (!rbitset_is_set(&info->last_uses, i))
862                         continue;
863
864                 op  = get_irn_n(node, i);
865                 reg = arch_get_irn_register(op);
866                 rbitset_clear(bitset, arch_register_get_index(reg));
867         }
868 }
869
870 /**
871  * Enforce constraints at a node by live range splits.
872  *
873  * @param  live_nodes  the set of live nodes, might be changed
874  * @param  node        the current node
875  */
876 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
877                                 unsigned *output_regs)
878 {
879         int arity = get_irn_arity(node);
880         int i, dummy, res;
881         hungarian_problem_t *bp;
882         unsigned l, r;
883         unsigned *assignment;
884
885         /* construct a list of register occupied by live-through values */
886         unsigned *live_through_regs = NULL;
887
888         /* see if any use constraints are not met */
889         bool good = true;
890         for (i = 0; i < arity; ++i) {
891                 ir_node                   *op = get_irn_n(node, i);
892                 const arch_register_t     *reg;
893                 const arch_register_req_t *req;
894                 const unsigned            *limited;
895                 unsigned                  r;
896
897                 if (!arch_irn_consider_in_reg_alloc(cls, op))
898                         continue;
899
900                 /* are there any limitations for the i'th operand? */
901                 req = arch_get_register_req(node, i);
902                 if (!(req->type & arch_register_req_type_limited))
903                         continue;
904
905                 limited = req->limited;
906                 reg     = arch_get_irn_register(op);
907                 r       = arch_register_get_index(reg);
908                 if (!rbitset_is_set(limited, r)) {
909                         /* found an assignment outside the limited set */
910                         good = false;
911                         break;
912                 }
913         }
914
915         /* is any of the live-throughs using a constrained output register? */
916         if (get_irn_mode(node) == mode_T) {
917                 const ir_edge_t *edge;
918
919                 foreach_out_edge(node, edge) {
920                         ir_node *proj = get_edge_src_irn(edge);
921                         const arch_register_req_t *req;
922
923                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
924                                 continue;
925
926                         req = arch_get_register_req_out(proj);
927                         if (!(req->type & arch_register_req_type_limited))
928                                 continue;
929
930                         if (live_through_regs == NULL) {
931                                 rbitset_alloca(live_through_regs, n_regs);
932                                 determine_live_through_regs(live_through_regs, node);
933                         }
934
935                         rbitset_or(output_regs, req->limited, n_regs);
936                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
937                                 good = false;
938                         }
939                 }
940         } else {
941                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
942                         const arch_register_req_t *req = arch_get_register_req_out(node);
943                         if (req->type & arch_register_req_type_limited) {
944                                 rbitset_alloca(live_through_regs, n_regs);
945                                 determine_live_through_regs(live_through_regs, node);
946                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
947                                         good = false;
948                                         rbitset_or(output_regs, req->limited, n_regs);
949                                 }
950                         }
951                 }
952         }
953
954         if (good)
955                 return;
956
957         /* create these arrays if we haven't yet */
958         if (live_through_regs == NULL) {
959                 rbitset_alloca(live_through_regs, n_regs);
960         }
961
962         /* at this point we have to construct a bipartite matching problem to see
963          * which values should go to which registers
964          * Note: We're building the matrix in "reverse" - source registers are
965          *       right, destinations left because this will produce the solution
966          *       in the format required for permute_values.
967          */
968         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
969
970         /* add all combinations, then remove not allowed ones */
971         for (l = 0; l < n_regs; ++l) {
972                 if (!rbitset_is_set(normal_regs, l)) {
973                         hungarian_add(bp, l, l, 1);
974                         continue;
975                 }
976
977                 for (r = 0; r < n_regs; ++r) {
978                         if (!rbitset_is_set(normal_regs, r))
979                                 continue;
980                         /* livethrough values may not use constrainted output registers */
981                         if (rbitset_is_set(live_through_regs, l)
982                                         && rbitset_is_set(output_regs, r))
983                                 continue;
984
985                         hungarian_add(bp, r, l, l == r ? 9 : 8);
986                 }
987         }
988
989         for (i = 0; i < arity; ++i) {
990                 ir_node                   *op = get_irn_n(node, i);
991                 const arch_register_t     *reg;
992                 const arch_register_req_t *req;
993                 const unsigned            *limited;
994                 unsigned                   current_reg;
995
996                 if (!arch_irn_consider_in_reg_alloc(cls, op))
997                         continue;
998
999                 req = arch_get_register_req(node, i);
1000                 if (!(req->type & arch_register_req_type_limited))
1001                         continue;
1002
1003                 limited     = req->limited;
1004                 reg         = arch_get_irn_register(op);
1005                 current_reg = arch_register_get_index(reg);
1006                 for (r = 0; r < n_regs; ++r) {
1007                         if (rbitset_is_set(limited, r))
1008                                 continue;
1009                         hungarian_remv(bp, r, current_reg);
1010                 }
1011         }
1012
1013         //hungarian_print_costmatrix(bp, 1);
1014         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1015
1016         assignment = ALLOCAN(unsigned, n_regs);
1017         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1018         assert(res == 0);
1019
1020 #if 0
1021         fprintf(stderr, "Swap result:");
1022         for (i = 0; i < (int) n_regs; ++i) {
1023                 fprintf(stderr, " %d", assignment[i]);
1024         }
1025         fprintf(stderr, "\n");
1026 #endif
1027
1028         hungarian_free(bp);
1029
1030         permute_values(live_nodes, node, assignment);
1031 }
1032
1033 /** test wether a node @p n is a copy of the value of node @p of */
1034 static bool is_copy_of(ir_node *value, ir_node *test_value)
1035 {
1036         allocation_info_t *test_info;
1037         allocation_info_t *info;
1038
1039         if (value == test_value)
1040                 return true;
1041
1042         info      = get_allocation_info(value);
1043         test_info = get_allocation_info(test_value);
1044         return test_info->original_value == info->original_value;
1045 }
1046
1047 /**
1048  * find a value in the end-assignment of a basic block
1049  * @returns the index into the assignment array if found
1050  *          -1 if not found
1051  */
1052 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1053 {
1054         unsigned   r;
1055         ir_node  **assignments = info->assignments;
1056         for (r = 0; r < n_regs; ++r) {
1057                 ir_node *a_value = assignments[r];
1058
1059                 if (a_value == NULL)
1060                         continue;
1061                 if (is_copy_of(a_value, value))
1062                         return (int) r;
1063         }
1064
1065         return -1;
1066 }
1067
1068 /**
1069  * Create the necessary permutations at the end of a basic block to fullfill
1070  * the register assignment for phi-nodes in the next block
1071  */
1072 static void add_phi_permutations(ir_node *block, int p)
1073 {
1074         unsigned   r;
1075         unsigned  *permutation;
1076         ir_node  **old_assignments;
1077         bool       need_permutation;
1078         ir_node   *node;
1079         ir_node   *pred = get_Block_cfgpred_block(block, p);
1080
1081         block_info_t *pred_info = get_block_info(pred);
1082
1083         /* predecessor not processed yet? nothing to do */
1084         if (!pred_info->processed)
1085                 return;
1086
1087         permutation = ALLOCAN(unsigned, n_regs);
1088         for (r = 0; r < n_regs; ++r) {
1089                 permutation[r] = r;
1090         }
1091
1092         /* check phi nodes */
1093         need_permutation = false;
1094         node = sched_first(block);
1095         for ( ; is_Phi(node); node = sched_next(node)) {
1096                 const arch_register_t *reg;
1097                 int                    regn;
1098                 int                    a;
1099                 ir_node               *op;
1100
1101                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1102                         continue;
1103
1104                 op = get_Phi_pred(node, p);
1105                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1106                         continue;
1107
1108                 a  = find_value_in_block_info(pred_info, op);
1109                 assert(a >= 0);
1110
1111                 reg  = arch_get_irn_register(node);
1112                 regn = arch_register_get_index(reg);
1113                 if (regn != a) {
1114                         permutation[regn] = a;
1115                         need_permutation  = true;
1116                 }
1117         }
1118
1119         if (need_permutation) {
1120                 /* permute values at end of predecessor */
1121                 old_assignments = assignments;
1122                 assignments     = pred_info->assignments;
1123                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1124                                                  permutation);
1125                 assignments = old_assignments;
1126         }
1127
1128         /* change phi nodes to use the copied values */
1129         node = sched_first(block);
1130         for ( ; is_Phi(node); node = sched_next(node)) {
1131                 int      a;
1132                 ir_node *op;
1133
1134                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1135                         continue;
1136
1137                 op = get_Phi_pred(node, p);
1138                 /* no need to do anything for Unknown inputs */
1139                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1140                         continue;
1141
1142                 /* we have permuted all values into the correct registers so we can
1143                    simply query which value occupies the phis register in the
1144                    predecessor */
1145                 a  = arch_register_get_index(arch_get_irn_register(node));
1146                 op = pred_info->assignments[a];
1147                 set_Phi_pred(node, p, op);
1148         }
1149 }
1150
1151 /**
1152  * Set preferences for a phis register based on the registers used on the
1153  * phi inputs.
1154  */
1155 static void adapt_phi_prefs(ir_node *phi)
1156 {
1157         int i;
1158         int arity = get_irn_arity(phi);
1159         ir_node           *block = get_nodes_block(phi);
1160         allocation_info_t *info  = get_allocation_info(phi);
1161
1162         for (i = 0; i < arity; ++i) {
1163                 ir_node               *op  = get_irn_n(phi, i);
1164                 const arch_register_t *reg = arch_get_irn_register(op);
1165                 ir_node               *pred;
1166                 ir_node               *pred_block;
1167                 block_info_t          *pred_block_info;
1168                 float                  weight;
1169                 unsigned               r;
1170
1171                 if (reg == NULL)
1172                         continue;
1173                 /* we only give the bonus if the predecessor already has register
1174                  * assigned, otherwise we only see a dummy value
1175                  * and any conclusions about its register are useless */
1176                 pred_block = get_Block_cfgpred_block(block, i);
1177                 pred_block_info = get_block_info(pred_block);
1178                 if (!pred_block_info->processed)
1179                         continue;
1180
1181                 /* give bonus for already assigned register */
1182                 pred   = get_Block_cfgpred_block(block, i);
1183                 weight = get_block_execfreq(execfreqs, pred);
1184                 r      = arch_register_get_index(reg);
1185                 info->prefs[r] += weight * AFF_PHI;
1186         }
1187 }
1188
1189 /**
1190  * After a phi has been assigned a register propagate preference inputs
1191  * to the phi inputs.
1192  */
1193 static void propagate_phi_register(ir_node *phi, unsigned r)
1194 {
1195         int                    i;
1196         ir_node               *block = get_nodes_block(phi);
1197         int                    arity = get_irn_arity(phi);
1198
1199         for (i = 0; i < arity; ++i) {
1200                 ir_node           *op   = get_Phi_pred(phi, i);
1201                 allocation_info_t *info = get_allocation_info(op);
1202                 ir_node           *pred;
1203                 float              weight;
1204
1205                 pred   = get_Block_cfgpred_block(block, i);
1206                 weight = get_block_execfreq(execfreqs, pred);
1207                 weight *= AFF_PHI;
1208
1209                 if (info->prefs[r] >= weight)
1210                         continue;
1211
1212                 /* promote the prefered register */
1213                 info->prefs[r] += AFF_PHI * weight;
1214                 if (is_Phi(op))
1215                         propagate_phi_register(op, r);
1216         }
1217 }
1218
1219 /**
1220  * Walker: assign registers to all nodes of a block that
1221  * need registers from the currently considered register class.
1222  */
1223 static void allocate_coalesce_block(ir_node *block, void *data)
1224 {
1225         int                    i;
1226         ir_nodeset_t           live_nodes;
1227         ir_nodeset_iterator_t  iter;
1228         ir_node               *node, *start;
1229         int                    n_preds;
1230         block_info_t          *block_info;
1231         block_info_t         **pred_block_infos;
1232         ir_node              **phi_ins;
1233         unsigned              *output_regs; /**< collects registers which must not
1234                                                                                      be used for optimistic splits */
1235
1236         (void) data;
1237         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1238
1239         /* clear assignments */
1240         block_info  = get_block_info(block);
1241         assignments = block_info->assignments;
1242
1243         ir_nodeset_init(&live_nodes);
1244
1245         /* gather regalloc infos of predecessor blocks */
1246         n_preds             = get_Block_n_cfgpreds(block);
1247         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1248         for (i = 0; i < n_preds; ++i) {
1249                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1250                 block_info_t *pred_info = get_block_info(pred);
1251                 pred_block_infos[i]     = pred_info;
1252         }
1253
1254         phi_ins = ALLOCAN(ir_node*, n_preds);
1255
1256         /* collect live-in nodes and preassigned values */
1257         be_lv_foreach(lv, block, be_lv_state_in, i) {
1258                 const arch_register_t *reg;
1259                 int                    p;
1260                 bool                   need_phi = false;
1261
1262                 node = be_lv_get_irn(lv, block, i);
1263                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1264                         continue;
1265
1266                 /* check all predecessors for this value, if it is not everywhere the
1267                    same or unknown then we have to construct a phi
1268                    (we collect the potential phi inputs here) */
1269                 for (p = 0; p < n_preds; ++p) {
1270                         block_info_t *pred_info = pred_block_infos[p];
1271
1272                         if (!pred_info->processed) {
1273                                 /* use node for now, it will get fixed later */
1274                                 phi_ins[p] = node;
1275                                 need_phi   = true;
1276                         } else {
1277                                 int a = find_value_in_block_info(pred_info, node);
1278
1279                                 /* must live out of predecessor */
1280                                 assert(a >= 0);
1281                                 phi_ins[p] = pred_info->assignments[a];
1282                                 /* different value from last time? then we need a phi */
1283                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1284                                         need_phi = true;
1285                                 }
1286                         }
1287                 }
1288
1289                 if (need_phi) {
1290                         ir_mode                   *mode = get_irn_mode(node);
1291                         const arch_register_req_t *req  = get_default_req_current_cls();
1292                         ir_node                   *phi;
1293                         int                        i;
1294
1295                         phi = new_r_Phi(block, n_preds, phi_ins, mode);
1296                         be_set_phi_reg_req(phi, req);
1297
1298                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1299 #ifdef DEBUG_libfirm
1300                         for (i = 0; i < n_preds; ++i) {
1301                                 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1302                         }
1303                         DB((dbg, LEVEL_3, "\n"));
1304 #endif
1305                         mark_as_copy_of(phi, node);
1306                         sched_add_after(block, phi);
1307
1308                         node = phi;
1309                 } else {
1310                         allocation_info_t *info = get_allocation_info(node);
1311                         info->current_value = phi_ins[0];
1312
1313                         /* Grab 1 of the inputs we constructed (might not be the same as
1314                          * "node" as we could see the same copy of the value in all
1315                          * predecessors */
1316                         node = phi_ins[0];
1317                 }
1318
1319                 /* if the node already has a register assigned use it */
1320                 reg = arch_get_irn_register(node);
1321                 if (reg != NULL) {
1322                         /* TODO: consult pred-block infos here. The value could be copied
1323                            away in some/all predecessor blocks. We need to construct
1324                            phi-nodes in this case.
1325                            We even need to construct some Phi_0 like constructs in cases
1326                            where the predecessor allocation is not determined yet. */
1327                         use_reg(node, reg);
1328                 }
1329
1330                 /* remember that this node is live at the beginning of the block */
1331                 ir_nodeset_insert(&live_nodes, node);
1332         }
1333
1334         rbitset_alloca(output_regs, n_regs);
1335
1336         /* handle phis... */
1337         node = sched_first(block);
1338         for ( ; is_Phi(node); node = sched_next(node)) {
1339                 const arch_register_t *reg;
1340
1341                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1342                         continue;
1343
1344                 /* fill in regs already assigned */
1345                 reg = arch_get_irn_register(node);
1346                 if (reg != NULL) {
1347                         use_reg(node, reg);
1348                 } else {
1349                         adapt_phi_prefs(node);
1350                         assign_reg(block, node, output_regs);
1351
1352                         reg = arch_get_irn_register(node);
1353                         propagate_phi_register(node, arch_register_get_index(reg));
1354                 }
1355         }
1356         start = node;
1357
1358         /* assign regs for live-in values */
1359         foreach_ir_nodeset(&live_nodes, node, iter) {
1360                 const arch_register_t *reg = arch_get_irn_register(node);
1361                 if (reg != NULL)
1362                         continue;
1363
1364                 assign_reg(block, node, output_regs);
1365                 /* shouldn't happen if we color in dominance order */
1366                 assert (!is_Phi(node));
1367         }
1368
1369         /* assign instructions in the block */
1370         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1371                 unsigned r;
1372
1373                 rewire_inputs(node);
1374
1375                 /* enforce use constraints */
1376                 rbitset_clear_all(output_regs, n_regs);
1377                 enforce_constraints(&live_nodes, node, output_regs);
1378                 /* we may not use registers occupied here for optimistic splits */
1379                 for (r = 0; r < n_regs; ++r) {
1380                         if (assignments[r] != NULL)
1381                                 rbitset_set(output_regs, r);
1382                 }
1383
1384                 rewire_inputs(node);
1385
1386                 /* free registers of values last used at this instruction */
1387                 free_last_uses(&live_nodes, node);
1388
1389                 /* assign output registers */
1390                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1391                 if (get_irn_mode(node) == mode_T) {
1392                         const ir_edge_t *edge;
1393                         foreach_out_edge(node, edge) {
1394                                 ir_node *proj = get_edge_src_irn(edge);
1395                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1396                                         continue;
1397                                 assign_reg(block, proj, output_regs);
1398                         }
1399                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1400                         assign_reg(block, node, output_regs);
1401                 }
1402         }
1403
1404         ir_nodeset_destroy(&live_nodes);
1405         assignments = NULL;
1406
1407         block_info->processed = true;
1408
1409         /* permute values at end of predecessor blocks in case of phi-nodes */
1410         if (n_preds > 1) {
1411                 int p;
1412                 for (p = 0; p < n_preds; ++p) {
1413                         add_phi_permutations(block, p);
1414                 }
1415         }
1416
1417         /* if we have exactly 1 successor then we might be able to produce phi
1418            copies now */
1419         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1420                 const ir_edge_t *edge
1421                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1422                 ir_node      *succ      = get_edge_src_irn(edge);
1423                 int           p         = get_edge_src_pos(edge);
1424                 block_info_t *succ_info = get_block_info(succ);
1425
1426                 if (succ_info->processed) {
1427                         add_phi_permutations(succ, p);
1428                 }
1429         }
1430 }
1431
1432 /**
1433  * Run the register allocator for the current register class.
1434  */
1435 static void be_straight_alloc_cls(void)
1436 {
1437         lv = be_assure_liveness(birg);
1438         be_liveness_assure_sets(lv);
1439         be_liveness_assure_chk(lv);
1440
1441         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1442         inc_irg_visited(irg);
1443
1444         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1445
1446         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1447         /* we need some dominance pre-order walk to ensure we see all
1448          *  definitions/create copies before we encounter their users */
1449         dom_tree_walk_irg(irg, allocate_coalesce_block, NULL, NULL);
1450
1451         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_IRN_VISITED);
1452 }
1453
1454 static void dump(int mask, ir_graph *irg, const char *suffix,
1455                  void (*dumper)(ir_graph *, const char *))
1456 {
1457         if(birg->main_env->options->dump_flags & mask)
1458                 be_dump(irg, suffix, dumper);
1459 }
1460
1461 /**
1462  * Run the spiller on the current graph.
1463  */
1464 static void spill(void)
1465 {
1466         /* make sure all nodes show their real register pressure */
1467         BE_TIMER_PUSH(t_ra_constr);
1468         be_pre_spill_prepare_constr(birg, cls);
1469         BE_TIMER_POP(t_ra_constr);
1470
1471         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1472
1473         /* spill */
1474         BE_TIMER_PUSH(t_ra_spill);
1475         be_do_spill(birg, cls);
1476         BE_TIMER_POP(t_ra_spill);
1477
1478         BE_TIMER_PUSH(t_ra_spill_apply);
1479         check_for_memory_operands(irg);
1480         BE_TIMER_POP(t_ra_spill_apply);
1481
1482         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1483 }
1484
1485 /**
1486  * The straight register allocator for a whole procedure.
1487  */
1488 static void be_straight_alloc(be_irg_t *new_birg)
1489 {
1490         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1491         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1492         int   c;
1493
1494         obstack_init(&obst);
1495
1496         birg      = new_birg;
1497         irg       = be_get_birg_irg(birg);
1498         execfreqs = birg->exec_freq;
1499
1500         /* TODO: extract some of the stuff from bechordal allocator, like
1501          * statistics, time measurements, etc. and use them here too */
1502
1503         for (c = 0; c < n_cls; ++c) {
1504                 cls             = arch_env_get_reg_class(arch_env, c);
1505                 default_cls_req = NULL;
1506                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1507                         continue;
1508
1509                 stat_ev_ctx_push_str("regcls", cls->name);
1510
1511                 n_regs      = arch_register_class_n_regs(cls);
1512                 normal_regs = rbitset_malloc(n_regs);
1513                 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1514
1515                 spill();
1516
1517                 /* verify schedule and register pressure */
1518                 BE_TIMER_PUSH(t_verify);
1519                 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1520                         be_verify_schedule(birg);
1521                         be_verify_register_pressure(birg, cls, irg);
1522                 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1523                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1524                         assert(be_verify_register_pressure(birg, cls, irg)
1525                                 && "Register pressure verification failed");
1526                 }
1527                 BE_TIMER_POP(t_verify);
1528
1529                 BE_TIMER_PUSH(t_ra_color);
1530                 be_straight_alloc_cls();
1531                 BE_TIMER_POP(t_ra_color);
1532
1533                 /* we most probably constructed new Phis so liveness info is invalid
1534                  * now */
1535                 /* TODO: test liveness_introduce */
1536                 be_liveness_invalidate(lv);
1537                 free(normal_regs);
1538
1539                 stat_ev_ctx_pop("regcls");
1540         }
1541
1542         BE_TIMER_PUSH(t_ra_spill_apply);
1543         be_abi_fix_stack_nodes(birg->abi);
1544         BE_TIMER_POP(t_ra_spill_apply);
1545
1546         BE_TIMER_PUSH(t_verify);
1547         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1548                 be_verify_register_allocation(birg);
1549         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1550                 assert(be_verify_register_allocation(birg)
1551                                 && "Register allocation invalid");
1552         }
1553         BE_TIMER_POP(t_verify);
1554
1555         obstack_free(&obst, NULL);
1556 }
1557
1558 /**
1559  * Initializes this module.
1560  */
1561 void be_init_straight_alloc(void)
1562 {
1563         static be_ra_t be_ra_straight = {
1564                 be_straight_alloc,
1565         };
1566
1567         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1568
1569         be_register_allocator("straight", &be_ra_straight);
1570 }
1571
1572 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);