remove unused be_add_remat function
[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 "beirgmod.h"
61 #include "beintlive_t.h"
62 #include "bemodule.h"
63 #include "be_t.h"
64
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 #define REMAT_COST_INFINITE  1000
68
69 typedef struct reloader_t reloader_t;
70 struct reloader_t {
71         reloader_t *next;
72         ir_node    *can_spill_after;
73         ir_node    *reloader;
74         ir_node    *rematted_node;
75         int         remat_cost_delta; /** costs needed for rematerialization,
76                                            compared to placing a reload */
77 };
78
79 typedef struct spill_t spill_t;
80 struct spill_t {
81         spill_t *next;
82         ir_node *after;  /**< spill has to be placed after this node (or earlier) */
83         ir_node *spill;
84 };
85
86 typedef struct spill_info_t spill_info_t;
87 struct spill_info_t {
88         ir_node    *to_spill;  /**< the value that should get spilled */
89         reloader_t *reloaders; /**< list of places where the value should get
90                                     reloaded */
91         spill_t    *spills;    /**< list of latest places where spill must be
92                                     placed */
93         double      spill_costs; /**< costs needed for spilling the value */
94         const arch_register_class_t *reload_cls; /** the register class in which the
95                                                      reload should be placed */
96 };
97
98 struct spill_env_t {
99         const arch_env_t *arch_env;
100         ir_graph         *irg;
101         struct obstack    obst;
102         int               spill_cost;     /**< the cost of a single spill node */
103         int               reload_cost;    /**< the cost of a reload node */
104         set              *spills;         /**< all spill_info_t's, which must be
105                                                placed */
106         ir_nodeset_t      mem_phis;       /**< set of all spilled phis. */
107         ir_exec_freq     *exec_freq;
108
109 #ifdef FIRM_STATISTICS
110         unsigned          spill_count;
111         unsigned          reload_count;
112         unsigned          remat_count;
113         unsigned          spilled_phi_count;
114 #endif
115 };
116
117 /**
118  * Compare two spill infos.
119  */
120 static int cmp_spillinfo(const void *x, const void *y, size_t size)
121 {
122         const spill_info_t *xx = (const spill_info_t*)x;
123         const spill_info_t *yy = (const spill_info_t*)y;
124         (void) size;
125
126         return xx->to_spill != yy->to_spill;
127 }
128
129 /**
130  * Returns spill info for a specific value (the value that is to be spilled)
131  */
132 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value)
133 {
134         spill_info_t info, *res;
135         int hash = hash_irn(value);
136
137         info.to_spill = value;
138         res = (spill_info_t*)set_find(env->spills, &info, sizeof(info), hash);
139
140         if (res == NULL) {
141                 info.reloaders   = NULL;
142                 info.spills      = NULL;
143                 info.spill_costs = -1;
144                 info.reload_cls  = NULL;
145                 res = (spill_info_t*)set_insert(env->spills, &info, sizeof(info), hash);
146         }
147
148         return res;
149 }
150
151 spill_env_t *be_new_spill_env(ir_graph *irg)
152 {
153         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
154
155         spill_env_t *env = XMALLOC(spill_env_t);
156         env->spills         = new_set(cmp_spillinfo, 1024);
157         env->irg            = irg;
158         env->arch_env       = arch_env;
159         ir_nodeset_init(&env->mem_phis);
160         env->spill_cost     = arch_env->spill_cost;
161         env->reload_cost    = arch_env->reload_cost;
162         env->exec_freq      = be_get_irg_exec_freq(irg);
163         obstack_init(&env->obst);
164
165 #ifdef FIRM_STATISTICS
166         env->spill_count       = 0;
167         env->reload_count      = 0;
168         env->remat_count       = 0;
169         env->spilled_phi_count = 0;
170 #endif
171
172         return env;
173 }
174
175 void be_delete_spill_env(spill_env_t *env)
176 {
177         del_set(env->spills);
178         ir_nodeset_destroy(&env->mem_phis);
179         obstack_free(&env->obst, NULL);
180         free(env);
181 }
182
183 /*
184  *  ____  _                  ____      _                 _
185  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
186  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
187  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
188  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
189  *
190  */
191
192 void be_add_spill(spill_env_t *env, ir_node *to_spill, ir_node *after)
193 {
194         spill_info_t  *spill_info = get_spillinfo(env, to_spill);
195         spill_t       *spill;
196         spill_t       *s;
197         spill_t       *last;
198
199         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
200         DB((dbg, LEVEL_1, "Add spill of %+F after %+F\n", to_spill, after));
201
202         /* Just for safety make sure that we do not insert the spill in front of a phi */
203         assert(!is_Phi(sched_next(after)));
204
205         /* spills that are dominated by others are not needed */
206         last = NULL;
207         s    = spill_info->spills;
208         for ( ; s != NULL; s = s->next) {
209                 /* no need to add this spill if it is dominated by another */
210                 if (value_dominates(s->after, after)) {
211                         DB((dbg, LEVEL_1, "...dominated by %+F, not added\n", s->after));
212                         return;
213                 }
214                 /* remove spills that we dominate */
215                 if (value_dominates(after, s->after)) {
216                         DB((dbg, LEVEL_1, "...remove old spill at %+F\n", s->after));
217                         if (last != NULL) {
218                                 last->next         = s->next;
219                         } else {
220                                 spill_info->spills = s->next;
221                         }
222                 } else {
223                         last = s;
224                 }
225         }
226
227         spill         = OALLOC(&env->obst, spill_t);
228         spill->after  = after;
229         spill->next   = spill_info->spills;
230         spill->spill  = NULL;
231
232         spill_info->spills = spill;
233 }
234
235 void be_add_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before,
236                 ir_node *can_spill_after, const arch_register_class_t *reload_cls,
237                 int allow_remat)
238 {
239         spill_info_t  *info;
240         reloader_t    *rel;
241
242         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
243
244         info = get_spillinfo(env, to_spill);
245
246         if (is_Phi(to_spill)) {
247                 int i, arity;
248
249                 /* create spillinfos for the phi arguments */
250                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
251                         ir_node *arg = get_irn_n(to_spill, i);
252                         get_spillinfo(env, arg);
253                 }
254         }
255
256         assert(!is_Proj(before) && !be_is_Keep(before));
257
258         /* put reload into list */
259         rel                   = OALLOC(&env->obst, reloader_t);
260         rel->next             = info->reloaders;
261         rel->reloader         = before;
262         rel->rematted_node    = NULL;
263         rel->can_spill_after  = can_spill_after;
264         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
265
266         info->reloaders  = rel;
267         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
268         info->reload_cls = reload_cls;
269
270         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
271                 to_spill, before, allow_remat ? "" : " not"));
272 }
273
274 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
275                    const arch_register_class_t *reload_cls, int allow_remat)
276 {
277         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
278
279 }
280
281 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
282 {
283         ir_node *last = sched_last(block);
284
285         /* we might have keeps behind the jump... */
286         while (be_is_Keep(last)) {
287                 last = sched_prev(last);
288                 assert(!sched_is_end(last));
289         }
290
291         assert(is_cfop(last));
292
293         /* add the reload before the (cond-)jump */
294         return last;
295 }
296
297 static ir_node *skip_keeps_phis(ir_node *node)
298 {
299         while (true) {
300                 ir_node *next = sched_next(node);
301                 if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
302                         break;
303                 node = next;
304         }
305         return node;
306 }
307
308 /**
309  * Returns the point at which you can insert a node that should be executed
310  * before block @p block when coming from pred @p pos.
311  */
312 static ir_node *get_block_insertion_point(ir_node *block, int pos)
313 {
314         ir_node *predblock;
315
316         /* simply add the reload to the beginning of the block if we only have 1
317          * predecessor. We don't need to check for phis as there can't be any in a
318          * block with only 1 pred. */
319         if (get_Block_n_cfgpreds(block) == 1) {
320                 assert(!is_Phi(sched_first(block)));
321                 return sched_first(block);
322         }
323
324         /* We have to reload the value in pred-block */
325         predblock = get_Block_cfgpred_block(block, pos);
326         return be_get_end_of_block_insertion_point(predblock);
327 }
328
329 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
330                           const ir_node *block,
331                           const arch_register_class_t *reload_cls,
332                           int allow_remat)
333 {
334         ir_node *before = be_get_end_of_block_insertion_point(block);
335         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
336 }
337
338 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
339                            int pos, const arch_register_class_t *reload_cls,
340                            int allow_remat)
341 {
342         ir_node *before = get_block_insertion_point(block, pos);
343         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
344 }
345
346 void be_spill_phi(spill_env_t *env, ir_node *node)
347 {
348         ir_node *block;
349         int i, arity;
350
351         assert(is_Phi(node));
352
353         ir_nodeset_insert(&env->mem_phis, node);
354
355         /* create spills for the phi arguments */
356         block = get_nodes_block(node);
357         for (i = 0, arity = get_irn_arity(node); i < arity; ++i) {
358                 ir_node *arg = get_irn_n(node, i);
359                 ir_node *insert;
360
361                 /* some backends have virtual noreg/unknown nodes that are not scheduled
362                  * and simply always available. */
363                 if (!sched_is_scheduled(arg)) {
364                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
365                         insert = be_get_end_of_block_insertion_point(pred_block);
366                         insert = sched_prev(insert);
367                 } else {
368                         insert = skip_keeps_phis(arg);
369                 }
370
371                 be_add_spill(env, arg, insert);
372         }
373 }
374
375 /*
376  *   ____                _         ____        _ _ _
377  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
378  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
379  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
380  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
381  *                                      |_|
382  */
383
384 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
385
386 /**
387  * Creates a spill.
388  *
389  * @param senv      the spill environment
390  * @param irn       the node that should be spilled
391  * @param ctx_irn   an user of the spilled node
392  *
393  * @return a be_Spill node
394  */
395 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
396 {
397         ir_node       *to_spill = spillinfo->to_spill;
398         const ir_node *insn     = skip_Proj_const(to_spill);
399         spill_t *spill;
400
401         /* determine_spill_costs must have been run before */
402         assert(spillinfo->spill_costs >= 0);
403
404         /* some backends have virtual noreg/unknown nodes that are not scheduled
405          * and simply always available. */
406         if (!sched_is_scheduled(insn)) {
407                 /* override spillinfos or create a new one */
408                 ir_graph *irg = get_irn_irg(to_spill);
409                 spillinfo->spills->spill = new_r_NoMem(irg);
410                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
411                 return;
412         }
413
414         DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
415         spill = spillinfo->spills;
416         for ( ; spill != NULL; spill = spill->next) {
417                 ir_node *after = spill->after;
418                 ir_node *block = get_block(after);
419
420                 after = skip_keeps_phis(after);
421
422                 spill->spill = be_spill(block, to_spill);
423                 sched_add_after(skip_Proj(after), spill->spill);
424                 DB((dbg, LEVEL_1, "\t%+F after %+F\n", spill->spill, after));
425 #ifdef FIRM_STATISTICS
426                 env->spill_count++;
427 #endif
428         }
429         DBG((dbg, LEVEL_1, "\n"));
430 }
431
432 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
433
434 /**
435  * If the first usage of a Phi result would be out of memory
436  * there is no sense in allocating a register for it.
437  * Thus we spill it and all its operands to the same spill slot.
438  * Therefore the phi/dataB becomes a phi/Memory
439  *
440  * @param senv      the spill environment
441  * @param phi       the Phi node that should be spilled
442  * @param ctx_irn   an user of the spilled node
443  */
444 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
445 {
446         ir_graph *irg   = env->irg;
447         ir_node  *phi   = spillinfo->to_spill;
448         ir_node  *block = get_nodes_block(phi);
449         ir_node  *unknown;
450         ir_node **ins;
451         spill_t  *spill;
452         int       i;
453         int       arity;
454
455         assert(is_Phi(phi));
456         assert(!get_opt_cse());
457         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
458
459         /* build a new PhiM */
460         arity   = get_irn_arity(phi);
461         ins     = ALLOCAN(ir_node*, arity);
462         unknown = new_r_Unknown(irg, mode_M);
463         for (i = 0; i < arity; ++i) {
464                 ins[i] = unknown;
465         }
466
467         /* override or replace spills list... */
468         spill         = OALLOC(&env->obst, spill_t);
469         spill->after  = skip_keeps_phis(phi);
470         spill->spill  = be_new_Phi(block, arity, ins, mode_M, NULL);
471         spill->next   = NULL;
472         sched_add_after(block, spill->spill);
473
474         spillinfo->spills = spill;
475 #ifdef FIRM_STATISTICS
476         env->spilled_phi_count++;
477 #endif
478
479         for (i = 0; i < arity; ++i) {
480                 ir_node      *arg      = get_irn_n(phi, i);
481                 spill_info_t *arg_info = get_spillinfo(env, arg);
482
483                 determine_spill_costs(env, arg_info);
484                 spill_node(env, arg_info);
485
486                 set_irn_n(spill->spill, i, arg_info->spills->spill);
487         }
488         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
489              spill->spill));
490 }
491
492 /**
493  * Spill a node.
494  *
495  * @param senv      the spill environment
496  * @param to_spill  the node that should be spilled
497  */
498 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
499 {
500         ir_node *to_spill;
501
502         /* node is already spilled */
503         if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
504                 return;
505
506         to_spill = spillinfo->to_spill;
507
508         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
509                 spill_phi(env, spillinfo);
510         } else {
511                 spill_irn(env, spillinfo);
512         }
513 }
514
515 /*
516  *
517  *  ____                      _            _       _ _
518  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
519  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
520  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
521  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
522  *
523  */
524
525 /**
526  * Tests whether value @p arg is available before node @p reloader
527  * @returns 1 if value is available, 0 otherwise
528  */
529 static int is_value_available(spill_env_t *env, const ir_node *arg,
530                               const ir_node *reloader)
531 {
532         if (is_Unknown(arg) || is_NoMem(arg))
533                 return 1;
534
535         if (be_is_Spill(skip_Proj_const(arg)))
536                 return 1;
537
538         if (arg == get_irg_frame(env->irg))
539                 return 1;
540
541         (void)reloader;
542
543         if (get_irn_mode(arg) == mode_T)
544                 return 0;
545
546         /*
547          * Ignore registers are always available
548          */
549         if (arch_irn_is_ignore(arg))
550                 return 1;
551
552         return 0;
553 }
554
555 /**
556  * Check if a node is rematerializable. This tests for the following conditions:
557  *
558  * - The node itself is rematerializable
559  * - All arguments of the node are available or also rematerialisable
560  * - The costs for the rematerialisation operation is less or equal a limit
561  *
562  * Returns the costs needed for rematerialisation or something
563  * >= REMAT_COST_INFINITE if remat is not possible.
564  */
565 static int check_remat_conditions_costs(spill_env_t *env,
566                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
567 {
568         int i, arity;
569         int argremats;
570         int costs = 0;
571         const ir_node *insn = skip_Proj_const(spilled);
572
573         assert(!be_is_Spill(insn));
574         if (!arch_irn_is(insn, rematerializable))
575                 return REMAT_COST_INFINITE;
576
577         if (be_is_Reload(insn)) {
578                 costs += 2;
579         } else {
580                 costs += arch_get_op_estimated_cost(insn);
581         }
582         if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
583                 return REMAT_COST_INFINITE;
584         }
585         /* never rematerialize a node which modifies the flags.
586          * (would be better to test wether the flags are actually live at point
587          * reloader...)
588          */
589         if (arch_irn_is(insn, modify_flags)) {
590                 return REMAT_COST_INFINITE;
591         }
592
593         argremats = 0;
594         for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
595                 ir_node *arg = get_irn_n(insn, i);
596
597                 if (is_value_available(env, arg, reloader))
598                         continue;
599
600                 /* we have to rematerialize the argument as well */
601                 ++argremats;
602                 if (argremats > 1) {
603                         /* we only support rematerializing 1 argument at the moment,
604                          * as multiple arguments could increase register pressure */
605                         return REMAT_COST_INFINITE;
606                 }
607
608                 costs += check_remat_conditions_costs(env, arg, reloader,
609                                                       parentcosts + costs);
610                 if (parentcosts + costs >= env->reload_cost + env->spill_cost)
611                         return REMAT_COST_INFINITE;
612         }
613
614         return costs;
615 }
616
617 /**
618  * Re-materialize a node.
619  *
620  * @param senv      the spill environment
621  * @param spilled   the node that was spilled
622  * @param reloader  a irn that requires a reload
623  */
624 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
625 {
626         int i, arity;
627         ir_node *res;
628         ir_node *bl;
629         ir_node **ins;
630
631         if (is_Block(reloader)) {
632                 bl = reloader;
633         } else {
634                 bl = get_nodes_block(reloader);
635         }
636
637         ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
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                         ins[i] = arg;
643                 } else {
644                         ins[i] = do_remat(env, arg, reloader);
645 #ifdef FIRM_STATISTICS
646                         /* don't count the recursive call as remat */
647                         env->remat_count--;
648 #endif
649                 }
650         }
651
652         /* create a copy of the node */
653         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
654                           get_irn_op(spilled), get_irn_mode(spilled),
655                           get_irn_arity(spilled), ins);
656         copy_node_attr(env->irg, spilled, res);
657         arch_env_mark_remat(env->arch_env, res);
658
659         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
660
661         if (! is_Proj(res)) {
662                 /* insert in schedule */
663                 sched_reset(res);
664                 sched_add_before(reloader, res);
665 #ifdef FIRM_STATISTICS
666                 env->remat_count++;
667 #endif
668         }
669
670         return res;
671 }
672
673 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
674 {
675         ir_node *block = get_nodes_block(before);
676         double   freq  = get_block_execfreq(env->exec_freq, block);
677         (void) to_spill;
678
679         return env->spill_cost * freq;
680 }
681
682 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
683                                        const ir_node *before)
684 {
685         if (be_do_remats) {
686                 /* is the node rematerializable? */
687                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
688                 if (costs < (unsigned) env->reload_cost)
689                         return costs;
690         }
691
692         return env->reload_cost;
693 }
694
695 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
696 {
697         ir_node      *block = get_nodes_block(before);
698         double        freq  = get_block_execfreq(env->exec_freq, block);
699
700         if (be_do_remats) {
701                 /* is the node rematerializable? */
702                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
703                 if (costs < env->reload_cost)
704                         return costs * freq;
705         }
706
707         return env->reload_cost * freq;
708 }
709
710 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
711                            const ir_node *before)
712 {
713         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
714 }
715
716 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
717                                    ir_node *block, int pos)
718 {
719         ir_node *before = get_block_insertion_point(block, pos);
720         return be_get_reload_costs(env, to_spill, before);
721 }
722
723 /*
724  *  ___                     _     ____      _                 _
725  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
726  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
727  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
728  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
729  *
730  */
731
732 /**
733  * analyzes how to best spill a node and determine costs for that
734  */
735 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo)
736 {
737         ir_node       *to_spill = spillinfo->to_spill;
738         const ir_node *insn     = skip_Proj_const(to_spill);
739         ir_node       *spill_block;
740         spill_t       *spill;
741         double         spill_execfreq;
742
743         /* already calculated? */
744         if (spillinfo->spill_costs >= 0)
745                 return;
746
747         assert(!arch_irn_is(insn, dont_spill));
748         assert(!be_is_Reload(insn));
749
750         /* some backends have virtual noreg/unknown nodes that are not scheduled
751          * and simply always available.
752          * TODO: this is kinda hairy, the NoMem is correct for an Unknown as Phi
753          * predecessor (of a PhiM) but this test might match other things too...
754          */
755         if (!sched_is_scheduled(insn)) {
756                 ir_graph *irg = get_irn_irg(to_spill);
757                 /* override spillinfos or create a new one */
758                 spill_t *spill = OALLOC(&env->obst, spill_t);
759                 spill->after = NULL;
760                 spill->next  = NULL;
761                 spill->spill = new_r_NoMem(irg);
762
763                 spillinfo->spills      = spill;
764                 spillinfo->spill_costs = 0;
765
766                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
767                 return;
768         }
769
770         spill_block    = get_nodes_block(insn);
771         spill_execfreq = get_block_execfreq(env->exec_freq, spill_block);
772
773         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
774                 /* TODO calculate correct costs...
775                  * (though we can't remat this node anyway so no big problem) */
776                 spillinfo->spill_costs = env->spill_cost * spill_execfreq;
777                 return;
778         }
779
780         if (spillinfo->spills != NULL) {
781                 spill_t *s;
782                 double   spills_execfreq;
783
784                 /* calculate sum of execution frequencies of individual spills */
785                 spills_execfreq = 0;
786                 s               = spillinfo->spills;
787                 for ( ; s != NULL; s = s->next) {
788                         ir_node *spill_block = get_block(s->after);
789                         double   freq = get_block_execfreq(env->exec_freq, spill_block);
790
791                         spills_execfreq += freq;
792                 }
793
794                 DB((dbg, LEVEL_1, "%+F: latespillcosts %f after def: %f\n", to_spill,
795                     spills_execfreq * env->spill_cost,
796                     spill_execfreq * env->spill_cost));
797
798                 /* multi-/latespill is advantageous -> return*/
799                 if (spills_execfreq < spill_execfreq) {
800                         DB((dbg, LEVEL_1, "use latespills for %+F\n", to_spill));
801                         spillinfo->spill_costs = spills_execfreq * env->spill_cost;
802                         return;
803                 }
804         }
805
806         /* override spillinfos or create a new one */
807         spill        = OALLOC(&env->obst, spill_t);
808         spill->after = skip_keeps_phis(to_spill);
809         spill->next  = NULL;
810         spill->spill = NULL;
811
812         spillinfo->spills      = spill;
813         spillinfo->spill_costs = spill_execfreq * env->spill_cost;
814         DB((dbg, LEVEL_1, "spill %+F after definition\n", to_spill));
815 }
816
817 void make_spill_locations_dominate_irn(spill_env_t *env, ir_node *irn)
818 {
819         const spill_info_t *si = get_spillinfo(env, irn);
820         ir_node *start_block   = get_irg_start_block(get_irn_irg(irn));
821         int n_blocks           = get_Block_dom_max_subtree_pre_num(start_block);
822         bitset_t *reloads      = bitset_alloca(n_blocks);
823         reloader_t *r;
824         spill_t *s;
825
826         if (si == NULL)
827                 return;
828
829         /* Fill the bitset with the dominance pre-order numbers
830          * of the blocks the reloads are located in. */
831         for (r = si->reloaders; r != NULL; r = r->next) {
832                 ir_node *bl = get_nodes_block(r->reloader);
833                 bitset_set(reloads, get_Block_dom_tree_pre_num(bl));
834         }
835
836         /* Now, cancel out all the blocks that are dominated by each spill.
837          * If the bitset is not empty after that, we have reloads that are
838          * not dominated by any spill. */
839         for (s = si->spills; s != NULL; s = s->next) {
840                 ir_node *bl = get_nodes_block(s->after);
841                 int start   = get_Block_dom_tree_pre_num(bl);
842                 int end     = get_Block_dom_max_subtree_pre_num(bl);
843
844                 bitset_clear_range(reloads, start, end);
845         }
846
847         if (!bitset_is_empty(reloads))
848                 be_add_spill(env, si->to_spill, si->to_spill);
849 }
850
851 void be_insert_spills_reloads(spill_env_t *env)
852 {
853         const ir_exec_freq    *exec_freq = env->exec_freq;
854         spill_info_t          *si;
855         ir_nodeset_iterator_t  iter;
856         ir_node               *node;
857
858         be_timer_push(T_RA_SPILL_APPLY);
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         foreach_set(env->spills, spill_info_t*, si) {
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(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_irg_liveness(env->irg); */
972
973                         be_ssa_construction_init(&senv, env->irg);
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->irg);
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(be_get_irg_liveness(env->irg));
1026
1027         be_remove_dead_nodes_from_schedule(env->irg);
1028
1029         be_timer_pop(T_RA_SPILL_APPLY);
1030 }
1031
1032 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill);
1033 void be_init_spill(void)
1034 {
1035         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1036 }