fix prefalloc after sched_foreach changes
[libfirm] / ir / be / beprefalloc.c
1 /*
2  * Copyright (C) 1995-2011 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       Preference Guided Register Assignment
23  * @author      Matthias Braun
24  * @date        14.2.2009
25  *
26  * The idea is to allocate registers in 2 passes:
27  * 1. A first pass to determine "preferred" registers for live-ranges. This
28  *    calculates for each register and each live-range a value indicating
29  *    the usefulness. (You can roughly think of the value as the negative
30  *    costs needed for copies when the value is in the specific registers...)
31  *
32  * 2. Walk blocks and assigns registers in a greedy fashion. Preferring
33  *    registers with high preferences. When register constraints are not met,
34  *    add copies and split live-ranges.
35  *
36  * TODO:
37  *  - make use of free registers in the permute_values code
38  */
39 #include "config.h"
40
41 #include <float.h>
42 #include <stdbool.h>
43 #include <math.h>
44 #include "lpp.h"
45
46 #include "error.h"
47 #include "execfreq.h"
48 #include "ircons.h"
49 #include "irdom.h"
50 #include "iredges_t.h"
51 #include "irgraph_t.h"
52 #include "irgwalk.h"
53 #include "irnode_t.h"
54 #include "irprintf.h"
55 #include "irdump.h"
56 #include "irtools.h"
57 #include "util.h"
58 #include "obst.h"
59 #include "raw_bitset.h"
60 #include "unionfind.h"
61 #include "pdeq.h"
62 #include "hungarian.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.h"
71 #include "bera.h"
72 #include "besched.h"
73 #include "bespill.h"
74 #include "bespillutil.h"
75 #include "beverify.h"
76 #include "beutil.h"
77 #include "bestack.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 #define MAX_OPTIMISTIC_SPLIT_RECURSION 0
86
87 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
88
89 static struct obstack               obst;
90 static ir_graph                    *irg;
91 static const arch_register_class_t *cls;
92 static be_lv_t                     *lv;
93 static const ir_exec_freq          *execfreqs;
94 static unsigned                     n_regs;
95 static unsigned                    *normal_regs;
96 static int                         *congruence_classes;
97 static ir_node                    **block_order;
98 static size_t                       n_block_order;
99 static int                          create_preferences        = true;
100 static int                          create_congruence_classes = true;
101 static int                          propagate_phi_registers   = true;
102
103 static const lc_opt_table_entry_t options[] = {
104         LC_OPT_ENT_BOOL("prefs", "use preference based coloring", &create_preferences),
105         LC_OPT_ENT_BOOL("congruences", "create congruence classes", &create_congruence_classes),
106         LC_OPT_ENT_BOOL("prop_phi", "propagate phi registers", &propagate_phi_registers),
107         LC_OPT_LAST
108 };
109
110 /** currently active assignments (while processing a basic block)
111  * maps registers to values(their current copies) */
112 static ir_node **assignments;
113
114 /**
115  * allocation information: last_uses, register preferences
116  * the information is per firm-node.
117  */
118 struct allocation_info_t {
119         unsigned  last_uses[2];   /**< bitset indicating last uses (input pos) */
120         ir_node  *current_value;  /**< copy of the value that should be used */
121         ir_node  *original_value; /**< for copies point to original value */
122         float     prefs[];        /**< register preferences */
123 };
124 typedef struct allocation_info_t allocation_info_t;
125
126 /** helper datastructure used when sorting register preferences */
127 struct reg_pref_t {
128         unsigned num;
129         float    pref;
130 };
131 typedef struct reg_pref_t reg_pref_t;
132
133 /** per basic-block information */
134 struct block_info_t {
135         bool     processed;       /**< indicate whether block is processed */
136         ir_node *assignments[];   /**< register assignments at end of block */
137 };
138 typedef struct block_info_t block_info_t;
139
140 /**
141  * Get the allocation info for a node.
142  * The info is allocated on the first visit of a node.
143  */
144 static allocation_info_t *get_allocation_info(ir_node *node)
145 {
146         allocation_info_t *info = (allocation_info_t*)get_irn_link(node);
147         if (info == NULL) {
148                 info = OALLOCFZ(&obst, allocation_info_t, prefs, n_regs);
149                 info->current_value  = node;
150                 info->original_value = node;
151                 set_irn_link(node, info);
152         }
153
154         return info;
155 }
156
157 static allocation_info_t *try_get_allocation_info(const ir_node *node)
158 {
159         return (allocation_info_t*) get_irn_link(node);
160 }
161
162 /**
163  * Get allocation information for a basic block
164  */
165 static block_info_t *get_block_info(ir_node *block)
166 {
167         block_info_t *info = (block_info_t*)get_irn_link(block);
168
169         assert(is_Block(block));
170         if (info == NULL) {
171                 info = OALLOCFZ(&obst, block_info_t, assignments, n_regs);
172                 set_irn_link(block, info);
173         }
174
175         return info;
176 }
177
178 /**
179  * Link the allocation info of a node to a copy.
180  * Afterwards, both nodes uses the same allocation info.
181  * Copy must not have an allocation info assigned yet.
182  *
183  * @param copy   the node that gets the allocation info assigned
184  * @param value  the original node
185  */
186 static void mark_as_copy_of(ir_node *copy, ir_node *value)
187 {
188         ir_node           *original;
189         allocation_info_t *info      = get_allocation_info(value);
190         allocation_info_t *copy_info = get_allocation_info(copy);
191
192         /* find original value */
193         original = info->original_value;
194         if (original != value) {
195                 info = get_allocation_info(original);
196         }
197
198         assert(info->original_value == original);
199         info->current_value = copy;
200
201         /* the copy should not be linked to something else yet */
202         assert(copy_info->original_value == copy);
203         copy_info->original_value = original;
204
205         /* copy over allocation preferences */
206         memcpy(copy_info->prefs, info->prefs, n_regs * sizeof(copy_info->prefs[0]));
207 }
208
209 /**
210  * Calculate the penalties for every register on a node and its live neighbors.
211  *
212  * @param live_nodes  the set of live nodes at the current position, may be NULL
213  * @param penalty     the penalty to subtract from
214  * @param limited     a raw bitset containing the limited set for the node
215  * @param node        the node
216  */
217 static void give_penalties_for_limits(const ir_nodeset_t *live_nodes,
218                                       float penalty, const unsigned* limited,
219                                       ir_node *node)
220 {
221         ir_nodeset_iterator_t iter;
222         unsigned              r;
223         size_t                n_allowed;
224         allocation_info_t     *info = get_allocation_info(node);
225         ir_node               *neighbor;
226
227         /* give penalty for all forbidden regs */
228         for (r = 0; r < n_regs; ++r) {
229                 if (rbitset_is_set(limited, r))
230                         continue;
231
232                 info->prefs[r] -= penalty;
233         }
234
235         /* all other live values should get a penalty for allowed regs */
236         if (live_nodes == NULL)
237                 return;
238
239         penalty   *= NEIGHBOR_FACTOR;
240         n_allowed  = rbitset_popcount(limited, n_regs);
241         if (n_allowed > 1) {
242                 /* only create a very weak penalty if multiple regs are allowed */
243                 penalty = (penalty * 0.8f) / n_allowed;
244         }
245         foreach_ir_nodeset(live_nodes, neighbor, iter) {
246                 allocation_info_t *neighbor_info;
247
248                 /* TODO: if op is used on multiple inputs we might not do a
249                  * continue here */
250                 if (neighbor == node)
251                         continue;
252
253                 neighbor_info = get_allocation_info(neighbor);
254                 for (r = 0; r < n_regs; ++r) {
255                         if (!rbitset_is_set(limited, r))
256                                 continue;
257
258                         neighbor_info->prefs[r] -= penalty;
259                 }
260         }
261 }
262
263 /**
264  * Calculate the preferences of a definition for the current register class.
265  * If the definition uses a limited set of registers, reduce the preferences
266  * for the limited register on the node and its neighbors.
267  *
268  * @param live_nodes  the set of live nodes at the current node
269  * @param weight      the weight
270  * @param node        the current node
271  */
272 static void check_defs(const ir_nodeset_t *live_nodes, float weight,
273                        ir_node *node)
274 {
275         const arch_register_req_t *req = arch_get_irn_register_req(node);
276         if (req->type & arch_register_req_type_limited) {
277                 const unsigned *limited = req->limited;
278                 float           penalty = weight * DEF_FACTOR;
279                 give_penalties_for_limits(live_nodes, penalty, limited, node);
280         }
281
282         if (req->type & arch_register_req_type_should_be_same) {
283                 ir_node           *insn  = skip_Proj(node);
284                 allocation_info_t *info  = get_allocation_info(node);
285                 int                arity = get_irn_arity(insn);
286                 int                i;
287
288                 float factor = 1.0f / rbitset_popcount(&req->other_same, arity);
289                 for (i = 0; i < arity; ++i) {
290                         ir_node           *op;
291                         unsigned           r;
292                         allocation_info_t *op_info;
293
294                         if (!rbitset_is_set(&req->other_same, i))
295                                 continue;
296
297                         op = get_irn_n(insn, i);
298
299                         /* if we the value at the should_be_same input doesn't die at the
300                          * node, then it is no use to propagate the constraints (since a
301                          * copy will emerge anyway) */
302                         if (ir_nodeset_contains(live_nodes, op))
303                                 continue;
304
305                         op_info = get_allocation_info(op);
306                         for (r = 0; r < n_regs; ++r) {
307                                 op_info->prefs[r] += info->prefs[r] * factor;
308                         }
309                 }
310         }
311 }
312
313 /**
314  * Walker: Runs an a block calculates the preferences for any
315  * node and every register from the considered register class.
316  */
317 static void analyze_block(ir_node *block, void *data)
318 {
319         float        weight = (float)get_block_execfreq(execfreqs, block);
320         ir_nodeset_t live_nodes;
321         (void) data;
322
323         ir_nodeset_init(&live_nodes);
324         be_liveness_end_of_block(lv, cls, block, &live_nodes);
325
326         sched_foreach_reverse(block, node) {
327                 allocation_info_t *info;
328                 int                i;
329                 int                arity;
330
331                 if (is_Phi(node))
332                         break;
333
334                 if (create_preferences) {
335                         ir_node *value;
336                         be_foreach_definition(node, cls, value,
337                                 check_defs(&live_nodes, weight, value);
338                         );
339                 }
340
341                 /* mark last uses */
342                 arity = get_irn_arity(node);
343
344                 /* the allocation info node currently only uses 1 unsigned value
345                    to mark last used inputs. So we will fail for a node with more than
346                    32 inputs. */
347                 if (arity >= (int) sizeof(info->last_uses) * 8) {
348                         panic("Node with more than %d inputs not supported yet",
349                                         (int) sizeof(info->last_uses) * 8);
350                 }
351
352                 info = get_allocation_info(node);
353                 for (i = 0; i < arity; ++i) {
354                         ir_node                   *op  = get_irn_n(node, i);
355                         const arch_register_req_t *req = arch_get_irn_register_req(op);
356                         if (req->cls != cls)
357                                 continue;
358
359                         /* last usage of a value? */
360                         if (!ir_nodeset_contains(&live_nodes, op)) {
361                                 rbitset_set(info->last_uses, i);
362                         }
363                 }
364
365                 be_liveness_transfer(cls, node, &live_nodes);
366
367                 if (create_preferences) {
368                         /* update weights based on usage constraints */
369                         for (i = 0; i < arity; ++i) {
370                                 const arch_register_req_t *req;
371                                 const unsigned            *limited;
372                                 ir_node                   *op = get_irn_n(node, i);
373
374                                 if (!arch_irn_consider_in_reg_alloc(cls, op))
375                                         continue;
376
377                                 req = arch_get_irn_register_req_in(node, i);
378                                 if (!(req->type & arch_register_req_type_limited))
379                                         continue;
380
381                                 limited = req->limited;
382                                 give_penalties_for_limits(&live_nodes, weight * USE_FACTOR,
383                                                           limited, op);
384                         }
385                 }
386         }
387
388         ir_nodeset_destroy(&live_nodes);
389 }
390
391 static void congruence_def(ir_nodeset_t *live_nodes, const ir_node *node)
392 {
393         const arch_register_req_t *req = arch_get_irn_register_req(node);
394
395         /* should be same constraint? */
396         if (req->type & arch_register_req_type_should_be_same) {
397                 const ir_node *insn  = skip_Proj_const(node);
398                 int      arity = get_irn_arity(insn);
399                 int      i;
400                 unsigned node_idx = get_irn_idx(node);
401                 node_idx          = uf_find(congruence_classes, node_idx);
402
403                 for (i = 0; i < arity; ++i) {
404                         ir_node               *live;
405                         ir_node               *op;
406                         int                    op_idx;
407                         ir_nodeset_iterator_t  iter;
408                         bool                   interferes = false;
409
410                         if (!rbitset_is_set(&req->other_same, i))
411                                 continue;
412
413                         op     = get_irn_n(insn, i);
414                         op_idx = get_irn_idx(op);
415                         op_idx = uf_find(congruence_classes, op_idx);
416
417                         /* do we interfere with the value */
418                         foreach_ir_nodeset(live_nodes, live, iter) {
419                                 int lv_idx = get_irn_idx(live);
420                                 lv_idx     = uf_find(congruence_classes, lv_idx);
421                                 if (lv_idx == op_idx) {
422                                         interferes = true;
423                                         break;
424                                 }
425                         }
426                         /* don't put in same affinity class if we interfere */
427                         if (interferes)
428                                 continue;
429
430                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
431                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
432                             node, op));
433                         /* one should_be_same is enough... */
434                         break;
435                 }
436         }
437 }
438
439 static void create_congruence_class(ir_node *block, void *data)
440 {
441         ir_nodeset_t live_nodes;
442
443         (void) data;
444         ir_nodeset_init(&live_nodes);
445         be_liveness_end_of_block(lv, cls, block, &live_nodes);
446
447         /* check should be same constraints */
448         ir_node *last_phi = NULL;
449         sched_foreach_reverse(block, node) {
450                 ir_node *value;
451                 if (is_Phi(node)) {
452                         last_phi = node;
453                         break;
454                 }
455
456                 be_foreach_definition(node, cls, value,
457                         congruence_def(&live_nodes, value);
458                 );
459                 be_liveness_transfer(cls, node, &live_nodes);
460         }
461         if (!last_phi)
462                 return;
463
464         /* check phi congruence classes */
465         sched_foreach_reverse_from(last_phi, phi) {
466                 int i;
467                 int arity;
468                 int node_idx;
469                 assert(is_Phi(phi));
470
471                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
472                         continue;
473
474                 node_idx = get_irn_idx(phi);
475                 node_idx = uf_find(congruence_classes, node_idx);
476
477                 arity = get_irn_arity(phi);
478                 for (i = 0; i < arity; ++i) {
479                         bool                  interferes = false;
480                         ir_nodeset_iterator_t iter;
481                         unsigned              r;
482                         int                   old_node_idx;
483                         ir_node              *live;
484                         allocation_info_t    *head_info;
485                         allocation_info_t    *other_info;
486                         ir_node              *op     = get_Phi_pred(phi, i);
487                         int                   op_idx = get_irn_idx(op);
488                         op_idx = uf_find(congruence_classes, op_idx);
489
490                         /* do we interfere with the value */
491                         foreach_ir_nodeset(&live_nodes, live, iter) {
492                                 int lv_idx = get_irn_idx(live);
493                                 lv_idx     = uf_find(congruence_classes, lv_idx);
494                                 if (lv_idx == op_idx) {
495                                         interferes = true;
496                                         break;
497                                 }
498                         }
499                         /* don't put in same affinity class if we interfere */
500                         if (interferes)
501                                 continue;
502                         /* any other phi has the same input? */
503                         sched_foreach(block, phi) {
504                                 ir_node *oop;
505                                 int      oop_idx;
506                                 if (!is_Phi(phi))
507                                         break;
508                                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
509                                         continue;
510                                 oop = get_Phi_pred(phi, i);
511                                 if (oop == op)
512                                         continue;
513                                 oop_idx = get_irn_idx(oop);
514                                 oop_idx = uf_find(congruence_classes, oop_idx);
515                                 if (oop_idx == op_idx) {
516                                         interferes = true;
517                                         break;
518                                 }
519                         }
520                         if (interferes)
521                                 continue;
522
523                         /* merge the 2 congruence classes and sum up their preferences */
524                         old_node_idx = node_idx;
525                         node_idx = uf_union(congruence_classes, node_idx, op_idx);
526                         DB((dbg, LEVEL_3, "Merge %+F and %+F congruence classes\n",
527                             phi, op));
528
529                         old_node_idx = node_idx == old_node_idx ? op_idx : old_node_idx;
530                         head_info  = get_allocation_info(get_idx_irn(irg, node_idx));
531                         other_info = get_allocation_info(get_idx_irn(irg, old_node_idx));
532                         for (r = 0; r < n_regs; ++r) {
533                                 head_info->prefs[r] += other_info->prefs[r];
534                         }
535                 }
536         }
537 }
538
539 static void set_congruence_prefs(ir_node *node, void *data)
540 {
541         allocation_info_t *info;
542         allocation_info_t *head_info;
543         unsigned node_idx = get_irn_idx(node);
544         unsigned node_set = uf_find(congruence_classes, node_idx);
545
546         (void) data;
547
548         /* head of congruence class or not in any class */
549         if (node_set == node_idx)
550                 return;
551
552         if (!arch_irn_consider_in_reg_alloc(cls, node))
553                 return;
554
555         head_info = get_allocation_info(get_idx_irn(irg, node_set));
556         info      = get_allocation_info(node);
557
558         memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
559 }
560
561 static void combine_congruence_classes(void)
562 {
563         size_t n = get_irg_last_idx(irg);
564         congruence_classes = XMALLOCN(int, n);
565         uf_init(congruence_classes, n);
566
567         /* create congruence classes */
568         irg_block_walk_graph(irg, create_congruence_class, NULL, NULL);
569         /* merge preferences */
570         irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
571         free(congruence_classes);
572 }
573
574
575
576 /**
577  * Assign register reg to the given node.
578  *
579  * @param node  the node
580  * @param reg   the register
581  */
582 static void use_reg(ir_node *node, const arch_register_t *reg)
583 {
584         unsigned r = arch_register_get_index(reg);
585         assignments[r] = node;
586         arch_set_irn_register(node, reg);
587 }
588
589 static void free_reg_of_value(ir_node *node)
590 {
591         const arch_register_t *reg;
592         unsigned               r;
593
594         if (!arch_irn_consider_in_reg_alloc(cls, node))
595                 return;
596
597         reg        = arch_get_irn_register(node);
598         r          = arch_register_get_index(reg);
599         /* assignment->value may be NULL if a value is used at 2 inputs
600            so it gets freed twice. */
601         assert(assignments[r] == node || assignments[r] == NULL);
602         assignments[r] = NULL;
603 }
604
605 /**
606  * Compare two register preferences in decreasing order.
607  */
608 static int compare_reg_pref(const void *e1, const void *e2)
609 {
610         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
611         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
612         if (rp1->pref < rp2->pref)
613                 return 1;
614         if (rp1->pref > rp2->pref)
615                 return -1;
616         return 0;
617 }
618
619 static void fill_sort_candidates(reg_pref_t *regprefs,
620                                  const allocation_info_t *info)
621 {
622         unsigned r;
623
624         for (r = 0; r < n_regs; ++r) {
625                 float pref = info->prefs[r];
626                 regprefs[r].num  = r;
627                 regprefs[r].pref = pref;
628         }
629         /* TODO: use a stable sort here to avoid unnecessary register jumping */
630         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
631 }
632
633 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
634                                  float pref, float pref_delta,
635                                  unsigned *forbidden_regs, int recursion)
636 {
637         const arch_register_t *from_reg;
638         const arch_register_t *reg;
639         ir_node               *original_insn;
640         ir_node               *block;
641         ir_node               *copy;
642         unsigned               r = 0;
643         unsigned               from_r;
644         unsigned               i;
645         allocation_info_t     *info = get_allocation_info(to_split);
646         reg_pref_t            *prefs;
647         float                  delta = 0;
648         float                  split_threshold;
649
650         (void) pref;
651
652         /* stupid hack: don't optimisticallt split don't spill nodes...
653          * (so we don't split away the values produced because of
654          *  must_be_different constraints) */
655         original_insn = skip_Proj(info->original_value);
656         if (arch_get_irn_flags(original_insn) & arch_irn_flags_dont_spill)
657                 return false;
658
659         from_reg        = arch_get_irn_register(to_split);
660         from_r          = arch_register_get_index(from_reg);
661         block           = get_nodes_block(before);
662         split_threshold = (float)get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
663
664         if (pref_delta < split_threshold*0.5)
665                 return false;
666
667         /* find the best free position where we could move to */
668         prefs = ALLOCAN(reg_pref_t, n_regs);
669         fill_sort_candidates(prefs, info);
670         for (i = 0; i < n_regs; ++i) {
671                 float apref;
672                 float apref_delta;
673                 bool  res;
674                 bool  old_source_state;
675
676                 /* we need a normal register which is not an output register
677                    an different from the current register of to_split */
678                 r = prefs[i].num;
679                 if (!rbitset_is_set(normal_regs, r))
680                         continue;
681                 if (rbitset_is_set(forbidden_regs, r))
682                         continue;
683                 if (r == from_r)
684                         continue;
685
686                 /* is the split worth it? */
687                 delta = pref_delta + prefs[i].pref;
688                 if (delta < split_threshold) {
689                         DB((dbg, LEVEL_3, "Not doing optimistical split of %+F (depth %d), win %f too low\n",
690                                 to_split, recursion, delta));
691                         return false;
692                 }
693
694                 /* if the register is free then we can do the split */
695                 if (assignments[r] == NULL)
696                         break;
697
698                 /* otherwise we might try recursively calling optimistic_split */
699                 if (recursion+1 > MAX_OPTIMISTIC_SPLIT_RECURSION)
700                         continue;
701
702                 apref        = prefs[i].pref;
703                 apref_delta  = i+1 < n_regs ? apref - prefs[i+1].pref : 0;
704                 apref_delta += pref_delta - split_threshold;
705
706                 /* our source register isn't a useful destination for recursive
707                    splits */
708                 old_source_state = rbitset_is_set(forbidden_regs, from_r);
709                 rbitset_set(forbidden_regs, from_r);
710                 /* try recursive split */
711                 res = try_optimistic_split(assignments[r], before, apref,
712                                            apref_delta, forbidden_regs, recursion+1);
713                 /* restore our destination */
714                 if (old_source_state) {
715                         rbitset_set(forbidden_regs, from_r);
716                 } else {
717                         rbitset_clear(forbidden_regs, from_r);
718                 }
719
720                 if (res)
721                         break;
722         }
723         if (i >= n_regs)
724                 return false;
725
726         reg  = arch_register_for_index(cls, r);
727         copy = be_new_Copy(block, to_split);
728         mark_as_copy_of(copy, to_split);
729         /* hacky, but correct here */
730         if (assignments[arch_register_get_index(from_reg)] == to_split)
731                 free_reg_of_value(to_split);
732         use_reg(copy, reg);
733         sched_add_before(before, copy);
734
735         DB((dbg, LEVEL_3,
736             "Optimistic live-range split %+F move %+F(%s) -> %s before %+F (win %f, depth %d)\n",
737             copy, to_split, from_reg->name, reg->name, before, delta, recursion));
738         return true;
739 }
740
741 /**
742  * Determine and assign a register for node @p node
743  */
744 static void assign_reg(const ir_node *block, ir_node *node,
745                        unsigned *forbidden_regs)
746 {
747         const arch_register_t     *final_reg;
748         allocation_info_t         *info;
749         const arch_register_req_t *req;
750         reg_pref_t                *reg_prefs;
751         ir_node                   *in_node;
752         unsigned                   r;
753         const unsigned            *allowed_regs;
754         unsigned                   final_reg_index = 0;
755
756         assert(!is_Phi(node));
757         /* preassigned register? */
758         final_reg = arch_get_irn_register(node);
759         if (final_reg != NULL) {
760                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, final_reg->name));
761                 use_reg(node, final_reg);
762                 return;
763         }
764
765         req = arch_get_irn_register_req(node);
766         /* ignore reqs must be preassigned */
767         assert (! (req->type & arch_register_req_type_ignore));
768
769         /* give should_be_same boni */
770         info    = get_allocation_info(node);
771         in_node = skip_Proj(node);
772         if (req->type & arch_register_req_type_should_be_same) {
773                 float weight = (float)get_block_execfreq(execfreqs, block);
774                 int   arity  = get_irn_arity(in_node);
775                 int   i;
776
777                 assert(arity <= (int) sizeof(req->other_same) * 8);
778                 for (i = 0; i < arity; ++i) {
779                         ir_node               *in;
780                         const arch_register_t *reg;
781                         unsigned               reg_index;
782                         if (!rbitset_is_set(&req->other_same, i))
783                                 continue;
784
785                         in  = get_irn_n(in_node, i);
786                         reg = arch_get_irn_register(in);
787                         assert(reg != NULL);
788                         reg_index = arch_register_get_index(reg);
789
790                         /* if the value didn't die here then we should not propagate the
791                          * should_be_same info */
792                         if (assignments[reg_index] == in)
793                                 continue;
794
795                         info->prefs[reg_index] += weight * AFF_SHOULD_BE_SAME;
796                 }
797         }
798
799         /* create list of register candidates and sort by their preference */
800         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
801         reg_prefs = ALLOCAN(reg_pref_t, n_regs);
802         fill_sort_candidates(reg_prefs, info);
803         for (r = 0; r < n_regs; ++r) {
804                 unsigned num = reg_prefs[r].num;
805                 const arch_register_t *reg;
806
807                 if (!rbitset_is_set(normal_regs, num))
808                         continue;
809                 reg = arch_register_for_index(cls, num);
810                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[r].pref));
811         }
812         DB((dbg, LEVEL_2, "\n"));
813
814         allowed_regs = normal_regs;
815         if (req->type & arch_register_req_type_limited) {
816                 allowed_regs = req->limited;
817         }
818
819         for (r = 0; r < n_regs; ++r) {
820                 float   pref, delta;
821                 ir_node *before;
822                 bool    res;
823
824                 final_reg_index = reg_prefs[r].num;
825                 if (!rbitset_is_set(allowed_regs, final_reg_index))
826                         continue;
827                 /* alignment constraint? */
828                 if (req->width > 1 && (req->type & arch_register_req_type_aligned)
829                                 && (final_reg_index % req->width) != 0)
830                         continue;
831
832                 if (assignments[final_reg_index] == NULL)
833                         break;
834                 pref   = reg_prefs[r].pref;
835                 delta  = r+1 < n_regs ? pref - reg_prefs[r+1].pref : 0;
836                 before = skip_Proj(node);
837                 res    = try_optimistic_split(assignments[final_reg_index], before,
838                                               pref, delta, forbidden_regs, 0);
839                 if (res)
840                         break;
841         }
842         if (r >= n_regs) {
843                 /* the common reason to hit this panic is when 1 of your nodes is not
844                  * register pressure faithful */
845                 panic("No register left for %+F\n", node);
846         }
847
848         final_reg = arch_register_for_index(cls, final_reg_index);
849         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, final_reg->name));
850         use_reg(node, final_reg);
851 }
852
853 /**
854  * Add an permutation in front of a node and change the assignments
855  * due to this permutation.
856  *
857  * To understand this imagine a permutation like this:
858  *
859  * 1 -> 2
860  * 2 -> 3
861  * 3 -> 1, 5
862  * 4 -> 6
863  * 5
864  * 6
865  * 7 -> 7
866  *
867  * First we count how many destinations a single value has. At the same time
868  * we can be sure that each destination register has at most 1 source register
869  * (it can have 0 which means we don't care what value is in it).
870  * We ignore all fulfilled permuations (like 7->7)
871  * In a first pass we create as much copy instructions as possible as they
872  * are generally cheaper than exchanges. We do this by counting into how many
873  * destinations a register has to be copied (in the example it's 2 for register
874  * 3, or 1 for the registers 1,2,4 and 7).
875  * We can then create a copy into every destination register when the usecount
876  * of that register is 0 (= noone else needs the value in the register).
877  *
878  * After this step we should only have cycles left. We implement a cyclic
879  * permutation of n registers with n-1 transpositions.
880  *
881  * @param live_nodes   the set of live nodes, updated due to live range split
882  * @param before       the node before we add the permutation
883  * @param permutation  the permutation array indices are the destination
884  *                     registers, the values in the array are the source
885  *                     registers.
886  */
887 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
888                            unsigned *permutation)
889 {
890         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
891         ir_node   *block;
892         unsigned   r;
893
894         /* determine how often each source register needs to be read */
895         for (r = 0; r < n_regs; ++r) {
896                 unsigned  old_reg = permutation[r];
897                 ir_node  *value;
898
899                 value = assignments[old_reg];
900                 if (value == NULL) {
901                         /* nothing to do here, reg is not live. Mark it as fixpoint
902                          * so we ignore it in the next steps */
903                         permutation[r] = r;
904                         continue;
905                 }
906
907                 ++n_used[old_reg];
908         }
909
910         block = get_nodes_block(before);
911
912         /* step1: create copies where immediately possible */
913         for (r = 0; r < n_regs; /* empty */) {
914                 ir_node *copy;
915                 ir_node *src;
916                 const arch_register_t *reg;
917                 unsigned               old_r = permutation[r];
918
919                 /* - no need to do anything for fixed points.
920                    - we can't copy if the value in the dest reg is still needed */
921                 if (old_r == r || n_used[r] > 0) {
922                         ++r;
923                         continue;
924                 }
925
926                 /* create a copy */
927                 src  = assignments[old_r];
928                 copy = be_new_Copy(block, src);
929                 sched_add_before(before, copy);
930                 reg = arch_register_for_index(cls, r);
931                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
932                     copy, src, before, reg->name));
933                 mark_as_copy_of(copy, src);
934                 use_reg(copy, reg);
935
936                 if (live_nodes != NULL) {
937                         ir_nodeset_insert(live_nodes, copy);
938                 }
939
940                 /* old register has 1 user less, permutation is resolved */
941                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
942                 permutation[r] = r;
943
944                 assert(n_used[old_r] > 0);
945                 --n_used[old_r];
946                 if (n_used[old_r] == 0) {
947                         if (live_nodes != NULL) {
948                                 ir_nodeset_remove(live_nodes, src);
949                         }
950                         free_reg_of_value(src);
951                 }
952
953                 /* advance or jump back (if this copy enabled another copy) */
954                 if (old_r < r && n_used[old_r] == 0) {
955                         r = old_r;
956                 } else {
957                         ++r;
958                 }
959         }
960
961         /* at this point we only have "cycles" left which we have to resolve with
962          * perm instructions
963          * TODO: if we have free registers left, then we should really use copy
964          * instructions for any cycle longer than 2 registers...
965          * (this is probably architecture dependent, there might be archs where
966          *  copies are preferable even for 2-cycles) */
967
968         /* create perms with the rest */
969         for (r = 0; r < n_regs; /* empty */) {
970                 const arch_register_t *reg;
971                 unsigned  old_r = permutation[r];
972                 unsigned  r2;
973                 ir_node  *in[2];
974                 ir_node  *perm;
975                 ir_node  *proj0;
976                 ir_node  *proj1;
977
978                 if (old_r == r) {
979                         ++r;
980                         continue;
981                 }
982
983                 /* we shouldn't have copies from 1 value to multiple destinations left*/
984                 assert(n_used[old_r] == 1);
985
986                 /* exchange old_r and r2; after that old_r is a fixed point */
987                 r2 = permutation[old_r];
988
989                 in[0] = assignments[r2];
990                 in[1] = assignments[old_r];
991                 perm = be_new_Perm(cls, block, 2, in);
992                 sched_add_before(before, perm);
993                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
994                     perm, in[0], in[1], before));
995
996                 proj0 = new_r_Proj(perm, get_irn_mode(in[0]), 0);
997                 mark_as_copy_of(proj0, in[0]);
998                 reg = arch_register_for_index(cls, old_r);
999                 use_reg(proj0, reg);
1000
1001                 proj1 = new_r_Proj(perm, get_irn_mode(in[1]), 1);
1002                 mark_as_copy_of(proj1, in[1]);
1003                 reg = arch_register_for_index(cls, r2);
1004                 use_reg(proj1, reg);
1005
1006                 /* 1 value is now in the correct register */
1007                 permutation[old_r] = old_r;
1008                 /* the source of r changed to r2 */
1009                 permutation[r] = r2;
1010
1011                 /* if we have reached a fixpoint update data structures */
1012                 if (live_nodes != NULL) {
1013                         ir_nodeset_remove(live_nodes, in[0]);
1014                         ir_nodeset_remove(live_nodes, in[1]);
1015                         ir_nodeset_remove(live_nodes, proj0);
1016                         ir_nodeset_insert(live_nodes, proj1);
1017                 }
1018         }
1019
1020 #ifdef DEBUG_libfirm
1021         /* now we should only have fixpoints left */
1022         for (r = 0; r < n_regs; ++r) {
1023                 assert(permutation[r] == r);
1024         }
1025 #endif
1026 }
1027
1028 /**
1029  * Free regs for values last used.
1030  *
1031  * @param live_nodes   set of live nodes, will be updated
1032  * @param node         the node to consider
1033  */
1034 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
1035 {
1036         allocation_info_t *info      = get_allocation_info(node);
1037         const unsigned    *last_uses = info->last_uses;
1038         int                arity     = get_irn_arity(node);
1039         int                i;
1040
1041         for (i = 0; i < arity; ++i) {
1042                 ir_node *op;
1043
1044                 /* check if one operand is the last use */
1045                 if (!rbitset_is_set(last_uses, i))
1046                         continue;
1047
1048                 op = get_irn_n(node, i);
1049                 free_reg_of_value(op);
1050                 ir_nodeset_remove(live_nodes, op);
1051         }
1052 }
1053
1054 /**
1055  * change inputs of a node to the current value (copies/perms)
1056  */
1057 static void rewire_inputs(ir_node *node)
1058 {
1059         int i;
1060         int arity = get_irn_arity(node);
1061
1062         for (i = 0; i < arity; ++i) {
1063                 ir_node           *op = get_irn_n(node, i);
1064                 allocation_info_t *info = try_get_allocation_info(op);
1065
1066                 if (info == NULL)
1067                         continue;
1068
1069                 info = get_allocation_info(info->original_value);
1070                 if (info->current_value != op) {
1071                         set_irn_n(node, i, info->current_value);
1072                 }
1073         }
1074 }
1075
1076 /**
1077  * Create a bitset of registers occupied with value living through an
1078  * instruction
1079  */
1080 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
1081 {
1082         const allocation_info_t *info = get_allocation_info(node);
1083         unsigned r;
1084         int i;
1085         int arity;
1086
1087         /* mark all used registers as potentially live-through */
1088         for (r = 0; r < n_regs; ++r) {
1089                 if (assignments[r] == NULL)
1090                         continue;
1091                 if (!rbitset_is_set(normal_regs, r))
1092                         continue;
1093
1094                 rbitset_set(bitset, r);
1095         }
1096
1097         /* remove registers of value dying at the instruction */
1098         arity = get_irn_arity(node);
1099         for (i = 0; i < arity; ++i) {
1100                 ir_node               *op;
1101                 const arch_register_t *reg;
1102
1103                 if (!rbitset_is_set(info->last_uses, i))
1104                         continue;
1105
1106                 op  = get_irn_n(node, i);
1107                 reg = arch_get_irn_register(op);
1108                 rbitset_clear(bitset, arch_register_get_index(reg));
1109         }
1110 }
1111
1112 static void solve_lpp(ir_nodeset_t *live_nodes, ir_node *node,
1113                       unsigned *forbidden_regs, unsigned *live_through_regs)
1114 {
1115         unsigned *forbidden_edges = rbitset_malloc(n_regs * n_regs);
1116         int      *lpp_vars        = XMALLOCNZ(int, n_regs*n_regs);
1117         int       arity           = get_irn_arity(node);
1118         int       i;
1119         unsigned  l;
1120         unsigned  r;
1121
1122         lpp_t *lpp = lpp_new("prefalloc", lpp_minimize);
1123         //lpp_set_time_limit(lpp, 20);
1124         lpp_set_log(lpp, stdout);
1125
1126         /** mark some edges as forbidden */
1127         for (i = 0; i < arity; ++i) {
1128                 ir_node                   *op = get_irn_n(node, i);
1129                 const arch_register_t     *reg;
1130                 const arch_register_req_t *req;
1131                 const unsigned            *limited;
1132                 unsigned                   current_reg;
1133
1134                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1135                         continue;
1136
1137                 req = arch_get_irn_register_req_in(node, i);
1138                 if (!(req->type & arch_register_req_type_limited))
1139                         continue;
1140
1141                 limited     = req->limited;
1142                 reg         = arch_get_irn_register(op);
1143                 current_reg = arch_register_get_index(reg);
1144                 for (r = 0; r < n_regs; ++r) {
1145                         if (rbitset_is_set(limited, r))
1146                                 continue;
1147
1148                         rbitset_set(forbidden_edges, current_reg*n_regs + r);
1149                 }
1150         }
1151
1152         /* add all combinations, except for not allowed ones */
1153         for (l = 0; l < n_regs; ++l) {
1154                 if (!rbitset_is_set(normal_regs, l)) {
1155                         char name[15];
1156                         snprintf(name, sizeof(name), "%u_to_%u", l, l);
1157                         lpp_vars[l*n_regs+l] = lpp_add_var(lpp, name, lpp_binary, 1);
1158                         continue;
1159                 }
1160
1161                 for (r = 0; r < n_regs; ++r) {
1162                         if (!rbitset_is_set(normal_regs, r))
1163                                 continue;
1164                         if (rbitset_is_set(forbidden_edges, l*n_regs + r))
1165                                 continue;
1166                         /* livethrough values may not use constrained output registers */
1167                         if (rbitset_is_set(live_through_regs, l)
1168                             && rbitset_is_set(forbidden_regs, r))
1169                                 continue;
1170
1171                         char name[15];
1172                         snprintf(name, sizeof(name), "%u_to_%u", l, r);
1173
1174                         double costs = l==r ? 9 : 8;
1175                         lpp_vars[l*n_regs+r]
1176                                 = lpp_add_var(lpp, name, lpp_binary, costs);
1177                         assert(lpp_vars[l*n_regs+r] > 0);
1178                 }
1179         }
1180         /* add constraints */
1181         for (l = 0; l < n_regs; ++l) {
1182                 int constraint;
1183                 /* only 1 destination per register */
1184                 constraint = -1;
1185                 for (r = 0; r < n_regs; ++r) {
1186                         int var = lpp_vars[l*n_regs+r];
1187                         if (var == 0)
1188                                 continue;
1189                         if (constraint < 0) {
1190                                 char name[64];
1191                                 snprintf(name, sizeof(name), "%u_to_dest", l);
1192                                 constraint = lpp_add_cst(lpp, name, lpp_equal, 1);
1193                         }
1194                         lpp_set_factor_fast(lpp, constraint, var, 1);
1195                 }
1196                 /* each destination used by at most 1 value */
1197                 constraint = -1;
1198                 for (r = 0; r < n_regs; ++r) {
1199                         int var = lpp_vars[r*n_regs+l];
1200                         if (var == 0)
1201                                 continue;
1202                         if (constraint < 0) {
1203                                 char name[64];
1204                                 snprintf(name, sizeof(name), "one_to_%u", l);
1205                                 constraint = lpp_add_cst(lpp, name, lpp_less_equal, 1);
1206                         }
1207                         lpp_set_factor_fast(lpp, constraint, var, 1);
1208                 }
1209         }
1210
1211         lpp_dump_plain(lpp, fopen("lppdump.txt", "w"));
1212
1213         /* solve lpp */
1214         {
1215                 unsigned *assignment;
1216                 lpp_solve(lpp, be_options.ilp_server, be_options.ilp_solver);
1217                 if (!lpp_is_sol_valid(lpp))
1218                         panic("ilp solution not valid!");
1219
1220                 assignment = ALLOCAN(unsigned, n_regs);
1221                 for (l = 0; l < n_regs; ++l) {
1222                         unsigned dest_reg = (unsigned)-1;
1223                         for (r = 0; r < n_regs; ++r) {
1224                                 int var = lpp_vars[l*n_regs+r];
1225                                 if (var == 0)
1226                                         continue;
1227                                 double val = lpp_get_var_sol(lpp, var);
1228                                 if (val == 1) {
1229                                         assert(dest_reg == (unsigned)-1);
1230                                         dest_reg = r;
1231                                 }
1232                         }
1233                         assert(dest_reg != (unsigned)-1);
1234                         assignment[dest_reg] = l;
1235                 }
1236
1237                 fprintf(stderr, "Assignment: ");
1238                 for (l = 0; l < n_regs; ++l) {
1239                         fprintf(stderr, "%u ", assignment[l]);
1240                 }
1241                 fprintf(stderr, "\n");
1242                 fflush(stdout);
1243                 permute_values(live_nodes, node, assignment);
1244         }
1245         lpp_free(lpp);
1246 }
1247
1248 static bool is_aligned(unsigned num, unsigned alignment)
1249 {
1250         unsigned mask = alignment-1;
1251         assert(is_po2(alignment));
1252         return (num&mask) == 0;
1253 }
1254
1255 /**
1256  * Enforce constraints at a node by live range splits.
1257  *
1258  * @param  live_nodes  the set of live nodes, might be changed
1259  * @param  node        the current node
1260  */
1261 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
1262                                 unsigned *forbidden_regs)
1263 {
1264         int arity = get_irn_arity(node);
1265         int i, res;
1266         hungarian_problem_t *bp;
1267         unsigned l, r;
1268         unsigned *assignment;
1269         ir_node  *value;
1270
1271         /* construct a list of register occupied by live-through values */
1272         unsigned *live_through_regs = NULL;
1273
1274         /* see if any use constraints are not met and whether double-width
1275          * values are involved */
1276         bool double_width = false;
1277         bool good = true;
1278         for (i = 0; i < arity; ++i) {
1279                 ir_node                   *op = get_irn_n(node, i);
1280                 const arch_register_t     *reg;
1281                 const arch_register_req_t *req;
1282                 const unsigned            *limited;
1283                 unsigned                   reg_index;
1284
1285                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1286                         continue;
1287
1288                 /* are there any limitations for the i'th operand? */
1289                 req = arch_get_irn_register_req_in(node, i);
1290                 if (req->width > 1)
1291                         double_width = true;
1292                 reg       = arch_get_irn_register(op);
1293                 reg_index = arch_register_get_index(reg);
1294                 if (req->type & arch_register_req_type_aligned) {
1295                         if (!is_aligned(reg_index, req->width)) {
1296                                 good = false;
1297                                 continue;
1298                         }
1299                 }
1300                 if (!(req->type & arch_register_req_type_limited))
1301                         continue;
1302
1303                 limited   = req->limited;
1304                 if (!rbitset_is_set(limited, reg_index)) {
1305                         /* found an assignment outside the limited set */
1306                         good = false;
1307                         continue;
1308                 }
1309         }
1310
1311         /* is any of the live-throughs using a constrained output register? */
1312         be_foreach_definition(node, cls, value,
1313                 if (req_->width > 1)
1314                         double_width = true;
1315                 if (! (req_->type & arch_register_req_type_limited))
1316                         continue;
1317                 if (live_through_regs == NULL) {
1318                         rbitset_alloca(live_through_regs, n_regs);
1319                         determine_live_through_regs(live_through_regs, node);
1320                 }
1321                 rbitset_or(forbidden_regs, req_->limited, n_regs);
1322                 if (rbitsets_have_common(req_->limited, live_through_regs, n_regs))
1323                         good = false;
1324         );
1325
1326         if (good)
1327                 return;
1328
1329         /* create these arrays if we haven't yet */
1330         if (live_through_regs == NULL) {
1331                 rbitset_alloca(live_through_regs, n_regs);
1332         }
1333
1334         if (double_width) {
1335                 /* only the ILP variant can solve this yet */
1336                 solve_lpp(live_nodes, node, forbidden_regs, live_through_regs);
1337                 return;
1338         }
1339
1340         /* at this point we have to construct a bipartite matching problem to see
1341          * which values should go to which registers
1342          * Note: We're building the matrix in "reverse" - source registers are
1343          *       right, destinations left because this will produce the solution
1344          *       in the format required for permute_values.
1345          */
1346         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1347
1348         /* add all combinations, then remove not allowed ones */
1349         for (l = 0; l < n_regs; ++l) {
1350                 if (!rbitset_is_set(normal_regs, l)) {
1351                         hungarian_add(bp, l, l, 1);
1352                         continue;
1353                 }
1354
1355                 for (r = 0; r < n_regs; ++r) {
1356                         if (!rbitset_is_set(normal_regs, r))
1357                                 continue;
1358                         /* livethrough values may not use constrainted output registers */
1359                         if (rbitset_is_set(live_through_regs, l)
1360                                         && rbitset_is_set(forbidden_regs, r))
1361                                 continue;
1362
1363                         hungarian_add(bp, r, l, l == r ? 9 : 8);
1364                 }
1365         }
1366
1367         for (i = 0; i < arity; ++i) {
1368                 ir_node                   *op = get_irn_n(node, i);
1369                 const arch_register_t     *reg;
1370                 const arch_register_req_t *req;
1371                 const unsigned            *limited;
1372                 unsigned                   current_reg;
1373
1374                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1375                         continue;
1376
1377                 req = arch_get_irn_register_req_in(node, i);
1378                 if (!(req->type & arch_register_req_type_limited))
1379                         continue;
1380
1381                 limited     = req->limited;
1382                 reg         = arch_get_irn_register(op);
1383                 current_reg = arch_register_get_index(reg);
1384                 for (r = 0; r < n_regs; ++r) {
1385                         if (rbitset_is_set(limited, r))
1386                                 continue;
1387                         hungarian_remove(bp, r, current_reg);
1388                 }
1389         }
1390
1391         //hungarian_print_cost_matrix(bp, 1);
1392         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1393
1394         assignment = ALLOCAN(unsigned, n_regs);
1395         res = hungarian_solve(bp, assignment, NULL, 0);
1396         assert(res == 0);
1397
1398 #if 0
1399         fprintf(stderr, "Swap result:");
1400         for (i = 0; i < (int) n_regs; ++i) {
1401                 fprintf(stderr, " %d", assignment[i]);
1402         }
1403         fprintf(stderr, "\n");
1404 #endif
1405
1406         hungarian_free(bp);
1407
1408         permute_values(live_nodes, node, assignment);
1409 }
1410
1411 /** test whether a node @p n is a copy of the value of node @p of */
1412 static bool is_copy_of(ir_node *value, ir_node *test_value)
1413 {
1414         allocation_info_t *test_info;
1415         allocation_info_t *info;
1416
1417         if (value == test_value)
1418                 return true;
1419
1420         info      = get_allocation_info(value);
1421         test_info = get_allocation_info(test_value);
1422         return test_info->original_value == info->original_value;
1423 }
1424
1425 /**
1426  * find a value in the end-assignment of a basic block
1427  * @returns the index into the assignment array if found
1428  *          -1 if not found
1429  */
1430 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1431 {
1432         unsigned   r;
1433         ir_node  **end_assignments = info->assignments;
1434         for (r = 0; r < n_regs; ++r) {
1435                 ir_node *a_value = end_assignments[r];
1436
1437                 if (a_value == NULL)
1438                         continue;
1439                 if (is_copy_of(a_value, value))
1440                         return (int) r;
1441         }
1442
1443         return -1;
1444 }
1445
1446 /**
1447  * Create the necessary permutations at the end of a basic block to fullfill
1448  * the register assignment for phi-nodes in the next block
1449  */
1450 static void add_phi_permutations(ir_node *block, int p)
1451 {
1452         unsigned   r;
1453         unsigned  *permutation;
1454         ir_node  **old_assignments;
1455         bool       need_permutation;
1456         ir_node   *phi;
1457         ir_node   *pred = get_Block_cfgpred_block(block, p);
1458
1459         block_info_t *pred_info = get_block_info(pred);
1460
1461         /* predecessor not processed yet? nothing to do */
1462         if (!pred_info->processed)
1463                 return;
1464
1465         permutation = ALLOCAN(unsigned, n_regs);
1466         for (r = 0; r < n_regs; ++r) {
1467                 permutation[r] = r;
1468         }
1469
1470         /* check phi nodes */
1471         need_permutation = false;
1472         phi = sched_first(block);
1473         for ( ; is_Phi(phi); phi = sched_next(phi)) {
1474                 const arch_register_t *reg;
1475                 const arch_register_t *op_reg;
1476                 int                    regn;
1477                 int                    a;
1478                 ir_node               *op;
1479
1480                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1481                         continue;
1482
1483                 op = get_Phi_pred(phi, p);
1484                 a  = find_value_in_block_info(pred_info, op);
1485                 assert(a >= 0);
1486
1487                 reg  = arch_get_irn_register(phi);
1488                 regn = arch_register_get_index(reg);
1489                 /* same register? nothing to do */
1490                 if (regn == a)
1491                         continue;
1492
1493                 op     = pred_info->assignments[a];
1494                 op_reg = arch_get_irn_register(op);
1495                 /* virtual or joker registers are ok too */
1496                 if ((op_reg->type & arch_register_type_joker)
1497                                 || (op_reg->type & arch_register_type_virtual))
1498                         continue;
1499
1500                 permutation[regn] = a;
1501                 need_permutation  = true;
1502         }
1503
1504         if (need_permutation) {
1505                 /* permute values at end of predecessor */
1506                 old_assignments = assignments;
1507                 assignments     = pred_info->assignments;
1508                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1509                                permutation);
1510                 assignments = old_assignments;
1511         }
1512
1513         /* change phi nodes to use the copied values */
1514         phi = sched_first(block);
1515         for ( ; is_Phi(phi); phi = sched_next(phi)) {
1516                 int      a;
1517                 ir_node *op;
1518
1519                 if (!arch_irn_consider_in_reg_alloc(cls, phi))
1520                         continue;
1521
1522                 op = get_Phi_pred(phi, p);
1523
1524                 /* we have permuted all values into the correct registers so we can
1525                    simply query which value occupies the phis register in the
1526                    predecessor */
1527                 a  = arch_register_get_index(arch_get_irn_register(phi));
1528                 op = pred_info->assignments[a];
1529                 set_Phi_pred(phi, p, op);
1530         }
1531 }
1532
1533 /**
1534  * Set preferences for a phis register based on the registers used on the
1535  * phi inputs.
1536  */
1537 static void adapt_phi_prefs(ir_node *phi)
1538 {
1539         int i;
1540         int arity = get_irn_arity(phi);
1541         ir_node           *block = get_nodes_block(phi);
1542         allocation_info_t *info  = get_allocation_info(phi);
1543
1544         for (i = 0; i < arity; ++i) {
1545                 ir_node               *op  = get_irn_n(phi, i);
1546                 const arch_register_t *reg = arch_get_irn_register(op);
1547                 ir_node               *pred_block;
1548                 block_info_t          *pred_block_info;
1549                 float                  weight;
1550                 unsigned               r;
1551
1552                 if (reg == NULL)
1553                         continue;
1554                 /* we only give the bonus if the predecessor already has registers
1555                  * assigned, otherwise we only see a dummy value
1556                  * and any conclusions about its register are useless */
1557                 pred_block = get_Block_cfgpred_block(block, i);
1558                 pred_block_info = get_block_info(pred_block);
1559                 if (!pred_block_info->processed)
1560                         continue;
1561
1562                 /* give bonus for already assigned register */
1563                 weight = (float)get_block_execfreq(execfreqs, pred_block);
1564                 r      = arch_register_get_index(reg);
1565                 info->prefs[r] += weight * AFF_PHI;
1566         }
1567 }
1568
1569 /**
1570  * After a phi has been assigned a register propagate preference inputs
1571  * to the phi inputs.
1572  */
1573 static void propagate_phi_register(ir_node *phi, unsigned assigned_r)
1574 {
1575         int      i;
1576         ir_node *block = get_nodes_block(phi);
1577         int      arity = get_irn_arity(phi);
1578
1579         for (i = 0; i < arity; ++i) {
1580                 ir_node           *op         = get_Phi_pred(phi, i);
1581                 allocation_info_t *info       = get_allocation_info(op);
1582                 ir_node           *pred_block = get_Block_cfgpred_block(block, i);
1583                 unsigned           r;
1584                 float              weight
1585                         = (float)get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1586
1587                 if (info->prefs[assigned_r] >= weight)
1588                         continue;
1589
1590                 /* promote the prefered register */
1591                 for (r = 0; r < n_regs; ++r) {
1592                         if (info->prefs[r] > -weight) {
1593                                 info->prefs[r] = -weight;
1594                         }
1595                 }
1596                 info->prefs[assigned_r] = weight;
1597
1598                 if (is_Phi(op))
1599                         propagate_phi_register(op, assigned_r);
1600         }
1601 }
1602
1603 static void assign_phi_registers(ir_node *block)
1604 {
1605         int                  n_phis = 0;
1606         int                  n;
1607         int                  res;
1608         unsigned            *assignment;
1609         hungarian_problem_t *bp;
1610
1611         /* count phi nodes */
1612         sched_foreach(block, node) {
1613                 if (!is_Phi(node))
1614                         break;
1615                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1616                         continue;
1617                 ++n_phis;
1618         }
1619
1620         if (n_phis == 0)
1621                 return;
1622
1623         /* build a bipartite matching problem for all phi nodes */
1624         bp = hungarian_new(n_phis, n_regs, HUNGARIAN_MATCH_PERFECT);
1625         n  = 0;
1626         sched_foreach(block, node) {
1627                 unsigned r;
1628
1629                 allocation_info_t *info;
1630                 if (!is_Phi(node))
1631                         break;
1632                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1633                         continue;
1634
1635                 /* give boni for predecessor colorings */
1636                 adapt_phi_prefs(node);
1637                 /* add stuff to bipartite problem */
1638                 info = get_allocation_info(node);
1639                 DB((dbg, LEVEL_3, "Prefs for %+F: ", node));
1640                 for (r = 0; r < n_regs; ++r) {
1641                         float costs;
1642
1643                         if (!rbitset_is_set(normal_regs, r))
1644                                 continue;
1645
1646                         costs = info->prefs[r];
1647                         costs = costs < 0 ? -logf(-costs+1) : logf(costs+1);
1648                         costs *= 100;
1649                         costs += 10000;
1650                         hungarian_add(bp, n, r, (int)costs);
1651                         DB((dbg, LEVEL_3, " %s(%f)", arch_register_for_index(cls, r)->name,
1652                                                 info->prefs[r]));
1653                 }
1654                 DB((dbg, LEVEL_3, "\n"));
1655                 ++n;
1656         }
1657
1658         //hungarian_print_cost_matrix(bp, 7);
1659         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1660
1661         assignment = ALLOCAN(unsigned, n_regs);
1662         res        = hungarian_solve(bp, assignment, NULL, 0);
1663         assert(res == 0);
1664
1665         /* apply results */
1666         n = 0;
1667         sched_foreach(block, node) {
1668                 unsigned               r;
1669                 const arch_register_t *reg;
1670
1671                 if (!is_Phi(node))
1672                         break;
1673                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1674                         continue;
1675
1676                 r = assignment[n++];
1677                 assert(rbitset_is_set(normal_regs, r));
1678                 reg = arch_register_for_index(cls, r);
1679                 DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
1680                 use_reg(node, reg);
1681
1682                 /* adapt preferences for phi inputs */
1683                 if (propagate_phi_registers)
1684                         propagate_phi_register(node, r);
1685         }
1686 }
1687
1688 /**
1689  * Walker: assign registers to all nodes of a block that
1690  * need registers from the currently considered register class.
1691  */
1692 static void allocate_coalesce_block(ir_node *block, void *data)
1693 {
1694         ir_nodeset_t   live_nodes;
1695         int            n_preds;
1696         block_info_t  *block_info;
1697         block_info_t **pred_block_infos;
1698         ir_node      **phi_ins;
1699         unsigned      *forbidden_regs; /**< collects registers which must
1700                                                 not be used for optimistic splits */
1701
1702         (void) data;
1703         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1704
1705         /* clear assignments */
1706         block_info  = get_block_info(block);
1707         assignments = block_info->assignments;
1708
1709         ir_nodeset_init(&live_nodes);
1710
1711         /* gather regalloc infos of predecessor blocks */
1712         n_preds          = get_Block_n_cfgpreds(block);
1713         pred_block_infos = ALLOCAN(block_info_t*, n_preds);
1714         for (int i = 0; i < n_preds; ++i) {
1715                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1716                 block_info_t *pred_info = get_block_info(pred);
1717                 pred_block_infos[i]     = pred_info;
1718         }
1719
1720         phi_ins = ALLOCAN(ir_node*, n_preds);
1721
1722         /* collect live-in nodes and preassigned values */
1723         be_lv_foreach(lv, block, be_lv_state_in, node) {
1724                 bool                       need_phi = false;
1725                 const arch_register_req_t *req;
1726                 const arch_register_t     *reg;
1727                 int                        p;
1728
1729                 req  = arch_get_irn_register_req(node);
1730                 if (req->cls != cls)
1731                         continue;
1732
1733                 if (req->type & arch_register_req_type_ignore) {
1734                         allocation_info_t *info = get_allocation_info(node);
1735                         info->current_value = node;
1736
1737                         reg = arch_get_irn_register(node);
1738                         assert(reg != NULL); /* ignore values must be preassigned */
1739                         use_reg(node, reg);
1740                         continue;
1741                 }
1742
1743                 /* check all predecessors for this value, if it is not everywhere the
1744                    same or unknown then we have to construct a phi
1745                    (we collect the potential phi inputs here) */
1746                 for (p = 0; p < n_preds; ++p) {
1747                         block_info_t *pred_info = pred_block_infos[p];
1748
1749                         if (!pred_info->processed) {
1750                                 /* use node for now, it will get fixed later */
1751                                 phi_ins[p] = node;
1752                                 need_phi   = true;
1753                         } else {
1754                                 int a = find_value_in_block_info(pred_info, node);
1755
1756                                 /* must live out of predecessor */
1757                                 assert(a >= 0);
1758                                 phi_ins[p] = pred_info->assignments[a];
1759                                 /* different value from last time? then we need a phi */
1760                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1761                                         need_phi = true;
1762                                 }
1763                         }
1764                 }
1765
1766                 if (need_phi) {
1767                         ir_mode *mode = get_irn_mode(node);
1768                         ir_node *phi  = be_new_Phi(block, n_preds, phi_ins, mode,
1769                                                    cls->class_req);
1770
1771                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1772 #ifdef DEBUG_libfirm
1773                         {
1774                                 int pi;
1775                                 for (pi = 0; pi < n_preds; ++pi) {
1776                                         DB((dbg, LEVEL_3, " %+F", phi_ins[pi]));
1777                                 }
1778                                 DB((dbg, LEVEL_3, "\n"));
1779                         }
1780 #endif
1781                         mark_as_copy_of(phi, node);
1782                         sched_add_after(block, phi);
1783
1784                         node = phi;
1785                 } else {
1786                         allocation_info_t *info = get_allocation_info(node);
1787                         info->current_value = phi_ins[0];
1788
1789                         /* Grab 1 of the inputs we constructed (might not be the same as
1790                          * "node" as we could see the same copy of the value in all
1791                          * predecessors */
1792                         node = phi_ins[0];
1793                 }
1794
1795                 /* if the node already has a register assigned use it */
1796                 reg = arch_get_irn_register(node);
1797                 if (reg != NULL) {
1798                         use_reg(node, reg);
1799                 }
1800
1801                 /* remember that this node is live at the beginning of the block */
1802                 ir_nodeset_insert(&live_nodes, node);
1803         }
1804
1805         rbitset_alloca(forbidden_regs, n_regs);
1806
1807         /* handle phis... */
1808         assign_phi_registers(block);
1809
1810         /* all live-ins must have a register */
1811 #ifdef DEBUG_libfirm
1812         {
1813                 ir_nodeset_iterator_t iter;
1814                 ir_node              *node;
1815                 foreach_ir_nodeset(&live_nodes, node, iter) {
1816                         const arch_register_t *reg = arch_get_irn_register(node);
1817                         assert(reg != NULL);
1818                 }
1819         }
1820 #endif
1821
1822         /* assign instructions in the block */
1823         sched_foreach(block, node) {
1824                 int arity;
1825                 ir_node *value;
1826
1827                 /* phis are already assigned */
1828                 if (is_Phi(node))
1829                         continue;
1830
1831                 rewire_inputs(node);
1832
1833                 /* enforce use constraints */
1834                 rbitset_clear_all(forbidden_regs, n_regs);
1835                 enforce_constraints(&live_nodes, node, forbidden_regs);
1836
1837                 rewire_inputs(node);
1838
1839                 /* we may not use registers used for inputs for optimistic splits */
1840                 arity = get_irn_arity(node);
1841                 for (int i = 0; i < arity; ++i) {
1842                         ir_node *op = get_irn_n(node, i);
1843                         const arch_register_t *reg;
1844                         if (!arch_irn_consider_in_reg_alloc(cls, op))
1845                                 continue;
1846
1847                         reg = arch_get_irn_register(op);
1848                         rbitset_set(forbidden_regs, arch_register_get_index(reg));
1849                 }
1850
1851                 /* free registers of values last used at this instruction */
1852                 free_last_uses(&live_nodes, node);
1853
1854                 /* assign output registers */
1855                 be_foreach_definition_(node, cls, value,
1856                         assign_reg(block, value, forbidden_regs);
1857                 );
1858         }
1859
1860         ir_nodeset_destroy(&live_nodes);
1861         assignments = NULL;
1862
1863         block_info->processed = true;
1864
1865         /* permute values at end of predecessor blocks in case of phi-nodes */
1866         if (n_preds > 1) {
1867                 int p;
1868                 for (p = 0; p < n_preds; ++p) {
1869                         add_phi_permutations(block, p);
1870                 }
1871         }
1872
1873         /* if we have exactly 1 successor then we might be able to produce phi
1874            copies now */
1875         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1876                 const ir_edge_t *edge
1877                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1878                 ir_node      *succ      = get_edge_src_irn(edge);
1879                 int           p         = get_edge_src_pos(edge);
1880                 block_info_t *succ_info = get_block_info(succ);
1881
1882                 if (succ_info->processed) {
1883                         add_phi_permutations(succ, p);
1884                 }
1885         }
1886 }
1887
1888 typedef struct block_costs_t block_costs_t;
1889 struct block_costs_t {
1890         float costs;   /**< costs of the block */
1891         int   dfs_num; /**< depth first search number (to detect backedges) */
1892 };
1893
1894 static int cmp_block_costs(const void *d1, const void *d2)
1895 {
1896         const ir_node       * const *block1 = (const ir_node**)d1;
1897         const ir_node       * const *block2 = (const ir_node**)d2;
1898         const block_costs_t *info1  = (const block_costs_t*)get_irn_link(*block1);
1899         const block_costs_t *info2  = (const block_costs_t*)get_irn_link(*block2);
1900         return QSORT_CMP(info2->costs, info1->costs);
1901 }
1902
1903 static void determine_block_order(void)
1904 {
1905         size_t    p;
1906         ir_node **blocklist = be_get_cfgpostorder(irg);
1907         size_t    n_blocks  = ARR_LEN(blocklist);
1908         int       dfs_num   = 0;
1909         pdeq     *worklist  = new_pdeq();
1910         ir_node **order     = XMALLOCN(ir_node*, n_blocks);
1911         size_t    order_p   = 0;
1912
1913         /* clear block links... */
1914         for (p = 0; p < n_blocks; ++p) {
1915                 ir_node *block = blocklist[p];
1916                 set_irn_link(block, NULL);
1917         }
1918
1919         /* walk blocks in reverse postorder, the costs for each block are the
1920          * sum of the costs of its predecessors (excluding the costs on backedges
1921          * which we can't determine) */
1922         for (p = n_blocks; p > 0;) {
1923                 block_costs_t *cost_info;
1924                 ir_node *block = blocklist[--p];
1925
1926                 float execfreq   = (float)get_block_execfreq(execfreqs, block);
1927                 float costs      = execfreq;
1928                 int   n_cfgpreds = get_Block_n_cfgpreds(block);
1929                 int   p2;
1930                 for (p2 = 0; p2 < n_cfgpreds; ++p2) {
1931                         ir_node       *pred_block = get_Block_cfgpred_block(block, p2);
1932                         block_costs_t *pred_costs = (block_costs_t*)get_irn_link(pred_block);
1933                         /* we don't have any info for backedges */
1934                         if (pred_costs == NULL)
1935                                 continue;
1936                         costs += pred_costs->costs;
1937                 }
1938
1939                 cost_info          = OALLOCZ(&obst, block_costs_t);
1940                 cost_info->costs   = costs;
1941                 cost_info->dfs_num = dfs_num++;
1942                 set_irn_link(block, cost_info);
1943         }
1944
1945         /* sort array by block costs */
1946         qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1947
1948         ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1949         inc_irg_block_visited(irg);
1950
1951         for (p = 0; p < n_blocks; ++p) {
1952                 ir_node       *block = blocklist[p];
1953                 if (Block_block_visited(block))
1954                         continue;
1955
1956                 /* continually add predecessors with highest costs to worklist
1957                  * (without using backedges) */
1958                 do {
1959                         block_costs_t *info       = (block_costs_t*)get_irn_link(block);
1960                         ir_node       *best_pred  = NULL;
1961                         float          best_costs = -1;
1962                         int            n_cfgpred  = get_Block_n_cfgpreds(block);
1963                         int            i;
1964
1965                         pdeq_putr(worklist, block);
1966                         mark_Block_block_visited(block);
1967                         for (i = 0; i < n_cfgpred; ++i) {
1968                                 ir_node       *pred_block = get_Block_cfgpred_block(block, i);
1969                                 block_costs_t *pred_info  = (block_costs_t*)get_irn_link(pred_block);
1970
1971                                 /* ignore backedges */
1972                                 if (pred_info->dfs_num > info->dfs_num)
1973                                         continue;
1974
1975                                 if (info->costs > best_costs) {
1976                                         best_costs = info->costs;
1977                                         best_pred  = pred_block;
1978                                 }
1979                         }
1980                         block = best_pred;
1981                 } while (block != NULL && !Block_block_visited(block));
1982
1983                 /* now put all nodes in the worklist in our final order */
1984                 while (!pdeq_empty(worklist)) {
1985                         ir_node *pblock = (ir_node*)pdeq_getr(worklist);
1986                         assert(order_p < n_blocks);
1987                         order[order_p++] = pblock;
1988                 }
1989         }
1990         assert(order_p == n_blocks);
1991         del_pdeq(worklist);
1992
1993         ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1994
1995         DEL_ARR_F(blocklist);
1996
1997         obstack_free(&obst, NULL);
1998         obstack_init(&obst);
1999
2000         block_order   = order;
2001         n_block_order = n_blocks;
2002 }
2003
2004 /**
2005  * Run the register allocator for the current register class.
2006  */
2007 static void be_pref_alloc_cls(void)
2008 {
2009         size_t i;
2010
2011         be_assure_live_sets(irg);
2012         lv = be_get_irg_liveness(irg);
2013
2014         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2015
2016         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
2017
2018         be_clear_links(irg);
2019
2020         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
2021         if (create_congruence_classes)
2022                 combine_congruence_classes();
2023
2024         for (i = 0; i < n_block_order; ++i) {
2025                 ir_node *block = block_order[i];
2026                 allocate_coalesce_block(block, NULL);
2027         }
2028
2029         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2030 }
2031
2032 static void dump(int mask, ir_graph *irg, const char *suffix)
2033 {
2034         if (be_options.dump_flags & mask)
2035                 dump_ir_graph(irg, suffix);
2036 }
2037
2038 /**
2039  * Run the spiller on the current graph.
2040  */
2041 static void spill(void)
2042 {
2043         /* make sure all nodes show their real register pressure */
2044         be_timer_push(T_RA_CONSTR);
2045         be_pre_spill_prepare_constr(irg, cls);
2046         be_timer_pop(T_RA_CONSTR);
2047
2048         dump(DUMP_RA, irg, "spillprepare");
2049
2050         /* spill */
2051         be_timer_push(T_RA_SPILL);
2052         be_do_spill(irg, cls);
2053         be_timer_pop(T_RA_SPILL);
2054
2055         be_timer_push(T_RA_SPILL_APPLY);
2056         check_for_memory_operands(irg);
2057         be_timer_pop(T_RA_SPILL_APPLY);
2058
2059         dump(DUMP_RA, irg, "spill");
2060 }
2061
2062 /**
2063  * The pref register allocator for a whole procedure.
2064  */
2065 static void be_pref_alloc(ir_graph *new_irg)
2066 {
2067         const arch_env_t *arch_env = be_get_irg_arch_env(new_irg);
2068         int   n_cls                = arch_env->n_register_classes;
2069         int   c;
2070
2071         obstack_init(&obst);
2072
2073         irg       = new_irg;
2074         execfreqs = be_get_irg_exec_freq(irg);
2075
2076         /* determine a good coloring order */
2077         determine_block_order();
2078
2079         for (c = 0; c < n_cls; ++c) {
2080                 cls = &arch_env->register_classes[c];
2081                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
2082                         continue;
2083
2084                 stat_ev_ctx_push_str("regcls", cls->name);
2085
2086                 n_regs      = arch_register_class_n_regs(cls);
2087                 normal_regs = rbitset_malloc(n_regs);
2088                 be_set_allocatable_regs(irg, cls, normal_regs);
2089
2090                 spill();
2091
2092                 /* verify schedule and register pressure */
2093                 be_timer_push(T_VERIFY);
2094                 if (be_options.verify_option == BE_VERIFY_WARN) {
2095                         be_verify_schedule(irg);
2096                         be_verify_register_pressure(irg, cls);
2097                 } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
2098                         assert(be_verify_schedule(irg) && "Schedule verification failed");
2099                         assert(be_verify_register_pressure(irg, cls)
2100                                 && "Register pressure verification failed");
2101                 }
2102                 be_timer_pop(T_VERIFY);
2103
2104                 be_timer_push(T_RA_COLOR);
2105                 be_pref_alloc_cls();
2106                 be_timer_pop(T_RA_COLOR);
2107
2108                 /* we most probably constructed new Phis so liveness info is invalid
2109                  * now */
2110                 be_invalidate_live_sets(irg);
2111                 free(normal_regs);
2112
2113                 stat_ev_ctx_pop("regcls");
2114         }
2115
2116         be_timer_push(T_RA_SPILL_APPLY);
2117         be_abi_fix_stack_nodes(irg);
2118         be_timer_pop(T_RA_SPILL_APPLY);
2119
2120         be_timer_push(T_VERIFY);
2121         if (be_options.verify_option == BE_VERIFY_WARN) {
2122                 be_verify_register_allocation(irg);
2123         } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
2124                 assert(be_verify_register_allocation(irg)
2125                        && "Register allocation invalid");
2126         }
2127         be_timer_pop(T_VERIFY);
2128
2129         obstack_free(&obst, NULL);
2130 }
2131
2132 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_pref_alloc)
2133 void be_init_pref_alloc(void)
2134 {
2135         static be_ra_t be_ra_pref = {
2136                 be_pref_alloc,
2137         };
2138         lc_opt_entry_t *be_grp              = lc_opt_get_grp(firm_opt_get_root(), "be");
2139         lc_opt_entry_t *prefalloc_group = lc_opt_get_grp(be_grp, "prefalloc");
2140         lc_opt_add_table(prefalloc_group, options);
2141
2142         be_register_allocator("pref", &be_ra_pref);
2143         FIRM_DBG_REGISTER(dbg, "firm.be.prefalloc");
2144 }