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