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