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