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