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