04e801af40ed0be0edec208ee475757ec0953507
[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 #include "error.h"
49
50 #include "bearch_t.h"
51 #include "belive_t.h"
52 #include "besched_t.h"
53 #include "bespill.h"
54 #include "belive_t.h"
55 #include "benode_t.h"
56 #include "bechordal_t.h"
57 #include "bejavacoal.h"
58 #include "benodesets.h"
59 #include "bespilloptions.h"
60 #include "bestatevent.h"
61 #include "bessaconstr.h"
62 #include "beirg_t.h"
63 #include "beintlive_t.h"
64 #include "bemodule.h"
65
66 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
67
68 #define REMAT_COST_INFINITE  1000
69
70 typedef struct reloader_t reloader_t;
71 struct reloader_t {
72         reloader_t *next;
73         ir_node    *can_spill_after;
74         ir_node    *reloader;
75         ir_node    *rematted_node;
76         int         remat_cost_delta; /** costs needed for rematerialization,
77                                            compared to placing a reload */
78 };
79
80 typedef struct spill_t spill_t;
81 struct spill_t {
82         spill_t *next;
83         ir_node *before;   /**< spill has to be placed before this node (or earlier) */
84         ir_node *spill;
85 };
86
87 typedef struct spill_info_t spill_info_t;
88 struct spill_info_t {
89         ir_node    *to_spill;  /**< the value that should get spilled */
90         reloader_t *reloaders; /**< list of places where the value should get
91                                     reloaded */
92         spill_t    *spills;    /**< list of latest places where spill must be
93                                     placed */
94         double      spill_costs; /**< costs needed for spilling the value */
95         const arch_register_class_t *reload_cls; /** the register class in which the
96                                                      reload should be placed */
97 };
98
99 struct spill_env_t {
100         const arch_env_t *arch_env;
101         ir_graph         *irg;
102         struct obstack    obst;
103         be_irg_t         *birg;
104         int               spill_cost;     /**< the cost of a single spill node */
105         int               reload_cost;    /**< the cost of a reload node */
106         set              *spills;         /**< all spill_info_t's, which must be
107                                                placed */
108         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
109         ir_exec_freq     *exec_freq;
110         unsigned          new_nodes_idx;  /**< all old nodes idx is smaller than
111                                                this */
112
113 #ifdef FIRM_STATISTICS
114         unsigned          spill_count;
115         unsigned          reload_count;
116         unsigned          remat_count;
117         unsigned          spilled_phi_count;
118 #endif
119 };
120
121 /**
122  * Compare two spill infos.
123  */
124 static int cmp_spillinfo(const void *x, const void *y, size_t size)
125 {
126         const spill_info_t *xx = x;
127         const spill_info_t *yy = y;
128         (void) size;
129
130         return xx->to_spill != yy->to_spill;
131 }
132
133 /**
134  * Returns spill info for a specific value (the value that is to be spilled)
135  */
136 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
137 {
138         spill_info_t info, *res;
139         int hash = nodeset_hash(value);
140
141         info.to_spill = value;
142         res = set_find(env->spills, &info, sizeof(info), hash);
143
144         if (res == NULL) {
145                 info.reloaders   = NULL;
146                 info.spills      = NULL;
147                 info.spill_costs = -1;
148                 info.reload_cls  = NULL;
149                 res = set_insert(env->spills, &info, sizeof(info), hash);
150         }
151
152         return res;
153 }
154
155 spill_env_t *be_new_spill_env(be_irg_t *birg)
156 {
157         const arch_env_t *arch_env = birg->main_env->arch_env;
158
159         spill_env_t *env        = xmalloc(sizeof(env[0]));
160         env->spills                     = new_set(cmp_spillinfo, 1024);
161         env->irg            = be_get_birg_irg(birg);
162         env->birg           = birg;
163         env->arch_env       = arch_env;
164         ir_nodeset_init(&env->mem_phis);
165         env->spill_cost     = arch_env->isa->spill_cost;
166         env->reload_cost    = arch_env->isa->reload_cost;
167         env->exec_freq      = be_get_birg_exec_freq(birg);
168         obstack_init(&env->obst);
169
170 #ifdef FIRM_STATISTICS
171         env->spill_count       = 0;
172         env->reload_count      = 0;
173         env->remat_count       = 0;
174         env->spilled_phi_count = 0;
175 #endif
176
177         return env;
178 }
179
180 void be_delete_spill_env(spill_env_t *env)
181 {
182         del_set(env->spills);
183         ir_nodeset_destroy(&env->mem_phis);
184         obstack_free(&env->obst, NULL);
185         free(env);
186 }
187
188 /*
189  *  ____  _                  ____      _                 _
190  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
191  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
192  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
193  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
194  *
195  */
196
197 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *before)
198 {
199         spill_info_t *spill_info = get_spillinfo(env, to_spill);
200         spill_t      *spill;
201         spill_t      *s;
202         spill_t      *last;
203
204         DB((dbg, LEVEL_1, "Add spill of %+F before %+F\n", to_spill, before));
205
206         /* spills that are dominated by others are not needed */
207         last = NULL;
208         s    = spill_info->spills;
209         for( ; s != NULL; s = s->next) {
210                 /* no need to add this spill if it is dominated by another */
211                 if(value_dominates(s->before, before)) {
212                         DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->before));
213                         return;
214                 }
215                 /* remove spills that we dominate */
216                 if(value_dominates(before, s->before)) {
217                         DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->before));
218                         if(last != NULL) {
219                                 last->next         = s->next;
220                         } else {
221                                 spill_info->spills = s->next;
222                         }
223                 } else {
224                         last = s;
225                 }
226         }
227
228         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
229         spill->before = before;
230         spill->next   = spill_info->spills;
231         spill->spill  = NULL;
232
233         spill_info->spills = spill;
234 }
235
236 void be_add_remat(spill_env_t *env, ir_node *to_spill, ir_node *before,
237                   ir_node *rematted_node)
238 {
239         spill_info_t *spill_info;
240         reloader_t *reloader;
241
242         spill_info = get_spillinfo(env, to_spill);
243
244         /* add the remat information */
245         reloader                   = obstack_alloc(&env->obst, sizeof(reloader[0]));
246         reloader->next             = spill_info->reloaders;
247         reloader->reloader         = before;
248         reloader->rematted_node    = rematted_node;
249         reloader->remat_cost_delta = 0; /* We will never have a cost win over a
250                                            reload since we're not even allowed to
251                                            create a reload */
252
253         spill_info->reloaders  = reloader;
254
255         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be rematerialized before %+F\n",
256                 to_spill, before));
257 }
258
259 void be_add_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before,
260                 ir_node *can_spill_after, const arch_register_class_t *reload_cls,
261                 int allow_remat)
262 {
263         spill_info_t *info;
264         reloader_t *rel;
265
266         info = get_spillinfo(env, to_spill);
267
268         if (is_Phi(to_spill)) {
269                 int i, arity;
270
271                 /* create spillinfos for the phi arguments */
272                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
273                         ir_node *arg = get_irn_n(to_spill, i);
274                         get_spillinfo(env, arg);
275                 }
276         }
277
278         assert(!is_Proj(before) && !be_is_Keep(before));
279
280         /* put reload into list */
281         rel                   = obstack_alloc(&env->obst, sizeof(rel[0]));
282         rel->next             = info->reloaders;
283         rel->reloader         = before;
284         rel->rematted_node    = NULL;
285         rel->can_spill_after  = can_spill_after;
286         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
287
288         info->reloaders  = rel;
289         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
290         info->reload_cls = reload_cls;
291
292         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
293                 to_spill, before, allow_remat ? "" : " not"));
294 }
295
296 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
297                    const arch_register_class_t *reload_cls, int allow_remat)
298 {
299         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
300
301 }
302
303 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
304 {
305         ir_node *last = sched_last(block);
306
307         /* we might have keeps behind the jump... */
308         while(be_is_Keep(last)) {
309                 last = sched_prev(last);
310                 assert(!sched_is_end(last));
311         }
312
313         assert(is_cfop(last));
314
315         /* add the reload before the (cond-)jump */
316         return last;
317 }
318
319 /**
320  * Returns the point at which you can insert a node that should be executed
321  * before block @p block when coming from pred @p pos.
322  */
323 static ir_node *get_block_insertion_point(ir_node *block, int pos)
324 {
325         ir_node *predblock;
326
327         /* simply add the reload to the beginning of the block if we only have 1
328          * predecessor. We don't need to check for phis as there can't be any in a
329          * block with only 1 pred. */
330         if(get_Block_n_cfgpreds(block) == 1) {
331                 assert(!is_Phi(sched_first(block)));
332                 return sched_first(block);
333         }
334
335         /* We have to reload the value in pred-block */
336         predblock = get_Block_cfgpred_block(block, pos);
337         return be_get_end_of_block_insertion_point(predblock);
338 }
339
340 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
341                           const ir_node *block,
342                           const arch_register_class_t *reload_cls,
343                           int allow_remat)
344 {
345         ir_node *before = be_get_end_of_block_insertion_point(block);
346         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
347 }
348
349 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
350                            int pos,     const arch_register_class_t *reload_cls,
351                            int allow_remat)
352 {
353         ir_node *before = get_block_insertion_point(block, pos);
354         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
355 }
356
357 void be_spill_phi(spill_env_t *env, ir_node *node)
358 {
359         ir_node *block;
360         spill_info_t* spill;
361         int i, arity;
362
363         assert(is_Phi(node));
364
365         ir_nodeset_insert(&env->mem_phis, node);
366
367         /* create spills for the phi arguments */
368         block = get_nodes_block(node);
369         spill = get_spillinfo(env, node);
370         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
371                 ir_node *arg        = get_irn_n(node, i);
372                 ir_node *pred_block = get_Block_cfgpred_block(block, i);
373                 ir_node *insert     = be_get_end_of_block_insertion_point(pred_block);
374                 //get_spillinfo(env, arg);
375                 be_add_spill(env, arg, insert);
376         }
377 }
378
379 /*
380  *   ____                _         ____        _ _ _
381  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
382  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
383  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
384  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
385  *                                      |_|
386  */
387
388 static ir_node *skip_keeps_phis(ir_node *node)
389 {
390         node = sched_next(node);
391         while(is_Phi(node) || be_is_Keep(node)) {
392                 node = sched_next(node);
393         }
394         return node;
395 }
396
397 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
398
399 /**
400  * Creates a spill.
401  *
402  * @param senv      the spill environment
403  * @param irn       the node that should be spilled
404  * @param ctx_irn   an user of the spilled node
405  *
406  * @return a be_Spill node
407  */
408 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
409 {
410         ir_node *to_spill = spillinfo->to_spill;
411         spill_t *spill;
412
413         /* determine_spill_costs must have been run before */
414         assert(spillinfo->spill_costs >= 0);
415
416         /* some backends have virtual noreg/unknown nodes that are not scheduled
417          * and simply always available. */
418         if(!sched_is_scheduled(to_spill)) {
419                 /* override spillinfos or create a new one */
420                 spillinfo->spills->spill = new_NoMem();
421                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
422                 return;
423         }
424
425         DBG((dbg, LEVEL_1, "spilling %+F ... ", to_spill));
426         spill = spillinfo->spills;
427         for( ; spill != NULL; spill = spill->next) {
428                 ir_node *block  = get_block(spill->before);
429                 ir_node *before = spill->before;
430
431                 /* place all spills before the reloads (as we can't guarantee the
432                  * same order as the be_add_spill and be_add_reload calls */
433                 while(get_irn_idx(sched_prev(before)) > env->new_nodes_idx) {
434                         before = sched_prev(before);
435                 }
436
437                 spill->spill    = be_spill(env->arch_env, block, to_spill);
438                 sched_add_before(before, spill->spill);
439                 DB((dbg, LEVEL_1, "\t%+F before %+F,", spill->spill, before));
440 #ifdef FIRM_STATISTICS
441                 env->spill_count++;
442 #endif
443         }
444         DBG((dbg, LEVEL_1, "\n"));
445 }
446
447 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
448
449 /**
450  * If the first usage of a Phi result would be out of memory
451  * there is no sense in allocating a register for it.
452  * Thus we spill it and all its operands to the same spill slot.
453  * Therefore the phi/dataB becomes a phi/Memory
454  *
455  * @param senv      the spill environment
456  * @param phi       the Phi node that should be spilled
457  * @param ctx_irn   an user of the spilled node
458  */
459 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
460 {
461         ir_graph *irg   = env->irg;
462         ir_node  *phi   = spillinfo->to_spill;
463         ir_node  *block = get_nodes_block(phi);
464         ir_node  *unknown;
465         ir_node **ins;
466         spill_t  *spill;
467         int       i;
468         int       arity;
469
470         assert(is_Phi(phi));
471         assert(!get_opt_cse());
472         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
473
474         /* build a new PhiM */
475         arity   = get_irn_arity(phi);
476         ins     = alloca(sizeof(ir_node*) * arity);
477         unknown = new_r_Unknown(irg, mode_M);
478         for(i = 0; i < arity; ++i) {
479                 ins[i] = unknown;
480         }
481
482         /* override or replace spills list... */
483         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
484         spill->before = skip_keeps_phis(phi);
485         spill->spill  = new_r_Phi(irg, block, arity, ins, mode_M);
486         spill->next   = NULL;
487
488         spillinfo->spills = spill;
489 #ifdef FIRM_STATISTICS
490         env->spilled_phi_count++;
491 #endif
492
493         for(i = 0; i < arity; ++i) {
494                 ir_node      *arg      = get_irn_n(phi, i);
495                 spill_info_t *arg_info = get_spillinfo(env, arg);
496
497                 determine_spill_costs(env, arg_info);
498                 spill_node(env, arg_info);
499
500                 set_irn_n(spill->spill, i, arg_info->spills->spill);
501         }
502         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
503              spill->spill));
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 void spill_node(spill_env_t *env, spill_info_t *spillinfo)
513 {
514         ir_node *to_spill;
515
516         /* node is already spilled */
517         if(spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
518                 return;
519
520         to_spill = spillinfo->to_spill;
521
522         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
523                 spill_phi(env, spillinfo);
524         } else {
525                 spill_irn(env, spillinfo);
526         }
527 }
528
529 /*
530  *
531  *  ____                      _            _       _ _
532  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
533  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
534  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
535  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
536  *
537  */
538
539 /**
540  * Tests whether value @p arg is available before node @p reloader
541  * @returns 1 if value is available, 0 otherwise
542  */
543 static int is_value_available(spill_env_t *env, const ir_node *arg,
544                               const ir_node *reloader)
545 {
546         if(is_Unknown(arg) || arg == new_NoMem())
547                 return 1;
548
549         if(be_is_Spill(arg))
550                 return 1;
551
552         if(arg == get_irg_frame(env->irg))
553                 return 1;
554
555         /* hack for now (happens when command should be inserted at end of block) */
556         if(is_Block(reloader)) {
557                 return 0;
558         }
559
560         /*
561          * Ignore registers are always available
562          */
563         if(arch_irn_is(env->arch_env, arg, ignore)) {
564                 return 1;
565         }
566
567         /* the following test does not work while spilling,
568          * because the liveness info is not adapted yet to the effects of the
569          * additional spills/reloads.
570          */
571 #if 0
572         /* we want to remat before the insn reloader
573          * thus an arguments is alive if
574          *   - it interferes with the reloaders result
575          *   - or it is (last-) used by reloader itself
576          */
577         if (values_interfere(env->birg->lv, reloader, arg)) {
578                 return 1;
579         }
580
581         arity = get_irn_arity(reloader);
582         for (i = 0; i < arity; ++i) {
583                 ir_node *rel_arg = get_irn_n(reloader, i);
584                 if (rel_arg == arg)
585                         return 1;
586         }
587 #endif
588
589         return 0;
590 }
591
592 /**
593  * Checks whether the node can principally be rematerialized
594  */
595 static int is_remat_node(spill_env_t *env, const ir_node *node)
596 {
597         const arch_env_t *arch_env = env->arch_env;
598
599         assert(!be_is_Spill(node));
600
601         if(arch_irn_is(arch_env, node, rematerializable))
602                 return 1;
603
604         return 0;
605 }
606
607 /**
608  * Check if a node is rematerializable. This tests for the following conditions:
609  *
610  * - The node itself is rematerializable
611  * - All arguments of the node are available or also rematerialisable
612  * - The costs for the rematerialisation operation is less or equal a limit
613  *
614  * Returns the costs needed for rematerialisation or something
615  * >= REMAT_COST_INFINITE if remat is not possible.
616  */
617 static int check_remat_conditions_costs(spill_env_t *env,
618                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
619 {
620         int i, arity;
621         int argremats;
622         int costs = 0;
623
624         if(!is_remat_node(env, spilled))
625                 return REMAT_COST_INFINITE;
626
627         if(be_is_Reload(spilled)) {
628                 costs += 2;
629         } else {
630                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
631         }
632         if(parentcosts + costs >= env->reload_cost + env->spill_cost) {
633                 return REMAT_COST_INFINITE;
634         }
635         if(arch_irn_is(env->arch_env, spilled, modify_flags)) {
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,
656                                                       parentcosts + costs);
657                 if(parentcosts + costs >= env->reload_cost + env->spill_cost)
658                         return REMAT_COST_INFINITE;
659         }
660
661         return costs;
662 }
663
664 /**
665  * Re-materialize a node.
666  *
667  * @param senv      the spill environment
668  * @param spilled   the node that was spilled
669  * @param reloader  a irn that requires a reload
670  */
671 static 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 *before)
721 {
722         ir_node *block = get_nodes_block(before);
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,
745                            const ir_node *before)
746 {
747         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
748 }
749
750 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
751                                    ir_node *block, int pos)
752 {
753         ir_node *before = get_block_insertion_point(block, pos);
754         return be_get_reload_costs(env, to_spill, before);
755 }
756
757 /*
758  *  ___                     _     ____      _                 _
759  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
760  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
761  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
762  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
763  *
764  */
765
766 /**
767  * analyzes how to best spill a node and determine costs for that
768  */
769 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
770 {
771         ir_node *to_spill = spillinfo->to_spill;
772         ir_node *spill_block;
773         spill_t *spill;
774         double   spill_execfreq;
775
776         /* already calculated? */
777         if(spillinfo->spill_costs >= 0)
778                 return;
779
780         assert(! arch_irn_is(env->arch_env, to_spill, dont_spill));
781         assert(!be_is_Reload(to_spill));
782
783         /* some backends have virtual noreg/unknown nodes that are not scheduled
784          * and simply always available.
785          * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
786          * predecessor (of a PhiM) but this test might match other things too...
787          */
788         if(!sched_is_scheduled(to_spill)) {
789                 /* override spillinfos or create a new one */
790                 spill_t *spill = obstack_alloc(&env->obst, sizeof(spill[0]));
791                 spill->before  = NULL;
792                 spill->next    = NULL;
793                 spill->spill   = new_NoMem();
794
795                 spillinfo->spills      = spill;
796                 spillinfo->spill_costs = 0;
797
798                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
799                 return;
800         }
801
802         spill_block    = get_nodes_block(to_spill);
803         spill_execfreq = get_block_execfreq(env->exec_freq, spill_block);
804
805         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
806                 /* TODO calculate correct costs...
807                  * (though we can't remat this node anyway so no big problem) */
808                 spillinfo->spill_costs = env->spill_cost * spill_execfreq;
809                 return;
810         }
811
812         if(spillinfo->spills != NULL) {
813                 spill_t *s;
814                 double   spills_execfreq;
815
816                 /* calculate sum of executaion frequencies of individual spills */
817                 spills_execfreq = 0;
818                 s               = spillinfo->spills;
819                 for( ; s != NULL; s = s->next) {
820                         ir_node *spill_block = s->before;
821                         double   freq;
822
823                         if(!is_Block(spill_block)) {
824                                 spill_block = get_nodes_block(spill_block);
825                         }
826                         freq = get_block_execfreq(env->exec_freq, spill_block);
827
828                         spills_execfreq += freq;
829                 }
830
831                 DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
832                     spills_execfreq * env->spill_cost,
833                     spill_execfreq * env->spill_cost));
834
835                 /* multi-/latespill is advantageous -> return*/
836                 if(spills_execfreq < spill_execfreq) {
837                         DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
838                         spillinfo->spill_costs = spills_execfreq * env->spill_cost;
839                         return;
840                 }
841         }
842
843         /* override spillinfos or create a new one */
844         spill         = obstack_alloc(&env->obst, sizeof(spill[0]));
845         spill->before = skip_keeps_phis(to_spill);
846         spill->next   = NULL;
847         spill->spill  = NULL;
848
849         spillinfo->spills      = spill;
850         spillinfo->spill_costs = spill_execfreq * env->spill_cost;
851         DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
852 }
853
854 void be_insert_spills_reloads(spill_env_t *env)
855 {
856         ir_graph              *irg       = env->irg;
857         const arch_env_t      *arch_env  = env->arch_env;
858         const ir_exec_freq    *exec_freq = env->exec_freq;
859         spill_info_t          *si;
860         ir_nodeset_iterator_t  iter;
861         ir_node               *node;
862
863         env->new_nodes_idx = get_irg_last_idx(irg);
864
865         /* create all phi-ms first, this is needed so, that phis, hanging on
866            spilled phis work correctly */
867         foreach_ir_nodeset(&env->mem_phis, node, iter) {
868                 spill_info_t *info = get_spillinfo(env, node);
869                 spill_node(env, info);
870         }
871
872         /* process each spilled node */
873         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
874                 reloader_t *rld;
875                 ir_node  *to_spill        = si->to_spill;
876                 ir_mode  *mode            = get_irn_mode(to_spill);
877                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
878                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
879                 int       force_remat     = 0;
880
881                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
882
883                 determine_spill_costs(env, si);
884
885                 /* determine possibility of rematerialisations */
886                 if(be_do_remats) {
887                         /* calculate cost savings for each indivial value when it would
888                            be rematted instead of reloaded */
889                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
890                                 double   freq;
891                                 int      remat_cost;
892                                 int      remat_cost_delta;
893                                 ir_node *block;
894                                 ir_node *reloader = rld->reloader;
895
896                                 if(rld->rematted_node != NULL) {
897                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
898                                              rld->rematted_node, reloader));
899                                         continue;
900                                 }
901                                 if(rld->remat_cost_delta >= REMAT_COST_INFINITE) {
902                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
903                                              reloader));
904                                         all_remat_costs = REMAT_COST_INFINITE;
905                                         continue;
906                                 }
907
908                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
909                                                                            reloader, 0);
910                                 if(remat_cost >= REMAT_COST_INFINITE) {
911                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
912                                              reloader));
913                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
914                                         all_remat_costs       = REMAT_COST_INFINITE;
915                                         continue;
916                                 }
917
918                                 remat_cost_delta      = remat_cost - env->reload_cost;
919                                 rld->remat_cost_delta = remat_cost_delta;
920                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
921                                 freq                  = get_block_execfreq(exec_freq, block);
922                                 all_remat_costs      += remat_cost_delta * freq;
923                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
924                                      "%d (rel %f)\n", reloader, remat_cost_delta,
925                                      remat_cost_delta * freq));
926                         }
927                         if(all_remat_costs < REMAT_COST_INFINITE) {
928                                 /* we don't need the costs for the spill if we can remat
929                                    all reloaders */
930                                 all_remat_costs -= si->spill_costs;
931
932                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
933                                      env->spill_cost, si->spill_costs));
934                         }
935
936                         if(all_remat_costs < 0) {
937                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
938                                      all_remat_costs));
939                                 force_remat = 1;
940                         }
941                 }
942
943                 /* go through all reloads for this spill */
944                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
945                         ir_node *copy; /* a reload is a "copy" of the original value */
946
947                         if (rld->rematted_node != NULL) {
948                                 copy = rld->rematted_node;
949                                 sched_add_before(rld->reloader, copy);
950                         } else if (be_do_remats &&
951                                         (force_remat || rld->remat_cost_delta < 0)) {
952                                 copy = do_remat(env, to_spill, rld->reloader);
953                         } else {
954                                 /* make sure we have a spill */
955                                 spill_node(env, si);
956
957                                 /* create a reload, use the first spill for now SSA
958                                  * reconstruction for memory comes below */
959                                 assert(si->spills != NULL);
960                                 copy = be_reload(arch_env, si->reload_cls, rld->reloader, mode,
961                                                  si->spills->spill);
962 #ifdef FIRM_STATISTICS
963                                 env->reload_count++;
964 #endif
965                         }
966
967                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
968                              copy, to_spill, rld->reloader));
969                         ARR_APP1(ir_node*, copies, copy);
970                 }
971
972                 /* if we had any reloads or remats, then we need to reconstruct the
973                  * SSA form for the spilled value */
974                 if (ARR_LEN(copies) > 0) {
975                         be_ssa_construction_env_t senv;
976                         /* be_lv_t *lv = be_get_birg_liveness(env->birg); */
977
978                         be_ssa_construction_init(&senv, env->birg);
979                         be_ssa_construction_add_copy(&senv, to_spill);
980                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
981                         be_ssa_construction_fix_users(&senv, to_spill);
982
983 #if 0
984                         /* no need to enable this as long as we invalidate liveness
985                            after this function... */
986                         be_ssa_construction_update_liveness_phis(&senv);
987                         be_liveness_update(to_spill);
988                         len = ARR_LEN(copies);
989                         for(i = 0; i < len; ++i) {
990                                 be_liveness_update(lv, copies[i]);
991                         }
992 #endif
993                         be_ssa_construction_destroy(&senv);
994                 }
995                 /* need to reconstruct SSA form if we had multiple spills */
996                 if (si->spills != NULL && si->spills->next != NULL) {
997                         spill_t *spill;
998                         int      spill_count = 0;
999
1000                         be_ssa_construction_env_t senv;
1001
1002                         be_ssa_construction_init(&senv, env->birg);
1003                         spill = si->spills;
1004                         for( ; spill != NULL; spill = spill->next) {
1005                                 /* maybe we rematerialized the value and need no spill */
1006                                 if(spill->spill == NULL)
1007                                         continue;
1008                                 be_ssa_construction_add_copy(&senv, spill->spill);
1009                                 spill_count++;
1010                         }
1011                         if(spill_count > 1) {
1012                                 /* all reloads are attached to the first spill, fix them now */
1013                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1014                         }
1015
1016                         be_ssa_construction_destroy(&senv);
1017                 }
1018
1019                 DEL_ARR_F(copies);
1020                 si->reloaders = NULL;
1021         }
1022
1023         stat_ev_dbl("spill_spills", env->spill_count);
1024         stat_ev_dbl("spill_reloads", env->reload_count);
1025         stat_ev_dbl("spill_remats", env->remat_count);
1026         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1027
1028         /* Matze: In theory be_ssa_construction should take care of the liveness...
1029          * try to disable this again in the future */
1030         be_liveness_invalidate(env->birg->lv);
1031
1032         be_remove_dead_nodes_from_schedule(env->birg);
1033 }
1034
1035 void be_init_spill(void)
1036 {
1037         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1038 }
1039
1040 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);