added missing include
[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
40 /**
41  * the environment for collecting data
42  */
43 typedef struct _collect_t {
44   ir_node *proj_X;      /**< initial exec proj */
45   ir_node *block;       /**< old first block */
46   int     blk_idx;      /**< cfgpred index of the initial exec in block */
47   ir_node *proj_m;      /**< linked list of memory from start proj's */
48   ir_node *proj_data;   /**< linked list of all parameter access proj's */
49 } collect_t;
50
51 /**
52  * walker for collecting data, fills a collect_t environment
53  */
54 static void collect_data(ir_node *node, void *env)
55 {
56   collect_t *data = env;
57   ir_node *pred;
58   ir_op *op;
59
60   switch (get_irn_opcode(node)) {
61   case iro_Proj:
62     pred = get_Proj_pred(node);
63
64     op = get_irn_op(pred);
65     if (op == op_Proj) {
66       ir_node *start = get_Proj_pred(pred);
67
68       if (get_irn_op(start) == op_Start) {
69             if (get_Proj_proj(pred) == pn_Start_T_args) {
70               /* found Proj(ProjT(Start)) */
71               set_irn_link(node, data->proj_data);
72               data->proj_data = node;
73             }
74       }
75     }
76     else if (op == op_Start) {
77       switch (get_Proj_proj(node)) {
78         case pn_Start_M:
79           /* found ProjM(Start) */
80               set_irn_link(node, data->proj_m);
81               data->proj_m = node;
82               break;
83             case pn_Start_X_initial_exec:
84               /* found ProjX(Start) */
85               data->proj_X = node;
86               break;
87             default:
88               break;
89       }
90     }
91     break;
92   case iro_Block: {
93     int i, n_pred = get_Block_n_cfgpreds(node);
94
95     /*
96      * the first block has the initial exec as cfg predecessor
97      */
98     if (node != current_ir_graph->start_block) {
99       for (i = 0; i < n_pred; ++i) {
100             if (get_Block_cfgpred(node, i) == data->proj_X) {
101               data->block   = node;
102               data->blk_idx = i;
103               break;
104             }
105       }
106     }
107     break;
108   }
109   default:
110     break;
111   }
112 }
113
114 /**
115  * do the graph reconstruction for tail-recursion elimination
116  *
117  * @param irg           the graph that will reconstructed
118  * @param rets          linked list of all rets
119  * @param n_tail_calls  number of tail-recursion calls
120  */
121 static void do_opt_tail_rec(ir_graph *irg, ir_node *rets, int n_tail_calls)
122 {
123   ir_graph *rem_irg = current_ir_graph;
124   ir_node *end_block = irg->end_block;
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
134   assert(n_tail_calls);
135
136   /* we add nwe nodes, so the outs are inconsistant */
137   set_irg_outs_inconsistent(irg);
138
139   /* we add new blocks and change the control flow */
140   set_irg_dom_inconsistent(irg);
141
142   /* we add a new loop */
143   set_irg_loopinfo_inconsistent(irg);
144
145   set_optimize(0);
146
147   /* collect needed data */
148   data.proj_X    = NULL;
149   data.block     = NULL;
150   data.blk_idx   = -1;
151   data.proj_m    = NULL;
152   data.proj_data = NULL;
153   irg_walk_graph(irg, NULL, collect_data, &data);
154
155   /* check number of arguments */
156   call = get_irn_link(end_block);
157   n_params = get_Call_n_params(call);
158
159   assert(data.proj_X && "Could not find initial exec from Start");
160   assert(data.block  && "Could not find first block");
161   assert(data.proj_m && "Could not find ProjM(Start)");
162   assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
163
164   current_ir_graph = irg;
165
166   /* allocate in's for phi and block construction */
167   NEW_ARR_A(ir_node *, in, n_tail_calls + 1);
168
169   in[0] = data.proj_X;
170
171   /* turn Return's into Jmp's */
172   for (i = 1, p = rets; p; p = get_irn_link(p)) {
173     ir_node *jmp;
174
175     set_cur_block(get_nodes_block(p));
176     jmp = new_Jmp();
177
178     exchange(p, new_Bad());
179     in[i++] = jmp;
180
181     add_End_keepalive(get_irg_end(irg), jmp);
182   }
183
184   /* create a new block at start */
185   block = new_Block(n_tail_calls + 1, in);
186   jmp   = new_Jmp();
187
188   /* the old first block is now the second one */
189   set_Block_cfgpred(data.block, data.blk_idx, jmp);
190
191   /* allocate phi's, position 0 contains the memory phi */
192   NEW_ARR_A(ir_node *, phis, n_params + 1);
193
194   /* build the memory phi */
195   i = 0;
196   in[i] = new_rd_Proj(NULL, irg, irg->start_block, irg->start, mode_M, pn_Start_M);
197   ++i;
198
199   for (calls = call; calls; calls = get_irn_link(calls)) {
200     in[i] = get_Call_mem(calls);
201     ++i;
202   }
203   assert(i == n_tail_calls + 1);
204
205   phis[0] = new_rd_Phi(NULL, irg, block, n_tail_calls + 1, in, mode_M);
206
207   /* build the data phi's */
208   if (n_params > 0) {
209     ir_node *calls;
210
211     NEW_ARR_A(ir_node **, call_params, n_params);
212
213     /* collect all parameters */
214     for (i = 0, calls = call; calls; calls = get_irn_link(calls)) {
215       call_params[i] = get_Call_param_arr(calls);
216       ++i;
217     }
218
219     /* build new projs and Phi's */
220     for (i = 0; i < n_params; ++i) {
221       ir_mode *mode = get_irn_mode(call_params[0][i]);
222
223       in[0] = new_rd_Proj(NULL, irg, block, irg->args, mode, i);
224       for (j = 0; j < n_tail_calls; ++j)
225         in[j + 1] = call_params[j][i];
226
227       phis[i + 1] = new_rd_Phi(NULL, irg, block, n_tail_calls + 1, in, mode);
228     }
229   }
230
231   /*
232    * ok, we are here, so we have build and collected all needed Phi's
233    * now exchange all Projs into links to Phi
234    */
235   for (p = data.proj_m; p; p = get_irn_link(p)) {
236     exchange(p, phis[0]);
237   }
238   for (p = data.proj_data; p; p = get_irn_link(p)) {
239     long proj = get_Proj_proj(p);
240
241     assert(0 <= proj && proj < n_params);
242     exchange(p, phis[proj + 1]);
243   }
244
245   /* tail recursion was done, all info is invalid */
246   set_irg_dom_inconsistent(irg);
247   set_irg_outs_inconsistent(irg);
248   set_irg_loopinfo_state(current_ir_graph, loopinfo_cf_inconsistent);
249   set_trouts_inconsistent();
250   set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
251
252   current_ir_graph = rem_irg;
253   set_optimize(rem);
254 }
255
256 /*
257  * convert simple tail-calls into loops
258  */
259 int opt_tail_rec_irg(ir_graph *irg)
260 {
261   ir_node *end_block = irg->end_block;
262   int n_preds;
263   int i, n_tail_calls = 0;
264   ir_node *rets = NULL;
265
266   if (! get_opt_tail_recursion() || ! get_opt_optimize())
267     return 0;
268
269   /*
270    * This tail recursion optimization works best
271    * if the Returns are normalized.
272    */
273   normalize_n_returns(irg);
274
275   set_irn_link(end_block, NULL);
276
277   n_preds = get_Block_n_cfgpreds(end_block);
278   for (i = 0; i < n_preds; ++i) {
279     ir_node *ret = get_Block_cfgpred(end_block, i);
280     ir_node *call, *call_ptr;
281     entity *ent;
282     int j, n_ress;
283     ir_node **ress;
284
285     /* search all returns of a block */
286     if (get_irn_op(ret) != op_Return)
287       continue;
288
289     /* check, if it's a Return self() */
290     call = skip_Proj(get_Return_mem(ret));
291     if (get_irn_op(call) != op_Call)
292       continue;
293
294     /* check if it's a recursive call */
295     call_ptr = get_Call_ptr(call);
296
297     if (get_irn_op(call_ptr) != op_SymConst)
298       continue;
299
300     if (get_SymConst_kind(call_ptr) != symconst_addr_ent)
301       continue;
302
303     ent = get_SymConst_entity(call_ptr);
304     if (!ent || get_entity_irg(ent) != irg)
305       continue;
306
307     /* ok, mem is routed to a recursive call, check return args */
308     n_ress = get_Return_n_ress(ret);
309     ress = get_Return_res_arr(ret);
310
311     for (j = 0; j < n_ress; ++j) {
312       ir_node *irn = skip_Proj(skip_Proj(ress[j]));
313
314       if (irn != call) {
315             /* not routed to a call */
316             break;
317       }
318     }
319     if (j < n_ress)
320       continue;
321
322     /* here, we have found a call */
323     set_irn_link(call, get_irn_link(end_block));
324     set_irn_link(end_block, call);
325     ++n_tail_calls;
326
327     /* link all returns, we will need this */
328     set_irn_link(ret, rets);
329     rets = ret;
330   }
331
332   /* now, end_block->link contains the list of all tail calls */
333   if (! n_tail_calls)
334     return 0;
335
336   if (get_opt_tail_recursion_verbose() && get_firm_verbosity() > 1)
337     printf("  Performing tail recursion for graph %s and %d Calls\n",
338            get_entity_ld_name(get_irg_entity(irg)), n_tail_calls);
339
340   do_opt_tail_rec(irg, rets, n_tail_calls);
341
342   return n_tail_calls;
343 }
344
345 /*
346  * optimize tail recursion away
347  */
348 void opt_tail_recursion(void)
349 {
350   int i;
351   int n_opt_applications = 0;
352
353   if (! get_opt_tail_recursion() || ! get_opt_optimize())
354     return;
355
356   for (i = 0; i < get_irp_n_irgs(); i++) {
357     current_ir_graph = get_irp_irg(i);
358
359     if (opt_tail_rec_irg(current_ir_graph))
360       ++n_opt_applications;
361   }
362
363   if (get_opt_tail_recursion_verbose())
364     printf("Performed tail recursion for %d of %d graphs\n", n_opt_applications, get_irp_n_irgs());
365 }