copy the belady3 changes to belady (only cleanups so far, no new functionality yet)
[libfirm] / ir / be / bespillbelady.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Beladys spillalgorithm.
23  * @author      Daniel Grund, Matthias Braun
24  * @date        20.09.2005
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "obst.h"
32 #include "irprintf_t.h"
33 #include "irgraph.h"
34 #include "irnode.h"
35 #include "irmode.h"
36 #include "irgwalk.h"
37 #include "irloop.h"
38 #include "iredges_t.h"
39 #include "ircons_t.h"
40 #include "irprintf.h"
41 #include "irnodeset.h"
42 #include "xmalloc.h"
43 #include "pdeq.h"
44
45 #include "beutil.h"
46 #include "bearch_t.h"
47 #include "bespillbelady.h"
48 #include "beuses.h"
49 #include "besched_t.h"
50 #include "beirgmod.h"
51 #include "belive_t.h"
52 #include "benode_t.h"
53 #include "bechordal_t.h"
54 #include "bespilloptions.h"
55 #include "beloopana.h"
56 #include "beirg_t.h"
57 #include "bemodule.h"
58
59 #define DBG_SPILL     1
60 #define DBG_WSETS     2
61 #define DBG_FIX       4
62 #define DBG_DECIDE    8
63 #define DBG_START    16
64 #define DBG_SLOTS    32
65 #define DBG_TRACE    64
66 #define DBG_WORKSET 128
67 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
68
69 typedef enum {
70         value_not_reloaded,       /* the value has not been reloaded */
71         value_partially_reloaded, /* the value has been reloaded on some paths */
72         value_reloaded            /* the value has been reloaded on all paths */
73 } reloaded_state_t;
74
75 /**
76  * An association between a node and a point in time.
77  */
78 typedef struct loc_t {
79         ir_node          *node;
80         unsigned          time;     /**< A use time (see beuses.h). */
81         reloaded_state_t  reloaded; /**< the value is a reloaded value */
82 } loc_t;
83
84 typedef struct _workset_t {
85         int   len;          /**< current length */
86         loc_t vals[0];      /**< inlined array of the values/distances in this working set */
87 } workset_t;
88
89 static struct obstack               obst;
90 static const arch_env_t            *arch_env;
91 static const arch_register_class_t *cls;
92 static const be_lv_t               *lv;
93 static be_loopana_t                *loop_ana;
94 static int                          n_regs;
95 static workset_t                   *ws;     /**< the main workset used while
96                                                      processing a block. */
97 static be_uses_t                   *uses;   /**< env for the next-use magic */
98 static ir_node                     *instr;  /**< current instruction */
99 static unsigned                     instr_nr; /**< current instruction number
100                                                        (relative to block start) */
101 static ir_nodeset_t                 used;
102 static spill_env_t                 *senv;   /**< see bespill.h */
103 static pdeq                        *worklist;
104
105 static int loc_compare(const void *a, const void *b)
106 {
107         const loc_t *p = a;
108         const loc_t *q = b;
109         return p->time - q->time;
110 }
111
112 void workset_print(const workset_t *w)
113 {
114         int i;
115
116         for(i = 0; i < w->len; ++i) {
117                 ir_fprintf(stderr, "%+F %d\n", w->vals[i].node, w->vals[i].time);
118         }
119 }
120
121 /**
122  * Alloc a new workset on obstack @p ob with maximum size @p max
123  */
124 static workset_t *new_workset(void)
125 {
126         workset_t *res;
127         size_t     size = sizeof(*res) + n_regs * sizeof(res->vals[0]);
128
129         res  = obstack_alloc(&obst, size);
130         memset(res, 0, size);
131         return res;
132 }
133
134 /**
135  * Alloc a new instance on obstack and make it equal to @param workset
136  */
137 static workset_t *workset_clone(workset_t *workset)
138 {
139         workset_t *res;
140         size_t size = sizeof(*res) + n_regs * sizeof(res->vals[0]);
141         res = obstack_alloc(&obst, size);
142         memcpy(res, workset, size);
143         return res;
144 }
145
146 /**
147  * Copy workset @param src to @param tgt
148  */
149 static void workset_copy(workset_t *dest, const workset_t *src)
150 {
151         size_t size = sizeof(*src) + n_regs * sizeof(src->vals[0]);
152         memcpy(dest, src, size);
153 }
154
155 /**
156  * Overwrites the current content array of @param ws with the
157  * @param count locations given at memory @param locs.
158  * Set the length of @param ws to count.
159  */
160 static void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs)
161 {
162         workset->len = count;
163         memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
164 }
165
166 /**
167  * Inserts the value @p val into the workset, iff it is not
168  * already contained. The workset must not be full.
169  */
170 static void workset_insert(workset_t *workset, ir_node *val, int reloaded)
171 {
172         loc_t *loc;
173         int    i;
174         /* check for current regclass */
175         assert(arch_irn_consider_in_reg_alloc(arch_env, cls, val));
176
177         /* check if val is already contained */
178         for (i = 0; i < workset->len; ++i) {
179                 loc = &workset->vals[i];
180                 if (loc->node == val) {
181                         if(!loc->reloaded) {
182                                 loc->reloaded = reloaded;
183                         }
184                         return;
185                 }
186         }
187
188         /* insert val */
189         assert(workset->len < n_regs && "Workset already full!");
190         loc           = &workset->vals[workset->len];
191         loc->node     = val;
192         loc->reloaded = reloaded;
193         loc->time     = 6666; /* undefined yet */
194         workset->len++;
195 }
196
197 /**
198  * Removes all entries from this workset
199  */
200 static void workset_clear(workset_t *workset)
201 {
202         workset->len = 0;
203 }
204
205 /**
206  * Removes the value @p val from the workset if present.
207  */
208 static INLINE void workset_remove(workset_t *workset, ir_node *val)
209 {
210         int i;
211         for(i = 0; i < workset->len; ++i) {
212                 if (workset->vals[i].node == val) {
213                         workset->vals[i] = workset->vals[--workset->len];
214                         return;
215                 }
216         }
217 }
218
219 static INLINE int workset_contains(const workset_t *ws, const ir_node *val)
220 {
221         int i;
222
223         for(i=0; i<ws->len; ++i) {
224                 if (ws->vals[i].node == val)
225                         return 1;
226         }
227
228         return 0;
229 }
230
231 /**
232  * Iterates over all values in the working set.
233  * @p ws The workset to iterate
234  * @p v  A variable to put the current value in
235  * @p i  An integer for internal use
236  */
237 #define workset_foreach(ws, v, i)       for(i=0; \
238                                                                                 v=(i < ws->len) ? ws->vals[i].node : NULL, i < ws->len; \
239                                                                                 ++i)
240
241 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
242 #define workset_get_time(ws, i) (ws)->vals[i].time
243 #define workset_set_length(ws, length) (ws)->len = length
244 #define workset_get_length(ws) ((ws)->len)
245 #define workset_get_val(ws, i) ((ws)->vals[i].node)
246 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
247
248 typedef struct _block_info_t
249 {
250         workset_t *start_workset;
251         workset_t *end_workset;
252 } block_info_t;
253
254
255 static void *new_block_info(void)
256 {
257         block_info_t *res = obstack_alloc(&obst, sizeof(res[0]));
258         memset(res, 0, sizeof(res[0]));
259
260         return res;
261 }
262
263 #define get_block_info(block)        ((block_info_t *)get_irn_link(block))
264 #define set_block_info(block, info)  set_irn_link(block, info)
265
266 /**
267  * @return The distance to the next use or 0 if irn has dont_spill flag set
268  */
269 static INLINE unsigned get_distance(ir_node *from, unsigned from_step,
270                                     const ir_node *def, int skip_from_uses)
271 {
272         be_next_use_t use;
273         int           flags = arch_irn_get_flags(arch_env, def);
274         unsigned      time;
275
276         assert(! (flags & arch_irn_flags_ignore));
277
278         use = be_get_next_use(uses, from, from_step, def, skip_from_uses);
279         if(USES_IS_INFINITE(use.time))
280                 return USES_INFINITY;
281
282         /* We have to keep nonspillable nodes in the workingset */
283         if(flags & arch_irn_flags_dont_spill)
284                 return 0;
285
286         time  = use.time;
287         time += be_get_reload_costs_no_weight(senv, def, use.before) * 10;
288
289         return use.time;
290 }
291
292 /**
293  * Performs the actions necessary to grant the request that:
294  * - new_vals can be held in registers
295  * - as few as possible other values are disposed
296  * - the worst values get disposed
297  *
298  * @p is_usage indicates that the values in new_vals are used (not defined)
299  * In this case reloads must be performed
300  */
301 static void displace(workset_t *new_vals, int is_usage)
302 {
303         ir_node *val;
304         int     i, len, max_allowed, demand, iter;
305
306         ir_node   **to_insert = alloca(n_regs * sizeof(to_insert[0]));
307
308         /*
309                 1. Identify the number of needed slots and the values to reload
310         */
311         demand = 0;
312         workset_foreach(new_vals, val, iter) {
313                 /* mark value as used */
314                 if (is_usage)
315                         ir_nodeset_insert(&used, val);
316
317                 if (! workset_contains(ws, val)) {
318                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
319                         to_insert[demand++] = val;
320                         if (is_usage) {
321                                 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, instr));
322                                 be_add_reload(senv, val, instr, cls, 1);
323                         }
324                 } else {
325                         DBG((dbg, DBG_DECIDE, "    %+F already in workset\n", val));
326                         assert(is_usage);
327                 }
328         }
329
330         /*
331                 2. Make room for at least 'demand' slots
332         */
333         len         = workset_get_length(ws);
334         max_allowed = n_regs - demand;
335
336         /* Only make more free room if we do not have enough */
337         if (len > max_allowed) {
338                 DBG((dbg, DBG_DECIDE, "    disposing %d values\n",
339                      ws->len - max_allowed));
340
341                 /* get current next-use distance */
342                 for (i = 0; i < ws->len; ++i) {
343                         ir_node  *val  = workset_get_val(ws, i);
344                         unsigned  dist = get_distance(instr, instr_nr, val, !is_usage);
345                         workset_set_time(ws, i, dist);
346                 }
347
348                 /* sort entries by increasing nextuse-distance*/
349                 workset_sort(ws);
350
351                 /*
352                         Logic for not needed live-ins: If a value is disposed
353                         before its first usage, remove it from start workset
354                         We don't do this for phis though
355                 */
356                 for (i = max_allowed; i < ws->len; ++i) {
357                         ir_node *node = ws->vals[i].node;
358
359                         DBG((dbg, DBG_DECIDE, "    disposing node %+F (%u)\n", node,
360                              workset_get_time(ws, i)));
361
362                         if(!USES_IS_INFINITE(ws->vals[i].time)
363                                         && !ws->vals[i].reloaded) {
364                                 //be_add_spill(senv, node, instr);
365                         }
366
367             if (is_Phi(node))
368                 continue;
369
370                         if (! ir_nodeset_contains(&used, node)) {
371                                 ir_node   *curr_bb  = get_nodes_block(instr);
372                                 workset_t *ws_start = get_block_info(curr_bb)->start_workset;
373                                 workset_remove(ws_start, node);
374
375                                 DBG((dbg, DBG_DECIDE, "    (and removing %+F from start workset)\n", node));
376                         }
377                 }
378
379                 /* kill the last 'demand' entries in the array */
380                 workset_set_length(ws, max_allowed);
381         }
382
383         /*
384                 3. Insert the new values into the workset
385         */
386         for (i = 0; i < demand; ++i)
387                 workset_insert(ws, to_insert[i], 1);
388 }
389
390 /** Decides whether a specific node should be in the start workset or not
391  *
392  * @param env      belady environment
393  * @param first
394  * @param node     the node to test
395  * @param loop     the loop of the node
396  */
397 static loc_t to_take_or_not_to_take(ir_node* first, ir_node *node,
398                                     ir_loop *loop)
399 {
400         be_next_use_t next_use;
401         loc_t         loc;
402
403         loc.time     = USES_INFINITY;
404         loc.node     = node;
405         //loc.reloaded = rand() % 2; /* provoke a bug... */
406         loc.reloaded = 0;
407
408         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, node)) {
409                 loc.time = USES_INFINITY;
410                 return loc;
411         }
412
413         /* We have to keep nonspillable nodes in the workingset */
414         if(arch_irn_get_flags(arch_env, node) & arch_irn_flags_dont_spill) {
415                 loc.time = 0;
416                 DBG((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
417                 return loc;
418         }
419
420         next_use = be_get_next_use(uses, first, 0, node, 0);
421         if(USES_IS_INFINITE(next_use.time)) {
422                 // the nodes marked as live in shouldn't be dead, so it must be a phi
423                 assert(is_Phi(node));
424                 loc.time = USES_INFINITY;
425                 DBG((dbg, DBG_START, "    %+F not taken (dead)\n", node));
426                 if(is_Phi(node)) {
427                         be_spill_phi(senv, node);
428                 }
429                 return loc;
430         }
431
432         loc.time = next_use.time;
433
434         if(next_use.outermost_loop >= get_loop_depth(loop)) {
435                 DBG((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
436         } else {
437                 loc.time = USES_PENDING;
438                 DBG((dbg, DBG_START, "    %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
439         }
440         return loc;
441 }
442
443 /**
444  * Computes the start-workset for a block with multiple predecessors. We assume
445  * that at least 1 of the predeccesors is a back-edge which means we're at the
446  * beginning of a loop. We try to reload as much values as possible now so they
447  * don't get reloaded inside the loop.
448  */
449 static void compute_live_ins(const ir_node *block)
450 {
451         ir_loop    *loop = get_irn_loop(block);
452         ir_node    *first;
453         ir_node    *node;
454         loc_t       loc;
455         loc_t      *starters;
456         loc_t      *delayed;
457         int         i, len, ws_count;
458         int             free_slots, free_pressure_slots;
459         unsigned    pressure;
460         //int arity;
461         //int         n_pred_worksets;
462         //workset_t **pred_worksets;
463
464         /* Collect all values living at start of block */
465         starters = NEW_ARR_F(loc_t, 0);
466         delayed  = NEW_ARR_F(loc_t, 0);
467
468         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
469         first = sched_first(block);
470
471         /* check all Phis first */
472         sched_foreach(block, node) {
473                 if (! is_Phi(node))
474                         break;
475
476                 loc = to_take_or_not_to_take(first, node, loop);
477
478                 if (! USES_IS_INFINITE(loc.time)) {
479                         if (USES_IS_PENDING(loc.time))
480                                 ARR_APP1(loc_t, delayed, loc);
481                         else
482                                 ARR_APP1(loc_t, starters, loc);
483                 }
484         }
485
486         /* check all Live-Ins */
487         be_lv_foreach(lv, block, be_lv_state_in, i) {
488                 ir_node *node = be_lv_get_irn(lv, block, i);
489
490                 loc = to_take_or_not_to_take(first, node, loop);
491
492                 if (! USES_IS_INFINITE(loc.time)) {
493                         if (USES_IS_PENDING(loc.time))
494                                 ARR_APP1(loc_t, delayed, loc);
495                         else
496                                 ARR_APP1(loc_t, starters, loc);
497                 }
498         }
499
500         pressure            = be_get_loop_pressure(loop_ana, cls, loop);
501         assert(ARR_LEN(delayed) <= (signed)pressure);
502         free_slots          = n_regs - ARR_LEN(starters);
503         free_pressure_slots = n_regs - (pressure - ARR_LEN(delayed));
504         free_slots          = MIN(free_slots, free_pressure_slots);
505
506         /* so far we only put nodes into the starters list that are used inside
507          * the loop. If register pressure in the loop is low then we can take some
508          * values and let them live through the loop */
509         if(free_slots > 0) {
510                 qsort(delayed, ARR_LEN(delayed), sizeof(delayed[0]), loc_compare);
511
512                 for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
513                         DBG((dbg, DBG_START, "    delayed %+F taken\n", delayed[i].node));
514                         ARR_APP1(loc_t, starters, delayed[i]);
515                         delayed[i].node = NULL;
516                 }
517         }
518
519         /* spill phis (the actual phis not just their values) that are in this block
520          * but not in the start workset */
521         for (i = ARR_LEN(delayed) - 1; i >= 0; --i) {
522                 ir_node *node = delayed[i].node;
523                 if(node == NULL || !is_Phi(node) || get_nodes_block(node) != block)
524                         continue;
525
526                 DBG((dbg, DBG_START, "    spilling delayed phi %+F\n", node));
527                 be_spill_phi(senv, node);
528         }
529         DEL_ARR_F(delayed);
530
531         /* Sort start values by first use */
532         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
533
534         /* Copy the best ones from starters to start workset */
535         ws_count = MIN(ARR_LEN(starters), n_regs);
536         workset_clear(ws);
537         workset_bulk_fill(ws, ws_count, starters);
538
539         /* spill phis (the actual phis not just their values) that are in this block
540          * but not in the start workset */
541         len = ARR_LEN(starters);
542         for (i = ws_count; i < len; ++i) {
543                 ir_node *node = starters[i].node;
544                 if (! is_Phi(node) || get_nodes_block(node) != block)
545                         continue;
546
547                 DBG((dbg, DBG_START, "    spilling phi %+F\n", node));
548                 be_spill_phi(senv, node);
549         }
550
551         DEL_ARR_F(starters);
552
553 #if 0
554         /* determine reloaded status of the values: If there's 1 pred block (which
555          * is no backedge) where the value is reloaded then we must set it to
556          * reloaded here. We place spills in all pred where the value was not yet
557          * reloaded to be sure we have a spill on each path */
558         n_pred_worksets = 0;
559         arity           = get_irn_arity(block);
560         pred_worksets   = alloca(sizeof(pred_worksets[0]) * arity);
561         for(i = 0; i < arity; ++i) {
562                 ir_node      *pred_block = get_Block_cfgpred_block(block, i);
563                 block_info_t *pred_info  = get_block_info(pred_block);
564                 if(pred_info == NULL)
565                         continue;
566
567                 pred_worksets[n_pred_worksets] = pred_info->end_workset;
568                 ++n_pred_worksets;
569         }
570
571         for(i = 0; i < ws_count; ++i) {
572                 loc_t   *loc   = &ws->vals[i];
573                 ir_node *value = loc->node;
574                 int      reloaded;
575                 int      n;
576
577                 /* phis from this block aren't reloaded */
578                 if(get_nodes_block(value) == block) {
579                         assert(is_Phi(value));
580                         loc->reloaded = value_not_reloaded;
581                         continue;
582                 }
583
584                 /* was the value reloaded on any of the other inputs */
585                 reloaded = 0;
586                 arity    = get_Block_n_cfgpreds(block);
587                 for(n = 0; n < n_pred_worksets; ++n) {
588                         workset_t *pred_workset = pred_worksets[n];
589                         int        p_len        = workset_get_length(pred_workset);
590                         int        p;
591
592                         for(p = 0; p < p_len; ++p) {
593                                 loc_t *l = &pred_workset->vals[p];
594                                 if(l->node == value) {
595                                         if(l->reloaded) {
596                                                 reloaded = 1;
597                                         }
598                                         break;
599                                 }
600                         }
601                         if(p >= p_len) {
602                                 reloaded = 1;
603                                 break;
604                         }
605                 }
606         }
607 #endif
608 }
609
610 /**
611  * For the given block @p block, decide for each values
612  * whether it is used from a register or is reloaded
613  * before the use.
614  */
615 static void belady(ir_node *block)
616 {
617         workset_t       *new_vals;
618         ir_node         *irn;
619         int              iter;
620         block_info_t    *block_info;
621         int              i, arity;
622         int              has_backedges = 0;
623         //int              first         = 0;
624         const ir_edge_t *edge;
625
626         /* no need to process a block twice */
627         if(get_block_info(block) != NULL) {
628                 return;
629         }
630
631         /* check if all predecessor blocks are processed yet (though for backedges
632          * we have to make an exception as we can't process them first) */
633         arity = get_Block_n_cfgpreds(block);
634         for(i = 0; i < arity; ++i) {
635                 ir_node      *pred_block = get_Block_cfgpred_block(block, i);
636                 block_info_t *pred_info  = get_block_info(pred_block);
637
638                 if(pred_info == NULL) {
639                         /* process predecessor first (it will be in the queue already) */
640                         if(!is_backedge(block, i)) {
641                                 return;
642                         }
643                         has_backedges = 1;
644                 }
645         }
646         (void) has_backedges;
647         if(arity == 0) {
648                 workset_clear(ws);
649         } else if(arity == 1) {
650                 ir_node      *pred_block = get_Block_cfgpred_block(block, 0);
651                 block_info_t *pred_info  = get_block_info(pred_block);
652
653                 assert(pred_info != NULL);
654                 workset_copy(ws, pred_info->end_workset);
655         } else {
656                 /* we need 2 heuristics here, for the case when all predecessor blocks
657                  * are known and when some are backedges (and therefore can't be known
658                  * yet) */
659                 compute_live_ins(block);
660         }
661
662         DBG((dbg, DBG_DECIDE, "\n"));
663         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
664
665         block_info = new_block_info();
666         set_block_info(block, block_info);
667
668         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
669         workset_foreach(ws, irn, iter) {
670                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn,
671                      workset_get_time(ws, iter)));
672         }
673
674         block_info->start_workset = workset_clone(ws);
675
676         /* process the block from start to end */
677         DBG((dbg, DBG_WSETS, "Processing...\n"));
678         ir_nodeset_init(&used);
679         instr_nr = 0;
680         /* TODO: this leaks (into the obstack)... */
681         new_vals = new_workset();
682
683         sched_foreach(block, irn) {
684                 int i, arity;
685                 assert(workset_get_length(ws) <= n_regs);
686
687                 /* Phis are no real instr (see insert_starters()) */
688                 if (is_Phi(irn)) {
689                         continue;
690                 }
691                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
692
693                 /* set instruction in the workset */
694                 instr = irn;
695
696                 /* allocate all values _used_ by this instruction */
697                 workset_clear(new_vals);
698                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
699                         ir_node *in = get_irn_n(irn, i);
700                         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, in))
701                                 continue;
702
703                         /* (note that reloaded_value is irrelevant here) */
704                         workset_insert(new_vals, in, 0);
705                 }
706                 displace(new_vals, 1);
707
708                 /* allocate all values _defined_ by this instruction */
709                 workset_clear(new_vals);
710                 if (get_irn_mode(irn) == mode_T) {
711                         const ir_edge_t *edge;
712
713                         foreach_out_edge(irn, edge) {
714                                 ir_node *proj = get_edge_src_irn(edge);
715                                 if (!arch_irn_consider_in_reg_alloc(arch_env, cls, proj))
716                                         continue;
717                                 workset_insert(new_vals, proj, 0);
718                         }
719                 } else {
720                         if (!arch_irn_consider_in_reg_alloc(arch_env, cls, irn))
721                                 continue;
722                         workset_insert(new_vals, irn, 0);
723                 }
724                 displace(new_vals, 0);
725
726                 instr_nr++;
727         }
728         ir_nodeset_destroy(&used);
729
730         /* Remember end-workset for this block */
731         block_info->end_workset = workset_clone(ws);
732         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
733         workset_foreach(ws, irn, iter)
734                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn,
735                      workset_get_time(ws, iter)));
736
737         /* add successor blocks into worklist */
738         foreach_block_succ(block, edge) {
739                 ir_node *succ = get_edge_src_irn(edge);
740                 pdeq_putr(worklist, succ);
741         }
742 }
743
744 /**
745  * 'decide' is block-local and makes assumptions
746  * about the set of live-ins. Thus we must adapt the
747  * live-outs to the live-ins at each block-border.
748  */
749 static void fix_block_borders(ir_node *block, void *data)
750 {
751         workset_t    *start_workset;
752         int           arity;
753         int           i;
754         int           iter;
755         (void) data;
756
757         DBG((dbg, DBG_FIX, "\n"));
758         DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
759
760         start_workset = get_block_info(block)->start_workset;
761
762         /* process all pred blocks */
763         arity = get_irn_arity(block);
764         for (i = 0; i < arity; ++i) {
765                 ir_node   *pred = get_Block_cfgpred_block(block, i);
766                 workset_t *pred_end_workset = get_block_info(pred)->end_workset;
767                 ir_node   *node;
768
769                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
770
771                 /* spill all values not used anymore */
772                 workset_foreach(pred_end_workset, node, iter) {
773                         ir_node *n2;
774                         int      iter2;
775                         int      found = 0;
776                         workset_foreach(start_workset, n2, iter2) {
777                                 if(n2 == node) {
778                                         found = 1;
779                                         break;
780                                 }
781                                 /* note that we do not look at phi inputs, becuase the values
782                                  * will be either live-end and need no spill or
783                                  * they have other users in which must be somewhere else in the
784                                  * workset */
785                         }
786
787 #if 0
788                         if(!found && be_is_live_out(lv, pred, node)
789                                         && !pred_end_workset->vals[iter].reloaded) {
790                                 ir_node *insert_point
791                                         = be_get_end_of_block_insertion_point(pred);
792                                 DBG((dbg, DBG_SPILL, "Spill %+F before %+F\n", node,
793                                      insert_point));
794                                 be_add_spill(senv, node, insert_point);
795                         }
796 #endif
797                 }
798
799                 /* reload missing values in predecessors */
800                 workset_foreach(start_workset, node, iter) {
801                         /* if node is a phi of the current block we reload
802                          * the corresponding argument, else node itself */
803                         if(is_Phi(node) && block == get_nodes_block(node)) {
804                                 node = get_irn_n(node, i);
805
806                                 /* we might have unknowns as argument for the phi */
807                                 if(!arch_irn_consider_in_reg_alloc(arch_env, cls, node))
808                                         continue;
809                         }
810
811                         /* check if node is in a register at end of pred */
812                         if(workset_contains(pred_end_workset, node))
813                                 continue;
814
815                         /* node is not in memory at the end of pred -> reload it */
816                         DBG((dbg, DBG_FIX, "    reload %+F\n", node));
817                         DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
818                         be_add_reload_on_edge(senv, node, block, i, cls, 1);
819                 }
820         }
821 }
822
823 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *rcls)
824 {
825         ir_graph *irg = be_get_birg_irg(birg);
826
827         be_liveness_assure_sets(be_assure_liveness(birg));
828
829         /* construct control flow loop tree */
830         if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
831                 construct_cf_backedges(irg);
832         }
833
834         be_clear_links(irg);
835
836         /* init belady env */
837         obstack_init(&obst);
838         arch_env = birg->main_env->arch_env;
839         cls      = rcls;
840         lv       = be_get_birg_liveness(birg);
841         n_regs   = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
842         ws       = new_workset();
843         uses     = be_begin_uses(irg, lv);
844         loop_ana = be_new_loop_pressure(birg);
845         senv     = be_new_spill_env(birg);
846         worklist = new_pdeq();
847
848         pdeq_putr(worklist, get_irg_start_block(irg));
849
850         while(!pdeq_empty(worklist)) {
851                 ir_node *block = pdeq_getl(worklist);
852                 belady(block);
853         }
854         /* end block might not be reachable in endless loops */
855         belady(get_irg_end_block(irg));
856
857         del_pdeq(worklist);
858
859         /* belady was block-local, fix the global flow by adding reloads on the
860          * edges */
861         irg_block_walk_graph(irg, fix_block_borders, NULL, NULL);
862
863         /* Insert spill/reload nodes into the graph and fix usages */
864         be_insert_spills_reloads(senv);
865
866         /* clean up */
867         be_delete_spill_env(senv);
868         be_end_uses(uses);
869         be_free_loop_pressure(loop_ana);
870         obstack_free(&obst, NULL);
871 }
872
873 void be_init_spillbelady(void)
874 {
875         static be_spiller_t belady_spiller = {
876                 be_spill_belady
877         };
878
879         be_register_spiller("belady", &belady_spiller);
880         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
881 }
882
883 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);