added new licence header
[libfirm] / ir / be / bespillbelady.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * Author:      Daniel Grund, Matthias Braun
22  * Date:        20.09.2005
23  * Copyright:   (c) Universitaet Karlsruhe
24  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
25  *
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "obst.h"
32 #include "set.h"
33 #include "pset.h"
34 #include "irprintf_t.h"
35 #include "irgraph.h"
36 #include "irnode.h"
37 #include "irmode.h"
38 #include "irgwalk.h"
39 #include "irloop.h"
40 #include "iredges_t.h"
41 #include "ircons_t.h"
42 #include "irprintf.h"
43 #include "xmalloc.h"
44
45 #include "beutil.h"
46 #include "bearch_t.h"
47 #include "bespillbelady.h"
48 #include "beuses_t.h"
49 #include "besched_t.h"
50 #include "beirgmod.h"
51 #include "belive_t.h"
52 #include "benode_t.h"
53 #include "bechordal_t.h"
54 #include "bespilloptions.h"
55 #include "beloopana.h"
56
57 #define DBG_SPILL   1
58 #define DBG_WSETS   2
59 #define DBG_FIX     4
60 #define DBG_DECIDE  8
61 #define DBG_START  16
62 #define DBG_SLOTS  32
63 #define DBG_TRACE  64
64 #define DBG_WORKSET 128
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 /**
68  * An association between a node and a point in time.
69  */
70 typedef struct _loc_t {
71   ir_node *irn;        /**< A node. */
72   unsigned time;       /**< A use time (see beuses.h). */
73 } loc_t;
74
75 typedef struct _workset_t {
76         int len;                        /**< current length */
77         loc_t vals[0];          /**< inlined array of the values/distances in this working set */
78 } workset_t;
79
80 typedef struct _belady_env_t {
81         struct obstack ob;
82         const arch_env_t *arch;
83         const arch_register_class_t *cls;
84         const be_lv_t *lv;
85         be_loopana_t *loop_ana;
86         int n_regs;                     /** number of regs in this reg-class */
87
88         workset_t *ws;          /**< the main workset used while processing a block. ob-allocated */
89         be_uses_t *uses;        /**< env for the next-use magic */
90         ir_node *instr;         /**< current instruction */
91         unsigned instr_nr;      /**< current instruction number (relative to block start) */
92         pset *used;
93
94         spill_env_t *senv;      /**< see bespill.h */
95 } belady_env_t;
96
97 static int loc_compare(const void *a, const void *b)
98 {
99         const loc_t *p = a;
100         const loc_t *q = b;
101         return p->time - q->time;
102 }
103
104 static INLINE void workset_print(const workset_t *w)
105 {
106         int i;
107
108         for(i = 0; i < w->len; ++i) {
109                 ir_fprintf(stderr, "%+F %d\n", w->vals[i].irn, w->vals[i].time);
110         }
111 }
112
113 /**
114  * Alloc a new workset on obstack @p ob with maximum size @p max
115  */
116 static INLINE workset_t *new_workset(belady_env_t *env, struct obstack *ob) {
117         workset_t *res;
118         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
119         res = obstack_alloc(ob, size);
120         memset(res, 0, size);
121         return res;
122 }
123
124 /**
125  * Alloc a new instance on obstack and make it equal to @param ws
126  */
127 static INLINE workset_t *workset_clone(belady_env_t *env, struct obstack *ob, workset_t *ws) {
128         workset_t *res;
129         size_t size = sizeof(*res) + (env->n_regs)*sizeof(res->vals[0]);
130         res = obstack_alloc(ob, size);
131         memcpy(res, ws, size);
132         return res;
133 }
134
135 /**
136  * Do NOT alloc anything. Make @param tgt equal to @param src.
137  * returns @param tgt for convenience
138  */
139 static INLINE workset_t *workset_copy(belady_env_t *env, workset_t *tgt, workset_t *src) {
140         size_t size = sizeof(*src) + (env->n_regs)*sizeof(src->vals[0]);
141         memcpy(tgt, src, size);
142         return tgt;
143 }
144
145 /**
146  * Overwrites the current content array of @param ws with the
147  * @param count locations given at memory @param locs.
148  * Set the length of @param ws to count.
149  */
150 static INLINE void workset_bulk_fill(workset_t *workset, int count, const loc_t *locs) {
151         workset->len = count;
152         memcpy(&(workset->vals[0]), locs, count * sizeof(locs[0]));
153 }
154
155 /**
156  * Inserts the value @p val into the workset, iff it is not
157  * already contained. The workset must not be full.
158  */
159 static INLINE void workset_insert(belady_env_t *env, workset_t *ws, ir_node *val) {
160         int i;
161         /* check for current regclass */
162         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, val)) {
163                 DBG((dbg, DBG_WORKSET, "Skipped %+F\n", val));
164                 return;
165         }
166
167         /* check if val is already contained */
168         for(i=0; i<ws->len; ++i)
169                 if (ws->vals[i].irn == val)
170                         return;
171
172         /* insert val */
173         assert(ws->len < env->n_regs && "Workset already full!");
174         ws->vals[ws->len++].irn = val;
175 }
176
177 /**
178  * Removes all entries from this workset
179  */
180 static INLINE void workset_clear(workset_t *ws) {
181         ws->len = 0;
182 }
183
184 /**
185  * Removes the value @p val from the workset if present.
186  */
187 static INLINE void workset_remove(workset_t *ws, ir_node *val) {
188         int i;
189         for(i=0; i<ws->len; ++i) {
190                 if (ws->vals[i].irn == val) {
191                         ws->vals[i] = ws->vals[--ws->len];
192                         return;
193                 }
194         }
195 }
196
197 static INLINE int workset_contains(const workset_t *ws, const ir_node *val) {
198         int i;
199         for(i=0; i<ws->len; ++i) {
200                 if (ws->vals[i].irn == val)
201                         return 1;
202         }
203
204         return 0;
205 }
206
207 /**
208  * Iterates over all values in the working set.
209  * @p ws The workset to iterate
210  * @p v  A variable to put the current value in
211  * @p i  An integer for internal use
212  */
213 #define workset_foreach(ws, v, i)       for(i=0; \
214                                                                                 v=(i < ws->len) ? ws->vals[i].irn : NULL, i < ws->len; \
215                                                                                 ++i)
216
217 #define workset_set_time(ws, i, t) (ws)->vals[i].time=t
218 #define workset_get_time(ws, i) (ws)->vals[i].time
219 #define workset_set_length(ws, length) (ws)->len = length
220 #define workset_get_length(ws) ((ws)->len)
221 #define workset_get_val(ws, i) ((ws)->vals[i].irn)
222 #define workset_sort(ws) qsort((ws)->vals, (ws)->len, sizeof((ws)->vals[0]), loc_compare);
223
224 typedef struct _block_info_t {
225         workset_t *ws_start, *ws_end;
226         int processed;
227 } block_info_t;
228
229
230 static INLINE void *new_block_info(struct obstack *ob) {
231         block_info_t *res = obstack_alloc(ob, sizeof(*res));
232         res->ws_start = NULL;
233         res->ws_end = NULL;
234         res->processed = 0;
235
236         return res;
237 }
238
239 #define get_block_info(block)        ((block_info_t *)get_irn_link(block))
240 #define set_block_info(block, info)  set_irn_link(block, info)
241
242 /**
243  * @return The distance to the next use or 0 if irn has dont_spill flag set
244  */
245 static INLINE unsigned get_distance(belady_env_t *env, ir_node *from, unsigned from_step, const ir_node *def, int skip_from_uses)
246 {
247         be_next_use_t use;
248         int flags = arch_irn_get_flags(env->arch, def);
249
250         assert(! (flags & arch_irn_flags_ignore));
251
252         use = be_get_next_use(env->uses, from, from_step, def, skip_from_uses);
253         if(USES_IS_INFINITE(use.time))
254                 return USES_INFINITY;
255
256         /* We have to keep nonspillable nodes in the workingset */
257         if(flags & arch_irn_flags_dont_spill)
258                 return 0;
259
260         return use.time;
261 }
262
263 /**
264  * Performs the actions necessary to grant the request that:
265  * - new_vals can be held in registers
266  * - as few as possible other values are disposed
267  * - the worst values get disposed
268  *
269  * @p is_usage indicates that the values in new_vals are used (not defined)
270  * In this case reloads must be performed
271  */
272 static void displace(belady_env_t *env, workset_t *new_vals, int is_usage) {
273         ir_node *val;
274         int     i, len, max_allowed, demand, iter;
275
276         workset_t *ws         = env->ws;
277         ir_node   **to_insert = alloca(env->n_regs * sizeof(*to_insert));
278
279         /*
280                 1. Identify the number of needed slots and the values to reload
281         */
282         demand = 0;
283         workset_foreach(new_vals, val, iter) {
284                 /* mark value as used */
285                 if (is_usage)
286                         pset_insert_ptr(env->used, val);
287
288                 if (! workset_contains(ws, val)) {
289                         DBG((dbg, DBG_DECIDE, "    insert %+F\n", val));
290                         to_insert[demand++] = val;
291                         if (is_usage) {
292                                 DBG((dbg, DBG_SPILL, "Reload %+F before %+F\n", val, env->instr));
293                                 be_add_reload(env->senv, val, env->instr, env->cls, 1);
294                         }
295                 }
296                 else {
297                         assert(is_usage || "Defined value already in workset?!?");
298                         DBG((dbg, DBG_DECIDE, "    skip %+F\n", val));
299                 }
300         }
301         DBG((dbg, DBG_DECIDE, "    demand = %d\n", demand));
302
303         /*
304                 2. Make room for at least 'demand' slots
305         */
306         len         = workset_get_length(ws);
307         max_allowed = env->n_regs - demand;
308
309         DBG((dbg, DBG_DECIDE, "    disposing %d values\n", ws->len - max_allowed));
310
311         /* Only make more free room if we do not have enough */
312         if (len > max_allowed) {
313                 /* get current next-use distance */
314                 for (i = 0; i < ws->len; ++i) {
315                         unsigned dist = get_distance(env, env->instr, env->instr_nr, workset_get_val(ws, i), !is_usage);
316                         workset_set_time(ws, i, dist);
317                 }
318
319                 /* sort entries by increasing nextuse-distance*/
320                 workset_sort(ws);
321
322                 /*
323                         Logic for not needed live-ins: If a value is disposed
324                         before its first usage, remove it from start workset
325                         We don't do this for phis though
326                 */
327                 for (i = max_allowed; i < ws->len; ++i) {
328                         ir_node *irn = ws->vals[i].irn;
329
330                         DBG((dbg, DBG_DECIDE, "    disposing %+F (%u)\n", irn, workset_get_time(ws, i)));
331
332             if (is_Phi(irn))
333                 continue;
334
335                         if (! pset_find_ptr(env->used, irn)) {
336                                 ir_node   *curr_bb  = get_nodes_block(env->instr);
337                                 workset_t *ws_start = get_block_info(curr_bb)->ws_start;
338                                 workset_remove(ws_start, irn);
339
340                                 DBG((dbg, DBG_DECIDE, "    (and removing %+F from start workset)\n", irn));
341                         }
342                 }
343
344                 /* kill the last 'demand' entries in the array */
345                 workset_set_length(ws, max_allowed);
346         }
347
348         /*
349                 3. Insert the new values into the workset
350         */
351         for (i = 0; i < demand; ++i)
352                 workset_insert(env, env->ws, to_insert[i]);
353 }
354
355 static void belady(ir_node *block, void *env);
356
357 /** Decides whether a specific node should be in the start workset or not
358  *
359  * @param env      belady environment
360  * @param first
361  * @param node     the node to test
362  * @param block    the block of the node
363  * @param loop     the loop of the node
364  */
365 static loc_t to_take_or_not_to_take(belady_env_t *env, ir_node* first,
366                                             ir_node *node, ir_node *block,
367                                                                         ir_loop *loop)
368 {
369         be_next_use_t next_use;
370         loc_t loc;
371         loc.time = USES_INFINITY;
372         loc.irn = node;
373
374         if (!arch_irn_consider_in_reg_alloc(env->arch, env->cls, node)) {
375                 loc.time = USES_INFINITY;
376                 return loc;
377         }
378
379         /* We have to keep nonspillable nodes in the workingset */
380         if(arch_irn_get_flags(env->arch, node) & arch_irn_flags_dont_spill) {
381                 loc.time = 0;
382                 DBG((dbg, DBG_START, "    %+F taken (dontspill node)\n", node, loc.time));
383                 return loc;
384         }
385
386         next_use = be_get_next_use(env->uses, first, 0, node, 0);
387         if(USES_IS_INFINITE(next_use.time)) {
388                 // the nodes marked as live in shouldn't be dead, so it must be a phi
389                 assert(is_Phi(node));
390                 loc.time = USES_INFINITY;
391                 DBG((dbg, DBG_START, "    %+F not taken (dead)\n", node));
392                 if(is_Phi(node)) {
393                         be_spill_phi(env->senv, node);
394                 }
395                 return loc;
396         }
397
398         loc.time = next_use.time;
399
400         if(next_use.outermost_loop >= get_loop_depth(loop)) {
401                 DBG((dbg, DBG_START, "    %+F taken (%u, loop %d)\n", node, loc.time, next_use.outermost_loop));
402         } else {
403                 loc.time = USES_PENDING;
404                 DBG((dbg, DBG_START, "    %+F delayed (outerloopdepth %d < loopdetph %d)\n", node, next_use.outermost_loop, get_loop_depth(loop)));
405         }
406         return loc;
407 }
408
409 /*
410  * Computes set of live-ins for each block with multiple predecessors
411  * and notifies spill algorithm which phis need to be spilled
412  */
413 static void compute_live_ins(ir_node *block, void *data) {
414         belady_env_t  *env  = data;
415         ir_loop       *loop = get_irn_loop(block);
416         const be_lv_t *lv   = env->lv;
417         block_info_t  *block_info;
418         ir_node       *first, *irn;
419         loc_t         loc, *starters, *delayed;
420         int           i, len, ws_count;
421         int               free_slots, free_pressure_slots;
422         unsigned      pressure;
423
424         if (get_Block_n_cfgpreds(block) == 1 && get_irg_start_block(get_irn_irg(block)) != block)
425                 return;
426
427         block_info = new_block_info(&env->ob);
428         set_block_info(block, block_info);
429
430         /* Collect all values living at start of block */
431         starters = NEW_ARR_F(loc_t, 0);
432         delayed  = NEW_ARR_F(loc_t, 0);
433
434         DBG((dbg, DBG_START, "Living at start of %+F:\n", block));
435         first = sched_first(block);
436
437         /* check all Phis first */
438         sched_foreach(block, irn) {
439                 if (! is_Phi(irn))
440                         break;
441
442                 loc = to_take_or_not_to_take(env, first, irn, block, loop);
443
444                 if (! USES_IS_INFINITE(loc.time)) {
445                         if (USES_IS_PENDING(loc.time))
446                                 ARR_APP1(loc_t, delayed, loc);
447                         else
448                                 ARR_APP1(loc_t, starters, loc);
449                 }
450         }
451
452         /* check all Live-Ins */
453         be_lv_foreach(lv, block, be_lv_state_in, i) {
454                 ir_node *node = be_lv_get_irn(lv, block, i);
455
456                 loc = to_take_or_not_to_take(env, first, node, block, loop);
457
458                 if (! USES_IS_INFINITE(loc.time)) {
459                         if (USES_IS_PENDING(loc.time))
460                                 ARR_APP1(loc_t, delayed, loc);
461                         else
462                                 ARR_APP1(loc_t, starters, loc);
463                 }
464         }
465
466         pressure            = be_get_loop_pressure(env->loop_ana, env->cls, loop);
467         assert(ARR_LEN(delayed) <= (signed)pressure);
468         free_slots          = env->n_regs - ARR_LEN(starters);
469         free_pressure_slots = env->n_regs - (pressure - ARR_LEN(delayed));
470         free_slots          = MIN(free_slots, free_pressure_slots);
471         /* append nodes delayed due to loop structure until start set is full */
472         for (i = 0; i < ARR_LEN(delayed) && i < free_slots; ++i) {
473                 DBG((dbg, DBG_START, "    delayed %+F taken\n", delayed[i].irn));
474                 ARR_APP1(loc_t, starters, delayed[i]);
475                 delayed[i].irn = NULL;
476         }
477
478         /* spill all delayed phis which didn't make it into start workset */
479         for (i = ARR_LEN(delayed) - 1; i >= 0; --i) {
480                 ir_node *irn = delayed[i].irn;
481                 if (irn && is_Phi(irn)) {
482                         DBG((dbg, DBG_START, "    spilling delayed phi %+F\n", irn));
483                         be_spill_phi(env->senv, irn);
484                 }
485         }
486         DEL_ARR_F(delayed);
487
488         /* Sort start values by first use */
489         qsort(starters, ARR_LEN(starters), sizeof(starters[0]), loc_compare);
490
491         /* Copy the best ones from starters to start workset */
492         ws_count             = MIN(ARR_LEN(starters), env->n_regs);
493         block_info->ws_start = new_workset(env, &env->ob);
494         workset_bulk_fill(block_info->ws_start, ws_count, starters);
495
496         /* The phis of this block which are not in the start set have to be spilled later. */
497         len = ARR_LEN(starters);
498         for (i = ws_count; i < len; ++i) {
499                 irn = starters[i].irn;
500                 if (! is_Phi(irn) || get_nodes_block(irn) != block)
501                         continue;
502
503                 be_spill_phi(env->senv, irn);
504         }
505
506         DEL_ARR_F(starters);
507 }
508
509 /**
510  * Collects all values live-in at block @p block and all phi results in this block.
511  * Then it adds the best values (at most n_regs) to the blocks start_workset.
512  * The phis among the remaining values get spilled: Introduce psudo-copies of
513  *  their args to break interference and make it possible to spill them to the
514  *  same spill slot.
515  */
516 static block_info_t *compute_block_start_info(belady_env_t *env, ir_node *block) {
517         ir_node *pred_block;
518         block_info_t *res, *pred_info;
519
520         /* Have we seen this block before? */
521         res = get_block_info(block);
522         if (res)
523                 return res;
524
525         /* Create the block info for this block. */
526         res = new_block_info(&env->ob);
527         set_block_info(block, res);
528
529         /* Use endset of predecessor block as startset */
530         assert(get_Block_n_cfgpreds(block) == 1 && block != get_irg_start_block(get_irn_irg(block)));
531         pred_block = get_Block_cfgpred_block(block, 0);
532         pred_info = get_block_info(pred_block);
533
534         /* if pred block has not been processed yet, do it now */
535         if (pred_info == NULL || pred_info->processed == 0) {
536                 belady(pred_block, env);
537                 pred_info = get_block_info(pred_block);
538         }
539
540         /* now we have an end_set of pred */
541         assert(pred_info->ws_end && "The recursive call (above) is supposed to compute an end_set");
542         res->ws_start = workset_clone(env, &env->ob, pred_info->ws_end);
543
544         return res;
545 }
546
547
548 /**
549  * For the given block @p block, decide for each values
550  * whether it is used from a register or is reloaded
551  * before the use.
552  */
553 static void belady(ir_node *block, void *data) {
554         belady_env_t *env = data;
555         workset_t *new_vals;
556         ir_node *irn;
557         int iter;
558         block_info_t *block_info;
559
560         /* make sure we have blockinfo (with startset) */
561         block_info = get_block_info(block);
562         if (block_info == NULL)
563                 block_info = compute_block_start_info(env, block);
564
565         /* Don't do a block twice */
566         if(block_info->processed)
567                 return;
568
569         /* get the starting workset for this block */
570         DBG((dbg, DBG_DECIDE, "\n"));
571         DBG((dbg, DBG_DECIDE, "Decide for %+F\n", block));
572
573         workset_copy(env, env->ws, block_info->ws_start);
574         DBG((dbg, DBG_WSETS, "Start workset for %+F:\n", block));
575         workset_foreach(env->ws, irn, iter)
576                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(env->ws, iter)));
577
578         /* process the block from start to end */
579         DBG((dbg, DBG_WSETS, "Processing...\n"));
580         env->used = pset_new_ptr_default();
581         env->instr_nr = 0;
582         new_vals = new_workset(env, &env->ob);
583         sched_foreach(block, irn) {
584                 int i, arity;
585                 assert(workset_get_length(env->ws) <= env->n_regs && "Too much values in workset!");
586
587                 /* projs are handled with the tuple value.
588                  * Phis are no real instr (see insert_starters())
589                  * instr_nr does not increase */
590                 if (is_Proj(irn) || is_Phi(irn)) {
591                         DBG((dbg, DBG_DECIDE, "  ...%+F skipped\n", irn));
592                         continue;
593                 }
594                 DBG((dbg, DBG_DECIDE, "  ...%+F\n", irn));
595
596                 /* set instruction in the workset */
597                 env->instr = irn;
598
599                 /* allocate all values _used_ by this instruction */
600                 workset_clear(new_vals);
601                 for(i = 0, arity = get_irn_arity(irn); i < arity; ++i) {
602                         workset_insert(env, new_vals, get_irn_n(irn, i));
603                 }
604                 displace(env, new_vals, 1);
605
606                 /* allocate all values _defined_ by this instruction */
607                 workset_clear(new_vals);
608                 if (get_irn_mode(irn) == mode_T) { /* special handling for tuples and projs */
609                         ir_node *proj;
610                         for(proj=sched_next(irn); is_Proj(proj); proj=sched_next(proj))
611                                 workset_insert(env, new_vals, proj);
612                 } else {
613                         workset_insert(env, new_vals, irn);
614                 }
615                 displace(env, new_vals, 0);
616
617                 env->instr_nr++;
618         }
619         del_pset(env->used);
620
621         /* Remember end-workset for this block */
622         block_info->ws_end = workset_clone(env, &env->ob, env->ws);
623         block_info->processed = 1;
624         DBG((dbg, DBG_WSETS, "End workset for %+F:\n", block));
625         workset_foreach(block_info->ws_end, irn, iter)
626                 DBG((dbg, DBG_WSETS, "  %+F (%u)\n", irn, workset_get_time(block_info->ws_end, iter)));
627 }
628
629 /**
630  * 'decide' is block-local and makes assumptions
631  * about the set of live-ins. Thus we must adapt the
632  * live-outs to the live-ins at each block-border.
633  */
634 static void fix_block_borders(ir_node *block, void *data) {
635         belady_env_t *env = data;
636         workset_t *wsb;
637         ir_graph *irg = get_irn_irg(block);
638         ir_node *startblock = get_irg_start_block(irg);
639         int i, max, iter, iter2;
640
641         if(block == startblock)
642             return;
643
644         DBG((dbg, DBG_FIX, "\n"));
645         DBG((dbg, DBG_FIX, "Fixing %+F\n", block));
646
647         wsb = get_block_info(block)->ws_start;
648
649         /* process all pred blocks */
650         for (i=0, max=get_irn_arity(block); i<max; ++i) {
651                 ir_node *irnb, *irnp, *pred = get_Block_cfgpred_block(block, i);
652                 workset_t *wsp = get_block_info(pred)->ws_end;
653
654                 DBG((dbg, DBG_FIX, "  Pred %+F\n", pred));
655
656                 workset_foreach(wsb, irnb, iter) {
657                         /* if irnb is a phi of the current block we reload
658                          * the corresponding argument, else irnb itself */
659                         if(is_Phi(irnb) && block == get_nodes_block(irnb)) {
660                                 irnb = get_irn_n(irnb, i);
661
662                                 // we might have unknowns as argument for the phi
663                                 if(!arch_irn_consider_in_reg_alloc(env->arch, env->cls, irnb))
664                                         continue;
665                         }
666
667                         /* Unknowns are available everywhere */
668                         if(get_irn_opcode(irnb) == iro_Unknown)
669                                 continue;
670
671                         /* check if irnb is in a register at end of pred */
672                         workset_foreach(wsp, irnp, iter2) {
673                                 if (irnb == irnp)
674                                         goto next_value;
675                         }
676
677                         /* irnb is not in memory at the end of pred, so we have to reload it */
678                         DBG((dbg, DBG_FIX, "    reload %+F\n", irnb));
679                         DBG((dbg, DBG_SPILL, "Reload %+F before %+F,%d\n", irnb, block, i));
680                         be_add_reload_on_edge(env->senv, irnb, block, i, env->cls, 1);
681
682 next_value:
683                         /*epsilon statement :)*/;
684                 }
685         }
686 }
687
688 /**
689  * Do spilling for a register class on a graph using the belady heuristic.
690  * In the transformed graph, the register pressure never exceeds the number
691  * of available registers.
692  *
693  * @param birg  The backend graph
694  * @param cls   The register class to spill
695  */
696 static void be_spill_belady(be_irg_t *birg, const arch_register_class_t *cls) {
697         be_spill_belady_spill_env(birg, cls, NULL);
698 }
699
700 void be_spill_belady_spill_env(be_irg_t *birg, const arch_register_class_t *cls, spill_env_t *spill_env) {
701         belady_env_t env;
702         ir_graph *irg = be_get_birg_irg(birg);
703         int n_regs;
704
705         /* some special classes contain only ignore regs, nothing to do then */
706         n_regs = cls->n_regs - be_put_ignore_regs(birg, cls, NULL);
707         if(n_regs == 0)
708                 return;
709
710         be_invalidate_liveness(birg);
711         be_assure_liveness(birg);
712         /* construct control flow loop tree */
713         if(! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
714                 construct_cf_backedges(irg);
715         }
716
717         /* init belady env */
718         obstack_init(&env.ob);
719         env.arch      = birg->main_env->arch_env;
720         env.cls       = cls;
721         env.lv        = be_get_birg_liveness(birg);
722         env.n_regs    = n_regs;
723         env.ws        = new_workset(&env, &env.ob);
724         env.uses      = be_begin_uses(irg, env.lv);
725         env.loop_ana  = be_new_loop_pressure(birg);
726         if(spill_env == NULL) {
727                 env.senv = be_new_spill_env(birg);
728         } else {
729                 env.senv = spill_env;
730         }
731         DEBUG_ONLY(be_set_spill_env_dbg_module(env.senv, dbg);)
732
733         be_clear_links(irg);
734         /* Decide which phi nodes will be spilled and place copies for them into the graph */
735         irg_block_walk_graph(irg, compute_live_ins, NULL, &env);
736         /* Fix high register pressure with belady algorithm */
737         irg_block_walk_graph(irg, NULL, belady, &env);
738         /* belady was block-local, fix the global flow by adding reloads on the edges */
739         irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
740         /* Insert spill/reload nodes into the graph and fix usages */
741         be_insert_spills_reloads(env.senv);
742
743         /* clean up */
744         if(spill_env == NULL)
745                 be_delete_spill_env(env.senv);
746         be_end_uses(env.uses);
747         be_free_loop_pressure(env.loop_ana);
748         obstack_free(&env.ob, NULL);
749 }
750
751 void be_init_spillbelady(void)
752 {
753         static be_spiller_t belady_spiller = {
754                 be_spill_belady
755         };
756
757         be_register_spiller("belady", &belady_spiller);
758         FIRM_DBG_REGISTER(dbg, "firm.be.spill.belady");
759 }
760
761 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillbelady);