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