init_sp Unknown node constructed with CSE disabled
[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  */
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif
11
12 #ifdef HAVE_ALLOCA_H
13 #include <alloca.h>
14 #endif
15
16 #ifdef HAVE_MALLOC_H
17 #include <malloc.h>
18 #endif
19
20 #include "obst.h"
21 #include "set.h"
22 #include "pset.h"
23 #include "irprintf_t.h"
24 #include "irgraph.h"
25 #include "irnode.h"
26 #include "irmode.h"
27 #include "irgwalk.h"
28 #include "iredges_t.h"
29 #include "ircons_t.h"
30 #include "irprintf.h"
31
32 #include "beutil.h"
33 #include "bearch.h"
34 #include "bespillbelady.h"
35 #include "beuses_t.h"
36 #include "besched_t.h"
37 #include "beirgmod.h"
38 #include "belive_t.h"
39 #include "benode_t.h"
40 #include "bechordal_t.h"
41
42 #define DBG_SPILL   1
43 #define DBG_WSETS   2
44 #define DBG_FIX     4
45 #define DBG_DECIDE  8
46 #define DBG_START  16
47 #define DBG_SLOTS  32
48 #define DBG_TRACE  64
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;)
52
53 typedef struct _workset_t workset_t;
54
55 typedef struct _belady_env_t {
56         struct obstack ob;
57         const arch_env_t *arch;
58         const arch_register_class_t *cls;
59         int n_regs;                     /** number of regs in this reg-class */
60
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
67         spill_env_t *senv;      /**< see bespill.h */
68 } belady_env_t;
69
70 struct _workset_t {
71         belady_env_t *bel;
72         int len;                        /**< current length */
73         loc_t vals[1];          /**< inlined array of the values/distances in this working set */
74 };
75
76 void workset_print(const workset_t *w)
77 {
78         int i;
79
80         for(i = 0; i < w->len; ++i) {
81                 ir_printf("%+F %d\n", w->vals[i].irn, w->vals[i].time);
82         }
83 }
84
85 /**
86  * Alloc a new workset on obstack @p ob with maximum size @p max
87  */
88 static INLINE workset_t *new_workset(struct obstack *ob, belady_env_t *bel) {
89         workset_t *res;
90         size_t size = sizeof(*res) + (bel->n_regs-1)*sizeof(res->vals[0]);
91         res = obstack_alloc(ob, size);
92         memset(res, 0, size);
93         res->bel = bel;
94         return res;
95 }
96
97 /**
98  * Alloc a new instance on obstack and make it equal to @param ws
99  */
100 static INLINE workset_t *workset_clone(struct obstack *ob, workset_t *ws) {
101         workset_t *res;
102         size_t size = sizeof(*res) + (ws->bel->n_regs-1)*sizeof(res->vals[0]);
103         res = obstack_alloc(ob, size);
104         memcpy(res, ws, size);
105         return res;
106 }
107
108 /**
109  * Do NOT alloc anything. Make @param tgt equal to @param src.
110  * returns @param tgt for convinience
111  */
112 static INLINE workset_t *workset_copy(workset_t *tgt, workset_t *src) {
113         size_t size = sizeof(*src) + (src->bel->n_regs-1)*sizeof(src->vals[0]);
114         memcpy(tgt, src, size);
115         return tgt;
116 }
117
118 /**
119  * Overwrites the current content array of @param ws with the
120  * @param count locations given at memory @param locs.
121  * Set the length of @param ws to count.
122  */
123 #define workset_bulk_fill(ws, count, locs) memcpy(&(ws)->vals[0], locs, ((ws)->len=count)*sizeof(locs[0]));
124
125
126 /**
127  * Inserts the value @p val into the workset, iff it is not
128  * already contained. The workset must not be full.
129  */
130 static INLINE void workset_insert(workset_t *ws, ir_node *val) {
131         int i;
132         /* check for current regclass */
133         if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
134                 DBG((dbg, DBG_WORKSET, "Dropped %+F\n", val));
135                 return;
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                         return;
142
143         /* insert val */
144         assert(ws->len < ws->bel->n_regs && "Workset already full!");
145         ws->vals[ws->len++].irn = val;
146 }
147
148 /**
149  * Inserts all values in array @p vals of length @p cnt
150  * into the workset. There must be enough space for the
151  * entries.
152  */
153 static INLINE void workset_bulk_insert(workset_t *ws, int cnt, ir_node **vals) {
154         int i, o;
155
156         for(o=0; o<cnt; ++o) {
157                 ir_node *val = vals[o];
158                 DBG((dbg, DBG_TRACE, "Bulk insert %+F\n", val));
159                 /* check for current regclass */
160                 if (arch_get_irn_reg_class(ws->bel->arch, val, -1) != ws->bel->cls) {
161                         DBG((dbg, DBG_TRACE, "Wrong reg class\n"));
162                         goto no_insert;
163                 }
164
165                 /* check if val is already contained */
166                 for(i=0; i<ws->len; ++i)
167                         if (ws->vals[i].irn == val) {
168                                 DBG((dbg, DBG_TRACE, "Already contained\n"));
169                                 goto no_insert;
170                         }
171
172                 /* insert val */
173                 assert(ws->len < ws->bel->n_regs && "Workset does not have enough room!");
174                 ws->vals[ws->len++].irn = val;
175                 DBG((dbg, DBG_TRACE, "Inserted\n"));
176
177 no_insert:
178                 /*epsilon statement :)*/;
179         }
180 }
181
182 /**
183  * Removes all entries from this workset
184  */
185 #define workset_clear(ws) (ws)->len = 0;
186
187 /**
188  * Removes the value @p val from the workset if present.
189  */
190 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
191         int i;
192         for(i=0; i<ws->len; ++i)
193                 if (ws->vals[i].irn == val) {
194                         ws->vals[i] = ws->vals[--ws->len];
195                         return;
196                 }
197 }
198
199 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
200         int i;
201         for(i=0; i<ws->len; ++i)
202                 if (ws->vals[i].irn == val)
203                         return 1;
204         return 0;
205 }
206
207 /**
208  * Iterates over all values in the working set.
209  * @p ws The workset to iterate
210  * @p v  A variable to put the current value in
211  * @p i  An integer for internal use
212  */
213 #define workset_foreach(ws, v, i)       for(i=0; \
214                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
215                                                                                 ++i)
216
217 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
218 #define workset_set_length(ws, length) (ws)->len = length
219 #define workset_get_length(ws) ((ws)->len)
220 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
221 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
222
223 typedef struct _block_info_t {
224         workset_t *ws_start, *ws_end;
225 } block_info_t;
226
227
228 static INLINE void *new_block_info(struct obstack *ob) {
229         block_info_t *res = obstack_alloc(ob, sizeof(*res));
230         res->ws_start = NULL;
231         res->ws_end = NULL;
232
233         return res;
234 }
235
236 #define get_block_info(blk)                     ((block_info_t *)get_irn_link(blk))
237 #define set_block_info(blk, info)       set_irn_link(blk, info)
238
239 /**
240  * @return The distance to the next use
241  *         Or 0 if irn is an ignore node
242  */
243 static INLINE unsigned get_distance(belady_env_t *bel, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
244 {
245         arch_irn_flags_t fl = arch_irn_get_flags(bel->arch, def);
246         unsigned dist = be_get_next_use(bel->uses, from, from_step, def, skip_from_uses);
247
248         if(!USES_IS_INIFINITE(dist) && (fl & (arch_irn_flags_ignore | arch_irn_flags_dont_spill)) != 0)
249                 return 0;
250
251         return dist + 1;
252 }
253
254 /**
255  * Performs the actions necessary 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, iter;
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, iter) {
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                         assert(is_usage || "Defined value already in workset?!?");
285                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
286                 }
287         }
288         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
289
290         /*
291          * 2. Make room for at least 'demand' slots
292          */
293         len = workset_get_length(ws);
294         max_allowed = bel->n_regs - demand;
295
296         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
297
298         /* Only make more free room if we do not have enough */
299         if (len > max_allowed) {
300                 /* get current next-use distance */
301                 for (i=0; i<ws->len; ++i)
302                         workset_set_time(ws, i, get_distance(bel, bel->instr, bel->instr_nr, workset_get_val(ws, i), !is_usage));
303
304                 /* sort entries by increasing nextuse-distance*/
305                 workset_sort(ws);
306
307                 /* Logic for not needed live-ins: If a value is disposed
308                    before its first usage, remove it from start workset */
309                 for (i=max_allowed; i<ws->len; ++i) {
310                         ir_node *irn = ws->vals[i].irn;
311
312                         if (!pset_find_ptr(bel->used, irn)) {
313                                 ir_node *curr_bb = get_nodes_block(bel->instr);
314                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
315                                 workset_remove(ws_start, irn);
316
317                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
318                         } else {
319                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
320                         }
321                 }
322
323                 /* kill the last 'demand' entries in the array */
324                 workset_set_length(ws, max_allowed);
325         }
326
327         /*
328          * 3. Insert the new values into the workset
329          */
330         workset_bulk_insert(bel->ws, demand, to_insert);
331 }
332
333 static void belady(ir_node *blk, void *env);
334
335 /**
336  * Collects all values live-in at block @p blk and all phi results in this block.
337  * Then it adds the best values (at most n_regs) to the blocks start_workset.
338  * The phis among the remaining values get spilled: Introduce psudo-copies of
339  *  their args to break interference and make it possible to spill them to the
340  *  same spill slot.
341  */
342 static block_info_t *compute_block_start_info(ir_node *blk, void *data) {
343         belady_env_t *env = data;
344         ir_node *irn, *first;
345         irn_live_t *li;
346         int i, count, ws_count;
347         loc_t loc, *starters;
348         ir_graph *irg = get_irn_irg(blk);
349         struct obstack ob;
350         block_info_t *res = get_block_info(blk);
351
352         /* Have we seen this block before? */
353         if (res)
354                 return res;
355
356         /* Create the block info for this block. */
357         res = new_block_info(&env->ob);
358         set_block_info(blk, res);
359
360
361         /* Get all values living at the block start sorted by next use*/
362         obstack_init(&ob);
363
364         DBG((dbg, DBG_START, "Living at start of %+F:\n", blk));
365         first = sched_first(blk);
366         count = 0;
367         sched_foreach(blk, irn) {
368                 if (is_Phi(irn) && arch_get_irn_reg_class(env->arch, irn, -1) == env->cls) {
369                         loc.irn = irn;
370                         loc.time = get_distance(env, first, 0, irn, 0);
371                         obstack_grow(&ob, &loc, sizeof(loc));
372                         DBG((dbg, DBG_START, "    %+F:\n", irn));
373                         count++;
374                 } else
375                         break;
376         }
377
378         live_foreach(blk, li) {
379                 if (live_is_in(li) && arch_get_irn_reg_class(env->arch, li->irn, -1) == env->cls) {
380                         loc.irn = (ir_node *)li->irn;
381                         loc.time = get_distance(env, first, 0, li->irn, 0);
382                         obstack_grow(&ob, &loc, sizeof(loc));
383                         DBG((dbg, DBG_START, "    %+F:\n", li->irn));
384                         count++;
385                 }
386         }
387
388         starters = obstack_finish(&ob);
389         qsort(starters, count, sizeof(starters[0]), loc_compare);
390
391
392         /* If we have only one predecessor, we want the start_set of blk to be the end_set of pred */
393         if (get_Block_n_cfgpreds(blk) == 1 && blk != get_irg_start_block(get_irn_irg(blk))) {
394                 ir_node *pred_blk       = get_Block_cfgpred_block(blk, 0);
395                 block_info_t *pred_info = get_block_info(pred_blk);
396
397                 /* if pred block has not been processed yet, do it now */
398                 if (! pred_info) {
399                         belady(pred_blk, env);
400                         pred_info = get_block_info(pred_blk);
401                 }
402
403                 /* now we have an end_set of pred */
404                 assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
405                 res->ws_start = workset_clone(&env->ob, pred_info->ws_end);
406
407         } else
408
409         /* Else we want the start_set to be the values used 'the closest' */
410         {
411                 /* Copy the best ones from starters to start workset */
412                 ws_count = MIN(count, env->n_regs);
413                 res->ws_start = new_workset(&env->ob, env);
414                 workset_bulk_fill(res->ws_start, ws_count, starters);
415         }
416
417
418
419         /* The phis of this block which are not in the start set have to be spilled later.
420          * Therefore we add temporary copies in the pred_blocks so the spills can spill
421          * into the same spill slot.
422          * After spilling these copies get deleted. */
423         for (i=workset_get_length(res->ws_start); i<count; ++i) {
424                 irn = starters[i].irn;
425                 if (!is_Phi(irn) || get_nodes_block(irn) != blk)
426                         continue;
427
428                 be_spill_phi(env->senv, irn);
429         }
430
431         obstack_free(&ob, NULL);
432         return res;
433 }
434
435
436 /**
437  * For the given block @p blk, decide for each values
438  * whether it is used from a register or is reloaded
439  * before the use.
440  */
441 static void belady(ir_node *blk, void *env) {
442         belady_env_t *bel = env;
443         workset_t *new_vals;
444         ir_node *irn;
445         int iter;
446         block_info_t *blk_info;
447
448         /* Don't do a block twice */
449         if (get_block_info(blk))
450                 return;
451
452         /* get the starting workset for this block */
453         blk_info = compute_block_start_info(blk, bel);
454
455         DBG((dbg, DBG_DECIDE, "\n"));
456         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", blk));
457
458         workset_copy(bel->ws, blk_info->ws_start);
459         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", blk));
460         workset_foreach(bel->ws, irn, iter)
461                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
462
463         /* process the block from start to end */
464         DBG((dbg, DBG_WSETS, "Processing...\n"));
465         bel->used = pset_new_ptr(32);
466         bel->instr_nr = 0;
467         new_vals = new_workset(&bel->ob, bel);
468         sched_foreach(blk, irn) {
469                 assert(workset_get_length(bel->ws) <= bel->n_regs && "Too much values in workset!");
470
471                 /* projs are handled with the tuple value.
472                  * Phis are no real instr (see insert_starters())
473                  * instr_nr does not increase */
474                 if (is_Proj(irn) || is_Phi(irn)) {
475                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
476                         continue;
477                 }
478                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
479
480                 /* set instruction in the workset */
481                 bel->instr = irn;
482
483                 /* allocate all values _used_ by this instruction */
484                 workset_clear(new_vals);
485                 workset_bulk_insert(new_vals, get_irn_arity(irn)+1, get_irn_in(irn));
486                 displace(bel, new_vals, 1);
487
488                 /* allocate all values _defined_ by this instruction */
489                 workset_clear(new_vals);
490                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
491                         ir_node *proj;
492                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
493                                 workset_insert(new_vals, proj);
494                 } else {
495                         workset_insert(new_vals, irn);
496                 }
497                 displace(bel, new_vals, 0);
498
499                 bel->instr_nr++;
500         }
501         del_pset(bel->used);
502
503         /* Remember end-workset for this block */
504         blk_info->ws_end = workset_clone(&bel->ob, bel->ws);
505         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", blk));
506         workset_foreach(blk_info->ws_end, irn, iter)
507                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
508 }
509
510 /**
511  * 'decide' is block-local and makes assumptions
512  * about the set of live-ins. Thus we must adapt the
513  * live-outs to the live-ins at each block-border.
514  */
515 static void fix_block_borders(ir_node *blk, void *env) {
516         workset_t *wsb;
517         belady_env_t *bel = env;
518         int i, max, iter, iter2;
519
520         DBG((dbg, DBG_FIX, "\n"));
521         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
522
523         wsb = get_block_info(blk)->ws_start;
524
525         /* process all pred blocks */
526         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
527                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
528                 workset_t *wsp = get_block_info(pred)->ws_end;
529
530                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
531
532                 workset_foreach(wsb, irnb, iter) {
533                         /* if irnb is a phi of the current block we reload
534                          * the corresponding argument, else irnb itself */
535                         if(is_Phi(irnb) && blk == get_nodes_block(irnb))
536                                 irnb = get_irn_n(irnb, i);
537
538                         /* Unknowns are available everywhere */
539                         if(get_irn_opcode(irnb) == iro_Unknown)
540                                 continue;
541
542                         /* check if irnb is in a register at end of pred */
543                         workset_foreach(wsp, irnp, iter2) {
544                                 if (irnb == irnp)
545                                         goto next_value;
546                         }
547
548                         /* irnb is in memory at the end of pred, so we have to reload it */
549                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
550                         be_add_reload_on_edge(bel->senv, irnb, blk, i);
551
552 next_value:
553                         /*epsilon statement :)*/;
554                 }
555         }
556 }
557
558 void be_spill_belady(const be_chordal_env_t *chordal_env) {
559         be_spill_belady_spill_env(chordal_env, NULL);
560 }
561
562 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
563         belady_env_t bel;
564
565         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
566
567         /* init belady env */
568         obstack_init(&bel.ob);
569         bel.arch      = chordal_env->birg->main_env->arch_env;
570         bel.cls       = chordal_env->cls;
571         bel.n_regs    = arch_register_class_n_regs(bel.cls);
572         bel.ws        = new_workset(&bel.ob, &bel);
573         bel.uses      = be_begin_uses(chordal_env->irg, chordal_env->birg->main_env->arch_env, bel.cls);
574         if(spill_env == NULL) {
575                 bel.senv = be_new_spill_env(chordal_env);
576         } else {
577                 bel.senv = spill_env;
578         }
579         DEBUG_ONLY(be_set_spill_env_dbg_module(bel.senv, dbg);)
580
581         DBG((dbg, LEVEL_1, "running on register class: %s\n", bel.cls->name));
582
583         /* do the work */
584         be_clear_links(chordal_env->irg);
585         irg_block_walk_graph(chordal_env->irg, NULL, belady, &bel);
586         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &bel);
587         be_insert_spills_reloads(bel.senv);
588
589         be_remove_dead_nodes_from_schedule(chordal_env->irg);
590
591         /* clean up */
592         if(spill_env == NULL)
593                 be_delete_spill_env(bel.senv);
594         be_end_uses(bel.uses);
595         obstack_free(&bel.ob, NULL);
596 }