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