now fehler39 exposes the original bug again :)
[libfirm] / ir / be / bespill.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       implementation of the spill/reload placement abstraction layer
23  * @author      Daniel Grund, Sebastian Hack, Matthias Braun
24  * @date                29.09.2005
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <stdlib.h>
32
33 #include "pset.h"
34 #include "irnode_t.h"
35 #include "ircons_t.h"
36 #include "iredges_t.h"
37 #include "irbackedge_t.h"
38 #include "irprintf.h"
39 #include "ident_t.h"
40 #include "type_t.h"
41 #include "entity_t.h"
42 #include "debug.h"
43 #include "irgwalk.h"
44 #include "array.h"
45 #include "pdeq.h"
46 #include "execfreq.h"
47 #include "irnodeset.h"
48
49 #include "bearch_t.h"
50 #include "belive_t.h"
51 #include "besched_t.h"
52 #include "bespill.h"
53 #include "belive_t.h"
54 #include "benode_t.h"
55 #include "bechordal_t.h"
56 #include "bejavacoal.h"
57 #include "benodesets.h"
58 #include "bespilloptions.h"
59 #include "bestatevent.h"
60 #include "bessaconstr.h"
61 #include "beirg_t.h"
62 #include "beintlive_t.h"
63 #include "bemodule.h"
64
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 #define REMAT_COST_INFINITE  1000
68
69 typedef struct reloader_t reloader_t;
70 struct reloader_t {
71         reloader_t *next;
72         ir_node    *reloader;
73         ir_node    *rematted_node;
74         int         remat_cost_delta; /** costs needed for rematerialization,
75                                            compared to placing a reload */
76 };
77
78 typedef struct spill_info_t spill_info_t;
79 struct spill_info_t {
80         ir_node    *to_spill;  /**< the value that should get spilled */
81         reloader_t *reloaders; /**< list of places where the value should get
82                                     reloaded */
83         ir_node    *spill;     /**< the spill node, or a PhiM node */
84         ir_node    *old_spill; /**< if we had the value of a phi spilled before but
85                                     not the phi itself then this field contains the
86                                     spill for the phi value */
87         const arch_register_class_t *reload_cls; /** the register class in which the
88                                                      reload should be placed */
89 };
90
91 struct spill_env_t {
92         const arch_env_t *arch_env;
93         ir_graph         *irg;
94         struct obstack    obst;
95         be_irg_t         *birg;
96         int               spill_cost;     /**< the cost of a single spill node */
97         int               reload_cost;    /**< the cost of a reload node */
98         set              *spills;         /**< all spill_info_t's, which must be
99                                                placed */
100         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
101         ir_exec_freq     *exec_freq;
102
103 #ifdef FIRM_STATISTICS
104         unsigned          spill_count;
105         unsigned          reload_count;
106         unsigned          remat_count;
107         unsigned          spilled_phi_count;
108 #endif
109 };
110
111 /**
112  * Compare two spill infos.
113  */
114 static
115 int cmp_spillinfo(const void *x, const void *y, size_t size)
116 {
117         const spill_info_t *xx = x;
118         const spill_info_t *yy = y;
119         (void) size;
120
121         return xx->to_spill != yy->to_spill;
122 }
123
124 /**
125  * Returns spill info for a specific value (the value that is to be spilled)
126  */
127 static
128 spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
129 {
130         spill_info_t info, *res;
131         int hash = nodeset_hash(value);
132
133         info.to_spill = value;
134         res = set_find(env->spills, &info, sizeof(info), hash);
135
136         if (res == NULL) {
137                 info.reloaders = NULL;
138                 info.spill = NULL;
139                 info.old_spill = NULL;
140                 info.reload_cls = NULL;
141                 res = set_insert(env->spills, &info, sizeof(info), hash);
142         }
143
144         return res;
145 }
146
147 spill_env_t *be_new_spill_env(be_irg_t *birg)
148 {
149         const arch_env_t *arch_env = birg->main_env->arch_env;
150
151         spill_env_t *env        = xmalloc(sizeof(env[0]));
152         env->spills                     = new_set(cmp_spillinfo, 1024);
153         env->irg            = be_get_birg_irg(birg);
154         env->birg           = birg;
155         env->arch_env       = arch_env;
156         ir_nodeset_init(&env->mem_phis);
157         env->spill_cost     = arch_env->isa->spill_cost;
158         env->reload_cost    = arch_env->isa->reload_cost;
159         env->exec_freq      = be_get_birg_exec_freq(birg);
160         obstack_init(&env->obst);
161
162 #ifdef FIRM_STATISTICS
163         env->spill_count       = 0;
164         env->reload_count      = 0;
165         env->remat_count       = 0;
166         env->spilled_phi_count = 0;
167 #endif
168
169         return env;
170 }
171
172 void be_delete_spill_env(spill_env_t *env)
173 {
174         del_set(env->spills);
175         ir_nodeset_destroy(&env->mem_phis);
176         obstack_free(&env->obst, NULL);
177         free(env);
178 }
179
180 /*
181  *  ____  _                  ____      _                 _
182  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
183  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
184  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
185  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
186  *
187  */
188
189 void be_add_remat(spill_env_t *env, ir_node *to_spill, ir_node *before,
190                   ir_node *rematted_node)
191 {
192         spill_info_t *spill_info;
193         reloader_t *reloader;
194
195         spill_info = get_spillinfo(env, to_spill);
196
197         /* add the remat information */
198         reloader                = obstack_alloc(&env->obst, sizeof(reloader[0]));
199         reloader->next          = spill_info->reloaders;
200         reloader->reloader      = before;
201         reloader->rematted_node = rematted_node;
202         reloader->remat_cost_delta = 0; /* We will never have a cost win over a
203                                            reload since we're not even allowed to
204                                            create a reload */
205
206         spill_info->reloaders  = reloader;
207
208         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be rematerialized before %+F\n",
209                 to_spill, before));
210 }
211
212 void be_add_reload(spill_env_t *env, ir_node *to_spill, ir_node *before,
213                    const arch_register_class_t *reload_cls, int allow_remat)
214 {
215         spill_info_t *info;
216         reloader_t *rel;
217
218         info = get_spillinfo(env, to_spill);
219
220         if (is_Phi(to_spill)) {
221                 int i, arity;
222
223                 /* create spillinfos for the phi arguments */
224                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
225                         ir_node *arg = get_irn_n(to_spill, i);
226                         get_spillinfo(env, arg);
227                 }
228
229 #if 1
230                 /* hackery... sometimes the morgan algo spilled the value of a phi,
231                  * the belady algo decides later to spill the whole phi, then sees the
232                  * spill node and adds a reload for that spill node, problem is the
233                  * reload gets attach to that same spill (and is totally unnecessary)
234                  */
235                 if (info->old_spill != NULL &&
236                         (before == info->old_spill || value_dominates(before, info->old_spill)))
237                 {
238                         printf("spilledphi hack was needed...\n");
239                         before = sched_next(info->old_spill);
240                 }
241 #endif
242         }
243
244         assert(!is_Proj(before) && !be_is_Keep(before));
245
246         /* put reload into list */
247         rel                = obstack_alloc(&env->obst, sizeof(rel[0]));
248         rel->next          = info->reloaders;
249         rel->reloader      = before;
250         rel->rematted_node = NULL;
251         if(!allow_remat) {
252                 rel->remat_cost_delta = REMAT_COST_INFINITE;
253         } else {
254                 rel->remat_cost_delta = 0;
255         }
256
257         info->reloaders  = rel;
258         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
259         info->reload_cls = reload_cls;
260
261         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
262                 to_spill, before, allow_remat ? "" : " not"));
263 }
264
265 /**
266  * Returns the point at which you can insert a node that should be executed
267  * before block @p block when coming from pred @p pos.
268  */
269 static
270 ir_node *get_block_insertion_point(ir_node *block, int pos)
271 {
272         ir_node *predblock, *last;
273
274         /* simply add the reload to the beginning of the block if we only have 1
275          * predecessor. We don't need to check for phis as there can't be any in a
276          * block with only 1 pred. */
277         if(get_Block_n_cfgpreds(block) == 1) {
278                 assert(!is_Phi(sched_first(block)));
279                 return sched_first(block);
280         }
281
282         /* We have to reload the value in pred-block */
283         predblock = get_Block_cfgpred_block(block, pos);
284         last = sched_last(predblock);
285
286         /* we might have projs and keepanys behind the jump... */
287         while(is_Proj(last) || be_is_Keep(last)) {
288                 last = sched_prev(last);
289                 assert(!sched_is_end(last));
290         }
291
292         if(!is_cfop(last)) {
293                 last = sched_next(last);
294                 /* last node must be a cfop, only exception is the start block */
295                 assert(last     == get_irg_start_block(get_irn_irg(block)));
296         }
297
298         /* add the reload before the (cond-)jump */
299         return last;
300 }
301
302 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
303                            int pos,     const arch_register_class_t *reload_cls,
304                            int allow_remat)
305 {
306         ir_node *before = get_block_insertion_point(block, pos);
307         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
308 }
309
310 void be_spill_phi(spill_env_t *env, ir_node *node)
311 {
312         spill_info_t* spill;
313         int i, arity;
314
315         assert(is_Phi(node));
316
317         ir_nodeset_insert(&env->mem_phis, node);
318
319         /* create spillinfos for the phi arguments */
320         spill = get_spillinfo(env, node);
321         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
322                 ir_node *arg = get_irn_n(node, i);
323                 get_spillinfo(env, arg);
324         }
325
326         /* if we had a spill for the phi value before, then remove this spill from
327          * schedule, as we will remove it in the insert spill/reload phase
328          */
329         if(spill->spill != NULL && !is_Phi(spill->spill)) {
330                 assert(spill->old_spill == NULL);
331                 spill->old_spill = spill->spill;
332                 spill->spill = NULL;
333         }
334 }
335
336 /*
337  *   ____                _         ____        _ _ _
338  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
339  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
340  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
341  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
342  *                                      |_|
343  */
344
345 /**
346  * Schedules a node after an instruction. That is the place after all projs and
347  * phis that are scheduled after the instruction. This function also skips phi
348  * nodes at the beginning of a block
349  */
350 static
351 void sched_add_after_insn(ir_node *sched_after, ir_node *node)
352 {
353         ir_node *next = sched_next(sched_after);
354         while(is_Proj(next) || is_Phi(next) || be_is_Keep(next)) {
355                 next = sched_next(next);
356         }
357         assert(next != NULL);
358
359         if(sched_is_end(next)) {
360                 sched_add_after(sched_last(get_nodes_block(sched_after)), node);
361         } else {
362                 sched_add_before(next, node);
363         }
364 }
365
366 /**
367  * Creates a spill.
368  *
369  * @param senv      the spill environment
370  * @param irn       the node that should be spilled
371  * @param ctx_irn   an user of the spilled node
372  *
373  * @return a be_Spill node
374  */
375 static
376 void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
377 {
378         optimization_state_t  opt;
379         ir_node              *to_spill = spillinfo->to_spill;
380
381         DBG((dbg, LEVEL_1, "spilling %+F ... ", to_spill));
382
383         /* Trying to spill an already spilled value, no need for a new spill
384          * node then, we can simply connect to the same one for this reload
385          *
386          * Normally reloads get simply rematerialized instead of spilled again; this
387          * can happen annyway when the reload is the pred of a phi to spill)
388          */
389         if (be_is_Reload(to_spill)) {
390                 spillinfo->spill = get_irn_n(to_spill, be_pos_Reload_mem);
391                 DB((dbg, LEVEL_1, "skip reload, using existing spill %+F\n", spillinfo->spill));
392                 return;
393         }
394
395         assert(!(arch_irn_is(env->arch_env, to_spill, dont_spill)
396                                 && "Attempt to spill a node marked 'dont_spill'"));
397
398         /* some backends have virtual noreg/unknown nodes that are not scheduled */
399         if(!sched_is_scheduled(to_spill)) {
400                 spillinfo->spill = new_NoMem();
401                 return;
402         }
403
404
405         /*
406          * We switch on optimizations here to get CSE. This is needed as the STA
407          * backends has some extra spill phases and we want to make use of those
408          * spills instead of creating new ones.
409          */
410         save_optimization_state(&opt);
411         set_optimize(1);
412         spillinfo->spill = be_spill(env->arch_env, to_spill);
413         restore_optimization_state(&opt);
414         if (! sched_is_scheduled(spillinfo->spill)) {
415                 DB((dbg, LEVEL_1, "add spill %+F after %+F\n", spillinfo->spill, to_spill));
416 #ifdef FIRM_STATISTICS
417                 env->spill_count++;
418 #endif
419                 sched_add_after_insn(to_spill, spillinfo->spill);
420         } else {
421                 DB((dbg, LEVEL_1, "re-using spill %+F after %+F\n", spillinfo->spill, to_spill));
422         }
423 }
424
425 static
426 void spill_node(spill_env_t *env, spill_info_t *spillinfo);
427
428 /**
429  * If the first usage of a Phi result would be out of memory
430  * there is no sense in allocating a register for it.
431  * Thus we spill it and all its operands to the same spill slot.
432  * Therefore the phi/dataB becomes a phi/Memory
433  *
434  * @param senv      the spill environment
435  * @param phi       the Phi node that should be spilled
436  * @param ctx_irn   an user of the spilled node
437  */
438 static
439 void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
440 {
441         ir_node *phi = spillinfo->to_spill;
442         int i;
443         int arity = get_irn_arity(phi);
444         ir_node     *block    = get_nodes_block(phi);
445         ir_node     **ins;
446
447         assert(is_Phi(phi));
448
449         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
450         /* build a new PhiM */
451         ins = alloca(sizeof(ir_node*) * arity);
452         for(i = 0; i < arity; ++i) {
453                 ins[i] = get_irg_bad(env->irg);
454         }
455         spillinfo->spill = new_r_Phi(env->irg, block, arity, ins, mode_M);
456 #ifdef FIRM_STATISTICS
457         env->spilled_phi_count++;
458 #endif
459
460         for(i = 0; i < arity; ++i) {
461                 ir_node *arg = get_irn_n(phi, i);
462                 spill_info_t *arg_info = get_spillinfo(env, arg);
463
464                 spill_node(env, arg_info);
465
466                 set_irn_n(spillinfo->spill, i, arg_info->spill);
467         }
468         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi, spillinfo->spill));
469
470         /* rewire reloads from old_spill to phi */
471         if (spillinfo->old_spill != NULL) {
472                 const ir_edge_t *edge, *next;
473                 ir_node *old_spill = spillinfo->old_spill;
474
475                 DBG((dbg, LEVEL_1, "old spill found, rewiring reloads:\n"));
476
477                 foreach_out_edge_safe(old_spill, edge, next) {
478                         ir_node *reload = get_edge_src_irn(edge);
479                         int     pos     = get_edge_src_pos(edge);
480
481                         DBG((dbg, LEVEL_1, "\tset input %d of %+F to %+F\n", pos, reload, spillinfo->spill));
482
483                         assert(be_is_Reload(reload) || is_Phi(reload));
484                         set_irn_n(reload, pos, spillinfo->spill);
485                 }
486                 DBG((dbg, LEVEL_1, "\tset input of %+F to BAD\n", old_spill));
487                 set_irn_n(old_spill, be_pos_Spill_val, new_Bad());
488                 /* sched_remove(old_spill); */
489                 spillinfo->old_spill = NULL;
490         }
491 }
492
493 /**
494  * Spill a node.
495  *
496  * @param senv      the spill environment
497  * @param to_spill  the node that should be spilled
498  */
499 static
500 void spill_node(spill_env_t *env, spill_info_t *spillinfo)
501 {
502         ir_node *to_spill;
503
504         /* the node should be tagged for spilling already... */
505         if(spillinfo->spill != NULL)
506                 return;
507
508         to_spill = spillinfo->to_spill;
509
510         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
511                 spill_phi(env, spillinfo);
512         } else {
513                 spill_irn(env, spillinfo);
514         }
515 }
516
517 /*
518  *
519  *  ____                      _            _       _ _
520  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
521  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
522  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
523  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
524  *
525  */
526
527 /**
528  * Tests whether value @p arg is available before node @p reloader
529  * @returns 1 if value is available, 0 otherwise
530  */
531 static
532 int is_value_available(spill_env_t *env, ir_node *arg, ir_node *reloader)
533 {
534         if(is_Unknown(arg) || arg == new_NoMem())
535                 return 1;
536
537         if(be_is_Spill(arg))
538                 return 1;
539
540         if(arg == get_irg_frame(env->irg))
541                 return 1;
542
543         /* hack for now (happens when command should be inserted at end of block) */
544         if(is_Block(reloader)) {
545                 return 0;
546         }
547
548         /*
549          * Ignore registers are always available
550          */
551         if(arch_irn_is(env->arch_env, arg, ignore)) {
552                 return 1;
553         }
554
555         /* the following test does not work while spilling,
556          * because the liveness info is not adapted yet to the effects of the
557          * additional spills/reloads.
558          */
559 #if 0
560         /* we want to remat before the insn reloader
561          * thus an arguments is alive if
562          *   - it interferes with the reloaders result
563          *   - or it is (last-) used by reloader itself
564          */
565         if (values_interfere(env->birg->lv, reloader, arg)) {
566                 return 1;
567         }
568
569         arity = get_irn_arity(reloader);
570         for (i = 0; i < arity; ++i) {
571                 ir_node *rel_arg = get_irn_n(reloader, i);
572                 if (rel_arg == arg)
573                         return 1;
574         }
575 #endif
576
577         return 0;
578 }
579
580 /**
581  * Checks whether the node can principally be rematerialized
582  */
583 static
584 int is_remat_node(spill_env_t *env, ir_node *node)
585 {
586         const arch_env_t *arch_env = env->arch_env;
587
588         assert(!be_is_Spill(node));
589
590         if(arch_irn_is(arch_env, node, rematerializable))
591                 return 1;
592
593         return 0;
594 }
595
596 /**
597  * Check if a node is rematerializable. This tests for the following conditions:
598  *
599  * - The node itself is rematerializable
600  * - All arguments of the node are available or also rematerialisable
601  * - The costs for the rematerialisation operation is less or equal a limit
602  *
603  * Returns the costs needed for rematerialisation or something
604  * >= REMAT_COST_INFINITE if remat is not possible.
605  */
606 static
607 int check_remat_conditions_costs(spill_env_t *env, ir_node *spilled,
608                                  ir_node *reloader, int parentcosts)
609 {
610         int i, arity;
611         int argremats;
612         int costs = 0;
613
614         if(!is_remat_node(env, spilled))
615                 return REMAT_COST_INFINITE;
616
617         if(be_is_Reload(spilled)) {
618                 costs += 2;
619         } else {
620                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
621         }
622         if(parentcosts + costs >= env->reload_cost + env->spill_cost) {
623                 return REMAT_COST_INFINITE;
624         }
625
626         argremats = 0;
627         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
628                 ir_node *arg = get_irn_n(spilled, i);
629
630                 if(is_value_available(env, arg, reloader))
631                         continue;
632
633                 /* we have to rematerialize the argument as well */
634                 if(argremats >= 1) {
635                         /* we only support rematerializing 1 argument at the moment,
636                          * so that we don't have to care about register pressure
637                          */
638                         return REMAT_COST_INFINITE;
639                 }
640                 argremats++;
641
642                 costs += check_remat_conditions_costs(env, arg, reloader, parentcosts + costs);
643                 if(parentcosts + costs >= env->reload_cost + env->spill_cost)
644                         return REMAT_COST_INFINITE;
645         }
646
647         return costs;
648 }
649
650 /**
651  * Re-materialize a node.
652  *
653  * @param senv      the spill environment
654  * @param spilled   the node that was spilled
655  * @param reloader  a irn that requires a reload
656  */
657 static
658 ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
659 {
660         int i, arity;
661         ir_node *res;
662         ir_node *bl;
663         ir_node **ins;
664
665         if(is_Block(reloader)) {
666                 bl = reloader;
667         } else {
668                 bl = get_nodes_block(reloader);
669         }
670
671         ins = alloca(get_irn_arity(spilled) * sizeof(ins[0]));
672         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
673                 ir_node *arg = get_irn_n(spilled, i);
674
675                 if(is_value_available(env, arg, reloader)) {
676                         ins[i] = arg;
677                 } else {
678                         ins[i] = do_remat(env, arg, reloader);
679 #ifdef FIRM_STATISTICS
680                         /* don't count the recursive call as remat */
681                         env->remat_count--;
682 #endif
683                 }
684         }
685
686         /* create a copy of the node */
687         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
688                           get_irn_op(spilled), get_irn_mode(spilled),
689                           get_irn_arity(spilled), ins);
690         copy_node_attr(spilled, res);
691         new_backedge_info(res);
692
693         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
694
695 #ifdef SCHEDULE_PROJS
696         /* insert in schedule */
697         sched_reset(res);
698         sched_add_before(reloader, res);
699 #ifdef FIRM_STATISTICS
700         if (! is_Proj(res))
701                 env->remat_count++;
702 #endif
703 #else
704         if (! is_Proj(res)) {
705                 /* insert in schedule */
706                 sched_reset(res);
707                 sched_add_before(reloader, res);
708 #ifdef FIRM_STATISTICS
709                 env->remat_count++;
710 #endif
711         }
712 #endif /* SCHEDULE_PROJS */
713
714         return res;
715 }
716
717 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *after)
718 {
719         ir_node *block = get_nodes_block(after);
720         double   freq  = get_block_execfreq(env->exec_freq, block);
721         (void) to_spill;
722
723         return env->spill_cost * freq;
724 }
725
726 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
727 {
728         ir_node      *block = get_nodes_block(before);
729         double        freq  = get_block_execfreq(env->exec_freq, block);
730
731         if(be_do_remats) {
732                 /* is the node rematerializable? */
733                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
734                 if(costs < env->reload_cost)
735                         return costs * freq;
736         }
737
738         return env->reload_cost * freq;
739 }
740
741 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
742                                 ir_node *block, int pos)
743 {
744         ir_node *before = get_block_insertion_point(block, pos);
745         return be_get_reload_costs(env, to_spill, before);
746 }
747
748 /*
749  *  ___                     _     ____      _                 _
750  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
751  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
752  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
753  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
754  *
755  */
756
757 void be_insert_spills_reloads(spill_env_t *env)
758 {
759         const arch_env_t      *arch_env  = env->arch_env;
760         const ir_exec_freq    *exec_freq = env->exec_freq;
761         spill_info_t          *si;
762         ir_nodeset_iterator_t  iter;
763         ir_node               *node;
764
765         /* create all phi-ms first, this is needed so, that phis, hanging on
766            spilled phis work correctly */
767         foreach_ir_nodeset(&env->mem_phis, node, iter) {
768                 spill_info_t *info = get_spillinfo(env, node);
769                 spill_node(env, info);
770         }
771
772         /* process each spilled node */
773         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
774                 reloader_t *rld;
775                 ir_node  *to_spill        = si->to_spill;
776                 ir_mode  *mode            = get_irn_mode(to_spill);
777                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
778                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
779                 int       force_remat     = 0;
780
781                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
782
783                 /* determine possibility of rematerialisations */
784                 if(be_do_remats) {
785                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
786                                 double   freq;
787                                 int      remat_cost;
788                                 int      remat_cost_delta;
789                                 ir_node *block;
790                                 ir_node *reloader = rld->reloader;
791
792                                 if(rld->rematted_node != NULL) {
793                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
794                                              rld->rematted_node, reloader));
795                                         continue;
796                                 }
797                                 if(rld->remat_cost_delta >= REMAT_COST_INFINITE) {
798                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
799                                              reloader));
800                                         all_remat_costs = REMAT_COST_INFINITE;
801                                         continue;
802                                 }
803
804                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
805                                                                            reloader, 0);
806                                 if(remat_cost >= REMAT_COST_INFINITE) {
807                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
808                                              reloader));
809                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
810                                         all_remat_costs       = REMAT_COST_INFINITE;
811                                         continue;
812                                 }
813
814                                 remat_cost_delta      = remat_cost - env->reload_cost;
815                                 rld->remat_cost_delta = remat_cost_delta;
816                                 block                 = get_nodes_block(reloader);
817                                 freq                  = get_block_execfreq(exec_freq, block);
818                                 all_remat_costs      += remat_cost_delta * freq;
819                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
820                                      "%d (rel %f)\n", reloader, remat_cost_delta,
821                                      remat_cost_delta * freq));
822                         }
823                         if(all_remat_costs < REMAT_COST_INFINITE) {
824                                 ir_node *block = get_nodes_block(to_spill);
825                                 double   freq  = get_block_execfreq(exec_freq, block);
826                                 /* we don't need the costs for the spill if we can remat
827                                    all reloaders */
828                                 all_remat_costs -= env->spill_cost * freq;
829
830                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
831                                      env->spill_cost, env->spill_cost * freq));
832                         }
833
834                         if(all_remat_costs < 0) {
835                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
836                                      all_remat_costs));
837                                 force_remat = 1;
838                         }
839                 }
840
841                 /* go through all reloads for this spill */
842                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
843                         ir_node *copy; /* a reload is a "copy" of the original value */
844
845                         if (rld->rematted_node != NULL) {
846                                 copy = rld->rematted_node;
847                                 sched_add_before(rld->reloader, copy);
848                         } else if (be_do_remats &&
849                                         (force_remat || rld->remat_cost_delta < 0)) {
850                                 copy = do_remat(env, to_spill, rld->reloader);
851                         } else {
852                                 /* make sure we have a spill */
853                                 if (si->spill == NULL) {
854                                         spill_node(env, si);
855                                 }
856
857                                 /* create a reload */
858                                 copy = be_reload(arch_env, si->reload_cls, rld->reloader, mode,
859                                                  si->spill);
860 #ifdef FIRM_STATISTICS
861                                 env->reload_count++;
862 #endif
863                         }
864
865                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
866                              copy, to_spill, rld->reloader));
867                         ARR_APP1(ir_node*, copies, copy);
868                 }
869
870                 /* if we had any reloads or remats, then we need to reconstruct the
871                  * SSA form for the spilled value */
872                 if (ARR_LEN(copies) > 0) {
873                         be_ssa_construction_env_t senv;
874                         /* be_lv_t *lv = be_get_birg_liveness(env->birg); */
875
876                         be_ssa_construction_init(&senv, env->birg);
877                         be_ssa_construction_add_copy(&senv, to_spill);
878                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
879                         be_ssa_construction_fix_users(&senv, to_spill);
880
881 #if 0
882                         /* no need to enable this as long as we invalidate liveness
883                            after this function... */
884                         be_ssa_construction_update_liveness_phis(&senv);
885                         be_liveness_update(to_spill);
886                         len = ARR_LEN(copies);
887                         for(i = 0; i < len; ++i) {
888                                 be_liveness_update(lv, copies[i]);
889                         }
890 #endif
891                         be_ssa_construction_destroy(&senv);
892                 }
893
894                 DEL_ARR_F(copies);
895                 si->reloaders = NULL;
896         }
897
898         stat_ev_dbl("spill_spills", env->spill_count);
899         stat_ev_dbl("spill_reloads", env->reload_count);
900         stat_ev_dbl("spill_remats", env->remat_count);
901         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
902
903         /* Matze: In theory be_ssa_construction should take care of the liveness...
904          * try to disable this again in the future */
905         be_liveness_invalidate(env->birg->lv);
906
907         be_remove_dead_nodes_from_schedule(env->birg);
908 }
909
910 void be_init_spill(void)
911 {
912         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
913 }
914
915 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);