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