48786e45d775a5e2ddc0ec313e39fdc93b88ef08
[libfirm] / ir / be / becopyheur4.c
1 /*
2  * Copyright (C) 1995-2007 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 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif /* HAVE_CONFIG_H */
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
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 static int last_chunk_id = 0;
79
80 typedef struct _col_cost_t {
81         int    col;
82         double cost;
83 } col_cost_t;
84
85 /**
86  * An affinity chunk.
87  */
88 typedef struct _aff_chunk_t {
89         ir_node  **n;                   /**< An ARR_F containing all nodes of the chunk. */
90         bitset_t *nodes;                /**< A bitset containing all nodes inside this chunk. */
91         bitset_t *interfere;            /**< A bitset containing all interfering neighbours of the nodes in this chunk. */
92         int      weight;                /**< Weight of this chunk */
93         unsigned weight_consistent : 1; /**< Set if the weight is consistent. */
94         unsigned deleted           : 1; /**< Set if the was deleted. */
95         int      id;                    /**< For debugging: An id of this chunk. */
96 } aff_chunk_t;
97
98 /**
99  * An affinity edge.
100  */
101 typedef struct _aff_edge_t {
102         ir_node *src;                   /**< Source node. */
103         ir_node *tgt;                   /**< Target node. */
104         double  weight;                 /**< The weight of this edge. */
105 } aff_edge_t;
106
107 /* main coalescing environment */
108 typedef struct _co_mst_env_t {
109         int              n_regs;         /**< number of regs in class */
110         int              k;              /**< number of non-ignore registers in class */
111         bitset_t         *ignore_regs;   /**< set containing all global ignore registers */
112         ir_phase         ph;             /**< phase object holding data for nodes */
113         pqueue           *chunks;        /**< priority queue for chunks */
114         pset             *chunkset;      /**< set holding all chunks */
115         be_ifg_t         *ifg;           /**< the interference graph */
116         const arch_env_t *aenv;          /**< the arch environment */
117         copy_opt_t       *co;            /**< the copy opt object */
118 } co_mst_env_t;
119
120 /* stores coalescing related information for a node */
121 typedef struct _co_mst_irn_t {
122         ir_node          *irn;              /**< the irn this information belongs to */
123         aff_chunk_t      *chunk;            /**< the chunk this irn belongs to */
124         bitset_t         *adm_colors;       /**< set of admissible colors for this irn */
125         ir_node          **int_neighs;      /**< array of all interfering neighbours (cached for speed reasons) */
126         int              n_neighs;          /**< length of the interfering neighbours array. */
127         int              int_aff_neigh;     /**< number of interfering affinity neighbours */
128         int              col;               /**< color currently assigned */
129         int              init_col;          /**< the initial color */
130         int              tmp_col;           /**< a temporary assigned color */
131         unsigned         fixed     : 1;     /**< the color is fixed */
132         struct list_head list;              /**< Queue for coloring undo. */
133 } co_mst_irn_t;
134
135 #define get_co_mst_irn(mst_env, irn) (phase_get_or_set_irn_data(&(mst_env)->ph, (irn)))
136
137 typedef int decide_func_t(const co_mst_irn_t *node, int col);
138
139 #ifdef DEBUG_libfirm
140
141 /**
142  * Write a chunk to stderr for debugging.
143  */
144 static void dbg_aff_chunk(const co_mst_env_t *env, const aff_chunk_t *c) {
145         bitset_pos_t idx;
146         if (c->weight_consistent)
147                 ir_fprintf(stderr, " $%d ", c->weight);
148         ir_fprintf(stderr, "{");
149         bitset_foreach(c->nodes, idx) {
150                 ir_node *n = get_idx_irn(env->co->irg, idx);
151                 ir_fprintf(stderr, " %+F,", n);
152         }
153         ir_fprintf(stderr, "}");
154 }
155
156 /**
157  * Dump all admissible colors to stderr.
158  */
159 static void dbg_admissible_colors(const co_mst_env_t *env, const co_mst_irn_t *node) {
160         bitset_pos_t idx;
161         (void) env;
162
163         if (bitset_popcnt(node->adm_colors) < 1)
164                 fprintf(stderr, "no admissible colors?!?");
165         else {
166                 bitset_foreach(node->adm_colors, idx)
167                         fprintf(stderr, " %d", idx);
168         }
169 }
170
171 /**
172  * Dump color-cost pairs to stderr.
173  */
174 static void dbg_col_cost(const co_mst_env_t *env, const col_cost_t *cost) {
175         int i;
176         for (i = 0; i < env->n_regs; ++i) {
177                 if (cost[i].cost == COL_COST_INFEASIBLE)
178                         fprintf(stderr, " (%d, INF)", cost[i].col);
179                 else
180                         fprintf(stderr, " (%d, %.1f)", cost[i].col, cost[i].cost);
181         }
182 }
183
184 #endif /* DEBUG_libfirm */
185
186 static INLINE int get_mst_irn_col(const co_mst_irn_t *node) {
187         return node->tmp_col >= 0 ? node->tmp_col : node->col;
188 }
189
190 /**
191  * @return 1 if node @p node has color @p col, 0 otherwise.
192  */
193 static int decider_has_color(const co_mst_irn_t *node, int col) {
194         return get_mst_irn_col(node) == col;
195 }
196
197 /**
198  * @return 1 if node @p node has not color @p col, 0 otherwise.
199  */
200 static int decider_hasnot_color(const co_mst_irn_t *node, int col) {
201         return get_mst_irn_col(node) != col;
202 }
203
204 /**
205  * Always returns true.
206  */
207 static int decider_always_yes(const co_mst_irn_t *node, int col) {
208         (void) node;
209         (void) col;
210         return 1;
211 }
212
213 /** compares two affinity edges by its weight */
214 static int cmp_aff_edge(const void *a, const void *b) {
215         const aff_edge_t *e1 = a;
216         const aff_edge_t *e2 = b;
217
218         if (e2->weight == e1->weight) {
219                 if (e2->src->node_idx == e1->src->node_idx)
220                         return QSORT_CMP(e2->tgt->node_idx, e1->tgt->node_idx);
221                 else
222                         return QSORT_CMP(e2->src->node_idx, e1->src->node_idx);
223         }
224         /* sort in descending order */
225         return QSORT_CMP(e2->weight, e1->weight);
226 }
227
228 /** compares to color-cost pairs */
229 static int cmp_col_cost(const void *a, const void *b) {
230         const col_cost_t *c1 = a;
231         const col_cost_t *c2 = b;
232
233         return c1->cost < c2->cost ? -1 : 1;
234 }
235
236 /**
237  * Creates a new affinity chunk
238  */
239 static INLINE aff_chunk_t *new_aff_chunk(co_mst_env_t *env) {
240         aff_chunk_t *c = xmalloc(sizeof(*c));
241         c->weight            = -1;
242         c->weight_consistent = 0;
243         c->n                 = NEW_ARR_F(ir_node *, 0);
244         c->nodes             = bitset_irg_malloc(env->co->irg);
245         c->interfere         = bitset_irg_malloc(env->co->irg);
246         c->id                = last_chunk_id++;
247         pset_insert(env->chunkset, c, c->id);
248         return c;
249 }
250
251 /**
252  * Frees all memory allocated by an affinity chunk.
253  */
254 static INLINE void delete_aff_chunk(co_mst_env_t *env, aff_chunk_t *c) {
255         pset_remove(env->chunkset, c, c->id);
256         bitset_free(c->nodes);
257         bitset_free(c->interfere);
258         DEL_ARR_F(c->n);
259         c->deleted = 1;
260         free(c);
261 }
262
263 /**
264  * Adds a node to an affinity chunk
265  */
266 static INLINE void aff_chunk_add_node(aff_chunk_t *c, co_mst_irn_t *node) {
267         int i;
268
269         if (bitset_is_set(c->nodes, get_irn_idx(node->irn)))
270                 return;
271
272         c->weight_consistent = 0;
273         node->chunk          = c;
274         bitset_set(c->nodes, get_irn_idx(node->irn));
275
276         ARR_APP1(ir_node *, c->n, node->irn);
277
278         for (i = node->n_neighs - 1; i >= 0; --i) {
279                 ir_node *neigh = node->int_neighs[i];
280                 bitset_set(c->interfere, get_irn_idx(neigh));
281         }
282 }
283
284 /**
285  * In case there is no phase information for irn, initialize it.
286  */
287 static void *co_mst_irn_init(ir_phase *ph, ir_node *irn, void *old) {
288         co_mst_irn_t *res = old ? old : phase_alloc(ph, sizeof(res[0]));
289         co_mst_env_t *env = ph->priv;
290
291         if (res != old) {
292                 const arch_register_req_t *req;
293                 void     *nodes_it = be_ifg_nodes_iter_alloca(env->ifg);
294                 ir_node  *neigh;
295                 unsigned len;
296
297                 res->irn           = irn;
298                 res->chunk         = NULL;
299                 res->fixed         = 0;
300                 res->tmp_col       = -1;
301                 res->int_neighs    = NULL;
302                 res->int_aff_neigh = 0;
303                 res->col           = arch_register_get_index(arch_get_irn_register(env->aenv, irn));
304                 res->init_col      = res->col;
305                 INIT_LIST_HEAD(&res->list);
306
307                 DB((dbg, LEVEL_4, "Creating phase info for %+F\n", irn));
308
309                 /* set admissible registers */
310                 res->adm_colors = bitset_obstack_alloc(phase_obst(ph), env->n_regs);
311
312                 /* Exclude colors not assignable to the irn */
313                 req = arch_get_register_req(env->aenv, irn, -1);
314                 if (arch_register_req_is(req, limited))
315                         rbitset_copy_to_bitset(req->limited, res->adm_colors);
316                 else
317                         bitset_set_all(res->adm_colors);
318
319                 /* exclude global ignore registers as well */
320                 bitset_andnot(res->adm_colors, env->ignore_regs);
321
322                 /* set the number of interfering affinity neighbours to -1, they are calculated later */
323                 res->int_aff_neigh = -1;
324
325                 /* build list of interfering neighbours */
326                 len = 0;
327                 be_ifg_foreach_neighbour(env->ifg, nodes_it, irn, neigh) {
328                         if (! arch_irn_is(env->aenv, neigh, ignore)) {
329                                 obstack_ptr_grow(phase_obst(ph), neigh);
330                                 ++len;
331                         }
332                 }
333                 res->int_neighs = obstack_finish(phase_obst(ph));
334                 res->n_neighs   = len;
335         }
336         return res;
337 }
338
339 /**
340  * Check if affinity chunk @p chunk interferes with node @p irn.
341  */
342 static INLINE int aff_chunk_interferes(co_mst_env_t *env, const aff_chunk_t *chunk, ir_node *irn) {
343         (void) env;
344         return bitset_is_set(chunk->interfere, get_irn_idx(irn));
345 }
346
347 /**
348  * Check if there are interference edges from c1 to c2.
349  * @param env   The global co_mst environment
350  * @param c1    A chunk
351  * @param c2    Another chunk
352  * @return 1 if there are interferences between nodes of c1 and c2, 0 otherwise.
353  */
354 static INLINE int aff_chunks_interfere(co_mst_env_t *env, const aff_chunk_t *c1, const aff_chunk_t *c2) {
355         bitset_t *tmp;
356
357         if (c1 == c2)
358                 return 0;
359
360         /* check if there is a node in c2 having an interfering neighbor in c1 */
361         tmp = bitset_alloca(get_irg_last_idx(env->co->irg));
362         tmp = bitset_copy(tmp, c1->interfere);
363         tmp = bitset_and(tmp, c2->nodes);
364
365         return bitset_popcnt(tmp) > 0;
366 }
367
368 /**
369  * Returns the affinity chunk of @p irn or creates a new
370  * one with @p irn as element if there is none assigned.
371  */
372 static INLINE aff_chunk_t *get_aff_chunk(co_mst_env_t *env, ir_node *irn) {
373         co_mst_irn_t *node = get_co_mst_irn(env, irn);
374         return node->chunk;
375 }
376
377 /**
378  * Let chunk(src) absorb the nodes of chunk(tgt) (only possible when there
379  * are no interference edges from chunk(src) to chunk(tgt)).
380  * @return 1 if successful, 0 if not possible
381  */
382 static int aff_chunk_absorb(co_mst_env_t *env, ir_node *src, ir_node *tgt) {
383         aff_chunk_t *c1 = get_aff_chunk(env, src);
384         aff_chunk_t *c2 = get_aff_chunk(env, tgt);
385
386 #ifdef DEBUG_libfirm
387                 DB((dbg, LEVEL_4, "Attempt to let c1 (id %d): ", c1 ? c1->id : -1));
388                 if (c1) {
389                         DBG_AFF_CHUNK(env, LEVEL_4, c1);
390                 } else {
391                         DB((dbg, LEVEL_4, "{%+F}", src));
392                 }
393                 DB((dbg, LEVEL_4, "\n\tabsorb c2 (id %d): ", c2 ? c2->id : -1));
394                 if (c2) {
395                         DBG_AFF_CHUNK(env, LEVEL_4, c2);
396                 } else {
397                         DB((dbg, LEVEL_4, "{%+F}", tgt));
398                 }
399                 DB((dbg, LEVEL_4, "\n"));
400 #endif
401
402         if (c1 == NULL) {
403                 if (c2 == NULL) {
404                         /* no chunk exists */
405                         co_mst_irn_t *mirn = get_co_mst_irn(env, src);
406                         int i;
407
408                         for (i = mirn->n_neighs - 1; i >= 0; --i) {
409                                 if (mirn->int_neighs[i] == tgt)
410                                         break;
411                         }
412                         if (i < 0) {
413                                 /* create one containing both nodes */
414                                 c1 = new_aff_chunk(env);
415                                 aff_chunk_add_node(c1, get_co_mst_irn(env, src));
416                                 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
417                                 goto absorbed;
418                         }
419                 } else {
420                         /* c2 already exists */
421                         if (! aff_chunk_interferes(env, c2, src)) {
422                                 aff_chunk_add_node(c2, get_co_mst_irn(env, src));
423                                 goto absorbed;
424                         }
425                 }
426         } else if (c2 == NULL) {
427                 /* c1 already exists */
428                 if (! aff_chunk_interferes(env, c1, tgt)) {
429                         aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
430                         goto absorbed;
431                 }
432         } else if (c1 != c2 && ! aff_chunks_interfere(env, c1, c2)) {
433                 int idx, len;
434
435                 for (idx = 0, len = ARR_LEN(c2->n); idx < len; ++idx) {
436                         ir_node      *n  = c2->n[idx];
437                         co_mst_irn_t *mn = get_co_mst_irn(env, n);
438
439                         mn->chunk = c1;
440
441                         if (! bitset_is_set(c1->nodes, get_irn_idx(n)))
442                                 ARR_APP1(ir_node *, c1->n, n);
443                 }
444
445                 bitset_or(c1->nodes, c2->nodes);
446                 bitset_or(c1->interfere, c2->interfere);
447                 c1->weight_consistent = 0;
448
449                 delete_aff_chunk(env, c2);
450                 goto absorbed;
451         }
452         DB((dbg, LEVEL_4, " ... c1 interferes with c2, skipped\n"));
453         return 0;
454
455 absorbed:
456         DB((dbg, LEVEL_4, " ... absorbed\n"));
457         return 1;
458 }
459
460 /**
461  * Assures that the weight of the given chunk is consistent.
462  */
463 static void aff_chunk_assure_weight(const co_mst_env_t *env, aff_chunk_t *c) {
464         if (! c->weight_consistent) {
465                 int w = 0;
466                 int idx, len;
467
468                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
469                         ir_node               *n  = c->n[idx];
470                         const affinity_node_t *an = get_affinity_info(env->co, n);
471
472                         if (an != NULL) {
473                                 neighb_t *neigh;
474                                 co_gs_foreach_neighb(an, neigh) {
475                                         const ir_node *m    = neigh->irn;
476                                         const int     m_idx = get_irn_idx(m);
477
478                                         /* skip ignore nodes */
479                                         if (arch_irn_is(env->aenv, m, ignore))
480                                                 continue;
481
482                                         w += bitset_is_set(c->nodes, m_idx) ? neigh->costs : 0;
483                                 }
484                         }
485                 }
486
487                 c->weight            = w;
488                 c->weight_consistent = 1;
489         }
490 }
491
492 /**
493  * Count the number of interfering affinity neighbours
494  */
495 static int count_interfering_aff_neighs(co_mst_env_t *env, const affinity_node_t *an) {
496         const neighb_t     *neigh;
497         ir_node            *irn  = an->irn;
498         const co_mst_irn_t *node = get_co_mst_irn(env, irn);
499         int                res   = 0;
500
501         co_gs_foreach_neighb(an, neigh) {
502                 const ir_node *n = neigh->irn;
503                 int           i;
504
505                 /* skip ignore nodes */
506                 if (arch_irn_is(env->aenv, n, ignore))
507                         continue;
508
509                 /* check if the affinity neighbour interfere */
510                 for (i = 0; i < node->n_neighs; ++i) {
511                         if (node->int_neighs[i] == n) {
512                                 ++res;
513                                 break;
514                         }
515                 }
516         }
517         return res;
518 }
519
520
521 /**
522  * Build chunks of nodes connected by affinity edges.
523  * We start at the heaviest affinity edge.
524  * The chunks of the two edge-defining nodes will be
525  * merged if there are no interference edges from one
526  * chunk to the other.
527  */
528 static void build_affinity_chunks(co_mst_env_t *env) {
529         void        *nodes_it = be_ifg_nodes_iter_alloca(env->ifg);
530         aff_edge_t  *edges    = NEW_ARR_F(aff_edge_t, 0);
531         ir_node     *n;
532         int         i, len;
533         aff_chunk_t *curr_chunk;
534
535         /* at first we create the affinity edge objects */
536         be_ifg_foreach_node(env->ifg, nodes_it, n) {
537                 int             n_idx = get_irn_idx(n);
538                 co_mst_irn_t    *n1;
539                 affinity_node_t *an;
540
541                 /* skip ignore nodes */
542                 if (arch_irn_is(env->aenv, n, ignore))
543                         continue;
544
545                 n1 = get_co_mst_irn(env, n);
546                 an = get_affinity_info(env->co, n);
547
548                 if (an != NULL) {
549                         neighb_t *neigh;
550
551                         if (n1->int_aff_neigh < 0)
552                                 n1->int_aff_neigh = count_interfering_aff_neighs(env, an);
553
554                         /* build the affinity edges */
555                         co_gs_foreach_neighb(an, neigh) {
556                                 ir_node *m    = neigh->irn;
557                                 int     m_idx = get_irn_idx(m);
558
559                                 /* record the edge in only one direction */
560                                 if (n_idx < m_idx) {
561                                         co_mst_irn_t *n2;
562                                         aff_edge_t   edge;
563
564                                         /* skip ignore nodes */
565                                         if (arch_irn_is(env->aenv, m, ignore))
566                                                 continue;
567
568                                         edge.src = n;
569                                         edge.tgt = m;
570
571                                         n2 = get_co_mst_irn(env, m);
572                                         if (n2->int_aff_neigh < 0) {
573                                                 affinity_node_t *am = get_affinity_info(env->co, m);
574                                                 n2->int_aff_neigh = count_interfering_aff_neighs(env, am);
575                                         }
576                                         /*
577                                          * these weights are pure hackery ;-).
578                                          * It's not chriswue's fault but mine.
579                                          */
580                                         edge.weight = (double)neigh->costs / (double)(1 + n1->int_aff_neigh + n2->int_aff_neigh);
581                                         ARR_APP1(aff_edge_t, edges, edge);
582                                 }
583                         }
584                 }
585         }
586
587         /* now: sort edges and build the affinity chunks */
588         len = ARR_LEN(edges);
589         qsort(edges, len, sizeof(edges[0]), cmp_aff_edge);
590         for (i = 0; i < len; ++i) {
591                 DBG((dbg, LEVEL_1, "edge (%u,%u) %f\n", edges[i].src->node_idx, edges[i].tgt->node_idx, edges[i].weight));
592
593                 (void)aff_chunk_absorb(env, edges[i].src, edges[i].tgt);
594         }
595
596         /* now insert all chunks into a priority queue */
597         foreach_pset(env->chunkset, curr_chunk) {
598                 aff_chunk_assure_weight(env, curr_chunk);
599
600                 DBG((dbg, LEVEL_1, "entry #%d", curr_chunk->id));
601                 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
602                 DBG((dbg, LEVEL_1, "\n"));
603
604                 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
605         }
606         foreach_phase_irn(&env->ph, n) {
607                 co_mst_irn_t *mirn = get_co_mst_irn(env, n);
608
609                 if (mirn->chunk == NULL) {
610                         /* no chunk is allocated so far, do it now */
611                         aff_chunk_t *curr_chunk = new_aff_chunk(env);
612                         aff_chunk_add_node(curr_chunk, mirn);
613
614                         aff_chunk_assure_weight(env, curr_chunk);
615
616                         DBG((dbg, LEVEL_1, "entry #%d", curr_chunk->id));
617                         DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
618                         DBG((dbg, LEVEL_1, "\n"));
619
620                         pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
621                 }
622         }
623
624         DEL_ARR_F(edges);
625 }
626
627 /**
628  * Greedy collect affinity neighbours into thew new chunk @p chunk starting at node @p node.
629  */
630 static void expand_chunk_from(co_mst_env_t *env, co_mst_irn_t *node, bitset_t *visited,
631         aff_chunk_t *chunk, aff_chunk_t *orig_chunk, decide_func_t *decider, int col)
632 {
633         waitq *nodes = new_waitq();
634
635         DBG((dbg, LEVEL_1, "\n\tExpanding new chunk (#%d) from %+F, color %d:", chunk->id, node->irn, col));
636
637         /* init queue and chunk */
638         waitq_put(nodes, node);
639         bitset_set(visited, get_irn_idx(node->irn));
640         aff_chunk_add_node(chunk, node);
641         DB((dbg, LEVEL_1, " %+F", node->irn));
642
643         /* as long as there are nodes in the queue */
644         while (! waitq_empty(nodes)) {
645                 co_mst_irn_t    *n  = waitq_get(nodes);
646                 affinity_node_t *an = get_affinity_info(env->co, n->irn);
647
648                 /* check all affinity neighbors */
649                 if (an != NULL) {
650                         neighb_t *neigh;
651                         co_gs_foreach_neighb(an, neigh) {
652                                 ir_node      *m    = neigh->irn;
653                                 int          m_idx = get_irn_idx(m);
654                                 co_mst_irn_t *n2;
655
656                                 /* skip ignore nodes */
657                                 if (arch_irn_is(env->aenv, m, ignore))
658                                         continue;
659
660                                 n2 = get_co_mst_irn(env, m);
661
662                                 if (! bitset_is_set(visited, m_idx)       &&
663                                         decider(n2, col)                      &&
664                                         ! n2->fixed                           &&
665                                         ! aff_chunk_interferes(env, chunk, m) &&
666                                         bitset_is_set(orig_chunk->nodes, m_idx))
667                                 {
668                                         /*
669                                                 following conditions are met:
670                                                 - neighbour is not visited
671                                                 - neighbour likes the color
672                                                 - neighbour has not yet a fixed color
673                                                 - the new chunk doesn't interfere with the neighbour
674                                                 - neighbour belongs or belonged once to the original chunk
675                                         */
676                                         bitset_set(visited, m_idx);
677                                         aff_chunk_add_node(chunk, n2);
678                                         DB((dbg, LEVEL_1, " %+F", n2->irn));
679                                         /* enqueue for further search */
680                                         waitq_put(nodes, n2);
681                                 }
682                         }
683                 }
684         }
685
686         DB((dbg, LEVEL_1, "\n"));
687
688         del_waitq(nodes);
689 }
690
691 /**
692  * Fragment the given chunk into chunks having given color and not having given color.
693  */
694 static aff_chunk_t *fragment_chunk(co_mst_env_t *env, int col, aff_chunk_t *c, waitq *tmp) {
695         bitset_t    *visited = bitset_irg_malloc(env->co->irg);
696         int         idx, len;
697         aff_chunk_t *best = NULL;
698
699         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
700                 ir_node       *irn;
701                 co_mst_irn_t  *node;
702                 aff_chunk_t   *tmp_chunk;
703                 decide_func_t *decider;
704                 int           check_for_best;
705
706                 irn = c->n[idx];
707                 if (bitset_is_set(visited, get_irn_idx(irn)))
708                         continue;
709
710                 node = get_co_mst_irn(env, irn);
711
712                 if (get_mst_irn_col(node) == col) {
713                         decider        = decider_has_color;
714                         check_for_best = 1;
715                         DBG((dbg, LEVEL_4, "\tcolor %d wanted", col));
716                 }
717                 else {
718                         decider        = decider_hasnot_color;
719                         check_for_best = 0;
720                         DBG((dbg, LEVEL_4, "\tcolor %d forbidden", col));
721                 }
722
723                 /* create a new chunk starting at current node */
724                 tmp_chunk = new_aff_chunk(env);
725                 waitq_put(tmp, tmp_chunk);
726                 expand_chunk_from(env, node, visited, tmp_chunk, c, decider, col);
727                 assert(bitset_popcnt(tmp_chunk->nodes) > 0 && "No nodes added to chunk");
728
729                 /* remember the local best */
730                 aff_chunk_assure_weight(env, tmp_chunk);
731                 if (check_for_best && (! best || best->weight < tmp_chunk->weight))
732                         best = tmp_chunk;
733         }
734
735         assert(best && "No chunk found?");
736         bitset_free(visited);
737         return best;
738 }
739
740 /**
741  * Initializes an array of color-cost pairs.
742  * Sets forbidden colors to costs COL_COST_INFEASIBLE and all others to @p c.
743  */
744 static INLINE void col_cost_init(co_mst_env_t *env, col_cost_t *cost, double c) {
745         int i;
746
747         for (i = 0; i < env->n_regs; ++i) {
748                 cost[i].col = i;
749                 if (bitset_is_set(env->ignore_regs, i))
750                         cost[i].cost = COL_COST_INFEASIBLE;
751                 else
752                         cost[i].cost = c;
753         }
754 }
755
756 /**
757  * Initializes an array of color-cost pairs.
758  * Sets all colors except color @p col to COL_COST_INFEASIBLE and @p col to 0.0
759  */
760 static INLINE void col_cost_init_single(co_mst_env_t *env, col_cost_t *cost, int col) {
761         assert(! bitset_is_set(env->ignore_regs, col) && "Attempt to use forbidden color.");
762         col_cost_init(env, cost, COL_COST_INFEASIBLE);
763         cost[col].col = 0;
764         cost[0].col   = col;
765         cost[0].cost  = 0.0;
766 }
767
768 /**
769  * Resets the temporary fixed color of all nodes within wait queue @p nodes.
770  * ATTENTION: the queue is empty after calling this function!
771  */
772 static INLINE void reject_coloring(struct list_head *nodes) {
773         co_mst_irn_t *n, *temp;
774         DB((dbg, LEVEL_4, "\treject coloring for"));
775         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
776                 DB((dbg, LEVEL_4, " %+F", n->irn));
777                 assert(n->tmp_col >= 0);
778                 n->tmp_col = -1;
779                 list_del_init(&n->list);
780         }
781         DB((dbg, LEVEL_4, "\n"));
782 }
783
784 static INLINE void materialize_coloring(struct list_head *nodes) {
785         co_mst_irn_t *n, *temp;
786         list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
787                 assert(n->tmp_col >= 0);
788                 n->col     = n->tmp_col;
789                 n->tmp_col = -1;
790                 list_del_init(&n->list);
791         }
792 }
793
794 static INLINE void set_temp_color(co_mst_irn_t *node, int col, struct list_head *changed)
795 {
796         assert(col >= 0);
797         assert(!node->fixed);
798         assert(node->tmp_col < 0);
799         assert(node->list.next == &node->list && node->list.prev == &node->list);
800
801         list_add_tail(&node->list, changed);
802         node->tmp_col = col;
803 }
804
805 static INLINE int is_loose(co_mst_irn_t *node)
806 {
807         return !node->fixed && node->tmp_col < 0;
808 }
809
810 /**
811  * Determines the costs for each color if it would be assigned to node @p node.
812  */
813 static void determine_color_costs(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs) {
814         affinity_node_t *an = get_affinity_info(env->co, node->irn);
815         neighb_t        *aff_neigh;
816         bitset_pos_t     idx;
817         int              i;
818
819         col_cost_init(env, costs, 0.0);
820
821         /* calculate (negative) costs for affinity neighbours */
822         if (an != NULL) {
823                 co_gs_foreach_neighb(an, aff_neigh) {
824                         ir_node      *m = aff_neigh->irn;
825                         co_mst_irn_t *neigh;
826                         double       c;
827
828                         /* skip ignore nodes */
829                         if (arch_irn_is(env->aenv, m, ignore))
830                                 continue;
831
832                         neigh = get_co_mst_irn(env, m);
833                         c     = (double)aff_neigh->costs;
834
835                         /* calculate costs for fixed affinity neighbours */
836                         if (!is_loose(neigh)) {
837                                 int col = get_mst_irn_col(neigh);
838                                 costs[col].cost -= c * AFF_NEIGHBOUR_FIX_BENEFIT;
839                         }
840                 }
841         }
842
843         /* calculate (positive) costs for interfering neighbours */
844         for (i = 0; i < node->n_neighs; ++i) {
845                 co_mst_irn_t *neigh;
846                 int          col, col_cnt;
847                 ir_node      *int_neigh;
848
849                 int_neigh = node->int_neighs[i];
850
851     assert(!arch_irn_is(env->aenv, int_neigh, ignore));
852
853                 neigh   = get_co_mst_irn(env, int_neigh);
854                 col     = get_mst_irn_col(neigh);
855                 col_cnt = bitset_popcnt(neigh->adm_colors);
856
857                 if (!is_loose(neigh)) {
858                         /* colors of fixed interfering neighbours are infeasible */
859                         costs[col].cost = COL_COST_INFEASIBLE;
860                 }
861                 else if (col_cnt < env->k) {
862                         /* calculate costs for constrained interfering neighbours */
863                         double ratio = 1.0 - ((double)col_cnt / (double)env->k);
864
865                         bitset_foreach_clear(neigh->adm_colors, idx) {
866                                 /* check only explicitly forbidden colors (skip global forbidden ones) */
867                                 if (! bitset_is_set(env->ignore_regs, idx)) {
868                                         costs[col].cost += ratio * NEIGHBOUR_CONSTR_COSTS;
869                                 }
870                         }
871                 }
872
873                 DB((dbg, LEVEL_4, "\tneigh %+F, loose: %d, color: %d\n", int_neigh, is_loose(neigh), col));
874         }
875
876         /* set all not admissible colors to COL_COST_INFEASIBLE */
877         bitset_foreach_clear(node->adm_colors, idx)
878                 costs[idx].cost = COL_COST_INFEASIBLE;
879 }
880
881 /* need forward declaration due to recursive call */
882 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed_ones);
883
884 /**
885  * Tries to change node to a color but @p explude_col.
886  * @return 1 if succeeded, 0 otherwise.
887  */
888 static int change_node_color_excluded(co_mst_env_t *env, co_mst_irn_t *node, int exclude_col, struct list_head *changed_ones) {
889         int col = get_mst_irn_col(node);
890         int res = 0;
891
892         /* neighbours has already a different color -> good, temporary fix it */
893         if (col != exclude_col) {
894                 if (is_loose(node))
895                         set_temp_color(node, col, changed_ones);
896                 return 1;
897         }
898
899         /* The node has the color it should not have _and_ has not been visited yet. */
900         if (is_loose(node)) {
901                 col_cost_t *costs = alloca(env->n_regs * sizeof(costs[0]));
902
903                 /* Get the costs for giving the node a specific color. */
904                 determine_color_costs(env, node, costs);
905
906                 /* Since the node must not have the not_col, set the costs for that color to "infinity" */
907                 costs[exclude_col].cost = COL_COST_INFEASIBLE;
908
909                 /* sort the colors according costs, cheapest first. */
910                 qsort(costs, env->n_regs, sizeof(costs[0]), cmp_col_cost);
911
912                 /* Try recoloring the node using the color list. */
913                 res = recolor_nodes(env, node, costs, changed_ones);
914         }
915
916         return res;
917 }
918
919 /**
920  * Tries to bring node @p node to cheapest color and color all interfering neighbours with other colors.
921  * ATTENTION: Expect @p costs already sorted by increasing costs.
922  * @return 1 if coloring could be applied, 0 otherwise.
923  */
924 static int recolor_nodes(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs, struct list_head *changed_ones) {
925         int   i;
926         struct list_head local_changed;
927
928         DBG((dbg, LEVEL_1, "\tRecoloring %+F with color-costs", node->irn));
929         DBG_COL_COST(env, LEVEL_1, costs);
930         DB((dbg, LEVEL_1, "\n"));
931
932         for (i = 0; i < env->n_regs; ++i) {
933                 int tgt_col  = costs[i].col;
934                 int neigh_ok = 1;
935                 int j;
936
937                 /* If the costs for that color (and all successive) are infinite, bail out we won't make it anyway. */
938                 if (costs[i].cost == COL_COST_INFEASIBLE) {
939                         return 0;
940                 }
941
942                 /* Set the new color of the node and mark the node as temporarily fixed. */
943                 assert(node->tmp_col < 0 && "Node must not have been temporary fixed.");
944                 INIT_LIST_HEAD(&local_changed);
945                 set_temp_color(node, tgt_col, &local_changed);
946                 DBG((dbg, LEVEL_4, "\tTemporary setting %+F to color %d\n", node->irn, tgt_col));
947
948                 /* try to color all interfering neighbours with current color forbidden */
949                 for (j = 0; j < node->n_neighs; ++j) {
950                         co_mst_irn_t *nn;
951                         ir_node      *neigh;
952
953                         neigh = node->int_neighs[j];
954
955                         /* skip ignore nodes */
956                         if (arch_irn_is(env->aenv, neigh, ignore))
957                                 continue;
958
959                         nn = get_co_mst_irn(env, neigh);
960                         DB((dbg, LEVEL_4, "\tHandling neighbour %+F, at position %d (fixed: %d, tmp_col: %d, col: %d)\n",
961                                 neigh, j, nn->fixed, nn->tmp_col, nn->col));
962
963                         /*
964                                 Try to change the color of the neighbor and record all nodes which
965                                 get changed in the tmp list. Add this list to the "changed" list for
966                                 that color. If we did not succeed to change the color of the neighbor,
967                                 we bail out and try the next color.
968                         */
969                         if (get_mst_irn_col(nn) == tgt_col) {
970                                 /* try to color neighbour with tgt_col forbidden */
971                                 neigh_ok = change_node_color_excluded(env, nn, tgt_col, &local_changed);
972
973                                 if (!neigh_ok)
974                                         break;
975                         }
976                 }
977
978                 /*
979                         We managed to assign the target color to all neighbors, so from the perspective
980                         of the current node, every thing was ok and we can return safely.
981                 */
982                 if (neigh_ok) {
983                         /* append the local_changed ones to global ones */
984                         list_splice(&local_changed, changed_ones);
985                         return 1;
986                 }
987                 else {
988                         /* coloring of neighbours failed, so we try next color */
989                         reject_coloring(&local_changed);
990                 }
991         }
992
993         return 0;
994 }
995
996 /**
997  * Tries to bring node @p node and all it's neighbours to color @p tgt_col.
998  * @return 1 if color @p col could be applied, 0 otherwise
999  */
1000 static int change_node_color(co_mst_env_t *env, co_mst_irn_t *node, int tgt_col, struct list_head *changed_ones) {
1001         int col = get_mst_irn_col(node);
1002
1003         /* if node already has the target color -> good, temporary fix it */
1004         if (col == tgt_col) {
1005                 DBG((dbg, LEVEL_4, "\t\tCNC: %+F has already color %d, fix temporary\n", node->irn, tgt_col));
1006                 if (is_loose(node))
1007                         set_temp_color(node, tgt_col, changed_ones);
1008                 return 1;
1009         }
1010
1011         /*
1012                 Node has not yet a fixed color and target color is admissible
1013                 -> try to recolor node and it's affinity neighbours
1014         */
1015         if (is_loose(node) && bitset_is_set(node->adm_colors, tgt_col)) {
1016                 col_cost_t *costs = alloca(env->n_regs * sizeof(costs[0]));
1017                 int        res;
1018
1019                 col_cost_init_single(env, costs, tgt_col);
1020
1021                 DBG((dbg, LEVEL_4, "\t\tCNC: Attempt to recolor %+F ===>>\n", node->irn));
1022                 res = recolor_nodes(env, node, costs, changed_ones);
1023                 DBG((dbg, LEVEL_4, "\t\tCNC: <<=== Recoloring of %+F %s\n", node->irn, res ? "succeeded" : "failed"));
1024
1025                 return res;
1026         }
1027
1028 #ifdef DEBUG_libfirm
1029                 if (firm_dbg_get_mask(dbg) & LEVEL_4) {
1030                         if (!is_loose(node))
1031                                 DB((dbg, LEVEL_4, "\t\tCNC: %+F has already fixed color %d\n", node->irn, col));
1032                         else {
1033                                 DB((dbg, LEVEL_4, "\t\tCNC: color %d not admissible for %+F (", tgt_col, node->irn));
1034                                 dbg_admissible_colors(env, node);
1035                                 DB((dbg, LEVEL_4, ")\n"));
1036                         }
1037                 }
1038 #endif
1039
1040         return 0;
1041 }
1042
1043 /**
1044  * Tries to color an affinity chunk (or at least a part of it).
1045  * Inserts uncolored parts of the chunk as a new chunk into the priority queue.
1046  */
1047 static void color_aff_chunk(co_mst_env_t *env, aff_chunk_t *c) {
1048         aff_chunk_t *best_chunk   = NULL;
1049         int         best_color    = -1;
1050         int         did_all       = 0;
1051         waitq       *tmp_chunks   = new_waitq();
1052         waitq       *best_starts  = NULL;
1053         bitset_t    *visited;
1054         int         col, idx, len;
1055         struct list_head changed_ones;
1056
1057         DB((dbg, LEVEL_2, "fragmentizing chunk #%d", c->id));
1058         DBG_AFF_CHUNK(env, LEVEL_2, c);
1059         DB((dbg, LEVEL_2, "\n"));
1060
1061
1062         /* check which color is the "best" for the given chunk.
1063          * if we found a color which was ok for all nodes, we take it
1064          * and do not look further. (see did_all flag usage below.)
1065          * If we have many colors which fit all nodes it is hard to decide
1066          * which one to take anyway.
1067          * TODO Sebastian: Perhaps we should at all nodes and figure out
1068          * a suitable color using costs as done above (determine_color_costs).
1069          */
1070         for (col = 0; col < env->n_regs && !did_all; ++col) {
1071                 int         one_good     = 0;
1072                 waitq       *good_starts = new_waitq();
1073                 aff_chunk_t *local_best;
1074
1075                 /* skip ignore colors */
1076                 if (bitset_is_set(env->ignore_regs, col))
1077                         continue;
1078
1079                 DB((dbg, LEVEL_3, "\ttrying color %d\n", col));
1080
1081                 /* suppose we can color all nodes to the same color */
1082                 did_all = 1;
1083
1084                 INIT_LIST_HEAD(&changed_ones);
1085
1086                 /* try to bring all nodes of given chunk to the current color. */
1087                 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1088                         ir_node      *irn  = c->n[idx];
1089                         co_mst_irn_t *node = get_co_mst_irn(env, irn);
1090                         int          good  = 0;
1091
1092                         assert(! node->fixed && "Node must not have a fixed color.");
1093                         DB((dbg, LEVEL_4, "\t\tBringing %+F from color %d to color %d ...\n", irn, node->col, col));
1094
1095                         /*
1096                                 The order of the colored nodes is important, so we record the successfully
1097                                 colored ones in the order they appeared.
1098                         */
1099                         good = change_node_color(env, node, col, &changed_ones);
1100                         if (good) {
1101                                 waitq_put(good_starts, node);
1102                         }
1103
1104                         one_good |= good;
1105                         did_all  &= good;
1106
1107                         DB((dbg, LEVEL_4, "\t\t... %+F attempt from %d to %d %s\n", irn, node->col, col, one_good ? "succeeded" : "failed"));
1108                 }
1109
1110                 /* try next color when failed */
1111                 if (! one_good) {
1112                         reject_coloring(&changed_ones);
1113                         continue;
1114                 }
1115
1116                 /* fragment the chunk according to the coloring */
1117                 local_best = fragment_chunk(env, col, c, tmp_chunks);
1118
1119                 /* search the best of the good list
1120                    and make it the new best if it is better than the current */
1121                 if (local_best) {
1122                         aff_chunk_assure_weight(env, local_best);
1123
1124                         DB((dbg, LEVEL_4, "\t\tlocal best chunk (id %d) for color %d: ", local_best->id, col));
1125                         DBG_AFF_CHUNK(env, LEVEL_4, local_best);
1126
1127                         if (! best_chunk || best_chunk->weight < local_best->weight) {
1128                                 best_chunk = local_best;
1129                                 best_color = col;
1130                                 if (best_starts)
1131                                         del_waitq(best_starts);
1132                                 best_starts = good_starts;
1133                                 DB((dbg, LEVEL_4, "\n\t\t... setting global best chunk (id %d), color %d\n", best_chunk->id, best_color));
1134                         } else {
1135                                 DB((dbg, LEVEL_4, "\n\t\t... omitting, global best is better\n"));
1136                                 del_waitq(good_starts);
1137                         }
1138                 }
1139                 else {
1140                         del_waitq(good_starts);
1141                 }
1142
1143                 reject_coloring(&changed_ones);
1144         }
1145
1146         /* free all intermediate created chunks except best one */
1147         while (! waitq_empty(tmp_chunks)) {
1148                 aff_chunk_t *tmp = waitq_get(tmp_chunks);
1149                 if (tmp != best_chunk)
1150                         delete_aff_chunk(env, tmp);
1151         }
1152         del_waitq(tmp_chunks);
1153
1154         /* return if coloring failed */
1155         if (! best_chunk) {
1156                 if (best_starts)
1157                         del_waitq(best_starts);
1158                 return;
1159         }
1160
1161         DB((dbg, LEVEL_2, "\tbest chunk #%d ", best_chunk->id));
1162         DBG_AFF_CHUNK(env, LEVEL_2, best_chunk);
1163         DB((dbg, LEVEL_2, "using color %d\n", best_color));
1164
1165         INIT_LIST_HEAD(&changed_ones);
1166         for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1167                 ir_node      *irn  = best_chunk->n[idx];
1168                 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1169                 int res;
1170
1171                 /* bring the node to the color. */
1172                 DB((dbg, LEVEL_4, "\tManifesting color %d for %+F, chunk #%d\n", best_color, node->irn, best_chunk->id));
1173                 INIT_LIST_HEAD(&changed_ones);
1174                 res = change_node_color(env, node, best_color, &changed_ones);
1175                 if (res) {
1176                         materialize_coloring(&changed_ones);
1177                         node->fixed = 1;
1178                 }
1179         }
1180
1181         /* remove the nodes in best chunk from original chunk */
1182         bitset_andnot(c->nodes, best_chunk->nodes);
1183         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1184                 ir_node *irn = c->n[idx];
1185
1186                 if (bitset_is_set(best_chunk->nodes, get_irn_idx(irn))) {
1187                         int last = ARR_LEN(c->n) - 1;
1188
1189                         c->n[idx] = c->n[last];
1190                         ARR_SHRINKLEN(c->n, last);
1191                         len--;
1192                 }
1193         }
1194
1195         /* we have to get the nodes back into the original chunk because they are scattered over temporary chunks */
1196         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1197                 ir_node      *n  = c->n[idx];
1198                 co_mst_irn_t *nn = get_co_mst_irn(env, n);
1199                 nn->chunk = c;
1200         }
1201
1202         /* fragment the remaining chunk */
1203         visited = bitset_irg_malloc(env->co->irg);
1204         bitset_or(visited, best_chunk->nodes);
1205         for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1206                 ir_node *irn = c->n[idx];
1207                 if (! bitset_is_set(visited, get_irn_idx(irn))) {
1208                         aff_chunk_t  *new_chunk = new_aff_chunk(env);
1209                         co_mst_irn_t *node      = get_co_mst_irn(env, irn);
1210
1211                         expand_chunk_from(env, node, visited, new_chunk, c, decider_always_yes, 0);
1212                         aff_chunk_assure_weight(env, new_chunk);
1213                         pqueue_put(env->chunks, new_chunk, new_chunk->weight);
1214                 }
1215         }
1216
1217         /* clear obsolete chunks and free some memory */
1218         delete_aff_chunk(env, best_chunk);
1219         bitset_free(visited);
1220         if (best_starts)
1221                 del_waitq(best_starts);
1222 }
1223
1224 /**
1225  * Main driver for mst safe coalescing algorithm.
1226  */
1227 int co_solve_heuristic_mst(copy_opt_t *co) {
1228         unsigned     n_regs       = co->cls->n_regs;
1229         bitset_t     *ignore_regs = bitset_alloca(n_regs);
1230         unsigned     k;
1231         ir_node      *irn;
1232         co_mst_env_t mst_env;
1233
1234         /* init phase */
1235         phase_init(&mst_env.ph, "co_mst", co->irg, PHASE_DEFAULT_GROWTH, co_mst_irn_init, &mst_env);
1236
1237         k = be_put_ignore_regs(co->cenv->birg, co->cls, ignore_regs);
1238         k = n_regs - k;
1239
1240         mst_env.n_regs      = n_regs;
1241         mst_env.k           = k;
1242         mst_env.chunks      = new_pqueue();
1243         mst_env.co          = co;
1244         mst_env.ignore_regs = ignore_regs;
1245         mst_env.ifg         = co->cenv->ifg;
1246         mst_env.aenv        = co->aenv;
1247         mst_env.chunkset    = pset_new_ptr(512);
1248
1249         DBG((dbg, LEVEL_1, "==== Coloring %+F, class %s ====\n", co->irg, co->cls->name));
1250
1251         /* build affinity chunks */
1252         build_affinity_chunks(&mst_env);
1253
1254         /* color chunks as long as there are some */
1255         while (! pqueue_empty(mst_env.chunks)) {
1256                 aff_chunk_t *chunk = pqueue_get(mst_env.chunks);
1257
1258                 color_aff_chunk(&mst_env, chunk);
1259                 DB((dbg, LEVEL_4, "<<<====== Coloring chunk (%d) done\n", chunk->id));
1260                 delete_aff_chunk(&mst_env, chunk);
1261         }
1262
1263         /* apply coloring */
1264         foreach_phase_irn(&mst_env.ph, irn) {
1265                 co_mst_irn_t *mirn = get_co_mst_irn(&mst_env, irn);
1266                 const arch_register_t *reg;
1267
1268                 if (arch_irn_is(mst_env.aenv, irn, ignore))
1269                         continue;
1270
1271                 // assert(mirn->fixed && "Node should have fixed color");
1272
1273                 /* skip nodes where color hasn't changed */
1274                 if (mirn->init_col == mirn->col)
1275                         continue;
1276
1277                 reg = arch_register_for_index(co->cls, mirn->col);
1278                 arch_set_irn_register(co->aenv, irn, reg);
1279                 DB((dbg, LEVEL_1, "%+F set color from %d to %d\n", irn, mirn->init_col, mirn->col));
1280         }
1281
1282         /* free allocated memory */
1283         del_pqueue(mst_env.chunks);
1284         phase_free(&mst_env.ph);
1285         del_pset(mst_env.chunkset);
1286
1287         return 0;
1288 }
1289
1290 void be_init_copyheur4(void) {
1291         FIRM_DBG_REGISTER(dbg, "firm.be.co.heur4");
1292 }
1293
1294 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyheur4);