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