ia32: Simplify ia32_register_saved_by().
[libfirm] / ir / be / bespillbelady.c
1 /*
2  * Copyright (C) 1995-2011 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  */
26 #include "config.h"
27
28 #include <stdbool.h>
29
30 #include "obst.h"
31 #include "irgraph.h"
32 #include "irnode.h"
33 #include "irmode.h"
34 #include "irgwalk.h"
35 #include "irloop.h"
36 #include "iredges_t.h"
37 #include "ircons_t.h"
38 #include "irprintf.h"
39 #include "irnodeset.h"
40 #include "irtools.h"
41 #include "statev_t.h"
42 #include "util.h"
43
44 #include "beutil.h"
45 #include "bearch.h"
46 #include "beuses.h"
47 #include "besched.h"
48 #include "beirgmod.h"
49 #include "belive_t.h"
50 #include "benode.h"
51 #include "bechordal_t.h"
52 #include "bespill.h"
53 #include "beloopana.h"
54 #include "beirg.h"
55 #include "bespillutil.h"
56 #include "bemodule.h"
57
58 #define DBG_SPILL     1
59 #define DBG_WSETS     2
60 #define DBG_FIX       4
61 #define DBG_DECIDE    8
62 #define DBG_START    16
63 #define DBG_SLOTS    32
64 #define DBG_TRACE    64
65 #define DBG_WORKSET 128
66 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
67
68 #define TIME_UNDEFINED 6666
69
70 /**
71  * An association between a node and a point in time.
72  */
73 typedef struct loc_t {
74         ir_node          *node;
75         unsigned          time;     /**< A use time (see beuses.h). */
76         bool              spilled;  /**< value was already spilled on this path */
77 } loc_t;
78
79 typedef struct workset_t {
80         unsigned len;     /**< current length */
81         loc_t    vals[];  /**< array of the values/distances in this working set */
82 } workset_t;
83
84 static struct obstack               obst;
85 static const arch_register_class_t *cls;
86 static const be_lv_t               *lv;
87 static be_loopana_t                *loop_ana;
88 static unsigned                     n_regs;
89 static workset_t                   *ws;     /**< the main workset used while
90                                                      processing a block. */
91 static be_uses_t                   *uses;   /**< env for the next-use magic */
92 static spill_env_t                 *senv;   /**< see bespill.h */
93 static ir_node                    **blocklist;
94
95 static int                          move_spills      = true;
96 static int                          respectloopdepth = true;
97 static int                          improve_known_preds = true;
98 /* factor to weight the different costs of reloading/rematerializing a node
99    (see bespill.h be_get_reload_costs_no_weight) */
100 static int                          remat_bonus      = 10;
101
102 static const lc_opt_table_entry_t options[] = {
103         LC_OPT_ENT_BOOL   ("movespills", "try to move spills out of loops", &move_spills),
104         LC_OPT_ENT_BOOL   ("respectloopdepth", "outermost loop cutting", &respectloopdepth),
105         LC_OPT_ENT_BOOL   ("improveknownpreds", "known preds cutting", &improve_known_preds),
106         LC_OPT_ENT_INT    ("rematbonus", "give bonus to rematerialisable nodes", &remat_bonus),
107         LC_OPT_LAST
108 };
109
110 /**
111  * Alloc a new workset on obstack @p ob with maximum size @p max
112  */
113 static workset_t *new_workset(void)
114 {
115         return OALLOCFZ(&obst, workset_t, vals, n_regs);
116 }
117
118 /**
119  * Alloc a new instance on obstack and make it equal to @param workset
120  */
121 static workset_t *workset_clone(workset_t *workset)
122 {
123         workset_t *res = OALLOCF(&obst, workset_t, vals, n_regs);
124         memcpy(res, workset, sizeof(*res) + n_regs * sizeof(res->vals[0]));
125         return res;
126 }
127
128 /**
129  * Copy workset @param src to @param tgt
130  */
131 static void workset_copy(workset_t *dest, const workset_t *src)
132 {
133         size_t size = sizeof(*src) + n_regs * sizeof(src->vals[0]);
134         memcpy(dest, src, size);
135 }
136
137 /**
138  * Overwrites the current content array of @param ws with the
139  * @param count locations given at memory @param locs.
140  * Set the length of @param ws to count.
141  */
142 static void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs)
143 {
144         workset->len = count;
145         memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
146 }
147
148 /**
149  * Inserts the value @p val into the workset, iff it is not
150  * already contained. The workset must not be full.
151  */
152 static void workset_insert(workset_t *workset, ir_node *val, bool spilled)
153 {
154         loc_t    *loc;
155         unsigned  i;
156         /* check for current regclass */
157         assert(arch_irn_consider_in_reg_alloc(cls, val));
158
159         /* check if val is already contained */
160         for (i = 0; i < workset->len; ++i) {
161                 loc = &workset->vals[i];
162                 if (loc->node == val) {
163                         if (spilled) {
164                                 loc->spilled = true;
165                         }
166                         return;
167                 }
168         }
169
170         /* insert val */
171         assert(workset->len < n_regs && "Workset already full!");
172         loc           = &workset->vals[workset->len];
173         loc->node     = val;
174         loc->spilled  = spilled;
175         loc->time     = TIME_UNDEFINED;
176         workset->len++;
177 }
178
179 /**
180  * Removes all entries from this workset
181  */
182 static void workset_clear(workset_t *workset)
183 {
184         workset->len = 0;
185 }
186
187 /**
188  * Removes the value @p val from the workset if present.
189  */
190 static void workset_remove(workset_t *workset, ir_node *val)
191 {
192         unsigned i;
193         for (i = 0; i < workset->len; ++i) {
194                 if (workset->vals[i].node == val) {
195                         workset->vals[i] = workset->vals[--workset->len];
196                         return;
197                 }
198         }
199 }
200
201 static const loc_t *workset_contains(const workset_t *ws, const ir_node *val)
202 {
203         unsigned i;
204         for (i = 0; i < ws->len; ++i) {
205                 if (ws->vals[i].node == val)
206                         return &ws->vals[i];
207         }
208
209         return NULL;
210 }
211
212 static int loc_compare(const void *a, const void *b)
213 {
214         const loc_t   *p  = ((const loc_t*) a);
215         const loc_t   *q  = ((const loc_t*) b);
216         const unsigned pt = p->time;
217         const unsigned qt = q->time;
218
219         if (pt < qt)
220                 return -1;
221         if (pt > qt)
222                 return 1;
223
224         return get_irn_node_nr(p->node) - get_irn_node_nr(q->node);
225 }
226
227 static void workset_sort(workset_t *workset)
228 {
229         qsort(workset->vals, workset->len, sizeof(workset->vals[0]), loc_compare);
230 }
231
232 static inline unsigned workset_get_time(const workset_t *workset, unsigned idx)
233 {
234         return workset->vals[idx].time;
235 }
236
237 static inline void workset_set_time(workset_t *workset, unsigned idx,
238                                     unsigned time)
239 {
240         workset->vals[idx].time = time;
241 }
242
243 static inline unsigned workset_get_length(const workset_t *workset)
244 {
245         return workset->len;
246 }
247
248 static inline void workset_set_length(workset_t *workset, unsigned len)
249 {
250         workset->len = len;
251 }
252
253 static inline ir_node *workset_get_val(const workset_t *workset, unsigned idx)
254 {
255         return workset->vals[idx].node;
256 }
257
258 /**
259  * Iterates over all values in the working set.
260  * @p ws The workset to iterate
261  * @p v  A variable to put the current value in
262  * @p i  An integer for internal use
263  */
264 #define workset_foreach(ws, v, i) \
265         for (i=0; v=(i < ws->len) ? ws->vals[i].node : NULL, i < ws->len; ++i)
266
267 typedef struct block_info_t {
268         workset_t *start_workset;
269         workset_t *end_workset;
270 } block_info_t;
271
272 static block_info_t *new_block_info(void)
273 {
274         return OALLOCZ(&obst, block_info_t);
275 }
276
277 static inline block_info_t *get_block_info(const ir_node *block)
278 {
279         return (block_info_t*)get_irn_link(block);
280 }
281
282 static inline void set_block_info(ir_node *block, block_info_t *info)
283 {
284         set_irn_link(block, info);
285 }
286
287 /**
288  * @return The distance to the next use or 0 if irn has dont_spill flag set
289  */
290 static unsigned get_distance(ir_node *from, const ir_node *def, int skip_from_uses)
291 {
292         be_next_use_t use;
293         unsigned      costs;
294         unsigned      time;
295
296         assert(!arch_irn_is_ignore(def));
297
298         use  = be_get_next_use(uses, from, def, skip_from_uses);
299         time = use.time;
300         if (USES_IS_INFINITE(time))
301                 return USES_INFINITY;
302
303         /* We have to keep nonspillable nodes in the workingset */
304         if (arch_get_irn_flags(skip_Proj_const(def)) & arch_irn_flags_dont_spill)
305                 return 0;
306
307         /* give some bonus to rematerialisable nodes */
308         if (remat_bonus > 0) {
309                 costs = be_get_reload_costs_no_weight(senv, def, use.before);
310                 assert(costs * remat_bonus < 1000);
311                 time  += 1000 - (costs * remat_bonus);
312         }
313
314         return time;
315 }
316
317 /**
318  * Performs the actions necessary to grant the request that:
319  * - new_vals can be held in registers
320  * - as few as possible other values are disposed
321  * - the worst values get disposed
322  *
323  * @p is_usage indicates that the values in new_vals are used (not defined)
324  * In this case reloads must be performed
325  */
326 static void displace(workset_t *const new_vals, int const is_usage, ir_node *const instr)
327 {
328         ir_node **to_insert = ALLOCAN(ir_node*, n_regs);
329         bool     *spilled   = ALLOCAN(bool,     n_regs);
330         ir_node  *val;
331         int       i;
332         int       len;
333         int       spills_needed;
334         int       demand;
335         unsigned  iter;
336
337         /* 1. Identify the number of needed slots and the values to reload */
338         demand = 0;
339         workset_foreach(new_vals, val, iter) {
340                 bool reloaded = false;
341
342                 if (! workset_contains(ws, val)) {
343                         DB((dbg, DBG_DECIDE, "    insert %+F\n", val));
344                         if (is_usage) {
345                                 DB((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, instr));
346                                 be_add_reload(senv, val, instr, cls, 1);
347                                 reloaded = true;
348                         }
349                 } else {
350                         DB((dbg, DBG_DECIDE, "    %+F already in workset\n", val));
351                         assert(is_usage);
352                         /* remove the value from the current workset so it is not accidently
353                          * spilled */
354                         workset_remove(ws, val);
355                 }
356                 spilled[demand]   = reloaded;
357                 to_insert[demand] = val;
358                 ++demand;
359         }
360
361         /* 2. Make room for at least 'demand' slots */
362         len           = workset_get_length(ws);
363         spills_needed = len + demand - n_regs;
364         assert(spills_needed <= len);
365
366         /* Only make more free room if we do not have enough */
367         if (spills_needed > 0) {
368                 DB((dbg, DBG_DECIDE, "    disposing %d values\n", spills_needed));
369
370                 /* calculate current next-use distance for live values */
371                 for (i = 0; i < len; ++i) {
372                         ir_node  *val  = workset_get_val(ws, i);
373                         unsigned  dist = get_distance(instr, val, !is_usage);
374                         workset_set_time(ws, i, dist);
375                 }
376
377                 /* sort entries by increasing nextuse-distance*/
378                 workset_sort(ws);
379
380                 for (i = len - spills_needed; i < len; ++i) {
381                         ir_node *val = ws->vals[i].node;
382
383                         DB((dbg, DBG_DECIDE, "    disposing node %+F (%u)\n", val,
384                              workset_get_time(ws, i)));
385
386                         if (move_spills) {
387                                 if (!USES_IS_INFINITE(ws->vals[i].time)
388                                                 && !ws->vals[i].spilled) {
389                                         ir_node *after_pos = sched_prev(instr);
390                                         DB((dbg, DBG_DECIDE, "Spill %+F after node %+F\n", val,
391                                                 after_pos));
392                                         be_add_spill(senv, val, after_pos);
393                                 }
394                         }
395                 }
396
397                 /* kill the last 'demand' entries in the array */
398                 workset_set_length(ws, len - spills_needed);
399         }
400
401         /* 3. Insert the new values into the workset */
402         for (i = 0; i < demand; ++i) {
403                 ir_node *val = to_insert[i];
404
405                 workset_insert(ws, val, spilled[i]);
406         }
407 }
408
409 enum {
410         AVAILABLE_EVERYWHERE,
411         AVAILABLE_NOWHERE,
412         AVAILABLE_PARTLY,
413         AVAILABLE_UNKNOWN
414 };
415
416 static unsigned available_in_all_preds(workset_t* const* pred_worksets,
417                                        size_t n_pred_worksets,
418                                        const ir_node *value, bool is_local_phi)
419 {
420         size_t i;
421         bool   avail_everywhere = true;
422         bool   avail_nowhere    = true;
423
424         assert(n_pred_worksets > 0);
425
426         /* value available in all preds? */
427         for (i = 0; i < n_pred_worksets; ++i) {
428                 bool             found     = false;
429                 const workset_t *p_workset = pred_worksets[i];
430                 int              p_len     = workset_get_length(p_workset);
431                 int              p_i;
432                 const ir_node   *l_value;
433
434                 if (is_local_phi) {
435                         assert(is_Phi(value));
436                         l_value = get_irn_n(value, i);
437                 } else {
438                         l_value = value;
439                 }
440
441                 for (p_i = 0; p_i < p_len; ++p_i) {
442                         const loc_t *p_l = &p_workset->vals[p_i];
443                         if (p_l->node != l_value)
444                                 continue;
445
446                         found = true;
447                         break;
448                 }
449
450                 if (found) {
451                         avail_nowhere = false;
452                 } else {
453                         avail_everywhere = false;
454                 }
455         }
456
457         if (avail_everywhere) {
458                 assert(!avail_nowhere);
459                 return AVAILABLE_EVERYWHERE;
460         } else if (avail_nowhere) {
461                 return AVAILABLE_NOWHERE;
462         } else {
463                 return AVAILABLE_PARTLY;
464         }
465 }
466
467 /** Decides whether a specific node should be in the start workset or not
468  *
469  * @param env      belady environment
470  * @param first
471  * @param node     the node to test
472  * @param loop     the loop of the node
473  */
474 static loc_t to_take_or_not_to_take(ir_node* first, ir_node *node,
475                                     ir_loop *loop, unsigned available)
476 {
477         be_next_use_t next_use;
478         loc_t         loc;
479
480         loc.time    = USES_INFINITY;
481         loc.node    = node;
482         loc.spilled = false;
483
484         /* We have to keep nonspillable nodes in the workingset */
485         if (arch_get_irn_flags(skip_Proj_const(node)) & arch_irn_flags_dont_spill) {
486                 loc.time = 0;
487                 DB((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
488                 return loc;
489         }
490
491         next_use = be_get_next_use(uses, first, node, 0);
492         if (USES_IS_INFINITE(next_use.time)) {
493                 /* the nodes marked as live in shouldn't be dead, so it must be a phi */
494                 assert(is_Phi(node));
495                 loc.time = USES_INFINITY;
496                 DB((dbg, DBG_START, "    %+F not taken (dead)\n", node));
497                 return loc;
498         }
499
500         loc.time = next_use.time;
501
502         if (improve_known_preds) {
503                 if (available == AVAILABLE_EVERYWHERE) {
504                         DB((dbg, DBG_START, "    %+F taken (%u, live in all preds)\n",
505                             node, loc.time));
506                         return loc;
507                 } else if (available == AVAILABLE_NOWHERE) {
508                         DB((dbg, DBG_START, "    %+F not taken (%u, live in no pred)\n",
509                             node, loc.time));
510                         loc.time = USES_INFINITY;
511                         return loc;
512                 }
513         }
514
515         if (!respectloopdepth || next_use.outermost_loop >= get_loop_depth(loop)) {
516                 DB((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time,
517                     next_use.outermost_loop));
518         } else {
519                 loc.time = USES_PENDING;
520                 DB((dbg, DBG_START, "    %+F delayed (outerdepth %d < loopdepth %d)\n",
521                     node, next_use.outermost_loop, get_loop_depth(loop)));
522         }
523
524         return loc;
525 }
526
527 /**
528  * Computes the start-workset for a block with multiple predecessors. We assume
529  * that at least 1 of the predeccesors is a back-edge which means we're at the
530  * beginning of a loop. We try to reload as much values as possible now so they
531  * don't get reloaded inside the loop.
532  */
533 static void decide_start_workset(const ir_node *block)
534 {
535         ir_loop    *loop = get_irn_loop(block);
536         ir_node    *first;
537         loc_t       loc;
538         loc_t      *starters;
539         loc_t      *delayed;
540         unsigned    len;
541         unsigned    i;
542         unsigned    ws_count;
543         int         free_slots, free_pressure_slots;
544         unsigned    pressure;
545         int         arity;
546         workset_t **pred_worksets;
547         bool        all_preds_known;
548
549         /* check predecessors */
550         arity           = get_irn_arity(block);
551         pred_worksets   = ALLOCAN(workset_t*, arity);
552         all_preds_known = true;
553         for (int in = 0; in < arity; ++in) {
554                 ir_node      *pred_block = get_Block_cfgpred_block(block, in);
555                 block_info_t *pred_info  = get_block_info(pred_block);
556
557                 if (pred_info == NULL) {
558                         pred_worksets[in] = NULL;
559                         all_preds_known   = false;
560                 } else {
561                         pred_worksets[in] = pred_info->end_workset;
562                 }
563         }
564
565         /* Collect all values living at start of block */
566         starters = NEW_ARR_F(loc_t, 0);
567         delayed  = NEW_ARR_F(loc_t, 0);
568
569         DB((dbg, DBG_START, "Living at start of %+F:\n", block));
570         first = sched_first(block);
571
572         /* check all Phis first */
573         sched_foreach(block, node) {
574                 unsigned available;
575
576                 if (! is_Phi(node))
577                         break;
578                 if (!arch_irn_consider_in_reg_alloc(cls, node))
579                         continue;
580
581                 if (all_preds_known) {
582                         available = available_in_all_preds(pred_worksets, arity, node, true);
583                 } else {
584                         available = AVAILABLE_UNKNOWN;
585                 }
586
587                 loc = to_take_or_not_to_take(first, node, loop, available);
588
589                 if (! USES_IS_INFINITE(loc.time)) {
590                         if (USES_IS_PENDING(loc.time))
591                                 ARR_APP1(loc_t, delayed, loc);
592                         else
593                                 ARR_APP1(loc_t, starters, loc);
594                 } else {
595                         be_spill_phi(senv, node);
596                 }
597         }
598
599         /* check all Live-Ins */
600         be_lv_foreach_cls(lv, block, be_lv_state_in, cls, node) {
601                 unsigned available;
602                 if (all_preds_known) {
603                         available = available_in_all_preds(pred_worksets, arity, node, false);
604                 } else {
605                         available = AVAILABLE_UNKNOWN;
606                 }
607
608                 loc = to_take_or_not_to_take(first, node, loop, available);
609
610                 if (! USES_IS_INFINITE(loc.time)) {
611                         if (USES_IS_PENDING(loc.time))
612                                 ARR_APP1(loc_t, delayed, loc);
613                         else
614                                 ARR_APP1(loc_t, starters, loc);
615                 }
616         }
617
618         pressure            = be_get_loop_pressure(loop_ana, cls, loop);
619         assert(ARR_LEN(delayed) <= pressure);
620         free_slots          = n_regs - ARR_LEN(starters);
621         free_pressure_slots = n_regs - (pressure - ARR_LEN(delayed));
622         free_slots          = MIN(free_slots, free_pressure_slots);
623
624         /* so far we only put nodes into the starters list that are used inside
625          * the loop. If register pressure in the loop is low then we can take some
626          * values and let them live through the loop */
627         DB((dbg, DBG_START, "Loop pressure %d, taking %d delayed vals\n",
628             pressure, free_slots));
629         if (free_slots > 0) {
630                 size_t i;
631
632                 qsort(delayed, ARR_LEN(delayed), sizeof(delayed[0]), loc_compare);
633
634                 for (i = 0; i < ARR_LEN(delayed) && free_slots > 0; ++i) {
635                         int    p, arity;
636                         loc_t *loc = & delayed[i];
637
638                         if (!is_Phi(loc->node)) {
639                                 /* don't use values which are dead in a known predecessors
640                                  * to not induce unnecessary reloads */
641                                 arity = get_irn_arity(block);
642                                 for (p = 0; p < arity; ++p) {
643                                         ir_node      *pred_block = get_Block_cfgpred_block(block, p);
644                                         block_info_t *pred_info  = get_block_info(pred_block);
645
646                                         if (pred_info == NULL)
647                                                 continue;
648
649                                         if (!workset_contains(pred_info->end_workset, loc->node)) {
650                                                 DB((dbg, DBG_START,
651                                                         "    delayed %+F not live at pred %+F\n", loc->node,
652                                                         pred_block));
653                                                 goto skip_delayed;
654                                         }
655                                 }
656                         }
657
658                         DB((dbg, DBG_START, "    delayed %+F taken\n", loc->node));
659                         ARR_APP1(loc_t, starters, *loc);
660                         loc->node = NULL;
661                         --free_slots;
662                 skip_delayed:
663                         ;
664                 }
665         }
666
667         /* spill phis (the actual phis not just their values) that are in this block
668          * but not in the start workset */
669         len = ARR_LEN(delayed);
670         for (i = 0; i < len; ++i) {
671                 ir_node *node = delayed[i].node;
672                 if (node == NULL || !is_Phi(node) || get_nodes_block(node) != block)
673                         continue;
674
675                 DB((dbg, DBG_START, "    spilling delayed phi %+F\n", node));
676                 be_spill_phi(senv, node);
677         }
678         DEL_ARR_F(delayed);
679
680         /* Sort start values by first use */
681         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
682
683         /* Copy the best ones from starters to start workset */
684         ws_count = MIN((unsigned) ARR_LEN(starters), n_regs);
685         workset_clear(ws);
686         workset_bulk_fill(ws, ws_count, starters);
687
688         /* spill phis (the actual phis not just their values) that are in this block
689          * but not in the start workset */
690         len = ARR_LEN(starters);
691         for (i = ws_count; i < len; ++i) {
692                 ir_node *node = starters[i].node;
693                 if (! is_Phi(node) || get_nodes_block(node) != block)
694                         continue;
695
696                 DB((dbg, DBG_START, "    spilling phi %+F\n", node));
697                 be_spill_phi(senv, node);
698         }
699
700         DEL_ARR_F(starters);
701
702         /* determine spill status of the values: If there's 1 pred block (which
703          * is no backedge) where the value is spilled then we must set it to
704          * spilled here. */
705         for (i = 0; i < ws_count; ++i) {
706                 loc_t   *loc     = &ws->vals[i];
707                 ir_node *value   = loc->node;
708                 bool     spilled;
709                 int      n;
710
711                 /* phis from this block aren't spilled */
712                 if (get_nodes_block(value) == block) {
713                         assert(is_Phi(value));
714                         loc->spilled = false;
715                         continue;
716                 }
717
718                 /* determine if value was spilled on any predecessor */
719                 spilled = false;
720                 for (n = 0; n < arity; ++n) {
721                         workset_t *pred_workset = pred_worksets[n];
722                         int        p_len;
723                         int        p;
724
725                         if (pred_workset == NULL)
726                                 continue;
727
728                         p_len = workset_get_length(pred_workset);
729                         for (p = 0; p < p_len; ++p) {
730                                 loc_t *l = &pred_workset->vals[p];
731
732                                 if (l->node != value)
733                                         continue;
734
735                                 if (l->spilled) {
736                                         spilled = true;
737                                 }
738                                 break;
739                         }
740                 }
741
742                 loc->spilled = spilled;
743         }
744 }
745
746 /**
747  * For the given block @p block, decide for each values
748  * whether it is used from a register or is reloaded
749  * before the use.
750  */
751 static void process_block(ir_node *block)
752 {
753         workset_t    *new_vals;
754         unsigned      iter;
755         block_info_t *block_info;
756         int           arity;
757
758         /* no need to process a block twice */
759         assert(get_block_info(block) == NULL);
760
761         /* construct start workset */
762         arity = get_Block_n_cfgpreds(block);
763         if (arity == 0) {
764                 /* no predecessor -> empty set */
765                 workset_clear(ws);
766         } else if (arity == 1) {
767                 /* one predecessor, copy its end workset */
768                 ir_node      *pred_block = get_Block_cfgpred_block(block, 0);
769                 block_info_t *pred_info  = get_block_info(pred_block);
770
771                 assert(pred_info != NULL);
772                 workset_copy(ws, pred_info->end_workset);
773         } else {
774                 /* multiple predecessors, do more advanced magic :) */
775                 decide_start_workset(block);
776         }
777
778         DB((dbg, DBG_DECIDE, "\n"));
779         DB((dbg, DBG_DECIDE, "Decide for %+F\n", block));
780
781         block_info = new_block_info();
782         set_block_info(block, block_info);
783
784         DB((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
785         {
786                 ir_node *irn;
787                 workset_foreach(ws, irn, iter) {
788                         DB((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(ws, iter)));
789                 }
790         }
791
792         block_info->start_workset = workset_clone(ws);
793
794         /* process the block from start to end */
795         DB((dbg, DBG_WSETS, "Processing...\n"));
796         /* TODO: this leaks (into the obstack)... */
797         new_vals = new_workset();
798
799         sched_foreach(block, irn) {
800                 assert(workset_get_length(ws) <= n_regs);
801
802                 /* Phis are no real instr (see insert_starters()) */
803                 if (is_Phi(irn)) {
804                         continue;
805                 }
806                 DB((dbg, DBG_DECIDE, "  ...%+F\n", irn));
807
808                 /* allocate all values _used_ by this instruction */
809                 workset_clear(new_vals);
810                 be_foreach_use(irn, cls, in_req_, in, in_req,
811                         /* (note that "spilled" is irrelevant here) */
812                         workset_insert(new_vals, in, false);
813                 );
814                 displace(new_vals, 1, irn);
815
816                 /* allocate all values _defined_ by this instruction */
817                 workset_clear(new_vals);
818                 be_foreach_definition(irn, cls, value, req,
819                         assert(req->width == 1);
820                         workset_insert(new_vals, value, false);
821                 );
822                 displace(new_vals, 0, irn);
823         }
824
825         /* Remember end-workset for this block */
826         block_info->end_workset = workset_clone(ws);
827         DB((dbg, DBG_WSETS, "End workset for %+F:\n", block));
828         {
829                 ir_node *irn;
830                 workset_foreach(ws, irn, iter)
831                         DB((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(ws, iter)));
832         }
833 }
834
835 /**
836  * 'decide' is block-local and makes assumptions
837  * about the set of live-ins. Thus we must adapt the
838  * live-outs to the live-ins at each block-border.
839  */
840 static void fix_block_borders(ir_node *block, void *data)
841 {
842         workset_t *start_workset;
843         int        arity;
844         int        i;
845         unsigned   iter;
846         (void) data;
847
848         DB((dbg, DBG_FIX, "\n"));
849         DB((dbg, DBG_FIX, "Fixing %+F\n", block));
850
851         arity = get_irn_arity(block);
852         /* can happen for endless loops */
853         if (arity == 0)
854                 return;
855
856         start_workset = get_block_info(block)->start_workset;
857
858         /* process all pred blocks */
859         for (i = 0; i < arity; ++i) {
860                 ir_node   *pred = get_Block_cfgpred_block(block, i);
861                 workset_t *pred_end_workset = get_block_info(pred)->end_workset;
862                 ir_node   *node;
863
864                 DB((dbg, DBG_FIX, "  Pred %+F\n", pred));
865
866                 /* spill all values not used anymore */
867                 workset_foreach(pred_end_workset, node, iter) {
868                         ir_node *n2;
869                         unsigned iter2;
870                         bool     found = false;
871                         workset_foreach(start_workset, n2, iter2) {
872                                 if (n2 == node) {
873                                         found = true;
874                                         break;
875                                 }
876                                 /* note that we do not look at phi inputs, becuase the values
877                                  * will be either live-end and need no spill or
878                                  * they have other users in which must be somewhere else in the
879                                  * workset */
880                         }
881
882                         if (found)
883                                 continue;
884
885                         if (move_spills && be_is_live_in(lv, block, node)
886                                         && !pred_end_workset->vals[iter].spilled) {
887                                 ir_node *insert_point;
888                                 if (arity > 1) {
889                                         insert_point = be_get_end_of_block_insertion_point(pred);
890                                         insert_point = sched_prev(insert_point);
891                                 } else {
892                                         insert_point = block;
893                                 }
894                                 DB((dbg, DBG_SPILL, "Spill %+F after %+F\n", node,
895                                      insert_point));
896                                 be_add_spill(senv, node, insert_point);
897                         }
898                 }
899
900                 /* reload missing values in predecessors, add missing spills */
901                 workset_foreach(start_workset, node, iter) {
902                         const loc_t *l    = &start_workset->vals[iter];
903                         const loc_t *pred_loc;
904
905                         /* if node is a phi of the current block we reload
906                          * the corresponding argument, else node itself */
907                         if (is_Phi(node) && get_nodes_block(node) == block) {
908                                 node = get_irn_n(node, i);
909                                 assert(!l->spilled);
910
911                                 /* we might have unknowns as argument for the phi */
912                                 if (!arch_irn_consider_in_reg_alloc(cls, node))
913                                         continue;
914                         }
915
916                         /* check if node is in a register at end of pred */
917                         pred_loc = workset_contains(pred_end_workset, node);
918                         if (pred_loc != NULL) {
919                                 /* we might have to spill value on this path */
920                                 if (move_spills && !pred_loc->spilled && l->spilled) {
921                                         ir_node *insert_point
922                                                 = be_get_end_of_block_insertion_point(pred);
923                                         insert_point = sched_prev(insert_point);
924                                         DB((dbg, DBG_SPILL, "Spill %+F after %+F\n", node,
925                                             insert_point));
926                                         be_add_spill(senv, node, insert_point);
927                                 }
928                         } else {
929                                 /* node is not in register at the end of pred -> reload it */
930                                 DB((dbg, DBG_FIX, "    reload %+F\n", node));
931                                 DB((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", node, block, i));
932                                 be_add_reload_on_edge(senv, node, block, i, cls, 1);
933                         }
934                 }
935         }
936 }
937
938 static void be_spill_belady(ir_graph *irg, const arch_register_class_t *rcls)
939 {
940         int i;
941
942         be_assure_live_sets(irg);
943
944         stat_ev_tim_push();
945         assure_loopinfo(irg);
946         stat_ev_tim_pop("belady_time_backedges");
947
948         stat_ev_tim_push();
949         be_clear_links(irg);
950         stat_ev_tim_pop("belady_time_clear_links");
951
952         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
953
954         /* init belady env */
955         stat_ev_tim_push();
956         obstack_init(&obst);
957         cls       = rcls;
958         lv        = be_get_irg_liveness(irg);
959         n_regs    = be_get_n_allocatable_regs(irg, cls);
960         ws        = new_workset();
961         uses      = be_begin_uses(irg, lv);
962         loop_ana  = be_new_loop_pressure(irg, cls);
963         senv      = be_new_spill_env(irg);
964         blocklist = be_get_cfgpostorder(irg);
965         stat_ev_tim_pop("belady_time_init");
966
967         stat_ev_tim_push();
968         /* walk blocks in reverse postorder */
969         for (i = ARR_LEN(blocklist) - 1; i >= 0; --i) {
970                 process_block(blocklist[i]);
971         }
972         DEL_ARR_F(blocklist);
973         stat_ev_tim_pop("belady_time_belady");
974
975         stat_ev_tim_push();
976         /* belady was block-local, fix the global flow by adding reloads on the
977          * edges */
978         irg_block_walk_graph(irg, fix_block_borders, NULL, NULL);
979         stat_ev_tim_pop("belady_time_fix_borders");
980
981         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
982
983         /* Insert spill/reload nodes into the graph and fix usages */
984         be_insert_spills_reloads(senv);
985
986         /* clean up */
987         be_delete_spill_env(senv);
988         be_end_uses(uses);
989         be_free_loop_pressure(loop_ana);
990         obstack_free(&obst, NULL);
991 }
992
993 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady)
994 void be_init_spillbelady(void)
995 {
996         static be_spiller_t belady_spiller = {
997                 be_spill_belady
998         };
999         lc_opt_entry_t *be_grp       = lc_opt_get_grp(firm_opt_get_root(), "be");
1000         lc_opt_entry_t *belady_group = lc_opt_get_grp(be_grp, "belady");
1001         lc_opt_add_table(belady_group, options);
1002
1003         be_register_spiller("belady", &belady_spiller);
1004         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
1005 }