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