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"
49 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
52 * the environment for collecting data
54 typedef struct collect_t {
55 ir_node *proj_X; /**< initial exec proj */
56 ir_node *block; /**< old first block */
57 int blk_idx; /**< cfgpred index of the initial exec in block */
58 ir_node *proj_m; /**< memory from start proj's */
59 ir_node *proj_data; /**< linked list of all parameter access proj's */
63 * walker for collecting data, fills a collect_t environment
65 static void collect_data(ir_node *node, void *env)
67 collect_t *data = (collect_t*)env;
71 switch (get_irn_opcode(node)) {
73 pred = get_Proj_pred(node);
75 opcode = (ir_opcode)get_irn_opcode(pred);
76 if (opcode == iro_Proj) {
77 ir_node *start = get_Proj_pred(pred);
79 if (is_Start(start)) {
80 if (get_Proj_proj(pred) == pn_Start_T_args) {
81 /* found Proj(ProjT(Start)) */
82 set_irn_link(node, data->proj_data);
83 data->proj_data = node;
86 } else if (opcode == iro_Start) {
87 if (get_Proj_proj(node) == pn_Start_X_initial_exec) {
88 /* found ProjX(Start) */
94 int i, n_pred = get_Block_n_cfgpreds(node);
97 * the first block has the initial exec as cfg predecessor
99 if (node != get_irg_start_block(get_irn_irg(node))) {
100 for (i = 0; i < n_pred; ++i) {
101 if (get_Block_cfgpred(node, i) == data->proj_X) {
115 typedef enum tail_rec_variants {
116 TR_DIRECT, /**< direct return value, i.e. return func(). */
117 TR_ADD, /**< additive return value, i.e. return x +/- func() */
118 TR_MUL, /**< multiplicative return value, i.e. return x * func() or return -func() */
119 TR_BAD, /**< any other transformation */
120 TR_UNKNOWN /**< during construction */
123 typedef struct tr_env {
124 int n_tail_calls; /**< number of tail calls found */
125 int n_ress; /**< number of return values */
126 tail_rec_variants *variants; /**< return value variants */
127 ir_node *rets; /**< list of returns that can be transformed */
132 * do the graph reconstruction for tail-recursion elimination
134 * @param irg the graph that will reconstructed
135 * @param env tail recursion environment
137 static void do_opt_tail_rec(ir_graph *irg, tr_env *env)
139 ir_node *end_block = get_irg_end_block(irg);
140 ir_node *block, *jmp, *call, *calls;
143 ir_node ***call_params;
145 int i, j, n_params, n_locs;
147 int rem = get_optimize();
148 ir_entity *ent = get_irg_entity(irg);
149 ir_type *method_tp = get_entity_type(ent);
151 assert(env->n_tail_calls > 0);
153 /* we add new blocks and change the control flow */
154 clear_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE);
156 /* we must build some new nodes WITHOUT CSE */
159 /* collect needed data */
163 data.proj_m = get_irg_initial_mem(irg);
164 data.proj_data = NULL;
165 irg_walk_graph(irg, NULL, collect_data, &data);
167 /* check number of arguments */
168 call = (ir_node*)get_irn_link(end_block);
169 n_params = get_Call_n_params(call);
171 assert(data.proj_X && "Could not find initial exec from Start");
172 assert(data.block && "Could not find first block");
173 assert(data.proj_m && "Could not find initial memory");
174 assert((data.proj_data || n_params == 0) && "Could not find Proj(ProjT(Start)) of non-void function");
176 /* allocate in's for phi and block construction */
177 NEW_ARR_A(ir_node *, in, env->n_tail_calls + 1);
179 /* build a new header block for the loop we create */
181 in[i++] = data.proj_X;
183 /* turn Return's into Jmp's */
184 for (p = env->rets; p; p = n) {
185 ir_node *block = get_nodes_block(p);
187 n = (ir_node*)get_irn_link(p);
188 in[i++] = new_r_Jmp(block);
190 // exchange(p, new_r_Bad(irg));
192 /* we might generate an endless loop, so add
193 * the block to the keep-alive list */
194 add_End_keepalive(get_irg_end(irg), block);
196 assert(i == env->n_tail_calls + 1);
199 block = new_r_Block(irg, i, in);
200 jmp = new_r_Jmp(block);
202 /* the old first block is now the second one */
203 set_Block_cfgpred(data.block, data.blk_idx, jmp);
205 /* allocate phi's, position 0 contains the memory phi */
206 NEW_ARR_A(ir_node *, phis, n_params + 1);
208 /* build the memory phi */
210 in[i] = new_r_Proj(get_irg_start(irg), mode_M, pn_Start_M);
211 set_irg_initial_mem(irg, in[i]);
214 for (calls = call; calls != NULL; calls = (ir_node*)get_irn_link(calls)) {
215 in[i] = get_Call_mem(calls);
218 assert(i == env->n_tail_calls + 1);
220 phis[0] = new_r_Phi(block, env->n_tail_calls + 1, in, mode_M);
222 /* build the data Phi's */
227 NEW_ARR_A(ir_node **, call_params, env->n_tail_calls);
229 /* collect all parameters */
230 for (i = 0, calls = call; calls != NULL;
231 calls = (ir_node*)get_irn_link(calls)) {
232 call_params[i] = get_Call_param_arr(calls);
236 /* build new Proj's and Phi's */
237 args = get_irg_args(irg);
238 for (i = 0; i < n_params; ++i) {
239 ir_mode *mode = get_type_mode(get_method_param_type(method_tp, i));
241 in[0] = new_r_Proj(args, mode, i);
242 for (j = 0; j < env->n_tail_calls; ++j)
243 in[j + 1] = call_params[j][i];
245 phis[i + 1] = new_r_Phi(block, env->n_tail_calls + 1, in, mode);
250 * ok, we are here, so we have build and collected all needed Phi's
251 * now exchange all Projs into links to Phi
253 exchange(data.proj_m, phis[0]);
254 for (p = data.proj_data; p; p = n) {
255 long proj = get_Proj_proj(p);
257 assert(0 <= proj && proj < n_params);
258 n = (ir_node*)get_irn_link(p);
259 exchange(p, phis[proj + 1]);
262 /* tail recursion was done, all info is invalid */
263 clear_irg_properties(irg, IR_GRAPH_PROPERTY_CONSISTENT_DOMINANCE
264 | IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
265 set_irg_callee_info_state(irg, irg_callee_info_inconsistent);
269 /* check if we need new values */
271 for (i = 0; i < env->n_ress; ++i) {
272 if (env->variants[i] != TR_DIRECT) {
279 ir_node *start_block;
283 NEW_ARR_A(ir_node *, in, env->n_ress);
284 NEW_ARR_A(ir_mode *, modes, env->n_ress);
285 ssa_cons_start(irg, env->n_ress);
287 start_block = get_irg_start_block(irg);
288 set_r_cur_block(irg, start_block);
290 /* set the neutral elements for the iteration start */
291 for (i = 0; i < env->n_ress; ++i) {
292 ir_type *tp = get_method_res_type(method_tp, i);
293 ir_mode *mode = get_type_mode(tp);
296 if (env->variants[i] == TR_ADD) {
297 set_r_value(irg, i, new_r_Const(irg, get_mode_null(mode)));
298 } else if (env->variants[i] == TR_MUL) {
299 set_r_value(irg, i, new_r_Const(irg, get_mode_one(mode)));
302 mature_immBlock(start_block);
304 /* no: we can kill all returns */
305 for (p = env->rets; p; p = n) {
306 ir_node *block = get_nodes_block(p);
307 ir_node *call, *mem, *jmp, *tuple;
309 set_r_cur_block(irg, block);
310 n = (ir_node*)get_irn_link(p);
312 call = skip_Proj(get_Return_mem(p));
313 assert(is_Call(call));
315 mem = get_Call_mem(call);
317 /* create a new jump, free of CSE */
319 jmp = new_r_Jmp(block);
322 for (i = 0; i < env->n_ress; ++i) {
323 ir_mode *mode = modes[i];
324 if (env->variants[i] != TR_DIRECT) {
325 in[i] = get_r_value(irg, i, mode);
327 in[i] = new_r_Bad(irg, mode);
330 /* create a new tuple for the return values */
331 tuple = new_r_Tuple(block, env->n_ress, in);
333 turn_into_tuple(call, pn_Call_max+1);
334 set_Tuple_pred(call, pn_Call_M, mem);
335 set_Tuple_pred(call, pn_Call_X_regular, jmp);
336 set_Tuple_pred(call, pn_Call_X_except, new_r_Bad(irg, mode_X));
337 set_Tuple_pred(call, pn_Call_T_result, tuple);
339 for (i = 0; i < env->n_ress; ++i) {
340 ir_node *res = get_Return_res(p, i);
341 if (env->variants[i] != TR_DIRECT) {
342 set_r_value(irg, i, res);
346 exchange(p, new_r_Bad(irg, mode_X));
349 /* finally fix all other returns */
350 end_block = get_irg_end_block(irg);
351 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
352 ir_node *ret = get_Block_cfgpred(end_block, i);
355 /* search all Returns of a block */
356 if (! is_Return(ret))
359 block = get_nodes_block(ret);
360 set_r_cur_block(irg, block);
361 for (j = 0; j < env->n_ress; ++j) {
362 ir_node *pred = get_Return_res(ret, j);
365 switch (env->variants[j]) {
370 n = get_r_value(irg, j, modes[j]);
371 n = new_r_Add(block, n, pred, modes[j]);
372 set_Return_res(ret, j, n);
376 n = get_r_value(irg, j, modes[j]);
377 n = new_r_Mul(block, n, pred, modes[j]);
378 set_Return_res(ret, j, n);
382 assert(!"unexpected tail recursion variant");
386 ssa_cons_finish(irg);
388 ir_node *bad = new_r_Bad(irg, mode_X);
390 /* no: we can kill all returns */
391 for (p = env->rets; p; p = n) {
392 n = (ir_node*)get_irn_link(p);
399 * Check the lifetime of locals in the given graph.
400 * Tail recursion can only be done, if we can prove that
401 * the lifetime of locals end with the recursive call.
402 * We do this by checking that no address of a local variable is
403 * stored or transmitted as an argument to a call.
405 * @return non-zero if it's ok to do tail recursion
407 static int check_lifetime_of_locals(ir_graph *irg)
411 ir_type *frame_tp = get_irg_frame_type(irg);
413 irg_frame = get_irg_frame(irg);
414 for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
415 ir_node *succ = get_irn_out(irg_frame, i);
418 /* Check if we have compound arguments.
419 For now, we cannot handle them, */
420 if (get_entity_owner(get_Sel_entity(succ)) != frame_tp)
423 if (is_address_taken(succ))
431 * Examine irn and detect the recursion variant.
433 static tail_rec_variants find_variant(ir_node *irn, ir_node *call)
436 tail_rec_variants va, vb, res;
438 if (skip_Proj(skip_Proj(irn)) == call) {
442 switch (get_irn_opcode(irn)) {
445 a = get_Add_left(irn);
446 if (get_nodes_block(a) != get_nodes_block(call)) {
447 /* we are outside, ignore */
450 va = find_variant(a, call);
454 b = get_Add_right(irn);
455 if (get_nodes_block(b) != get_nodes_block(call)) {
456 /* we are outside, ignore */
459 vb = find_variant(b, call);
466 else if (va == TR_UNKNOWN)
468 else if (vb == TR_UNKNOWN)
471 /* they are different but none is TR_UNKNOWN -> incompatible */
474 if (res == TR_DIRECT || res == TR_ADD)
480 /* try additive, but return value must be left */
481 a = get_Sub_left(irn);
482 if (get_nodes_block(a) != get_nodes_block(call)) {
483 /* we are outside, ignore */
486 va = find_variant(a, call);
490 b = get_Sub_right(irn);
491 if (get_nodes_block(b) != get_nodes_block(call)) {
492 /* we are outside, ignore */
495 vb = find_variant(b, call);
496 if (vb != TR_UNKNOWN)
500 if (res == TR_DIRECT || res == TR_ADD)
506 /* try multiplicative */
507 a = get_Mul_left(irn);
508 if (get_nodes_block(a) != get_nodes_block(call)) {
509 /* we are outside, ignore */
512 va = find_variant(a, call);
516 b = get_Mul_right(irn);
517 if (get_nodes_block(b) != get_nodes_block(call)) {
518 /* we are outside, ignore */
521 vb = find_variant(b, call);
528 else if (va == TR_UNKNOWN)
530 else if (vb == TR_UNKNOWN)
533 /* they are different but none is TR_UNKNOWN -> incompatible */
536 if (res == TR_DIRECT || res == TR_MUL)
542 /* try multiplicative */
543 a = get_Minus_op(irn);
544 res = find_variant(a, call);
545 if (res == TR_DIRECT)
547 if (res == TR_MUL || res == TR_UNKNOWN)
559 * convert simple tail-calls into loops
561 void opt_tail_rec_irg(ir_graph *irg)
565 int i, n_ress, n_tail_calls = 0;
566 ir_node *rets = NULL;
567 ir_type *mtd_type, *call_type;
571 assure_irg_properties(irg,
572 IR_GRAPH_PROPERTY_MANY_RETURNS
573 | IR_GRAPH_PROPERTY_NO_BADS
574 | IR_GRAPH_PROPERTY_CONSISTENT_OUTS);
576 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
578 if (! check_lifetime_of_locals(irg)) {
579 confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_ALL);
583 rem = current_ir_graph;
584 current_ir_graph = irg;
586 ent = get_irg_entity(irg);
587 mtd_type = get_entity_type(ent);
588 n_ress = get_method_n_ress(mtd_type);
594 NEW_ARR_A(tail_rec_variants, env.variants, n_ress);
596 for (i = 0; i < n_ress; ++i)
597 env.variants[i] = TR_DIRECT;
600 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
602 end_block = get_irg_end_block(irg);
603 set_irn_link(end_block, NULL);
605 for (i = get_Block_n_cfgpreds(end_block) - 1; i >= 0; --i) {
606 ir_node *ret = get_Block_cfgpred(end_block, i);
607 ir_node *call, *call_ptr;
611 /* search all Returns of a block */
612 if (! is_Return(ret))
615 /* check, if it's a Return self() */
616 call = skip_Proj(get_Return_mem(ret));
620 /* the call must be in the same block as the return */
621 if (get_nodes_block(call) != get_nodes_block(ret))
624 /* check if it's a recursive call */
625 call_ptr = get_Call_ptr(call);
627 if (! is_SymConst_addr_ent(call_ptr))
630 ent = get_SymConst_entity(call_ptr);
631 if (!ent || get_entity_irg(ent) != irg)
635 * Check, that the types match. At least in C
638 mtd_type = get_entity_type(ent);
639 call_type = get_Call_type(call);
641 if (mtd_type != call_type) {
643 * Hmm, the types did not match, bad.
644 * This can happen in C when no prototype is given
645 * or K&R style is used.
647 DB((dbg, LEVEL_3, " tail recursion fails because of call type mismatch: %+F != %+F\n", mtd_type, call_type));
651 /* ok, mem is routed to a recursive call, check return args */
652 ress = get_Return_res_arr(ret);
653 for (j = get_Return_n_ress(ret) - 1; j >= 0; --j) {
654 tail_rec_variants var = find_variant(ress[j], call);
657 /* cannot be transformed */
660 if (var == TR_DIRECT) {
661 var = env.variants[j];
662 } else if (env.variants[j] == TR_DIRECT) {
663 env.variants[j] = var;
665 if (env.variants[j] != var) {
667 DB((dbg, LEVEL_3, " tail recursion fails for %d return value of %+F\n", j, ret));
674 /* here, we have found a call */
675 set_irn_link(call, get_irn_link(end_block));
676 set_irn_link(end_block, call);
679 /* link all returns, we will need this */
680 set_irn_link(ret, rets);
684 /* now, end_block->link contains the list of all tail calls */
685 if (n_tail_calls > 0) {
686 DB((dbg, LEVEL_2, " Performing tail recursion for graph %s and %d Calls\n",
687 get_entity_ld_name(get_irg_entity(irg)), n_tail_calls));
689 hook_tail_rec(irg, n_tail_calls);
691 env.n_tail_calls = n_tail_calls;
693 do_opt_tail_rec(irg, &env);
694 confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_NONE);
696 confirm_irg_properties(irg, IR_GRAPH_PROPERTIES_ALL);
698 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
699 current_ir_graph = rem;
702 ir_graph_pass_t *opt_tail_rec_irg_pass(const char *name)
704 return def_graph_pass(name ? name : "tailrec", opt_tail_rec_irg);
708 * optimize tail recursion away
710 void opt_tail_recursion(void)
714 FIRM_DBG_REGISTER(dbg, "firm.opt.tailrec");
716 DB((dbg, LEVEL_1, "Performing tail recursion ...\n"));
717 for (i = 0, n = get_irp_n_irgs(); i < n; ++i) {
718 ir_graph *irg = get_irp_irg(i);
719 opt_tail_rec_irg(irg);
723 ir_prog_pass_t *opt_tail_recursion_pass(const char *name)
725 return def_prog_pass(name ? name : "tailrec", opt_tail_recursion);