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