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