fix trailing whitespaces and tabulators in the middle of a line
[libfirm] / ir / be / bespillutil.c
1 /*
2  * Copyright (C) 1995-2008 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 #include "config.h"
28
29 #include <stdlib.h>
30 #include <stdbool.h>
31
32 #include "pset.h"
33 #include "irnode_t.h"
34 #include "ircons_t.h"
35 #include "iredges_t.h"
36 #include "irbackedge_t.h"
37 #include "irprintf.h"
38 #include "ident_t.h"
39 #include "type_t.h"
40 #include "entity_t.h"
41 #include "debug.h"
42 #include "irgwalk.h"
43 #include "array.h"
44 #include "pdeq.h"
45 #include "execfreq.h"
46 #include "irnodeset.h"
47 #include "error.h"
48
49 #include "bearch.h"
50 #include "belive_t.h"
51 #include "besched.h"
52 #include "bespill.h"
53 #include "bespillutil.h"
54 #include "belive_t.h"
55 #include "benode.h"
56 #include "bechordal_t.h"
57 #include "bestatevent.h"
58 #include "bessaconstr.h"
59 #include "beirg.h"
60 #include "beintlive_t.h"
61 #include "bemodule.h"
62 #include "be_t.h"
63
64 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
65
66 #define REMAT_COST_INFINITE  1000
67
68 typedef struct reloader_t reloader_t;
69 struct reloader_t {
70         reloader_t *next;
71         ir_node    *can_spill_after;
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_t spill_t;
79 struct spill_t {
80         spill_t *next;
81         ir_node *after;  /**< spill has to be placed after this node (or earlier) */
82         ir_node *spill;
83 };
84
85 typedef struct spill_info_t spill_info_t;
86 struct spill_info_t {
87         ir_node    *to_spill;  /**< the value that should get spilled */
88         reloader_t *reloaders; /**< list of places where the value should get
89                                     reloaded */
90         spill_t    *spills;    /**< list of latest places where spill must be
91                                     placed */
92         double      spill_costs; /**< costs needed for spilling the value */
93         const arch_register_class_t *reload_cls; /** the register class in which the
94                                                      reload should be placed */
95 };
96
97 struct spill_env_t {
98         const arch_env_t *arch_env;
99         ir_graph         *irg;
100         struct obstack    obst;
101         int               spill_cost;     /**< the cost of a single spill node */
102         int               reload_cost;    /**< the cost of a reload node */
103         set              *spills;         /**< all spill_info_t's, which must be
104                                                placed */
105         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
106         ir_exec_freq     *exec_freq;
107
108 #ifdef FIRM_STATISTICS
109         unsigned          spill_count;
110         unsigned          reload_count;
111         unsigned          remat_count;
112         unsigned          spilled_phi_count;
113 #endif
114 };
115
116 /**
117  * Compare two spill infos.
118  */
119 static int cmp_spillinfo(const void *x, const void *y, size_t size)
120 {
121         const spill_info_t *xx = x;
122         const spill_info_t *yy = y;
123         (void) size;
124
125         return xx->to_spill != yy->to_spill;
126 }
127
128 /**
129  * Returns spill info for a specific value (the value that is to be spilled)
130  */
131 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
132 {
133         spill_info_t info, *res;
134         int hash = hash_irn(value);
135
136         info.to_spill = value;
137         res = set_find(env->spills, &info, sizeof(info), hash);
138
139         if (res == NULL) {
140                 info.reloaders   = NULL;
141                 info.spills      = NULL;
142                 info.spill_costs = -1;
143                 info.reload_cls  = NULL;
144                 res = set_insert(env->spills, &info, sizeof(info), hash);
145         }
146
147         return res;
148 }
149
150 spill_env_t *be_new_spill_env(ir_graph *irg)
151 {
152         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
153
154         spill_env_t *env = XMALLOC(spill_env_t);
155         env->spills         = new_set(cmp_spillinfo, 1024);
156         env->irg            = irg;
157         env->arch_env       = arch_env;
158         ir_nodeset_init(&env->mem_phis);
159         env->spill_cost     = arch_env->spill_cost;
160         env->reload_cost    = arch_env->reload_cost;
161         env->exec_freq      = be_get_irg_exec_freq(irg);
162         obstack_init(&env->obst);
163
164 #ifdef FIRM_STATISTICS
165         env->spill_count       = 0;
166         env->reload_count      = 0;
167         env->remat_count       = 0;
168         env->spilled_phi_count = 0;
169 #endif
170
171         return env;
172 }
173
174 void be_delete_spill_env(spill_env_t *env)
175 {
176         del_set(env->spills);
177         ir_nodeset_destroy(&env->mem_phis);
178         obstack_free(&env->obst, NULL);
179         free(env);
180 }
181
182 /*
183  *  ____  _                  ____      _                 _
184  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
185  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
186  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
187  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
188  *
189  */
190
191 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *after)
192 {
193         spill_info_t  *spill_info = get_spillinfo(env, to_spill);
194         spill_t       *spill;
195         spill_t       *s;
196         spill_t       *last;
197
198         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
199         DB((dbg, LEVEL_1, "Add spill of %+F after %+F\n", to_spill, after));
200
201         /* Just for safety make sure that we do not insert the spill in front of a phi */
202         assert(!is_Phi(sched_next(after)));
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->after, after)) {
210                         DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->after));
211                         return;
212                 }
213                 /* remove spills that we dominate */
214                 if (value_dominates(after, s->after)) {
215                         DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->after));
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         = OALLOC(&env->obst, spill_t);
227         spill->after  = after;
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                   = OALLOC(&env->obst, reloader_t);
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         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
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                   = OALLOC(&env->obst, reloader_t);
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 static ir_node *skip_keeps_phis(ir_node *node)
320 {
321         while (true) {
322                 ir_node *next = sched_next(node);
323                 if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
324                         break;
325                 node = next;
326         }
327         return node;
328 }
329
330 /**
331  * Returns the point at which you can insert a node that should be executed
332  * before block @p block when coming from pred @p pos.
333  */
334 static ir_node *get_block_insertion_point(ir_node *block, int pos)
335 {
336         ir_node *predblock;
337
338         /* simply add the reload to the beginning of the block if we only have 1
339          * predecessor. We don't need to check for phis as there can't be any in a
340          * block with only 1 pred. */
341         if (get_Block_n_cfgpreds(block) == 1) {
342                 assert(!is_Phi(sched_first(block)));
343                 return sched_first(block);
344         }
345
346         /* We have to reload the value in pred-block */
347         predblock = get_Block_cfgpred_block(block, pos);
348         return be_get_end_of_block_insertion_point(predblock);
349 }
350
351 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
352                           const ir_node *block,
353                           const arch_register_class_t *reload_cls,
354                           int allow_remat)
355 {
356         ir_node *before = be_get_end_of_block_insertion_point(block);
357         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
358 }
359
360 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
361                            int pos, const arch_register_class_t *reload_cls,
362                            int allow_remat)
363 {
364         ir_node *before = get_block_insertion_point(block, pos);
365         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
366 }
367
368 void be_spill_phi(spill_env_t *env, ir_node *node)
369 {
370         ir_node *block;
371         int i, arity;
372
373         assert(is_Phi(node));
374
375         ir_nodeset_insert(&env->mem_phis, node);
376
377         /* create spills for the phi arguments */
378         block = get_nodes_block(node);
379         for (i = 0, arity = get_irn_arity(node); i < arity; ++i) {
380                 ir_node *arg = get_irn_n(node, i);
381                 ir_node *insert;
382
383                 /* some backends have virtual noreg/unknown nodes that are not scheduled
384                  * and simply always available. */
385                 if (!sched_is_scheduled(arg)) {
386                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
387                         insert = be_get_end_of_block_insertion_point(pred_block);
388                         insert = sched_prev(insert);
389                 } else {
390                         insert = skip_keeps_phis(arg);
391                 }
392
393                 be_add_spill(env, arg, insert);
394         }
395 }
396
397 /*
398  *   ____                _         ____        _ _ _
399  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
400  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
401  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
402  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
403  *                                      |_|
404  */
405
406 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
407
408 /**
409  * Creates a spill.
410  *
411  * @param senv      the spill environment
412  * @param irn       the node that should be spilled
413  * @param ctx_irn   an user of the spilled node
414  *
415  * @return a be_Spill node
416  */
417 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
418 {
419         ir_node       *to_spill = spillinfo->to_spill;
420         const ir_node *insn     = skip_Proj_const(to_spill);
421         spill_t *spill;
422
423         /* determine_spill_costs must have been run before */
424         assert(spillinfo->spill_costs >= 0);
425
426         /* some backends have virtual noreg/unknown nodes that are not scheduled
427          * and simply always available. */
428         if (!sched_is_scheduled(insn)) {
429                 /* override spillinfos or create a new one */
430                 spillinfo->spills->spill = new_NoMem();
431                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
432                 return;
433         }
434
435         DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
436         spill = spillinfo->spills;
437         for ( ; spill != NULL; spill = spill->next) {
438                 ir_node *after = spill->after;
439                 ir_node *block = get_block(after);
440
441                 after = skip_keeps_phis(after);
442
443                 spill->spill = be_spill(block, to_spill);
444                 sched_add_after(skip_Proj(after), spill->spill);
445                 DB((dbg, LEVEL_1, "\t%+F after %+F\n", spill->spill, after));
446 #ifdef FIRM_STATISTICS
447                 env->spill_count++;
448 #endif
449         }
450         DBG((dbg, LEVEL_1, "\n"));
451 }
452
453 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
454
455 /**
456  * If the first usage of a Phi result would be out of memory
457  * there is no sense in allocating a register for it.
458  * Thus we spill it and all its operands to the same spill slot.
459  * Therefore the phi/dataB becomes a phi/Memory
460  *
461  * @param senv      the spill environment
462  * @param phi       the Phi node that should be spilled
463  * @param ctx_irn   an user of the spilled node
464  */
465 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
466 {
467         ir_graph *irg   = env->irg;
468         ir_node  *phi   = spillinfo->to_spill;
469         ir_node  *block = get_nodes_block(phi);
470         ir_node  *unknown;
471         ir_node **ins;
472         spill_t  *spill;
473         int       i;
474         int       arity;
475
476         assert(is_Phi(phi));
477         assert(!get_opt_cse());
478         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
479
480         /* build a new PhiM */
481         arity   = get_irn_arity(phi);
482         ins     = ALLOCAN(ir_node*, arity);
483         unknown = new_r_Unknown(irg, mode_M);
484         for (i = 0; i < arity; ++i) {
485                 ins[i] = unknown;
486         }
487
488         /* override or replace spills list... */
489         spill         = OALLOC(&env->obst, spill_t);
490         spill->after  = skip_keeps_phis(phi);
491         spill->spill  = new_r_Phi(block, arity, ins, mode_M);
492         spill->next   = NULL;
493
494         spillinfo->spills = spill;
495 #ifdef FIRM_STATISTICS
496         env->spilled_phi_count++;
497 #endif
498
499         for (i = 0; i < arity; ++i) {
500                 ir_node      *arg      = get_irn_n(phi, i);
501                 spill_info_t *arg_info = get_spillinfo(env, arg);
502
503                 determine_spill_costs(env, arg_info);
504                 spill_node(env, arg_info);
505
506                 set_irn_n(spill->spill, i, arg_info->spills->spill);
507         }
508         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
509              spill->spill));
510 }
511
512 /**
513  * Spill a node.
514  *
515  * @param senv      the spill environment
516  * @param to_spill  the node that should be spilled
517  */
518 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
519 {
520         ir_node *to_spill;
521
522         /* node is already spilled */
523         if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
524                 return;
525
526         to_spill = spillinfo->to_spill;
527
528         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
529                 spill_phi(env, spillinfo);
530         } else {
531                 spill_irn(env, spillinfo);
532         }
533 }
534
535 /*
536  *
537  *  ____                      _            _       _ _
538  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
539  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
540  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
541  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
542  *
543  */
544
545 /**
546  * Tests whether value @p arg is available before node @p reloader
547  * @returns 1 if value is available, 0 otherwise
548  */
549 static int is_value_available(spill_env_t *env, const ir_node *arg,
550                               const ir_node *reloader)
551 {
552         if (is_Unknown(arg) || arg == new_NoMem())
553                 return 1;
554
555         if (be_is_Spill(skip_Proj_const(arg)))
556                 return 1;
557
558         if (arg == get_irg_frame(env->irg))
559                 return 1;
560
561         (void)reloader;
562
563         if (get_irn_mode(arg) == mode_T)
564                 return 0;
565
566         /*
567          * Ignore registers are always available
568          */
569         if (arch_irn_is_ignore(arg))
570                 return 1;
571
572         return 0;
573 }
574
575 /**
576  * Check if a node is rematerializable. This tests for the following conditions:
577  *
578  * - The node itself is rematerializable
579  * - All arguments of the node are available or also rematerialisable
580  * - The costs for the rematerialisation operation is less or equal a limit
581  *
582  * Returns the costs needed for rematerialisation or something
583  * >= REMAT_COST_INFINITE if remat is not possible.
584  */
585 static int check_remat_conditions_costs(spill_env_t *env,
586                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
587 {
588         int i, arity;
589         int argremats;
590         int costs = 0;
591         const ir_node *insn = skip_Proj_const(spilled);
592
593         assert(!be_is_Spill(insn));
594         if (!arch_irn_is(insn, rematerializable))
595                 return REMAT_COST_INFINITE;
596
597         if (be_is_Reload(insn)) {
598                 costs += 2;
599         } else {
600                 costs += arch_get_op_estimated_cost(insn);
601         }
602         if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
603                 return REMAT_COST_INFINITE;
604         }
605         /* never rematerialize a node which modifies the flags.
606          * (would be better to test wether the flags are actually live at point
607          * reloader...)
608          */
609         if (arch_irn_is(insn, modify_flags)) {
610                 return REMAT_COST_INFINITE;
611         }
612
613         argremats = 0;
614         for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
615                 ir_node *arg = get_irn_n(insn, i);
616
617                 if (is_value_available(env, arg, reloader))
618                         continue;
619
620                 /* we have to rematerialize the argument as well */
621                 ++argremats;
622                 if (argremats > 1) {
623                         /* we only support rematerializing 1 argument at the moment,
624                          * as multiple arguments could increase register pressure */
625                         return REMAT_COST_INFINITE;
626                 }
627
628                 costs += check_remat_conditions_costs(env, arg, reloader,
629                                                       parentcosts + costs);
630                 if (parentcosts + costs >= env->reload_cost + env->spill_cost)
631                         return REMAT_COST_INFINITE;
632         }
633
634         return costs;
635 }
636
637 /**
638  * Re-materialize a node.
639  *
640  * @param senv      the spill environment
641  * @param spilled   the node that was spilled
642  * @param reloader  a irn that requires a reload
643  */
644 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
645 {
646         int i, arity;
647         ir_node *res;
648         ir_node *bl;
649         ir_node **ins;
650
651         if (is_Block(reloader)) {
652                 bl = reloader;
653         } else {
654                 bl = get_nodes_block(reloader);
655         }
656
657         ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
658         for (i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
659                 ir_node *arg = get_irn_n(spilled, i);
660
661                 if (is_value_available(env, arg, reloader)) {
662                         ins[i] = arg;
663                 } else {
664                         ins[i] = do_remat(env, arg, reloader);
665 #ifdef FIRM_STATISTICS
666                         /* don't count the recursive call as remat */
667                         env->remat_count--;
668 #endif
669                 }
670         }
671
672         /* create a copy of the node */
673         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
674                           get_irn_op(spilled), get_irn_mode(spilled),
675                           get_irn_arity(spilled), ins);
676         copy_node_attr(env->irg, spilled, res);
677         arch_env_mark_remat(env->arch_env, res);
678
679         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
680
681         if (! is_Proj(res)) {
682                 /* insert in schedule */
683                 sched_reset(res);
684                 sched_add_before(reloader, res);
685 #ifdef FIRM_STATISTICS
686                 env->remat_count++;
687 #endif
688         }
689
690         return res;
691 }
692
693 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
694 {
695         ir_node *block = get_nodes_block(before);
696         double   freq  = get_block_execfreq(env->exec_freq, block);
697         (void) to_spill;
698
699         return env->spill_cost * freq;
700 }
701
702 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
703                                        const ir_node *before)
704 {
705         if (be_do_remats) {
706                 /* is the node rematerializable? */
707                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
708                 if (costs < (unsigned) env->reload_cost)
709                         return costs;
710         }
711
712         return env->reload_cost;
713 }
714
715 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
716 {
717         ir_node      *block = get_nodes_block(before);
718         double        freq  = get_block_execfreq(env->exec_freq, block);
719
720         if (be_do_remats) {
721                 /* is the node rematerializable? */
722                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
723                 if (costs < env->reload_cost)
724                         return costs * freq;
725         }
726
727         return env->reload_cost * freq;
728 }
729
730 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
731                            const ir_node *before)
732 {
733         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
734 }
735
736 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
737                                    ir_node *block, int pos)
738 {
739         ir_node *before = get_block_insertion_point(block, pos);
740         return be_get_reload_costs(env, to_spill, before);
741 }
742
743 /*
744  *  ___                     _     ____      _                 _
745  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
746  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
747  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
748  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
749  *
750  */
751
752 /**
753  * analyzes how to best spill a node and determine costs for that
754  */
755 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
756 {
757         ir_node       *to_spill = spillinfo->to_spill;
758         const ir_node *insn     = skip_Proj_const(to_spill);
759         ir_node       *spill_block;
760         spill_t       *spill;
761         double         spill_execfreq;
762
763         /* already calculated? */
764         if (spillinfo->spill_costs >= 0)
765                 return;
766
767         assert(!arch_irn_is(insn, dont_spill));
768         assert(!be_is_Reload(insn));
769
770         /* some backends have virtual noreg/unknown nodes that are not scheduled
771          * and simply always available.
772          * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
773          * predecessor (of a PhiM) but this test might match other things too...
774          */
775         if (!sched_is_scheduled(insn)) {
776                 /* override spillinfos or create a new one */
777                 spill_t *spill = OALLOC(&env->obst, spill_t);
778                 spill->after = NULL;
779                 spill->next  = NULL;
780                 spill->spill = new_NoMem();
781
782                 spillinfo->spills      = spill;
783                 spillinfo->spill_costs = 0;
784
785                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
786                 return;
787         }
788
789         spill_block    = get_nodes_block(insn);
790         spill_execfreq = get_block_execfreq(env->exec_freq, spill_block);
791
792         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
793                 /* TODO calculate correct costs...
794                  * (though we can't remat this node anyway so no big problem) */
795                 spillinfo->spill_costs = env->spill_cost * spill_execfreq;
796                 return;
797         }
798
799         if (spillinfo->spills != NULL) {
800                 spill_t *s;
801                 double   spills_execfreq;
802
803                 /* calculate sum of execution frequencies of individual spills */
804                 spills_execfreq = 0;
805                 s               = spillinfo->spills;
806                 for ( ; s != NULL; s = s->next) {
807                         ir_node *spill_block = get_block(s->after);
808                         double   freq = get_block_execfreq(env->exec_freq, spill_block);
809
810                         spills_execfreq += freq;
811                 }
812
813                 DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
814                     spills_execfreq * env->spill_cost,
815                     spill_execfreq * env->spill_cost));
816
817                 /* multi-/latespill is advantageous -> return*/
818                 if (spills_execfreq < spill_execfreq) {
819                         DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
820                         spillinfo->spill_costs = spills_execfreq * env->spill_cost;
821                         return;
822                 }
823         }
824
825         /* override spillinfos or create a new one */
826         spill        = OALLOC(&env->obst, spill_t);
827         spill->after = skip_keeps_phis(to_spill);
828         spill->next  = NULL;
829         spill->spill = NULL;
830
831         spillinfo->spills      = spill;
832         spillinfo->spill_costs = spill_execfreq * env->spill_cost;
833         DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
834 }
835
836 void make_spill_locations_dominate_irn(spill_env_t *env, ir_node *irn)
837 {
838         const spill_info_t *si = get_spillinfo(env, irn);
839         ir_node *start_block   = get_irg_start_block(get_irn_irg(irn));
840         int n_blocks           = get_Block_dom_max_subtree_pre_num(start_block);
841         bitset_t *reloads      = bitset_alloca(n_blocks);
842         reloader_t *r;
843         spill_t *s;
844
845         if (si == NULL)
846                 return;
847
848         /* Fill the bitset with the dominance pre-order numbers
849          * of the blocks the reloads are located in. */
850         for (r = si->reloaders; r != NULL; r = r->next) {
851                 ir_node *bl = get_nodes_block(r->reloader);
852                 bitset_set(reloads, get_Block_dom_tree_pre_num(bl));
853         }
854
855         /* Now, cancel out all the blocks that are dominated by each spill.
856          * If the bitset is not empty after that, we have reloads that are
857          * not dominated by any spill. */
858         for (s = si->spills; s != NULL; s = s->next) {
859                 ir_node *bl = get_nodes_block(s->after);
860                 int start   = get_Block_dom_tree_pre_num(bl);
861                 int end     = get_Block_dom_max_subtree_pre_num(bl);
862
863                 bitset_clear_range(reloads, start, end);
864         }
865
866         if (!bitset_is_empty(reloads))
867                 be_add_spill(env, si->to_spill, si->to_spill);
868 }
869
870 void be_insert_spills_reloads(spill_env_t *env)
871 {
872         const ir_exec_freq    *exec_freq = env->exec_freq;
873         spill_info_t          *si;
874         ir_nodeset_iterator_t  iter;
875         ir_node               *node;
876
877         be_timer_push(T_RA_SPILL_APPLY);
878
879         /* create all phi-ms first, this is needed so, that phis, hanging on
880            spilled phis work correctly */
881         foreach_ir_nodeset(&env->mem_phis, node, iter) {
882                 spill_info_t *info = get_spillinfo(env, node);
883                 spill_node(env, info);
884         }
885
886         /* process each spilled node */
887         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
888                 reloader_t *rld;
889                 ir_node  *to_spill        = si->to_spill;
890                 ir_mode  *mode            = get_irn_mode(to_spill);
891                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
892                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
893                 int       force_remat     = 0;
894
895                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
896
897                 determine_spill_costs(env, si);
898
899                 /* determine possibility of rematerialisations */
900                 if (be_do_remats) {
901                         /* calculate cost savings for each indivial value when it would
902                            be rematted instead of reloaded */
903                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
904                                 double   freq;
905                                 int      remat_cost;
906                                 int      remat_cost_delta;
907                                 ir_node *block;
908                                 ir_node *reloader = rld->reloader;
909
910                                 if (rld->rematted_node != NULL) {
911                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
912                                              rld->rematted_node, reloader));
913                                         continue;
914                                 }
915                                 if (rld->remat_cost_delta >= REMAT_COST_INFINITE) {
916                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
917                                              reloader));
918                                         all_remat_costs = REMAT_COST_INFINITE;
919                                         continue;
920                                 }
921
922                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
923                                                                            reloader, 0);
924                                 if (remat_cost >= REMAT_COST_INFINITE) {
925                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
926                                              reloader));
927                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
928                                         all_remat_costs       = REMAT_COST_INFINITE;
929                                         continue;
930                                 }
931
932                                 remat_cost_delta      = remat_cost - env->reload_cost;
933                                 rld->remat_cost_delta = remat_cost_delta;
934                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
935                                 freq                  = get_block_execfreq(exec_freq, block);
936                                 all_remat_costs      += remat_cost_delta * freq;
937                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
938                                      "%d (rel %f)\n", reloader, remat_cost_delta,
939                                      remat_cost_delta * freq));
940                         }
941                         if (all_remat_costs < REMAT_COST_INFINITE) {
942                                 /* we don't need the costs for the spill if we can remat
943                                    all reloaders */
944                                 all_remat_costs -= si->spill_costs;
945
946                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
947                                      env->spill_cost, si->spill_costs));
948                         }
949
950                         if (all_remat_costs < 0) {
951                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
952                                      all_remat_costs));
953                                 force_remat = 1;
954                         }
955                 }
956
957                 /* go through all reloads for this spill */
958                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
959                         ir_node *copy; /* a reload is a "copy" of the original value */
960
961                         if (rld->rematted_node != NULL) {
962                                 copy = rld->rematted_node;
963                                 sched_add_before(rld->reloader, copy);
964                         } else if (be_do_remats &&
965                                         (force_remat || rld->remat_cost_delta < 0)) {
966                                 copy = do_remat(env, to_spill, rld->reloader);
967                         } else {
968                                 /* make sure we have a spill */
969                                 spill_node(env, si);
970
971                                 /* create a reload, use the first spill for now SSA
972                                  * reconstruction for memory comes below */
973                                 assert(si->spills != NULL);
974                                 copy = be_reload(si->reload_cls, rld->reloader, mode,
975                                                  si->spills->spill);
976 #ifdef FIRM_STATISTICS
977                                 env->reload_count++;
978 #endif
979                         }
980
981                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
982                              copy, to_spill, rld->reloader));
983                         ARR_APP1(ir_node*, copies, copy);
984                 }
985
986                 /* if we had any reloads or remats, then we need to reconstruct the
987                  * SSA form for the spilled value */
988                 if (ARR_LEN(copies) > 0) {
989                         be_ssa_construction_env_t senv;
990                         /* be_lv_t *lv = be_get_irg_liveness(env->irg); */
991
992                         be_ssa_construction_init(&senv, env->irg);
993                         be_ssa_construction_add_copy(&senv, to_spill);
994                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
995                         be_ssa_construction_fix_users(&senv, to_spill);
996
997 #if 0
998                         /* no need to enable this as long as we invalidate liveness
999                            after this function... */
1000                         be_ssa_construction_update_liveness_phis(&senv);
1001                         be_liveness_update(to_spill);
1002                         len = ARR_LEN(copies);
1003                         for (i = 0; i < len; ++i) {
1004                                 be_liveness_update(lv, copies[i]);
1005                         }
1006 #endif
1007                         be_ssa_construction_destroy(&senv);
1008                 }
1009                 /* need to reconstruct SSA form if we had multiple spills */
1010                 if (si->spills != NULL && si->spills->next != NULL) {
1011                         spill_t *spill;
1012                         int      spill_count = 0;
1013
1014                         be_ssa_construction_env_t senv;
1015
1016                         be_ssa_construction_init(&senv, env->irg);
1017                         spill = si->spills;
1018                         for ( ; spill != NULL; spill = spill->next) {
1019                                 /* maybe we rematerialized the value and need no spill */
1020                                 if (spill->spill == NULL)
1021                                         continue;
1022                                 be_ssa_construction_add_copy(&senv, spill->spill);
1023                                 spill_count++;
1024                         }
1025                         if (spill_count > 1) {
1026                                 /* all reloads are attached to the first spill, fix them now */
1027                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1028                         }
1029
1030                         be_ssa_construction_destroy(&senv);
1031                 }
1032
1033                 DEL_ARR_F(copies);
1034                 si->reloaders = NULL;
1035         }
1036
1037         stat_ev_dbl("spill_spills", env->spill_count);
1038         stat_ev_dbl("spill_reloads", env->reload_count);
1039         stat_ev_dbl("spill_remats", env->remat_count);
1040         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1041
1042         /* Matze: In theory be_ssa_construction should take care of the liveness...
1043          * try to disable this again in the future */
1044         be_liveness_invalidate(be_get_irg_liveness(env->irg));
1045
1046         be_remove_dead_nodes_from_schedule(env->irg);
1047
1048         be_timer_pop(T_RA_SPILL_APPLY);
1049 }
1050
1051 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);
1052 void be_init_spill(void)
1053 {
1054         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1055 }