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