added support for unaligned entities
[libfirm] / ir / be / bespillmorgan.c
1 /*
2  * Copyright (C) 1995-2007 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       Morgans spill algorithm.
23  * @author      Matthias Braun
24  * @date        05.05.2006
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "irgwalk.h"
32 #include "irloop_t.h"
33 #include "irgraph_t.h"
34 #include "irprintf.h"
35 #include "obst.h"
36 #include "error.h"
37
38 #include "bespillmorgan.h"
39 #include "bechordal_t.h"
40 #include "bespill.h"
41 #include "belive_t.h"
42 #include "beabi.h"
43 #include "bespillbelady.h"
44 #include "beverify.h"
45 #include "benodesets.h"
46 #include "bespilloptions.h"
47 #include "besched.h"
48 #include "beutil.h"
49 #include "bemodule.h"
50 #include "beirg_t.h"
51
52 #define DBG_LIVE                1
53 #define DBG_LOOPANA             2
54 #define DBG_PRESSURE    4
55 #define DBG_SPILLS      8
56 #define DBG_CHOOSE              16
57 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
58
59 typedef struct morgan_env {
60         const arch_env_t *arch;
61         const arch_register_class_t *cls;
62         ir_graph *irg;
63         be_lv_t *lv;
64         struct obstack obst;
65         /** maximum safe register pressure */
66         int registers_available;
67
68         spill_env_t *senv;
69
70         set *loop_attr_set;
71         set *block_attr_set;
72 } morgan_env_t;
73
74 typedef struct loop_edge {
75         ir_node *block;
76         int pos;
77 } loop_edge_t;
78
79 typedef struct loop_attr {
80         const ir_loop *loop;
81         set *out_edges;
82         set *in_edges;
83         /** The set of all values that are live in the loop but not used in the loop */
84         bitset_t *livethrough_unused;
85 } loop_attr_t;
86
87 typedef struct morgan_block_attr {
88         const ir_node *block;
89         /** set of all values that are live in the block but not used in the block */
90         bitset_t *livethrough_unused;
91 } block_attr_t;
92
93 //---------------------------------------------------------------------------
94
95 static int loop_edge_cmp(const void* p1, const void* p2, size_t size) {
96         loop_edge_t *e1 = (loop_edge_t*) p1;
97         loop_edge_t *e2 = (loop_edge_t*) p2;
98         (void) size;
99
100         return e1->block != e2->block || e1->pos != e2->pos;
101 }
102
103 static int loop_attr_cmp(const void *e1, const void *e2, size_t size) {
104         loop_attr_t *la1 = (loop_attr_t*) e1;
105         loop_attr_t *la2 = (loop_attr_t*) e2;
106         (void) size;
107
108         return la1->loop != la2->loop;
109 }
110
111 static int block_attr_cmp(const void *e1, const void *e2, size_t size) {
112         block_attr_t *b1 = (block_attr_t*) e1;
113         block_attr_t *b2 = (block_attr_t*) e2;
114         (void) size;
115
116         return b1->block != b2->block;
117 }
118
119 static INLINE int loop_attr_hash(const loop_attr_t *a) {
120 #ifdef DEBUG_libfirm
121         return a->loop->loop_nr;
122 #else
123         return HASH_PTR(a->loop);
124 #endif
125 }
126
127 static INLINE int block_attr_hash(const block_attr_t *b) {
128         return nodeset_hash(b->block);
129 }
130
131 static INLINE int loop_edge_hash(const loop_edge_t *e) {
132         return nodeset_hash(e->block) ^ (e->pos * 31);
133 }
134
135 static INLINE loop_attr_t *get_loop_attr(morgan_env_t *env, const ir_loop *loop) {
136         loop_attr_t l_attr, *res;
137         int hash;
138         l_attr.loop = loop;
139
140         hash = loop_attr_hash(&l_attr);
141         res = set_find(env->loop_attr_set, &l_attr, sizeof(l_attr), hash);
142
143         // create new loop_attr if none exists yet
144         if (res == NULL) {
145                 l_attr.out_edges = new_set(loop_edge_cmp, 1);
146                 l_attr.in_edges = new_set(loop_edge_cmp, 1);
147                 l_attr.livethrough_unused = bitset_obstack_alloc(&env->obst, get_irg_last_idx(env->irg));
148                 res = set_insert(env->loop_attr_set, &l_attr, sizeof(l_attr), hash);
149         }
150
151         return res;
152 }
153
154 static INLINE block_attr_t *get_block_attr(morgan_env_t *env, const ir_node *block) {
155         block_attr_t b_attr, *res;
156         int hash;
157         b_attr.block = block;
158
159         hash = block_attr_hash(&b_attr);
160         res = set_find(env->block_attr_set, &b_attr, sizeof(b_attr), hash);
161
162         if(res == NULL) {
163                 b_attr.livethrough_unused = NULL;
164                 res = set_insert(env->block_attr_set, &b_attr, sizeof(b_attr), hash);
165         }
166
167         return res;
168 }
169
170 //---------------------------------------------------------------------------
171
172 static INLINE int consider_for_spilling(const arch_env_t *env, const arch_register_class_t *cls, const ir_node *node) {
173         if(!arch_irn_has_reg_class(env, node, -1, cls))
174                 return 0;
175
176         return !(arch_irn_get_flags(env, node) & (arch_irn_flags_ignore | arch_irn_flags_dont_spill));
177 }
178
179 /**
180  * Determine edges going out of a loop (= edges that go to a block that is not
181  * inside the loop or one of its subloops)
182  */
183 static INLINE void construct_loop_edges(ir_node *block, void *data) {
184         morgan_env_t *env = data;
185         int n_cfgpreds = get_Block_n_cfgpreds(block);
186         int i;
187         ir_loop* loop = get_irn_loop(block);
188         DBG((dbg, DBG_LOOPANA, "Loop for %+F: %d (depth %d)\n", block, loop->loop_nr, loop->depth));
189
190         for(i = 0; i < n_cfgpreds; ++i) {
191                 loop_edge_t edge;
192                 int hash;
193                 ir_node* cfgpred = get_Block_cfgpred(block, i);
194                 ir_node* cfgpred_block = get_nodes_block(cfgpred);
195                 ir_loop* cfgpred_loop = get_irn_loop(cfgpred_block);
196
197                 if(cfgpred_loop == loop)
198                         continue;
199
200                 assert(get_loop_depth(cfgpred_loop) != get_loop_depth(loop));
201
202                 edge.block = block;
203                 edge.pos = i;
204                 hash = loop_edge_hash(&edge);
205
206                 // edge out of a loop?
207                 if(get_loop_depth(cfgpred_loop) > get_loop_depth(loop)) {
208                         ir_loop *l;
209
210                         DBG((dbg, DBG_LOOPANA, "Loop out edge from %+F (loop %d) to %+F (loop %d)\n", block, get_loop_loop_nr(loop),
211                              cfgpred_block, get_loop_loop_nr(cfgpred_loop)));
212
213                         /* this might be a jump out of multiple loops, so add this to all
214                      * needed outedge sets */
215                         l = cfgpred_loop;
216                         do {
217                                 loop_attr_t *l_attr = get_loop_attr(env, l);
218                                 set_insert(l_attr->out_edges, &edge, sizeof(edge), hash);
219
220                                 l = get_loop_outer_loop(l);
221                                 assert(l != NULL);
222                         } while(l != loop);
223                 } else {
224                         ir_loop *l;
225
226                         // edge into a loop
227                         DBG((dbg, DBG_LOOPANA, "Loop in edge from %+F (loop %d) to %+F (loop %d)\n", block, get_loop_loop_nr(loop),
228                              cfgpred_block, get_loop_loop_nr(cfgpred_loop)));
229
230                         l = loop;
231                         do {
232                                 loop_attr_t *l_attr = get_loop_attr(env, l);
233                                 set_insert(l_attr->in_edges, &edge, sizeof(edge), hash);
234
235                                 l = get_loop_outer_loop(l);
236                         } while(l != cfgpred_loop);
237                 }
238         }
239 }
240
241 static void free_loop_edges(morgan_env_t *env) {
242         loop_attr_t *l_attr;
243
244         for(l_attr = set_first(env->loop_attr_set); l_attr != NULL; l_attr = set_next(env->loop_attr_set)) {
245                 del_set(l_attr->out_edges);
246                 del_set(l_attr->in_edges);
247         }
248 }
249
250 #if 0
251 /**
252  * Debugging help, shows all nodes in a (node-)bitset
253  */
254 static void show_nodebitset(ir_graph* irg, const bitset_t* bitset) {
255         int i;
256
257         bitset_foreach(bitset, i) {
258                 ir_node* node = get_idx_irn(irg, i);
259                 ir_fprintf(stderr, " %+F", node);
260         }
261         fprintf(stderr, "\n");
262 }
263 #endif
264
265 static INLINE void init_livethrough_unuseds(block_attr_t *attr, morgan_env_t *env) {
266         const ir_node *block;
267         int i;
268         const be_lv_t *lv = env->lv;
269
270         if(attr->livethrough_unused != NULL)
271                 return;
272
273         block = attr->block;
274
275         attr->livethrough_unused = bitset_obstack_alloc(&env->obst, get_irg_last_idx(env->irg));
276
277         // copy all live-outs into the livethrough_unused set
278         be_lv_foreach(lv, block, be_lv_state_in | be_lv_state_out, i) {
279                 ir_node *irn = be_lv_get_irn(lv, block, i);
280                 int node_idx;
281
282                 if(!consider_for_spilling(env->arch, env->cls, irn))
283                         continue;
284
285                 node_idx = get_irn_idx(irn);
286                 bitset_set(attr->livethrough_unused, node_idx);
287         }
288 }
289
290 /**
291  * Construct the livethrough unused set for a block
292  */
293 static void construct_block_livethrough_unused(ir_node *block, void *data) {
294         morgan_env_t* env = data;
295         block_attr_t *block_attr = get_block_attr(env, block);
296         ir_node *node;
297         int n_cfgpreds;
298         block_attr_t **pred_attrs = NULL;
299         int i;
300
301         init_livethrough_unuseds(block_attr, env);
302
303         DBG((dbg, DBG_LIVE, "Processing block %d\n", get_irn_node_nr(block)));
304
305         n_cfgpreds = get_Block_n_cfgpreds(block);
306         if(n_cfgpreds > 1) {
307                 pred_attrs = alloca(sizeof(pred_attrs[0]) * n_cfgpreds);
308                 for(i = 0; i < n_cfgpreds; ++i) {
309                         ir_node *pred_block = get_Block_cfgpred_block(block, i);
310                         pred_attrs[i] = get_block_attr(env, pred_block);
311                         init_livethrough_unuseds(pred_attrs[i], env);
312                 }
313         }
314
315         /*
316          * All values that are used within the block are not unused (and therefore not
317          * livethrough_unused)
318          *
319          * TODO FIXME use block out edges and not schedule to find uses
320          */
321         panic("needs fixing");
322         sched_foreach(block, node) {
323                 int i, arity;
324
325                 // phis are really uses in the pred block
326                 if(is_Phi(node)) {
327                         int j;
328                         for(j = 0; j < n_cfgpreds; ++j) {
329                                 ir_node *used_value = get_Phi_pred(node, j);
330                                 int idx = get_irn_idx(used_value);
331                                 block_attr_t *pred_attr = pred_attrs[j];
332
333                                 bitset_clear(pred_attr->livethrough_unused, idx);
334                         }
335                 } else {
336                         // mark all used values as used
337                         for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
338                                 int idx = get_irn_idx(get_irn_n(node, i));
339                                 bitset_clear(block_attr->livethrough_unused, idx);
340                         }
341                 }
342         }
343 }
344
345 /**
346  * Construct the livethrough unused set for a loop (and all its subloops+blocks)
347  */
348 static bitset_t *construct_loop_livethrough_unused(morgan_env_t *env, const ir_loop *loop) {
349         int i;
350         loop_attr_t* loop_attr = get_loop_attr(env, loop);
351
352         DBG((dbg, DBG_LIVE, "Processing Loop %d\n", loop->loop_nr));
353         assert(get_loop_n_elements(loop) > 0);
354         for(i = 0; i < get_loop_n_elements(loop); ++i) {
355                 loop_element elem = get_loop_element(loop, i);
356                 switch (*elem.kind) {
357                 case k_ir_node: {
358                         ir_node *block = elem.node;
359                         block_attr_t *block_attr = get_block_attr(env, block);
360                         bitset_t *livethrough_block_unused = block_attr->livethrough_unused;
361
362                         assert(is_Block(elem.node));
363                         assert(livethrough_block_unused != NULL);
364
365                         if(i == 0) {
366                                 bitset_copy(loop_attr->livethrough_unused, livethrough_block_unused);
367                         } else {
368                                 bitset_and(loop_attr->livethrough_unused, livethrough_block_unused);
369                         }
370                         break;
371                 }
372                 case k_ir_loop: {
373                         bitset_t *livethrough_son_unused;
374
375                         livethrough_son_unused = construct_loop_livethrough_unused(env, elem.son);
376                         if(i == 0) {
377                                 bitset_copy(loop_attr->livethrough_unused, livethrough_son_unused);
378                         } else {
379                                 bitset_and(loop_attr->livethrough_unused, livethrough_son_unused);
380                         }
381                         break;
382                 }
383             default:
384                         assert(0);
385                         break;
386                 }
387     }
388         DBG((dbg, DBG_LIVE, "Done with loop %d\n", loop->loop_nr));
389
390         // remove all unused livethroughs that are remembered for this loop from child loops and blocks
391         for(i = 0; i < get_loop_n_elements(loop); ++i) {
392                 const loop_element elem = get_loop_element(loop, i);
393
394                 if(*elem.kind == k_ir_loop) {
395                         loop_attr_t *son_attr = get_loop_attr(env, elem.son);
396                         bitset_andnot(son_attr->livethrough_unused, loop_attr->livethrough_unused);
397
398                         DBG((dbg, DBG_LIVE, "Livethroughs for loop %d:\n", loop->loop_nr));
399                 } else if(*elem.kind == k_ir_node) {
400                         block_attr_t *block_attr = get_block_attr(env, elem.node);
401                         bitset_andnot(block_attr->livethrough_unused, loop_attr->livethrough_unused);
402
403                         DBG((dbg, DBG_LIVE, "Livethroughs for block %+F\n", elem.node));
404                 } else {
405                         assert(0);
406                 }
407         }
408
409         return loop_attr->livethrough_unused;
410 }
411
412 /*---------------------------------------------------------------------------*/
413
414 typedef struct _spillcandidate_t {
415         ir_node *node;
416         int cost;
417 } spillcandidate_t;
418
419 static int compare_spillcandidates(const void *d1, const void *d2) {
420         const spillcandidate_t *cand1 = d1;
421         const spillcandidate_t *cand2 = d2;
422
423         return cand1->cost - cand2->cost;
424 }
425
426 static void spill_values(morgan_env_t *env, const loop_attr_t *loop_attr, int spills) {
427         const bitset_t *cand_bitset = loop_attr->livethrough_unused;
428         int candidatecount = bitset_popcnt(cand_bitset);
429         spillcandidate_t *candidates;
430         bitset_pos_t idx;
431         int i, c;
432         loop_edge_t *edge;
433
434         assert(spills <= candidatecount);
435
436         candidates = alloca(sizeof(candidates[0]) * candidatecount);
437
438         DBG((dbg, DBG_CHOOSE, "Candidates for loop %d\n", get_loop_loop_nr(loop_attr->loop)));
439         // build candidiatelist
440         c = 0;
441         bitset_foreach(cand_bitset, idx) {
442                 ir_node *node = get_idx_irn(env->irg, idx);
443                 candidates[c].node = node;
444                 candidates[c].cost = 0;
445
446                 for(edge = set_first(loop_attr->out_edges); edge != NULL; edge = set_next(loop_attr->out_edges)) {
447                         candidates[c].cost += be_get_reload_costs_on_edge(env->senv, node, edge->block, edge->pos);
448                 }
449                 DBG((dbg, DBG_CHOOSE, "%+F has costs %d\n", node, candidates[c].cost));
450
451                 c++;
452         }
453         assert(c == candidatecount);
454
455         // sort list
456         qsort(candidates, candidatecount, sizeof(candidates[0]), compare_spillcandidates);
457
458         // spill values
459         for(i = 0; i < spills; ++i) {
460                 ir_node *to_spill = candidates[i].node;
461                 DBG((dbg, DBG_CHOOSE, "Spilling %+F ", to_spill));
462
463                 for(edge = set_first(loop_attr->out_edges); edge != NULL; edge = set_next(loop_attr->out_edges)) {
464                         be_add_reload_on_edge(env->senv, to_spill, edge->block, edge->pos, env->cls, 1);
465                 }
466         }
467 }
468
469 static int reduce_register_pressure_in_block(morgan_env_t *env, const ir_node* block, int loop_unused_spills_possible) {
470         ir_node *node;
471         int max_pressure;
472         int loop_unused_spills_needed;
473         ir_nodeset_t live_nodes;
474         const be_lv_t *lv = env->lv;
475
476         ir_nodeset_init(&live_nodes);
477
478         be_liveness_end_of_block(lv, env->arch, env->cls, block, &live_nodes);
479         max_pressure = ir_nodeset_size(&live_nodes);
480
481         DBG((dbg, DBG_LIVE, "Reduce pressure to %d In Block %+F:\n", env->registers_available, block));
482
483         /**
484          * Determine register pressure in block
485          */
486         sched_foreach_reverse(block, node) {
487                 int pressure;
488
489                 if(is_Phi(node))
490                         break;
491
492                 be_liveness_transfer(env->arch, env->cls, node, &live_nodes);
493                 pressure = ir_nodeset_size(&live_nodes);
494                 if(pressure > max_pressure)
495                         max_pressure = pressure;
496         }
497         ir_nodeset_destroy(&live_nodes);
498
499         loop_unused_spills_needed = max_pressure - env->registers_available;
500
501         if(loop_unused_spills_needed < 0) {
502                 loop_unused_spills_needed = 0;
503         } else if(loop_unused_spills_needed > loop_unused_spills_possible) {
504                 loop_unused_spills_needed = loop_unused_spills_possible;
505         }
506
507         DBG((dbg, DBG_PRESSURE, "Block %+F: max-pressure %d spills possible: %d spills used: %d\n",
508                  block, max_pressure, loop_unused_spills_possible, loop_unused_spills_needed));
509         return loop_unused_spills_needed;
510 }
511
512 /**
513  * Reduce register pressure in a loop
514  *
515  * @param unused_spills_possible        Number of spills from livethrough_unused variables possible in outer loops
516  * @return                                                      Number of spills of livethrough_unused variables needed in outer loops
517  */
518 static int reduce_register_pressure_in_loop(morgan_env_t *env, const ir_loop *loop, int outer_spills_possible) {
519         int i;
520         loop_attr_t* loop_attr = get_loop_attr(env, loop);
521         int spills_needed = 0;
522         int spills_possible = outer_spills_possible + bitset_popcnt(loop_attr->livethrough_unused);
523         int outer_spills_needed;
524
525         DBG((dbg, DBG_PRESSURE, "Reducing Pressure in loop %d\n", loop->loop_nr));
526         for(i = 0; i < get_loop_n_elements(loop); ++i) {
527                 loop_element elem = get_loop_element(loop, i);
528                 switch (*elem.kind) {
529                 case k_ir_node: {
530                         int needed;
531                         assert(is_Block(elem.node));
532                         needed = reduce_register_pressure_in_block(env, elem.node, spills_possible);
533                         assert(needed >= 0);
534                         assert(needed <= spills_possible);
535                         if(needed > spills_needed)
536                                 spills_needed = needed;
537                         break;
538                 }
539                 case k_ir_loop: {
540                         int needed = reduce_register_pressure_in_loop(env, elem.son, spills_possible);
541                         assert(needed >= 0);
542                         assert(needed <= spills_possible);
543                         if(needed > spills_needed)
544                                 spills_needed = needed;
545                         break;
546                 }
547             default:
548                         assert(0);
549                         break;
550                 }
551     }
552
553         /* calculate number of spills needed in outer loop and spill
554          * unused livethrough nodes around this loop */
555         if(spills_needed > outer_spills_possible) {
556                 int spills_to_place;
557                 outer_spills_needed = outer_spills_possible;
558                 spills_needed -= outer_spills_possible;
559
560                 spills_to_place = spills_needed;
561
562                 DBG((dbg, DBG_SPILLS, "%d values unused in loop %d, spilling %d\n",
563                  spills_possible - outer_spills_possible, loop->loop_nr, spills_to_place));
564
565                 spill_values(env, loop_attr, spills_to_place);
566         } else {
567                 outer_spills_needed = spills_needed;
568         }
569
570         return outer_spills_needed;
571 }
572
573 void be_spill_morgan(be_irg_t *birg, const arch_register_class_t *cls) {
574         ir_graph     *irg = be_get_birg_irg(birg);
575         morgan_env_t env;
576
577         be_liveness_assure_sets(be_assure_liveness(birg));
578
579         env.arch = birg->main_env->arch_env;
580         env.irg  = irg;
581         env.cls  = cls;
582         env.lv   = be_get_birg_liveness(birg);
583         env.senv = be_new_spill_env(birg);
584
585         obstack_init(&env.obst);
586
587         env.registers_available = env.cls->n_regs - be_put_ignore_regs(birg, env.cls, NULL);
588
589         env.loop_attr_set  = new_set(loop_attr_cmp, 5);
590         env.block_attr_set = new_set(block_attr_cmp, 20);
591
592         /* -- Part1: Analysis -- */
593
594         /* construct control flow loop tree */
595         if (! (get_irg_loopinfo_state(irg) & loopinfo_cf_consistent)) {
596                 construct_cf_backedges(irg);
597         }
598
599         /* construct loop out edges and livethrough_unused sets for loops and blocks */
600         irg_block_walk_graph(irg, construct_block_livethrough_unused, construct_loop_edges, &env);
601         construct_loop_livethrough_unused(&env, get_irg_loop(irg));
602
603         /* -- Part2: Transformation -- */
604
605         /* spill unused livethrough values around loops and blocks where
606          * the pressure is too high
607          */
608         reduce_register_pressure_in_loop(&env, get_irg_loop(irg), 0);
609
610         /* Insert real spill/reload nodes and fix usages */
611         be_insert_spills_reloads(env.senv);
612
613         /* Verify the result */
614         if (birg->main_env->options->vrfy_option == BE_VRFY_WARN) {
615                 be_verify_schedule(birg);
616         } else if (birg->main_env->options->vrfy_option == BE_VRFY_ASSERT) {
617                 assert(be_verify_schedule(birg));
618         }
619
620         /* cleanup */
621         free_loop_edges(&env);
622         del_set(env.loop_attr_set);
623         del_set(env.block_attr_set);
624
625         /* fix the remaining places with too high register pressure with beladies algorithm */
626         be_spill_belady_spill_env(birg, cls, env.senv);
627
628         be_delete_spill_env(env.senv);
629         obstack_free(&env.obst, NULL);
630 }
631
632 void be_init_spillmorgan(void)
633 {
634         static be_spiller_t morgan_spiller = {
635                 be_spill_morgan
636         };
637
638         be_register_spiller("morgan", &morgan_spiller);
639         FIRM_DBG_REGISTER(dbg, "ir.be.spillmorgan");
640 }
641
642 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillmorgan);