fix for scheduling changes
[libfirm] / ir / be / bespill.c
1 /*
2  * Author:      Daniel Grund, Sebastian Hack, Matthias Braun
3  * Date:                29.09.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  */
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include <stdlib.h>
12
13 #include "pset.h"
14 #include "irnode_t.h"
15 #include "ircons_t.h"
16 #include "iredges_t.h"
17 #include "irbackedge_t.h"
18 #include "irprintf.h"
19 #include "ident_t.h"
20 #include "type_t.h"
21 #include "entity_t.h"
22 #include "debug.h"
23 #include "irgwalk.h"
24 #include "array.h"
25 #include "pdeq.h"
26 #include "unionfind.h"
27 #include "execfreq.h"
28
29 #include "belive_t.h"
30 #include "besched_t.h"
31 #include "bespill.h"
32 #include "belive_t.h"
33 #include "benode_t.h"
34 #include "bechordal_t.h"
35 #include "bejavacoal.h"
36 #include "benodesets.h"
37 #include "bespilloptions.h"
38 #include "bestatevent.h"
39
40 // only rematerialise when costs are less than REMAT_COST_LIMIT
41 // TODO determine a good value here...
42 #define REMAT_COST_LIMIT        10
43
44 typedef struct _reloader_t reloader_t;
45
46 struct _reloader_t {
47         reloader_t *next;
48         ir_node *reloader;
49 };
50
51 typedef struct _spill_info_t {
52         /** the value that should get spilled */
53         ir_node *spilled_node;
54         /** list of places where the value should get reloaded */
55         reloader_t *reloaders;
56
57         /** the spill node, or a PhiM node */
58         ir_node *spill;
59         /** if we had the value of a phi spilled before but not the phi itself then
60          * this field contains the spill for the phi value */
61         ir_node *old_spill;
62
63         /** the register class in which the reload should be placed */
64         const arch_register_class_t *reload_cls;
65 } spill_info_t;
66
67 struct _spill_env_t {
68         const arch_register_class_t *cls;
69         const arch_env_t *arch_env;
70         const be_chordal_env_t *chordal_env;
71         struct obstack obst;
72         be_irg_t *birg;
73         int spill_cost;     /**< the cost of a single spill node */
74         int reload_cost;    /**< the cost of a reload node */
75         set *spills;        /**< all spill_info_t's, which must be placed */
76         pset *mem_phis;     /**< set of all special spilled phis. allocated and freed separately */
77
78         DEBUG_ONLY(firm_dbg_module_t *dbg;)
79 };
80
81 /**
82  * Compare two spill infos.
83  */
84 static int cmp_spillinfo(const void *x, const void *y, size_t size) {
85         const spill_info_t *xx = x;
86         const spill_info_t *yy = y;
87         return xx->spilled_node != yy->spilled_node;
88 }
89
90 /**
91  * Returns spill info for a specific value (returns NULL if the info doesn't
92  * exist yet)
93  */
94 static spill_info_t *find_spillinfo(const spill_env_t *env, ir_node *value) {
95         spill_info_t info;
96         int hash = nodeset_hash(value);
97
98         info.spilled_node = value;
99
100         return set_find(env->spills, &info, sizeof(info), hash);
101 }
102
103 /**
104  * Returns spill info for a specific value (the value that is to be spilled)
105  */
106 static spill_info_t *get_spillinfo(const spill_env_t *env, ir_node *value) {
107         spill_info_t info, *res;
108         int hash = nodeset_hash(value);
109
110         info.spilled_node = value;
111         res = set_find(env->spills, &info, sizeof(info), hash);
112
113         if (res == NULL) {
114                 info.reloaders = NULL;
115                 info.spill = NULL;
116                 info.old_spill = NULL;
117                 res = set_insert(env->spills, &info, sizeof(info), hash);
118         }
119
120         return res;
121 }
122
123 DEBUG_ONLY(
124 /* Sets the debug module of a spill environment. */
125 void be_set_spill_env_dbg_module(spill_env_t *env, firm_dbg_module_t *dbg) {
126         env->dbg = dbg;
127 }
128 )
129
130 /* Creates a new spill environment. */
131 spill_env_t *be_new_spill_env(const be_chordal_env_t *chordal_env) {
132         spill_env_t *env        = xmalloc(sizeof(env[0]));
133         env->spills                     = new_set(cmp_spillinfo, 1024);
134         env->cls                        = chordal_env->cls;
135         env->chordal_env        = chordal_env;
136         env->birg           = chordal_env->birg;
137         env->arch_env       = env->chordal_env->birg->main_env->arch_env;
138         env->mem_phis           = pset_new_ptr_default();
139         // TODO, ask backend about costs...
140         env->spill_cost     = 8;
141         env->reload_cost    = 5;
142         obstack_init(&env->obst);
143         return env;
144 }
145
146 /* Deletes a spill environment. */
147 void be_delete_spill_env(spill_env_t *env) {
148         del_set(env->spills);
149         del_pset(env->mem_phis);
150         obstack_free(&env->obst, NULL);
151         free(env);
152 }
153
154 /*
155  *  ____  _                  ____      _                 _
156  * |  _ \| | __ _  ___ ___  |  _ \ ___| | ___   __ _  __| |___
157  * | |_) | |/ _` |/ __/ _ \ | |_) / _ \ |/ _ \ / _` |/ _` / __|
158  * |  __/| | (_| | (_|  __/ |  _ <  __/ | (_) | (_| | (_| \__ \
159  * |_|   |_|\__,_|\___\___| |_| \_\___|_|\___/ \__,_|\__,_|___/
160  *
161  */
162
163 void be_add_reload(spill_env_t *env, ir_node *to_spill, ir_node *before, const arch_register_class_t *reload_cls) {
164         spill_info_t *info;
165         reloader_t *rel;
166
167         assert(arch_irn_consider_in_reg_alloc(env->arch_env, env->cls, to_spill));
168
169         info = get_spillinfo(env, to_spill);
170
171         if(is_Phi(to_spill)) {
172                 int i, arity;
173
174                 /* create spillinfos for the phi arguments */
175                 for (i = 0, arity = get_irn_arity(to_spill); i < arity; ++i) {
176                         ir_node *arg = get_irn_n(to_spill, i);
177                         get_spillinfo(env, arg);
178                 }
179
180 #if 1
181                 // hackery... sometimes the morgan algo spilled the value of a phi,
182                 // the belady algo decides later to spill the whole phi, then sees the
183                 // spill node and adds a reload for that spill node, problem is the
184                 // reload gets attach to that same spill (and is totally unnecessary)
185                 if (info->old_spill != NULL &&
186                         (before == info->old_spill || value_dominates(before, info->old_spill))) {
187                         printf("spilledphi hack was needed...\n");
188                         before = sched_next(info->old_spill);
189                 }
190 #endif
191         }
192
193         /* put reload into list */
194         rel           = obstack_alloc(&env->obst, sizeof(rel[0]));
195         rel->reloader = before;
196         rel->next     = info->reloaders;
197
198         info->reloaders  = rel;
199         info->reload_cls = reload_cls;
200 }
201
202 static ir_node *get_reload_insertion_point(ir_node *block, int pos) {
203         ir_node *predblock, *last;
204
205         /* simply add the reload to the beginning of the block if we only have 1 predecessor
206          * (we don't need to check for phis as there can't be any in a block with only 1 pred)
207          */
208         if(get_Block_n_cfgpreds(block) == 1) {
209                 assert(!is_Phi(sched_first(block)));
210                 return sched_first(block);
211         }
212
213         /* We have to reload the value in pred-block */
214         predblock = get_Block_cfgpred_block(block, pos);
215         last = sched_last(predblock);
216
217         /* we might have projs and keepanys behind the jump... */
218         while(is_Proj(last) || be_is_Keep(last)) {
219                 last = sched_prev(last);
220                 assert(!sched_is_end(last));
221         }
222
223         if(!is_cfop(last)) {
224                 ir_graph *irg = get_irn_irg(block);
225                 ir_node *startblock = get_irg_start_block(irg);
226
227                 last = sched_next(last);
228                 // last node must be a cfop, only exception is the start block
229                 assert(last     == startblock);
230         }
231
232         // add the reload before the (cond-)jump
233         return last;
234 }
235
236 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill,
237                 ir_node *block, int pos, const arch_register_class_t *reload_cls)
238 {
239         ir_node *before = get_reload_insertion_point(block, pos);
240         be_add_reload(env, to_spill, before, reload_cls);
241 }
242
243 void be_spill_phi(spill_env_t *env, ir_node *node) {
244         spill_info_t* spill;
245         int i, arity;
246
247         assert(is_Phi(node));
248
249         pset_insert_ptr(env->mem_phis, node);
250
251         // create spillinfos for the phi arguments
252         spill = get_spillinfo(env, node);
253         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
254                 ir_node *arg = get_irn_n(node, i);
255                 get_spillinfo(env, arg);
256         }
257
258         // if we had a spill for the phi value before, then remove this spill from
259         // schedule, as we will remove it in the insert spill/reload phase
260         if(spill->spill != NULL && !is_Phi(spill->spill)) {
261                 assert(spill->old_spill == NULL);
262                 spill->old_spill = spill->spill;
263                 spill->spill = NULL;
264         }
265 }
266
267 /*
268  *   ____                _         ____        _ _ _
269  *  / ___|_ __ ___  __ _| |_ ___  / ___| _ __ (_) | |___
270  * | |   | '__/ _ \/ _` | __/ _ \ \___ \| '_ \| | | / __|
271  * | |___| | |  __/ (_| | ||  __/  ___) | |_) | | | \__ \
272  *  \____|_|  \___|\__,_|\__\___| |____/| .__/|_|_|_|___/
273  *                                      |_|
274  */
275
276 /**
277  * Schedules a node after an instruction. (That is the place after all projs and phis
278  * that are scheduled after the instruction)
279  * This function also skips phi nodes at the beginning of a block
280  */
281 static void sched_add_after_insn(ir_node *sched_after, ir_node *node) {
282         ir_node *next = sched_next(sched_after);
283         while(is_Proj(next) || is_Phi(next)) {
284                 next = sched_next(next);
285         }
286         assert(next != NULL);
287
288         if(sched_is_end(next)) {
289                 sched_add_after(sched_last(get_nodes_block(sched_after)), node);
290         } else {
291                 sched_add_before(next, node);
292         }
293 }
294
295 /**
296  * Creates a spill.
297  *
298  * @param senv      the spill environment
299  * @param irn       the node that should be spilled
300  * @param ctx_irn   an user of the spilled node
301  *
302  * @return a be_Spill node
303  */
304 static void spill_irn(spill_env_t *env, spill_info_t *spillinfo) {
305         ir_node *to_spill = spillinfo->spilled_node;
306
307         DBG((env->dbg, LEVEL_1, "%+F\n", to_spill));
308
309         /* Trying to spill an already spilled value, no need for a new spill
310          * node then, we can simply connect to the same one for this reload
311          *
312          * (although rematerialization code should handle most of these cases
313          * this can still happen when spilling Phis)
314          */
315         if(be_is_Reload(to_spill)) {
316                 spillinfo->spill = get_irn_n(to_spill, be_pos_Reload_mem);
317                 return;
318         }
319
320         if (arch_irn_is(env->arch_env, to_spill, dont_spill)) {
321                 if (env->chordal_env->opts->vrfy_option == BE_CH_VRFY_WARN)
322                         ir_fprintf(stderr, "Verify warning: spilling 'dont_spill' node %+F\n", to_spill);
323                 else if (env->chordal_env->opts->vrfy_option == BE_CH_VRFY_ASSERT)
324                         assert(0 && "Attempt to spill a node marked 'dont_spill'");
325         }
326
327         spillinfo->spill = be_spill(env->arch_env, to_spill);
328         sched_add_after_insn(to_spill, spillinfo->spill);
329 }
330
331 static void spill_node(spill_env_t *env, spill_info_t *spillinfo);
332
333 /**
334  * If the first usage of a Phi result would be out of memory
335  * there is no sense in allocating a register for it.
336  * Thus we spill it and all its operands to the same spill slot.
337  * Therefore the phi/dataB becomes a phi/Memory
338  *
339  * @param senv      the spill environment
340  * @param phi       the Phi node that should be spilled
341  * @param ctx_irn   an user of the spilled node
342  */
343 static void spill_phi(spill_env_t *env, spill_info_t *spillinfo) {
344         ir_node *phi = spillinfo->spilled_node;
345         int i;
346         int arity = get_irn_arity(phi);
347         ir_node     *block    = get_nodes_block(phi);
348         ir_node     **ins;
349
350         assert(is_Phi(phi));
351
352         /* build a new PhiM */
353         ins = alloca(sizeof(ir_node*) * arity);
354         for(i = 0; i < arity; ++i) {
355                 ins[i] = get_irg_bad(env->chordal_env->irg);
356         }
357         spillinfo->spill = new_r_Phi(env->chordal_env->irg, block, arity, ins, mode_M);
358
359         for(i = 0; i < arity; ++i) {
360                 ir_node *arg = get_irn_n(phi, i);
361                 spill_info_t *arg_info = get_spillinfo(env, arg);
362
363                 spill_node(env, arg_info);
364
365                 set_irn_n(spillinfo->spill, i, arg_info->spill);
366         }
367
368         // rewire reloads from old_spill to phi
369         if(spillinfo->old_spill != NULL) {
370                 const ir_edge_t *edge, *next;
371                 ir_node *old_spill = spillinfo->old_spill;
372
373                 foreach_out_edge_safe(old_spill, edge, next) {
374                         ir_node* reload = get_edge_src_irn(edge);
375                         assert(be_is_Reload(reload) || is_Phi(reload));
376                         set_irn_n(reload, get_edge_src_pos(edge), spillinfo->spill);
377                 }
378                 set_irn_n(old_spill, be_pos_Spill_val, new_Bad());
379                 //sched_remove(old_spill);
380                 spillinfo->old_spill = NULL;
381         }
382 }
383
384 /**
385  * Spill a node.
386  *
387  * @param senv      the spill environment
388  * @param to_spill  the node that should be spilled
389  */
390 static void spill_node(spill_env_t *env, spill_info_t *spillinfo) {
391         ir_node *to_spill;
392
393         // the node should be tagged for spilling already...
394         if(spillinfo->spill != NULL)
395                 return;
396
397         to_spill = spillinfo->spilled_node;
398         if (is_Phi(to_spill) && pset_find_ptr(env->mem_phis, spillinfo->spilled_node)) {
399                 spill_phi(env, spillinfo);
400         } else {
401                 spill_irn(env, spillinfo);
402         }
403 }
404
405 /*
406  *
407  *  ____                      _            _       _ _
408  * |  _ \ ___ _ __ ___   __ _| |_ ___ _ __(_) __ _| (_)_______
409  * | |_) / _ \ '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | |_  / _ \
410  * |  _ <  __/ | | | | | (_| | ||  __/ |  | | (_| | | |/ /  __/
411  * |_| \_\___|_| |_| |_|\__,_|\__\___|_|  |_|\__,_|_|_/___\___|
412  *
413  */
414
415 /**
416  * Tests whether value @p arg is available before node @p reloader
417  * @returns 1 if value is available, 0 otherwise
418  */
419 static int is_value_available(spill_env_t *env, ir_node *arg, ir_node *reloader) {
420         if(is_Unknown(arg) || arg == new_NoMem())
421                 return 1;
422
423         if(be_is_Spill(arg))
424                 return 1;
425
426         if(arg == get_irg_frame(env->chordal_env->irg))
427                 return 1;
428
429         // hack for now (happens when command should be inserted at end of block)
430         if(is_Block(reloader)) {
431                 return 0;
432         }
433
434         /* the following test does not work while spilling,
435          * because the liveness info is not adapted yet to the effects of the
436          * additional spills/reloads.
437          *
438          * So we can only do this test for ignore registers (of our register class)
439          */
440         if(arch_get_irn_reg_class(env->arch_env, arg, -1) == env->cls
441            && arch_irn_is(env->arch_env, arg, ignore)) {
442                 int i, arity;
443
444                 /* we want to remat before the insn reloader
445                  * thus an arguments is alive if
446                  *   - it interferes with the reloaders result
447                  *   - or it is (last-) used by reloader itself
448                  */
449                 if (values_interfere(env->birg->lv, reloader, arg)) {
450                         return 1;
451                 }
452
453                 arity = get_irn_arity(reloader);
454                 for (i = 0; i < arity; ++i) {
455                         ir_node *rel_arg = get_irn_n(reloader, i);
456                         if (rel_arg == arg)
457                                 return 1;
458                 }
459         }
460
461         return 0;
462 }
463
464 /**
465  * Checks whether the node can principally be rematerialized
466  */
467 static int is_remat_node(spill_env_t *env, ir_node *node) {
468         const arch_env_t *arch_env = env->arch_env;
469
470         assert(!be_is_Spill(node));
471
472         if(arch_irn_is(arch_env, node, rematerializable)) {
473                 return 1;
474         }
475
476         if(be_is_StackParam(node))
477                 return 1;
478
479         return 0;
480 }
481
482 /**
483  * Check if a node is rematerializable. This tests for the following conditions:
484  *
485  * - The node itself is rematerializable
486  * - All arguments of the node are available or also rematerialisable
487  * - The costs for the rematerialisation operation is less or equal a limit
488  *
489  * Returns the costs needed for rematerialisation or something
490  * > REMAT_COST_LIMIT if remat is not possible.
491  */
492 static int check_remat_conditions_costs(spill_env_t *env, ir_node *spilled, ir_node *reloader, int parentcosts) {
493         int i, arity;
494         int argremats;
495         int costs = 0;
496
497         if(!is_remat_node(env, spilled))
498                 return REMAT_COST_LIMIT;
499
500         if(be_is_Reload(spilled)) {
501                 costs += 2;
502         } else {
503                 costs += arch_get_op_estimated_cost(env->arch_env, spilled);
504         }
505         if(parentcosts + costs >= REMAT_COST_LIMIT) {
506                 return REMAT_COST_LIMIT;
507         }
508
509         argremats = 0;
510         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
511                 ir_node *arg = get_irn_n(spilled, i);
512
513                 if(is_value_available(env, arg, reloader))
514                         continue;
515
516                 // we have to rematerialize the argument as well...
517                 if(argremats >= 1) {
518                         /* we only support rematerializing 1 argument at the moment,
519                          * so that we don't have to care about register pressure
520                          */
521                         return REMAT_COST_LIMIT;
522                 }
523                 argremats++;
524
525                 costs += check_remat_conditions_costs(env, arg, reloader, parentcosts + costs);
526                 if(parentcosts + costs >= REMAT_COST_LIMIT)
527                         return REMAT_COST_LIMIT;
528         }
529
530         return costs;
531 }
532
533 static int check_remat_conditions(spill_env_t *env, ir_node *spilled, ir_node *reloader) {
534         int costs = check_remat_conditions_costs(env, spilled, reloader, 0);
535
536         return costs < REMAT_COST_LIMIT;
537 }
538
539 /**
540  * Re-materialize a node.
541  *
542  * @param senv      the spill environment
543  * @param spilled   the node that was spilled
544  * @param reloader  a irn that requires a reload
545  */
546 static ir_node *do_remat(spill_env_t *env, ir_node *spilled, ir_node *reloader) {
547         int i, arity;
548         ir_node *res;
549         ir_node *bl;
550         ir_node **ins;
551
552         if(is_Block(reloader)) {
553                 bl = reloader;
554         } else {
555                 bl = get_nodes_block(reloader);
556         }
557
558         ins = alloca(get_irn_arity(spilled) * sizeof(ins[0]));
559         for(i = 0, arity = get_irn_arity(spilled); i < arity; ++i) {
560                 ir_node *arg = get_irn_n(spilled, i);
561
562                 if(is_value_available(env, arg, reloader)) {
563                         ins[i] = arg;
564                 } else {
565                         ins[i] = do_remat(env, arg, reloader);
566                 }
567         }
568
569         /* create a copy of the node */
570         res = new_ir_node(get_irn_dbg_info(spilled), env->chordal_env->irg, bl,
571                 get_irn_op(spilled),
572                 get_irn_mode(spilled),
573                 get_irn_arity(spilled),
574                 ins);
575         copy_node_attr(spilled, res);
576         new_backedge_info(res);
577         sched_reset(res);
578
579         DBG((env->dbg, LEVEL_1, "Insert remat %+F before reloader %+F\n", res, reloader));
580
581         /* insert in schedule */
582         sched_add_before(reloader, res);
583
584         return res;
585 }
586
587 int be_get_reload_costs(spill_env_t *env, ir_node *to_spill, ir_node *before) {
588         spill_info_t *spill_info;
589
590         if(be_do_remats) {
591                 // is the node rematerializable?
592                 int costs = check_remat_conditions_costs(env, to_spill, before, 0);
593                 if(costs < REMAT_COST_LIMIT)
594                         return costs;
595         }
596
597         // do we already have a spill?
598         spill_info = find_spillinfo(env, to_spill);
599         if(spill_info != NULL && spill_info->spill != NULL)
600                 return env->reload_cost;
601
602         return env->spill_cost + env->reload_cost;
603 }
604
605 int be_get_reload_costs_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *block, int pos) {
606         ir_node *before = get_reload_insertion_point(block, pos);
607         return be_get_reload_costs(env, to_spill, before);
608 }
609
610 /*
611  *  ___                     _     ____      _                 _
612  * |_ _|_ __  ___  ___ _ __| |_  |  _ \ ___| | ___   __ _  __| |___
613  *  | || '_ \/ __|/ _ \ '__| __| | |_) / _ \ |/ _ \ / _` |/ _` / __|
614  *  | || | | \__ \  __/ |  | |_  |  _ <  __/ | (_) | (_| | (_| \__ \
615  * |___|_| |_|___/\___|_|   \__| |_| \_\___|_|\___/ \__,_|\__,_|___/
616  *
617  */
618
619 void be_insert_spills_reloads(spill_env_t *env) {
620         const arch_env_t *arch_env = env->arch_env;
621         int              remats    = 0;
622         int              reloads   = 0;
623         int              spills    = 0;
624         spill_info_t     *si;
625
626         /* process each spilled node */
627         for (si = set_first(env->spills); si; si = set_next(env->spills)) {
628                 reloader_t *rld;
629                 ir_mode    *mode   = get_irn_mode(si->spilled_node);
630                 pset       *values = pset_new_ptr(16);
631
632                 /* go through all reloads for this spill */
633                 for (rld = si->reloaders; rld; rld = rld->next) {
634                         ir_node *new_val;
635
636                         if (be_do_remats && check_remat_conditions(env, si->spilled_node, rld->reloader)) {
637                                 new_val = do_remat(env, si->spilled_node, rld->reloader);
638                                 remats++;
639                         }
640                         else {
641                                 /* make sure we have a spill */
642                                 if (si->spill == NULL) {
643                                         spill_node(env, si);
644                                         spills++;
645                                 }
646
647                                 /* create a reload */
648                                 new_val = be_reload(arch_env, si->reload_cls, rld->reloader, mode, si->spill);
649                                 reloads++;
650                         }
651
652                         DBG((env->dbg, LEVEL_1, " %+F of %+F before %+F\n", new_val, si->spilled_node, rld->reloader));
653                         pset_insert_ptr(values, new_val);
654                 }
655
656                 if (pset_count(values) > 0) {
657                         /* introduce copies, rewire the uses */
658                         pset_insert_ptr(values, si->spilled_node);
659                         be_ssa_constr_set_ignore(env->birg->dom_front, env->birg->lv, values, env->mem_phis);
660                 }
661
662                 del_pset(values);
663
664                 si->reloaders = NULL;
665         }
666
667 #ifdef FIRM_STATISTICS
668         if (be_stat_ev_is_active()) {
669                 be_stat_ev("spill_spills", spills);
670                 be_stat_ev("spill_reloads", reloads);
671                 be_stat_ev("spill_remats", remats);
672         }
673 #endif /* FIRM_STATISTICS */
674
675         be_remove_dead_nodes_from_schedule(env->chordal_env->irg);
676         //be_liveness_recompute(env->birg->lv);
677         be_invalidate_liveness(env->birg);
678 }