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