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