Bugfix: allocate the right number of in's
[libfirm] / ir / opt / tailrec.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/tailrec.c
4  * Purpose:     tail-recursion optimization
5  * Author:      Michael Beck
6  * Modified by:
7  * Created:     08.06.2004
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2002-2004 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12 #ifdef HAVE_CONFIG_H
13 # include "config.h"
14 #endif
15
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19 #ifdef HAVE_MALLOC_H
20 #include <malloc.h>
21 #endif
22 #ifdef HAVE_STRING_H
23 #include <string.h>
24 #endif
25
26 #include <assert.h>
27 #include "tailrec.h"
28 #include "array.h"
29 #include "irprog.h"
30 #include "irgwalk.h"
31 #include "irgmod.h"
32 #include "irop.h"
33 #include "irnode_t.h"
34 #include "irgraph_t.h"
35 #include "ircons.h"
36 #include "irflag.h"
37 #include "trouts.h"
38 #include "return.h"
39 #include "irhooks.h"
40
41 /**
42  * the environment for collecting data
43  */
44 typedef struct _collect_t {
45   ir_node *proj_X;      /**< initial exec proj */
46   ir_node *block;       /**< old first block */
47   int     blk_idx;      /**< cfgpred index of the initial exec in block */
48   ir_node *proj_m;      /**< linked list of memory from start proj's */
49   ir_node *proj_data;   /**< linked list of all parameter access proj's */
50 } collect_t;
51
52 /**
53  * walker for collecting data, fills a collect_t environment
54  */
55 static void collect_data(ir_node *node, void *env)
56 {
57   collect_t *data = env;
58   ir_node *pred;
59   ir_op *op;
60
61   switch (get_irn_opcode(node)) {
62   case iro_Proj:
63     pred = get_Proj_pred(node);
64
65     op = get_irn_op(pred);
66     if (op == op_Proj) {
67       ir_node *start = get_Proj_pred(pred);
68
69       if (get_irn_op(start) == op_Start) {
70             if (get_Proj_proj(pred) == pn_Start_T_args) {
71               /* found Proj(ProjT(Start)) */
72               set_irn_link(node, data->proj_data);
73               data->proj_data = node;
74             }
75       }
76     }
77     else if (op == op_Start) {
78       switch (get_Proj_proj(node)) {
79         case pn_Start_M:
80           /* found ProjM(Start) */
81               set_irn_link(node, data->proj_m);
82               data->proj_m = node;
83               break;
84             case pn_Start_X_initial_exec:
85               /* found ProjX(Start) */
86               data->proj_X = node;
87               break;
88             default:
89               break;
90       }
91     }
92     break;
93   case iro_Block: {
94     int i, n_pred = get_Block_n_cfgpreds(node);
95
96     /*
97      * the first block has the initial exec as cfg predecessor
98      */
99     if (node != current_ir_graph->start_block) {
100       for (i = 0; i < n_pred; ++i) {
101             if (get_Block_cfgpred(node, i) == data->proj_X) {
102               data->block   = node;
103               data->blk_idx = i;
104               break;
105             }
106       }
107     }
108     break;
109   }
110   default:
111     break;
112   }
113 }
114
115 /**
116  * do the graph reconstruction for tail-recursion elimination
117  *
118  * @param irg           the graph that will reconstructed
119  * @param rets          linked list of all rets
120  * @param n_tail_calls  number of tail-recursion calls
121  */
122 static void do_opt_tail_rec(ir_graph *irg, ir_node *rets, int n_tail_calls)
123 {
124   ir_node *end_block = get_irg_end_block(irg);
125   ir_node *block, *jmp, *call, *calls;
126   ir_node **in;
127   ir_node **phis;
128   ir_node ***call_params;
129   ir_node *p;
130   int i, j, n_params;
131   collect_t data;
132   int rem         = get_optimize();
133   entity *ent     = get_irg_entity(irg);
134   type *method_tp = get_entity_type(ent);
135
136   assert(n_tail_calls);
137
138   /* we add new nodes, so the outs are inconsistant */
139   set_irg_outs_inconsistent(irg);
140
141   /* we add new blocks and change the control flow */
142   set_irg_dom_inconsistent(irg);
143
144   /* we add a new loop */
145   set_irg_loopinfo_inconsistent(irg);
146
147   /* calls are removed */
148   set_trouts_inconsistent();
149
150   /* we must build some new nodes WITHOUT CSE */
151   set_optimize(0);
152
153   /* collect needed data */
154   data.proj_X    = NULL;
155   data.block     = NULL;
156   data.blk_idx   = -1;
157   data.proj_m    = NULL;
158   data.proj_data = NULL;
159   irg_walk_graph(irg, NULL, collect_data, &data);
160
161   /* check number of arguments */
162   call = get_irn_link(end_block);
163   n_params = get_Call_n_params(call);
164
165   assert(data.proj_X && "Could not find initial exec from Start");
166   assert(data.block  && "Could not find first block");
167   assert(data.proj_m && "Could not find ProjM(Start)");
168   assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
169
170   /* allocate in's for phi and block construction */
171   NEW_ARR_A(ir_node *, in, n_tail_calls + 1);
172
173   in[0] = data.proj_X;
174
175   /* turn Return's into Jmp's */
176   for (i = 1, p = rets; p; p = get_irn_link(p)) {
177     ir_node *jmp;
178     ir_node *block = get_nodes_block(p);
179
180     jmp = new_r_Jmp(irg, block);
181
182     exchange(p, new_r_Bad(irg));
183     in[i++] = jmp;
184
185     /* we might generate an endless loop, so add
186      * the block to the keep-alive list */
187     add_End_keepalive(get_irg_end(irg), block);
188   }
189
190   /* create a new block at start */
191   block = new_r_Block(irg, n_tail_calls + 1, in);
192   jmp   = new_r_Jmp(irg, block);
193
194   /* the old first block is now the second one */
195   set_Block_cfgpred(data.block, data.blk_idx, jmp);
196
197   /* allocate phi's, position 0 contains the memory phi */
198   NEW_ARR_A(ir_node *, phis, n_params + 1);
199
200   /* build the memory phi */
201   i = 0;
202   in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
203   ++i;
204
205   for (calls = call; calls; calls = get_irn_link(calls)) {
206     in[i] = get_Call_mem(calls);
207     ++i;
208   }
209   assert(i == n_tail_calls + 1);
210
211   phis[0] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode_M);
212
213   /* build the data phi's */
214   if (n_params > 0) {
215     ir_node *calls;
216
217     NEW_ARR_A(ir_node **, call_params, n_tail_calls);
218
219     /* collect all parameters */
220     for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
221       call_params[i] = get_Call_param_arr(calls);
222       ++i;
223     }
224
225     /* build new projs and Phi's */
226     for (i = 0; i < n_params; ++i) {
227       ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
228
229       in[0] = new_r_Proj(irg, block, irg->args, mode, i);
230       for (j = 0; j < n_tail_calls; ++j)
231         in[j + 1] = call_params[j][i];
232
233       phis[i + 1] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode);
234     }
235   }
236
237   /*
238    * ok, we are here, so we have build and collected all needed Phi's
239    * now exchange all Projs into links to Phi
240    */
241   for (p = data.proj_m; p; p = get_irn_link(p)) {
242     exchange(p, phis[0]);
243   }
244   for (p = data.proj_data; p; p = get_irn_link(p)) {
245     long proj = get_Proj_proj(p);
246
247     assert(0 <= proj && proj < n_params);
248     exchange(p, phis[proj + 1]);
249   }
250
251   /* tail recursion was done, all info is invalid */
252   set_irg_dom_inconsistent(irg);
253   set_irg_outs_inconsistent(irg);
254   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
255   set_trouts_inconsistent();
256   set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
257
258   set_optimize(rem);
259 }
260
261 /*
262  * convert simple tail-calls into loops
263  */
264 int opt_tail_rec_irg(ir_graph *irg)
265 {
266   ir_node *end_block;
267   int n_preds;
268   int i, n_tail_calls = 0;
269   ir_node *rets = NULL;
270
271   if (! get_opt_tail_recursion() || ! get_opt_optimize())
272     return 0;
273
274   /*
275    * This tail recursion optimization works best
276    * if the Returns are normalized.
277    */
278   normalize_n_returns(irg);
279
280   end_block = get_irg_end_block(irg);
281   set_irn_link(end_block, NULL);
282
283   n_preds = get_Block_n_cfgpreds(end_block);
284   for (i = 0; i < n_preds; ++i) {
285     ir_node *ret = get_Block_cfgpred(end_block, i);
286     ir_node *call, *call_ptr;
287     entity *ent;
288     int j, n_ress;
289     ir_node **ress;
290
291     /* search all returns of a block */
292     if (get_irn_op(ret) != op_Return)
293       continue;
294
295     /* check, if it's a Return self() */
296     call = skip_Proj(get_Return_mem(ret));
297     if (get_irn_op(call) != op_Call)
298       continue;
299
300     /* check if it's a recursive call */
301     call_ptr = get_Call_ptr(call);
302
303     if (get_irn_op(call_ptr) != op_SymConst)
304       continue;
305
306     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
307       continue;
308
309     ent = get_SymConst_entity(call_ptr);
310     if (!ent || get_entity_irg(ent) != irg)
311       continue;
312
313     /* ok, mem is routed to a recursive call, check return args */
314     n_ress = get_Return_n_ress(ret);
315     ress = get_Return_res_arr(ret);
316
317     for (j = 0; j < n_ress; ++j) {
318       ir_node *irn = skip_Proj(skip_Proj(ress[j]));
319
320       if (irn != call) {
321             /* not routed to a call */
322             break;
323       }
324     }
325     if (j < n_ress)
326       continue;
327
328     /* here, we have found a call */
329     set_irn_link(call, get_irn_link(end_block));
330     set_irn_link(end_block, call);
331     ++n_tail_calls;
332
333     /* link all returns, we will need this */
334     set_irn_link(ret, rets);
335     rets = ret;
336   }
337
338   /* now, end_block->link contains the list of all tail calls */
339   if (! n_tail_calls)
340     return 0;
341
342   if (get_opt_tail_recursion_verbose() && get_firm_verbosity() > 1)
343     printf("  Performing tail recursion for graph %s and %d Calls\n",
344            get_entity_ld_name(get_irg_entity(irg)), n_tail_calls);
345
346   hook_tail_rec(irg, n_tail_calls);
347   do_opt_tail_rec(irg, rets, n_tail_calls);
348
349   return n_tail_calls;
350 }
351
352 /*
353  * optimize tail recursion away
354  */
355 void opt_tail_recursion(void)
356 {
357   int i;
358   int n_opt_applications = 0;
359
360   if (! get_opt_tail_recursion() || ! get_opt_optimize())
361     return;
362
363   for (i = 0; i < get_irp_n_irgs(); i++) {
364     current_ir_graph = get_irp_irg(i);
365
366     if (opt_tail_rec_irg(current_ir_graph))
367       ++n_opt_applications;
368   }
369
370   if (get_opt_tail_recursion_verbose())
371     printf("Performed tail recursion for %d of %d graphs\n", n_opt_applications, get_irp_n_irgs());
372 }