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