Remove the very thin wrapper function arch_register_get_index().
[libfirm] / ir / be / becopyheur4.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       Simple copy minimization heuristics.
23  * @author      Christian Wuerdig
24  * @date        27.04.2007
25  *
26  * This is the C implementation of the mst algorithm
27  * originally written in Java by Sebastian Hack.
28  * (also known as "heur3" :)
29  * Performs simple copy minimization.
30  */
31 #include "config.h"
32
33 #define DISABLE_STATEV
34
35 #include <float.h>
36
37 #include "array.h"
38 #include "irnode_t.h"
39 #include "bitset.h"
40 #include "raw_bitset.h"
41 #include "irnodemap.h"
42 #include "pqueue.h"
43 #include "xmalloc.h"
44 #include "pdeq.h"
45 #include "irprintf.h"
46 #include "util.h"
47 #include "irtools.h"
48 #include "error.h"
49 #include "list.h"
50 #include "statev_t.h"
51
52 #include "bearch.h"
53 #include "beifg.h"
54 #include "be_t.h"
55 #include "becopyopt_t.h"
56 #include "bemodule.h"
57
58
59 #define COL_COST_INFEASIBLE       DBL_MAX
60 #define AFF_NEIGHBOUR_FIX_BENEFIT 128.0
61 #define NEIGHBOUR_CONSTR_COSTS    64.0
62
63
64 #ifdef DEBUG_libfirm
65
66 #define DBG_AFF_CHUNK(env, level, chunk) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_aff_chunk((env), (chunk)); } while (0)
67 #define DBG_COL_COST(env, level, cost)   do { if (firm_dbg_get_mask(dbg) & (level)) dbg_col_cost((env), (cost)); } while (0)
68
69 static firm_dbg_module_t *dbg = NULL;
70
71 #else
72
73 #define DBG_AFF_CHUNK(env, level, chunk)
74 #define DBG_COL_COST(env, level, cost)
75
76 #endif
77
78 typedef float real_t;
79 #define REAL(C)   (C ## f)
80
81 static unsigned last_chunk_id   = 0;
82 static int recolor_limit        = 7;
83 static double dislike_influence = REAL(0.1);
84
85 typedef struct col_cost_t {
86         int     col;
87         real_t  cost;
88 } col_cost_t;
89
90 /**
91  * An affinity chunk.
92  */
93 typedef struct aff_chunk_t {
94         const ir_node  **n;                     /**< An ARR_F containing all nodes of the chunk. */
95         const ir_node  **interfere;             /**< An ARR_F containing all inference. */
96         int              weight;                /**< Weight of this chunk */
97         unsigned         weight_consistent : 1; /**< Set if the weight is consistent. */
98         unsigned         deleted           : 1; /**< For debugging: Set if the was deleted. */
99         unsigned         id;                    /**< An id of this chunk. */
100         unsigned         visited;
101         list_head        list;
102         col_cost_t       color_affinity[1];
103 } aff_chunk_t;
104
105 /**
106  * An affinity edge.
107  */
108 typedef struct aff_edge_t {
109         const ir_node *src;                   /**< Source node. */
110         const ir_node *tgt;                   /**< Target node. */
111         int           weight;                 /**< The weight of this edge. */
112 } aff_edge_t;
113
114 /* main coalescing environment */
115 typedef struct co_mst_env_t {
116         int              n_regs;         /**< number of regs in class */
117         int              k;              /**< number of non-ignore registers in class */
118         bitset_t         *allocatable_regs; /**< set containing all global ignore registers */
119         ir_nodemap        map;           /**< phase object holding data for nodes */
120         struct obstack    obst;
121         pqueue_t         *chunks;        /**< priority queue for chunks */
122         list_head         chunklist;     /**< list holding all chunks */
123         be_ifg_t         *ifg;           /**< the interference graph */
124         copy_opt_t       *co;            /**< the copy opt object */
125         unsigned         chunk_visited;
126         col_cost_t      **single_cols;
127 } co_mst_env_t;
128
129 /* stores coalescing related information for a node */
130 typedef struct co_mst_irn_t {
131         const ir_node    *irn;              /**< the irn this information belongs to */
132         aff_chunk_t      *chunk;            /**< the chunk this irn belongs to */
133         bitset_t         *adm_colors;       /**< set of admissible colors for this irn */
134         ir_node          **int_neighs;      /**< array of all interfering neighbours (cached for speed reasons) */
135         int              n_neighs;          /**< length of the interfering neighbours array. */
136         int              int_aff_neigh;     /**< number of interfering affinity neighbours */
137         int              col;               /**< color currently assigned */
138         int              init_col;          /**< the initial color */
139         int              tmp_col;           /**< a temporary assigned color */
140         unsigned         fixed     : 1;     /**< the color is fixed */
141         struct list_head list;              /**< Queue for coloring undo. */
142         real_t           constr_factor;
143 } co_mst_irn_t;
144
145 /**
146  * In case there is no phase information for irn, initialize it.
147  */
148 static co_mst_irn_t *co_mst_irn_init(co_mst_env_t *env, const ir_node *irn)
149 {
150         co_mst_irn_t *res = OALLOC(&env->obst, co_mst_irn_t);
151
152         const arch_register_req_t *req;
153         neighbours_iter_t nodes_it;
154         ir_node  *neigh;
155         unsigned len;
156
157         res->irn           = irn;
158         res->chunk         = NULL;
159         res->fixed         = 0;
160         res->tmp_col       = -1;
161         res->int_neighs    = NULL;
162         res->int_aff_neigh = 0;
163         res->col           = arch_get_irn_register(irn)->index;
164         res->init_col      = res->col;
165         INIT_LIST_HEAD(&res->list);
166
167         DB((dbg, LEVEL_4, "Creating phase info for %+F\n", irn));
168
169         /* set admissible registers */
170         res->adm_colors = bitset_obstack_alloc(&env->obst, env->n_regs);
171
172         /* Exclude colors not assignable to the irn */
173         req = arch_get_irn_register_req(irn);
174         if (arch_register_req_is(req, limited)) {
175                 rbitset_copy_to_bitset(req->limited, res->adm_colors);
176         } else {
177                 bitset_set_all(res->adm_colors);
178         }
179
180         /* exclude global ignore registers as well */
181         bitset_and(res->adm_colors, env->allocatable_regs);
182
183         /* compute the constraint factor */
184         res->constr_factor = (real_t) (1 + env->n_regs - bitset_popcount(res->adm_colors)) / env->n_regs;
185
186         /* set the number of interfering affinity neighbours to -1, they are calculated later */
187         res->int_aff_neigh = -1;
188
189         /* build list of interfering neighbours */
190         len = 0;
191         be_ifg_foreach_neighbour(env->ifg, &nodes_it, irn, neigh) {
192                 if (!arch_irn_is_ignore(neigh)) {
193                         obstack_ptr_grow(&env->obst, neigh);
194                         ++len;
195                 }
196         }
197         res->int_neighs = (ir_node**)obstack_finish(&env->obst);
198         res->n_neighs   = len;
199         return res;
200 }
201
202 static co_mst_irn_t *get_co_mst_irn(co_mst_env_t *env, const ir_node *node)
203 {
204         co_mst_irn_t *res = ir_nodemap_get(co_mst_irn_t, &env->map, node);
205         if (res == NULL) {
206                 res = co_mst_irn_init(env, node);
207                 ir_nodemap_insert(&env->map, node, res);
208         }
209         return res;
210 }
211
212 typedef int decide_func_t(const co_mst_irn_t *node, int col);
213
214 #ifdef DEBUG_libfirm
215
216 /**
217  * Write a chunk to stderr for debugging.
218  */
219 static void dbg_aff_chunk(const co_mst_env_t *env, const aff_chunk_t *c)
220 {
221         int i, l;
222         (void) env;
223         if (c->weight_consistent)
224                 ir_fprintf(stderr, " $%d ", c->weight);
225         ir_fprintf(stderr, "{");
226         for (i = 0, l = ARR_LEN(c->n); i < l; ++i) {
227                 const ir_node *n = c->n[i];
228                 ir_fprintf(stderr, " %+F,", n);
229         }
230         ir_fprintf(stderr, "}");
231 }
232
233 /**
234  * Dump all admissible colors to stderr.
235  */
236 static void dbg_admissible_colors(const co_mst_env_t *env, const co_mst_irn_t *node)
237 {
238         (void) env;
239
240         if (bitset_popcount(node->adm_colors) < 1)
241                 fprintf(stderr, "no admissible colors?!?");
242         else {
243                 bitset_foreach(node->adm_colors, idx) {
244                         ir_fprintf(stderr, " %zu", idx);
245                 }
246         }
247 }
248
249 /**
250  * Dump color-cost pairs to stderr.
251  */
252 static void dbg_col_cost(const co_mst_env_t *env, const col_cost_t *cost)
253 {
254         int i;
255         for (i = 0; i < env->n_regs; ++i)
256                 fprintf(stderr, " (%d, %.4f)", cost[i].col, cost[i].cost);
257 }
258
259 #endif /* DEBUG_libfirm */
260
261 static inline int get_mst_irn_col(const co_mst_irn_t *node)
262 {
263         return node->tmp_col >= 0 ? node->tmp_col : node->col;
264 }
265
266 /**
267  * @return 1 if node @p node has color @p col, 0 otherwise.
268  */
269 static int decider_has_color(const co_mst_irn_t *node, int col)
270 {
271         return get_mst_irn_col(node) == col;
272 }
273
274 /**
275  * @return 1 if node @p node has not color @p col, 0 otherwise.
276  */
277 static int decider_hasnot_color(const co_mst_irn_t *node, int col)
278 {
279         return get_mst_irn_col(node) != col;
280 }
281
282 /**
283  * Always returns true.
284  */
285 static int decider_always_yes(const co_mst_irn_t *node, int col)
286 {
287         (void) node;
288         (void) col;
289         return 1;
290 }
291
292 /** compares two affinity edges by its weight */
293 static int cmp_aff_edge(const void *a, const void *b)
294 {
295         const aff_edge_t *e1 = (const aff_edge_t*)a;
296         const aff_edge_t *e2 = (const aff_edge_t*)b;
297
298         if (e2->weight == e1->weight) {
299                 if (e2->src->node_idx == e1->src->node_idx)
300                         return QSORT_CMP(e2->tgt->node_idx, e1->tgt->node_idx);
301                 else
302                         return QSORT_CMP(e2->src->node_idx, e1->src->node_idx);
303         }
304         /* sort in descending order */
305         return QSORT_CMP(e2->weight, e1->weight);
306 }
307
308 /** compares to color-cost pairs */
309 static __attribute__((unused)) int cmp_col_cost_lt(const void *a, const void *b)
310 {
311         const col_cost_t *c1 = (const col_cost_t*)a;
312         const col_cost_t *c2 = (const col_cost_t*)b;
313         real_t diff = c1->cost - c2->cost;
314
315         if (diff < 0)
316                 return 1;
317         if (diff > 0)
318                 return -1;
319
320         return QSORT_CMP(c1->col, c2->col);
321 }
322
323 static int cmp_col_cost_gt(const void *a, const void *b)
324 {
325         const col_cost_t *c1 = (const col_cost_t*)a;
326         const col_cost_t *c2 = (const col_cost_t*)b;
327         real_t diff = c2->cost - c1->cost;
328
329         if (diff > 0)
330                 return 1;
331         if (diff < 0)
332                 return -1;
333
334         return QSORT_CMP(c1->col, c2->col);
335 }
336
337 /**
338  * Creates a new affinity chunk
339  */
340 static inline aff_chunk_t *new_aff_chunk(co_mst_env_t *env)
341 {
342         aff_chunk_t *c = XMALLOCF(aff_chunk_t, color_affinity, env->n_regs);
343         c->n                 = NEW_ARR_F(const ir_node *, 0);
344         c->interfere         = NEW_ARR_F(const ir_node *, 0);
345         c->weight            = -1;
346         c->weight_consistent = 0;
347         c->deleted           = 0;
348         c->id                = ++last_chunk_id;
349         c->visited           = 0;
350         list_add(&c->list, &env->chunklist);
351         return c;
352 }
353
354 /**
355  * Frees all memory allocated by an affinity chunk.
356  */
357 static inline void delete_aff_chunk(aff_chunk_t *c)
358 {
359         list_del(&c->list);
360         DEL_ARR_F(c->interfere);
361         DEL_ARR_F(c->n);
362         c->deleted = 1;
363         free(c);
364 }
365
366 /**
367  * binary search of sorted nodes.
368  *
369  * @return the position where n is found in the array arr or ~pos
370  * if the nodes is not here.
371  */
372 static inline int nodes_bsearch(const ir_node **arr, const ir_node *n)
373 {
374         int hi = ARR_LEN(arr);
375         int lo = 0;
376
377         while (lo < hi) {
378                 int md = lo + ((hi - lo) >> 1);
379
380                 if (arr[md] == n)
381                         return md;
382                 if (arr[md] < n)
383                         lo = md + 1;
384                 else
385                         hi = md;
386         }
387
388         return ~lo;
389 }
390
391 /** Check if a node n can be found inside arr. */
392 static int node_contains(const ir_node **arr, const ir_node *n)
393 {
394         int i = nodes_bsearch(arr, n);
395         return i >= 0;
396 }
397
398 /**
399  * Insert a node into the sorted nodes list.
400  *
401  * @return 1 if the node was inserted, 0 else
402  */
403 static int nodes_insert(const ir_node ***arr, const ir_node *irn)
404 {
405         int idx = nodes_bsearch(*arr, irn);
406
407         if (idx < 0) {
408                 int i, n = ARR_LEN(*arr);
409                 const ir_node **l;
410
411                 ARR_APP1(const ir_node *, *arr, irn);
412
413                 /* move it */
414                 idx = ~idx;
415                 l = *arr;
416                 for (i = n - 1; i >= idx; --i)
417                         l[i + 1] = l[i];
418                 l[idx] = irn;
419                 return 1;
420         }
421         return 0;
422 }
423
424 /**
425  * Adds a node to an affinity chunk
426  */
427 static inline void aff_chunk_add_node(aff_chunk_t *c, co_mst_irn_t *node)
428 {
429         int i;
430
431         if (! nodes_insert(&c->n, node->irn))
432                 return;
433
434         c->weight_consistent = 0;
435         node->chunk          = c;
436
437         for (i = node->n_neighs - 1; i >= 0; --i) {
438                 ir_node *neigh = node->int_neighs[i];
439                 nodes_insert(&c->interfere, neigh);
440         }
441 }
442
443 /**
444  * Check if affinity chunk @p chunk interferes with node @p irn.
445  */
446 static inline int aff_chunk_interferes(const aff_chunk_t *chunk, const ir_node *irn)
447 {
448         return node_contains(chunk->interfere, irn);
449 }
450
451 /**
452  * Check if there are interference edges from c1 to c2.
453  * @param c1    A chunk
454  * @param c2    Another chunk
455  * @return 1 if there are interferences between nodes of c1 and c2, 0 otherwise.
456  */
457 static inline int aff_chunks_interfere(const aff_chunk_t *c1, const aff_chunk_t *c2)
458 {
459         int i;
460
461         if (c1 == c2)
462                 return 0;
463
464         /* check if there is a node in c2 having an interfering neighbor in c1 */
465         for (i = ARR_LEN(c2->n) - 1; i >= 0; --i) {
466                 const ir_node *irn = c2->n[i];
467
468                 if (node_contains(c1->interfere, irn))
469                         return 1;
470         }
471         return 0;
472 }
473
474 /**
475  * Returns the affinity chunk of @p irn or creates a new
476  * one with @p irn as element if there is none assigned.
477  */
478 static inline aff_chunk_t *get_aff_chunk(co_mst_env_t *env, const ir_node *irn)
479 {
480         co_mst_irn_t *node = get_co_mst_irn(env, irn);
481         return node->chunk;
482 }
483
484 /**
485  * Let chunk(src) absorb the nodes of chunk(tgt) (only possible when there
486  * are no interference edges from chunk(src) to chunk(tgt)).
487  * @return 1 if successful, 0 if not possible
488  */
489 static int aff_chunk_absorb(co_mst_env_t *env, const ir_node *src, const ir_node *tgt)
490 {
491         aff_chunk_t *c1 = get_aff_chunk(env, src);
492         aff_chunk_t *c2 = get_aff_chunk(env, tgt);
493
494 #ifdef DEBUG_libfirm
495                 DB((dbg, LEVEL_4, "Attempt to let c1 (id %u): ", c1 ? c1->id : 0));
496                 if (c1) {
497                         DBG_AFF_CHUNK(env, LEVEL_4, c1);
498                 } else {
499                         DB((dbg, LEVEL_4, "{%+F}", src));
500                 }
501                 DB((dbg, LEVEL_4, "\n\tabsorb c2 (id %u): ", c2 ? c2->id : 0));
502                 if (c2) {
503                         DBG_AFF_CHUNK(env, LEVEL_4, c2);
504                 } else {
505                         DB((dbg, LEVEL_4, "{%+F}", tgt));
506                 }
507                 DB((dbg, LEVEL_4, "\n"));
508 #endif
509
510         if (c1 == NULL) {
511                 if (c2 == NULL) {
512                         /* no chunk exists */
513                         co_mst_irn_t *mirn = get_co_mst_irn(env, src);
514                         int i;
515
516                         for (i = mirn->n_neighs - 1; i >= 0; --i) {
517                                 if (mirn->int_neighs[i] == tgt)
518                                         break;
519                         }
520                         if (i < 0) {
521                                 /* create one containing both nodes */
522                                 c1 = new_aff_chunk(env);
523                                 aff_chunk_add_node(c1, get_co_mst_irn(env, src));
524                                 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
525                                 goto absorbed;
526                         }
527                 } else {
528                         /* c2 already exists */
529                         if (! aff_chunk_interferes(c2, src)) {
530                                 aff_chunk_add_node(c2, get_co_mst_irn(env, src));
531                                 goto absorbed;
532                         }
533                 }
534         } else if (c2 == NULL) {
535                 /* c1 already exists */
536                 if (! aff_chunk_interferes(c1, tgt)) {
537                         aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
538                         goto absorbed;
539                 }
540         } else if (c1 != c2 && ! aff_chunks_interfere(c1, c2)) {
541                 int idx, len;
542
543                 for (idx = 0, len = ARR_LEN(c2->n); idx < len; ++idx)
544                         aff_chunk_add_node(c1, get_co_mst_irn(env, c2->n[idx]));
545
546                 for (idx = 0, len = ARR_LEN(c2->interfere); idx < len; ++idx) {
547                         const ir_node *irn = c2->interfere[idx];
548                         nodes_insert(&c1->interfere, irn);
549                 }
550
551                 c1->weight_consistent = 0;
552
553                 delete_aff_chunk(c2);
554                 goto absorbed;
555         }
556         DB((dbg, LEVEL_4, " ... c1 interferes with c2, skipped\n"));
557         return 0;
558
559 absorbed:
560         DB((dbg, LEVEL_4, " ... absorbed\n"));
561         return 1;
562 }
563
564 /**
565  * Assures that the weight of the given chunk is consistent.
566  */
567 static void aff_chunk_assure_weight(co_mst_env_t *env, aff_chunk_t *c)
568 {
569         if (! c->weight_consistent) {
570                 int w = 0;
571                 int idx, len, i;
572
573                 for (i = 0; i < env->n_regs; ++i) {
574                         c->color_affinity[i].col = i;
575                         c->color_affinity[i].cost = REAL(0.0);
576                 }
577
578                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
579                         const ir_node         *n       = c->n[idx];
580                         const affinity_node_t *an      = get_affinity_info(env->co, n);
581                         co_mst_irn_t          *node    = get_co_mst_irn(env, n);
582
583                         node->chunk = c;
584                         if (node->constr_factor > REAL(0.0)) {
585                                 bitset_foreach (node->adm_colors, col)
586                                         c->color_affinity[col].cost += node->constr_factor;
587                         }
588
589                         if (an != NULL) {
590                                 co_gs_foreach_neighb(an, neigh) {
591                                         const ir_node *m = neigh->irn;
592
593                                         if (arch_irn_is_ignore(m))
594                                                 continue;
595
596                                         w += node_contains(c->n, m) ? neigh->costs : 0;
597                                 }
598                         }
599                 }
600
601                 for (i = 0; i < env->n_regs; ++i)
602                         c->color_affinity[i].cost *= (REAL(1.0) / ARR_LEN(c->n));
603
604                 c->weight            = w;
605                 // c->weight            = bitset_popcount(c->nodes);
606                 c->weight_consistent = 1;
607         }
608 }
609
610 /**
611  * Count the number of interfering affinity neighbours
612  */
613 static int count_interfering_aff_neighs(co_mst_env_t *env, const affinity_node_t *an)
614 {
615         const ir_node      *irn  = an->irn;
616         const co_mst_irn_t *node = get_co_mst_irn(env, irn);
617         int                res   = 0;
618
619         co_gs_foreach_neighb(an, neigh) {
620                 const ir_node *n = neigh->irn;
621                 int           i;
622
623                 if (arch_irn_is_ignore(n))
624                         continue;
625
626                 /* check if the affinity neighbour interfere */
627                 for (i = 0; i < node->n_neighs; ++i) {
628                         if (node->int_neighs[i] == n) {
629                                 ++res;
630                                 break;
631                         }
632                 }
633         }
634         return res;
635 }
636
637
638 /**
639  * Build chunks of nodes connected by affinity edges.
640  * We start at the heaviest affinity edge.
641  * The chunks of the two edge-defining nodes will be
642  * merged if there are no interference edges from one
643  * chunk to the other.
644  */
645 static void build_affinity_chunks(co_mst_env_t *env)
646 {
647         nodes_iter_t nodes_it;
648         aff_edge_t  *edges    = NEW_ARR_F(aff_edge_t, 0);
649         ir_node     *n;
650         int         i, len;
651         size_t      pn;
652
653         /* at first we create the affinity edge objects */
654         be_ifg_foreach_node(env->ifg, &nodes_it, n) {
655                 int             n_idx = get_irn_idx(n);
656                 co_mst_irn_t    *n1;
657                 affinity_node_t *an;
658
659                 if (arch_irn_is_ignore(n))
660                         continue;
661
662                 n1 = get_co_mst_irn(env, n);
663                 an = get_affinity_info(env->co, n);
664
665                 if (an != NULL) {
666                         if (n1->int_aff_neigh < 0)
667                                 n1->int_aff_neigh = count_interfering_aff_neighs(env, an);
668
669                         /* build the affinity edges */
670                         co_gs_foreach_neighb(an, neigh) {
671                                 const ir_node *m     = neigh->irn;
672                                 int            m_idx = get_irn_idx(m);
673
674                                 /* record the edge in only one direction */
675                                 if (n_idx < m_idx) {
676                                         co_mst_irn_t *n2;
677                                         aff_edge_t   edge;
678
679                                         /* skip ignore nodes */
680                                         if (arch_irn_is_ignore(m))
681                                                 continue;
682
683                                         edge.src = n;
684                                         edge.tgt = m;
685
686                                         n2 = get_co_mst_irn(env, m);
687                                         if (n2->int_aff_neigh < 0) {
688                                                 affinity_node_t *am = get_affinity_info(env->co, m);
689                                                 n2->int_aff_neigh = count_interfering_aff_neighs(env, am);
690                                         }
691                                         /*
692                                          * these weights are pure hackery ;-).
693                                          * It's not chriswue's fault but mine.
694                                          */
695                                         edge.weight = neigh->costs;
696                                         ARR_APP1(aff_edge_t, edges, edge);
697                                 }
698                         }
699                 }
700         }
701
702         /* now: sort edges and build the affinity chunks */
703         len = ARR_LEN(edges);
704         qsort(edges, len, sizeof(edges[0]), cmp_aff_edge);
705         for (i = 0; i < len; ++i) {
706                 DBG((dbg, LEVEL_1, "edge (%u,%u) %f\n", edges[i].src->node_idx, edges[i].tgt->node_idx, edges[i].weight));
707
708                 (void)aff_chunk_absorb(env, edges[i].src, edges[i].tgt);
709         }
710
711         /* now insert all chunks into a priority queue */
712         list_for_each_entry(aff_chunk_t, curr_chunk, &env->chunklist, list) {
713                 aff_chunk_assure_weight(env, curr_chunk);
714
715                 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
716                 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
717                 DBG((dbg, LEVEL_1, "\n"));
718
719                 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
720         }
721
722         for (pn = 0; pn < ARR_LEN(env->map.data); ++pn) {
723                 co_mst_irn_t *mirn = (co_mst_irn_t*)env->map.data[pn];
724                 if (mirn == NULL)
725                         continue;
726                 if (mirn->chunk != NULL)
727                         continue;
728
729                 /* no chunk is allocated so far, do it now */
730                 aff_chunk_t *curr_chunk = new_aff_chunk(env);
731                 aff_chunk_add_node(curr_chunk, mirn);
732
733                 aff_chunk_assure_weight(env, curr_chunk);
734
735                 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
736                 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
737                 DBG((dbg, LEVEL_1, "\n"));
738
739                 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
740         }
741
742         DEL_ARR_F(edges);
743 }
744
745 static __attribute__((unused)) void chunk_order_nodes(co_mst_env_t *env, aff_chunk_t *chunk)
746 {
747         pqueue_t      *grow       = new_pqueue();
748         ir_node const *max_node   = NULL;
749         int            max_weight = 0;
750         size_t         i;
751
752         for (i = ARR_LEN(chunk->n); i != 0;) {
753                 const ir_node   *irn = chunk->n[--i];
754                 affinity_node_t *an  = get_affinity_info(env->co, irn);
755                 int w = 0;
756
757                 if (arch_irn_is_ignore(irn))
758                         continue;
759
760                 if (an) {
761                         co_gs_foreach_neighb(an, neigh)
762                                 w += neigh->costs;
763
764                         if (w > max_weight) {
765                                 max_weight = w;
766                                 max_node   = irn;
767                         }
768                 }
769         }
770
771         if (max_node) {
772                 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
773
774                 for (i = ARR_LEN(chunk->n); i != 0;)
775                         bitset_set(visited, get_irn_idx(chunk->n[--i]));
776
777                 pqueue_put(grow, (void *) max_node, max_weight);
778                 bitset_clear(visited, get_irn_idx(max_node));
779                 i = 0;
780                 while (!pqueue_empty(grow)) {
781                         ir_node *irn = (ir_node*)pqueue_pop_front(grow);
782                         affinity_node_t *an = get_affinity_info(env->co, irn);
783
784                         if (arch_irn_is_ignore(irn))
785                                 continue;
786
787                         assert(i <= ARR_LEN(chunk->n));
788                         chunk->n[i++] = irn;
789
790                         assert(an);
791
792                         /* build the affinity edges */
793                         co_gs_foreach_neighb(an, neigh) {
794                                 co_mst_irn_t *node = get_co_mst_irn(env, neigh->irn);
795
796                                 if (bitset_is_set(visited, get_irn_idx(node->irn))) {
797                                         pqueue_put(grow, (void *) neigh->irn, neigh->costs);
798                                         bitset_clear(visited, get_irn_idx(node->irn));
799                                 }
800                         }
801                 }
802
803                 del_pqueue(grow);
804                 bitset_free(visited);
805         }
806 }
807
808 /**
809  * Greedy collect affinity neighbours into thew new chunk @p chunk starting at node @p node.
810  */
811 static void expand_chunk_from(co_mst_env_t *env, co_mst_irn_t *node, bitset_t *visited,
812         aff_chunk_t *chunk, aff_chunk_t *orig_chunk, decide_func_t *decider, int col)
813 {
814         waitq *nodes = new_waitq();
815
816         DBG((dbg, LEVEL_1, "\n\tExpanding new chunk (#%u) from %+F, color %d:", chunk->id, node->irn, col));
817
818         /* init queue and chunk */
819         waitq_put(nodes, node);
820         bitset_set(visited, get_irn_idx(node->irn));
821         aff_chunk_add_node(chunk, node);
822         DB((dbg, LEVEL_1, " %+F", node->irn));
823
824         /* as long as there are nodes in the queue */
825         while (! waitq_empty(nodes)) {
826                 co_mst_irn_t    *n  = (co_mst_irn_t*)waitq_get(nodes);
827                 affinity_node_t *an = get_affinity_info(env->co, n->irn);
828
829                 /* check all affinity neighbors */
830                 if (an != NULL) {
831                         co_gs_foreach_neighb(an, neigh) {
832                                 const ir_node *m    = neigh->irn;
833                                 int            m_idx = get_irn_idx(m);
834                                 co_mst_irn_t *n2;
835
836                                 if (arch_irn_is_ignore(m))
837                                         continue;
838
839                                 n2 = get_co_mst_irn(env, m);
840
841                                 if (! bitset_is_set(visited, m_idx)  &&
842                                         decider(n2, col)                 &&
843                                         ! n2->fixed                      &&
844                                         ! aff_chunk_interferes(chunk, m) &&
845                                         node_contains(orig_chunk->n, m))
846                                 {
847                                         /*
848                                                 following conditions are met:
849                                                 - neighbour is not visited
850                                                 - neighbour likes the color
851                                                 - neighbour has not yet a fixed color
852                                                 - the new chunk doesn't interfere with the neighbour
853                                                 - neighbour belongs or belonged once to the original chunk
854                                         */
855                                         bitset_set(visited, m_idx);
856                                         aff_chunk_add_node(chunk, n2);
857                                         DB((dbg, LEVEL_1, " %+F", n2->irn));
858                                         /* enqueue for further search */
859                                         waitq_put(nodes, n2);
860                                 }
861                         }
862                 }
863         }
864
865         DB((dbg, LEVEL_1, "\n"));
866
867         del_waitq(nodes);
868 }
869
870 /**
871  * Fragment the given chunk into chunks having given color and not having given color.
872  */
873 static aff_chunk_t *fragment_chunk(co_mst_env_t *env, int col, aff_chunk_t *c, waitq *tmp)
874 {
875         bitset_t    *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
876         int         idx, len;
877         aff_chunk_t *best = NULL;
878
879         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
880                 const ir_node *irn;
881                 co_mst_irn_t  *node;
882                 aff_chunk_t   *tmp_chunk;
883                 decide_func_t *decider;
884                 int           check_for_best;
885
886                 irn = c->n[idx];
887                 if (bitset_is_set(visited, get_irn_idx(irn)))
888                         continue;
889
890                 node = get_co_mst_irn(env, irn);
891
892                 if (get_mst_irn_col(node) == col) {
893                         decider        = decider_has_color;
894                         check_for_best = 1;
895                         DBG((dbg, LEVEL_4, "\tcolor %d wanted\n", col));
896                 }
897                 else {
898                         decider        = decider_hasnot_color;
899                         check_for_best = 0;
900                         DBG((dbg, LEVEL_4, "\tcolor %d forbidden\n", col));
901                 }
902
903                 /* create a new chunk starting at current node */
904                 tmp_chunk = new_aff_chunk(env);
905                 waitq_put(tmp, tmp_chunk);
906                 expand_chunk_from(env, node, visited, tmp_chunk, c, decider, col);
907                 assert(ARR_LEN(tmp_chunk->n) > 0 && "No nodes added to chunk");
908
909                 /* remember the local best */
910                 aff_chunk_assure_weight(env, tmp_chunk);
911                 if (check_for_best && (! best || best->weight < tmp_chunk->weight))
912                         best = tmp_chunk;
913         }
914
915         assert(best && "No chunk found?");
916         bitset_free(visited);
917         return best;
918 }
919
920 /**
921  * Resets the temporary fixed color of all nodes within wait queue @p nodes.
922  * ATTENTION: the queue is empty after calling this function!
923  */
924 static inline void reject_coloring(struct list_head *nodes)
925 {
926         DB((dbg, LEVEL_4, "\treject coloring for"));
927         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
928                 DB((dbg, LEVEL_4, " %+F", n->irn));
929                 assert(n->tmp_col >= 0);
930                 n->tmp_col = -1;
931                 list_del_init(&n->list);
932         }
933         DB((dbg, LEVEL_4, "\n"));
934 }
935
936 static inline void materialize_coloring(struct list_head *nodes)
937 {
938         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
939                 assert(n->tmp_col >= 0);
940                 n->col     = n->tmp_col;
941                 n->tmp_col = -1;
942                 list_del_init(&n->list);
943         }
944 }
945
946 static inline void set_temp_color(co_mst_irn_t *node, int col, struct list_head *changed)
947 {
948         assert(col >= 0);
949         assert(!node->fixed);
950         assert(node->tmp_col < 0);
951         assert(node->list.next == &node->list && node->list.prev == &node->list);
952         assert(bitset_is_set(node->adm_colors, col));
953
954         list_add_tail(&node->list, changed);
955         node->tmp_col = col;
956 }
957
958 static inline int is_loose(co_mst_irn_t *node)
959 {
960         return !node->fixed && node->tmp_col < 0;
961 }
962
963 /**
964  * Determines the costs for each color if it would be assigned to node @p node.
965  */
966 static void determine_color_costs(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs)
967 {
968         int   *neigh_cols = ALLOCAN(int, env->n_regs);
969         int    n_loose    = 0;
970         real_t coeff;
971         int    i;
972
973         for (i = 0; i < env->n_regs; ++i) {
974                 neigh_cols[i] = 0;
975                 costs[i].col = i;
976                 costs[i].cost = bitset_is_set(node->adm_colors, i) ? node->constr_factor : REAL(0.0);
977         }
978
979         for (i = 0; i < node->n_neighs; ++i) {
980                 co_mst_irn_t *n = get_co_mst_irn(env, node->int_neighs[i]);
981                 int col = get_mst_irn_col(n);
982                 if (is_loose(n)) {
983                         ++n_loose;
984                         ++neigh_cols[col];
985                 } else
986                         costs[col].cost = REAL(0.0);
987         }
988
989         if (n_loose > 0) {
990                 coeff = REAL(1.0) / n_loose;
991                 for (i = 0; i < env->n_regs; ++i)
992                         costs[i].cost *= REAL(1.0) - coeff * neigh_cols[i];
993         }
994 }
995
996 /* need forward declaration due to recursive call */
997 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed_ones, int depth, int *max_depth, int *trip);
998
999 /**
1000  * Tries to change node to a color but @p explude_col.
1001  * @return 1 if succeeded, 0 otherwise.
1002  */
1003 static int change_node_color_excluded(co_mst_env_t *env, co_mst_irn_t *node, int exclude_col, struct list_head *changed, int depth, int *max_depth, int *trip)
1004 {
1005         int col = get_mst_irn_col(node);
1006         int res = 0;
1007
1008         /* neighbours has already a different color -> good, temporary fix it */
1009         if (col != exclude_col) {
1010                 if (is_loose(node))
1011                         set_temp_color(node, col, changed);
1012                 return 1;
1013         }
1014
1015         /* The node has the color it should not have _and_ has not been visited yet. */
1016         if (is_loose(node)) {
1017                 col_cost_t *costs = ALLOCAN(col_cost_t, env->n_regs);
1018
1019                 /* Get the costs for giving the node a specific color. */
1020                 determine_color_costs(env, node, costs);
1021
1022                 /* Since the node must not have the not_col, set the costs for that color to "infinity" */
1023                 costs[exclude_col].cost = REAL(0.0);
1024
1025                 /* sort the colors according costs, cheapest first. */
1026                 qsort(costs, env->n_regs, sizeof(costs[0]), cmp_col_cost_gt);
1027
1028                 /* Try recoloring the node using the color list. */
1029                 res = recolor_nodes(env, node, costs, changed, depth + 1, max_depth, trip);
1030         }
1031
1032         return res;
1033 }
1034
1035 /**
1036  * Tries to bring node @p node to cheapest color and color all interfering neighbours with other colors.
1037  * ATTENTION: Expect @p costs already sorted by increasing costs.
1038  * @return 1 if coloring could be applied, 0 otherwise.
1039  */
1040 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed, int depth, int *max_depth, int *trip)
1041 {
1042         int   i;
1043         struct list_head local_changed;
1044
1045         ++*trip;
1046         if (depth > *max_depth)
1047                 *max_depth = depth;
1048
1049         DBG((dbg, LEVEL_4, "\tRecoloring %+F with color-costs", node->irn));
1050         DBG_COL_COST(env, LEVEL_4, costs);
1051         DB((dbg, LEVEL_4, "\n"));
1052
1053         if (depth >= recolor_limit) {
1054                 DBG((dbg, LEVEL_4, "\tHit recolor limit\n"));
1055                 return 0;
1056         }
1057
1058         for (i = 0; i < env->n_regs; ++i) {
1059                 int tgt_col  = costs[i].col;
1060                 int neigh_ok = 1;
1061                 int j;
1062
1063                 /* If the costs for that color (and all successive) are infinite, bail out we won't make it anyway. */
1064                 if (costs[i].cost == REAL(0.0)) {
1065                         DBG((dbg, LEVEL_4, "\tAll further colors forbidden\n"));
1066                         return 0;
1067                 }
1068
1069                 /* Set the new color of the node and mark the node as temporarily fixed. */
1070                 assert(node->tmp_col < 0 && "Node must not have been temporary fixed.");
1071                 INIT_LIST_HEAD(&local_changed);
1072                 set_temp_color(node, tgt_col, &local_changed);
1073                 DBG((dbg, LEVEL_4, "\tTemporary setting %+F to color %d\n", node->irn, tgt_col));
1074
1075                 /* try to color all interfering neighbours with current color forbidden */
1076                 for (j = 0; j < node->n_neighs; ++j) {
1077                         co_mst_irn_t *nn;
1078                         ir_node      *neigh;
1079
1080                         neigh = node->int_neighs[j];
1081
1082                         if (arch_irn_is_ignore(neigh))
1083                                 continue;
1084
1085                         nn = get_co_mst_irn(env, neigh);
1086                         DB((dbg, LEVEL_4, "\tHandling neighbour %+F, at position %d (fixed: %d, tmp_col: %d, col: %d)\n",
1087                                 neigh, j, nn->fixed, nn->tmp_col, nn->col));
1088
1089                         /*
1090                                 Try to change the color of the neighbor and record all nodes which
1091                                 get changed in the tmp list. Add this list to the "changed" list for
1092                                 that color. If we did not succeed to change the color of the neighbor,
1093                                 we bail out and try the next color.
1094                         */
1095                         if (get_mst_irn_col(nn) == tgt_col) {
1096                                 /* try to color neighbour with tgt_col forbidden */
1097                                 neigh_ok = change_node_color_excluded(env, nn, tgt_col, &local_changed, depth + 1, max_depth, trip);
1098
1099                                 if (!neigh_ok)
1100                                         break;
1101                         }
1102                 }
1103
1104                 /*
1105                         We managed to assign the target color to all neighbors, so from the perspective
1106                         of the current node, every thing was ok and we can return safely.
1107                 */
1108                 if (neigh_ok) {
1109                         /* append the local_changed ones to global ones */
1110                         list_splice(&local_changed, changed);
1111                         return 1;
1112                 }
1113                 else {
1114                         /* coloring of neighbours failed, so we try next color */
1115                         reject_coloring(&local_changed);
1116                 }
1117         }
1118
1119         DBG((dbg, LEVEL_4, "\tAll colors failed\n"));
1120         return 0;
1121 }
1122
1123 /**
1124  * Tries to bring node @p node and all its neighbours to color @p tgt_col.
1125  * @return 1 if color @p col could be applied, 0 otherwise
1126  */
1127 static int change_node_color(co_mst_env_t *env, co_mst_irn_t *node, int tgt_col, struct list_head *changed)
1128 {
1129         int col = get_mst_irn_col(node);
1130
1131         /* if node already has the target color -> good, temporary fix it */
1132         if (col == tgt_col) {
1133                 DBG((dbg, LEVEL_4, "\t\tCNC: %+F has already color %d, fix temporary\n", node->irn, tgt_col));
1134                 if (is_loose(node))
1135                         set_temp_color(node, tgt_col, changed);
1136                 return 1;
1137         }
1138
1139         /*
1140                 Node has not yet a fixed color and target color is admissible
1141                 -> try to recolor node and its affinity neighbours
1142         */
1143         if (is_loose(node) && bitset_is_set(node->adm_colors, tgt_col)) {
1144                 col_cost_t *costs = env->single_cols[tgt_col];
1145                 int res, max_depth, trip;
1146
1147                 max_depth = 0;
1148                 trip      = 0;
1149
1150                 DBG((dbg, LEVEL_4, "\t\tCNC: Attempt to recolor %+F ===>>\n", node->irn));
1151                 res = recolor_nodes(env, node, costs, changed, 0, &max_depth, &trip);
1152                 DBG((dbg, LEVEL_4, "\t\tCNC: <<=== Recoloring of %+F %s\n", node->irn, res ? "succeeded" : "failed"));
1153                 stat_ev_int("heur4_recolor_depth_max", max_depth);
1154                 stat_ev_int("heur4_recolor_trip", trip);
1155
1156
1157                 return res;
1158         }
1159
1160 #ifdef DEBUG_libfirm
1161                 if (firm_dbg_get_mask(dbg) & LEVEL_4) {
1162                         if (!is_loose(node))
1163                                 DB((dbg, LEVEL_4, "\t\tCNC: %+F has already fixed color %d\n", node->irn, col));
1164                         else {
1165                                 DB((dbg, LEVEL_4, "\t\tCNC: color %d not admissible for %+F (", tgt_col, node->irn));
1166                                 dbg_admissible_colors(env, node);
1167                                 DB((dbg, LEVEL_4, ")\n"));
1168                         }
1169                 }
1170 #endif
1171
1172         return 0;
1173 }
1174
1175 /**
1176  * Tries to color an affinity chunk (or at least a part of it).
1177  * Inserts uncolored parts of the chunk as a new chunk into the priority queue.
1178  */
1179 static void color_aff_chunk(co_mst_env_t *env, aff_chunk_t *c)
1180 {
1181         aff_chunk_t *best_chunk   = NULL;
1182         int         n_nodes       = ARR_LEN(c->n);
1183         int         best_color    = -1;
1184         int         n_int_chunks  = 0;
1185         waitq       *tmp_chunks   = new_waitq();
1186         waitq       *best_starts  = NULL;
1187         col_cost_t  *order        = ALLOCANZ(col_cost_t, env->n_regs);
1188         bitset_t    *visited;
1189         int         i;
1190         size_t      idx;
1191         size_t      len;
1192         size_t      nidx;
1193         size_t      pos;
1194         struct list_head changed;
1195
1196         DB((dbg, LEVEL_2, "fragmentizing chunk #%u", c->id));
1197         DBG_AFF_CHUNK(env, LEVEL_2, c);
1198         DB((dbg, LEVEL_2, "\n"));
1199
1200         stat_ev_ctx_push_fmt("heur4_color_chunk", "%u", c->id);
1201
1202         ++env->chunk_visited;
1203
1204         /* compute color preference */
1205         for (pos = 0, len = ARR_LEN(c->interfere); pos < len; ++pos) {
1206                 const ir_node *n = c->interfere[pos];
1207                 co_mst_irn_t *node = get_co_mst_irn(env, n);
1208                 aff_chunk_t *chunk = node->chunk;
1209
1210                 if (is_loose(node) && chunk && chunk->visited < env->chunk_visited) {
1211                         assert(!chunk->deleted);
1212                         chunk->visited = env->chunk_visited;
1213                         ++n_int_chunks;
1214
1215                         aff_chunk_assure_weight(env, chunk);
1216                         for (i = 0; i < env->n_regs; ++i)
1217                                 order[i].cost += chunk->color_affinity[i].cost;
1218                 }
1219         }
1220
1221         for (i = 0; i < env->n_regs; ++i) {
1222                 real_t dislike = n_int_chunks > 0 ? REAL(1.0) - order[i].cost / n_int_chunks : REAL(0.0);
1223                 order[i].col  = i;
1224                 order[i].cost = (REAL(1.0) - dislike_influence) * c->color_affinity[i].cost + dislike_influence * dislike;
1225         }
1226
1227         qsort(order, env->n_regs, sizeof(order[0]), cmp_col_cost_gt);
1228
1229         DBG_COL_COST(env, LEVEL_2, order);
1230         DB((dbg, LEVEL_2, "\n"));
1231
1232         /* check which color is the "best" for the given chunk.
1233          * if we found a color which was ok for all nodes, we take it
1234          * and do not look further. (see did_all flag usage below.)
1235          * If we have many colors which fit all nodes it is hard to decide
1236          * which one to take anyway.
1237          * TODO Sebastian: Perhaps we should at all nodes and figure out
1238          * a suitable color using costs as done above (determine_color_costs).
1239          */
1240         for (i = 0; i < env->k; ++i) {
1241                 int         col = order[i].col;
1242                 waitq       *good_starts;
1243                 aff_chunk_t *local_best;
1244                 int          n_succeeded;
1245
1246                 /* skip ignore colors */
1247                 if (!bitset_is_set(env->allocatable_regs, col))
1248                         continue;
1249
1250                 DB((dbg, LEVEL_2, "\ttrying color %d\n", col));
1251
1252                 n_succeeded = 0;
1253                 good_starts = new_waitq();
1254
1255                 /* try to bring all nodes of given chunk to the current color. */
1256                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1257                         const ir_node   *irn  = c->n[idx];
1258                         co_mst_irn_t    *node = get_co_mst_irn(env, irn);
1259                         int              good;
1260
1261                         assert(! node->fixed && "Node must not have a fixed color.");
1262                         DB((dbg, LEVEL_4, "\t\tBringing %+F from color %d to color %d ...\n", irn, node->col, col));
1263
1264                         /*
1265                                 The order of the colored nodes is important, so we record the successfully
1266                                 colored ones in the order they appeared.
1267                         */
1268                         INIT_LIST_HEAD(&changed);
1269                         stat_ev_tim_push();
1270                         good = change_node_color(env, node, col, &changed);
1271                         stat_ev_tim_pop("heur4_recolor");
1272                         if (good) {
1273                                 waitq_put(good_starts, node);
1274                                 materialize_coloring(&changed);
1275                                 node->fixed = 1;
1276                         }
1277
1278                         else
1279                                 reject_coloring(&changed);
1280
1281                         n_succeeded += good;
1282                         DB((dbg, LEVEL_4, "\t\t... %+F attempt from %d to %d %s\n", irn, node->col, col, good ? "succeeded" : "failed"));
1283                 }
1284
1285                 /* unfix all nodes */
1286                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1287                         co_mst_irn_t *node = get_co_mst_irn(env, c->n[idx]);
1288                         node->fixed = 0;
1289                 }
1290
1291                 /* try next color when failed */
1292                 if (n_succeeded == 0) {
1293                         del_waitq(good_starts);
1294                         continue;
1295                 }
1296
1297                 /* fragment the chunk according to the coloring */
1298                 local_best = fragment_chunk(env, col, c, tmp_chunks);
1299
1300                 /* search the best of the good list
1301                    and make it the new best if it is better than the current */
1302                 if (local_best) {
1303                         aff_chunk_assure_weight(env, local_best);
1304
1305                         DB((dbg, LEVEL_3, "\t\tlocal best chunk (id %u) for color %d: ", local_best->id, col));
1306                         DBG_AFF_CHUNK(env, LEVEL_3, local_best);
1307
1308                         if (! best_chunk || best_chunk->weight < local_best->weight) {
1309                                 best_chunk = local_best;
1310                                 best_color = col;
1311                                 if (best_starts)
1312                                         del_waitq(best_starts);
1313                                 best_starts = good_starts;
1314                                 DB((dbg, LEVEL_3, "\n\t\t... setting global best chunk (id %u), color %d\n", best_chunk->id, best_color));
1315                         } else {
1316                                 DB((dbg, LEVEL_3, "\n\t\t... omitting, global best is better\n"));
1317                                 del_waitq(good_starts);
1318                         }
1319                 }
1320                 else {
1321                         del_waitq(good_starts);
1322                 }
1323
1324                 /* if all nodes were recolored, bail out */
1325                 if (n_succeeded == n_nodes)
1326                         break;
1327         }
1328
1329         stat_ev_int("heur4_colors_tried", i);
1330
1331         /* free all intermediate created chunks except best one */
1332         while (! waitq_empty(tmp_chunks)) {
1333                 aff_chunk_t *tmp = (aff_chunk_t*)waitq_get(tmp_chunks);
1334                 if (tmp != best_chunk)
1335                         delete_aff_chunk(tmp);
1336         }
1337         del_waitq(tmp_chunks);
1338
1339         /* return if coloring failed */
1340         if (! best_chunk) {
1341                 if (best_starts)
1342                         del_waitq(best_starts);
1343                 return;
1344         }
1345
1346         DB((dbg, LEVEL_2, "\tbest chunk #%u ", best_chunk->id));
1347         DBG_AFF_CHUNK(env, LEVEL_2, best_chunk);
1348         DB((dbg, LEVEL_2, "using color %d\n", best_color));
1349
1350         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1351                 const ir_node *irn  = best_chunk->n[idx];
1352                 co_mst_irn_t  *node = get_co_mst_irn(env, irn);
1353                 int res;
1354
1355                 /* bring the node to the color. */
1356                 DB((dbg, LEVEL_4, "\tManifesting color %d for %+F, chunk #%u\n", best_color, node->irn, best_chunk->id));
1357                 INIT_LIST_HEAD(&changed);
1358                 stat_ev_tim_push();
1359                 res = change_node_color(env, node, best_color, &changed);
1360                 stat_ev_tim_pop("heur4_recolor");
1361                 if (res) {
1362                         materialize_coloring(&changed);
1363                         node->fixed = 1;
1364                 }
1365                 assert(list_empty(&changed));
1366         }
1367
1368         /* remove the nodes in best chunk from original chunk */
1369         len = ARR_LEN(best_chunk->n);
1370         for (idx = 0; idx < len; ++idx) {
1371                 const ir_node *irn = best_chunk->n[idx];
1372                 int pos = nodes_bsearch(c->n, irn);
1373
1374                 if (pos > 0)
1375                         c->n[pos] = NULL;
1376         }
1377         len = ARR_LEN(c->n);
1378         for (idx = nidx = 0; idx < len; ++idx) {
1379                 const ir_node *irn = c->n[idx];
1380
1381                 if (irn != NULL) {
1382                         c->n[nidx++] = irn;
1383                 }
1384         }
1385         ARR_SHRINKLEN(c->n, nidx);
1386
1387
1388         /* we have to get the nodes back into the original chunk because they are scattered over temporary chunks */
1389         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1390                 const ir_node *n  = c->n[idx];
1391                 co_mst_irn_t  *nn = get_co_mst_irn(env, n);
1392                 nn->chunk = c;
1393         }
1394
1395         /* fragment the remaining chunk */
1396         visited = bitset_malloc(get_irg_last_idx(env->co->irg));
1397         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx)
1398                 bitset_set(visited, get_irn_idx(best_chunk->n[idx]));
1399
1400         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1401                 const ir_node *irn = c->n[idx];
1402                 if (! bitset_is_set(visited, get_irn_idx(irn))) {
1403                         aff_chunk_t  *new_chunk = new_aff_chunk(env);
1404                         co_mst_irn_t *node      = get_co_mst_irn(env, irn);
1405
1406                         expand_chunk_from(env, node, visited, new_chunk, c, decider_always_yes, 0);
1407                         aff_chunk_assure_weight(env, new_chunk);
1408                         pqueue_put(env->chunks, new_chunk, new_chunk->weight);
1409                 }
1410         }
1411
1412         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1413                 const ir_node *n  = best_chunk->n[idx];
1414                 co_mst_irn_t  *nn = get_co_mst_irn(env, n);
1415                 nn->chunk = NULL;
1416         }
1417
1418         /* clear obsolete chunks and free some memory */
1419         delete_aff_chunk(best_chunk);
1420         bitset_free(visited);
1421         if (best_starts)
1422                 del_waitq(best_starts);
1423
1424         stat_ev_ctx_pop("heur4_color_chunk");
1425 }
1426
1427 /**
1428  * Main driver for mst safe coalescing algorithm.
1429  */
1430 static int co_solve_heuristic_mst(copy_opt_t *co)
1431 {
1432         unsigned     n_regs            = co->cls->n_regs;
1433         bitset_t     *allocatable_regs = bitset_alloca(n_regs);
1434         unsigned     i, j;
1435         size_t       k;
1436         size_t       pn;
1437         ir_node      *irn;
1438         co_mst_env_t mst_env;
1439
1440         last_chunk_id = 0;
1441
1442         stat_ev_tim_push();
1443
1444         /* init phase */
1445         ir_nodemap_init(&mst_env.map, co->irg);
1446         obstack_init(&mst_env.obst);
1447
1448         be_put_allocatable_regs(co->cenv->irg, co->cls, allocatable_regs);
1449         k = bitset_popcount(allocatable_regs);
1450
1451         mst_env.n_regs           = n_regs;
1452         mst_env.k                = k;
1453         mst_env.chunks           = new_pqueue();
1454         mst_env.co               = co;
1455         mst_env.allocatable_regs = allocatable_regs;
1456         mst_env.ifg              = co->cenv->ifg;
1457         INIT_LIST_HEAD(&mst_env.chunklist);
1458         mst_env.chunk_visited    = 0;
1459         mst_env.single_cols      = OALLOCN(&mst_env.obst, col_cost_t*, n_regs);
1460
1461         for (i = 0; i < n_regs; ++i) {
1462                 col_cost_t *vec = OALLOCN(&mst_env.obst, col_cost_t, n_regs);
1463
1464                 mst_env.single_cols[i] = vec;
1465                 for (j = 0; j < n_regs; ++j) {
1466                         vec[j].col  = j;
1467                         vec[j].cost = REAL(0.0);
1468                 }
1469                 vec[i].col  = 0;
1470                 vec[0].col  = i;
1471                 vec[0].cost = REAL(1.0);
1472         }
1473
1474         DBG((dbg, LEVEL_1, "==== Coloring %+F, class %s ====\n", co->irg, co->cls->name));
1475
1476         /* build affinity chunks */
1477         stat_ev_tim_push();
1478         build_affinity_chunks(&mst_env);
1479         stat_ev_tim_pop("heur4_initial_chunk");
1480
1481         /* color chunks as long as there are some */
1482         while (! pqueue_empty(mst_env.chunks)) {
1483                 aff_chunk_t *chunk = (aff_chunk_t*)pqueue_pop_front(mst_env.chunks);
1484
1485                 color_aff_chunk(&mst_env, chunk);
1486                 DB((dbg, LEVEL_4, "<<<====== Coloring chunk (%u) done\n", chunk->id));
1487                 delete_aff_chunk(chunk);
1488         }
1489
1490         /* apply coloring */
1491         for (pn = 0; pn < ARR_LEN(mst_env.map.data); ++pn) {
1492                 co_mst_irn_t *mirn = (co_mst_irn_t*)mst_env.map.data[pn];
1493                 const arch_register_t *reg;
1494                 if (mirn == NULL)
1495                         continue;
1496                 irn = get_idx_irn(co->irg, pn);
1497                 if (arch_irn_is_ignore(irn))
1498                         continue;
1499
1500                 /* skip nodes where color hasn't changed */
1501                 if (mirn->init_col == mirn->col)
1502                         continue;
1503
1504                 reg = arch_register_for_index(co->cls, mirn->col);
1505                 arch_set_irn_register(irn, reg);
1506                 DB((dbg, LEVEL_1, "%+F set color from %d to %d\n", irn, mirn->init_col, mirn->col));
1507         }
1508
1509         /* free allocated memory */
1510         del_pqueue(mst_env.chunks);
1511         obstack_free(&mst_env.obst, NULL);
1512         ir_nodemap_destroy(&mst_env.map);
1513
1514         stat_ev_tim_pop("heur4_total");
1515
1516         return 0;
1517 }
1518
1519 static const lc_opt_table_entry_t options[] = {
1520         LC_OPT_ENT_INT      ("limit", "limit recoloring",  &recolor_limit),
1521         LC_OPT_ENT_DBL      ("di",    "dislike influence", &dislike_influence),
1522         LC_OPT_LAST
1523 };
1524
1525 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyheur4)
1526 void be_init_copyheur4(void)
1527 {
1528         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1529         lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
1530         lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
1531         lc_opt_entry_t *co_grp = lc_opt_get_grp(chordal_grp, "co");
1532         lc_opt_entry_t *heur4_grp = lc_opt_get_grp(co_grp, "heur4");
1533
1534         static co_algo_info copyheur = {
1535                 co_solve_heuristic_mst, 0
1536         };
1537
1538         lc_opt_add_table(heur4_grp, options);
1539         be_register_copyopt("heur4", &copyheur);
1540
1541         FIRM_DBG_REGISTER(dbg, "firm.be.co.heur4");
1542 }