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