2 * This file is part of libFirm.
3 * Copyright (C) 2012 University of Karlsruhe.
8 * @brief Simple copy minimization heuristics.
9 * @author Christian Wuerdig
12 * This is the C implementation of the mst algorithm
13 * originally written in Java by Sebastian Hack.
14 * (also known as "heur3" :)
15 * Performs simple copy minimization.
19 #define DISABLE_STATEV
26 #include "raw_bitset.h"
27 #include "irnodemap.h"
41 #include "becopyopt_t.h"
47 #define DBG_AFF_CHUNK(env, level, chunk) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_aff_chunk((env), (chunk)); } while (0)
48 #define DBG_COL_COST(env, level, cost) do { if (firm_dbg_get_mask(dbg) & (level)) dbg_col_cost((env), (cost)); } while (0)
50 static firm_dbg_module_t *dbg = NULL;
54 #define DBG_AFF_CHUNK(env, level, chunk)
55 #define DBG_COL_COST(env, level, cost)
60 #define REAL(C) (C ## f)
62 static unsigned last_chunk_id = 0;
63 static int recolor_limit = 7;
64 static double dislike_influence = REAL(0.1);
66 typedef struct col_cost_t {
74 typedef struct aff_chunk_t {
75 const ir_node **n; /**< An ARR_F containing all nodes of the chunk. */
76 const ir_node **interfere; /**< An ARR_F containing all inference. */
77 int weight; /**< Weight of this chunk */
78 unsigned weight_consistent : 1; /**< Set if the weight is consistent. */
79 unsigned deleted : 1; /**< For debugging: Set if the was deleted. */
80 unsigned id; /**< An id of this chunk. */
83 col_cost_t color_affinity[1];
89 typedef struct aff_edge_t {
90 const ir_node *src; /**< Source node. */
91 const ir_node *tgt; /**< Target node. */
92 int weight; /**< The weight of this edge. */
95 /* main coalescing environment */
96 typedef struct co_mst_env_t {
97 int n_regs; /**< number of regs in class */
98 bitset_t const *allocatable_regs; /**< set containing all global ignore registers */
99 ir_nodemap map; /**< phase object holding data for nodes */
101 pqueue_t *chunks; /**< priority queue for chunks */
102 list_head chunklist; /**< list holding all chunks */
103 be_ifg_t *ifg; /**< the interference graph */
104 copy_opt_t *co; /**< the copy opt object */
105 unsigned chunk_visited;
106 col_cost_t **single_cols;
109 /* stores coalescing related information for a node */
110 typedef struct co_mst_irn_t {
111 const ir_node *irn; /**< the irn this information belongs to */
112 aff_chunk_t *chunk; /**< the chunk this irn belongs to */
113 bitset_t *adm_colors; /**< set of admissible colors for this irn */
114 ir_node **int_neighs; /**< array of all interfering neighbours (cached for speed reasons) */
115 int n_neighs; /**< length of the interfering neighbours array. */
116 int int_aff_neigh; /**< number of interfering affinity neighbours */
117 int col; /**< color currently assigned */
118 int init_col; /**< the initial color */
119 int tmp_col; /**< a temporary assigned color */
120 unsigned fixed : 1; /**< the color is fixed */
121 struct list_head list; /**< Queue for coloring undo. */
122 real_t constr_factor;
126 * In case there is no phase information for irn, initialize it.
128 static co_mst_irn_t *co_mst_irn_init(co_mst_env_t *env, const ir_node *irn)
130 co_mst_irn_t *const res = OALLOC(&env->obst, co_mst_irn_t);
135 res->int_neighs = NULL;
136 /* set the number of interfering affinity neighbours to -1, they are calculated later */
137 res->int_aff_neigh = -1;
138 res->col = arch_get_irn_register(irn)->index;
139 res->init_col = res->col;
140 INIT_LIST_HEAD(&res->list);
142 DB((dbg, LEVEL_4, "Creating phase info for %+F\n", irn));
144 /* set admissible registers */
145 unsigned const n_regs = env->n_regs;
146 bitset_t *const adm = bitset_obstack_alloc(&env->obst, n_regs);
147 res->adm_colors = adm;
148 bitset_copy(adm, env->allocatable_regs);
150 /* Exclude colors not assignable to the irn */
151 arch_register_req_t const *const req = arch_get_irn_register_req(irn);
152 if (arch_register_req_is(req, limited))
153 rbitset_and(adm->data, req->limited, n_regs);
155 /* compute the constraint factor */
156 res->constr_factor = (real_t)(1 + n_regs - bitset_popcount(adm)) / n_regs;
158 /* build list of interfering neighbours */
160 neighbours_iter_t nodes_it;
161 be_ifg_foreach_neighbour(env->ifg, &nodes_it, irn, neigh) {
162 if (!arch_irn_is_ignore(neigh)) {
163 obstack_ptr_grow(&env->obst, neigh);
167 res->int_neighs = (ir_node**)obstack_finish(&env->obst);
172 static co_mst_irn_t *get_co_mst_irn(co_mst_env_t *env, const ir_node *node)
174 co_mst_irn_t *res = ir_nodemap_get(co_mst_irn_t, &env->map, node);
176 res = co_mst_irn_init(env, node);
177 ir_nodemap_insert(&env->map, node, res);
182 typedef int decide_func_t(const co_mst_irn_t *node, int col);
187 * Write a chunk to stderr for debugging.
189 static void dbg_aff_chunk(const co_mst_env_t *env, const aff_chunk_t *c)
193 if (c->weight_consistent)
194 ir_fprintf(stderr, " $%d ", c->weight);
195 ir_fprintf(stderr, "{");
196 for (i = 0, l = ARR_LEN(c->n); i < l; ++i) {
197 const ir_node *n = c->n[i];
198 ir_fprintf(stderr, " %+F,", n);
200 ir_fprintf(stderr, "}");
204 * Dump all admissible colors to stderr.
206 static void dbg_admissible_colors(const co_mst_env_t *env, const co_mst_irn_t *node)
210 if (bitset_popcount(node->adm_colors) < 1)
211 fprintf(stderr, "no admissible colors?!?");
213 bitset_foreach(node->adm_colors, idx) {
214 ir_fprintf(stderr, " %zu", idx);
220 * Dump color-cost pairs to stderr.
222 static void dbg_col_cost(const co_mst_env_t *env, const col_cost_t *cost)
225 for (i = 0; i < env->n_regs; ++i)
226 fprintf(stderr, " (%d, %.4f)", cost[i].col, cost[i].cost);
229 #endif /* DEBUG_libfirm */
231 static inline int get_mst_irn_col(const co_mst_irn_t *node)
233 return node->tmp_col >= 0 ? node->tmp_col : node->col;
237 * @return 1 if node @p node has color @p col, 0 otherwise.
239 static int decider_has_color(const co_mst_irn_t *node, int col)
241 return get_mst_irn_col(node) == col;
245 * @return 1 if node @p node has not color @p col, 0 otherwise.
247 static int decider_hasnot_color(const co_mst_irn_t *node, int col)
249 return get_mst_irn_col(node) != col;
253 * Always returns true.
255 static int decider_always_yes(const co_mst_irn_t *node, int col)
262 /** compares two affinity edges by its weight */
263 static int cmp_aff_edge(const void *a, const void *b)
265 const aff_edge_t *e1 = (const aff_edge_t*)a;
266 const aff_edge_t *e2 = (const aff_edge_t*)b;
268 if (e2->weight == e1->weight) {
269 if (e2->src->node_idx == e1->src->node_idx)
270 return QSORT_CMP(e2->tgt->node_idx, e1->tgt->node_idx);
272 return QSORT_CMP(e2->src->node_idx, e1->src->node_idx);
274 /* sort in descending order */
275 return QSORT_CMP(e2->weight, e1->weight);
278 /** compares to color-cost pairs */
279 static __attribute__((unused)) int cmp_col_cost_lt(const void *a, const void *b)
281 const col_cost_t *c1 = (const col_cost_t*)a;
282 const col_cost_t *c2 = (const col_cost_t*)b;
283 real_t diff = c1->cost - c2->cost;
290 return QSORT_CMP(c1->col, c2->col);
293 static int cmp_col_cost_gt(const void *a, const void *b)
295 const col_cost_t *c1 = (const col_cost_t*)a;
296 const col_cost_t *c2 = (const col_cost_t*)b;
297 real_t diff = c2->cost - c1->cost;
304 return QSORT_CMP(c1->col, c2->col);
308 * Creates a new affinity chunk
310 static inline aff_chunk_t *new_aff_chunk(co_mst_env_t *env)
312 aff_chunk_t *c = XMALLOCF(aff_chunk_t, color_affinity, env->n_regs);
313 c->n = NEW_ARR_F(const ir_node *, 0);
314 c->interfere = NEW_ARR_F(const ir_node *, 0);
316 c->weight_consistent = 0;
318 c->id = ++last_chunk_id;
320 list_add(&c->list, &env->chunklist);
325 * Frees all memory allocated by an affinity chunk.
327 static inline void delete_aff_chunk(aff_chunk_t *c)
330 DEL_ARR_F(c->interfere);
337 * binary search of sorted nodes.
339 * @return the position where n is found in the array arr or ~pos
340 * if the nodes is not here.
342 static inline int nodes_bsearch(const ir_node **arr, const ir_node *n)
344 int hi = ARR_LEN(arr);
348 int md = lo + ((hi - lo) >> 1);
361 /** Check if a node n can be found inside arr. */
362 static int node_contains(const ir_node **arr, const ir_node *n)
364 int i = nodes_bsearch(arr, n);
369 * Insert a node into the sorted nodes list.
371 * @return 1 if the node was inserted, 0 else
373 static int nodes_insert(const ir_node ***arr, const ir_node *irn)
375 int idx = nodes_bsearch(*arr, irn);
378 int i, n = ARR_LEN(*arr);
381 ARR_APP1(const ir_node *, *arr, irn);
386 for (i = n - 1; i >= idx; --i)
395 * Adds a node to an affinity chunk
397 static inline void aff_chunk_add_node(aff_chunk_t *c, co_mst_irn_t *node)
401 if (! nodes_insert(&c->n, node->irn))
404 c->weight_consistent = 0;
407 for (i = node->n_neighs - 1; i >= 0; --i) {
408 ir_node *neigh = node->int_neighs[i];
409 nodes_insert(&c->interfere, neigh);
414 * Check if affinity chunk @p chunk interferes with node @p irn.
416 static inline int aff_chunk_interferes(const aff_chunk_t *chunk, const ir_node *irn)
418 return node_contains(chunk->interfere, irn);
422 * Check if there are interference edges from c1 to c2.
424 * @param c2 Another chunk
425 * @return 1 if there are interferences between nodes of c1 and c2, 0 otherwise.
427 static inline int aff_chunks_interfere(const aff_chunk_t *c1, const aff_chunk_t *c2)
434 /* check if there is a node in c2 having an interfering neighbor in c1 */
435 for (i = ARR_LEN(c2->n) - 1; i >= 0; --i) {
436 const ir_node *irn = c2->n[i];
438 if (node_contains(c1->interfere, irn))
445 * Returns the affinity chunk of @p irn or creates a new
446 * one with @p irn as element if there is none assigned.
448 static inline aff_chunk_t *get_aff_chunk(co_mst_env_t *env, const ir_node *irn)
450 co_mst_irn_t *node = get_co_mst_irn(env, irn);
455 * Let chunk(src) absorb the nodes of chunk(tgt) (only possible when there
456 * are no interference edges from chunk(src) to chunk(tgt)).
457 * @return 1 if successful, 0 if not possible
459 static int aff_chunk_absorb(co_mst_env_t *env, const ir_node *src, const ir_node *tgt)
461 aff_chunk_t *c1 = get_aff_chunk(env, src);
462 aff_chunk_t *c2 = get_aff_chunk(env, tgt);
465 DB((dbg, LEVEL_4, "Attempt to let c1 (id %u): ", c1 ? c1->id : 0));
467 DBG_AFF_CHUNK(env, LEVEL_4, c1);
469 DB((dbg, LEVEL_4, "{%+F}", src));
471 DB((dbg, LEVEL_4, "\n\tabsorb c2 (id %u): ", c2 ? c2->id : 0));
473 DBG_AFF_CHUNK(env, LEVEL_4, c2);
475 DB((dbg, LEVEL_4, "{%+F}", tgt));
477 DB((dbg, LEVEL_4, "\n"));
482 /* no chunk exists */
483 co_mst_irn_t *mirn = get_co_mst_irn(env, src);
486 for (i = mirn->n_neighs - 1; i >= 0; --i) {
487 if (mirn->int_neighs[i] == tgt)
491 /* create one containing both nodes */
492 c1 = new_aff_chunk(env);
493 aff_chunk_add_node(c1, get_co_mst_irn(env, src));
494 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
498 /* c2 already exists */
499 if (! aff_chunk_interferes(c2, src)) {
500 aff_chunk_add_node(c2, get_co_mst_irn(env, src));
504 } else if (c2 == NULL) {
505 /* c1 already exists */
506 if (! aff_chunk_interferes(c1, tgt)) {
507 aff_chunk_add_node(c1, get_co_mst_irn(env, tgt));
510 } else if (c1 != c2 && ! aff_chunks_interfere(c1, c2)) {
513 for (idx = 0, len = ARR_LEN(c2->n); idx < len; ++idx)
514 aff_chunk_add_node(c1, get_co_mst_irn(env, c2->n[idx]));
516 for (idx = 0, len = ARR_LEN(c2->interfere); idx < len; ++idx) {
517 const ir_node *irn = c2->interfere[idx];
518 nodes_insert(&c1->interfere, irn);
521 c1->weight_consistent = 0;
523 delete_aff_chunk(c2);
526 DB((dbg, LEVEL_4, " ... c1 interferes with c2, skipped\n"));
530 DB((dbg, LEVEL_4, " ... absorbed\n"));
535 * Assures that the weight of the given chunk is consistent.
537 static void aff_chunk_assure_weight(co_mst_env_t *env, aff_chunk_t *c)
539 if (! c->weight_consistent) {
543 for (i = 0; i < env->n_regs; ++i) {
544 c->color_affinity[i].col = i;
545 c->color_affinity[i].cost = REAL(0.0);
548 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
549 const ir_node *n = c->n[idx];
550 const affinity_node_t *an = get_affinity_info(env->co, n);
551 co_mst_irn_t *node = get_co_mst_irn(env, n);
554 if (node->constr_factor > REAL(0.0)) {
555 bitset_foreach (node->adm_colors, col)
556 c->color_affinity[col].cost += node->constr_factor;
560 co_gs_foreach_neighb(an, neigh) {
561 const ir_node *m = neigh->irn;
563 if (arch_irn_is_ignore(m))
566 w += node_contains(c->n, m) ? neigh->costs : 0;
571 for (i = 0; i < env->n_regs; ++i)
572 c->color_affinity[i].cost *= (REAL(1.0) / ARR_LEN(c->n));
575 // c->weight = bitset_popcount(c->nodes);
576 c->weight_consistent = 1;
581 * Count the number of interfering affinity neighbours
583 static int count_interfering_aff_neighs(co_mst_env_t *env, const affinity_node_t *an)
585 const ir_node *irn = an->irn;
586 const co_mst_irn_t *node = get_co_mst_irn(env, irn);
589 co_gs_foreach_neighb(an, neigh) {
590 const ir_node *n = neigh->irn;
593 if (arch_irn_is_ignore(n))
596 /* check if the affinity neighbour interfere */
597 for (i = 0; i < node->n_neighs; ++i) {
598 if (node->int_neighs[i] == n) {
609 * Build chunks of nodes connected by affinity edges.
610 * We start at the heaviest affinity edge.
611 * The chunks of the two edge-defining nodes will be
612 * merged if there are no interference edges from one
613 * chunk to the other.
615 static void build_affinity_chunks(co_mst_env_t *env)
617 aff_edge_t *edges = NEW_ARR_F(aff_edge_t, 0);
619 /* at first we create the affinity edge objects */
620 be_ifg_foreach_node(env->ifg, n) {
621 int n_idx = get_irn_idx(n);
625 if (arch_irn_is_ignore(n))
628 n1 = get_co_mst_irn(env, n);
629 an = get_affinity_info(env->co, n);
632 if (n1->int_aff_neigh < 0)
633 n1->int_aff_neigh = count_interfering_aff_neighs(env, an);
635 /* build the affinity edges */
636 co_gs_foreach_neighb(an, neigh) {
637 const ir_node *m = neigh->irn;
638 int m_idx = get_irn_idx(m);
640 /* record the edge in only one direction */
645 /* skip ignore nodes */
646 if (arch_irn_is_ignore(m))
652 n2 = get_co_mst_irn(env, m);
653 if (n2->int_aff_neigh < 0) {
654 affinity_node_t *am = get_affinity_info(env->co, m);
655 n2->int_aff_neigh = count_interfering_aff_neighs(env, am);
658 * these weights are pure hackery ;-).
659 * It's not chriswue's fault but mine.
661 edge.weight = neigh->costs;
662 ARR_APP1(aff_edge_t, edges, edge);
668 /* now: sort edges and build the affinity chunks */
669 size_t const len = ARR_LEN(edges);
670 qsort(edges, len, sizeof(edges[0]), cmp_aff_edge);
671 for (size_t i = 0; i < len; ++i) {
672 DBG((dbg, LEVEL_1, "edge (%u,%u) %f\n", edges[i].src->node_idx, edges[i].tgt->node_idx, edges[i].weight));
674 (void)aff_chunk_absorb(env, edges[i].src, edges[i].tgt);
677 /* now insert all chunks into a priority queue */
678 list_for_each_entry(aff_chunk_t, curr_chunk, &env->chunklist, list) {
679 aff_chunk_assure_weight(env, curr_chunk);
681 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
682 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
683 DBG((dbg, LEVEL_1, "\n"));
685 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
688 for (size_t pn = 0; pn < ARR_LEN(env->map.data); ++pn) {
689 co_mst_irn_t *mirn = (co_mst_irn_t*)env->map.data[pn];
692 if (mirn->chunk != NULL)
695 /* no chunk is allocated so far, do it now */
696 aff_chunk_t *curr_chunk = new_aff_chunk(env);
697 aff_chunk_add_node(curr_chunk, mirn);
699 aff_chunk_assure_weight(env, curr_chunk);
701 DBG((dbg, LEVEL_1, "entry #%u", curr_chunk->id));
702 DBG_AFF_CHUNK(env, LEVEL_1, curr_chunk);
703 DBG((dbg, LEVEL_1, "\n"));
705 pqueue_put(env->chunks, curr_chunk, curr_chunk->weight);
711 static __attribute__((unused)) void chunk_order_nodes(co_mst_env_t *env, aff_chunk_t *chunk)
713 pqueue_t *grow = new_pqueue();
714 ir_node const *max_node = NULL;
718 for (i = ARR_LEN(chunk->n); i != 0;) {
719 const ir_node *irn = chunk->n[--i];
720 affinity_node_t *an = get_affinity_info(env->co, irn);
723 if (arch_irn_is_ignore(irn))
727 co_gs_foreach_neighb(an, neigh)
730 if (w > max_weight) {
738 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
740 for (i = ARR_LEN(chunk->n); i != 0;)
741 bitset_set(visited, get_irn_idx(chunk->n[--i]));
743 pqueue_put(grow, (void *) max_node, max_weight);
744 bitset_clear(visited, get_irn_idx(max_node));
746 while (!pqueue_empty(grow)) {
747 ir_node *irn = (ir_node*)pqueue_pop_front(grow);
748 affinity_node_t *an = get_affinity_info(env->co, irn);
750 if (arch_irn_is_ignore(irn))
753 assert(i <= ARR_LEN(chunk->n));
758 /* build the affinity edges */
759 co_gs_foreach_neighb(an, neigh) {
760 co_mst_irn_t *node = get_co_mst_irn(env, neigh->irn);
762 if (bitset_is_set(visited, get_irn_idx(node->irn))) {
763 pqueue_put(grow, (void *) neigh->irn, neigh->costs);
764 bitset_clear(visited, get_irn_idx(node->irn));
770 bitset_free(visited);
775 * Greedy collect affinity neighbours into thew new chunk @p chunk starting at node @p node.
777 static void expand_chunk_from(co_mst_env_t *env, co_mst_irn_t *node, bitset_t *visited,
778 aff_chunk_t *chunk, aff_chunk_t *orig_chunk, decide_func_t *decider, int col)
780 waitq *nodes = new_waitq();
782 DBG((dbg, LEVEL_1, "\n\tExpanding new chunk (#%u) from %+F, color %d:", chunk->id, node->irn, col));
784 /* init queue and chunk */
785 waitq_put(nodes, node);
786 bitset_set(visited, get_irn_idx(node->irn));
787 aff_chunk_add_node(chunk, node);
788 DB((dbg, LEVEL_1, " %+F", node->irn));
790 /* as long as there are nodes in the queue */
791 while (! waitq_empty(nodes)) {
792 co_mst_irn_t *n = (co_mst_irn_t*)waitq_get(nodes);
793 affinity_node_t *an = get_affinity_info(env->co, n->irn);
795 /* check all affinity neighbors */
797 co_gs_foreach_neighb(an, neigh) {
798 const ir_node *m = neigh->irn;
799 int m_idx = get_irn_idx(m);
802 if (arch_irn_is_ignore(m))
805 n2 = get_co_mst_irn(env, m);
807 if (! bitset_is_set(visited, m_idx) &&
810 ! aff_chunk_interferes(chunk, m) &&
811 node_contains(orig_chunk->n, m))
814 following conditions are met:
815 - neighbour is not visited
816 - neighbour likes the color
817 - neighbour has not yet a fixed color
818 - the new chunk doesn't interfere with the neighbour
819 - neighbour belongs or belonged once to the original chunk
821 bitset_set(visited, m_idx);
822 aff_chunk_add_node(chunk, n2);
823 DB((dbg, LEVEL_1, " %+F", n2->irn));
824 /* enqueue for further search */
825 waitq_put(nodes, n2);
831 DB((dbg, LEVEL_1, "\n"));
837 * Fragment the given chunk into chunks having given color and not having given color.
839 static aff_chunk_t *fragment_chunk(co_mst_env_t *env, int col, aff_chunk_t *c, waitq *tmp)
841 bitset_t *visited = bitset_malloc(get_irg_last_idx(env->co->irg));
843 aff_chunk_t *best = NULL;
845 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
848 aff_chunk_t *tmp_chunk;
849 decide_func_t *decider;
853 if (bitset_is_set(visited, get_irn_idx(irn)))
856 node = get_co_mst_irn(env, irn);
858 if (get_mst_irn_col(node) == col) {
859 decider = decider_has_color;
861 DBG((dbg, LEVEL_4, "\tcolor %d wanted\n", col));
864 decider = decider_hasnot_color;
866 DBG((dbg, LEVEL_4, "\tcolor %d forbidden\n", col));
869 /* create a new chunk starting at current node */
870 tmp_chunk = new_aff_chunk(env);
871 waitq_put(tmp, tmp_chunk);
872 expand_chunk_from(env, node, visited, tmp_chunk, c, decider, col);
873 assert(ARR_LEN(tmp_chunk->n) > 0 && "No nodes added to chunk");
875 /* remember the local best */
876 aff_chunk_assure_weight(env, tmp_chunk);
877 if (check_for_best && (! best || best->weight < tmp_chunk->weight))
881 assert(best && "No chunk found?");
882 bitset_free(visited);
887 * Resets the temporary fixed color of all nodes within wait queue @p nodes.
888 * ATTENTION: the queue is empty after calling this function!
890 static inline void reject_coloring(struct list_head *nodes)
892 DB((dbg, LEVEL_4, "\treject coloring for"));
893 list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
894 DB((dbg, LEVEL_4, " %+F", n->irn));
895 assert(n->tmp_col >= 0);
897 list_del_init(&n->list);
899 DB((dbg, LEVEL_4, "\n"));
902 static inline void materialize_coloring(struct list_head *nodes)
904 list_for_each_entry_safe(co_mst_irn_t, n, temp, nodes, list) {
905 assert(n->tmp_col >= 0);
908 list_del_init(&n->list);
912 static inline void set_temp_color(co_mst_irn_t *node, int col, struct list_head *changed)
915 assert(!node->fixed);
916 assert(node->tmp_col < 0);
917 assert(node->list.next == &node->list && node->list.prev == &node->list);
918 assert(bitset_is_set(node->adm_colors, col));
920 list_add_tail(&node->list, changed);
924 static inline int is_loose(co_mst_irn_t *node)
926 return !node->fixed && node->tmp_col < 0;
930 * Determines the costs for each color if it would be assigned to node @p node.
932 static void determine_color_costs(co_mst_env_t *env, co_mst_irn_t *node, col_cost_t *costs)
934 int *neigh_cols = ALLOCAN(int, env->n_regs);
939 for (i = 0; i < env->n_regs; ++i) {
942 costs[i].cost = bitset_is_set(node->adm_colors, i) ? node->constr_factor : REAL(0.0);
945 for (i = 0; i < node->n_neighs; ++i) {
946 co_mst_irn_t *n = get_co_mst_irn(env, node->int_neighs[i]);
947 int col = get_mst_irn_col(n);
952 costs[col].cost = REAL(0.0);
956 coeff = REAL(1.0) / n_loose;
957 for (i = 0; i < env->n_regs; ++i)
958 costs[i].cost *= REAL(1.0) - coeff * neigh_cols[i];
962 /* need forward declaration due to recursive call */
963 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);
966 * Tries to change node to a color but @p explude_col.
967 * @return 1 if succeeded, 0 otherwise.
969 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)
971 int col = get_mst_irn_col(node);
974 /* neighbours has already a different color -> good, temporary fix it */
975 if (col != exclude_col) {
977 set_temp_color(node, col, changed);
981 /* The node has the color it should not have _and_ has not been visited yet. */
982 if (is_loose(node)) {
983 col_cost_t *costs = ALLOCAN(col_cost_t, env->n_regs);
985 /* Get the costs for giving the node a specific color. */
986 determine_color_costs(env, node, costs);
988 /* Since the node must not have the not_col, set the costs for that color to "infinity" */
989 costs[exclude_col].cost = REAL(0.0);
991 /* sort the colors according costs, cheapest first. */
992 qsort(costs, env->n_regs, sizeof(costs[0]), cmp_col_cost_gt);
994 /* Try recoloring the node using the color list. */
995 res = recolor_nodes(env, node, costs, changed, depth + 1, max_depth, trip);
1002 * Tries to bring node @p node to cheapest color and color all interfering neighbours with other colors.
1003 * ATTENTION: Expect @p costs already sorted by increasing costs.
1004 * @return 1 if coloring could be applied, 0 otherwise.
1006 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)
1009 struct list_head local_changed;
1012 if (depth > *max_depth)
1015 DBG((dbg, LEVEL_4, "\tRecoloring %+F with color-costs", node->irn));
1016 DBG_COL_COST(env, LEVEL_4, costs);
1017 DB((dbg, LEVEL_4, "\n"));
1019 if (depth >= recolor_limit) {
1020 DBG((dbg, LEVEL_4, "\tHit recolor limit\n"));
1024 for (i = 0; i < env->n_regs; ++i) {
1025 int tgt_col = costs[i].col;
1029 /* If the costs for that color (and all successive) are infinite, bail out we won't make it anyway. */
1030 if (costs[i].cost == REAL(0.0)) {
1031 DBG((dbg, LEVEL_4, "\tAll further colors forbidden\n"));
1035 /* Set the new color of the node and mark the node as temporarily fixed. */
1036 assert(node->tmp_col < 0 && "Node must not have been temporary fixed.");
1037 INIT_LIST_HEAD(&local_changed);
1038 set_temp_color(node, tgt_col, &local_changed);
1039 DBG((dbg, LEVEL_4, "\tTemporary setting %+F to color %d\n", node->irn, tgt_col));
1041 /* try to color all interfering neighbours with current color forbidden */
1042 for (j = 0; j < node->n_neighs; ++j) {
1046 neigh = node->int_neighs[j];
1048 if (arch_irn_is_ignore(neigh))
1051 nn = get_co_mst_irn(env, neigh);
1052 DB((dbg, LEVEL_4, "\tHandling neighbour %+F, at position %d (fixed: %d, tmp_col: %d, col: %d)\n",
1053 neigh, j, nn->fixed, nn->tmp_col, nn->col));
1056 Try to change the color of the neighbor and record all nodes which
1057 get changed in the tmp list. Add this list to the "changed" list for
1058 that color. If we did not succeed to change the color of the neighbor,
1059 we bail out and try the next color.
1061 if (get_mst_irn_col(nn) == tgt_col) {
1062 /* try to color neighbour with tgt_col forbidden */
1063 neigh_ok = change_node_color_excluded(env, nn, tgt_col, &local_changed, depth + 1, max_depth, trip);
1071 We managed to assign the target color to all neighbors, so from the perspective
1072 of the current node, every thing was ok and we can return safely.
1075 /* append the local_changed ones to global ones */
1076 list_splice(&local_changed, changed);
1080 /* coloring of neighbours failed, so we try next color */
1081 reject_coloring(&local_changed);
1085 DBG((dbg, LEVEL_4, "\tAll colors failed\n"));
1090 * Tries to bring node @p node and all its neighbours to color @p tgt_col.
1091 * @return 1 if color @p col could be applied, 0 otherwise
1093 static int change_node_color(co_mst_env_t *env, co_mst_irn_t *node, int tgt_col, struct list_head *changed)
1095 int col = get_mst_irn_col(node);
1097 /* if node already has the target color -> good, temporary fix it */
1098 if (col == tgt_col) {
1099 DBG((dbg, LEVEL_4, "\t\tCNC: %+F has already color %d, fix temporary\n", node->irn, tgt_col));
1101 set_temp_color(node, tgt_col, changed);
1106 Node has not yet a fixed color and target color is admissible
1107 -> try to recolor node and its affinity neighbours
1109 if (is_loose(node) && bitset_is_set(node->adm_colors, tgt_col)) {
1110 col_cost_t *costs = env->single_cols[tgt_col];
1111 int res, max_depth, trip;
1116 DBG((dbg, LEVEL_4, "\t\tCNC: Attempt to recolor %+F ===>>\n", node->irn));
1117 res = recolor_nodes(env, node, costs, changed, 0, &max_depth, &trip);
1118 DBG((dbg, LEVEL_4, "\t\tCNC: <<=== Recoloring of %+F %s\n", node->irn, res ? "succeeded" : "failed"));
1119 stat_ev_int("heur4_recolor_depth_max", max_depth);
1120 stat_ev_int("heur4_recolor_trip", trip);
1126 #ifdef DEBUG_libfirm
1127 if (firm_dbg_get_mask(dbg) & LEVEL_4) {
1128 if (!is_loose(node))
1129 DB((dbg, LEVEL_4, "\t\tCNC: %+F has already fixed color %d\n", node->irn, col));
1131 DB((dbg, LEVEL_4, "\t\tCNC: color %d not admissible for %+F (", tgt_col, node->irn));
1132 dbg_admissible_colors(env, node);
1133 DB((dbg, LEVEL_4, ")\n"));
1142 * Tries to color an affinity chunk (or at least a part of it).
1143 * Inserts uncolored parts of the chunk as a new chunk into the priority queue.
1145 static void color_aff_chunk(co_mst_env_t *env, aff_chunk_t *c)
1147 aff_chunk_t *best_chunk = NULL;
1148 int n_nodes = ARR_LEN(c->n);
1149 int best_color = -1;
1150 int n_int_chunks = 0;
1151 waitq *tmp_chunks = new_waitq();
1152 waitq *best_starts = NULL;
1153 col_cost_t *order = ALLOCANZ(col_cost_t, env->n_regs);
1160 struct list_head changed;
1162 DB((dbg, LEVEL_2, "fragmentizing chunk #%u", c->id));
1163 DBG_AFF_CHUNK(env, LEVEL_2, c);
1164 DB((dbg, LEVEL_2, "\n"));
1166 stat_ev_ctx_push_fmt("heur4_color_chunk", "%u", c->id);
1168 ++env->chunk_visited;
1170 /* compute color preference */
1171 for (pos = 0, len = ARR_LEN(c->interfere); pos < len; ++pos) {
1172 const ir_node *n = c->interfere[pos];
1173 co_mst_irn_t *node = get_co_mst_irn(env, n);
1174 aff_chunk_t *chunk = node->chunk;
1176 if (is_loose(node) && chunk && chunk->visited < env->chunk_visited) {
1177 assert(!chunk->deleted);
1178 chunk->visited = env->chunk_visited;
1181 aff_chunk_assure_weight(env, chunk);
1182 for (i = 0; i < env->n_regs; ++i)
1183 order[i].cost += chunk->color_affinity[i].cost;
1187 for (i = 0; i < env->n_regs; ++i) {
1188 real_t dislike = n_int_chunks > 0 ? REAL(1.0) - order[i].cost / n_int_chunks : REAL(0.0);
1190 order[i].cost = (REAL(1.0) - dislike_influence) * c->color_affinity[i].cost + dislike_influence * dislike;
1193 qsort(order, env->n_regs, sizeof(order[0]), cmp_col_cost_gt);
1195 DBG_COL_COST(env, LEVEL_2, order);
1196 DB((dbg, LEVEL_2, "\n"));
1198 /* check which color is the "best" for the given chunk.
1199 * if we found a color which was ok for all nodes, we take it
1200 * and do not look further. (see did_all flag usage below.)
1201 * If we have many colors which fit all nodes it is hard to decide
1202 * which one to take anyway.
1203 * TODO Sebastian: Perhaps we should at all nodes and figure out
1204 * a suitable color using costs as done above (determine_color_costs).
1206 for (i = 0; i < env->n_regs; ++i) {
1207 int col = order[i].col;
1209 aff_chunk_t *local_best;
1212 /* skip ignore colors */
1213 if (!bitset_is_set(env->allocatable_regs, col))
1216 DB((dbg, LEVEL_2, "\ttrying color %d\n", col));
1219 good_starts = new_waitq();
1221 /* try to bring all nodes of given chunk to the current color. */
1222 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1223 const ir_node *irn = c->n[idx];
1224 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1227 assert(! node->fixed && "Node must not have a fixed color.");
1228 DB((dbg, LEVEL_4, "\t\tBringing %+F from color %d to color %d ...\n", irn, node->col, col));
1231 The order of the colored nodes is important, so we record the successfully
1232 colored ones in the order they appeared.
1234 INIT_LIST_HEAD(&changed);
1236 good = change_node_color(env, node, col, &changed);
1237 stat_ev_tim_pop("heur4_recolor");
1239 waitq_put(good_starts, node);
1240 materialize_coloring(&changed);
1245 reject_coloring(&changed);
1247 n_succeeded += good;
1248 DB((dbg, LEVEL_4, "\t\t... %+F attempt from %d to %d %s\n", irn, node->col, col, good ? "succeeded" : "failed"));
1251 /* unfix all nodes */
1252 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1253 co_mst_irn_t *node = get_co_mst_irn(env, c->n[idx]);
1257 /* try next color when failed */
1258 if (n_succeeded == 0) {
1259 del_waitq(good_starts);
1263 /* fragment the chunk according to the coloring */
1264 local_best = fragment_chunk(env, col, c, tmp_chunks);
1266 /* search the best of the good list
1267 and make it the new best if it is better than the current */
1269 aff_chunk_assure_weight(env, local_best);
1271 DB((dbg, LEVEL_3, "\t\tlocal best chunk (id %u) for color %d: ", local_best->id, col));
1272 DBG_AFF_CHUNK(env, LEVEL_3, local_best);
1274 if (! best_chunk || best_chunk->weight < local_best->weight) {
1275 best_chunk = local_best;
1278 del_waitq(best_starts);
1279 best_starts = good_starts;
1280 DB((dbg, LEVEL_3, "\n\t\t... setting global best chunk (id %u), color %d\n", best_chunk->id, best_color));
1282 DB((dbg, LEVEL_3, "\n\t\t... omitting, global best is better\n"));
1283 del_waitq(good_starts);
1287 del_waitq(good_starts);
1290 /* if all nodes were recolored, bail out */
1291 if (n_succeeded == n_nodes)
1295 stat_ev_int("heur4_colors_tried", i);
1297 /* free all intermediate created chunks except best one */
1298 while (! waitq_empty(tmp_chunks)) {
1299 aff_chunk_t *tmp = (aff_chunk_t*)waitq_get(tmp_chunks);
1300 if (tmp != best_chunk)
1301 delete_aff_chunk(tmp);
1303 del_waitq(tmp_chunks);
1305 /* return if coloring failed */
1308 del_waitq(best_starts);
1312 DB((dbg, LEVEL_2, "\tbest chunk #%u ", best_chunk->id));
1313 DBG_AFF_CHUNK(env, LEVEL_2, best_chunk);
1314 DB((dbg, LEVEL_2, "using color %d\n", best_color));
1316 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1317 const ir_node *irn = best_chunk->n[idx];
1318 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1321 /* bring the node to the color. */
1322 DB((dbg, LEVEL_4, "\tManifesting color %d for %+F, chunk #%u\n", best_color, node->irn, best_chunk->id));
1323 INIT_LIST_HEAD(&changed);
1325 res = change_node_color(env, node, best_color, &changed);
1326 stat_ev_tim_pop("heur4_recolor");
1328 materialize_coloring(&changed);
1331 assert(list_empty(&changed));
1334 /* remove the nodes in best chunk from original chunk */
1335 len = ARR_LEN(best_chunk->n);
1336 for (idx = 0; idx < len; ++idx) {
1337 const ir_node *irn = best_chunk->n[idx];
1338 int pos = nodes_bsearch(c->n, irn);
1343 len = ARR_LEN(c->n);
1344 for (idx = nidx = 0; idx < len; ++idx) {
1345 const ir_node *irn = c->n[idx];
1351 ARR_SHRINKLEN(c->n, nidx);
1354 /* we have to get the nodes back into the original chunk because they are scattered over temporary chunks */
1355 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1356 const ir_node *n = c->n[idx];
1357 co_mst_irn_t *nn = get_co_mst_irn(env, n);
1361 /* fragment the remaining chunk */
1362 visited = bitset_malloc(get_irg_last_idx(env->co->irg));
1363 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx)
1364 bitset_set(visited, get_irn_idx(best_chunk->n[idx]));
1366 for (idx = 0, len = ARR_LEN(c->n); idx < len; ++idx) {
1367 const ir_node *irn = c->n[idx];
1368 if (! bitset_is_set(visited, get_irn_idx(irn))) {
1369 aff_chunk_t *new_chunk = new_aff_chunk(env);
1370 co_mst_irn_t *node = get_co_mst_irn(env, irn);
1372 expand_chunk_from(env, node, visited, new_chunk, c, decider_always_yes, 0);
1373 aff_chunk_assure_weight(env, new_chunk);
1374 pqueue_put(env->chunks, new_chunk, new_chunk->weight);
1378 for (idx = 0, len = ARR_LEN(best_chunk->n); idx < len; ++idx) {
1379 const ir_node *n = best_chunk->n[idx];
1380 co_mst_irn_t *nn = get_co_mst_irn(env, n);
1384 /* clear obsolete chunks and free some memory */
1385 delete_aff_chunk(best_chunk);
1386 bitset_free(visited);
1388 del_waitq(best_starts);
1390 stat_ev_ctx_pop("heur4_color_chunk");
1394 * Main driver for mst safe coalescing algorithm.
1396 static int co_solve_heuristic_mst(copy_opt_t *co)
1403 co_mst_env_t mst_env;
1404 ir_nodemap_init(&mst_env.map, co->irg);
1405 obstack_init(&mst_env.obst);
1407 unsigned const n_regs = co->cls->n_regs;
1409 mst_env.n_regs = n_regs;
1410 mst_env.chunks = new_pqueue();
1412 mst_env.allocatable_regs = co->cenv->allocatable_regs;
1413 mst_env.ifg = co->cenv->ifg;
1414 INIT_LIST_HEAD(&mst_env.chunklist);
1415 mst_env.chunk_visited = 0;
1416 mst_env.single_cols = OALLOCN(&mst_env.obst, col_cost_t*, n_regs);
1418 for (unsigned i = 0; i < n_regs; ++i) {
1419 col_cost_t *vec = OALLOCN(&mst_env.obst, col_cost_t, n_regs);
1421 mst_env.single_cols[i] = vec;
1422 for (unsigned j = 0; j < n_regs; ++j) {
1424 vec[j].cost = REAL(0.0);
1428 vec[0].cost = REAL(1.0);
1431 DBG((dbg, LEVEL_1, "==== Coloring %+F, class %s ====\n", co->irg, co->cls->name));
1433 /* build affinity chunks */
1435 build_affinity_chunks(&mst_env);
1436 stat_ev_tim_pop("heur4_initial_chunk");
1438 /* color chunks as long as there are some */
1439 while (! pqueue_empty(mst_env.chunks)) {
1440 aff_chunk_t *chunk = (aff_chunk_t*)pqueue_pop_front(mst_env.chunks);
1442 color_aff_chunk(&mst_env, chunk);
1443 DB((dbg, LEVEL_4, "<<<====== Coloring chunk (%u) done\n", chunk->id));
1444 delete_aff_chunk(chunk);
1447 /* apply coloring */
1448 for (size_t pn = 0; pn < ARR_LEN(mst_env.map.data); ++pn) {
1449 co_mst_irn_t *mirn = (co_mst_irn_t*)mst_env.map.data[pn];
1450 const arch_register_t *reg;
1453 ir_node *const irn = get_idx_irn(co->irg, pn);
1454 if (arch_irn_is_ignore(irn))
1457 /* skip nodes where color hasn't changed */
1458 if (mirn->init_col == mirn->col)
1461 reg = arch_register_for_index(co->cls, mirn->col);
1462 arch_set_irn_register(irn, reg);
1463 DB((dbg, LEVEL_1, "%+F set color from %d to %d\n", irn, mirn->init_col, mirn->col));
1466 /* free allocated memory */
1467 del_pqueue(mst_env.chunks);
1468 obstack_free(&mst_env.obst, NULL);
1469 ir_nodemap_destroy(&mst_env.map);
1471 stat_ev_tim_pop("heur4_total");
1476 static const lc_opt_table_entry_t options[] = {
1477 LC_OPT_ENT_INT ("limit", "limit recoloring", &recolor_limit),
1478 LC_OPT_ENT_DBL ("di", "dislike influence", &dislike_influence),
1482 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_copyheur4)
1483 void be_init_copyheur4(void)
1485 lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1486 lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
1487 lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
1488 lc_opt_entry_t *co_grp = lc_opt_get_grp(chordal_grp, "co");
1489 lc_opt_entry_t *heur4_grp = lc_opt_get_grp(co_grp, "heur4");
1491 static co_algo_info copyheur = {
1492 co_solve_heuristic_mst, 0
1495 lc_opt_add_table(heur4_grp, options);
1496 be_register_copyopt("heur4", ©heur);
1498 FIRM_DBG_REGISTER(dbg, "firm.be.co.heur4");