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
32 #include "iroptimize.h"
33 #include "scalar_replace.h"
40 #include "irgraph_t.h"
48 #include "opt_manage.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 blocks and change the control flow */
155 clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE);
157 /* we must build some new nodes WITHOUT CSE */
160 /* collect needed data */
164 data.proj_m = get_irg_initial_mem(irg);
165 data.proj_data = NULL;
166 irg_walk_graph(irg, NULL, collect_data, &data);
168 /* check number of arguments */
169 call = (ir_node*)get_irn_link(end_block);
170 n_params = get_Call_n_params(call);
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");
177 /* allocate in's for phi and block construction */
178 NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
180 /* build a new header block for the loop we create */
182 in[i++] = data.proj_X;
184 /* turn Return's into Jmp's */
185 for (p = env->rets; p; p = n) {
186 ir_node *block = get_nodes_block(p);
188 n = (ir_node*)get_irn_link(p);
189 in[i++] = new_r_Jmp(block);
191 // exchange(p, new_r_Bad(irg));
193 /* we might generate an endless loop, so add
194 * the block to the keep-alive list */
195 add_End_keepalive(get_irg_end(irg), block);
197 assert(i == env->n_tail_calls + 1);
200 block = new_r_Block(irg, i, in);
201 jmp = new_r_Jmp(block);
203 /* the old first block is now the second one */
204 set_Block_cfgpred(data.block, data.blk_idx, jmp);
206 /* allocate phi's, position 0 contains the memory phi */
207 NEW_ARR_A(ir_node *, phis, n_params + 1);
209 /* build the memory phi */
211 in[i] = new_r_Proj(get_irg_start(irg), mode_M, pn_Start_M);
212 set_irg_initial_mem(irg, in[i]);
215 for (calls = call; calls != NULL; calls = (ir_node*)get_irn_link(calls)) {
216 in[i] = get_Call_mem(calls);
219 assert(i == env->n_tail_calls + 1);
221 phis[0] = new_r_Phi(block, env->n_tail_calls + 1, in, mode_M);
223 /* build the data Phi's */
228 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
230 /* collect all parameters */
231 for (i = 0, calls = call; calls != NULL;
232 calls = (ir_node*)get_irn_link(calls)) {
233 call_params[i] = get_Call_param_arr(calls);
237 /* build new Proj's and Phi's */
238 args = get_irg_args(irg);
239 for (i = 0; i < n_params; ++i) {
240 ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
242 in[0] = new_r_Proj(args, mode, i);
243 for (j = 0; j < env->n_tail_calls; ++j)
244 in[j + 1] = call_params[j][i];
246 phis[i + 1] = new_r_Phi(block, env->n_tail_calls + 1, in, mode);
251 * ok, we are here, so we have build and collected all needed Phi's
252 * now exchange all Projs into links to Phi
254 exchange(data.proj_m, phis[0]);
255 for (p = data.proj_data; p; p = n) {
256 long proj = get_Proj_proj(p);
258 assert(0 <= proj && proj < n_params);
259 n = (ir_node*)get_irn_link(p);
260 exchange(p, phis[proj + 1]);
263 /* tail recursion was done, all info is invalid */
264 clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE
265 | IR_GRAPH_STATE_CONSISTENT_LOOPINFO);
266 set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
270 /* check if we need new values */
272 for (i = 0; i < env->n_ress; ++i) {
273 if (env->variants[i] != TR_DIRECT) {
280 ir_node *start_block;
284 NEW_ARR_A(ir_node *, in, env->n_ress);
285 NEW_ARR_A(ir_mode *, modes, env->n_ress);
286 ssa_cons_start(irg, env->n_ress);
288 start_block = get_irg_start_block(irg);
289 set_r_cur_block(irg, start_block);
291 /* set the neutral elements for the iteration start */
292 for (i = 0; i < env->n_ress; ++i) {
293 ir_type *tp = get_method_res_type(method_tp, i);
294 ir_mode *mode = get_type_mode(tp);
297 if (env->variants[i] == TR_ADD) {
298 set_r_value(irg, i, new_r_Const(irg, get_mode_null(mode)));
299 } else if (env->variants[i] == TR_MUL) {
300 set_r_value(irg, i, new_r_Const(irg, get_mode_one(mode)));
303 mature_immBlock(start_block);
305 /* no: we can kill all returns */
306 for (p = env->rets; p; p = n) {
307 ir_node *block = get_nodes_block(p);
308 ir_node *call, *mem, *jmp, *tuple;
310 set_r_cur_block(irg, block);
311 n = (ir_node*)get_irn_link(p);
313 call = skip_Proj(get_Return_mem(p));
314 assert(is_Call(call));
316 mem = get_Call_mem(call);
318 /* create a new jump, free of CSE */
320 jmp = new_r_Jmp(block);
323 for (i = 0; i < env->n_ress; ++i) {
324 ir_mode *mode = modes[i];
325 if (env->variants[i] != TR_DIRECT) {
326 in[i] = get_r_value(irg, i, mode);
328 in[i] = new_r_Bad(irg, mode);
331 /* create a new tuple for the return values */
332 tuple = new_r_Tuple(block, env->n_ress, in);
334 turn_into_tuple(call, pn_Call_max+1);
335 set_Tuple_pred(call, pn_Call_M, mem);
336 set_Tuple_pred(call, pn_Call_X_regular, jmp);
337 set_Tuple_pred(call, pn_Call_X_except, new_r_Bad(irg, mode_X));
338 set_Tuple_pred(call, pn_Call_T_result, tuple);
340 for (i = 0; i < env->n_ress; ++i) {
341 ir_node *res = get_Return_res(p, i);
342 if (env->variants[i] != TR_DIRECT) {
343 set_r_value(irg, i, res);
347 exchange(p, new_r_Bad(irg, mode_X));
350 /* finally fix all other returns */
351 end_block = get_irg_end_block(irg);
352 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
353 ir_node *ret = get_Block_cfgpred(end_block, i);
356 /* search all Returns of a block */
357 if (! is_Return(ret))
360 block = get_nodes_block(ret);
361 set_r_cur_block(irg, block);
362 for (j = 0; j < env->n_ress; ++j) {
363 ir_node *pred = get_Return_res(ret, j);
366 switch (env->variants[j]) {
371 n = get_r_value(irg, j, modes[j]);
372 n = new_r_Add(block, n, pred, modes[j]);
373 set_Return_res(ret, j, n);
377 n = get_r_value(irg, j, modes[j]);
378 n = new_r_Mul(block, n, pred, modes[j]);
379 set_Return_res(ret, j, n);
383 assert(!"unexpected tail recursion variant");
387 ssa_cons_finish(irg);
389 ir_node *bad = new_r_Bad(irg, mode_X);
391 /* no: we can kill all returns */
392 for (p = env->rets; p; p = n) {
393 n = (ir_node*)get_irn_link(p);
400 * Check the lifetime of locals in the given graph.
401 * Tail recursion can only be done, if we can prove that
402 * the lifetime of locals end with the recursive call.
403 * We do this by checking that no address of a local variable is
404 * stored or transmitted as an argument to a call.
406 * @return non-zero if it's ok to do tail recursion
408 static int check_lifetime_of_locals(ir_graph *irg)
412 ir_type *frame_tp = get_irg_frame_type(irg);
414 irg_frame = get_irg_frame(irg);
415 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
416 ir_node *succ = get_irn_out(irg_frame, i);
419 /* Check if we have compound arguments.
420 For now, we cannot handle them, */
421 if (get_entity_owner(get_Sel_entity(succ)) != frame_tp)
424 if (is_address_taken(succ))
432 * Examine irn and detect the recursion variant.
434 static tail_rec_variants find_variant(ir_node *irn, ir_node *call)
437 tail_rec_variants va, vb, res;
439 if (skip_Proj(skip_Proj(irn)) == call) {
443 switch (get_irn_opcode(irn)) {
446 a = get_Add_left(irn);
447 if (get_nodes_block(a) != get_nodes_block(call)) {
448 /* we are outside, ignore */
451 va = find_variant(a, call);
455 b = get_Add_right(irn);
456 if (get_nodes_block(b) != get_nodes_block(call)) {
457 /* we are outside, ignore */
460 vb = find_variant(b, call);
467 else if (va == TR_UNKNOWN)
469 else if (vb == TR_UNKNOWN)
472 /* they are different but none is TR_UNKNOWN -> incompatible */
475 if (res == TR_DIRECT || res == TR_ADD)
481 /* try additive, but return value must be left */
482 a = get_Sub_left(irn);
483 if (get_nodes_block(a) != get_nodes_block(call)) {
484 /* we are outside, ignore */
487 va = find_variant(a, call);
491 b = get_Sub_right(irn);
492 if (get_nodes_block(b) != get_nodes_block(call)) {
493 /* we are outside, ignore */
496 vb = find_variant(b, call);
497 if (vb != TR_UNKNOWN)
501 if (res == TR_DIRECT || res == TR_ADD)
507 /* try multiplicative */
508 a = get_Mul_left(irn);
509 if (get_nodes_block(a) != get_nodes_block(call)) {
510 /* we are outside, ignore */
513 va = find_variant(a, call);
517 b = get_Mul_right(irn);
518 if (get_nodes_block(b) != get_nodes_block(call)) {
519 /* we are outside, ignore */
522 vb = find_variant(b, call);
529 else if (va == TR_UNKNOWN)
531 else if (vb == TR_UNKNOWN)
534 /* they are different but none is TR_UNKNOWN -> incompatible */
537 if (res == TR_DIRECT || res == TR_MUL)
543 /* try multiplicative */
544 a = get_Minus_op(irn);
545 res = find_variant(a, call);
546 if (res == TR_DIRECT)
548 if (res == TR_MUL || res == TR_UNKNOWN)
560 * convert simple tail-calls into loops
562 static ir_graph_state_t do_tailrec(ir_graph *irg)
566 int i, n_ress, n_tail_calls = 0;
567 ir_node *rets = NULL;
568 ir_type *mtd_type, *call_type;
572 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
574 if (! check_lifetime_of_locals(irg))
577 rem = current_ir_graph;
578 current_ir_graph = irg;
580 ent = get_irg_entity(irg);
581 mtd_type = get_entity_type(ent);
582 n_ress = get_method_n_ress(mtd_type);
588 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
590 for (i = 0; i < n_ress; ++i)
591 env.variants[i] = TR_DIRECT;
594 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
596 end_block = get_irg_end_block(irg);
597 set_irn_link(end_block, NULL);
599 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
600 ir_node *ret = get_Block_cfgpred(end_block, i);
601 ir_node *call, *call_ptr;
605 /* search all Returns of a block */
606 if (! is_Return(ret))
609 /* check, if it's a Return self() */
610 call = skip_Proj(get_Return_mem(ret));
614 /* the call must be in the same block as the return */
615 if (get_nodes_block(call) != get_nodes_block(ret))
618 /* check if it's a recursive call */
619 call_ptr = get_Call_ptr(call);
621 if (! is_SymConst_addr_ent(call_ptr))
624 ent = get_SymConst_entity(call_ptr);
625 if (!ent || get_entity_irg(ent) != irg)
629 * Check, that the types match. At least in C
632 mtd_type = get_entity_type(ent);
633 call_type = get_Call_type(call);
635 if (mtd_type != call_type) {
637 * Hmm, the types did not match, bad.
638 * This can happen in C when no prototype is given
639 * or K&R style is used.
641 DB((dbg, LEVEL_3, " tail recursion fails because of call type mismatch: %+F != %+F\n", mtd_type, call_type));
645 /* ok, mem is routed to a recursive call, check return args */
646 ress = get_Return_res_arr(ret);
647 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
648 tail_rec_variants var = find_variant(ress[j], call);
651 /* cannot be transformed */
654 if (var == TR_DIRECT)
655 var = env.variants[j];
656 else if (env.variants[j] == TR_DIRECT)
657 env.variants[j] = var;
658 if (env.variants[j] != var) {
660 DB((dbg, LEVEL_3, " tail recursion fails for %d return value of %+F\n", j, ret));
667 /* here, we have found a call */
668 set_irn_link(call, get_irn_link(end_block));
669 set_irn_link(end_block, call);
672 /* link all returns, we will need this */
673 set_irn_link(ret, rets);
677 /* now, end_block->link contains the list of all tail calls */
678 if (n_tail_calls > 0) {
679 DB((dbg, LEVEL_2, " Performing tail recursion for graph %s and %d Calls\n",
680 get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
682 hook_tail_rec(irg, n_tail_calls);
684 env.n_tail_calls = n_tail_calls;
686 do_opt_tail_rec(irg, &env);
688 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
689 current_ir_graph = rem;
695 * This tail recursion optimization works best
696 * if the Returns are normalized.
698 static optdesc_t opt_tailrec = {
700 IR_GRAPH_STATE_MANY_RETURNS | IR_GRAPH_STATE_NO_BADS | IR_GRAPH_STATE_CONSISTENT_OUTS,
704 int opt_tail_rec_irg(ir_graph *irg) {
705 perform_irg_optimization(irg, &opt_tailrec);
706 return 1; /* conservatively report changes */
709 ir_graph_pass_t *opt_tail_rec_irg_pass(const char *name)
711 return def_graph_pass_ret(name ? name : "tailrec", opt_tail_rec_irg);
715 * optimize tail recursion away
717 void opt_tail_recursion(void)
720 size_t n_opt_applications = 0;
722 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
724 DB((dbg, LEVEL_1, "Performing tail recursion ...\n"));
725 for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
726 ir_graph *irg = get_irp_irg(i);
728 if (opt_tail_rec_irg(irg))
729 ++n_opt_applications;
732 DB((dbg, LEVEL_1, "Done for %zu of %zu graphs.\n",
733 n_opt_applications, get_irp_n_irgs()));
736 ir_prog_pass_t *opt_tail_recursion_pass(const char *name)
738 return def_prog_pass(name ? name : "tailrec", opt_tail_recursion);