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