2 * Copyright (C) 1995-2011 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Tail-recursion call optimization.
24 * @author Michael Beck
33 #include "iroptimize.h"
34 #include "scalar_replace.h"
41 #include "irgraph_t.h"
50 DEBUG_ONLY(static firm_dbg_module_t *dbg);
53 * the environment for collecting data
55 typedef struct collect_t {
56 ir_node *proj_X; /**< initial exec proj */
57 ir_node *block; /**< old first block */
58 int blk_idx; /**< cfgpred index of the initial exec in block */
59 ir_node *proj_m; /**< memory from start proj's */
60 ir_node *proj_data; /**< linked list of all parameter access proj's */
64 * walker for collecting data, fills a collect_t environment
66 static void collect_data(ir_node *node, void *env)
68 collect_t *data = (collect_t*)env;
72 switch (get_irn_opcode(node)) {
74 pred = get_Proj_pred(node);
76 opcode = get_irn_opcode(pred);
77 if (opcode == iro_Proj) {
78 ir_node *start = get_Proj_pred(pred);
80 if (is_Start(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;
87 } else if (opcode == iro_Start) {
88 if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
89 /* found ProjX(Start) */
95 int i, n_pred = get_Block_n_cfgpreds(node);
98 * the first block has the initial exec as cfg predecessor
100 if (node != get_irg_start_block(get_irn_irg(node))) {
101 for (i = 0; i < n_pred; ++i) {
102 if (get_Block_cfgpred(node, i) == data->proj_X) {
116 typedef enum tail_rec_variants {
117 TR_DIRECT, /**< direct return value, i.e. return func(). */
118 TR_ADD, /**< additive return value, i.e. return x +/- func() */
119 TR_MUL, /**< multiplicative return value, i.e. return x * func() or return -func() */
120 TR_BAD, /**< any other transformation */
121 TR_UNKNOWN /**< during construction */
124 typedef struct tr_env {
125 int n_tail_calls; /**< number of tail calls found */
126 int n_ress; /**< number of return values */
127 tail_rec_variants *variants; /**< return value variants */
128 ir_node *rets; /**< list of returns that can be transformed */
133 * do the graph reconstruction for tail-recursion elimination
135 * @param irg the graph that will reconstructed
136 * @param env tail recursion environment
138 static void do_opt_tail_rec(ir_graph *irg, tr_env *env)
140 ir_node *end_block = get_irg_end_block(irg);
141 ir_node *block, *jmp, *call, *calls;
144 ir_node ***call_params;
146 int i, j, n_params, n_locs;
148 int rem = get_optimize();
149 ir_entity *ent = get_irg_entity(irg);
150 ir_type *method_tp = get_entity_type(ent);
152 assert(env->n_tail_calls > 0);
154 /* we add new nodes, so the outs are inconsistent */
155 set_irg_outs_inconsistent(irg);
157 /* we add new blocks and change the control flow */
158 set_irg_doms_inconsistent(irg);
159 set_irg_extblk_inconsistent(irg);
161 /* we add a new loop */
162 set_irg_loopinfo_inconsistent(irg);
164 /* calls are removed */
165 set_trouts_inconsistent();
167 /* we must build some new nodes WITHOUT CSE */
170 /* collect needed data */
174 data.proj_m = get_irg_initial_mem(irg);
175 data.proj_data = NULL;
176 irg_walk_graph(irg, NULL, collect_data, &data);
178 /* check number of arguments */
179 call = (ir_node*)get_irn_link(end_block);
180 n_params = get_Call_n_params(call);
182 assert(data.proj_X && "Could not find initial exec from Start");
183 assert(data.block && "Could not find first block");
184 assert(data.proj_m && "Could not find initial memory");
185 assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
187 /* allocate in's for phi and block construction */
188 NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
190 /* build a new header block for the loop we create */
192 in[i++] = data.proj_X;
194 /* turn Return's into Jmp's */
195 for (p = env->rets; p; p = n) {
196 ir_node *block = get_nodes_block(p);
198 n = (ir_node*)get_irn_link(p);
199 in[i++] = new_r_Jmp(block);
201 // exchange(p, new_r_Bad(irg));
203 /* we might generate an endless loop, so add
204 * the block to the keep-alive list */
205 add_End_keepalive(get_irg_end(irg), block);
207 assert(i == env->n_tail_calls + 1);
210 block = new_r_Block(irg, i, in);
211 jmp = new_r_Jmp(block);
213 /* the old first block is now the second one */
214 set_Block_cfgpred(data.block, data.blk_idx, jmp);
216 /* allocate phi's, position 0 contains the memory phi */
217 NEW_ARR_A(ir_node *, phis, n_params + 1);
219 /* build the memory phi */
221 in[i] = new_r_Proj(get_irg_start(irg), mode_M, pn_Start_M);
222 set_irg_initial_mem(irg, in[i]);
225 for (calls = call; calls != NULL; calls = (ir_node*)get_irn_link(calls)) {
226 in[i] = get_Call_mem(calls);
229 assert(i == env->n_tail_calls + 1);
231 phis[0] = new_r_Phi(block, env->n_tail_calls + 1, in, mode_M);
233 /* build the data Phi's */
239 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
241 /* collect all parameters */
242 for (i = 0, calls = call; calls != NULL;
243 calls = (ir_node*)get_irn_link(calls)) {
244 call_params[i] = get_Call_param_arr(calls);
248 /* build new Proj's and Phi's */
249 args = get_irg_args(irg);
250 args_bl = get_nodes_block(args);
251 for (i = 0; i < n_params; ++i) {
252 ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
254 in[0] = new_r_Proj(args, mode, i);
255 for (j = 0; j < env->n_tail_calls; ++j)
256 in[j + 1] = call_params[j][i];
258 phis[i + 1] = new_r_Phi(block, env->n_tail_calls + 1, in, mode);
263 * ok, we are here, so we have build and collected all needed Phi's
264 * now exchange all Projs into links to Phi
266 exchange(data.proj_m, phis[0]);
267 for (p = data.proj_data; p; p = n) {
268 long proj = get_Proj_proj(p);
270 assert(0 <= proj && proj < n_params);
271 n = (ir_node*)get_irn_link(p);
272 exchange(p, phis[proj + 1]);
275 /* tail recursion was done, all info is invalid */
276 set_irg_doms_inconsistent(irg);
277 set_irg_outs_inconsistent(irg);
278 set_irg_extblk_inconsistent(irg);
279 set_irg_loopinfo_state(irg, loopinfo_cf_inconsistent);
280 set_trouts_inconsistent();
281 set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
285 /* check if we need new values */
287 for (i = 0; i < env->n_ress; ++i) {
288 if (env->variants[i] != TR_DIRECT) {
295 ir_node *start_block;
299 NEW_ARR_A(ir_node *, in, env->n_ress);
300 NEW_ARR_A(ir_mode *, modes, env->n_ress);
301 ssa_cons_start(irg, env->n_ress);
303 start_block = get_irg_start_block(irg);
304 set_r_cur_block(irg, start_block);
306 /* set the neutral elements for the iteration start */
307 for (i = 0; i < env->n_ress; ++i) {
308 ir_type *tp = get_method_res_type(method_tp, i);
309 ir_mode *mode = get_type_mode(tp);
312 if (env->variants[i] == TR_ADD) {
313 set_r_value(irg, i, new_r_Const(irg, get_mode_null(mode)));
314 } else if (env->variants[i] == TR_MUL) {
315 set_r_value(irg, i, new_r_Const(irg, get_mode_one(mode)));
318 mature_immBlock(start_block);
320 /* no: we can kill all returns */
321 for (p = env->rets; p; p = n) {
322 ir_node *block = get_nodes_block(p);
323 ir_node *call, *mem, *jmp, *tuple;
325 set_r_cur_block(irg, block);
326 n = (ir_node*)get_irn_link(p);
328 call = skip_Proj(get_Return_mem(p));
329 assert(is_Call(call));
331 mem = get_Call_mem(call);
333 /* create a new jump, free of CSE */
335 jmp = new_r_Jmp(block);
338 for (i = 0; i < env->n_ress; ++i) {
339 ir_mode *mode = modes[i];
340 if (env->variants[i] != TR_DIRECT) {
341 in[i] = get_r_value(irg, i, mode);
343 in[i] = new_r_Bad(irg, mode);
346 /* create a new tuple for the return values */
347 tuple = new_r_Tuple(block, env->n_ress, in);
349 turn_into_tuple(call, pn_Call_max);
350 set_Tuple_pred(call, pn_Call_M, mem);
351 set_Tuple_pred(call, pn_Call_X_regular, jmp);
352 set_Tuple_pred(call, pn_Call_X_except, new_r_Bad(irg, mode_X));
353 set_Tuple_pred(call, pn_Call_T_result, tuple);
355 for (i = 0; i < env->n_ress; ++i) {
356 ir_node *res = get_Return_res(p, i);
357 if (env->variants[i] != TR_DIRECT) {
358 set_r_value(irg, i, res);
362 exchange(p, new_r_Bad(irg, mode_X));
365 /* finally fix all other returns */
366 end_block = get_irg_end_block(irg);
367 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
368 ir_node *ret = get_Block_cfgpred(end_block, i);
371 /* search all Returns of a block */
372 if (! is_Return(ret))
375 block = get_nodes_block(ret);
376 set_r_cur_block(irg, block);
377 for (j = 0; j < env->n_ress; ++j) {
378 ir_node *pred = get_Return_res(ret, j);
381 switch (env->variants[j]) {
386 n = get_r_value(irg, j, modes[j]);
387 n = new_r_Add(block, n, pred, modes[j]);
388 set_Return_res(ret, j, n);
392 n = get_r_value(irg, j, modes[j]);
393 n = new_r_Mul(block, n, pred, modes[j]);
394 set_Return_res(ret, j, n);
398 assert(!"unexpected tail recursion variant");
402 ssa_cons_finish(irg);
404 ir_node *bad = new_r_Bad(irg, mode_X);
406 /* no: we can kill all returns */
407 for (p = env->rets; p; p = n) {
408 n = (ir_node*)get_irn_link(p);
415 * Check the lifetime of locals in the given graph.
416 * Tail recursion can only be done, if we can prove that
417 * the lifetime of locals end with the recursive call.
418 * We do this by checking that no address of a local variable is
419 * stored or transmitted as an argument to a call.
421 * @return non-zero if it's ok to do tail recursion
423 static int check_lifetime_of_locals(ir_graph *irg)
427 ir_type *frame_tp = get_irg_frame_type(irg);
429 irg_frame = get_irg_frame(irg);
430 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
431 ir_node *succ = get_irn_out(irg_frame, i);
434 /* Check if we have compound arguments.
435 For now, we cannot handle them, */
436 if (get_entity_owner(get_Sel_entity(succ)) != frame_tp)
439 if (is_address_taken(succ))
447 * Examine irn and detect the recursion variant.
449 static tail_rec_variants find_variant(ir_node *irn, ir_node *call)
452 tail_rec_variants va, vb, res;
454 if (skip_Proj(skip_Proj(irn)) == call) {
458 switch (get_irn_opcode(irn)) {
461 a = get_Add_left(irn);
462 if (get_nodes_block(a) != get_nodes_block(call)) {
463 /* we are outside, ignore */
466 va = find_variant(a, call);
470 b = get_Add_right(irn);
471 if (get_nodes_block(b) != get_nodes_block(call)) {
472 /* we are outside, ignore */
475 vb = find_variant(b, call);
482 else if (va == TR_UNKNOWN)
484 else if (vb == TR_UNKNOWN)
487 /* they are different but none is TR_UNKNOWN -> incompatible */
490 if (res == TR_DIRECT || res == TR_ADD)
496 /* try additive, but return value must be left */
497 a = get_Sub_left(irn);
498 if (get_nodes_block(a) != get_nodes_block(call)) {
499 /* we are outside, ignore */
502 va = find_variant(a, call);
506 b = get_Sub_right(irn);
507 if (get_nodes_block(b) != get_nodes_block(call)) {
508 /* we are outside, ignore */
511 vb = find_variant(b, call);
512 if (vb != TR_UNKNOWN)
516 if (res == TR_DIRECT || res == TR_ADD)
522 /* try multiplicative */
523 a = get_Mul_left(irn);
524 if (get_nodes_block(a) != get_nodes_block(call)) {
525 /* we are outside, ignore */
528 va = find_variant(a, call);
532 b = get_Mul_right(irn);
533 if (get_nodes_block(b) != get_nodes_block(call)) {
534 /* we are outside, ignore */
537 vb = find_variant(b, call);
544 else if (va == TR_UNKNOWN)
546 else if (vb == TR_UNKNOWN)
549 /* they are different but none is TR_UNKNOWN -> incompatible */
552 if (res == TR_DIRECT || res == TR_MUL)
558 /* try multiplicative */
559 a = get_Minus_op(irn);
560 res = find_variant(a, call);
561 if (res == TR_DIRECT)
563 if (res == TR_MUL || res == TR_UNKNOWN)
575 * convert simple tail-calls into loops
577 int opt_tail_rec_irg(ir_graph *irg)
581 int i, n_ress, n_tail_calls = 0;
582 ir_node *rets = NULL;
583 ir_type *mtd_type, *call_type;
587 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
589 assure_irg_outs(irg);
591 if (! check_lifetime_of_locals(irg))
594 rem = current_ir_graph;
595 current_ir_graph = irg;
597 ent = get_irg_entity(irg);
598 mtd_type = get_entity_type(ent);
599 n_ress = get_method_n_ress(mtd_type);
605 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
607 for (i = 0; i < n_ress; ++i)
608 env.variants[i] = TR_DIRECT;
612 * This tail recursion optimization works best
613 * if the Returns are normalized.
615 normalize_n_returns(irg);
617 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
619 end_block = get_irg_end_block(irg);
620 set_irn_link(end_block, NULL);
622 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
623 ir_node *ret = get_Block_cfgpred(end_block, i);
624 ir_node *call, *call_ptr;
628 /* search all Returns of a block */
629 if (! is_Return(ret))
632 /* check, if it's a Return self() */
633 call = skip_Proj(get_Return_mem(ret));
637 /* the call must be in the same block as the return */
638 if (get_nodes_block(call) != get_nodes_block(ret))
641 /* check if it's a recursive call */
642 call_ptr = get_Call_ptr(call);
644 if (! is_Global(call_ptr))
647 ent = get_Global_entity(call_ptr);
648 if (!ent || get_entity_irg(ent) != irg)
652 * Check, that the types match. At least in C
655 mtd_type = get_entity_type(ent);
656 call_type = get_Call_type(call);
658 if (mtd_type != call_type) {
660 * Hmm, the types did not match, bad.
661 * This can happen in C when no prototype is given
662 * or K&R style is used.
664 DB((dbg, LEVEL_3, " tail recursion fails because of call type mismatch: %+F != %+F\n", mtd_type, call_type));
668 /* ok, mem is routed to a recursive call, check return args */
669 ress = get_Return_res_arr(ret);
670 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
671 tail_rec_variants var = find_variant(ress[j], call);
674 /* cannot be transformed */
677 if (var == TR_DIRECT)
678 var = env.variants[j];
679 else if (env.variants[j] == TR_DIRECT)
680 env.variants[j] = var;
681 if (env.variants[j] != var) {
683 DB((dbg, LEVEL_3, " tail recursion fails for %d return value of %+F\n", j, ret));
690 /* here, we have found a call */
691 set_irn_link(call, get_irn_link(end_block));
692 set_irn_link(end_block, call);
695 /* link all returns, we will need this */
696 set_irn_link(ret, rets);
700 /* now, end_block->link contains the list of all tail calls */
701 if (n_tail_calls > 0) {
702 DB((dbg, LEVEL_2, " Performing tail recursion for graph %s and %d Calls\n",
703 get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
705 hook_tail_rec(irg, n_tail_calls);
707 env.n_tail_calls = n_tail_calls;
709 do_opt_tail_rec(irg, &env);
711 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
712 current_ir_graph = rem;
716 ir_graph_pass_t *opt_tail_rec_irg_pass(const char *name)
718 return def_graph_pass_ret(name ? name : "tailrec", opt_tail_rec_irg);
722 * optimize tail recursion away
724 void opt_tail_recursion(void)
727 size_t n_opt_applications = 0;
729 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
731 DB((dbg, LEVEL_1, "Performing tail recursion ...\n"));
732 for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
733 ir_graph *irg = get_irp_irg(i);
735 if (opt_tail_rec_irg(irg))
736 ++n_opt_applications;
739 DB((dbg, LEVEL_1, "Done for %zu of %zu graphs.\n",
740 n_opt_applications, get_irp_n_irgs()));
743 ir_prog_pass_t *opt_tail_recursion_pass(const char *name)
745 return def_prog_pass(name ? name : "tailrec", opt_tail_recursion);