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