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