Changes API a little bit :-)
[libfirm] / ir / be / bespillbelady.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                20.09.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  */
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #ifdef HAVE_ALLOCA_H
12 #include <alloca.h>
13 #endif
14
15 #ifdef HAVE_MALLOC_H
16 #include <malloc.h>
17 #endif
18
19 #include "obst.h"
20 #include "set.h"
21 #include "pset.h"
22 #include "irgraph.h"
23 #include "irnode.h"
24 #include "irmode.h"
25 #include "irgwalk.h"
26 #include "iredges_t.h"
27 #include "ircons_t.h"
28
29 #include "beutil.h"
30 #include "bearch.h"
31 #include "bespillbelady.h"
32 #include "beuses_t.h"
33 #include "besched_t.h"
34 #include "beirgmod.h"
35 #include "belive_t.h"
36 #include "benode_t.h"
37 #include "bechordal_t.h"
38
39 #define DBG_SPILL   1
40 #define DBG_WSETS   2
41 #define DBG_FIX     4
42 #define DBG_DECIDE  8
43 #define DBG_START  16
44 #define DBG_TRACE  64
45 #define DEBUG_LVL SET_LEVEL_0 //(DBG_START | DBG_DECIDE | DBG_WSETS | DBG_FIX | DBG_SPILL)
46 static firm_dbg_module_t *dbg = NULL;
47
48 #define MIN(a,b) (((a)<(b))?(a):(b))
49 #define SINGLE_START_PROJS
50
51 typedef struct _workset_t workset_t;
52
53 typedef struct _belady_env_t {
54         struct obstack ob;
55         const be_node_factory_t *factory;
56         const arch_env_t *arch;
57         const arch_register_class_t *cls;
58         int n_regs;                     /** number of regs in this reg-class */
59
60         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
61         be_uses_t *uses;        /**< env for the next-use magic */
62         ir_node *instr;         /**< current instruction */
63         unsigned instr_nr;      /**< current instruction number (relative to block start) */
64         pset *used;                     /**< holds the values used (so far) in the current BB */
65
66         spill_env_t *senv;      /* see bespill.h */
67         pset *reloads;          /**< all reload nodes placed */
68 } belady_env_t;
69
70 struct _workset_t {
71         belady_env_t *bel;
72         int i;                          /**< used for iteration */
73         int len;                        /**< current length */
74         loc_t vals[1];          /**< inlined array of the values/distances in this working set */
75 };
76
77 typedef struct _block_info_t {
78         workset_t *ws_start, *ws_end;
79 } block_info_t;
80
81 /**
82  * Alloc a new workset on obstack @p ob with maximum size @p max
83  */
84 static INLINE workset_t *new_workset(struct obstack *ob, belady_env_t *bel) {
85         workset_t *res;
86         size_t size = sizeof(*res) + (bel->n_regs-1)*sizeof(res->vals[0]);
87         res = obstack_alloc(ob, size);
88         memset(res, 0, size);
89         res->bel = bel;
90         return res;
91 }
92
93 static INLINE workset_t *workset_clone(struct obstack *ob, workset_t *ws) {
94         workset_t *res;
95         size_t size = sizeof(*res) + (ws->bel->n_regs-1)*sizeof(res->vals[0]);
96         res = obstack_alloc(ob, size);
97         memcpy(res, ws, size);
98         return res;
99 }
100
101 /**
102  * Inserts the value @p val into the workset, iff it is not
103  * already contained. The workset must not be full.
104  */
105 static INLINE void workset_insert(workset_t *ws, ir_node *val) {
106         int i;
107         /* check for current regclass */
108         if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
109                 DBG((dbg, DBG_DECIDE, "Dropped %+F\n", val));
110                 return;
111         }
112
113         /* check if val is already contained */
114         for(i=0; i<ws->len; ++i)
115                 if (ws->vals[i].irn == val)
116                         return;
117
118         /* insert val */
119         assert(ws->len < ws->bel->n_regs && "Workset already full!");
120         ws->vals[ws->len++].irn = val;
121 }
122
123 /**
124  * Inserts all values in array @p vals of length @p cnt
125  * into the workset. There must be enough space for the
126  * entries.
127  */
128 static INLINE void workset_bulk_insert(workset_t *ws, int cnt, ir_node **vals) {
129         int i, o;
130
131         for(o=0; o<cnt; ++o) {
132                 ir_node *val = vals[o];
133                 DBG((dbg, DBG_TRACE, "Bulk insert %+F\n", val));
134                 /* check for current regclass */
135                 if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
136                         DBG((dbg, DBG_TRACE, "Wrong reg class\n"));
137                         goto no_insert;
138                 }
139
140                 /* check if val is already contained */
141                 for(i=0; i<ws->len; ++i)
142                         if (ws->vals[i].irn == val) {
143                                 DBG((dbg, DBG_TRACE, "Already contained\n"));
144                                 goto no_insert;
145                         }
146
147                 /* insert val */
148                 assert(ws->len < ws->bel->n_regs && "Workset does not have enough room!");
149                 ws->vals[ws->len++].irn = val;
150                 DBG((dbg, DBG_TRACE, "Inserted\n"));
151
152 no_insert:
153                 /*epsilon statement :)*/;
154         }
155 }
156
157 /**
158  * Overwrites the current contents of @p ws with the
159  * locations given in @p locs
160  */
161 #define workset_bulk_fill(ws, count, locs) memcpy(&(ws)->vals[0], locs, ((ws)->len=count)*sizeof(locs[0]));
162
163 /**
164  * Removes all entries from this workset
165  */
166 #define workset_clear(ws) (ws)->len = 0;
167
168 /**
169  * Removes the value @p val from the workset if present.
170  */
171 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
172         int i;
173         for(i=0; i<ws->len; ++i)
174                 if (ws->vals[i].irn == val) {
175                         ws->vals[i] = ws->vals[--ws->len];
176                         return;
177                 }
178 }
179
180 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
181         int i;
182         for(i=0; i<ws->len; ++i)
183                 if (ws->vals[i].irn == val)
184                         return 1;
185         return 0;
186 }
187
188 #define workset_foreach(ws, v)  for(ws->i=0; \
189                                                                         v=(ws->i < ws->len) ? ws->vals[ws->i].irn : NULL, ws->i < ws->len; \
190                                                                         ws->i++)
191
192 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
193 #define workset_set_length(ws, length) (ws)->len = length
194 #define workset_get_length(ws) ((ws)->len)
195 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
196 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
197
198
199 static int is_mem_phi(const ir_node *irn, void *data) {
200         workset_t *sws;
201         ir_node *blk = get_nodes_block(irn);
202
203         DBG((dbg, DBG_SPILL, "Is %+F a mem-phi?\n", irn));
204         sws = ((block_info_t *) get_irn_link(blk))->ws_start;
205         DBG((dbg, DBG_SPILL, "  %d\n", !workset_contains(sws, irn)));
206         return !workset_contains(sws, irn);
207 }
208
209 /**
210  * Collects all values live-in at block @p blk and all phi results in this block.
211  * Then it adds the best values (at most n_regs) to the ws.
212  */
213 static void build_start_set(belady_env_t *bel, ir_node *blk) {
214         workset_t *ws = bel->ws;
215         ir_node *irn, *first;
216         irn_live_t *li;
217         int count;
218         loc_t loc, *starters;
219         struct obstack ob;
220
221         obstack_init(&ob);
222
223         /* get all values */
224         first = sched_first(blk);
225         count = 0;
226         sched_foreach(blk, irn)
227                 if (is_Phi(irn) && arch_get_irn_reg_class(bel->arch, irn, -1) == bel->cls) {
228                         loc.irn = irn;
229                         loc.time = be_get_next_use(bel->uses, first, 0, irn, 0);
230                         DBG((dbg, DBG_START, "  %+F next-use %d\n", loc.irn, loc.time));
231                         obstack_grow(&ob, &loc, sizeof(loc));
232                         count++;
233                 } else
234                         break;
235
236         live_foreach(blk, li)
237                 if (live_is_in(li) && arch_get_irn_reg_class(bel->arch, li->irn, -1) == bel->cls) {
238                         loc.irn = (ir_node *)li->irn;
239                         loc.time = be_get_next_use(bel->uses, first, 0, li->irn, 0);
240                         DBG((dbg, DBG_START, "  %+F next-use %d\n", loc.irn, loc.time));
241                         obstack_grow(&ob, &loc, sizeof(loc));
242                         count++;
243                 }
244         starters = obstack_finish(&ob);
245
246         /* sort all values */
247         qsort(starters, count, sizeof(starters[0]), loc_compare);
248
249         /* copy the best ones to the ws */
250         count = MIN(count, ws->bel->n_regs);
251         workset_bulk_fill(ws, count, starters);
252
253         obstack_free(&ob, NULL);
254 }
255
256 /**
257  * Performs the actions neccessary to grant the request that:
258  * - new_vals can be held in registers
259  * - as few as possible other values are disposed
260  * - the worst values get disposed
261  *
262  * @p is_usage indicates that the values in new_vals are used (not defined)
263  * In this case reloads must be performed
264  */
265 static void displace(belady_env_t *bel, workset_t *new_vals, int is_usage) {
266         ir_node *val;
267         int i, len, max_allowed, demand;
268         workset_t *ws = bel->ws;
269         ir_node **to_insert = alloca(bel->n_regs * sizeof(*to_insert));
270
271         /*
272          * 1. Identify the number of needed slots and the values to reload
273          */
274         demand = 0;
275         workset_foreach(new_vals, val) {
276                 /* mark value as used */
277                 if (is_usage)
278                         pset_insert_ptr(bel->used, val);
279
280                 if (!workset_contains(ws, val)) {
281                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
282                         to_insert[demand++] = val;
283                         if (is_usage)
284                                 be_add_reload(bel->senv, val, bel->instr);
285                 } else
286                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
287         }
288         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
289
290
291         /*
292          * 2. Make room for at least 'demand' slots
293          */
294         len = workset_get_length(ws);
295         max_allowed = bel->n_regs - demand;
296
297         /* Only make more free room if we do not have enough */
298         if (len > max_allowed) {
299                 /* get current next-use distance */
300                 for (i=0; i<ws->len; ++i)
301                         workset_set_time(ws, i, be_get_next_use(bel->uses, bel->instr, bel->instr_nr, workset_get_val(ws, i), !is_usage));
302
303                 /* sort entries by increasing nextuse-distance*/
304                 workset_sort(ws);
305
306                 /* Logic for not needed live-ins: If a value is disposed
307                    before its first usage, remove it from start workset */
308                 for (i=max_allowed; i<ws->len; ++i) {
309                         ir_node *irn = ws->vals[i].irn;
310                         if (!pset_find_ptr(bel->used, irn)) {
311                                 ir_node *curr_bb = get_nodes_block(bel->instr);
312                                 workset_t *ws_start = ((block_info_t *) get_irn_link(curr_bb))->ws_start;
313                                 workset_remove(ws_start, irn);
314
315                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
316                         } else
317                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
318                 }
319
320                 /* kill the last 'demand' entries in the array */
321                 workset_set_length(ws, max_allowed);
322         }
323
324         /*
325          * 3. Insert the new values into the workset
326          */
327         workset_bulk_insert(bel->ws, demand, to_insert);
328 }
329
330 /**
331  * For the given block @p blk, decide for each values
332  * whether it is used from a register or is reloaded
333  * before the use.
334  */
335 static void decide(ir_node *blk, void *env) {
336         belady_env_t *bel = env;
337         workset_t *new_vals;
338         ir_node *irn;
339 #ifdef SINGLE_START_PROJS
340         ir_node *start_blk = get_irg_start_block(get_irn_irg(blk));
341 #endif
342         block_info_t *blk_info = obstack_alloc(&bel->ob, sizeof(*blk_info));
343         set_irn_link(blk, blk_info);
344
345         DBG((dbg, DBG_DECIDE, "\n"));
346         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
347
348         /* build starting-workset for this block */
349         build_start_set(bel, blk);
350         blk_info->ws_start = workset_clone(&bel->ob, bel->ws);
351         DBG((dbg, DBG_WSETS, "Initial start workset for %+F:\n", blk));
352         workset_foreach(blk_info->ws_start, irn)
353                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
354
355         /* process the block from start to end */
356         DBG((dbg, DBG_WSETS, "Processing...\n"));
357         bel->used = pset_new_ptr(32);
358         bel->instr_nr = 0;
359         new_vals = new_workset(&bel->ob, bel);
360         sched_foreach(blk, irn) {
361                 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
362
363
364 #ifdef SINGLE_START_PROJS
365                 if (is_Phi(irn) ||
366                         (is_Proj(irn) && blk!=start_blk) ||
367                         (get_irn_mode(irn) == mode_T && blk==start_blk)) {
368                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
369                         continue;
370                 }
371 #else
372                 /* projs are handled with the tuple value.
373                  * Phis are no real instr (see insert_starters)
374                  * instr_nr does not increase */
375                 if (is_Proj(irn) || is_Phi(irn)) {
376                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
377                         continue;
378                 }
379 #endif
380                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
381
382                 /* set instruction in the workset */
383                 bel->instr = irn;
384
385                 /* allocate all values _used_ by this instruction */
386                 workset_clear(new_vals);
387                 workset_bulk_insert(new_vals, get_irn_arity(irn)+1, get_irn_in(irn));
388                 displace(bel, new_vals, 1);
389
390                 /* allocate all values _defined_ by this instruction */
391                 workset_clear(new_vals);
392                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
393                         ir_node *proj;
394                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
395                                 workset_insert(new_vals, proj);
396                 } else {
397                         workset_insert(new_vals, irn);
398                 }
399                 displace(bel, new_vals, 0);
400
401                 bel->instr_nr++;
402         }
403         del_pset(bel->used);
404
405         /* Remember end-workset for this block */
406         blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
407         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
408         workset_foreach(blk_info->ws_start, irn)
409                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
410         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
411         workset_foreach(blk_info->ws_end, irn)
412                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
413 }
414
415 /**
416  * 'decide' is block-local and makes assumptions
417  * about the set of live-ins. Thus we must adapt the
418  * live-outs to the live-ins at each block-border.
419  */
420 static void fix_block_borders(ir_node *blk, void *env) {
421         workset_t *wsb;
422         belady_env_t *bel = env;
423         int i, max;
424
425         DBG((dbg, DBG_FIX, "\n"));
426         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
427
428         wsb = ((block_info_t *)get_irn_link(blk))->ws_start;
429
430         /* process all pred blocks */
431         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
432                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
433                 workset_t *wsp = ((block_info_t *)get_irn_link(pred))->ws_end;
434
435                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
436
437                 workset_foreach(wsb, irnb) {
438                         /* if irnb is a phi of the current block we reload
439                          * the corresponding argument, else irnb itself */
440                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
441                                 irnb = get_irn_n(irnb, i);
442
443                         /* Unknowns are available everywhere */
444                         if(get_irn_opcode(irnb) == iro_Unknown)
445                                 continue;
446
447                         /* check if irnb is in a register at end of pred */
448                         workset_foreach(wsp, irnp)
449                                 if (irnb == irnp)
450                                         goto next_value;
451
452                         /* irnb is in memory at the end of pred, so we have to reload it */
453                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
454                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
455
456 next_value:
457                         /*epsilon statement :)*/;
458                 }
459         }
460 }
461
462 /**
463  * Removes all used reloads from bel->reloads.
464  * The remaining nodes in bel->reloads will be removed from the graph.
465  */
466 static void rescue_used_reloads(ir_node *irn, void *env) {
467         pset *rlds = (pset *)env;
468         if (pset_find_ptr(rlds, irn))
469                 pset_remove_ptr(rlds, irn);
470 }
471
472 /**
473  * Finds all unused reloads and remove them from the schedule
474  * Also removes spills if they are not used anymore after removing reloads
475  */
476 static void remove_unused_reloads(ir_graph *irg, belady_env_t *bel) {
477         ir_node *irn;
478
479         irg_walk_graph(irg, rescue_used_reloads, NULL, bel->reloads);
480         for(irn = pset_first(bel->reloads); irn; irn = pset_next(bel->reloads)) {
481                 ir_node *spill;
482                 DBG((dbg, DBG_SPILL, "Removing %+F before %+F in %+F\n", irn, sched_next(irn), get_nodes_block(irn)));
483
484                 spill = get_irn_n(irn, 0);
485
486                 /* remove reload */
487                 set_irn_n(irn, 0, new_Bad());
488                 sched_remove(irn);
489
490                 /* if spill not used anymore, remove it too
491                  * test of regclass is necessary since spill may be a phi-M */
492                 if (get_irn_n_edges(spill) == 0 && bel->cls == arch_get_irn_reg_class(bel->arch, spill, -1)) {
493                         set_irn_n(spill, 0, new_Bad());
494                         sched_remove(spill);
495                 }
496         }
497 }
498
499 void be_spill_belady(const be_chordal_env_t *chordal_env) {
500         belady_env_t bel;
501
502         dbg = firm_dbg_register("ir.be.spillbelady");
503         firm_dbg_set_mask(dbg, DEBUG_LVL);
504
505         /* init belady env */
506         obstack_init(&bel.ob);
507         bel.factory = chordal_env->main_env->node_factory;
508         bel.arch    = chordal_env->main_env->arch_env;
509         bel.cls     = chordal_env->cls;
510         bel.n_regs  = arch_register_class_n_regs(bel.cls);
511         bel.ws      = new_workset(&bel.ob, &bel);
512         bel.uses    = be_begin_uses(chordal_env->irg, chordal_env->main_env->arch_env, bel.cls);
513         bel.senv    = be_new_spill_env(dbg, chordal_env, is_mem_phi, NULL);
514         bel.reloads = pset_new_ptr_default();
515
516         /* do the work */
517         irg_block_walk_graph(chordal_env->irg, decide, NULL, &bel);
518         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &bel);
519         be_insert_spills_reloads(bel.senv, bel.reloads);
520         remove_unused_reloads(chordal_env->irg, &bel);
521
522         /* clean up */
523         del_pset(bel.reloads);
524         be_delete_spill_env(bel.senv);
525         be_end_uses(bel.uses);
526         obstack_free(&bel.ob, NULL);
527 }