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