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