2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-tailcall.c
blob6f0d6ccfd2faaf43e894079f6fd0f8fc5b04abf8
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "input.h"
25 #include "alias.h"
26 #include "symtab.h"
27 #include "tree.h"
28 #include "fold-const.h"
29 #include "stor-layout.h"
30 #include "tm_p.h"
31 #include "predict.h"
32 #include "hard-reg-set.h"
33 #include "function.h"
34 #include "dominance.h"
35 #include "cfg.h"
36 #include "basic-block.h"
37 #include "tree-ssa-alias.h"
38 #include "internal-fn.h"
39 #include "gimple-expr.h"
40 #include "is-a.h"
41 #include "gimple.h"
42 #include "gimple-iterator.h"
43 #include "gimplify-me.h"
44 #include "gimple-ssa.h"
45 #include "tree-cfg.h"
46 #include "tree-phinodes.h"
47 #include "stringpool.h"
48 #include "tree-ssanames.h"
49 #include "tree-into-ssa.h"
50 #include "rtl.h"
51 #include "flags.h"
52 #include "insn-config.h"
53 #include "expmed.h"
54 #include "dojump.h"
55 #include "explow.h"
56 #include "calls.h"
57 #include "emit-rtl.h"
58 #include "varasm.h"
59 #include "stmt.h"
60 #include "expr.h"
61 #include "tree-dfa.h"
62 #include "gimple-pretty-print.h"
63 #include "except.h"
64 #include "tree-pass.h"
65 #include "langhooks.h"
66 #include "dbgcnt.h"
67 #include "target.h"
68 #include "cfgloop.h"
69 #include "common/common-target.h"
70 #include "plugin-api.h"
71 #include "ipa-ref.h"
72 #include "cgraph.h"
73 #include "ipa-utils.h"
75 /* The file implements the tail recursion elimination. It is also used to
76 analyze the tail calls in general, passing the results to the rtl level
77 where they are used for sibcall optimization.
79 In addition to the standard tail recursion elimination, we handle the most
80 trivial cases of making the call tail recursive by creating accumulators.
81 For example the following function
83 int sum (int n)
85 if (n > 0)
86 return n + sum (n - 1);
87 else
88 return 0;
91 is transformed into
93 int sum (int n)
95 int acc = 0;
97 while (n > 0)
98 acc += n--;
100 return acc;
103 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
104 when we reach the return x statement, we should return a_acc + x * m_acc
105 instead. They are initially initialized to 0 and 1, respectively,
106 so the semantics of the function is obviously preserved. If we are
107 guaranteed that the value of the accumulator never change, we
108 omit the accumulator.
110 There are three cases how the function may exit. The first one is
111 handled in adjust_return_value, the other two in adjust_accumulator_values
112 (the second case is actually a special case of the third one and we
113 present it separately just for clarity):
115 1) Just return x, where x is not in any of the remaining special shapes.
116 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
118 2) return f (...), where f is the current function, is rewritten in a
119 classical tail-recursion elimination way, into assignment of arguments
120 and jump to the start of the function. Values of the accumulators
121 are unchanged.
123 3) return a + m * f(...), where a and m do not depend on call to f.
124 To preserve the semantics described before we want this to be rewritten
125 in such a way that we finally return
127 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
129 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
130 eliminate the tail call to f. Special cases when the value is just
131 added or just multiplied are obtained by setting a = 0 or m = 1.
133 TODO -- it is possible to do similar tricks for other operations. */
135 /* A structure that describes the tailcall. */
137 struct tailcall
139 /* The iterator pointing to the call statement. */
140 gimple_stmt_iterator call_gsi;
142 /* True if it is a call to the current function. */
143 bool tail_recursion;
145 /* The return value of the caller is mult * f + add, where f is the return
146 value of the call. */
147 tree mult, add;
149 /* Next tailcall in the chain. */
150 struct tailcall *next;
153 /* The variables holding the value of multiplicative and additive
154 accumulator. */
155 static tree m_acc, a_acc;
157 static bool optimize_tail_call (struct tailcall *, bool);
158 static void eliminate_tail_call (struct tailcall *);
160 /* Returns false when the function is not suitable for tail call optimization
161 from some reason (e.g. if it takes variable number of arguments). */
163 static bool
164 suitable_for_tail_opt_p (void)
166 if (cfun->stdarg)
167 return false;
169 return true;
171 /* Returns false when the function is not suitable for tail call optimization
172 for some reason (e.g. if it takes variable number of arguments).
173 This test must pass in addition to suitable_for_tail_opt_p in order to make
174 tail call discovery happen. */
176 static bool
177 suitable_for_tail_call_opt_p (void)
179 tree param;
181 /* alloca (until we have stack slot life analysis) inhibits
182 sibling call optimizations, but not tail recursion. */
183 if (cfun->calls_alloca)
184 return false;
186 /* If we are using sjlj exceptions, we may need to add a call to
187 _Unwind_SjLj_Unregister at exit of the function. Which means
188 that we cannot do any sibcall transformations. */
189 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
190 && current_function_has_exception_handlers ())
191 return false;
193 /* Any function that calls setjmp might have longjmp called from
194 any called function. ??? We really should represent this
195 properly in the CFG so that this needn't be special cased. */
196 if (cfun->calls_setjmp)
197 return false;
199 /* ??? It is OK if the argument of a function is taken in some cases,
200 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
201 for (param = DECL_ARGUMENTS (current_function_decl);
202 param;
203 param = DECL_CHAIN (param))
204 if (TREE_ADDRESSABLE (param))
205 return false;
207 return true;
210 /* Checks whether the expression EXPR in stmt AT is independent of the
211 statement pointed to by GSI (in a sense that we already know EXPR's value
212 at GSI). We use the fact that we are only called from the chain of
213 basic blocks that have only single successor. Returns the expression
214 containing the value of EXPR at GSI. */
216 static tree
217 independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
219 basic_block bb, call_bb, at_bb;
220 edge e;
221 edge_iterator ei;
223 if (is_gimple_min_invariant (expr))
224 return expr;
226 if (TREE_CODE (expr) != SSA_NAME)
227 return NULL_TREE;
229 /* Mark the blocks in the chain leading to the end. */
230 at_bb = gimple_bb (at);
231 call_bb = gimple_bb (gsi_stmt (gsi));
232 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
233 bb->aux = &bb->aux;
234 bb->aux = &bb->aux;
236 while (1)
238 at = SSA_NAME_DEF_STMT (expr);
239 bb = gimple_bb (at);
241 /* The default definition or defined before the chain. */
242 if (!bb || !bb->aux)
243 break;
245 if (bb == call_bb)
247 for (; !gsi_end_p (gsi); gsi_next (&gsi))
248 if (gsi_stmt (gsi) == at)
249 break;
251 if (!gsi_end_p (gsi))
252 expr = NULL_TREE;
253 break;
256 if (gimple_code (at) != GIMPLE_PHI)
258 expr = NULL_TREE;
259 break;
262 FOR_EACH_EDGE (e, ei, bb->preds)
263 if (e->src->aux)
264 break;
265 gcc_assert (e);
267 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
268 if (TREE_CODE (expr) != SSA_NAME)
270 /* The value is a constant. */
271 break;
275 /* Unmark the blocks. */
276 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
277 bb->aux = NULL;
278 bb->aux = NULL;
280 return expr;
283 /* Simulates the effect of an assignment STMT on the return value of the tail
284 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
285 additive factor for the real return value. */
287 static bool
288 process_assignment (gassign *stmt, gimple_stmt_iterator call, tree *m,
289 tree *a, tree *ass_var)
291 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
292 tree dest = gimple_assign_lhs (stmt);
293 enum tree_code code = gimple_assign_rhs_code (stmt);
294 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
295 tree src_var = gimple_assign_rhs1 (stmt);
297 /* See if this is a simple copy operation of an SSA name to the function
298 result. In that case we may have a simple tail call. Ignore type
299 conversions that can never produce extra code between the function
300 call and the function return. */
301 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
302 && (TREE_CODE (src_var) == SSA_NAME))
304 /* Reject a tailcall if the type conversion might need
305 additional code. */
306 if (gimple_assign_cast_p (stmt))
308 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
309 return false;
311 /* Even if the type modes are the same, if the precision of the
312 type is smaller than mode's precision,
313 reduce_to_bit_field_precision would generate additional code. */
314 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
315 && (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (dest)))
316 > TYPE_PRECISION (TREE_TYPE (dest))))
317 return false;
320 if (src_var != *ass_var)
321 return false;
323 *ass_var = dest;
324 return true;
327 switch (rhs_class)
329 case GIMPLE_BINARY_RHS:
330 op1 = gimple_assign_rhs2 (stmt);
332 /* Fall through. */
334 case GIMPLE_UNARY_RHS:
335 op0 = gimple_assign_rhs1 (stmt);
336 break;
338 default:
339 return false;
342 /* Accumulator optimizations will reverse the order of operations.
343 We can only do that for floating-point types if we're assuming
344 that addition and multiplication are associative. */
345 if (!flag_associative_math)
346 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
347 return false;
349 if (rhs_class == GIMPLE_UNARY_RHS)
351 else if (op0 == *ass_var
352 && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
354 else if (op1 == *ass_var
355 && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
357 else
358 return false;
360 switch (code)
362 case PLUS_EXPR:
363 *a = non_ass_var;
364 *ass_var = dest;
365 return true;
367 case POINTER_PLUS_EXPR:
368 if (op0 != *ass_var)
369 return false;
370 *a = non_ass_var;
371 *ass_var = dest;
372 return true;
374 case MULT_EXPR:
375 *m = non_ass_var;
376 *ass_var = dest;
377 return true;
379 case NEGATE_EXPR:
380 *m = build_minus_one_cst (TREE_TYPE (op0));
381 *ass_var = dest;
382 return true;
384 case MINUS_EXPR:
385 if (*ass_var == op0)
386 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
387 else
389 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
390 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
393 *ass_var = dest;
394 return true;
396 /* TODO -- Handle POINTER_PLUS_EXPR. */
398 default:
399 return false;
403 /* Propagate VAR through phis on edge E. */
405 static tree
406 propagate_through_phis (tree var, edge e)
408 basic_block dest = e->dest;
409 gphi_iterator gsi;
411 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
413 gphi *phi = gsi.phi ();
414 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
415 return PHI_RESULT (phi);
417 return var;
420 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
421 added to the start of RET. */
423 static void
424 find_tail_calls (basic_block bb, struct tailcall **ret)
426 tree ass_var = NULL_TREE, ret_var, func, param;
427 gimple stmt;
428 gcall *call = NULL;
429 gimple_stmt_iterator gsi, agsi;
430 bool tail_recursion;
431 struct tailcall *nw;
432 edge e;
433 tree m, a;
434 basic_block abb;
435 size_t idx;
436 tree var;
438 if (!single_succ_p (bb))
439 return;
441 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
443 stmt = gsi_stmt (gsi);
445 /* Ignore labels, returns, clobbers and debug stmts. */
446 if (gimple_code (stmt) == GIMPLE_LABEL
447 || gimple_code (stmt) == GIMPLE_RETURN
448 || gimple_clobber_p (stmt)
449 || is_gimple_debug (stmt))
450 continue;
452 /* Check for a call. */
453 if (is_gimple_call (stmt))
455 call = as_a <gcall *> (stmt);
456 ass_var = gimple_call_lhs (call);
457 break;
460 /* If the statement references memory or volatile operands, fail. */
461 if (gimple_references_memory_p (stmt)
462 || gimple_has_volatile_ops (stmt))
463 return;
466 if (gsi_end_p (gsi))
468 edge_iterator ei;
469 /* Recurse to the predecessors. */
470 FOR_EACH_EDGE (e, ei, bb->preds)
471 find_tail_calls (e->src, ret);
473 return;
476 /* If the LHS of our call is not just a simple register, we can't
477 transform this into a tail or sibling call. This situation happens,
478 in (e.g.) "*p = foo()" where foo returns a struct. In this case
479 we won't have a temporary here, but we need to carry out the side
480 effect anyway, so tailcall is impossible.
482 ??? In some situations (when the struct is returned in memory via
483 invisible argument) we could deal with this, e.g. by passing 'p'
484 itself as that argument to foo, but it's too early to do this here,
485 and expand_call() will not handle it anyway. If it ever can, then
486 we need to revisit this here, to allow that situation. */
487 if (ass_var && !is_gimple_reg (ass_var))
488 return;
490 /* We found the call, check whether it is suitable. */
491 tail_recursion = false;
492 func = gimple_call_fndecl (call);
493 if (func
494 && !DECL_BUILT_IN (func)
495 && recursive_call_p (current_function_decl, func))
497 tree arg;
499 for (param = DECL_ARGUMENTS (func), idx = 0;
500 param && idx < gimple_call_num_args (call);
501 param = DECL_CHAIN (param), idx ++)
503 arg = gimple_call_arg (call, idx);
504 if (param != arg)
506 /* Make sure there are no problems with copying. The parameter
507 have a copyable type and the two arguments must have reasonably
508 equivalent types. The latter requirement could be relaxed if
509 we emitted a suitable type conversion statement. */
510 if (!is_gimple_reg_type (TREE_TYPE (param))
511 || !useless_type_conversion_p (TREE_TYPE (param),
512 TREE_TYPE (arg)))
513 break;
515 /* The parameter should be a real operand, so that phi node
516 created for it at the start of the function has the meaning
517 of copying the value. This test implies is_gimple_reg_type
518 from the previous condition, however this one could be
519 relaxed by being more careful with copying the new value
520 of the parameter (emitting appropriate GIMPLE_ASSIGN and
521 updating the virtual operands). */
522 if (!is_gimple_reg (param))
523 break;
526 if (idx == gimple_call_num_args (call) && !param)
527 tail_recursion = true;
530 /* Make sure the tail invocation of this function does not refer
531 to local variables. */
532 FOR_EACH_LOCAL_DECL (cfun, idx, var)
534 if (TREE_CODE (var) != PARM_DECL
535 && auto_var_in_fn_p (var, cfun->decl)
536 && (ref_maybe_used_by_stmt_p (call, var)
537 || call_may_clobber_ref_p (call, var)))
538 return;
541 /* Now check the statements after the call. None of them has virtual
542 operands, so they may only depend on the call through its return
543 value. The return value should also be dependent on each of them,
544 since we are running after dce. */
545 m = NULL_TREE;
546 a = NULL_TREE;
548 abb = bb;
549 agsi = gsi;
550 while (1)
552 tree tmp_a = NULL_TREE;
553 tree tmp_m = NULL_TREE;
554 gsi_next (&agsi);
556 while (gsi_end_p (agsi))
558 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
559 abb = single_succ (abb);
560 agsi = gsi_start_bb (abb);
563 stmt = gsi_stmt (agsi);
565 if (gimple_code (stmt) == GIMPLE_LABEL)
566 continue;
568 if (gimple_code (stmt) == GIMPLE_RETURN)
569 break;
571 if (gimple_clobber_p (stmt))
572 continue;
574 if (is_gimple_debug (stmt))
575 continue;
577 if (gimple_code (stmt) != GIMPLE_ASSIGN)
578 return;
580 /* This is a gimple assign. */
581 if (! process_assignment (as_a <gassign *> (stmt), gsi, &tmp_m,
582 &tmp_a, &ass_var))
583 return;
585 if (tmp_a)
587 tree type = TREE_TYPE (tmp_a);
588 if (a)
589 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
590 else
591 a = tmp_a;
593 if (tmp_m)
595 tree type = TREE_TYPE (tmp_m);
596 if (m)
597 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
598 else
599 m = tmp_m;
601 if (a)
602 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
606 /* See if this is a tail call we can handle. */
607 ret_var = gimple_return_retval (as_a <greturn *> (stmt));
609 /* We may proceed if there either is no return value, or the return value
610 is identical to the call's return. */
611 if (ret_var
612 && (ret_var != ass_var))
613 return;
615 /* If this is not a tail recursive call, we cannot handle addends or
616 multiplicands. */
617 if (!tail_recursion && (m || a))
618 return;
620 /* For pointers only allow additions. */
621 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
622 return;
624 nw = XNEW (struct tailcall);
626 nw->call_gsi = gsi;
628 nw->tail_recursion = tail_recursion;
630 nw->mult = m;
631 nw->add = a;
633 nw->next = *ret;
634 *ret = nw;
637 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
639 static void
640 add_successor_phi_arg (edge e, tree var, tree phi_arg)
642 gphi_iterator gsi;
644 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
645 if (PHI_RESULT (gsi.phi ()) == var)
646 break;
648 gcc_assert (!gsi_end_p (gsi));
649 add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
652 /* Creates a GIMPLE statement which computes the operation specified by
653 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
654 statement in the position specified by GSI. Returns the
655 tree node of the statement's result. */
657 static tree
658 adjust_return_value_with_ops (enum tree_code code, const char *label,
659 tree acc, tree op1, gimple_stmt_iterator gsi)
662 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
663 tree result = make_temp_ssa_name (ret_type, NULL, label);
664 gassign *stmt;
666 if (POINTER_TYPE_P (ret_type))
668 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
669 code = POINTER_PLUS_EXPR;
671 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
672 && code != POINTER_PLUS_EXPR)
673 stmt = gimple_build_assign (result, code, acc, op1);
674 else
676 tree tem;
677 if (code == POINTER_PLUS_EXPR)
678 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
679 else
680 tem = fold_build2 (code, TREE_TYPE (op1),
681 fold_convert (TREE_TYPE (op1), acc), op1);
682 tree rhs = fold_convert (ret_type, tem);
683 rhs = force_gimple_operand_gsi (&gsi, rhs,
684 false, NULL, true, GSI_SAME_STMT);
685 stmt = gimple_build_assign (result, rhs);
688 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
689 return result;
692 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
693 the computation specified by CODE and OP1 and insert the statement
694 at the position specified by GSI as a new statement. Returns new SSA name
695 of updated accumulator. */
697 static tree
698 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
699 gimple_stmt_iterator gsi)
701 gassign *stmt;
702 tree var = copy_ssa_name (acc);
703 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
704 stmt = gimple_build_assign (var, code, acc, op1);
705 else
707 tree rhs = fold_convert (TREE_TYPE (acc),
708 fold_build2 (code,
709 TREE_TYPE (op1),
710 fold_convert (TREE_TYPE (op1), acc),
711 op1));
712 rhs = force_gimple_operand_gsi (&gsi, rhs,
713 false, NULL, false, GSI_CONTINUE_LINKING);
714 stmt = gimple_build_assign (var, rhs);
716 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
717 return var;
720 /* Adjust the accumulator values according to A and M after GSI, and update
721 the phi nodes on edge BACK. */
723 static void
724 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
726 tree var, a_acc_arg, m_acc_arg;
728 if (m)
729 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
730 if (a)
731 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
733 a_acc_arg = a_acc;
734 m_acc_arg = m_acc;
735 if (a)
737 if (m_acc)
739 if (integer_onep (a))
740 var = m_acc;
741 else
742 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
743 a, gsi);
745 else
746 var = a;
748 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
751 if (m)
752 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
754 if (a_acc)
755 add_successor_phi_arg (back, a_acc, a_acc_arg);
757 if (m_acc)
758 add_successor_phi_arg (back, m_acc, m_acc_arg);
761 /* Adjust value of the return at the end of BB according to M and A
762 accumulators. */
764 static void
765 adjust_return_value (basic_block bb, tree m, tree a)
767 tree retval;
768 greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
769 gimple_stmt_iterator gsi = gsi_last_bb (bb);
771 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
773 retval = gimple_return_retval (ret_stmt);
774 if (!retval || retval == error_mark_node)
775 return;
777 if (m)
778 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
779 gsi);
780 if (a)
781 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
782 gsi);
783 gimple_return_set_retval (ret_stmt, retval);
784 update_stmt (ret_stmt);
787 /* Subtract COUNT and FREQUENCY from the basic block and it's
788 outgoing edge. */
789 static void
790 decrease_profile (basic_block bb, gcov_type count, int frequency)
792 edge e;
793 bb->count -= count;
794 if (bb->count < 0)
795 bb->count = 0;
796 bb->frequency -= frequency;
797 if (bb->frequency < 0)
798 bb->frequency = 0;
799 if (!single_succ_p (bb))
801 gcc_assert (!EDGE_COUNT (bb->succs));
802 return;
804 e = single_succ_edge (bb);
805 e->count -= count;
806 if (e->count < 0)
807 e->count = 0;
810 /* Returns true if argument PARAM of the tail recursive call needs to be copied
811 when the call is eliminated. */
813 static bool
814 arg_needs_copy_p (tree param)
816 tree def;
818 if (!is_gimple_reg (param))
819 return false;
821 /* Parameters that are only defined but never used need not be copied. */
822 def = ssa_default_def (cfun, param);
823 if (!def)
824 return false;
826 return true;
829 /* Eliminates tail call described by T. TMP_VARS is a list of
830 temporary variables used to copy the function arguments. */
832 static void
833 eliminate_tail_call (struct tailcall *t)
835 tree param, rslt;
836 gimple stmt, call;
837 tree arg;
838 size_t idx;
839 basic_block bb, first;
840 edge e;
841 gphi *phi;
842 gphi_iterator gpi;
843 gimple_stmt_iterator gsi;
844 gimple orig_stmt;
846 stmt = orig_stmt = gsi_stmt (t->call_gsi);
847 bb = gsi_bb (t->call_gsi);
849 if (dump_file && (dump_flags & TDF_DETAILS))
851 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
852 bb->index);
853 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
854 fprintf (dump_file, "\n");
857 gcc_assert (is_gimple_call (stmt));
859 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
861 /* Remove the code after call_gsi that will become unreachable. The
862 possibly unreachable code in other blocks is removed later in
863 cfg cleanup. */
864 gsi = t->call_gsi;
865 gsi_next (&gsi);
866 while (!gsi_end_p (gsi))
868 gimple t = gsi_stmt (gsi);
869 /* Do not remove the return statement, so that redirect_edge_and_branch
870 sees how the block ends. */
871 if (gimple_code (t) == GIMPLE_RETURN)
872 break;
874 gsi_remove (&gsi, true);
875 release_defs (t);
878 /* Number of executions of function has reduced by the tailcall. */
879 e = single_succ_edge (gsi_bb (t->call_gsi));
880 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), e->count, EDGE_FREQUENCY (e));
881 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), e->count,
882 EDGE_FREQUENCY (e));
883 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
884 decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
886 /* Replace the call by a jump to the start of function. */
887 e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
888 first);
889 gcc_assert (e);
890 PENDING_STMT (e) = NULL;
892 /* Add phi node entries for arguments. The ordering of the phi nodes should
893 be the same as the ordering of the arguments. */
894 for (param = DECL_ARGUMENTS (current_function_decl),
895 idx = 0, gpi = gsi_start_phis (first);
896 param;
897 param = DECL_CHAIN (param), idx++)
899 if (!arg_needs_copy_p (param))
900 continue;
902 arg = gimple_call_arg (stmt, idx);
903 phi = gpi.phi ();
904 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
906 add_phi_arg (phi, arg, e, gimple_location (stmt));
907 gsi_next (&gpi);
910 /* Update the values of accumulators. */
911 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
913 call = gsi_stmt (t->call_gsi);
914 rslt = gimple_call_lhs (call);
915 if (rslt != NULL_TREE)
917 /* Result of the call will no longer be defined. So adjust the
918 SSA_NAME_DEF_STMT accordingly. */
919 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
922 gsi_remove (&t->call_gsi, true);
923 release_defs (call);
926 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
927 mark the tailcalls for the sibcall optimization. */
929 static bool
930 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
932 if (t->tail_recursion)
934 eliminate_tail_call (t);
935 return true;
938 if (opt_tailcalls)
940 gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
942 gimple_call_set_tail (stmt, true);
943 cfun->tail_call_marked = true;
944 if (dump_file && (dump_flags & TDF_DETAILS))
946 fprintf (dump_file, "Found tail call ");
947 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
948 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
952 return false;
955 /* Creates a tail-call accumulator of the same type as the return type of the
956 current function. LABEL is the name used to creating the temporary
957 variable for the accumulator. The accumulator will be inserted in the
958 phis of a basic block BB with single predecessor with an initial value
959 INIT converted to the current function return type. */
961 static tree
962 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
964 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
965 if (POINTER_TYPE_P (ret_type))
966 ret_type = sizetype;
968 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
969 gphi *phi;
971 phi = create_phi_node (tmp, bb);
972 /* RET_TYPE can be a float when -ffast-maths is enabled. */
973 add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
974 UNKNOWN_LOCATION);
975 return PHI_RESULT (phi);
978 /* Optimizes tail calls in the function, turning the tail recursion
979 into iteration. */
981 static unsigned int
982 tree_optimize_tail_calls_1 (bool opt_tailcalls)
984 edge e;
985 bool phis_constructed = false;
986 struct tailcall *tailcalls = NULL, *act, *next;
987 bool changed = false;
988 basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
989 tree param;
990 gimple stmt;
991 edge_iterator ei;
993 if (!suitable_for_tail_opt_p ())
994 return 0;
995 if (opt_tailcalls)
996 opt_tailcalls = suitable_for_tail_call_opt_p ();
998 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1000 /* Only traverse the normal exits, i.e. those that end with return
1001 statement. */
1002 stmt = last_stmt (e->src);
1004 if (stmt
1005 && gimple_code (stmt) == GIMPLE_RETURN)
1006 find_tail_calls (e->src, &tailcalls);
1009 /* Construct the phi nodes and accumulators if necessary. */
1010 a_acc = m_acc = NULL_TREE;
1011 for (act = tailcalls; act; act = act->next)
1013 if (!act->tail_recursion)
1014 continue;
1016 if (!phis_constructed)
1018 /* Ensure that there is only one predecessor of the block
1019 or if there are existing degenerate PHI nodes. */
1020 if (!single_pred_p (first)
1021 || !gimple_seq_empty_p (phi_nodes (first)))
1022 first =
1023 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1025 /* Copy the args if needed. */
1026 for (param = DECL_ARGUMENTS (current_function_decl);
1027 param;
1028 param = DECL_CHAIN (param))
1029 if (arg_needs_copy_p (param))
1031 tree name = ssa_default_def (cfun, param);
1032 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1033 gphi *phi;
1035 set_ssa_default_def (cfun, param, new_name);
1036 phi = create_phi_node (name, first);
1037 add_phi_arg (phi, new_name, single_pred_edge (first),
1038 EXPR_LOCATION (param));
1040 phis_constructed = true;
1043 if (act->add && !a_acc)
1044 a_acc = create_tailcall_accumulator ("add_acc", first,
1045 integer_zero_node);
1047 if (act->mult && !m_acc)
1048 m_acc = create_tailcall_accumulator ("mult_acc", first,
1049 integer_one_node);
1052 if (a_acc || m_acc)
1054 /* When the tail call elimination using accumulators is performed,
1055 statements adding the accumulated value are inserted at all exits.
1056 This turns all other tail calls to non-tail ones. */
1057 opt_tailcalls = false;
1060 for (; tailcalls; tailcalls = next)
1062 next = tailcalls->next;
1063 changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1064 free (tailcalls);
1067 if (a_acc || m_acc)
1069 /* Modify the remaining return statements. */
1070 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1072 stmt = last_stmt (e->src);
1074 if (stmt
1075 && gimple_code (stmt) == GIMPLE_RETURN)
1076 adjust_return_value (e->src, m_acc, a_acc);
1080 if (changed)
1082 /* We may have created new loops. Make them magically appear. */
1083 loops_state_set (LOOPS_NEED_FIXUP);
1084 free_dominance_info (CDI_DOMINATORS);
1087 /* Add phi nodes for the virtual operands defined in the function to the
1088 header of the loop created by tail recursion elimination. Do so
1089 by triggering the SSA renamer. */
1090 if (phis_constructed)
1091 mark_virtual_operands_for_renaming (cfun);
1093 if (changed)
1094 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1095 return 0;
1098 static bool
1099 gate_tail_calls (void)
1101 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1104 static unsigned int
1105 execute_tail_calls (void)
1107 return tree_optimize_tail_calls_1 (true);
1110 namespace {
1112 const pass_data pass_data_tail_recursion =
1114 GIMPLE_PASS, /* type */
1115 "tailr", /* name */
1116 OPTGROUP_NONE, /* optinfo_flags */
1117 TV_NONE, /* tv_id */
1118 ( PROP_cfg | PROP_ssa ), /* properties_required */
1119 0, /* properties_provided */
1120 0, /* properties_destroyed */
1121 0, /* todo_flags_start */
1122 0, /* todo_flags_finish */
1125 class pass_tail_recursion : public gimple_opt_pass
1127 public:
1128 pass_tail_recursion (gcc::context *ctxt)
1129 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1132 /* opt_pass methods: */
1133 opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1134 virtual bool gate (function *) { return gate_tail_calls (); }
1135 virtual unsigned int execute (function *)
1137 return tree_optimize_tail_calls_1 (false);
1140 }; // class pass_tail_recursion
1142 } // anon namespace
1144 gimple_opt_pass *
1145 make_pass_tail_recursion (gcc::context *ctxt)
1147 return new pass_tail_recursion (ctxt);
1150 namespace {
1152 const pass_data pass_data_tail_calls =
1154 GIMPLE_PASS, /* type */
1155 "tailc", /* name */
1156 OPTGROUP_NONE, /* optinfo_flags */
1157 TV_NONE, /* tv_id */
1158 ( PROP_cfg | PROP_ssa ), /* properties_required */
1159 0, /* properties_provided */
1160 0, /* properties_destroyed */
1161 0, /* todo_flags_start */
1162 0, /* todo_flags_finish */
1165 class pass_tail_calls : public gimple_opt_pass
1167 public:
1168 pass_tail_calls (gcc::context *ctxt)
1169 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1172 /* opt_pass methods: */
1173 virtual bool gate (function *) { return gate_tail_calls (); }
1174 virtual unsigned int execute (function *) { return execute_tail_calls (); }
1176 }; // class pass_tail_calls
1178 } // anon namespace
1180 gimple_opt_pass *
1181 make_pass_tail_calls (gcc::context *ctxt)
1183 return new pass_tail_calls (ctxt);