fixed debug output of unary x87 nodes
[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 be_chordal_env_t *cenv;
58         const arch_env_t *arch;
59         const arch_register_class_t *cls;
60         int n_regs;                     /** number of regs in this reg-class */
61
62         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
63         be_uses_t *uses;        /**< env for the next-use magic */
64         ir_node *instr;         /**< current instruction */
65         unsigned instr_nr;      /**< current instruction number (relative to block start) */
66         pset *used;
67
68         spill_env_t *senv;      /**< see bespill.h */
69 } belady_env_t;
70
71 struct _workset_t {
72         int len;                        /**< current length */
73         loc_t vals[0];          /**< 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_fprintf(stderr, "%+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(belady_env_t *env, struct obstack *ob) {
89         workset_t *res;
90         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
91         res = obstack_alloc(ob, size);
92         memset(res, 0, size);
93         return res;
94 }
95
96 /**
97  * Alloc a new instance on obstack and make it equal to @param ws
98  */
99 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
100         workset_t *res;
101         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
102         res = obstack_alloc(ob, size);
103         memcpy(res, ws, size);
104         return res;
105 }
106
107 /**
108  * Do NOT alloc anything. Make @param tgt equal to @param src.
109  * returns @param tgt for convenience
110  */
111 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
112         size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
113         memcpy(tgt, src, size);
114         return tgt;
115 }
116
117 /**
118  * Overwrites the current content array of @param ws with the
119  * @param count locations given at memory @param locs.
120  * Set the length of @param ws to count.
121  */
122 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
123         workset->len = count;
124         memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
125 }
126
127 /**
128  * Inserts the value @p val into the workset, iff it is not
129  * already contained. The workset must not be full.
130  */
131 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
132         int i;
133         /* check for current regclass */
134         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
135                 DBG((dbg, DBG_WORKSET, "Dropped %+F\n", val));
136                 return;
137         }
138
139         /* check if val is already contained */
140         for(i=0; i<ws->len; ++i)
141                 if (ws->vals[i].irn == val)
142                         return;
143
144         /* insert val */
145         assert(ws->len < env->n_regs && "Workset already full!");
146         ws->vals[ws->len++].irn = val;
147 }
148
149 /**
150  * Removes all entries from this workset
151  */
152 static INLINE void workset_clear(workset_t *ws) {
153         ws->len = 0;
154 }
155
156 /**
157  * Removes the value @p val from the workset if present.
158  */
159 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
160         int i;
161         for(i=0; i<ws->len; ++i) {
162                 if (ws->vals[i].irn == val) {
163                         ws->vals[i] = ws->vals[--ws->len];
164                         return;
165                 }
166         }
167 }
168
169 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
170         int i;
171         for(i=0; i<ws->len; ++i) {
172                 if (ws->vals[i].irn == val)
173                         return 1;
174         }
175
176         return 0;
177 }
178
179 /**
180  * Iterates over all values in the working set.
181  * @p ws The workset to iterate
182  * @p v  A variable to put the current value in
183  * @p i  An integer for internal use
184  */
185 #define workset_foreach(ws, v, i)       for(i=0; \
186                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
187                                                                                 ++i)
188
189 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
190 #define workset_get_time(ws, i) (ws)->vals[i].time
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 typedef struct _block_info_t {
197         workset_t *ws_start, *ws_end;
198         int processed;
199 } block_info_t;
200
201
202 static INLINE void *new_block_info(struct obstack *ob) {
203         block_info_t *res = obstack_alloc(ob, sizeof(*res));
204         res->ws_start = NULL;
205         res->ws_end = NULL;
206         res->processed = 0;
207
208         return res;
209 }
210
211 #define get_block_info(blk)                     ((block_info_t *)get_irn_link(blk))
212 #define set_block_info(blk, info)       set_irn_link(blk, info)
213
214 /**
215  * @return The distance to the next use or 0 if irn has dont_spill flag set
216  */
217 static INLINE unsigned get_distance(belady_env_t *env, const ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
218 {
219         int flags = arch_irn_get_flags(env->arch, def);
220         unsigned dist = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
221
222         assert(! (flags & arch_irn_flags_ignore));
223
224         /* we have to keep nonspillable nodes in the workingset */
225         if(flags & arch_irn_flags_dont_spill)
226                 return 0;
227
228         return dist;
229 }
230
231 /**
232  * Fix to remove dead nodes (especially don't spill nodes) from workset.
233  */
234 static void fix_dead_values(workset_t *ws, ir_node *irn) {
235         int idx;
236         ir_node *node;
237         ir_node *block = get_nodes_block(irn);
238
239         DBG((dbg, DBG_DECIDE, "fixing dead values at %+F:\n", irn));
240
241         workset_foreach(ws, node, idx) {
242                 const ir_edge_t *edge;
243                 int             fixme = 1;
244
245                 /* skip already fixed nodes */
246                 if (workset_get_time(ws, idx) == INT_MAX)
247                         continue;
248
249                 /* check all users */
250                 foreach_out_edge(node, edge) {
251                         ir_node *user = get_edge_src_irn(edge);
252
253                         if ((get_nodes_block(user) != block)                           ||  /* user is in a different block */
254                                 (sched_is_scheduled(user) && sched_comes_after(irn, user)) ||  /* user is scheduled after irn */
255                                 user == irn)                                                   /* irn is the user */
256                         {                                                                  /* => don't fix distance */
257                                 fixme = 0;
258                                 break;
259                         }
260                 }
261
262                 /* all users scheduled prior to current irn in in same block as irn -> fix */
263                 if (fixme) {
264                         workset_set_time(ws, idx, INT_MAX);
265                         DBG((dbg, DBG_DECIDE, "\tfixing time for %+F to INT_MAX\n", node));
266                 }
267         }
268
269 }
270
271 /**
272  * Performs the actions necessary to grant the request that:
273  * - new_vals can be held in registers
274  * - as few as possible other values are disposed
275  * - the worst values get disposed
276  *
277  * @p is_usage indicates that the values in new_vals are used (not defined)
278  * In this case reloads must be performed
279  */
280 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
281         ir_node *val;
282         int     i, len, max_allowed, demand, iter;
283
284         workset_t *ws         = env->ws;
285         ir_node   **to_insert = alloca(env->n_regs * sizeof(*to_insert));
286
287         /*
288                 1. Identify the number of needed slots and the values to reload
289         */
290         demand = 0;
291         workset_foreach(new_vals, val, iter) {
292                 /* mark value as used */
293                 if (is_usage)
294                         pset_insert_ptr(env->used, val);
295
296                 if (! workset_contains(ws, val)) {
297                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
298                         to_insert[demand++] = val;
299                         if (is_usage)
300                                 be_add_reload(env->senv, val, env->instr);
301                 }
302                 else {
303                         assert(is_usage || "Defined value already in workset?!?");
304                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
305                 }
306         }
307         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
308
309         /*
310                 2. Make room for at least 'demand' slots
311         */
312         len         = workset_get_length(ws);
313         max_allowed = env->n_regs - demand;
314
315         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
316
317         /* Only make more free room if we do not have enough */
318         if (len > max_allowed) {
319                 /* get current next-use distance */
320                 for (i = 0; i < ws->len; ++i)
321                         workset_set_time(ws, i, get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage));
322
323                 /*
324                         FIX for don't spill nodes:
325                         Problem is that get_distance always returns 0 for those nodes even if they are not
326                         needed anymore (all their usages have already been visited).
327                         Even if we change this behavior, get_distance doesn't distinguish between not
328                         used anymore (dead) and live out of block.
329                         Solution: Set distances of all nodes having all their usages in schedule prior to
330                         current instruction to MAX_INT.
331                 */
332                 fix_dead_values(ws, env->instr);
333
334                 /* sort entries by increasing nextuse-distance*/
335                 workset_sort(ws);
336
337                 /*
338                         Logic for not needed live-ins: If a value is disposed
339                         before its first usage, remove it from start workset
340                         We don't do this for phis though
341                 */
342                 for (i = max_allowed; i < ws->len; ++i) {
343                         ir_node *irn = ws->vals[i].irn;
344
345             if (is_Phi(irn))
346                 continue;
347
348                         if (! pset_find_ptr(env->used, irn)) {
349                                 ir_node   *curr_bb  = get_nodes_block(env->instr);
350                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
351                                 workset_remove(ws_start, irn);
352
353                                 DBG((dbg, DBG_DECIDE, "    dispose %+F dumb\n", irn));
354                         }
355                         else {
356                                 DBG((dbg, DBG_DECIDE, "    dispose %+F\n", irn));
357                         }
358                 }
359
360                 /* kill the last 'demand' entries in the array */
361                 workset_set_length(ws, max_allowed);
362         }
363
364         /*
365                 3. Insert the new values into the workset
366         */
367         for (i = 0; i < demand; ++i)
368                 workset_insert(env, env->ws, to_insert[i]);
369 }
370
371 static void belady(ir_node *blk, void *env);
372
373 /*
374  * Computes set of live-ins for each block with multiple predecessors
375  * and notifies spill algorithm which phis need to be spilled
376  */
377 static void spill_phi_walker(ir_node *block, void *data) {
378         belady_env_t *env = data;
379         block_info_t *block_info;
380         ir_node *first, *irn;
381         loc_t loc, *starters;
382         int i, len, ws_count;
383
384         if(get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
385                 return;
386
387         block_info = new_block_info(&env->ob);
388         set_block_info(block, block_info);
389
390         /* Collect all values living at start of block */
391         starters = NEW_ARR_F(loc_t, 0);
392
393         /* rebuild schedule time information, because it seems to be broken */
394         sched_renumber(block);
395
396         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
397         first = sched_first(block);
398         sched_foreach(block, irn) {
399                 if(!is_Phi(irn))
400                         break;
401                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn))
402                         continue;
403
404                 loc.irn = irn;
405                 loc.time = get_distance(env, first, 0, irn, 0);
406                 ARR_APP1(loc_t, starters, loc);
407                 DBG((dbg, DBG_START, "    %+F:\n", irn));
408         }
409
410         be_lv_foreach(env->cenv->lv, block, be_lv_state_in, i) {
411                 ir_node *irn = be_lv_get_irn(env->cenv->lv, block, i);
412                 if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irn))
413                         continue;
414
415                 loc.irn = irn;
416                 loc.time = get_distance(env, first, 0, irn, 0);
417                 ARR_APP1(loc_t, starters, loc);
418                 DBG((dbg, DBG_START, "    %+F:\n", irn));
419         }
420
421         // Sort start values by first use
422         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
423
424         /* Copy the best ones from starters to start workset */
425         ws_count = MIN(ARR_LEN(starters), env->n_regs);
426         block_info->ws_start = new_workset(env, &env->ob);
427         workset_bulk_fill(block_info->ws_start, ws_count, starters);
428
429         /* The phis of this block which are not in the start set have to be spilled later. */
430         for (i = ws_count, len = ARR_LEN(starters); i < len; ++i) {
431                 irn = starters[i].irn;
432                 if (!is_Phi(irn) || get_nodes_block(irn) != block)
433                         continue;
434
435                 be_spill_phi(env->senv, irn);
436         }
437
438         DEL_ARR_F(starters);
439 }
440
441 /**
442  * Collects all values live-in at block @p blk and all phi results in this block.
443  * Then it adds the best values (at most n_regs) to the blocks start_workset.
444  * The phis among the remaining values get spilled: Introduce psudo-copies of
445  *  their args to break interference and make it possible to spill them to the
446  *  same spill slot.
447  */
448 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
449         ir_node *pred_block;
450         block_info_t *res, *pred_info;
451
452         /* Have we seen this block before? */
453         res = get_block_info(block);
454         if (res)
455                 return res;
456
457         /* Create the block info for this block. */
458         res = new_block_info(&env->ob);
459         set_block_info(block, res);
460
461         /* Use endset of predecessor block as startset */
462         assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
463         pred_block = get_Block_cfgpred_block(block, 0);
464         pred_info = get_block_info(pred_block);
465
466         /* if pred block has not been processed yet, do it now */
467         if (pred_info == NULL || pred_info->processed == 0) {
468                 belady(pred_block, env);
469                 pred_info = get_block_info(pred_block);
470         }
471
472         /* now we have an end_set of pred */
473         assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
474         res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
475
476         return res;
477 }
478
479
480 /**
481  * For the given block @p blk, decide for each values
482  * whether it is used from a register or is reloaded
483  * before the use.
484  */
485 static void belady(ir_node *block, void *data) {
486         belady_env_t *env = data;
487         workset_t *new_vals;
488         ir_node *irn;
489         int iter;
490         block_info_t *block_info;
491
492         /* make sure we have blockinfo (with startset) */
493         block_info = get_block_info(block);
494         if (block_info == NULL)
495                 block_info = compute_block_start_info(env, block);
496
497         /* Don't do a block twice */
498         if(block_info->processed)
499                 return;
500
501         /* get the starting workset for this block */
502         DBG((dbg, DBG_DECIDE, "\n"));
503         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
504
505         workset_copy(env, env->ws, block_info->ws_start);
506         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
507         workset_foreach(env->ws, irn, iter)
508                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
509
510         /* process the block from start to end */
511         DBG((dbg, DBG_WSETS, "Processing...\n"));
512         env->used = pset_new_ptr_default();
513         env->instr_nr = 0;
514         new_vals = new_workset(env, &env->ob);
515         sched_foreach(block, irn) {
516                 int i, arity;
517                 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
518
519                 /* projs are handled with the tuple value.
520                  * Phis are no real instr (see insert_starters())
521                  * instr_nr does not increase */
522                 if (is_Proj(irn) || is_Phi(irn)) {
523                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
524                         continue;
525                 }
526                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
527
528                 /* set instruction in the workset */
529                 env->instr = irn;
530
531                 /* allocate all values _used_ by this instruction */
532                 workset_clear(new_vals);
533                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
534                         workset_insert(env, new_vals, get_irn_n(irn, i));
535                 }
536                 displace(env, new_vals, 1);
537
538                 /* allocate all values _defined_ by this instruction */
539                 workset_clear(new_vals);
540                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
541                         ir_node *proj;
542                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
543                                 workset_insert(env, new_vals, proj);
544                 } else {
545                         workset_insert(env, new_vals, irn);
546                 }
547                 displace(env, new_vals, 0);
548
549                 env->instr_nr++;
550         }
551         del_pset(env->used);
552
553         /* Remember end-workset for this block */
554         block_info->ws_end = workset_clone(env, &env->ob, env->ws);
555         block_info->processed = 1;
556         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
557         workset_foreach(block_info->ws_end, irn, iter)
558                 DBG((dbg, DBG_WSETS, "  %+F\n", irn));
559 }
560
561 /**
562  * 'decide' is block-local and makes assumptions
563  * about the set of live-ins. Thus we must adapt the
564  * live-outs to the live-ins at each block-border.
565  */
566 static void fix_block_borders(ir_node *blk, void *data) {
567         belady_env_t *env = data;
568         workset_t *wsb;
569         int i, max, iter, iter2;
570
571         DBG((dbg, DBG_FIX, "\n"));
572         DBG((dbg, DBG_FIX, "Fixing %+F\n", blk));
573
574         wsb = get_block_info(blk)->ws_start;
575
576         /* process all pred blocks */
577         for (i=0, max=get_irn_arity(blk); i<max; ++i) {
578                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(blk, i);
579                 workset_t *wsp = get_block_info(pred)->ws_end;
580
581                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
582
583                 workset_foreach(wsb, irnb, iter) {
584                         /* if irnb is a phi of the current block we reload
585                          * the corresponding argument, else irnb itself */
586                         if(is_Phi(irnb) && blk == get_nodes_block(irnb)) {
587                                 irnb = get_irn_n(irnb, i);
588
589                                 // we might have unknowns as argument for the phi
590                                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irnb))
591                                         continue;
592                         }
593
594                         /* Unknowns are available everywhere */
595                         if(get_irn_opcode(irnb) == iro_Unknown)
596                                 continue;
597
598                         /* check if irnb is in a register at end of pred */
599                         workset_foreach(wsp, irnp, iter2) {
600                                 if (irnb == irnp)
601                                         goto next_value;
602                         }
603
604                         /* irnb is not in memory at the end of pred, so we have to reload it */
605                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
606                         be_add_reload_on_edge(env->senv, irnb, blk, i);
607
608 next_value:
609                         /*epsilon statement :)*/;
610                 }
611         }
612 }
613
614 void be_spill_belady(const be_chordal_env_t *chordal_env) {
615         be_spill_belady_spill_env(chordal_env, NULL);
616 }
617
618 void be_spill_belady_spill_env(const be_chordal_env_t *chordal_env, spill_env_t *spill_env) {
619         belady_env_t env;
620
621         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
622         //firm_dbg_set_mask(dbg, DBG_WSETS);
623
624         /* init belady env */
625         obstack_init(&env.ob);
626         env.cenv      = chordal_env;
627         env.arch      = chordal_env->birg->main_env->arch_env;
628         env.cls       = chordal_env->cls;
629         env.n_regs    = arch_count_non_ignore_regs(env.arch, env.cls);
630         env.ws        = new_workset(&env, &env.ob);
631         env.uses      = be_begin_uses(chordal_env->irg, chordal_env->lv, chordal_env->birg->main_env->arch_env, env.cls);
632         if(spill_env == NULL) {
633                 env.senv = be_new_spill_env(chordal_env);
634         } else {
635                 env.senv = spill_env;
636         }
637         DEBUG_ONLY(be_set_spill_env_dbg_module(env.senv, dbg);)
638
639         DBG((dbg, LEVEL_1, "running on register class: %s\n", env.cls->name));
640
641         be_clear_links(chordal_env->irg);
642         /* Decide which phi nodes will be spilled and place copies for them into the graph */
643         irg_block_walk_graph(chordal_env->irg, spill_phi_walker, NULL, &env);
644         /* Fix high register pressure with belady algorithm */
645         irg_block_walk_graph(chordal_env->irg, NULL, belady, &env);
646         /* belady was block-local, fix the global flow by adding reloads on the edges */
647         irg_block_walk_graph(chordal_env->irg, fix_block_borders, NULL, &env);
648         /* Insert spill/reload nodes into the graph and fix usages */
649         be_insert_spills_reloads(env.senv);
650
651         be_remove_dead_nodes_from_schedule(chordal_env->irg);
652         be_liveness_recompute(chordal_env->lv);
653
654         /* clean up */
655         if(spill_env == NULL)
656                 be_delete_spill_env(env.senv);
657         be_end_uses(env.uses);
658         obstack_free(&env.ob, NULL);
659 }