2 * Author: Daniel Grund, Matthias Braun
4 * Copyright: (c) Universitaet Karlsruhe
5 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
23 #include "irprintf_t.h"
29 #include "iredges_t.h"
35 #include "bespillbelady.h"
37 #include "besched_t.h"
41 #include "bechordal_t.h"
42 #include "bespilloptions.h"
43 #include "beloopana.h"
52 #define DBG_WORKSET 128
53 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
56 * An association between a node and a point in time.
58 typedef struct _loc_t {
59 ir_node *irn; /**< A node. */
60 unsigned time; /**< A use time (see beuses.h). */
63 typedef struct _workset_t {
64 int len; /**< current length */
65 loc_t vals[0]; /**< inlined array of the values/distances in this working set */
68 typedef struct _belady_env_t {
70 const arch_env_t *arch;
71 const arch_register_class_t *cls;
73 be_loopana_t *loop_ana;
74 int n_regs; /** number of regs in this reg-class */
76 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
77 be_uses_t *uses; /**< env for the next-use magic */
78 ir_node *instr; /**< current instruction */
79 unsigned instr_nr; /**< current instruction number (relative to block start) */
82 spill_env_t *senv; /**< see bespill.h */
85 static int loc_compare(const void *a, const void *b)
89 return p->time - q->time;
92 static INLINE void workset_print(const workset_t *w)
96 for(i = 0; i < w->len; ++i) {
97 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
102 * Alloc a new workset on obstack @p ob with maximum size @p max
104 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
106 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
107 res = obstack_alloc(ob, size);
108 memset(res, 0, size);
113 * Alloc a new instance on obstack and make it equal to @param ws
115 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
117 size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
118 res = obstack_alloc(ob, size);
119 memcpy(res, ws, size);
124 * Do NOT alloc anything. Make @param tgt equal to @param src.
125 * returns @param tgt for convenience
127 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
128 size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
129 memcpy(tgt, src, size);
134 * Overwrites the current content array of @param ws with the
135 * @param count locations given at memory @param locs.
136 * Set the length of @param ws to count.
138 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
139 workset->len = count;
140 memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
144 * Inserts the value @p val into the workset, iff it is not
145 * already contained. The workset must not be full.
147 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
149 /* check for current regclass */
150 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
151 DBG((dbg, DBG_WORKSET, "Skipped %+F\n", val));
155 /* check if val is already contained */
156 for(i=0; i<ws->len; ++i)
157 if (ws->vals[i].irn == val)
161 assert(ws->len < env->n_regs && "Workset already full!");
162 ws->vals[ws->len++].irn = val;
166 * Removes all entries from this workset
168 static INLINE void workset_clear(workset_t *ws) {
173 * Removes the value @p val from the workset if present.
175 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
177 for(i=0; i<ws->len; ++i) {
178 if (ws->vals[i].irn == val) {
179 ws->vals[i] = ws->vals[--ws->len];
185 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
187 for(i=0; i<ws->len; ++i) {
188 if (ws->vals[i].irn == val)
196 * Iterates over all values in the working set.
197 * @p ws The workset to iterate
198 * @p v A variable to put the current value in
199 * @p i An integer for internal use
201 #define workset_foreach(ws, v, i) for(i=0; \
202 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
205 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
206 #define workset_get_time(ws, i) (ws)->vals[i].time
207 #define workset_set_length(ws, length) (ws)->len = length
208 #define workset_get_length(ws) ((ws)->len)
209 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
210 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
212 typedef struct _block_info_t {
213 workset_t *ws_start, *ws_end;
218 static INLINE void *new_block_info(struct obstack *ob) {
219 block_info_t *res = obstack_alloc(ob, sizeof(*res));
220 res->ws_start = NULL;
227 #define get_block_info(block) ((block_info_t *)get_irn_link(block))
228 #define set_block_info(block, info) set_irn_link(block, info)
231 * @return The distance to the next use or 0 if irn has dont_spill flag set
233 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
236 int flags = arch_irn_get_flags(env->arch, def);
238 assert(! (flags & arch_irn_flags_ignore));
240 use = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
241 if(USES_IS_INFINITE(use.time))
242 return USES_INFINITY;
244 /* We have to keep nonspillable nodes in the workingset */
245 if(flags & arch_irn_flags_dont_spill)
252 * Performs the actions necessary to grant the request that:
253 * - new_vals can be held in registers
254 * - as few as possible other values are disposed
255 * - the worst values get disposed
257 * @p is_usage indicates that the values in new_vals are used (not defined)
258 * In this case reloads must be performed
260 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
262 int i, len, max_allowed, demand, iter;
264 workset_t *ws = env->ws;
265 ir_node **to_insert = alloca(env->n_regs * sizeof(*to_insert));
268 1. Identify the number of needed slots and the values to reload
271 workset_foreach(new_vals, val, iter) {
272 /* mark value as used */
274 pset_insert_ptr(env->used, val);
276 if (! workset_contains(ws, val)) {
277 DBG((dbg, DBG_DECIDE, " insert %+F\n", val));
278 to_insert[demand++] = val;
280 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
281 be_add_reload(env->senv, val, env->instr, env->cls, 1);
285 assert(is_usage || "Defined value already in workset?!?");
286 DBG((dbg, DBG_DECIDE, " skip %+F\n", val));
289 DBG((dbg, DBG_DECIDE, " demand = %d\n", demand));
292 2. Make room for at least 'demand' slots
294 len = workset_get_length(ws);
295 max_allowed = env->n_regs - demand;
297 DBG((dbg, DBG_DECIDE, " disposing %d values\n", ws->len - max_allowed));
299 /* Only make more free room if we do not have enough */
300 if (len > max_allowed) {
301 /* get current next-use distance */
302 for (i = 0; i < ws->len; ++i) {
303 unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
304 workset_set_time(ws, i, dist);
307 /* sort entries by increasing nextuse-distance*/
311 Logic for not needed live-ins: If a value is disposed
312 before its first usage, remove it from start workset
313 We don't do this for phis though
315 for (i = max_allowed; i < ws->len; ++i) {
316 ir_node *irn = ws->vals[i].irn;
318 DBG((dbg, DBG_DECIDE, " disposing %+F (%u)\n", irn, workset_get_time(ws, i)));
323 if (! pset_find_ptr(env->used, irn)) {
324 ir_node *curr_bb = get_nodes_block(env->instr);
325 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
326 workset_remove(ws_start, irn);
328 DBG((dbg, DBG_DECIDE, " (and removing %+F from start workset)\n", irn));
332 /* kill the last 'demand' entries in the array */
333 workset_set_length(ws, max_allowed);
337 3. Insert the new values into the workset
339 for (i = 0; i < demand; ++i)
340 workset_insert(env, env->ws, to_insert[i]);
343 static void belady(ir_node *block, void *env);
345 /** Decides whether a specific node should be in the start workset or not
347 * @param env belady environment
349 * @param node the node to test
350 * @param block the block of the node
351 * @param loop the loop of the node
353 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
354 ir_node *node, ir_node *block,
357 be_next_use_t next_use;
359 loc.time = USES_INFINITY;
362 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
363 loc.time = USES_INFINITY;
367 /* We have to keep nonspillable nodes in the workingset */
368 if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
370 DBG((dbg, DBG_START, " %+F taken (dontspill node)\n", node, loc.time));
374 next_use = be_get_next_use(env->uses, first, 0, node, 0);
375 if(USES_IS_INFINITE(next_use.time)) {
376 // the nodes marked as live in shouldn't be dead, so it must be a phi
377 assert(is_Phi(node));
378 loc.time = USES_INFINITY;
379 DBG((dbg, DBG_START, " %+F not taken (dead)\n", node));
383 loc.time = next_use.time;
385 if(next_use.outermost_loop >= get_loop_depth(loop)) {
386 DBG((dbg, DBG_START, " %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
388 loc.time = USES_PENDING;
389 DBG((dbg, DBG_START, " %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
395 * Computes set of live-ins for each block with multiple predecessors
396 * and notifies spill algorithm which phis need to be spilled
398 static void compute_live_ins(ir_node *block, void *data) {
399 belady_env_t *env = data;
400 ir_loop *loop = get_irn_loop(block);
401 const be_lv_t *lv = env->lv;
402 block_info_t *block_info;
403 ir_node *first, *irn;
404 loc_t loc, *starters, *delayed;
405 int i, len, ws_count;
406 int free_slots, free_pressure_slots;
409 if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
412 block_info = new_block_info(&env->ob);
413 set_block_info(block, block_info);
415 /* Collect all values living at start of block */
416 starters = NEW_ARR_F(loc_t, 0);
417 delayed = NEW_ARR_F(loc_t, 0);
419 DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
420 first = sched_first(block);
422 /* check all Phis first */
423 sched_foreach(block, irn) {
427 loc = to_take_or_not_to_take(env, first, irn, block, loop);
429 if (! USES_IS_INFINITE(loc.time)) {
430 if (USES_IS_PENDING(loc.time))
431 ARR_APP1(loc_t, delayed, loc);
433 ARR_APP1(loc_t, starters, loc);
435 be_spill_phi(env->senv, irn);
439 /* check all Live-Ins */
440 be_lv_foreach(lv, block, be_lv_state_in, i) {
441 ir_node *node = be_lv_get_irn(lv, block, i);
443 loc = to_take_or_not_to_take(env, first, node, block, loop);
445 if (! USES_IS_INFINITE(loc.time)) {
446 if (USES_IS_PENDING(loc.time))
447 ARR_APP1(loc_t, delayed, loc);
449 ARR_APP1(loc_t, starters, loc);
453 pressure = be_get_loop_pressure(env->loop_ana, env->cls, loop);
454 assert(ARR_LEN(delayed) <= pressure);
455 free_slots = env->n_regs - ARR_LEN(starters);
456 free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
457 free_slots = MIN(free_slots, free_pressure_slots);
458 /* append nodes delayed due to loop structure until start set is full */
459 for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
460 DBG((dbg, DBG_START, " delayed %+F taken\n", delayed[i].irn));
461 ARR_APP1(loc_t, starters, delayed[i]);
465 /* Sort start values by first use */
466 qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
468 /* Copy the best ones from starters to start workset */
469 ws_count = MIN(ARR_LEN(starters), env->n_regs);
470 block_info->ws_start = new_workset(env, &env->ob);
471 workset_bulk_fill(block_info->ws_start, ws_count, starters);
473 /* The phis of this block which are not in the start set have to be spilled later. */
474 len = ARR_LEN(starters);
475 for (i = ws_count; i < len; ++i) {
476 irn = starters[i].irn;
477 if (! is_Phi(irn) || get_nodes_block(irn) != block)
480 be_spill_phi(env->senv, irn);
487 * Collects all values live-in at block @p block and all phi results in this block.
488 * Then it adds the best values (at most n_regs) to the blocks start_workset.
489 * The phis among the remaining values get spilled: Introduce psudo-copies of
490 * their args to break interference and make it possible to spill them to the
493 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
495 block_info_t *res, *pred_info;
497 /* Have we seen this block before? */
498 res = get_block_info(block);
502 /* Create the block info for this block. */
503 res = new_block_info(&env->ob);
504 set_block_info(block, res);
506 /* Use endset of predecessor block as startset */
507 assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
508 pred_block = get_Block_cfgpred_block(block, 0);
509 pred_info = get_block_info(pred_block);
511 /* if pred block has not been processed yet, do it now */
512 if (pred_info == NULL || pred_info->processed == 0) {
513 belady(pred_block, env);
514 pred_info = get_block_info(pred_block);
517 /* now we have an end_set of pred */
518 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
519 res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
526 * For the given block @p block, decide for each values
527 * whether it is used from a register or is reloaded
530 static void belady(ir_node *block, void *data) {
531 belady_env_t *env = data;
535 block_info_t *block_info;
537 /* make sure we have blockinfo (with startset) */
538 block_info = get_block_info(block);
539 if (block_info == NULL)
540 block_info = compute_block_start_info(env, block);
542 /* Don't do a block twice */
543 if(block_info->processed)
546 /* get the starting workset for this block */
547 DBG((dbg, DBG_DECIDE, "\n"));
548 DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
550 workset_copy(env, env->ws, block_info->ws_start);
551 DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
552 workset_foreach(env->ws, irn, iter)
553 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
555 /* process the block from start to end */
556 DBG((dbg, DBG_WSETS, "Processing...\n"));
557 env->used = pset_new_ptr_default();
559 new_vals = new_workset(env, &env->ob);
560 sched_foreach(block, irn) {
562 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
564 /* projs are handled with the tuple value.
565 * Phis are no real instr (see insert_starters())
566 * instr_nr does not increase */
567 if (is_Proj(irn) || is_Phi(irn)) {
568 DBG((dbg, DBG_DECIDE, " ...%+F skipped\n", irn));
571 DBG((dbg, DBG_DECIDE, " ...%+F\n", irn));
573 /* set instruction in the workset */
576 /* allocate all values _used_ by this instruction */
577 workset_clear(new_vals);
578 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
579 workset_insert(env, new_vals, get_irn_n(irn, i));
581 displace(env, new_vals, 1);
583 /* allocate all values _defined_ by this instruction */
584 workset_clear(new_vals);
585 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
587 for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
588 workset_insert(env, new_vals, proj);
590 workset_insert(env, new_vals, irn);
592 displace(env, new_vals, 0);
598 /* Remember end-workset for this block */
599 block_info->ws_end = workset_clone(env, &env->ob, env->ws);
600 block_info->processed = 1;
601 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
602 workset_foreach(block_info->ws_end, irn, iter)
603 DBG((dbg, DBG_WSETS, " %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
607 * 'decide' is block-local and makes assumptions
608 * about the set of live-ins. Thus we must adapt the
609 * live-outs to the live-ins at each block-border.
611 static void fix_block_borders(ir_node *block, void *data) {
612 belady_env_t *env = data;
614 ir_graph *irg = get_irn_irg(block);
615 ir_node *startblock = get_irg_start_block(irg);
616 int i, max, iter, iter2;
618 if(block == startblock)
621 DBG((dbg, DBG_FIX, "\n"));
622 DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
624 wsb = get_block_info(block)->ws_start;
626 /* process all pred blocks */
627 for (i=0, max=get_irn_arity(block); i<max; ++i) {
628 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(block, i);
629 workset_t *wsp = get_block_info(pred)->ws_end;
631 DBG((dbg, DBG_FIX, " Pred %+F\n", pred));
633 workset_foreach(wsb, irnb, iter) {
634 /* if irnb is a phi of the current block we reload
635 * the corresponding argument, else irnb itself */
636 if(is_Phi(irnb) && block == get_nodes_block(irnb)) {
637 irnb = get_irn_n(irnb, i);
639 // we might have unknowns as argument for the phi
640 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irnb))
644 /* Unknowns are available everywhere */
645 if(get_irn_opcode(irnb) == iro_Unknown)
648 /* check if irnb is in a register at end of pred */
649 workset_foreach(wsp, irnp, iter2) {
654 /* irnb is not in memory at the end of pred, so we have to reload it */
655 DBG((dbg, DBG_FIX, " reload %+F\n", irnb));
656 DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", irnb, block, i));
657 be_add_reload_on_edge(env->senv, irnb, block, i, env->cls, 1);
660 /*epsilon statement :)*/;
665 void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
666 be_spill_belady_spill_env(birg, cls, NULL);
669 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
671 ir_graph *irg = be_get_birg_irg(birg);
673 be_invalidate_liveness(birg);
674 be_assure_liveness(birg);
675 /* construct control flow loop tree */
676 if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
677 construct_cf_backedges(irg);
680 /* init belady env */
681 obstack_init(&env.ob);
682 env.arch = birg->main_env->arch_env;
684 env.lv = be_get_birg_liveness(birg);
685 env.n_regs = env.cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
686 env.ws = new_workset(&env, &env.ob);
687 env.uses = be_begin_uses(irg, env.lv);
688 env.loop_ana = be_new_loop_pressure(birg);
689 if(spill_env == NULL) {
690 env.senv = be_new_spill_env(birg);
692 env.senv = spill_env;
694 DEBUG_ONLY(be_set_spill_env_dbg_module(env.senv, dbg);)
697 /* Decide which phi nodes will be spilled and place copies for them into the graph */
698 irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
699 /* Fix high register pressure with belady algorithm */
700 irg_block_walk_graph(irg, NULL, belady, &env);
701 /* belady was block-local, fix the global flow by adding reloads on the edges */
702 irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
703 /* Insert spill/reload nodes into the graph and fix usages */
704 be_insert_spills_reloads(env.senv);
707 if(spill_env == NULL)
708 be_delete_spill_env(env.senv);
709 be_end_uses(env.uses);
710 be_free_loop_pressure(env.loop_ana);
711 obstack_free(&env.ob, NULL);
714 void be_init_spillbelady(void)
716 static be_spiller_t belady_spiller = {
720 be_register_spiller("belady", &belady_spiller);
721 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
724 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);