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