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