Move includes for alloca() to xmalloc.h, so not everyone and his dog has to use the...
[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_STRING_H
17 #include <string.h>
18 #endif
19
20 #include <assert.h>
21 #include "tailrec.h"
22 #include "array.h"
23 #include "irprog_t.h"
24 #include "irgwalk.h"
25 #include "irgmod.h"
26 #include "irop.h"
27 #include "irnode_t.h"
28 #include "irgraph_t.h"
29 #include "ircons.h"
30 #include "irflag.h"
31 #include "trouts.h"
32 #include "return.h"
33 #include "scalar_replace.h"
34 #include "irouts.h"
35 #include "irhooks.h"
36 #include "xmalloc.h"
37
38 /**
39  * the environment for collecting data
40  */
41 typedef struct _collect_t {
42   ir_node *proj_X;      /**< initial exec proj */
43   ir_node *block;       /**< old first block */
44   int     blk_idx;      /**< cfgpred index of the initial exec in block */
45   ir_node *proj_m;      /**< memory from start proj's */
46   ir_node *proj_data;   /**< linked list of all parameter access proj's */
47 } collect_t;
48
49 /**
50  * walker for collecting data, fills a collect_t environment
51  */
52 static void collect_data(ir_node *node, void *env)
53 {
54   collect_t *data = env;
55   ir_node *pred;
56   ir_op *op;
57
58   switch (get_irn_opcode(node)) {
59   case iro_Proj:
60     pred = get_Proj_pred(node);
61
62     op = get_irn_op(pred);
63     if (op == op_Proj) {
64       ir_node *start = get_Proj_pred(pred);
65
66       if (get_irn_op(start) == op_Start) {
67         if (get_Proj_proj(pred) == pn_Start_T_args) {
68           /* found Proj(ProjT(Start)) */
69           set_irn_link(node, data->proj_data);
70           data->proj_data = node;
71         }
72       }
73     }
74     else if (op == op_Start) {
75       if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
76         /* found ProjX(Start) */
77         data->proj_X = node;
78       }
79     }
80     break;
81   case iro_Block: {
82     int i, n_pred = get_Block_n_cfgpreds(node);
83
84     /*
85      * the first block has the initial exec as cfg predecessor
86      */
87     if (node != get_irg_start_block(current_ir_graph)) {
88       for (i = 0; i < n_pred; ++i) {
89         if (get_Block_cfgpred(node, i) == data->proj_X) {
90           data->block   = node;
91           data->blk_idx = i;
92           break;
93         }
94       }
95     }
96     break;
97   }
98   default:
99     break;
100   }
101 }
102
103 /**
104  * do the graph reconstruction for tail-recursion elimination
105  *
106  * @param irg           the graph that will reconstructed
107  * @param rets          linked list of all rets
108  * @param n_tail_calls  number of tail-recursion calls
109  */
110 static void do_opt_tail_rec(ir_graph *irg, ir_node *rets, int n_tail_calls)
111 {
112   ir_node *end_block = get_irg_end_block(irg);
113   ir_node *block, *jmp, *call, *calls;
114   ir_node **in;
115   ir_node **phis;
116   ir_node ***call_params;
117   ir_node *p, *n;
118   int i, j, n_params;
119   collect_t data;
120   int rem            = get_optimize();
121   ir_entity *ent     = get_irg_entity(irg);
122   ir_type *method_tp = get_entity_type(ent);
123
124   assert(n_tail_calls);
125
126   /* we add new nodes, so the outs are inconsistent */
127   set_irg_outs_inconsistent(irg);
128
129   /* we add new blocks and change the control flow */
130   set_irg_doms_inconsistent(irg);
131   set_irg_extblk_inconsistent(irg);
132
133   /* we add a new loop */
134   set_irg_loopinfo_inconsistent(irg);
135
136   /* calls are removed */
137   set_trouts_inconsistent();
138
139   /* we must build some new nodes WITHOUT CSE */
140   set_optimize(0);
141
142   /* collect needed data */
143   data.proj_X    = NULL;
144   data.block     = NULL;
145   data.blk_idx   = -1;
146   data.proj_m    = get_irg_initial_mem(irg);
147   data.proj_data = NULL;
148   irg_walk_graph(irg, NULL, collect_data, &data);
149
150   /* check number of arguments */
151   call = get_irn_link(end_block);
152   n_params = get_Call_n_params(call);
153
154   assert(data.proj_X && "Could not find initial exec from Start");
155   assert(data.block  && "Could not find first block");
156   assert(data.proj_m && "Could not find initial memory");
157   assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
158
159   /* allocate in's for phi and block construction */
160   NEW_ARR_A(ir_node *, in, n_tail_calls + 1);
161
162   in[0] = data.proj_X;
163
164   /* turn Return's into Jmp's */
165   for (i = 1, p = rets; p; p = n) {
166     ir_node *block = get_nodes_block(p);
167
168     n = get_irn_link(p);
169     in[i++] = new_r_Jmp(irg, block);
170
171     exchange(p, new_r_Bad(irg));
172
173     /* we might generate an endless loop, so add
174      * the block to the keep-alive list */
175     add_End_keepalive(get_irg_end(irg), block);
176   }
177
178   /* create a new block at start */
179   block = new_r_Block(irg, n_tail_calls + 1, in);
180   jmp   = new_r_Jmp(irg, block);
181
182   /* the old first block is now the second one */
183   set_Block_cfgpred(data.block, data.blk_idx, jmp);
184
185   /* allocate phi's, position 0 contains the memory phi */
186   NEW_ARR_A(ir_node *, phis, n_params + 1);
187
188   /* build the memory phi */
189   i = 0;
190   in[i] = new_r_Proj(irg, get_irg_start_block(irg), get_irg_start(irg), mode_M, pn_Start_M);
191   set_irg_initial_mem(irg, in[i]);
192   ++i;
193
194   for (calls = call; calls; calls = get_irn_link(calls)) {
195     in[i] = get_Call_mem(calls);
196     ++i;
197   }
198   assert(i == n_tail_calls + 1);
199
200   phis[0] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode_M);
201
202   /* build the data Phi's */
203   if (n_params > 0) {
204     ir_node *calls;
205     ir_node *args;
206     ir_node *args_bl;
207
208     NEW_ARR_A(ir_node **, call_params, n_tail_calls);
209
210     /* collect all parameters */
211     for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
212       call_params[i] = get_Call_param_arr(calls);
213       ++i;
214     }
215
216     /* build new Proj's and Phi's */
217     args    = get_irg_args(irg);
218     args_bl = get_nodes_block(args);
219     for (i = 0; i < n_params; ++i) {
220       ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
221
222       in[0] = new_r_Proj(irg, args_bl, args, mode, i);
223       for (j = 0; j < n_tail_calls; ++j)
224         in[j + 1] = call_params[j][i];
225
226       phis[i + 1] = new_r_Phi(irg, block, n_tail_calls + 1, in, mode);
227     }
228   }
229
230   /*
231    * ok, we are here, so we have build and collected all needed Phi's
232    * now exchange all Projs into links to Phi
233    */
234   for (p = data.proj_m; p; p = n) {
235     n = get_irn_link(p);
236     exchange(p, phis[0]);
237   }
238   for (p = data.proj_data; p; p = n) {
239     long proj = get_Proj_proj(p);
240
241     assert(0 <= proj && proj < n_params);
242     n = get_irn_link(p);
243     exchange(p, phis[proj + 1]);
244   }
245
246   /* tail recursion was done, all info is invalid */
247   set_irg_doms_inconsistent(irg);
248   set_irg_outs_inconsistent(irg);
249   set_irg_extblk_inconsistent(irg);
250   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
251   set_trouts_inconsistent();
252   set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
253
254   set_optimize(rem);
255 }
256
257 /**
258  * Check the lifetime of locals in the given graph.
259  * Tail recursion can only be done, if we can prove that
260  * the lifetime of locals end with the recursive call.
261  * We do this by checking that no address of a local variable is
262  * stored or transmitted as an argument to a call.
263  *
264  * @return non-zero if it's ok to do tail recursion
265  */
266 static int check_lifetime_of_locals(ir_graph *irg)
267 {
268   ir_node *irg_frame = get_irg_frame(irg);
269   int i;
270
271   if (get_irg_outs_state(irg) != outs_consistent)
272     compute_irg_outs(irg);
273
274   for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
275     ir_node *succ = get_irn_out(irg_frame, i);
276
277     if (is_Sel(succ) && is_address_taken(succ))
278       return 0;
279   }
280   return 1;
281 }
282
283 /*
284  * convert simple tail-calls into loops
285  */
286 int opt_tail_rec_irg(ir_graph *irg)
287 {
288   ir_node *end_block;
289   int i, n_tail_calls = 0;
290   ir_node *rets = NULL;
291   ir_type *mtd_type, *call_type;
292
293   if (! get_opt_tail_recursion() || ! get_opt_optimize())
294     return 0;
295
296   if (! check_lifetime_of_locals(irg))
297     return 0;
298
299   /*
300    * This tail recursion optimization works best
301    * if the Returns are normalized.
302    */
303   normalize_n_returns(irg);
304
305   end_block = get_irg_end_block(irg);
306   set_irn_link(end_block, NULL);
307
308   for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
309     ir_node *ret = get_Block_cfgpred(end_block, i);
310     ir_node *call, *call_ptr;
311     ir_entity *ent;
312     int j;
313     ir_node **ress;
314
315     /* search all Returns of a block */
316     if (! is_Return(ret))
317       continue;
318
319     /* check, if it's a Return self() */
320     call = skip_Proj(get_Return_mem(ret));
321     if (! is_Call(call))
322       continue;
323
324     /* check if it's a recursive call */
325     call_ptr = get_Call_ptr(call);
326
327     if (get_irn_op(call_ptr) != op_SymConst)
328       continue;
329
330     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
331       continue;
332
333     ent = get_SymConst_entity(call_ptr);
334     if (!ent || get_entity_irg(ent) != irg)
335       continue;
336
337     /* ok, mem is routed to a recursive call, check return args */
338     ress = get_Return_res_arr(ret);
339     for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
340       ir_node *irn = skip_Proj(skip_Proj(ress[j]));
341
342       if (irn != call) {
343         /* not routed to a call */
344         break;
345       }
346     }
347     if (j >= 0)
348       continue;
349
350     /*
351      * Check, that the types match. At least in C
352      * this might fail.
353      */
354     mtd_type  = get_entity_type(ent);
355     call_type = get_Call_type(call);
356
357     if (mtd_type != call_type) {
358       /*
359        * Hmm, the types did not match, bad.
360        * This can happen in C when no prototype is given
361        * or K&R style is used.
362        */
363 #if 0
364       printf("Warning: Tail recursion fails because of different method and call types:\n");
365       dump_type(mtd_type);
366       dump_type(call_type);
367 #endif
368       return 0;
369     }
370
371     /* here, we have found a call */
372     set_irn_link(call, get_irn_link(end_block));
373     set_irn_link(end_block, call);
374     ++n_tail_calls;
375
376     /* link all returns, we will need this */
377     set_irn_link(ret, rets);
378     rets = ret;
379   }
380
381   /* now, end_block->link contains the list of all tail calls */
382   if (! n_tail_calls)
383     return 0;
384
385   if (get_opt_tail_recursion_verbose() && get_firm_verbosity() > 1)
386     printf("  Performing tail recursion for graph %s and %d Calls\n",
387        get_entity_ld_name(get_irg_entity(irg)), n_tail_calls);
388
389   hook_tail_rec(irg, n_tail_calls);
390   do_opt_tail_rec(irg, rets, n_tail_calls);
391
392   return n_tail_calls;
393 }
394
395 /*
396  * optimize tail recursion away
397  */
398 void opt_tail_recursion(void)
399 {
400   int i;
401   int n_opt_applications = 0;
402   ir_graph *irg;
403
404   if (! get_opt_tail_recursion() || ! get_opt_optimize())
405     return;
406
407   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
408     irg = get_irp_irg(i);
409
410     if (opt_tail_rec_irg(irg))
411       ++n_opt_applications;
412   }
413
414   if (get_opt_tail_recursion_verbose())
415     printf("Performed tail recursion for %d of %d graphs\n", n_opt_applications, get_irp_n_irgs());
416 }