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