Another rewrite of prolog/epilog handling: Delay their creation until after register...
[libfirm] / ir / be / bespilldaemel.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       Naive spilling algorithm
23  * @author      Matthias Braun
24  * @date        20.09.2005
25  * @version     $Id: bespillbelady.c 13913 2007-05-18 12:48:56Z matze $
26  * @brief
27  *   This implements a naive spilling algorithm. It is designed to produce
28  *   similar effects to the spill decisions produced by traditional graph
29  *   coloring register allocators that spill while they are coloring the graph.
30  *
31  *   This spiller walks over all blocks and looks for places with too high
32  *   register pressure where it spills the values that are cheapest to spill.
33  *   Spilling in this context means placing a spill instruction behind the
34  *   definition of the value and a reload before each usage.
35  */
36 #include "config.h"
37
38 #include "debug.h"
39
40 #include "irnodeset.h"
41 #include "irgwalk.h"
42 #include "irprintf.h"
43 #include "iredges_t.h"
44 #include "error.h"
45
46 #include "beirg.h"
47 #include "bespill.h"
48 #include "bespillutil.h"
49 #include "bemodule.h"
50 #include "besched.h"
51 #include "bearch.h"
52 #include "be_t.h"
53 #include "benode.h"
54 #include "beirg.h"
55 #include "belive.h"
56
57 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
58
59 static spill_env_t                 *spill_env;
60 static unsigned                     n_regs;
61 static const arch_register_class_t *cls;
62 static const be_lv_t               *lv;
63 static bitset_t                    *spilled_nodes;
64
65 typedef struct spill_candidate_t spill_candidate_t;
66 struct spill_candidate_t {
67         double   costs;
68         ir_node *node;
69 };
70
71 static int compare_spill_candidates_desc(const void *d1, const void *d2)
72 {
73         const spill_candidate_t *c1 = (const spill_candidate_t*)d1;
74         const spill_candidate_t *c2 = (const spill_candidate_t*)d2;
75
76         return (int) (c1->costs - c2->costs);
77 }
78
79 static double get_spill_costs(ir_node *node)
80 {
81         const ir_edge_t *edge;
82         ir_node         *spill_place = skip_Proj(node);
83         double           costs       = be_get_spill_costs(spill_env, node,
84                                                           spill_place);
85
86         foreach_out_edge(node, edge) {
87                 ir_node *use = get_edge_src_irn(edge);
88
89                 /* keeps should be directly below the node */
90                 if (be_is_Keep(use)) {
91                         continue;
92                 }
93
94                 if (is_Phi(use)) {
95                         int      in    = get_edge_src_pos(edge);
96                         ir_node *block = get_nodes_block(use);
97
98                         costs += be_get_reload_costs_on_edge(spill_env, node, block, in);
99                 } else {
100                         costs += be_get_reload_costs(spill_env, node, use);
101                 }
102         }
103
104         return costs;
105 }
106
107 /**
108  * spills a node by placing a reload before each usage
109  */
110 static void spill_node(ir_node *node)
111 {
112         const ir_edge_t *edge;
113
114         DBG((dbg, LEVEL_3, "\tspilling %+F\n", node));
115
116         foreach_out_edge(node, edge) {
117                 ir_node *use = get_edge_src_irn(edge);
118                 if (is_Anchor(use))
119                         continue;
120                 if (be_is_Keep(use))
121                         continue;
122
123                 if (is_Phi(use)) {
124                         int      in         = get_edge_src_pos(edge);
125                         ir_node *block      = get_nodes_block(use);
126
127                         be_add_reload_on_edge(spill_env, node, block, in, cls, 1);
128                 } else {
129                         be_add_reload(spill_env, node, use, cls, 1);
130                 }
131         }
132
133         bitset_set(spilled_nodes, get_irn_idx(node));
134 }
135
136 static unsigned get_value_width(const ir_node *node)
137 {
138         const arch_register_req_t *req = arch_get_register_req_out(node);
139         return req->width;
140 }
141
142 /**
143  * spill @p n nodes from a nodeset. Removes the nodes from the nodeset and
144  * sets the spilled bits in spilled_nodes.
145  */
146 static void do_spilling(ir_nodeset_t *live_nodes, ir_node *node)
147 {
148         size_t                 n_live_nodes     = ir_nodeset_size(live_nodes);
149         size_t                 values_defined   = 0;
150         size_t                 free_regs_needed = 0;
151         spill_candidate_t     *candidates;
152         ir_nodeset_iterator_t  iter;
153         int                    i, arity;
154         size_t                 c;
155         int                    spills_needed;
156         size_t                 cand_idx;
157         ir_node               *n;
158         ir_node               *value;
159
160         be_foreach_definition(node, cls, value,
161                 assert(req_->width >= 1);
162                 values_defined += req_->width;
163         );
164
165         /* we need registers for the non-live argument values */
166         arity = get_irn_arity(node);
167         for (i = 0; i < arity; ++i) {
168                 ir_node *pred = get_irn_n(node, i);
169                 if (arch_irn_consider_in_reg_alloc(cls, pred)
170                                 && !ir_nodeset_contains(live_nodes, pred)) {
171                         free_regs_needed += get_value_width(pred);
172                 }
173         }
174
175         /* we can reuse all reloaded values for the defined values, but we might
176          * need even more registers */
177         if (values_defined > free_regs_needed)
178                 free_regs_needed = values_defined;
179
180         spills_needed = (n_live_nodes + free_regs_needed) - n_regs;
181         if (spills_needed <= 0)
182                 return;
183         DBG((dbg, LEVEL_2, "\tspills needed after %+F: %d\n", node, spills_needed));
184
185         candidates = ALLOCAN(spill_candidate_t, n_live_nodes);
186
187         /* construct array with spill candidates and calculate their costs */
188         c = 0;
189         foreach_ir_nodeset(live_nodes, n, iter) {
190                 spill_candidate_t *candidate = & candidates[c];
191
192                 assert(!bitset_is_set(spilled_nodes, get_irn_idx(n)));
193
194                 candidate->node  = n;
195                 candidate->costs = get_spill_costs(n);
196                 ++c;
197         }
198         assert(c == n_live_nodes);
199
200         /* sort spill candidates */
201         qsort(candidates, n_live_nodes, sizeof(candidates[0]),
202               compare_spill_candidates_desc);
203
204         /* spill cheapest ones */
205         cand_idx = 0;
206         while (spills_needed > 0) {
207                 bool                       is_use = false;
208                 spill_candidate_t         *candidate;
209                 ir_node                   *cand_node;
210
211                 if (cand_idx >= n_live_nodes) {
212                         panic("can't spill enough values for node %+F", node);
213                 }
214
215                 candidate = &candidates[cand_idx];
216                 cand_node = candidate->node;
217                 ++cand_idx;
218
219                 if (arch_irn_is(skip_Proj_const(cand_node), dont_spill))
220                         continue;
221
222                 /* make sure the node is not an argument of the instruction */
223                 for (i = 0; i < arity; ++i) {
224                         ir_node *in = get_irn_n(node, i);
225                         if (in == cand_node) {
226                                 is_use = true;
227                                 break;
228                         }
229                 }
230                 if (is_use)
231                         continue;
232
233                 spill_node(cand_node);
234                 ir_nodeset_remove(live_nodes, cand_node);
235                 spills_needed -= get_value_width(cand_node);
236         }
237 }
238
239 /**
240  * removes all values from the nodeset that are defined by node
241  */
242 static void remove_defs(ir_node *node, ir_nodeset_t *nodeset)
243 {
244         ir_node *value;
245         /* You must break out of your loop when hitting the first phi function. */
246         assert(!is_Phi(node));
247
248         be_foreach_definition(node, cls, value,
249                 ir_nodeset_remove(nodeset, value);
250         );
251 }
252
253 static void add_uses(ir_node *node, ir_nodeset_t *nodeset)
254 {
255         int i, arity;
256
257         arity = get_irn_arity(node);
258         for (i = 0; i < arity; ++i) {
259                 ir_node *op = get_irn_n(node, i);
260
261                 if (arch_irn_consider_in_reg_alloc(cls, op) &&
262                                 !bitset_is_set(spilled_nodes, get_irn_idx(op))) {
263                         ir_nodeset_insert(nodeset, op);
264                 }
265         }
266 }
267
268 static __attribute__((unused))
269 void print_nodeset(ir_nodeset_t *nodeset)
270 {
271         ir_nodeset_iterator_t  iter;
272         ir_node               *node;
273
274         foreach_ir_nodeset(nodeset, node, iter) {
275                 ir_fprintf(stderr, "%+F ", node);
276         }
277         fprintf(stderr, "\n");
278 }
279
280 /**
281  * make sure register pressure in a block is always equal or below the number
282  * of available registers
283  */
284 static void spill_block(ir_node *block, void *data)
285 {
286         ir_nodeset_t           live_nodes;
287         ir_nodeset_iterator_t  iter;
288         ir_node               *node;
289         int                    n_phi_values_spilled;
290         int                    regpressure;
291         int                    live_nodes_pressure;
292         int                    phi_spills_needed;
293         (void) data;
294
295         DBG((dbg, LEVEL_1, "spilling block %+F\n", block));
296
297         /* construct set of live nodes at end of block */
298         ir_nodeset_init(&live_nodes);
299         be_liveness_end_of_block(lv, cls, block, &live_nodes);
300
301         /* remove already spilled nodes from liveset */
302         foreach_ir_nodeset(&live_nodes, node, iter) {
303                 DBG((dbg, LEVEL_2, "\t%+F is live-end... ", node));
304                 if (bitset_is_set(spilled_nodes, get_irn_idx(node))) {
305                         DBG((dbg, LEVEL_2, "but spilled; removing.\n"));
306                         ir_nodeset_remove_iterator(&live_nodes, &iter);
307                 } else {
308                         DBG((dbg, LEVEL_2, "keeping.\n"));
309                 }
310         }
311
312         /* walk schedule backwards and spill until register pressure is fine at
313          * each node */
314         sched_foreach_reverse(block, node) {
315                 if (is_Phi(node))
316                         break;
317
318                 remove_defs(node, &live_nodes);
319                 do_spilling(&live_nodes, node);
320                 add_uses(node, &live_nodes);
321         }
322
323         /* until now only the values of some phis have been spilled the phis itself
324          * are still there and occupy registers, so we need to count them and might
325          * have to spill some of them. */
326         n_phi_values_spilled = 0;
327         sched_foreach(block, node) {
328                 if (!is_Phi(node))
329                         break;
330
331                 if (bitset_is_set(spilled_nodes, get_irn_idx(node))) {
332                         n_phi_values_spilled += get_value_width(node);
333                 }
334         }
335
336         live_nodes_pressure = 0;
337         foreach_ir_nodeset(&live_nodes, node, iter) {
338                 live_nodes_pressure += get_value_width(node);
339         }
340
341         /* calculate how many of the phis need to be spilled */
342         regpressure       = live_nodes_pressure + n_phi_values_spilled;
343         phi_spills_needed = regpressure - n_regs;
344         DBG((dbg, LEVEL_3, "Regpressure before phis: %d phispills: %d\n",
345              regpressure, phi_spills_needed));
346
347         /* spill as many phis as needed */
348         /* TODO: we should really estimate costs of the phi spill as well...
349          * and preferably spill phis with lower costs... */
350         sched_foreach(block, node) {
351                 if (!is_Phi(node))
352                         break;
353                 if (phi_spills_needed <= 0)
354                         break;
355
356                 if (!bitset_is_set(spilled_nodes, get_irn_idx(node)))
357                         continue;
358
359                 be_spill_phi(spill_env, node);
360                 phi_spills_needed -= get_value_width(node);
361         }
362         assert(phi_spills_needed <= 0);
363
364         ir_nodeset_destroy(&live_nodes);
365 }
366
367 static void be_spill_daemel(ir_graph *irg, const arch_register_class_t *new_cls)
368 {
369         n_regs = be_get_n_allocatable_regs(irg, new_cls);
370         if (n_regs == 0)
371                 return;
372
373         be_liveness_assure_sets(be_assure_liveness(irg));
374
375         spill_env     = be_new_spill_env(irg);
376         cls           = new_cls;
377         lv            = be_get_irg_liveness(irg);
378         spilled_nodes = bitset_malloc(get_irg_last_idx(irg));
379
380         DBG((dbg, LEVEL_1, "*** RegClass %s\n", cls->name));
381
382         irg_block_walk_graph(irg, spill_block, NULL, NULL);
383
384         bitset_free(spilled_nodes);
385
386         be_insert_spills_reloads(spill_env);
387         be_delete_spill_env(spill_env);
388 }
389
390 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_daemelspill);
391 void be_init_daemelspill(void)
392 {
393         static be_spiller_t daemel_spiller = {
394                 be_spill_daemel
395         };
396
397         be_register_spiller("daemel", &daemel_spiller);
398         FIRM_DBG_REGISTER(dbg, "firm.be.spilldaemel");
399 }