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