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