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