The constructor initializes the array.
[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         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 = (spill_info_t*)set_find(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                 res = (spill_info_t*)set_insert(env->spills, &info, sizeof(info), hash);
144         }
145
146         return res;
147 }
148
149 spill_env_t *be_new_spill_env(ir_graph *irg)
150 {
151         const arch_env_t *arch_env = be_get_irg_arch_env(irg);
152
153         spill_env_t *env = XMALLOC(spill_env_t);
154         env->spills         = new_set(cmp_spillinfo, 1024);
155         env->irg            = irg;
156         env->arch_env       = arch_env;
157         ir_nodeset_init(&env->mem_phis);
158         env->spill_cost     = arch_env->spill_cost;
159         env->reload_cost    = arch_env->reload_cost;
160         env->exec_freq      = be_get_irg_exec_freq(irg);
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         ir_nodeset_destroy(&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_reload2(spill_env_t *env, ir_node *to_spill, ir_node *before,
232                 ir_node *can_spill_after, const arch_register_class_t *reload_cls,
233                 int allow_remat)
234 {
235         spill_info_t  *info;
236         reloader_t    *rel;
237
238         assert(!arch_irn_is(skip_Proj_const(to_spill), dont_spill));
239
240         info = get_spillinfo(env, to_spill);
241
242         if (is_Phi(to_spill)) {
243                 int i, arity;
244
245                 /* create spillinfos for the phi arguments */
246                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
247                         ir_node *arg = get_irn_n(to_spill, i);
248                         get_spillinfo(env, arg);
249                 }
250         }
251
252         assert(!is_Proj(before) && !be_is_Keep(before));
253
254         /* put reload into list */
255         rel                   = OALLOC(&env->obst, reloader_t);
256         rel->next             = info->reloaders;
257         rel->reloader         = before;
258         rel->rematted_node    = NULL;
259         rel->can_spill_after  = can_spill_after;
260         rel->remat_cost_delta = allow_remat ? 0 : REMAT_COST_INFINITE;
261
262         info->reloaders  = rel;
263         assert(info->reload_cls == NULL || info->reload_cls == reload_cls);
264         info->reload_cls = reload_cls;
265
266         DBG((dbg, LEVEL_1, "creating spillinfo for %+F, will be reloaded before %+F, may%s be rematerialized\n",
267                 to_spill, before, allow_remat ? "" : " not"));
268 }
269
270 void be_add_reload(spill_env_t *senv, ir_node *to_spill, ir_node *before,
271                    const arch_register_class_t *reload_cls, int allow_remat)
272 {
273         be_add_reload2(senv, to_spill, before, to_spill, reload_cls, allow_remat);
274
275 }
276
277 ir_node *be_get_end_of_block_insertion_point(const ir_node *block)
278 {
279         ir_node *last = sched_last(block);
280
281         /* we might have keeps behind the jump... */
282         while (be_is_Keep(last)) {
283                 last = sched_prev(last);
284                 assert(!sched_is_end(last));
285         }
286
287         assert(is_cfop(last));
288
289         /* add the reload before the (cond-)jump */
290         return last;
291 }
292
293 /**
294  * determine final spill position: it should be after all phis, keep nodes
295  * and behind nodes marked as prolog
296  */
297 static ir_node *determine_spill_point(ir_node *node)
298 {
299         node = skip_Proj(node);
300         while (true) {
301                 ir_node *next = sched_next(node);
302                 if (!is_Phi(next) && !be_is_Keep(next) && !be_is_CopyKeep(next))
303                         break;
304                 node = next;
305         }
306         return node;
307 }
308
309 /**
310  * Returns the point at which you can insert a node that should be executed
311  * before block @p block when coming from pred @p pos.
312  */
313 static ir_node *get_block_insertion_point(ir_node *block, int pos)
314 {
315         ir_node *predblock;
316
317         /* simply add the reload to the beginning of the block if we only have 1
318          * predecessor. We don't need to check for phis as there can't be any in a
319          * block with only 1 pred. */
320         if (get_Block_n_cfgpreds(block) == 1) {
321                 assert(!is_Phi(sched_first(block)));
322                 return sched_first(block);
323         }
324
325         /* We have to reload the value in pred-block */
326         predblock = get_Block_cfgpred_block(block, pos);
327         return be_get_end_of_block_insertion_point(predblock);
328 }
329
330 void be_add_reload_at_end(spill_env_t *env, ir_node *to_spill,
331                           const ir_node *block,
332                           const arch_register_class_t *reload_cls,
333                           int allow_remat)
334 {
335         ir_node *before = be_get_end_of_block_insertion_point(block);
336         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
337 }
338
339 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block,
340                            int pos, const arch_register_class_t *reload_cls,
341                            int allow_remat)
342 {
343         ir_node *before = get_block_insertion_point(block, pos);
344         be_add_reload(env, to_spill, before, reload_cls, allow_remat);
345 }
346
347 void be_spill_phi(spill_env_t *env, ir_node *node)
348 {
349         ir_node *block;
350         int i, arity;
351
352         assert(is_Phi(node));
353
354         ir_nodeset_insert(&env->mem_phis, node);
355
356         /* create spills for the phi arguments */
357         block = get_nodes_block(node);
358         for (i = 0, arity = get_irn_arity(node); i < arity; ++i) {
359                 ir_node *arg = get_irn_n(node, i);
360                 ir_node *insert;
361
362                 /* some backends have virtual noreg/unknown nodes that are not scheduled
363                  * and simply always available. */
364                 if (!sched_is_scheduled(arg)) {
365                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
366                         insert = be_get_end_of_block_insertion_point(pred_block);
367                         insert = sched_prev(insert);
368                 } else {
369                         insert = determine_spill_point(arg);
370                 }
371
372                 be_add_spill(env, arg, insert);
373         }
374 }
375
376 /*
377  *   ____                _         ____        _ _ _
378  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
379  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
380  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
381  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
382  *                                      |_|
383  */
384
385 static void determine_spill_costs(spill_env_t *env, spill_info_t *spillinfo);
386
387 /**
388  * Creates a spill.
389  *
390  * @param senv      the spill environment
391  * @param irn       the node that should be spilled
392  * @param ctx_irn   an user of the spilled node
393  *
394  * @return a be_Spill node
395  */
396 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo)
397 {
398         ir_node       *to_spill = spillinfo->to_spill;
399         const ir_node *insn     = skip_Proj_const(to_spill);
400         spill_t *spill;
401
402         /* determine_spill_costs must have been run before */
403         assert(spillinfo->spill_costs >= 0);
404
405         /* some backends have virtual noreg/unknown nodes that are not scheduled
406          * and simply always available. */
407         if (!sched_is_scheduled(insn)) {
408                 /* override spillinfos or create a new one */
409                 ir_graph *irg = get_irn_irg(to_spill);
410                 spillinfo->spills->spill = get_irg_no_mem(irg);
411                 DB((dbg, LEVEL_1, "don't spill %+F use NoMem\n", to_spill));
412                 return;
413         }
414
415         DBG((dbg, LEVEL_1, "spilling %+F ... \n", to_spill));
416         spill = spillinfo->spills;
417         for ( ; spill != NULL; spill = spill->next) {
418                 ir_node *after = spill->after;
419                 ir_node *block = get_block(after);
420
421                 after = determine_spill_point(after);
422
423                 spill->spill = be_spill(block, to_spill);
424                 sched_add_after(skip_Proj(after), spill->spill);
425                 DB((dbg, LEVEL_1, "\t%+F after %+F\n", spill->spill, after));
426                 env->spill_count++;
427         }
428         DBG((dbg, LEVEL_1, "\n"));
429 }
430
431 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
432
433 /**
434  * If the first usage of a Phi result would be out of memory
435  * there is no sense in allocating a register for it.
436  * Thus we spill it and all its operands to the same spill slot.
437  * Therefore the phi/dataB becomes a phi/Memory
438  *
439  * @param senv      the spill environment
440  * @param phi       the Phi node that should be spilled
441  * @param ctx_irn   an user of the spilled node
442  */
443 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo)
444 {
445         ir_graph *irg   = env->irg;
446         ir_node  *phi   = spillinfo->to_spill;
447         ir_node  *block = get_nodes_block(phi);
448         ir_node  *unknown;
449         ir_node **ins;
450         spill_t  *spill;
451         int       i;
452         int       arity;
453
454         assert(is_Phi(phi));
455         assert(!get_opt_cse());
456         DBG((dbg, LEVEL_1, "spilling Phi %+F:\n", phi));
457
458         /* build a new PhiM */
459         arity   = get_irn_arity(phi);
460         ins     = ALLOCAN(ir_node*, arity);
461         unknown = new_r_Unknown(irg, mode_M);
462         for (i = 0; i < arity; ++i) {
463                 ins[i] = unknown;
464         }
465
466         /* override or replace spills list... */
467         spill         = OALLOC(&env->obst, spill_t);
468         spill->after  = determine_spill_point(phi);
469         spill->spill  = be_new_Phi(block, arity, ins, mode_M, NULL);
470         spill->next   = NULL;
471         sched_add_after(block, spill->spill);
472
473         spillinfo->spills = spill;
474         env->spilled_phi_count++;
475
476         for (i = 0; i < arity; ++i) {
477                 ir_node      *arg      = get_irn_n(phi, i);
478                 spill_info_t *arg_info = get_spillinfo(env, arg);
479
480                 determine_spill_costs(env, arg_info);
481                 spill_node(env, arg_info);
482
483                 set_irn_n(spill->spill, i, arg_info->spills->spill);
484         }
485         DBG((dbg, LEVEL_1, "... done spilling Phi %+F, created PhiM %+F\n", phi,
486              spill->spill));
487 }
488
489 /**
490  * Spill a node.
491  *
492  * @param senv      the spill environment
493  * @param to_spill  the node that should be spilled
494  */
495 static void spill_node(spill_env_t *env, spill_info_t *spillinfo)
496 {
497         ir_node *to_spill;
498
499         /* node is already spilled */
500         if (spillinfo->spills != NULL && spillinfo->spills->spill != NULL)
501                 return;
502
503         to_spill = spillinfo->to_spill;
504
505         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
506                 spill_phi(env, spillinfo);
507         } else {
508                 spill_irn(env, spillinfo);
509         }
510 }
511
512 /*
513  *
514  *  ____                      _            _       _ _
515  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
516  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
517  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
518  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
519  *
520  */
521
522 /**
523  * Tests whether value @p arg is available before node @p reloader
524  * @returns 1 if value is available, 0 otherwise
525  */
526 static int is_value_available(spill_env_t *env, const ir_node *arg,
527                               const ir_node *reloader)
528 {
529         if (is_Unknown(arg) || is_NoMem(arg))
530                 return 1;
531
532         if (be_is_Spill(skip_Proj_const(arg)))
533                 return 1;
534
535         if (arg == get_irg_frame(env->irg))
536                 return 1;
537
538         (void)reloader;
539
540         if (get_irn_mode(arg) == mode_T)
541                 return 0;
542
543         /*
544          * Ignore registers are always available
545          */
546         if (arch_irn_is_ignore(arg))
547                 return 1;
548
549         return 0;
550 }
551
552 /**
553  * Check if a node is rematerializable. This tests for the following conditions:
554  *
555  * - The node itself is rematerializable
556  * - All arguments of the node are available or also rematerialisable
557  * - The costs for the rematerialisation operation is less or equal a limit
558  *
559  * Returns the costs needed for rematerialisation or something
560  * >= REMAT_COST_INFINITE if remat is not possible.
561  */
562 static int check_remat_conditions_costs(spill_env_t *env,
563                 const ir_node *spilled, const ir_node *reloader, int parentcosts)
564 {
565         int i, arity;
566         int argremats;
567         int costs = 0;
568         const ir_node *insn = skip_Proj_const(spilled);
569
570         assert(!be_is_Spill(insn));
571         if (!arch_irn_is(insn, rematerializable))
572                 return REMAT_COST_INFINITE;
573
574         if (be_is_Reload(insn)) {
575                 costs += 2;
576         } else {
577                 costs += arch_get_op_estimated_cost(insn);
578         }
579         if (parentcosts + costs >= env->reload_cost + env->spill_cost) {
580                 return REMAT_COST_INFINITE;
581         }
582         /* never rematerialize a node which modifies the flags.
583          * (would be better to test whether the flags are actually live at point
584          * reloader...)
585          */
586         if (arch_irn_is(insn, modify_flags)) {
587                 return REMAT_COST_INFINITE;
588         }
589
590         argremats = 0;
591         for (i = 0, arity = get_irn_arity(insn); i < arity; ++i) {
592                 ir_node *arg = get_irn_n(insn, i);
593
594                 if (is_value_available(env, arg, reloader))
595                         continue;
596
597                 /* we have to rematerialize the argument as well */
598                 ++argremats;
599                 if (argremats > 1) {
600                         /* we only support rematerializing 1 argument at the moment,
601                          * as multiple arguments could increase register pressure */
602                         return REMAT_COST_INFINITE;
603                 }
604
605                 costs += check_remat_conditions_costs(env, arg, reloader,
606                                                       parentcosts + costs);
607                 if (parentcosts + costs >= env->reload_cost + env->spill_cost)
608                         return REMAT_COST_INFINITE;
609         }
610
611         return costs;
612 }
613
614 /**
615  * Re-materialize a node.
616  *
617  * @param senv      the spill environment
618  * @param spilled   the node that was spilled
619  * @param reloader  a irn that requires a reload
620  */
621 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader)
622 {
623         int i, arity;
624         ir_node *res;
625         ir_node *bl;
626         ir_node **ins;
627
628         if (is_Block(reloader)) {
629                 bl = reloader;
630         } else {
631                 bl = get_nodes_block(reloader);
632         }
633
634         ins = ALLOCAN(ir_node*, get_irn_arity(spilled));
635         for (i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
636                 ir_node *arg = get_irn_n(spilled, i);
637
638                 if (is_value_available(env, arg, reloader)) {
639                         ins[i] = arg;
640                 } else {
641                         ins[i] = do_remat(env, arg, reloader);
642                         /* don't count the recursive call as remat */
643                         env->remat_count--;
644                 }
645         }
646
647         /* create a copy of the node */
648         res = new_ir_node(get_irn_dbg_info(spilled), env->irg, bl,
649                           get_irn_op(spilled), get_irn_mode(spilled),
650                           get_irn_arity(spilled), ins);
651         copy_node_attr(env->irg, spilled, res);
652         arch_env_mark_remat(env->arch_env, res);
653
654         DBG((dbg, LEVEL_1, "Insert remat %+F of %+F before reloader %+F\n", res, spilled, reloader));
655
656         if (! is_Proj(res)) {
657                 /* insert in schedule */
658                 sched_reset(res);
659                 sched_add_before(reloader, res);
660                 env->remat_count++;
661         }
662
663         return res;
664 }
665
666 double be_get_spill_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
667 {
668         ir_node *block = get_nodes_block(before);
669         double   freq  = get_block_execfreq(env->exec_freq, block);
670         (void) to_spill;
671
672         return env->spill_cost * freq;
673 }
674
675 unsigned be_get_reload_costs_no_weight(spill_env_t *env, const ir_node *to_spill,
676                                        const ir_node *before)
677 {
678         if (be_do_remats) {
679                 /* is the node rematerializable? */
680                 unsigned costs = check_remat_conditions_costs(env, to_spill, before, 0);
681                 if (costs < (unsigned) env->reload_cost)
682                         return costs;
683         }
684
685         return env->reload_cost;
686 }
687
688 double be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before)
689 {
690         ir_node      *block = get_nodes_block(before);
691         double        freq  = get_block_execfreq(env->exec_freq, block);
692
693         if (be_do_remats) {
694                 /* is the node rematerializable? */
695                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
696                 if (costs < env->reload_cost)
697                         return costs * freq;
698         }
699
700         return env->reload_cost * freq;
701 }
702
703 int be_is_rematerializable(spill_env_t *env, const ir_node *to_remat,
704                            const ir_node *before)
705 {
706         return check_remat_conditions_costs(env, to_remat, before, 0) < REMAT_COST_INFINITE;
707 }
708
709 double be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill,
710                                    ir_node *block, int pos)
711 {
712         ir_node *before = get_block_insertion_point(block, pos);
713         return be_get_reload_costs(env, to_spill, before);
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(env->exec_freq, spill_block);
765
766         if (is_Phi(to_spill) && ir_nodeset_contains(&env->mem_phis, to_spill)) {
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(env->exec_freq, 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         const ir_exec_freq    *exec_freq = env->exec_freq;
847         spill_info_t          *si;
848         ir_nodeset_iterator_t  iter;
849         ir_node               *node;
850
851         be_timer_push(T_RA_SPILL_APPLY);
852
853         /* create all phi-ms first, this is needed so, that phis, hanging on
854            spilled phis work correctly */
855         foreach_ir_nodeset(&env->mem_phis, node, iter) {
856                 spill_info_t *info = get_spillinfo(env, node);
857                 spill_node(env, info);
858         }
859
860         /* process each spilled node */
861         foreach_set(env->spills, spill_info_t*, si) {
862                 reloader_t *rld;
863                 ir_node  *to_spill        = si->to_spill;
864                 ir_mode  *mode            = get_irn_mode(to_spill);
865                 ir_node **copies          = NEW_ARR_F(ir_node*, 0);
866                 double    all_remat_costs = 0; /** costs when we would remat all nodes */
867                 int       force_remat     = 0;
868
869                 DBG((dbg, LEVEL_1, "\nhandling all reloaders of %+F:\n", to_spill));
870
871                 determine_spill_costs(env, si);
872
873                 /* determine possibility of rematerialisations */
874                 if (be_do_remats) {
875                         /* calculate cost savings for each indivial value when it would
876                            be rematted instead of reloaded */
877                         for (rld = si->reloaders; rld != NULL; rld = rld->next) {
878                                 double   freq;
879                                 int      remat_cost;
880                                 int      remat_cost_delta;
881                                 ir_node *block;
882                                 ir_node *reloader = rld->reloader;
883
884                                 if (rld->rematted_node != NULL) {
885                                         DBG((dbg, LEVEL_2, "\tforced remat %+F before %+F\n",
886                                              rld->rematted_node, reloader));
887                                         continue;
888                                 }
889                                 if (rld->remat_cost_delta >= REMAT_COST_INFINITE) {
890                                         DBG((dbg, LEVEL_2, "\treload before %+F is forbidden\n",
891                                              reloader));
892                                         all_remat_costs = REMAT_COST_INFINITE;
893                                         continue;
894                                 }
895
896                                 remat_cost  = check_remat_conditions_costs(env, to_spill,
897                                                                            reloader, 0);
898                                 if (remat_cost >= REMAT_COST_INFINITE) {
899                                         DBG((dbg, LEVEL_2, "\tremat before %+F not possible\n",
900                                              reloader));
901                                         rld->remat_cost_delta = REMAT_COST_INFINITE;
902                                         all_remat_costs       = REMAT_COST_INFINITE;
903                                         continue;
904                                 }
905
906                                 remat_cost_delta      = remat_cost - env->reload_cost;
907                                 rld->remat_cost_delta = remat_cost_delta;
908                                 block                 = is_Block(reloader) ? reloader : get_nodes_block(reloader);
909                                 freq                  = get_block_execfreq(exec_freq, block);
910                                 all_remat_costs      += remat_cost_delta * freq;
911                                 DBG((dbg, LEVEL_2, "\tremat costs delta before %+F: "
912                                      "%d (rel %f)\n", reloader, remat_cost_delta,
913                                      remat_cost_delta * freq));
914                         }
915                         if (all_remat_costs < REMAT_COST_INFINITE) {
916                                 /* we don't need the costs for the spill if we can remat
917                                    all reloaders */
918                                 all_remat_costs -= si->spill_costs;
919
920                                 DBG((dbg, LEVEL_2, "\tspill costs %d (rel %f)\n",
921                                      env->spill_cost, si->spill_costs));
922                         }
923
924                         if (all_remat_costs < 0) {
925                                 DBG((dbg, LEVEL_1, "\nforcing remats of all reloaders (%f)\n",
926                                      all_remat_costs));
927                                 force_remat = 1;
928                         }
929                 }
930
931                 /* go through all reloads for this spill */
932                 for (rld = si->reloaders; rld != NULL; rld = rld->next) {
933                         ir_node *copy; /* a reload is a "copy" of the original value */
934
935                         if (rld->rematted_node != NULL) {
936                                 copy = rld->rematted_node;
937                                 sched_add_before(rld->reloader, copy);
938                         } else if (be_do_remats &&
939                                         (force_remat || rld->remat_cost_delta < 0)) {
940                                 copy = do_remat(env, to_spill, rld->reloader);
941                         } else {
942                                 /* make sure we have a spill */
943                                 spill_node(env, si);
944
945                                 /* create a reload, use the first spill for now SSA
946                                  * reconstruction for memory comes below */
947                                 assert(si->spills != NULL);
948                                 copy = be_reload(si->reload_cls, rld->reloader, mode,
949                                                  si->spills->spill);
950                                 env->reload_count++;
951                         }
952
953                         DBG((dbg, LEVEL_1, " %+F of %+F before %+F\n",
954                              copy, to_spill, rld->reloader));
955                         ARR_APP1(ir_node*, copies, copy);
956                 }
957
958                 /* if we had any reloads or remats, then we need to reconstruct the
959                  * SSA form for the spilled value */
960                 if (ARR_LEN(copies) > 0) {
961                         be_ssa_construction_env_t senv;
962                         /* be_lv_t *lv = be_get_irg_liveness(env->irg); */
963
964                         be_ssa_construction_init(&senv, env->irg);
965                         be_ssa_construction_add_copy(&senv, to_spill);
966                         be_ssa_construction_add_copies(&senv, copies, ARR_LEN(copies));
967                         be_ssa_construction_fix_users(&senv, to_spill);
968
969 #if 0
970                         /* no need to enable this as long as we invalidate liveness
971                            after this function... */
972                         be_ssa_construction_update_liveness_phis(&senv);
973                         be_liveness_update(to_spill);
974                         len = ARR_LEN(copies);
975                         for (i = 0; i < len; ++i) {
976                                 be_liveness_update(lv, copies[i]);
977                         }
978 #endif
979                         be_ssa_construction_destroy(&senv);
980                 }
981                 /* need to reconstruct SSA form if we had multiple spills */
982                 if (si->spills != NULL && si->spills->next != NULL) {
983                         spill_t *spill;
984                         int      spill_count = 0;
985
986                         be_ssa_construction_env_t senv;
987
988                         be_ssa_construction_init(&senv, env->irg);
989                         spill = si->spills;
990                         for ( ; spill != NULL; spill = spill->next) {
991                                 /* maybe we rematerialized the value and need no spill */
992                                 if (spill->spill == NULL)
993                                         continue;
994                                 be_ssa_construction_add_copy(&senv, spill->spill);
995                                 spill_count++;
996                         }
997                         if (spill_count > 1) {
998                                 /* all reloads are attached to the first spill, fix them now */
999                                 be_ssa_construction_fix_users(&senv, si->spills->spill);
1000                         }
1001
1002                         be_ssa_construction_destroy(&senv);
1003                 }
1004
1005                 DEL_ARR_F(copies);
1006                 si->reloaders = NULL;
1007         }
1008
1009         stat_ev_dbl("spill_spills", env->spill_count);
1010         stat_ev_dbl("spill_reloads", env->reload_count);
1011         stat_ev_dbl("spill_remats", env->remat_count);
1012         stat_ev_dbl("spill_spilled_phis", env->spilled_phi_count);
1013
1014         /* Matze: In theory be_ssa_construction should take care of the liveness...
1015          * try to disable this again in the future */
1016         be_liveness_invalidate(be_get_irg_liveness(env->irg));
1017
1018         be_remove_dead_nodes_from_schedule(env->irg);
1019
1020         be_timer_pop(T_RA_SPILL_APPLY);
1021 }
1022
1023 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spill)
1024 void be_init_spill(void)
1025 {
1026         FIRM_DBG_REGISTER(dbg, "firm.be.spill");
1027 }