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