new heursitic for good coloring order; add utility function to generate a postorder
[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
53 #include "error.h"
54 #include "execfreq.h"
55 #include "ircons.h"
56 #include "irdom.h"
57 #include "iredges_t.h"
58 #include "irgraph_t.h"
59 #include "irgwalk.h"
60 #include "irnode_t.h"
61 #include "irprintf.h"
62 #include "obst.h"
63 #include "raw_bitset.h"
64 #include "unionfind.h"
65 #include "pdeq.h"
66 #include "hungarian.h"
67
68 #include "beabi.h"
69 #include "bechordal_t.h"
70 #include "be.h"
71 #include "beirg.h"
72 #include "belive_t.h"
73 #include "bemodule.h"
74 #include "benode_t.h"
75 #include "bera.h"
76 #include "besched.h"
77 #include "bespill.h"
78 #include "bespillutil.h"
79 #include "beverify.h"
80 #include "beutil.h"
81
82 #define USE_FACTOR         1.0f
83 #define DEF_FACTOR         1.0f
84 #define NEIGHBOR_FACTOR    0.2f
85 #define AFF_SHOULD_BE_SAME 0.5f
86 #define AFF_PHI            1.0f
87 #define SPLIT_DELTA        1.0f
88
89 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
90
91 static struct obstack               obst;
92 static be_irg_t                    *birg;
93 static ir_graph                    *irg;
94 static const arch_register_class_t *cls;
95 static const arch_register_req_t   *default_cls_req;
96 static be_lv_t                     *lv;
97 static const ir_exec_freq          *execfreqs;
98 static unsigned                     n_regs;
99 static unsigned                    *normal_regs;
100 static int                         *congruence_classes;
101 static ir_node                    **block_order;
102 static int                          n_block_order;
103
104 /** currently active assignments (while processing a basic block)
105  * maps registers to values(their current copies) */
106 static ir_node **assignments;
107
108 /**
109  * allocation information: last_uses, register preferences
110  * the information is per firm-node.
111  */
112 struct allocation_info_t {
113         unsigned  last_uses;      /**< bitset indicating last uses (input pos) */
114         ir_node  *current_value;  /**< copy of the value that should be used */
115         ir_node  *original_value; /**< for copies point to original value */
116         unsigned char should_be_same[2];
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 create_congurence_class(ir_node *node, void *data)
401 {
402         (void) data;
403         if (is_Phi(node)) {
404                 int      i;
405                 int      arity   = get_irn_arity(node);
406                 unsigned phi_idx = get_irn_idx(node);
407                 phi_idx     = uf_find(congruence_classes, phi_idx);
408                 for (i = 0; i < arity; ++i) {
409                         ir_node *op     = get_Phi_pred(node, i);
410                         int      op_idx = get_irn_idx(op);
411                         op_idx  = uf_find(congruence_classes, op_idx);
412                         phi_idx = uf_union(congruence_classes, phi_idx, op_idx);
413                 }
414                 return;
415         }
416         /* should be same constraint? */
417         if (is_Proj(node)) {
418                 const arch_register_req_t *req = arch_get_register_req_out(node);
419                 if (req->type & arch_register_req_type_should_be_same) {
420                         ir_node *pred  = get_Proj_pred(node);
421                         int      arity = get_irn_arity(pred);
422                         int      i;
423                         unsigned node_idx = get_irn_idx(node);
424                         node_idx          = uf_find(congruence_classes, node_idx);
425
426                         for (i = 0; i < arity; ++i) {
427                                 ir_node *op;
428                                 unsigned op_idx;
429
430                                 if (!rbitset_is_set(&req->other_same, i))
431                                         continue;
432
433                                 op     = get_irn_n(pred, i);
434                                 op_idx = get_irn_idx(op);
435                                 op_idx = uf_find(congruence_classes, op_idx);
436                                 node_idx = uf_union(congruence_classes, node_idx, op_idx);
437                         }
438                 }
439                 return;
440         }
441 }
442
443 static void merge_congruence_prefs(ir_node *node, void *data)
444 {
445         allocation_info_t *info;
446         allocation_info_t *head_info;
447         unsigned node_idx = get_irn_idx(node);
448         unsigned node_set = uf_find(congruence_classes, node_idx);
449         unsigned r;
450
451         (void) data;
452
453         /* head of congruence class or not in any class */
454         if (node_set == node_idx)
455                 return;
456
457         if (!arch_irn_consider_in_reg_alloc(cls, node))
458                 return;
459
460         head_info = get_allocation_info(get_idx_irn(irg, node_set));
461         info      = get_allocation_info(node);
462
463         for (r = 0; r < n_regs; ++r) {
464                 head_info->prefs[r] += info->prefs[r];
465         }
466 }
467
468 static void set_congruence_prefs(ir_node *node, void *data)
469 {
470         allocation_info_t *info;
471         allocation_info_t *head_info;
472         unsigned node_idx = get_irn_idx(node);
473         unsigned node_set = uf_find(congruence_classes, node_idx);
474
475         (void) data;
476
477         /* head of congruence class or not in any class */
478         if (node_set == node_idx)
479                 return;
480
481         if (!arch_irn_consider_in_reg_alloc(cls, node))
482                 return;
483
484         head_info = get_allocation_info(get_idx_irn(irg, node_set));
485         info      = get_allocation_info(node);
486
487         memcpy(info->prefs, head_info->prefs, n_regs * sizeof(info->prefs[0]));
488 }
489
490 static void combine_congruence_classes(void)
491 {
492         size_t n = get_irg_last_idx(irg);
493         congruence_classes = XMALLOCN(int, n);
494         uf_init(congruence_classes, n);
495
496         /* create congruence classes */
497         irg_walk_graph(irg, create_congurence_class, NULL, NULL);
498         /* merge preferences */
499         irg_walk_graph(irg, merge_congruence_prefs, NULL, NULL);
500         irg_walk_graph(irg, set_congruence_prefs, NULL, NULL);
501 }
502
503
504
505
506
507 /**
508  * Assign register reg to the given node.
509  *
510  * @param node  the node
511  * @param reg   the register
512  */
513 static void use_reg(ir_node *node, const arch_register_t *reg)
514 {
515         unsigned r = arch_register_get_index(reg);
516         assignments[r] = node;
517         arch_set_irn_register(node, reg);
518 }
519
520 static void free_reg_of_value(ir_node *node)
521 {
522         const arch_register_t *reg;
523         unsigned               r;
524
525         if (!arch_irn_consider_in_reg_alloc(cls, node))
526                 return;
527
528         reg        = arch_get_irn_register(node);
529         r          = arch_register_get_index(reg);
530         /* assignment->value may be NULL if a value is used at 2 inputs
531            so it gets freed twice. */
532         assert(assignments[r] == node || assignments[r] == NULL);
533         assignments[r] = NULL;
534 }
535
536 /**
537  * Compare two register preferences in decreasing order.
538  */
539 static int compare_reg_pref(const void *e1, const void *e2)
540 {
541         const reg_pref_t *rp1 = (const reg_pref_t*) e1;
542         const reg_pref_t *rp2 = (const reg_pref_t*) e2;
543         if (rp1->pref < rp2->pref)
544                 return 1;
545         if (rp1->pref > rp2->pref)
546                 return -1;
547         return 0;
548 }
549
550 static void fill_sort_candidates(reg_pref_t *regprefs,
551                                  const allocation_info_t *info)
552 {
553         unsigned r;
554
555         for (r = 0; r < n_regs; ++r) {
556                 float pref = info->prefs[r];
557                 regprefs[r].num  = r;
558                 regprefs[r].pref = pref;
559         }
560         /* TODO: use a stable sort here to avoid unnecessary register jumping */
561         qsort(regprefs, n_regs, sizeof(regprefs[0]), compare_reg_pref);
562 }
563
564 static bool try_optimistic_split(ir_node *to_split, ir_node *before,
565                                  float pref, float pref_delta,
566                                  unsigned *output_regs)
567 {
568         const arch_register_t *reg;
569         ir_node               *original_insn;
570         ir_node               *block;
571         ir_node               *copy;
572         unsigned               r;
573         unsigned               i;
574         allocation_info_t     *info = get_allocation_info(to_split);
575         reg_pref_t            *prefs;
576         float                  delta;
577         float                  split_threshold;
578
579         (void) pref;
580
581         /* stupid hack: don't optimisticallt split don't spill nodes...
582          * (so we don't split away the values produced because of
583          *  must_be_different constraints) */
584         original_insn = skip_Proj(info->original_value);
585         if (arch_irn_get_flags(original_insn) & arch_irn_flags_dont_spill)
586                 return false;
587
588         /* find the best free position where we could move to */
589         prefs = ALLOCAN(reg_pref_t, n_regs);
590         fill_sort_candidates(prefs, info);
591         for (i = 0; i < n_regs; ++i) {
592                 r = prefs[i].num;
593                 if (!rbitset_is_set(normal_regs, r))
594                         continue;
595                 if (rbitset_is_set(output_regs, r))
596                         continue;
597                 if (assignments[r] == NULL)
598                         break;
599         }
600         if (i >= n_regs) {
601                 return false;
602         }
603         /* TODO: use execfreq somehow... */
604         block = get_nodes_block(before);
605         delta = pref_delta + prefs[i].pref;
606         split_threshold = get_block_execfreq(execfreqs, block) * SPLIT_DELTA;
607         if (delta < split_threshold) {
608                 DB((dbg, LEVEL_3, "Not doing optimistical split, win %f too low\n",
609                     delta));
610                 return false;
611         }
612
613         reg   = arch_register_for_index(cls, r);
614         copy = be_new_Copy(cls, block, to_split);
615         mark_as_copy_of(copy, to_split);
616         free_reg_of_value(to_split);
617         use_reg(copy, reg);
618         sched_add_before(before, copy);
619
620         DB((dbg, LEVEL_3,
621             "Optimistic live-range split %+F move %+F -> %s before %+F (win %f)\n",
622             copy, to_split, reg->name, before, delta));
623         return true;
624 }
625
626 /**
627  * Determine and assign a register for node @p node
628  */
629 static void assign_reg(const ir_node *block, ir_node *node,
630                        unsigned *output_regs)
631 {
632         const arch_register_t     *reg;
633         allocation_info_t         *info;
634         const arch_register_req_t *req;
635         reg_pref_t                *reg_prefs;
636         ir_node                   *in_node;
637         unsigned                   i;
638         const unsigned            *allowed_regs;
639         unsigned                   r;
640
641         assert(arch_irn_consider_in_reg_alloc(cls, node));
642
643         /* preassigned register? */
644         reg = arch_get_irn_register(node);
645         if (reg != NULL) {
646                 DB((dbg, LEVEL_2, "Preassignment %+F -> %s\n", node, reg->name));
647                 use_reg(node, reg);
648                 return;
649         }
650
651         /* give should_be_same boni */
652         info = get_allocation_info(node);
653         req  = arch_get_register_req_out(node);
654
655         in_node = skip_Proj(node);
656         if (req->type & arch_register_req_type_should_be_same) {
657                 float weight = get_block_execfreq(execfreqs, block);
658                 int   arity  = get_irn_arity(in_node);
659                 int   i;
660
661                 assert(arity <= (int) sizeof(req->other_same) * 8);
662                 for (i = 0; i < arity; ++i) {
663                         ir_node               *in;
664                         const arch_register_t *reg;
665                         unsigned               r;
666                         if (!rbitset_is_set(&req->other_same, i))
667                                 continue;
668
669                         in  = get_irn_n(in_node, i);
670                         reg = arch_get_irn_register(in);
671                         assert(reg != NULL);
672                         r = arch_register_get_index(reg);
673
674                         /* if the value didn't die here then we should not propagate the
675                          * should_be_same info */
676                         if (assignments[r] == in)
677                                 continue;
678
679                         info->prefs[r] += weight * AFF_SHOULD_BE_SAME;
680                 }
681         }
682
683         /* create list of register candidates and sort by their preference */
684         DB((dbg, LEVEL_2, "Candidates for %+F:", node));
685         reg_prefs = alloca(n_regs * sizeof(reg_prefs[0]));
686         fill_sort_candidates(reg_prefs, info);
687         for (i = 0; i < n_regs; ++i) {
688                 unsigned num = reg_prefs[i].num;
689                 const arch_register_t *reg;
690
691                 if (!rbitset_is_set(normal_regs, num))
692                         continue;
693
694                 reg = arch_register_for_index(cls, num);
695                 DB((dbg, LEVEL_2, " %s(%f)", reg->name, reg_prefs[i].pref));
696         }
697         DB((dbg, LEVEL_2, "\n"));
698
699         allowed_regs = normal_regs;
700         if (req->type & arch_register_req_type_limited) {
701                 allowed_regs = req->limited;
702         }
703
704         for (i = 0; i < n_regs; ++i) {
705                 r = reg_prefs[i].num;
706                 if (!rbitset_is_set(allowed_regs, r))
707                         continue;
708                 if (assignments[r] == NULL)
709                         break;
710                 if (!is_Phi(node)) {
711                         float    pref   = reg_prefs[i].pref;
712                         float    delta  = i+1 < n_regs ? pref - reg_prefs[i+1].pref : 0;
713                         ir_node *before = skip_Proj(node);
714                         bool     res    = try_optimistic_split(assignments[r], before,
715                                                                pref, delta,
716                                                                output_regs);
717                         if (res)
718                                 break;
719                 }
720         }
721         if (i >= n_regs) {
722                 panic("No register left for %+F\n", node);
723         }
724
725         reg = arch_register_for_index(cls, r);
726         DB((dbg, LEVEL_2, "Assign %+F -> %s\n", node, reg->name));
727         use_reg(node, reg);
728 }
729
730 /**
731  * Add an permutation in front of a node and change the assignments
732  * due to this permutation.
733  *
734  * To understand this imagine a permutation like this:
735  *
736  * 1 -> 2
737  * 2 -> 3
738  * 3 -> 1, 5
739  * 4 -> 6
740  * 5
741  * 6
742  * 7 -> 7
743  *
744  * First we count how many destinations a single value has. At the same time
745  * we can be sure that each destination register has at most 1 source register
746  * (it can have 0 which means we don't care what value is in it).
747  * We ignore all fullfilled permuations (like 7->7)
748  * In a first pass we create as much copy instructions as possible as they
749  * are generally cheaper than exchanges. We do this by counting into how many
750  * destinations a register has to be copied (in the example it's 2 for register
751  * 3, or 1 for the registers 1,2,4 and 7).
752  * We can then create a copy into every destination register when the usecount
753  * of that register is 0 (= noone else needs the value in the register).
754  *
755  * After this step we should have cycles left. We implement a cyclic permutation
756  * of n registers with n-1 transpositions.
757  *
758  * @param live_nodes   the set of live nodes, updated due to live range split
759  * @param before       the node before we add the permutation
760  * @param permutation  the permutation array indices are the destination
761  *                     registers, the values in the array are the source
762  *                     registers.
763  */
764 static void permute_values(ir_nodeset_t *live_nodes, ir_node *before,
765                              unsigned *permutation)
766 {
767         unsigned  *n_used = ALLOCANZ(unsigned, n_regs);
768         ir_node   *block;
769         unsigned   r;
770
771         /* determine how often each source register needs to be read */
772         for (r = 0; r < n_regs; ++r) {
773                 unsigned  old_reg = permutation[r];
774                 ir_node  *value;
775
776                 value = assignments[old_reg];
777                 if (value == NULL) {
778                         /* nothing to do here, reg is not live. Mark it as fixpoint
779                          * so we ignore it in the next steps */
780                         permutation[r] = r;
781                         continue;
782                 }
783
784                 ++n_used[old_reg];
785         }
786
787         block = get_nodes_block(before);
788
789         /* step1: create copies where immediately possible */
790         for (r = 0; r < n_regs; /* empty */) {
791                 ir_node *copy;
792                 ir_node *src;
793                 const arch_register_t *reg;
794                 unsigned               old_r = permutation[r];
795
796                 /* - no need to do anything for fixed points.
797                    - we can't copy if the value in the dest reg is still needed */
798                 if (old_r == r || n_used[r] > 0) {
799                         ++r;
800                         continue;
801                 }
802
803                 /* create a copy */
804                 src  = assignments[old_r];
805                 copy = be_new_Copy(cls, block, src);
806                 sched_add_before(before, copy);
807                 reg = arch_register_for_index(cls, r);
808                 DB((dbg, LEVEL_2, "Copy %+F (from %+F, before %+F) -> %s\n",
809                     copy, src, before, reg->name));
810                 mark_as_copy_of(copy, src);
811                 use_reg(copy, reg);
812
813                 if (live_nodes != NULL) {
814                         ir_nodeset_insert(live_nodes, copy);
815                 }
816
817                 /* old register has 1 user less, permutation is resolved */
818                 assert(arch_register_get_index(arch_get_irn_register(src)) == old_r);
819                 permutation[r] = r;
820
821                 assert(n_used[old_r] > 0);
822                 --n_used[old_r];
823                 if (n_used[old_r] == 0) {
824                         if (live_nodes != NULL) {
825                                 ir_nodeset_remove(live_nodes, src);
826                         }
827                         free_reg_of_value(src);
828                 }
829
830                 /* advance or jump back (if this copy enabled another copy) */
831                 if (old_r < r && n_used[old_r] == 0) {
832                         r = old_r;
833                 } else {
834                         ++r;
835                 }
836         }
837
838         /* at this point we only have "cycles" left which we have to resolve with
839          * perm instructions
840          * TODO: if we have free registers left, then we should really use copy
841          * instructions for any cycle longer than 2 registers...
842          * (this is probably architecture dependent, there might be archs where
843          *  copies are preferable even for 2-cycles) */
844
845         /* create perms with the rest */
846         for (r = 0; r < n_regs; /* empty */) {
847                 const arch_register_t *reg;
848                 unsigned  old_r = permutation[r];
849                 unsigned  r2;
850                 ir_node  *in[2];
851                 ir_node  *perm;
852                 ir_node  *proj0;
853                 ir_node  *proj1;
854
855                 if (old_r == r) {
856                         ++r;
857                         continue;
858                 }
859
860                 /* we shouldn't have copies from 1 value to multiple destinations left*/
861                 assert(n_used[old_r] == 1);
862
863                 /* exchange old_r and r2; after that old_r is a fixed point */
864                 r2 = permutation[old_r];
865
866                 in[0] = assignments[r2];
867                 in[1] = assignments[old_r];
868                 perm = be_new_Perm(cls, block, 2, in);
869                 sched_add_before(before, perm);
870                 DB((dbg, LEVEL_2, "Perm %+F (perm %+F,%+F, before %+F)\n",
871                     perm, in[0], in[1], before));
872
873                 proj0 = new_r_Proj(block, perm, get_irn_mode(in[0]), 0);
874                 mark_as_copy_of(proj0, in[0]);
875                 reg = arch_register_for_index(cls, old_r);
876                 use_reg(proj0, reg);
877
878                 proj1 = new_r_Proj(block, perm, get_irn_mode(in[1]), 1);
879                 mark_as_copy_of(proj1, in[1]);
880                 reg = arch_register_for_index(cls, r2);
881                 use_reg(proj1, reg);
882
883                 /* 1 value is now in the correct register */
884                 permutation[old_r] = old_r;
885                 /* the source of r changed to r2 */
886                 permutation[r] = r2;
887
888                 /* if we have reached a fixpoint update data structures */
889                 if (live_nodes != NULL) {
890                         ir_nodeset_remove(live_nodes, in[0]);
891                         ir_nodeset_remove(live_nodes, in[1]);
892                         ir_nodeset_remove(live_nodes, proj0);
893                         ir_nodeset_insert(live_nodes, proj1);
894                 }
895         }
896
897 #ifdef DEBUG_libfirm
898         /* now we should only have fixpoints left */
899         for (r = 0; r < n_regs; ++r) {
900                 assert(permutation[r] == r);
901         }
902 #endif
903 }
904
905 /**
906  * Free regs for values last used.
907  *
908  * @param live_nodes   set of live nodes, will be updated
909  * @param node         the node to consider
910  */
911 static void free_last_uses(ir_nodeset_t *live_nodes, ir_node *node)
912 {
913         allocation_info_t     *info      = get_allocation_info(node);
914         const unsigned        *last_uses = &info->last_uses;
915         int                    arity     = get_irn_arity(node);
916         int                    i;
917
918         for (i = 0; i < arity; ++i) {
919                 ir_node *op;
920
921                 /* check if one operand is the last use */
922                 if (!rbitset_is_set(last_uses, i))
923                         continue;
924
925                 op = get_irn_n(node, i);
926                 free_reg_of_value(op);
927                 ir_nodeset_remove(live_nodes, op);
928         }
929 }
930
931 /**
932  * change inputs of a node to the current value (copies/perms)
933  */
934 static void rewire_inputs(ir_node *node)
935 {
936         int i;
937         int arity = get_irn_arity(node);
938
939         for (i = 0; i < arity; ++i) {
940                 ir_node           *op = get_irn_n(node, i);
941                 allocation_info_t *info;
942
943                 if (!arch_irn_consider_in_reg_alloc(cls, op))
944                         continue;
945
946                 info = get_allocation_info(op);
947                 info = get_allocation_info(info->original_value);
948                 if (info->current_value != op) {
949                         set_irn_n(node, i, info->current_value);
950                 }
951         }
952 }
953
954 /**
955  * Create a bitset of registers occupied with value living through an
956  * instruction
957  */
958 static void determine_live_through_regs(unsigned *bitset, ir_node *node)
959 {
960         const allocation_info_t *info = get_allocation_info(node);
961         unsigned r;
962         int i;
963         int arity;
964
965         /* mark all used registers as potentially live-through */
966         for (r = 0; r < n_regs; ++r) {
967                 if (assignments[r] == NULL)
968                         continue;
969                 if (!rbitset_is_set(normal_regs, r))
970                         continue;
971
972                 rbitset_set(bitset, r);
973         }
974
975         /* remove registers of value dying at the instruction */
976         arity = get_irn_arity(node);
977         for (i = 0; i < arity; ++i) {
978                 ir_node               *op;
979                 const arch_register_t *reg;
980
981                 if (!rbitset_is_set(&info->last_uses, i))
982                         continue;
983
984                 op  = get_irn_n(node, i);
985                 reg = arch_get_irn_register(op);
986                 rbitset_clear(bitset, arch_register_get_index(reg));
987         }
988 }
989
990 /**
991  * Enforce constraints at a node by live range splits.
992  *
993  * @param  live_nodes  the set of live nodes, might be changed
994  * @param  node        the current node
995  */
996 static void enforce_constraints(ir_nodeset_t *live_nodes, ir_node *node,
997                                 unsigned *output_regs)
998 {
999         int arity = get_irn_arity(node);
1000         int i, dummy, res;
1001         hungarian_problem_t *bp;
1002         unsigned l, r;
1003         unsigned *assignment;
1004
1005         /* construct a list of register occupied by live-through values */
1006         unsigned *live_through_regs = NULL;
1007
1008         /* see if any use constraints are not met */
1009         bool good = true;
1010         for (i = 0; i < arity; ++i) {
1011                 ir_node                   *op = get_irn_n(node, i);
1012                 const arch_register_t     *reg;
1013                 const arch_register_req_t *req;
1014                 const unsigned            *limited;
1015                 unsigned                  r;
1016
1017                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1018                         continue;
1019
1020                 /* are there any limitations for the i'th operand? */
1021                 req = arch_get_register_req(node, i);
1022                 if (!(req->type & arch_register_req_type_limited))
1023                         continue;
1024
1025                 limited = req->limited;
1026                 reg     = arch_get_irn_register(op);
1027                 r       = arch_register_get_index(reg);
1028                 if (!rbitset_is_set(limited, r)) {
1029                         /* found an assignment outside the limited set */
1030                         good = false;
1031                         break;
1032                 }
1033         }
1034
1035         /* is any of the live-throughs using a constrained output register? */
1036         if (get_irn_mode(node) == mode_T) {
1037                 const ir_edge_t *edge;
1038
1039                 foreach_out_edge(node, edge) {
1040                         ir_node *proj = get_edge_src_irn(edge);
1041                         const arch_register_req_t *req;
1042
1043                         if (!arch_irn_consider_in_reg_alloc(cls, proj))
1044                                 continue;
1045
1046                         req = arch_get_register_req_out(proj);
1047                         if (!(req->type & arch_register_req_type_limited))
1048                                 continue;
1049
1050                         if (live_through_regs == NULL) {
1051                                 rbitset_alloca(live_through_regs, n_regs);
1052                                 determine_live_through_regs(live_through_regs, node);
1053                         }
1054
1055                         rbitset_or(output_regs, req->limited, n_regs);
1056                         if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1057                                 good = false;
1058                         }
1059                 }
1060         } else {
1061                 if (arch_irn_consider_in_reg_alloc(cls, node)) {
1062                         const arch_register_req_t *req = arch_get_register_req_out(node);
1063                         if (req->type & arch_register_req_type_limited) {
1064                                 rbitset_alloca(live_through_regs, n_regs);
1065                                 determine_live_through_regs(live_through_regs, node);
1066                                 if (rbitsets_have_common(req->limited, live_through_regs, n_regs)) {
1067                                         good = false;
1068                                         rbitset_or(output_regs, req->limited, n_regs);
1069                                 }
1070                         }
1071                 }
1072         }
1073
1074         if (good)
1075                 return;
1076
1077         /* create these arrays if we haven't yet */
1078         if (live_through_regs == NULL) {
1079                 rbitset_alloca(live_through_regs, n_regs);
1080         }
1081
1082         /* at this point we have to construct a bipartite matching problem to see
1083          * which values should go to which registers
1084          * Note: We're building the matrix in "reverse" - source registers are
1085          *       right, destinations left because this will produce the solution
1086          *       in the format required for permute_values.
1087          */
1088         bp = hungarian_new(n_regs, n_regs, HUNGARIAN_MATCH_PERFECT);
1089
1090         /* add all combinations, then remove not allowed ones */
1091         for (l = 0; l < n_regs; ++l) {
1092                 if (!rbitset_is_set(normal_regs, l)) {
1093                         hungarian_add(bp, l, l, 1);
1094                         continue;
1095                 }
1096
1097                 for (r = 0; r < n_regs; ++r) {
1098                         if (!rbitset_is_set(normal_regs, r))
1099                                 continue;
1100                         /* livethrough values may not use constrainted output registers */
1101                         if (rbitset_is_set(live_through_regs, l)
1102                                         && rbitset_is_set(output_regs, r))
1103                                 continue;
1104
1105                         hungarian_add(bp, r, l, l == r ? 9 : 8);
1106                 }
1107         }
1108
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                   current_reg;
1115
1116                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1117                         continue;
1118
1119                 req = arch_get_register_req(node, i);
1120                 if (!(req->type & arch_register_req_type_limited))
1121                         continue;
1122
1123                 limited     = req->limited;
1124                 reg         = arch_get_irn_register(op);
1125                 current_reg = arch_register_get_index(reg);
1126                 for (r = 0; r < n_regs; ++r) {
1127                         if (rbitset_is_set(limited, r))
1128                                 continue;
1129                         hungarian_remv(bp, r, current_reg);
1130                 }
1131         }
1132
1133         //hungarian_print_costmatrix(bp, 1);
1134         hungarian_prepare_cost_matrix(bp, HUNGARIAN_MODE_MAXIMIZE_UTIL);
1135
1136         assignment = ALLOCAN(unsigned, n_regs);
1137         res = hungarian_solve(bp, (int*) assignment, &dummy, 0);
1138         assert(res == 0);
1139
1140 #if 0
1141         fprintf(stderr, "Swap result:");
1142         for (i = 0; i < (int) n_regs; ++i) {
1143                 fprintf(stderr, " %d", assignment[i]);
1144         }
1145         fprintf(stderr, "\n");
1146 #endif
1147
1148         hungarian_free(bp);
1149
1150         permute_values(live_nodes, node, assignment);
1151 }
1152
1153 /** test wether a node @p n is a copy of the value of node @p of */
1154 static bool is_copy_of(ir_node *value, ir_node *test_value)
1155 {
1156         allocation_info_t *test_info;
1157         allocation_info_t *info;
1158
1159         if (value == test_value)
1160                 return true;
1161
1162         info      = get_allocation_info(value);
1163         test_info = get_allocation_info(test_value);
1164         return test_info->original_value == info->original_value;
1165 }
1166
1167 /**
1168  * find a value in the end-assignment of a basic block
1169  * @returns the index into the assignment array if found
1170  *          -1 if not found
1171  */
1172 static int find_value_in_block_info(block_info_t *info, ir_node *value)
1173 {
1174         unsigned   r;
1175         ir_node  **assignments = info->assignments;
1176         for (r = 0; r < n_regs; ++r) {
1177                 ir_node *a_value = assignments[r];
1178
1179                 if (a_value == NULL)
1180                         continue;
1181                 if (is_copy_of(a_value, value))
1182                         return (int) r;
1183         }
1184
1185         return -1;
1186 }
1187
1188 /**
1189  * Create the necessary permutations at the end of a basic block to fullfill
1190  * the register assignment for phi-nodes in the next block
1191  */
1192 static void add_phi_permutations(ir_node *block, int p)
1193 {
1194         unsigned   r;
1195         unsigned  *permutation;
1196         ir_node  **old_assignments;
1197         bool       need_permutation;
1198         ir_node   *node;
1199         ir_node   *pred = get_Block_cfgpred_block(block, p);
1200
1201         block_info_t *pred_info = get_block_info(pred);
1202
1203         /* predecessor not processed yet? nothing to do */
1204         if (!pred_info->processed)
1205                 return;
1206
1207         permutation = ALLOCAN(unsigned, n_regs);
1208         for (r = 0; r < n_regs; ++r) {
1209                 permutation[r] = r;
1210         }
1211
1212         /* check phi nodes */
1213         need_permutation = false;
1214         node = sched_first(block);
1215         for ( ; is_Phi(node); node = sched_next(node)) {
1216                 const arch_register_t *reg;
1217                 int                    regn;
1218                 int                    a;
1219                 ir_node               *op;
1220
1221                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1222                         continue;
1223
1224                 op = get_Phi_pred(node, p);
1225                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1226                         continue;
1227
1228                 a  = find_value_in_block_info(pred_info, op);
1229                 assert(a >= 0);
1230
1231                 reg  = arch_get_irn_register(node);
1232                 regn = arch_register_get_index(reg);
1233                 if (regn != a) {
1234                         permutation[regn] = a;
1235                         need_permutation  = true;
1236                 }
1237         }
1238
1239         if (need_permutation) {
1240                 /* permute values at end of predecessor */
1241                 old_assignments = assignments;
1242                 assignments     = pred_info->assignments;
1243                 permute_values(NULL, be_get_end_of_block_insertion_point(pred),
1244                                                  permutation);
1245                 assignments = old_assignments;
1246         }
1247
1248         /* change phi nodes to use the copied values */
1249         node = sched_first(block);
1250         for ( ; is_Phi(node); node = sched_next(node)) {
1251                 int      a;
1252                 ir_node *op;
1253
1254                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1255                         continue;
1256
1257                 op = get_Phi_pred(node, p);
1258                 /* no need to do anything for Unknown inputs */
1259                 if (!arch_irn_consider_in_reg_alloc(cls, op))
1260                         continue;
1261
1262                 /* we have permuted all values into the correct registers so we can
1263                    simply query which value occupies the phis register in the
1264                    predecessor */
1265                 a  = arch_register_get_index(arch_get_irn_register(node));
1266                 op = pred_info->assignments[a];
1267                 set_Phi_pred(node, p, op);
1268         }
1269 }
1270
1271 /**
1272  * Set preferences for a phis register based on the registers used on the
1273  * phi inputs.
1274  */
1275 static void adapt_phi_prefs(ir_node *phi)
1276 {
1277         int i;
1278         int arity = get_irn_arity(phi);
1279         ir_node           *block = get_nodes_block(phi);
1280         allocation_info_t *info  = get_allocation_info(phi);
1281
1282         for (i = 0; i < arity; ++i) {
1283                 ir_node               *op  = get_irn_n(phi, i);
1284                 const arch_register_t *reg = arch_get_irn_register(op);
1285                 ir_node               *pred_block;
1286                 block_info_t          *pred_block_info;
1287                 float                  weight;
1288                 unsigned               r;
1289
1290                 if (reg == NULL)
1291                         continue;
1292                 /* we only give the bonus if the predecessor already has registers
1293                  * assigned, otherwise we only see a dummy value
1294                  * and any conclusions about its register are useless */
1295                 pred_block = get_Block_cfgpred_block(block, i);
1296                 pred_block_info = get_block_info(pred_block);
1297                 if (!pred_block_info->processed)
1298                         continue;
1299
1300                 /* give bonus for already assigned register */
1301                 weight = get_block_execfreq(execfreqs, pred_block);
1302                 r      = arch_register_get_index(reg);
1303                 info->prefs[r] += weight * AFF_PHI;
1304         }
1305 }
1306
1307 /**
1308  * After a phi has been assigned a register propagate preference inputs
1309  * to the phi inputs.
1310  */
1311 static void propagate_phi_register(ir_node *phi, unsigned r)
1312 {
1313         int                    i;
1314         ir_node               *block = get_nodes_block(phi);
1315         int                    arity = get_irn_arity(phi);
1316
1317         for (i = 0; i < arity; ++i) {
1318                 ir_node           *op         = get_Phi_pred(phi, i);
1319                 allocation_info_t *info       = get_allocation_info(op);
1320                 ir_node           *pred_block = get_Block_cfgpred_block(block, i);
1321                 float              weight
1322                         = get_block_execfreq(execfreqs, pred_block) * AFF_PHI;
1323
1324                 if (info->prefs[r] >= weight)
1325                         continue;
1326
1327                 /* promote the prefered register */
1328                 info->prefs[r] = AFF_PHI * weight;
1329                 if (is_Phi(op))
1330                         propagate_phi_register(op, r);
1331         }
1332 }
1333
1334 /**
1335  * Walker: assign registers to all nodes of a block that
1336  * need registers from the currently considered register class.
1337  */
1338 static void allocate_coalesce_block(ir_node *block, void *data)
1339 {
1340         int                    i;
1341         ir_nodeset_t           live_nodes;
1342         ir_nodeset_iterator_t  iter;
1343         ir_node               *node, *start;
1344         int                    n_preds;
1345         block_info_t          *block_info;
1346         block_info_t         **pred_block_infos;
1347         ir_node              **phi_ins;
1348         unsigned              *output_regs; /**< collects registers which must not
1349                                                                                      be used for optimistic splits */
1350
1351         (void) data;
1352         DB((dbg, LEVEL_2, "* Block %+F\n", block));
1353
1354         /* clear assignments */
1355         block_info  = get_block_info(block);
1356         assignments = block_info->assignments;
1357
1358         ir_nodeset_init(&live_nodes);
1359
1360         /* gather regalloc infos of predecessor blocks */
1361         n_preds             = get_Block_n_cfgpreds(block);
1362         pred_block_infos    = ALLOCAN(block_info_t*, n_preds);
1363         for (i = 0; i < n_preds; ++i) {
1364                 ir_node      *pred      = get_Block_cfgpred_block(block, i);
1365                 block_info_t *pred_info = get_block_info(pred);
1366                 pred_block_infos[i]     = pred_info;
1367         }
1368
1369         phi_ins = ALLOCAN(ir_node*, n_preds);
1370
1371         /* collect live-in nodes and preassigned values */
1372         be_lv_foreach(lv, block, be_lv_state_in, i) {
1373                 const arch_register_t *reg;
1374                 int                    p;
1375                 bool                   need_phi = false;
1376
1377                 node = be_lv_get_irn(lv, block, i);
1378                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1379                         continue;
1380
1381                 /* check all predecessors for this value, if it is not everywhere the
1382                    same or unknown then we have to construct a phi
1383                    (we collect the potential phi inputs here) */
1384                 for (p = 0; p < n_preds; ++p) {
1385                         block_info_t *pred_info = pred_block_infos[p];
1386
1387                         if (!pred_info->processed) {
1388                                 /* use node for now, it will get fixed later */
1389                                 phi_ins[p] = node;
1390                                 need_phi   = true;
1391                         } else {
1392                                 int a = find_value_in_block_info(pred_info, node);
1393
1394                                 /* must live out of predecessor */
1395                                 assert(a >= 0);
1396                                 phi_ins[p] = pred_info->assignments[a];
1397                                 /* different value from last time? then we need a phi */
1398                                 if (p > 0 && phi_ins[p-1] != phi_ins[p]) {
1399                                         need_phi = true;
1400                                 }
1401                         }
1402                 }
1403
1404                 if (need_phi) {
1405                         ir_mode                   *mode = get_irn_mode(node);
1406                         const arch_register_req_t *req  = get_default_req_current_cls();
1407                         ir_node                   *phi;
1408                         int                        i;
1409
1410                         phi = new_r_Phi(block, n_preds, phi_ins, mode);
1411                         be_set_phi_reg_req(phi, req);
1412
1413                         DB((dbg, LEVEL_3, "Create Phi %+F (for %+F) -", phi, node));
1414 #ifdef DEBUG_libfirm
1415                         for (i = 0; i < n_preds; ++i) {
1416                                 DB((dbg, LEVEL_3, " %+F", phi_ins[i]));
1417                         }
1418                         DB((dbg, LEVEL_3, "\n"));
1419 #endif
1420                         mark_as_copy_of(phi, node);
1421                         sched_add_after(block, phi);
1422
1423                         node = phi;
1424                 } else {
1425                         allocation_info_t *info = get_allocation_info(node);
1426                         info->current_value = phi_ins[0];
1427
1428                         /* Grab 1 of the inputs we constructed (might not be the same as
1429                          * "node" as we could see the same copy of the value in all
1430                          * predecessors */
1431                         node = phi_ins[0];
1432                 }
1433
1434                 /* if the node already has a register assigned use it */
1435                 reg = arch_get_irn_register(node);
1436                 if (reg != NULL) {
1437                         /* TODO: consult pred-block infos here. The value could be copied
1438                            away in some/all predecessor blocks. We need to construct
1439                            phi-nodes in this case.
1440                            We even need to construct some Phi_0 like constructs in cases
1441                            where the predecessor allocation is not determined yet. */
1442                         use_reg(node, reg);
1443                 }
1444
1445                 /* remember that this node is live at the beginning of the block */
1446                 ir_nodeset_insert(&live_nodes, node);
1447         }
1448
1449         rbitset_alloca(output_regs, n_regs);
1450
1451         /* handle phis... */
1452         node = sched_first(block);
1453         for ( ; is_Phi(node); node = sched_next(node)) {
1454                 const arch_register_t *reg;
1455
1456                 if (!arch_irn_consider_in_reg_alloc(cls, node))
1457                         continue;
1458
1459                 /* fill in regs already assigned */
1460                 reg = arch_get_irn_register(node);
1461                 if (reg != NULL) {
1462                         use_reg(node, reg);
1463                 } else {
1464                         adapt_phi_prefs(node);
1465                         assign_reg(block, node, output_regs);
1466
1467                         reg = arch_get_irn_register(node);
1468                         propagate_phi_register(node, arch_register_get_index(reg));
1469                 }
1470         }
1471         start = node;
1472
1473         /* assign regs for live-in values */
1474         foreach_ir_nodeset(&live_nodes, node, iter) {
1475                 const arch_register_t *reg = arch_get_irn_register(node);
1476                 if (reg != NULL)
1477                         continue;
1478
1479                 assign_reg(block, node, output_regs);
1480                 /* shouldn't happen if we color in dominance order */
1481                 assert (!is_Phi(node));
1482         }
1483
1484         /* assign instructions in the block */
1485         for (node = start; !sched_is_end(node); node = sched_next(node)) {
1486                 unsigned r;
1487
1488                 rewire_inputs(node);
1489
1490                 /* enforce use constraints */
1491                 rbitset_clear_all(output_regs, n_regs);
1492                 enforce_constraints(&live_nodes, node, output_regs);
1493                 /* we may not use registers occupied here for optimistic splits */
1494                 for (r = 0; r < n_regs; ++r) {
1495                         if (assignments[r] != NULL)
1496                                 rbitset_set(output_regs, r);
1497                 }
1498
1499                 rewire_inputs(node);
1500
1501                 /* free registers of values last used at this instruction */
1502                 free_last_uses(&live_nodes, node);
1503
1504                 /* assign output registers */
1505                 /* TODO: 2 phases: first: pre-assigned ones, 2nd real regs */
1506                 if (get_irn_mode(node) == mode_T) {
1507                         const ir_edge_t *edge;
1508                         foreach_out_edge(node, edge) {
1509                                 ir_node *proj = get_edge_src_irn(edge);
1510                                 if (!arch_irn_consider_in_reg_alloc(cls, proj))
1511                                         continue;
1512                                 assign_reg(block, proj, output_regs);
1513                         }
1514                 } else if (arch_irn_consider_in_reg_alloc(cls, node)) {
1515                         assign_reg(block, node, output_regs);
1516                 }
1517         }
1518
1519         ir_nodeset_destroy(&live_nodes);
1520         assignments = NULL;
1521
1522         block_info->processed = true;
1523
1524         /* permute values at end of predecessor blocks in case of phi-nodes */
1525         if (n_preds > 1) {
1526                 int p;
1527                 for (p = 0; p < n_preds; ++p) {
1528                         add_phi_permutations(block, p);
1529                 }
1530         }
1531
1532         /* if we have exactly 1 successor then we might be able to produce phi
1533            copies now */
1534         if (get_irn_n_edges_kind(block, EDGE_KIND_BLOCK) == 1) {
1535                 const ir_edge_t *edge
1536                         = get_irn_out_edge_first_kind(block, EDGE_KIND_BLOCK);
1537                 ir_node      *succ      = get_edge_src_irn(edge);
1538                 int           p         = get_edge_src_pos(edge);
1539                 block_info_t *succ_info = get_block_info(succ);
1540
1541                 if (succ_info->processed) {
1542                         add_phi_permutations(succ, p);
1543                 }
1544         }
1545 }
1546
1547 typedef struct block_costs_t block_costs_t;
1548 struct block_costs_t {
1549         float costs;   /**< costs of the block */
1550         int   dfs_num; /**< depth first search number (to detect backedges) */
1551 };
1552
1553 static int cmp_block_costs(const void *d1, const void *d2)
1554 {
1555         const ir_node       * const *block1 = d1;
1556         const ir_node       * const *block2 = d2;
1557         const block_costs_t *info1  = get_irn_link(*block1);
1558         const block_costs_t *info2  = get_irn_link(*block2);
1559         return QSORT_CMP(info2->costs, info1->costs);
1560 }
1561
1562 static void determine_block_order(void)
1563 {
1564         int i;
1565         ir_node **blocklist = be_get_cfgpostorder(irg);
1566         int       n_blocks  = ARR_LEN(blocklist);
1567         int       dfs_num   = 0;
1568
1569         /* clear block links... */
1570         for (i = 0; i < n_blocks; ++i) {
1571                 ir_node *block = blocklist[i];
1572                 set_irn_link(block, NULL);
1573         }
1574
1575         /* walk blocks in reverse postorder, the costs for each block are the
1576          * sum of the costs of its predecessors (excluding the costs on backedges
1577          * which we can't determine) */
1578         for (i = n_blocks-1; i >= 0; --i) {
1579                 block_costs_t *cost_info;
1580                 ir_node *block = blocklist[i];
1581
1582                 float execfreq   = get_block_execfreq(execfreqs, block);
1583                 float costs      = execfreq;
1584                 int   n_cfgpreds = get_Block_n_cfgpreds(block);
1585                 int   p;
1586                 for (p = 0; p < n_cfgpreds; ++p) {
1587                         ir_node       *pred_block = get_Block_cfgpred_block(block, p);
1588                         block_costs_t *pred_costs = get_irn_link(pred_block);
1589                         /* we don't have any info for backedges */
1590                         if (pred_costs == NULL)
1591                                 continue;
1592                         costs += pred_costs->costs;
1593                 }
1594
1595                 cost_info          = OALLOCZ(&obst, block_costs_t);
1596                 cost_info->costs   = costs;
1597                 cost_info->dfs_num = dfs_num++;
1598                 set_irn_link(block, cost_info);
1599         }
1600
1601         /* sort array by block costs */
1602         qsort(blocklist, n_blocks, sizeof(blocklist[0]), cmp_block_costs);
1603
1604         ir_reserve_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1605         inc_irg_block_visited(irg);
1606
1607         pdeq     *worklist = new_pdeq();
1608         ir_node **order    = XMALLOCN(ir_node*, n_blocks);
1609         int       order_p  = 0;
1610         for (i = 0; i < n_blocks; ++i) {
1611                 ir_node       *block = blocklist[i];
1612                 if (Block_block_visited(block))
1613                         continue;
1614
1615                 /* continually add predecessors with highest costs to worklist
1616                  * (without using backedges) */
1617                 do {
1618                         block_costs_t *info       = get_irn_link(block);
1619                         ir_node       *best_pred  = NULL;
1620                         float          best_costs = -1;
1621                         int            n_cfgpred  = get_Block_n_cfgpreds(block);
1622                         int            i;
1623
1624                         pdeq_putr(worklist, block);
1625                         mark_Block_block_visited(block);
1626                         for (i = 0; i < n_cfgpred; ++i) {
1627                                 ir_node       *pred_block = get_Block_cfgpred_block(block, i);
1628                                 block_costs_t *pred_info  = get_irn_link(pred_block);
1629
1630                                 /* ignore backedges */
1631                                 if (pred_info->dfs_num > info->dfs_num)
1632                                         continue;
1633
1634                                 if (info->costs > best_costs) {
1635                                         best_costs = info->costs;
1636                                         best_pred  = pred_block;
1637                                 }
1638                         }
1639                         block = best_pred;
1640                 } while(block != NULL && !Block_block_visited(block));
1641
1642                 /* now put all nodes in the worklist in our final order */
1643                 while (!pdeq_empty(worklist)) {
1644                         ir_node *pblock = pdeq_getr(worklist);
1645                         assert(order_p < n_blocks);
1646                         order[order_p++] = pblock;
1647                 }
1648         }
1649         assert(order_p == n_blocks);
1650         del_pdeq(worklist);
1651
1652         ir_free_resources(irg, IR_RESOURCE_BLOCK_VISITED);
1653
1654         DEL_ARR_F(blocklist);
1655
1656         obstack_free(&obst, NULL);
1657         obstack_init(&obst);
1658
1659         block_order   = order;
1660         n_block_order = n_blocks;
1661 }
1662
1663 /**
1664  * Run the register allocator for the current register class.
1665  */
1666 static void be_straight_alloc_cls(void)
1667 {
1668         int i;
1669
1670         lv = be_assure_liveness(birg);
1671         be_liveness_assure_sets(lv);
1672         be_liveness_assure_chk(lv);
1673
1674         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
1675
1676         DB((dbg, LEVEL_2, "=== Allocating registers of %s ===\n", cls->name));
1677
1678         be_clear_links(irg);
1679         irg_block_walk_graph(irg, NULL, analyze_block, NULL);
1680         combine_congruence_classes();
1681
1682         for (i = 0; i < n_block_order; ++i) {
1683                 ir_node *block = block_order[i];
1684                 allocate_coalesce_block(block, NULL);
1685         }
1686
1687         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
1688 }
1689
1690 static void dump(int mask, ir_graph *irg, const char *suffix,
1691                  void (*dumper)(ir_graph *, const char *))
1692 {
1693         if(birg->main_env->options->dump_flags & mask)
1694                 be_dump(irg, suffix, dumper);
1695 }
1696
1697 /**
1698  * Run the spiller on the current graph.
1699  */
1700 static void spill(void)
1701 {
1702         /* make sure all nodes show their real register pressure */
1703         BE_TIMER_PUSH(t_ra_constr);
1704         be_pre_spill_prepare_constr(birg, cls);
1705         BE_TIMER_POP(t_ra_constr);
1706
1707         dump(DUMP_RA, irg, "-spillprepare", dump_ir_block_graph_sched);
1708
1709         /* spill */
1710         BE_TIMER_PUSH(t_ra_spill);
1711         be_do_spill(birg, cls);
1712         BE_TIMER_POP(t_ra_spill);
1713
1714         BE_TIMER_PUSH(t_ra_spill_apply);
1715         check_for_memory_operands(irg);
1716         BE_TIMER_POP(t_ra_spill_apply);
1717
1718         dump(DUMP_RA, irg, "-spill", dump_ir_block_graph_sched);
1719 }
1720
1721 /**
1722  * The straight register allocator for a whole procedure.
1723  */
1724 static void be_straight_alloc(be_irg_t *new_birg)
1725 {
1726         const arch_env_t *arch_env = new_birg->main_env->arch_env;
1727         int   n_cls                = arch_env_get_n_reg_class(arch_env);
1728         int   c;
1729
1730         obstack_init(&obst);
1731
1732         birg      = new_birg;
1733         irg       = be_get_birg_irg(birg);
1734         execfreqs = birg->exec_freq;
1735
1736         /* determine a good coloring order */
1737         determine_block_order();
1738
1739         for (c = 0; c < n_cls; ++c) {
1740                 cls             = arch_env_get_reg_class(arch_env, c);
1741                 default_cls_req = NULL;
1742                 if (arch_register_class_flags(cls) & arch_register_class_flag_manual_ra)
1743                         continue;
1744
1745                 stat_ev_ctx_push_str("regcls", cls->name);
1746
1747                 n_regs      = arch_register_class_n_regs(cls);
1748                 normal_regs = rbitset_malloc(n_regs);
1749                 be_abi_set_non_ignore_regs(birg->abi, cls, normal_regs);
1750
1751                 spill();
1752
1753                 /* verify schedule and register pressure */
1754                 BE_TIMER_PUSH(t_verify);
1755                 if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1756                         be_verify_schedule(birg);
1757                         be_verify_register_pressure(birg, cls, irg);
1758                 } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1759                         assert(be_verify_schedule(birg) && "Schedule verification failed");
1760                         assert(be_verify_register_pressure(birg, cls, irg)
1761                                 && "Register pressure verification failed");
1762                 }
1763                 BE_TIMER_POP(t_verify);
1764
1765                 BE_TIMER_PUSH(t_ra_color);
1766                 be_straight_alloc_cls();
1767                 BE_TIMER_POP(t_ra_color);
1768
1769                 /* we most probably constructed new Phis so liveness info is invalid
1770                  * now */
1771                 /* TODO: test liveness_introduce */
1772                 be_liveness_invalidate(lv);
1773                 free(normal_regs);
1774
1775                 stat_ev_ctx_pop("regcls");
1776         }
1777
1778         BE_TIMER_PUSH(t_ra_spill_apply);
1779         be_abi_fix_stack_nodes(birg->abi);
1780         BE_TIMER_POP(t_ra_spill_apply);
1781
1782         BE_TIMER_PUSH(t_verify);
1783         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
1784                 be_verify_register_allocation(birg);
1785         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
1786                 assert(be_verify_register_allocation(birg)
1787                                 && "Register allocation invalid");
1788         }
1789         BE_TIMER_POP(t_verify);
1790
1791         obstack_free(&obst, NULL);
1792 }
1793
1794 /**
1795  * Initializes this module.
1796  */
1797 void be_init_straight_alloc(void)
1798 {
1799         static be_ra_t be_ra_straight = {
1800                 be_straight_alloc,
1801         };
1802
1803         FIRM_DBG_REGISTER(dbg, "firm.be.straightalloc");
1804
1805         be_register_allocator("straight", &be_ra_straight);
1806 }
1807
1808 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_straight_alloc);