Merge Fix: Spills have ProjMs now
[libfirm] / ir / be / bestate.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Handles state switching. This is basically the belady spill
23  *              algorithm optimized for the 1-register case.
24  * @author      Matthias Braun
25  * @date        26.03.2007
26  * @version     $Id$
27  */
28 #include "config.h"
29
30 #include "bestate.h"
31
32 #include "obst.h"
33 #include "irgraph_t.h"
34 #include "irnode_t.h"
35 #include "irgwalk.h"
36 #include "irloop.h"
37 #include "iredges_t.h"
38 #include "ircons_t.h"
39 #include "irgmod.h"
40 #include "irnodeset.h"
41 #include "irnodemap.h"
42 #include "adt/cpset.h"
43
44 #include "bearch.h"
45 #include "beuses.h"
46 #include "besched.h"
47 #include "belive_t.h"
48 #include "bemodule.h"
49 #include "benode.h"
50 #include "beirgmod.h"
51 #include "bessaconstr.h"
52
53 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
54
55 typedef struct spill_info_t {
56         struct spill_info_t *next;
57         ir_node *value;
58         ir_node *spill;
59         ir_node **reloads;
60 } spill_info_t;
61
62 typedef struct minibelady_env_t {
63         struct obstack         obst;
64         const arch_register_t *reg;
65         const be_lv_t         *lv;
66         void                  *func_env;
67         create_reload_func     create_reload;
68         create_spill_func      create_spill;
69         spill_info_t          *spills;
70         ir_nodemap_t           spill_infos;
71
72         be_uses_t             *uses;           /**< env for the next-use magic */
73 } minibelady_env_t;
74
75 typedef struct block_info_t {
76         ir_node *start_state;
77         ir_node *end_state;
78 } block_info_t;
79
80 static inline block_info_t *new_block_info(struct obstack *obst, ir_node *block)
81 {
82         block_info_t *res = OALLOCZ(obst, block_info_t);
83
84         assert(is_Block(block));
85         set_irn_link(block, res);
86         mark_irn_visited(block);
87
88         return res;
89 }
90
91 static inline block_info_t *get_block_info(ir_node *block)
92 {
93         assert(irn_visited(block));
94         return (block_info_t*) get_irn_link(block);
95 }
96
97 static inline spill_info_t *create_spill_info(minibelady_env_t *env, ir_node *state)
98 {
99         spill_info_t *spill_info = OALLOCZ(&env->obst, spill_info_t);
100         spill_info->value = state;
101         spill_info->reloads = NEW_ARR_F(ir_node*, 0);
102
103         ir_nodemap_insert(&env->spill_infos, state, spill_info);
104         //ir_fprintf(stderr, "Insert %+F -> %p\n", state, spill_info);
105
106         spill_info->next = env->spills;
107         env->spills = spill_info;
108
109         return spill_info;
110 }
111
112 static inline spill_info_t *get_spill_info(minibelady_env_t *env, const ir_node *node)
113 {
114         spill_info_t *spill_info
115                 = (spill_info_t*) ir_nodemap_get(&env->spill_infos, node);
116         //ir_fprintf(stderr, "Get %+F -> %p\n", node, spill_info);
117         return spill_info;
118 }
119
120 static spill_info_t *create_spill(minibelady_env_t *env, ir_node *state, int force)
121 {
122         spill_info_t *spill_info;
123         ir_node *next;
124         ir_node *after;
125
126         spill_info = get_spill_info(env, state);
127         if (spill_info == NULL) {
128                 spill_info = create_spill_info(env, state);
129         } else if (spill_info->spill != NULL) {
130                 return spill_info;
131         }
132
133         if (sched_is_scheduled(state)) {
134                 next = state;
135                 do {
136                         after = next;
137                         next = sched_next(after);
138                 } while (is_Proj(next) || is_Phi(next) || be_is_Keep(next));
139         } else {
140                 after = state;
141         }
142         spill_info->spill = env->create_spill(env->func_env, state, force, after);
143
144         return spill_info;
145 }
146
147 static void create_reload(minibelady_env_t *env, ir_node *state,
148                           ir_node *before, ir_node *last_state)
149 {
150         spill_info_t *spill_info = create_spill(env, state, 0);
151         ir_node *spill = spill_info->spill;
152         ir_node *reload;
153
154         reload = env->create_reload(env->func_env, state, spill, before,
155                                     last_state);
156         ARR_APP1(ir_node*, spill_info->reloads, reload);
157 }
158
159 static void spill_phi(minibelady_env_t *env, ir_node *phi)
160 {
161         ir_graph     *irg           = get_irn_irg(phi);
162         ir_node      *block         = get_nodes_block(phi);
163         int           arity         = get_irn_arity(phi);
164         ir_node     **phi_in        = ALLOCAN(ir_node*, arity);
165         ir_node      *dummy         = new_r_Dummy(irg, mode_M);
166         ir_node      *spill_to_kill = NULL;
167         spill_info_t *spill_info;
168         int           i;
169
170         /* does a spill exist for the phis value? */
171         spill_info = get_spill_info(env, phi);
172         if (spill_info != NULL) {
173                 spill_to_kill = spill_info->spill;
174         } else {
175                 spill_info = create_spill_info(env, phi);
176         }
177
178         /* create a new phi-M with bad preds */
179         for (i = 0; i < arity; ++i) {
180                 phi_in[i] = dummy;
181         }
182
183         DBG((dbg, LEVEL_2, "\tcreate Phi-M for %+F\n", phi));
184
185         /* create a Phi-M */
186         spill_info->spill = be_new_Phi(block, arity, phi_in, mode_M, NULL);
187         sched_add_after(block, spill_info->spill);
188
189         if (spill_to_kill != NULL) {
190                 exchange(spill_to_kill, spill_info->spill);
191                 sched_remove(spill_to_kill);
192         }
193
194         /* create spills for the phi values */
195         for (i = 0; i < arity; ++i) {
196                 ir_node *in = get_irn_n(phi, i);
197                 spill_info_t *pred_spill = create_spill(env, in, 1);
198                 set_irn_n(spill_info->spill, i, pred_spill->spill);
199         }
200 }
201
202 static void belady(minibelady_env_t *env, ir_node *block);
203
204 /**
205  * Collects all values live-in at block @p block and all phi results in this
206  * block.
207  * Then it adds the best values (at most n_regs) to the blocks start_workset.
208  * The phis among the remaining values get spilled: Introduce pseudo-copies of
209  * their args to break interference and make it possible to spill them to the
210  * same spill slot.
211  */
212 static block_info_t *compute_block_start_state(minibelady_env_t *env, ir_node *block)
213 {
214         block_info_t  *block_info;
215         be_next_use_t  next_use;
216         ir_loop       *loop;
217         ir_node       *best_starter, *first;
218         ir_node       *node;
219         int            n_cfgpreds;
220         unsigned       best_time;
221         int            outer_loop_allowed;
222         int            i;
223
224         /* Create the block info for this block. */
225         block_info = new_block_info(&env->obst, block);
226         n_cfgpreds = get_Block_n_cfgpreds(block);
227
228         /* no cfgpred -> no value active */
229         if (n_cfgpreds == 0) {
230                 block_info->start_state = NULL;
231                 return block_info;
232         }
233
234         /* for 1 pred only: simply take the the end-state of the pred */
235         if (n_cfgpreds == 1) {
236                 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
237                 block_info_t *pred_info;
238
239                 /* process pred block */
240                 belady(env, pred_block);
241
242                 pred_info = get_block_info(pred_block);
243
244                 DBG((dbg, LEVEL_2, "Taking end state from %+F: %+F\n", pred_block, pred_info->end_state));
245                 block_info->start_state = pred_info->end_state;
246                 return block_info;
247         }
248
249         /* Collect all values living at start of block */
250         DBG((dbg, LEVEL_2, "Living at start of %+F:\n", block));
251         first = sched_first(block);
252         loop = get_irn_loop(block);
253         best_starter = NULL;
254         best_time = USES_INFINITY;
255         outer_loop_allowed = 1;
256
257         /* check all Phis first */
258         sched_foreach(block, node) {
259                 if (!is_Phi(node))
260                         break;
261                 if (arch_get_irn_register(node) != env->reg)
262                         continue;
263
264                 DBG((dbg, LEVEL_2, "\t...checking %+F\n", node));
265                 next_use = be_get_next_use(env->uses, first, node, 0);
266
267                 if (USES_IS_INFINITE(next_use.time)) {
268                         DBG((dbg, LEVEL_2, "\tnot taken (dead)\n"));
269                         continue;
270                 }
271
272                 if (next_use.outermost_loop >= get_loop_depth(loop)) {
273                         if (outer_loop_allowed || next_use.time < best_time) {
274                                 DBG((dbg, LEVEL_2, "\ttaken (%u, loop %d)\n", next_use.time,
275                                      next_use.outermost_loop));
276
277                                 if (best_starter != NULL) {
278                                         /* spill the phi as it is not used */
279                                         spill_phi(env, best_starter);
280                                 }
281                                 best_starter = node;
282                                 best_time = next_use.time;
283                                 outer_loop_allowed = 0;
284                         }
285                 } else {
286                         if (outer_loop_allowed && next_use.time < best_time) {
287                                 DBG((dbg, LEVEL_2, "\ttaken (%u, loop %d)\n", next_use.time,
288                                      next_use.outermost_loop));
289                                 if (best_starter != NULL) {
290                                         /* spill the phi as it is not used */
291                                         spill_phi(env, best_starter);
292                                 }
293                                 best_starter = node;
294                                 best_time = next_use.time;
295                         }
296                 }
297
298                 if (best_starter != node) {
299                         /* spill the phi as it is not used */
300                         spill_phi(env, best_starter);
301                 }
302         }
303
304         /* check all Live-Ins */
305         be_lv_foreach(env->lv, block, be_lv_state_in, i) {
306                 node = be_lv_get_irn(env->lv, block, i);
307
308                 if (!mode_is_data(get_irn_mode(node)))
309                         continue;
310
311                 if (arch_get_irn_register(node) != env->reg)
312                         continue;
313
314                 DBG((dbg, LEVEL_2, "\t...checking %+F\n", node));
315                 next_use = be_get_next_use(env->uses, first, node, 0);
316
317                 if (USES_IS_INFINITE(next_use.time)) {
318                         DBG((dbg, LEVEL_2, "\tnot taken (dead)\n"));
319                         continue;
320                 }
321
322                 if (next_use.outermost_loop >= get_loop_depth(loop)) {
323                         if (outer_loop_allowed || next_use.time < best_time) {
324                                 DBG((dbg, LEVEL_2, "\ttaken (%u, loop %d)\n", next_use.time,
325                                      next_use.outermost_loop));
326
327                                 if (best_starter != NULL && is_Phi(best_starter)) {
328                                         /* spill the phi as it is not used */
329                                         spill_phi(env, best_starter);
330                                 }
331                                 best_starter = node;
332                                 best_time = next_use.time;
333                                 outer_loop_allowed = 0;
334                         }
335                 } else {
336                         if (outer_loop_allowed && next_use.time < best_time) {
337                                 DBG((dbg, LEVEL_2, "\ttaken (%u, loop %d)\n", next_use.time,
338                                      next_use.outermost_loop));
339                                 if (best_starter != NULL && is_Phi(best_starter)) {
340                                         /* spill the phi as it is not used */
341                                         spill_phi(env, best_starter);
342                                 }
343                                 best_starter = node;
344                                 best_time = next_use.time;
345                         }
346                 }
347         }
348
349         block_info->start_state = best_starter;
350
351         return block_info;
352 }
353
354 /**
355  * For the given block @p block, decide for each values
356  * whether it is used from a register or is reloaded
357  * before the use.
358  */
359 static void belady(minibelady_env_t *env, ir_node *block)
360 {
361         ir_node *current_state;
362         ir_node *node;
363         block_info_t *block_info;
364
365         /* Don't do a block twice */
366         if (irn_visited(block))
367                 return;
368
369         /* compute value to start with */
370         block_info = compute_block_start_state(env, block);
371
372         /* get the starting workset for this block */
373         DBG((dbg, LEVEL_3, "\n"));
374         DBG((dbg, LEVEL_3, "Decide for %+F\n", block));
375
376         current_state = block_info->start_state;
377         DBG((dbg, LEVEL_3, "Start value: %+F\n", current_state));
378
379         /* process the block from start to end */
380         DBG((dbg, LEVEL_3, "Processing...\n"));
381
382         sched_foreach(block, node) {
383                 int i, arity;
384                 ir_node *need_val = NULL;
385
386                 /* projs are handled with the tuple value.
387                  * Phis are no real instr (see insert_starters()) */
388                 if (is_Proj(node) || is_Phi(node)) {
389                         continue;
390                 }
391
392                 /* check which state is desired for the node */
393                 arity = get_irn_arity(node);
394                 for (i = 0; i < arity; ++i) {
395                         const arch_register_t *reg;
396                         ir_node *in = get_irn_n(node, i);
397
398                         if (!mode_is_data(get_irn_mode(in)))
399                                 continue;
400
401                         reg = arch_get_irn_register(in);
402                         if (reg == env->reg) {
403                                 assert(need_val == NULL);
404                                 need_val = in;
405                                 DBG((dbg, LEVEL_3, "\t... need state %+F\n", need_val));
406                         }
407                 }
408                 /* create a reload to match state if necessary */
409                 if (need_val != NULL && need_val != current_state) {
410                         ir_node *before = node;
411                         DBG((dbg, LEVEL_3, "\t... reloading %+F\n", need_val));
412                         create_reload(env, need_val, before, current_state);
413                         current_state = need_val;
414                 }
415
416                 DBG((dbg, LEVEL_3, "  ...%+F\n", node));
417
418                 /* record state changes by the node */
419                 if (get_irn_mode(node) == mode_T) {
420                         const ir_edge_t *edge;
421
422                         foreach_out_edge(node, edge) {
423                                 const arch_register_t *reg;
424                                 ir_node *proj = get_edge_src_irn(edge);
425
426                                 if (!mode_is_data(get_irn_mode(proj)))
427                                         continue;
428
429                                 reg = arch_get_irn_register(proj);
430                                 if (reg == env->reg) {
431                                         current_state = proj;
432                                         DBG((dbg, LEVEL_3, "\t... current_state <- %+F\n", current_state));
433                                 }
434                         }
435                 } else {
436                         if (mode_is_data(get_irn_mode(node))) {
437                                 const arch_register_t *reg = arch_get_irn_register(node);
438                                 if (reg == env->reg) {
439                                         current_state = node;
440                                         DBG((dbg, LEVEL_3, "\t... current_state <- %+F\n", current_state));
441                                 }
442                         }
443                 }
444         }
445
446         /* Remember end-workset for this block */
447         block_info->end_state = current_state;
448         DBG((dbg, LEVEL_3, "End value for %+F: %+F\n", block, current_state));
449 }
450
451 static void belady_walker(ir_node *block, void *data)
452 {
453         belady((minibelady_env_t*) data, block);
454 }
455
456 static ir_node *get_end_of_block_insertion_point(ir_node *block)
457 {
458         ir_node *last = sched_last(block);
459
460         /* skip Projs and Keep-alikes behind the jump... */
461         while (is_Proj(last) || be_is_Keep(last)) {
462                 last = sched_prev(last);
463         }
464
465         if (!is_cfop(last)) {
466                 last = sched_next(last);
467                 /* last node must be a cfop, only exception is the start block */
468                 assert(last == get_irg_start_block(get_irn_irg(block)));
469         }
470
471         return last;
472 }
473
474 /**
475  * We must adapt the live-outs to the live-ins at each block-border.
476  */
477 static void fix_block_borders(ir_node *block, void *data)
478 {
479         minibelady_env_t *env = (minibelady_env_t*)data;
480         ir_graph *irg = get_irn_irg(block);
481         ir_node *startblock = get_irg_start_block(irg);
482         int i;
483         int arity;
484         block_info_t *block_info;
485
486         if (block == startblock)
487                 return;
488
489         DBG((dbg, LEVEL_3, "\n"));
490
491         block_info = get_block_info(block);
492
493         DBG((dbg, LEVEL_3, "Fixing %+F (needs %+F)\n", block,
494              block_info->start_state));
495
496         /* process all pred blocks */
497         arity = get_irn_arity(block);
498         for (i = 0; i < arity; ++i) {
499                 ir_node      *pred       = get_Block_cfgpred_block(block, i);
500                 block_info_t *pred_info  = get_block_info(pred);
501                 ir_node      *need_state = block_info->start_state;
502
503                 if (need_state == NULL)
504                         continue;
505
506                 if (is_Phi(need_state) && get_nodes_block(need_state) == block) {
507                         need_state = get_irn_n(need_state, i);
508                 }
509
510                 DBG((dbg, LEVEL_3, "  Pred %+F (ends in %+F, we need %+F)\n", pred,
511                      pred_info->end_state, need_state));
512
513                 if (pred_info->end_state != need_state) {
514                         ir_node *insert_point = get_end_of_block_insertion_point(pred);
515
516
517                         DBG((dbg, LEVEL_3, "  Creating reload for %+F\n", need_state));
518                         create_reload(env, need_state, insert_point, pred_info->end_state);
519                 }
520         }
521 }
522
523 void be_assure_state(ir_graph *irg, const arch_register_t *reg, void *func_env,
524                      create_spill_func create_spill,
525                      create_reload_func create_reload)
526 {
527         minibelady_env_t env;
528         spill_info_t *info;
529         be_lv_t *lv = be_assure_liveness(irg);
530
531         be_liveness_assure_sets(lv);
532         /* construct control flow loop tree */
533         if (! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
534                 construct_cf_backedges(irg);
535         }
536
537         obstack_init(&env.obst);
538         env.reg           = reg;
539         env.func_env      = func_env;
540         env.create_spill  = create_spill;
541         env.create_reload = create_reload;
542         env.lv            = be_get_irg_liveness(irg);
543         env.uses          = be_begin_uses(irg, env.lv);
544         env.spills        = NULL;
545         ir_nodemap_init(&env.spill_infos);
546
547         assure_doms(irg);
548         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED | IR_RESOURCE_IRN_LINK);
549         inc_irg_visited(irg);
550
551         /* process blocks */
552         irg_block_walk_graph(irg, NULL, belady_walker, &env);
553
554         /* fix block end_states that don't match the next blocks start_state */
555         irg_block_walk_graph(irg, fix_block_borders, NULL, &env);
556
557         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED | IR_RESOURCE_IRN_LINK);
558
559         /* reconstruct ssa-form */
560         info = env.spills;
561         while (info != NULL) {
562                 be_ssa_construction_env_t senv;
563                 size_t i, len;
564                 ir_node **phis;
565
566                 be_ssa_construction_init(&senv, irg);
567                 if (sched_is_scheduled(info->value))
568                         be_ssa_construction_add_copy(&senv, info->value);
569                 be_ssa_construction_add_copies(&senv,
570                                                info->reloads, ARR_LEN(info->reloads));
571                 be_ssa_construction_fix_users(&senv, info->value);
572
573                 if (lv != NULL) {
574                         be_ssa_construction_update_liveness_phis(&senv, lv);
575
576                         be_liveness_update(lv, info->value);
577                         len = ARR_LEN(info->reloads);
578                         for (i = 0; i < len; ++i) {
579                                 ir_node *reload = info->reloads[i];
580                                 be_liveness_update(lv, reload);
581                         }
582                 }
583
584                 phis = be_ssa_construction_get_new_phis(&senv);
585
586                 /* set register requirements for phis */
587                 len = ARR_LEN(phis);
588                 for (i = 0; i < len; ++i) {
589                         ir_node *phi = phis[i];
590                         arch_set_irn_register(phi, env.reg);
591                 }
592                 be_ssa_construction_destroy(&senv);
593
594                 info = info->next;
595         }
596
597         /* some nodes might be dead now. */
598         be_remove_dead_nodes_from_schedule(irg);
599
600         ir_nodemap_destroy(&env.spill_infos);
601         be_end_uses(env.uses);
602         obstack_free(&env.obst, NULL);
603 }
604
605 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_state)
606 void be_init_state(void)
607 {
608         FIRM_DBG_REGISTER(dbg, "firm.be.state");
609 }