4 * Copyright: (c) Universitaet Karlsruhe
5 * Licence: This file protected by GPL - GNU GENERAL PUBLIC LICENSE.
23 #include "irprintf_t.h"
28 #include "iredges_t.h"
34 #include "bespillbelady.h"
36 #include "besched_t.h"
40 #include "bechordal_t.h"
49 #define DBG_WORKSET 128
50 #define DEBUG_LVL 0 //(DBG_START | DBG_DECIDE | DBG_WSETS | DBG_FIX | DBG_SPILL)
51 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
53 typedef struct _workset_t workset_t;
55 typedef struct _belady_env_t {
57 const arch_env_t *arch;
58 const arch_register_class_t *cls;
59 int n_regs; /** number of regs in this reg-class */
61 workset_t *ws; /**< the main workset used while processing a block. ob-allocated */
62 be_uses_t *uses; /**< env for the next-use magic */
63 ir_node *instr; /**< current instruction */
64 unsigned instr_nr; /**< current instruction number (relative to block start) */
65 pset *used; /**< holds the values used (so far) in the current BB */
66 ir_node **copies; /**< holds all copies placed due to phi-spilling */
68 spill_env_t *senv; /**< see bespill.h */
73 int len; /**< current length */
74 loc_t vals[1]; /**< inlined array of the values/distances in this working set */
77 void workset_print(const workset_t *w)
81 for(i = 0; i < w->len; ++i) {
82 ir_printf("%+F %d\n", w->vals[i].irn, w->vals[i].time);
87 * Alloc a new workset on obstack @p ob with maximum size @p max
89 static INLINE workset_t *new_workset(struct obstack *ob, belady_env_t *bel) {
91 size_t size = sizeof(*res) + (bel->n_regs-1)*sizeof(res->vals[0]);
92 res = obstack_alloc(ob, size);
99 * Alloc a new instance on obstack and make it equal to @param ws
101 static INLINE workset_t *workset_clone(struct obstack *ob, workset_t *ws) {
103 size_t size = sizeof(*res) + (ws->bel->n_regs-1)*sizeof(res->vals[0]);
104 res = obstack_alloc(ob, size);
105 memcpy(res, ws, size);
110 * Do NOT alloc anything. Make @param tgt equal to @param src.
111 * returns @param tgt for convinience
113 static INLINE workset_t *workset_copy(workset_t *tgt, workset_t *src) {
114 size_t size = sizeof(*src) + (src->bel->n_regs-1)*sizeof(src->vals[0]);
115 memcpy(tgt, src, size);
120 * Overwrites the current content array of @param ws with the
121 * @param count locations given at memory @param locs.
122 * Set the length of @param ws to count.
124 #define workset_bulk_fill(ws, count, locs) memcpy(&(ws)->vals[0], locs, ((ws)->len=count)*sizeof(locs[0]));
128 * Inserts the value @p val into the workset, iff it is not
129 * already contained. The workset must not be full.
131 static INLINE void workset_insert(workset_t *ws, ir_node *val) {
133 /* check for current regclass */
134 if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
135 DBG((dbg, DBG_WORKSET, "Dropped %+F\n", val));
139 /* check if val is already contained */
140 for(i=0; i<ws->len; ++i)
141 if (ws->vals[i].irn == val)
145 assert(ws->len < ws->bel->n_regs && "Workset already full!");
146 ws->vals[ws->len++].irn = val;
150 * Inserts all values in array @p vals of length @p cnt
151 * into the workset. There must be enough space for the
154 static INLINE void workset_bulk_insert(workset_t *ws, int cnt, ir_node **vals) {
157 for(o=0; o<cnt; ++o) {
158 ir_node *val = vals[o];
159 DBG((dbg, DBG_TRACE, "Bulk insert %+F\n", val));
160 /* check for current regclass */
161 if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
162 DBG((dbg, DBG_TRACE, "Wrong reg class\n"));
166 /* check if val is already contained */
167 for(i=0; i<ws->len; ++i)
168 if (ws->vals[i].irn == val) {
169 DBG((dbg, DBG_TRACE, "Already contained\n"));
174 assert(ws->len < ws->bel->n_regs && "Workset does not have enough room!");
175 ws->vals[ws->len++].irn = val;
176 DBG((dbg, DBG_TRACE, "Inserted\n"));
179 /*epsilon statement :)*/;
184 * Removes all entries from this workset
186 #define workset_clear(ws) (ws)->len = 0;
189 * Removes the value @p val from the workset if present.
191 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
193 for(i=0; i<ws->len; ++i)
194 if (ws->vals[i].irn == val) {
195 ws->vals[i] = ws->vals[--ws->len];
200 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
202 for(i=0; i<ws->len; ++i)
203 if (ws->vals[i].irn == val)
209 * Iterates over all values in the working set.
210 * @p ws The workset to iterate
211 * @p v A variable to put the current value in
212 * @p i An integer for internal use
214 #define workset_foreach(ws, v, i) for(i=0; \
215 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
218 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
219 #define workset_set_length(ws, length) (ws)->len = length
220 #define workset_get_length(ws) ((ws)->len)
221 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
222 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
224 typedef struct _block_info_t {
225 workset_t *ws_start, *ws_end;
229 static INLINE void *new_block_info(struct obstack *ob) {
230 block_info_t *res = obstack_alloc(ob, sizeof(*res));
231 res->ws_start = NULL;
237 #define get_block_info(blk) ((block_info_t *)get_irn_link(blk))
238 #define set_block_info(blk, info) set_irn_link(blk, info)
241 * @return The distance to the next use
242 * Or 0 if irn is an ignore node
244 static INLINE unsigned get_distance(belady_env_t *bel, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
246 arch_irn_flags_t fl = arch_irn_get_flags(bel->arch, def);
247 unsigned dist = be_get_next_use(bel->uses, from, from_step, def, skip_from_uses);
249 if(!USES_IS_INIFINITE(dist) && (fl & (arch_irn_flags_ignore | arch_irn_flags_dont_spill)) != 0)
256 * Performs the actions necessary to grant the request that:
257 * - new_vals can be held in registers
258 * - as few as possible other values are disposed
259 * - the worst values get disposed
261 * @p is_usage indicates that the values in new_vals are used (not defined)
262 * In this case reloads must be performed
264 static void displace(belady_env_t *bel, workset_t *new_vals, int is_usage) {
266 int i, len, max_allowed, demand, iter;
267 workset_t *ws = bel->ws;
268 ir_node **to_insert = alloca(bel->n_regs * sizeof(*to_insert));
271 * 1. Identify the number of needed slots and the values to reload
274 workset_foreach(new_vals, val, iter) {
275 /* mark value as used */
277 pset_insert_ptr(bel->used, val);
279 if (!workset_contains(ws, val)) {
280 DBG((dbg, DBG_DECIDE, " insert %+F\n", val));
281 to_insert[demand++] = val;
283 be_add_reload(bel->senv, val, bel->instr);
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 = bel->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 workset_set_time(ws, i, get_distance(bel, bel->instr, bel->instr_nr, workset_get_val(ws, i), !is_usage));
305 /* sort entries by increasing nextuse-distance*/
308 /* Logic for not needed live-ins: If a value is disposed
309 before its first usage, remove it from start workset */
310 for (i=max_allowed; i<ws->len; ++i) {
311 ir_node *irn = ws->vals[i].irn;
313 if (!pset_find_ptr(bel->used, irn)) {
314 ir_node *curr_bb = get_nodes_block(bel->instr);
315 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
316 workset_remove(ws_start, irn);
318 DBG((dbg, DBG_DECIDE, " dispose %+F dumb\n", irn));
320 DBG((dbg, DBG_DECIDE, " dispose %+F\n", irn));
324 /* kill the last 'demand' entries in the array */
325 workset_set_length(ws, max_allowed);
329 * 3. Insert the new values into the workset
331 workset_bulk_insert(bel->ws, demand, to_insert);
334 static void belady(ir_node *blk, void *env);
337 * Inserts a copy (needed for spilled phi handling) of a value at the earliest
338 * possible location in a block. That is after the last use/def of the value or at
339 * the beginning of the block if there is no use/def.
341 static ir_node *insert_copy(belady_env_t *env, ir_node *block, ir_node *value) {
343 ir_graph *irg = get_irn_irg(block);
344 ir_node *copy = be_new_Copy(env->cls, irg, block, value);
346 ARR_APP1(ir_node*, env->copies, copy);
348 // walk schedule backwards until we find a use/def, or until we have reached the first phi
349 // TODO we could also do this by iterating over all uses and checking the
350 // sched_get_time_step value. Need benchmarks to decide this...
351 sched_foreach_reverse(block, node) {
355 sched_add_after(node, copy);
359 sched_add_after(node, copy);
362 for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
363 ir_node *arg = get_irn_n(node, i);
365 sched_add_after(node, copy);
370 // we didn't find a use or a phi yet, so place the copy at the beginning of the block
371 sched_add_before(sched_first(block), copy);
379 * Collects all values live-in at block @p blk and all phi results in this block.
380 * Then it adds the best values (at most n_regs) to the blocks start_workset.
381 * The phis among the remaining values get spilled: Introduce psudo-copies of
382 * their args to break interference and make it possible to spill them to the
385 static block_info_t *compute_block_start_info(ir_node *blk, void *data) {
386 belady_env_t *env = data;
387 ir_node *irn, *first;
389 int i, count, ws_count;
390 loc_t loc, *starters;
391 ir_graph *irg = get_irn_irg(blk);
393 block_info_t *res = get_block_info(blk);
395 /* Have we seen this block before? */
399 /* Create the block info for this block. */
400 res = new_block_info(&env->ob);
401 set_block_info(blk, res);
404 /* Get all values living at the block start sorted by next use*/
407 DBG((dbg, DBG_START, "Living at start of %+F:\n", blk));
408 first = sched_first(blk);
410 sched_foreach(blk, irn) {
411 if (is_Phi(irn) && arch_get_irn_reg_class(env->arch, irn, -1) == env->cls) {
413 loc.time = get_distance(env, first, 0, irn, 0);
414 obstack_grow(&ob, &loc, sizeof(loc));
415 DBG((dbg, DBG_START, " %+F:\n", irn));
421 live_foreach(blk, li) {
422 if (live_is_in(li) && arch_get_irn_reg_class(env->arch, li->irn, -1) == env->cls) {
423 loc.irn = (ir_node *)li->irn;
424 loc.time = get_distance(env, first, 0, li->irn, 0);
425 obstack_grow(&ob, &loc, sizeof(loc));
426 DBG((dbg, DBG_START, " %+F:\n", li->irn));
431 starters = obstack_finish(&ob);
432 qsort(starters, count, sizeof(starters[0]), loc_compare);
435 /* If we have only one predecessor, we want the start_set of blk to be the end_set of pred */
436 if (get_Block_n_cfgpreds(blk) == 1 && blk != get_irg_start_block(get_irn_irg(blk))) {
437 ir_node *pred_blk = get_Block_cfgpred_block(blk, 0);
438 block_info_t *pred_info = get_block_info(pred_blk);
440 /* if pred block has not been processed yet, do it now */
442 belady(pred_blk, env);
443 pred_info = get_block_info(pred_blk);
446 /* now we have an end_set of pred */
447 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
448 res->ws_start = workset_clone(&env->ob, pred_info->ws_end);
452 /* Else we want the start_set to be the values used 'the closest' */
454 /* Copy the best ones from starters to start workset */
455 ws_count = MIN(count, env->n_regs);
456 res->ws_start = new_workset(&env->ob, env);
457 workset_bulk_fill(res->ws_start, ws_count, starters);
462 /* The phis of this block which are not in the start set have to be spilled later.
463 * Therefore we add temporary copies in the pred_blocks so the spills can spill
464 * into the same spill slot.
465 * After spilling these copies get deleted. */
466 for (i=workset_get_length(res->ws_start); i<count; ++i) {
467 irn = starters[i].irn;
468 if (!is_Phi(irn) || get_nodes_block(irn) != blk)
471 be_spill_phi(env->senv, irn);
474 obstack_free(&ob, NULL);
480 * For the given block @p blk, decide for each values
481 * whether it is used from a register or is reloaded
484 static void belady(ir_node *blk, void *env) {
485 belady_env_t *bel = env;
489 block_info_t *blk_info;
491 /* Don't do a block twice */
492 if (get_block_info(blk))
495 /* get the starting workset for this block */
496 blk_info = compute_block_start_info(blk, bel);
498 DBG((dbg, DBG_DECIDE, "\n"));
499 DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
501 workset_copy(bel->ws, blk_info->ws_start);
502 DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
503 workset_foreach(bel->ws, irn, iter)
504 DBG((dbg, DBG_WSETS, " %+F\n", irn));
506 /* process the block from start to end */
507 DBG((dbg, DBG_WSETS, "Processing...\n"));
508 bel->used = pset_new_ptr(32);
510 new_vals = new_workset(&bel->ob, bel);
511 sched_foreach(blk, irn) {
512 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
514 /* projs are handled with the tuple value.
515 * Phis are no real instr (see insert_starters())
516 * instr_nr does not increase */
517 if (is_Proj(irn) || is_Phi(irn)) {
518 DBG((dbg, DBG_DECIDE, " ...%+F skipped\n", irn));
521 DBG((dbg, DBG_DECIDE, " ...%+F\n", irn));
523 /* set instruction in the workset */
526 /* allocate all values _used_ by this instruction */
527 workset_clear(new_vals);
528 workset_bulk_insert(new_vals, get_irn_arity(irn)+1, get_irn_in(irn));
529 displace(bel, new_vals, 1);
531 /* allocate all values _defined_ by this instruction */
532 workset_clear(new_vals);
533 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
535 for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
536 workset_insert(new_vals, proj);
538 workset_insert(new_vals, irn);
540 displace(bel, new_vals, 0);
546 /* Remember end-workset for this block */
547 blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
548 DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
549 workset_foreach(blk_info->ws_end, irn, iter)
550 DBG((dbg, DBG_WSETS, " %+F\n", irn));
554 * 'decide' is block-local and makes assumptions
555 * about the set of live-ins. Thus we must adapt the
556 * live-outs to the live-ins at each block-border.
558 static void fix_block_borders(ir_node *blk, void *env) {
560 belady_env_t *bel = env;
561 int i, max, iter, iter2;
563 DBG((dbg, DBG_FIX, "\n"));
564 DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
566 wsb = get_block_info(blk)->ws_start;
568 /* process all pred blocks */
569 for (i=0, max=get_irn_arity(blk); i<max; ++i) {
570 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
571 workset_t *wsp = get_block_info(pred)->ws_end;
573 DBG((dbg, DBG_FIX, " Pred %+F\n", pred));
575 workset_foreach(wsb, irnb, iter) {
576 /* if irnb is a phi of the current block we reload
577 * the corresponding argument, else irnb itself */
578 if(is_Phi(irnb) && blk == get_nodes_block(irnb))
579 irnb = get_irn_n(irnb, i);
581 /* Unknowns are available everywhere */
582 if(get_irn_opcode(irnb) == iro_Unknown)
585 /* check if irnb is in a register at end of pred */
586 workset_foreach(wsp, irnp, iter2) {
591 /* irnb is in memory at the end of pred, so we have to reload it */
592 DBG((dbg, DBG_FIX, " reload %+F\n", irnb));
593 be_add_reload_on_edge(bel->senv, irnb, blk, i);
596 /*epsilon statement :)*/;
602 * Removes all copies introduced for phi-spills
604 static void remove_copies(belady_env_t *env) {
607 for(i = 0; i < ARR_LEN(env->copies); ++i) {
608 ir_node *node = env->copies[i];
610 const ir_edge_t *edge, *ne;
612 assert(be_is_Copy(node));
614 src = be_get_Copy_op(node);
615 foreach_out_edge_safe(node, edge, ne) {
616 ir_node *user = get_edge_src_irn(edge);
617 int user_pos = get_edge_src_pos(edge);
619 set_irn_n(user, user_pos, src);
624 void be_spill_belady(const be_chordal_env_t *chordal_env) {
625 be_spill_belady_spill_env(chordal_env, NULL);
628 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
631 FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
633 /* init belady env */
634 obstack_init(&bel.ob);
635 bel.arch = chordal_env->birg->main_env->arch_env;
636 bel.cls = chordal_env->cls;
637 bel.n_regs = arch_register_class_n_regs(bel.cls);
638 bel.ws = new_workset(&bel.ob, &bel);
639 bel.uses = be_begin_uses(chordal_env->irg, chordal_env->birg->main_env->arch_env, bel.cls);
640 if(spill_env == NULL) {
641 bel.senv = be_new_spill_env(chordal_env);
643 bel.senv = spill_env;
645 DEBUG_ONLY(be_set_spill_env_dbg_module(bel.senv, dbg);)
646 bel.copies = NEW_ARR_F(ir_node*, 0);
648 DBG((dbg, LEVEL_1, "running on register class: %s\n", bel.cls->name));
651 be_clear_links(chordal_env->irg);
652 irg_block_walk_graph(chordal_env->irg, NULL, belady, &bel);
653 irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &bel);
654 be_insert_spills_reloads(bel.senv);
656 DEL_ARR_F(bel.copies);
658 be_remove_dead_nodes_from_schedule(chordal_env->irg);
661 if(spill_env == NULL)
662 be_delete_spill_env(bel.senv);
663 be_end_uses(bel.uses);
664 obstack_free(&bel.ob, NULL);