2015-06-23 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-tailcall.c
blob37179c11fd14b1bbf776d934fa4e69f91478512a
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 "alias.h"
25 #include "symtab.h"
26 #include "tree.h"
27 #include "fold-const.h"
28 #include "stor-layout.h"
29 #include "tm_p.h"
30 #include "predict.h"
31 #include "hard-reg-set.h"
32 #include "function.h"
33 #include "dominance.h"
34 #include "cfg.h"
35 #include "basic-block.h"
36 #include "tree-ssa-alias.h"
37 #include "internal-fn.h"
38 #include "gimple-expr.h"
39 #include "gimple.h"
40 #include "gimple-iterator.h"
41 #include "gimplify-me.h"
42 #include "gimple-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-phinodes.h"
45 #include "stringpool.h"
46 #include "tree-ssanames.h"
47 #include "tree-into-ssa.h"
48 #include "rtl.h"
49 #include "flags.h"
50 #include "insn-config.h"
51 #include "expmed.h"
52 #include "dojump.h"
53 #include "explow.h"
54 #include "calls.h"
55 #include "emit-rtl.h"
56 #include "varasm.h"
57 #include "stmt.h"
58 #include "expr.h"
59 #include "tree-dfa.h"
60 #include "gimple-pretty-print.h"
61 #include "except.h"
62 #include "tree-pass.h"
63 #include "langhooks.h"
64 #include "dbgcnt.h"
65 #include "target.h"
66 #include "cfgloop.h"
67 #include "common/common-target.h"
68 #include "plugin-api.h"
69 #include "ipa-ref.h"
70 #include "cgraph.h"
71 #include "ipa-utils.h"
73 /* The file implements the tail recursion elimination. It is also used to
74 analyze the tail calls in general, passing the results to the rtl level
75 where they are used for sibcall optimization.
77 In addition to the standard tail recursion elimination, we handle the most
78 trivial cases of making the call tail recursive by creating accumulators.
79 For example the following function
81 int sum (int n)
83 if (n > 0)
84 return n + sum (n - 1);
85 else
86 return 0;
89 is transformed into
91 int sum (int n)
93 int acc = 0;
95 while (n > 0)
96 acc += n--;
98 return acc;
101 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
102 when we reach the return x statement, we should return a_acc + x * m_acc
103 instead. They are initially initialized to 0 and 1, respectively,
104 so the semantics of the function is obviously preserved. If we are
105 guaranteed that the value of the accumulator never change, we
106 omit the accumulator.
108 There are three cases how the function may exit. The first one is
109 handled in adjust_return_value, the other two in adjust_accumulator_values
110 (the second case is actually a special case of the third one and we
111 present it separately just for clarity):
113 1) Just return x, where x is not in any of the remaining special shapes.
114 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
116 2) return f (...), where f is the current function, is rewritten in a
117 classical tail-recursion elimination way, into assignment of arguments
118 and jump to the start of the function. Values of the accumulators
119 are unchanged.
121 3) return a + m * f(...), where a and m do not depend on call to f.
122 To preserve the semantics described before we want this to be rewritten
123 in such a way that we finally return
125 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
127 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
128 eliminate the tail call to f. Special cases when the value is just
129 added or just multiplied are obtained by setting a = 0 or m = 1.
131 TODO -- it is possible to do similar tricks for other operations. */
133 /* A structure that describes the tailcall. */
135 struct tailcall
137 /* The iterator pointing to the call statement. */
138 gimple_stmt_iterator call_gsi;
140 /* True if it is a call to the current function. */
141 bool tail_recursion;
143 /* The return value of the caller is mult * f + add, where f is the return
144 value of the call. */
145 tree mult, add;
147 /* Next tailcall in the chain. */
148 struct tailcall *next;
151 /* The variables holding the value of multiplicative and additive
152 accumulator. */
153 static tree m_acc, a_acc;
155 static bool optimize_tail_call (struct tailcall *, bool);
156 static void eliminate_tail_call (struct tailcall *);
158 /* Returns false when the function is not suitable for tail call optimization
159 from some reason (e.g. if it takes variable number of arguments). */
161 static bool
162 suitable_for_tail_opt_p (void)
164 if (cfun->stdarg)
165 return false;
167 return true;
169 /* Returns false when the function is not suitable for tail call optimization
170 for some reason (e.g. if it takes variable number of arguments).
171 This test must pass in addition to suitable_for_tail_opt_p in order to make
172 tail call discovery happen. */
174 static bool
175 suitable_for_tail_call_opt_p (void)
177 tree param;
179 /* alloca (until we have stack slot life analysis) inhibits
180 sibling call optimizations, but not tail recursion. */
181 if (cfun->calls_alloca)
182 return false;
184 /* If we are using sjlj exceptions, we may need to add a call to
185 _Unwind_SjLj_Unregister at exit of the function. Which means
186 that we cannot do any sibcall transformations. */
187 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
188 && current_function_has_exception_handlers ())
189 return false;
191 /* Any function that calls setjmp might have longjmp called from
192 any called function. ??? We really should represent this
193 properly in the CFG so that this needn't be special cased. */
194 if (cfun->calls_setjmp)
195 return false;
197 /* ??? It is OK if the argument of a function is taken in some cases,
198 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
199 for (param = DECL_ARGUMENTS (current_function_decl);
200 param;
201 param = DECL_CHAIN (param))
202 if (TREE_ADDRESSABLE (param))
203 return false;
205 return true;
208 /* Checks whether the expression EXPR in stmt AT is independent of the
209 statement pointed to by GSI (in a sense that we already know EXPR's value
210 at GSI). We use the fact that we are only called from the chain of
211 basic blocks that have only single successor. Returns the expression
212 containing the value of EXPR at GSI. */
214 static tree
215 independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
217 basic_block bb, call_bb, at_bb;
218 edge e;
219 edge_iterator ei;
221 if (is_gimple_min_invariant (expr))
222 return expr;
224 if (TREE_CODE (expr) != SSA_NAME)
225 return NULL_TREE;
227 /* Mark the blocks in the chain leading to the end. */
228 at_bb = gimple_bb (at);
229 call_bb = gimple_bb (gsi_stmt (gsi));
230 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
231 bb->aux = &bb->aux;
232 bb->aux = &bb->aux;
234 while (1)
236 at = SSA_NAME_DEF_STMT (expr);
237 bb = gimple_bb (at);
239 /* The default definition or defined before the chain. */
240 if (!bb || !bb->aux)
241 break;
243 if (bb == call_bb)
245 for (; !gsi_end_p (gsi); gsi_next (&gsi))
246 if (gsi_stmt (gsi) == at)
247 break;
249 if (!gsi_end_p (gsi))
250 expr = NULL_TREE;
251 break;
254 if (gimple_code (at) != GIMPLE_PHI)
256 expr = NULL_TREE;
257 break;
260 FOR_EACH_EDGE (e, ei, bb->preds)
261 if (e->src->aux)
262 break;
263 gcc_assert (e);
265 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
266 if (TREE_CODE (expr) != SSA_NAME)
268 /* The value is a constant. */
269 break;
273 /* Unmark the blocks. */
274 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
275 bb->aux = NULL;
276 bb->aux = NULL;
278 return expr;
281 /* Simulates the effect of an assignment STMT on the return value of the tail
282 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
283 additive factor for the real return value. */
285 static bool
286 process_assignment (gassign *stmt, gimple_stmt_iterator call, tree *m,
287 tree *a, tree *ass_var)
289 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
290 tree dest = gimple_assign_lhs (stmt);
291 enum tree_code code = gimple_assign_rhs_code (stmt);
292 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
293 tree src_var = gimple_assign_rhs1 (stmt);
295 /* See if this is a simple copy operation of an SSA name to the function
296 result. In that case we may have a simple tail call. Ignore type
297 conversions that can never produce extra code between the function
298 call and the function return. */
299 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
300 && (TREE_CODE (src_var) == SSA_NAME))
302 /* Reject a tailcall if the type conversion might need
303 additional code. */
304 if (gimple_assign_cast_p (stmt))
306 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
307 return false;
309 /* Even if the type modes are the same, if the precision of the
310 type is smaller than mode's precision,
311 reduce_to_bit_field_precision would generate additional code. */
312 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
313 && (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (dest)))
314 > TYPE_PRECISION (TREE_TYPE (dest))))
315 return false;
318 if (src_var != *ass_var)
319 return false;
321 *ass_var = dest;
322 return true;
325 switch (rhs_class)
327 case GIMPLE_BINARY_RHS:
328 op1 = gimple_assign_rhs2 (stmt);
330 /* Fall through. */
332 case GIMPLE_UNARY_RHS:
333 op0 = gimple_assign_rhs1 (stmt);
334 break;
336 default:
337 return false;
340 /* Accumulator optimizations will reverse the order of operations.
341 We can only do that for floating-point types if we're assuming
342 that addition and multiplication are associative. */
343 if (!flag_associative_math)
344 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
345 return false;
347 if (rhs_class == GIMPLE_UNARY_RHS)
349 else if (op0 == *ass_var
350 && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
352 else if (op1 == *ass_var
353 && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
355 else
356 return false;
358 switch (code)
360 case PLUS_EXPR:
361 *a = non_ass_var;
362 *ass_var = dest;
363 return true;
365 case POINTER_PLUS_EXPR:
366 if (op0 != *ass_var)
367 return false;
368 *a = non_ass_var;
369 *ass_var = dest;
370 return true;
372 case MULT_EXPR:
373 *m = non_ass_var;
374 *ass_var = dest;
375 return true;
377 case NEGATE_EXPR:
378 *m = build_minus_one_cst (TREE_TYPE (op0));
379 *ass_var = dest;
380 return true;
382 case MINUS_EXPR:
383 if (*ass_var == op0)
384 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
385 else
387 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
388 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
391 *ass_var = dest;
392 return true;
394 /* TODO -- Handle POINTER_PLUS_EXPR. */
396 default:
397 return false;
401 /* Propagate VAR through phis on edge E. */
403 static tree
404 propagate_through_phis (tree var, edge e)
406 basic_block dest = e->dest;
407 gphi_iterator gsi;
409 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
411 gphi *phi = gsi.phi ();
412 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
413 return PHI_RESULT (phi);
415 return var;
418 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
419 added to the start of RET. */
421 static void
422 find_tail_calls (basic_block bb, struct tailcall **ret)
424 tree ass_var = NULL_TREE, ret_var, func, param;
425 gimple stmt;
426 gcall *call = NULL;
427 gimple_stmt_iterator gsi, agsi;
428 bool tail_recursion;
429 struct tailcall *nw;
430 edge e;
431 tree m, a;
432 basic_block abb;
433 size_t idx;
434 tree var;
436 if (!single_succ_p (bb))
437 return;
439 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
441 stmt = gsi_stmt (gsi);
443 /* Ignore labels, returns, clobbers and debug stmts. */
444 if (gimple_code (stmt) == GIMPLE_LABEL
445 || gimple_code (stmt) == GIMPLE_RETURN
446 || gimple_clobber_p (stmt)
447 || is_gimple_debug (stmt))
448 continue;
450 /* Check for a call. */
451 if (is_gimple_call (stmt))
453 call = as_a <gcall *> (stmt);
454 ass_var = gimple_call_lhs (call);
455 break;
458 /* If the statement references memory or volatile operands, fail. */
459 if (gimple_references_memory_p (stmt)
460 || gimple_has_volatile_ops (stmt))
461 return;
464 if (gsi_end_p (gsi))
466 edge_iterator ei;
467 /* Recurse to the predecessors. */
468 FOR_EACH_EDGE (e, ei, bb->preds)
469 find_tail_calls (e->src, ret);
471 return;
474 /* If the LHS of our call is not just a simple register, we can't
475 transform this into a tail or sibling call. This situation happens,
476 in (e.g.) "*p = foo()" where foo returns a struct. In this case
477 we won't have a temporary here, but we need to carry out the side
478 effect anyway, so tailcall is impossible.
480 ??? In some situations (when the struct is returned in memory via
481 invisible argument) we could deal with this, e.g. by passing 'p'
482 itself as that argument to foo, but it's too early to do this here,
483 and expand_call() will not handle it anyway. If it ever can, then
484 we need to revisit this here, to allow that situation. */
485 if (ass_var && !is_gimple_reg (ass_var))
486 return;
488 /* We found the call, check whether it is suitable. */
489 tail_recursion = false;
490 func = gimple_call_fndecl (call);
491 if (func
492 && !DECL_BUILT_IN (func)
493 && recursive_call_p (current_function_decl, func))
495 tree arg;
497 for (param = DECL_ARGUMENTS (func), idx = 0;
498 param && idx < gimple_call_num_args (call);
499 param = DECL_CHAIN (param), idx ++)
501 arg = gimple_call_arg (call, idx);
502 if (param != arg)
504 /* Make sure there are no problems with copying. The parameter
505 have a copyable type and the two arguments must have reasonably
506 equivalent types. The latter requirement could be relaxed if
507 we emitted a suitable type conversion statement. */
508 if (!is_gimple_reg_type (TREE_TYPE (param))
509 || !useless_type_conversion_p (TREE_TYPE (param),
510 TREE_TYPE (arg)))
511 break;
513 /* The parameter should be a real operand, so that phi node
514 created for it at the start of the function has the meaning
515 of copying the value. This test implies is_gimple_reg_type
516 from the previous condition, however this one could be
517 relaxed by being more careful with copying the new value
518 of the parameter (emitting appropriate GIMPLE_ASSIGN and
519 updating the virtual operands). */
520 if (!is_gimple_reg (param))
521 break;
524 if (idx == gimple_call_num_args (call) && !param)
525 tail_recursion = true;
528 /* Make sure the tail invocation of this function does not refer
529 to local variables. */
530 FOR_EACH_LOCAL_DECL (cfun, idx, var)
532 if (TREE_CODE (var) != PARM_DECL
533 && auto_var_in_fn_p (var, cfun->decl)
534 && (ref_maybe_used_by_stmt_p (call, var)
535 || call_may_clobber_ref_p (call, var)))
536 return;
539 /* Now check the statements after the call. None of them has virtual
540 operands, so they may only depend on the call through its return
541 value. The return value should also be dependent on each of them,
542 since we are running after dce. */
543 m = NULL_TREE;
544 a = NULL_TREE;
546 abb = bb;
547 agsi = gsi;
548 while (1)
550 tree tmp_a = NULL_TREE;
551 tree tmp_m = NULL_TREE;
552 gsi_next (&agsi);
554 while (gsi_end_p (agsi))
556 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
557 abb = single_succ (abb);
558 agsi = gsi_start_bb (abb);
561 stmt = gsi_stmt (agsi);
563 if (gimple_code (stmt) == GIMPLE_LABEL)
564 continue;
566 if (gimple_code (stmt) == GIMPLE_RETURN)
567 break;
569 if (gimple_clobber_p (stmt))
570 continue;
572 if (is_gimple_debug (stmt))
573 continue;
575 if (gimple_code (stmt) != GIMPLE_ASSIGN)
576 return;
578 /* This is a gimple assign. */
579 if (! process_assignment (as_a <gassign *> (stmt), gsi, &tmp_m,
580 &tmp_a, &ass_var))
581 return;
583 if (tmp_a)
585 tree type = TREE_TYPE (tmp_a);
586 if (a)
587 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
588 else
589 a = tmp_a;
591 if (tmp_m)
593 tree type = TREE_TYPE (tmp_m);
594 if (m)
595 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
596 else
597 m = tmp_m;
599 if (a)
600 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
604 /* See if this is a tail call we can handle. */
605 ret_var = gimple_return_retval (as_a <greturn *> (stmt));
607 /* We may proceed if there either is no return value, or the return value
608 is identical to the call's return. */
609 if (ret_var
610 && (ret_var != ass_var))
611 return;
613 /* If this is not a tail recursive call, we cannot handle addends or
614 multiplicands. */
615 if (!tail_recursion && (m || a))
616 return;
618 /* For pointers only allow additions. */
619 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
620 return;
622 nw = XNEW (struct tailcall);
624 nw->call_gsi = gsi;
626 nw->tail_recursion = tail_recursion;
628 nw->mult = m;
629 nw->add = a;
631 nw->next = *ret;
632 *ret = nw;
635 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
637 static void
638 add_successor_phi_arg (edge e, tree var, tree phi_arg)
640 gphi_iterator gsi;
642 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
643 if (PHI_RESULT (gsi.phi ()) == var)
644 break;
646 gcc_assert (!gsi_end_p (gsi));
647 add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
650 /* Creates a GIMPLE statement which computes the operation specified by
651 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
652 statement in the position specified by GSI. Returns the
653 tree node of the statement's result. */
655 static tree
656 adjust_return_value_with_ops (enum tree_code code, const char *label,
657 tree acc, tree op1, gimple_stmt_iterator gsi)
660 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
661 tree result = make_temp_ssa_name (ret_type, NULL, label);
662 gassign *stmt;
664 if (POINTER_TYPE_P (ret_type))
666 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
667 code = POINTER_PLUS_EXPR;
669 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
670 && code != POINTER_PLUS_EXPR)
671 stmt = gimple_build_assign (result, code, acc, op1);
672 else
674 tree tem;
675 if (code == POINTER_PLUS_EXPR)
676 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
677 else
678 tem = fold_build2 (code, TREE_TYPE (op1),
679 fold_convert (TREE_TYPE (op1), acc), op1);
680 tree rhs = fold_convert (ret_type, tem);
681 rhs = force_gimple_operand_gsi (&gsi, rhs,
682 false, NULL, true, GSI_SAME_STMT);
683 stmt = gimple_build_assign (result, rhs);
686 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
687 return result;
690 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
691 the computation specified by CODE and OP1 and insert the statement
692 at the position specified by GSI as a new statement. Returns new SSA name
693 of updated accumulator. */
695 static tree
696 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
697 gimple_stmt_iterator gsi)
699 gassign *stmt;
700 tree var = copy_ssa_name (acc);
701 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
702 stmt = gimple_build_assign (var, code, acc, op1);
703 else
705 tree rhs = fold_convert (TREE_TYPE (acc),
706 fold_build2 (code,
707 TREE_TYPE (op1),
708 fold_convert (TREE_TYPE (op1), acc),
709 op1));
710 rhs = force_gimple_operand_gsi (&gsi, rhs,
711 false, NULL, false, GSI_CONTINUE_LINKING);
712 stmt = gimple_build_assign (var, rhs);
714 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
715 return var;
718 /* Adjust the accumulator values according to A and M after GSI, and update
719 the phi nodes on edge BACK. */
721 static void
722 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
724 tree var, a_acc_arg, m_acc_arg;
726 if (m)
727 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
728 if (a)
729 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
731 a_acc_arg = a_acc;
732 m_acc_arg = m_acc;
733 if (a)
735 if (m_acc)
737 if (integer_onep (a))
738 var = m_acc;
739 else
740 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
741 a, gsi);
743 else
744 var = a;
746 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
749 if (m)
750 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
752 if (a_acc)
753 add_successor_phi_arg (back, a_acc, a_acc_arg);
755 if (m_acc)
756 add_successor_phi_arg (back, m_acc, m_acc_arg);
759 /* Adjust value of the return at the end of BB according to M and A
760 accumulators. */
762 static void
763 adjust_return_value (basic_block bb, tree m, tree a)
765 tree retval;
766 greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
767 gimple_stmt_iterator gsi = gsi_last_bb (bb);
769 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
771 retval = gimple_return_retval (ret_stmt);
772 if (!retval || retval == error_mark_node)
773 return;
775 if (m)
776 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
777 gsi);
778 if (a)
779 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
780 gsi);
781 gimple_return_set_retval (ret_stmt, retval);
782 update_stmt (ret_stmt);
785 /* Subtract COUNT and FREQUENCY from the basic block and it's
786 outgoing edge. */
787 static void
788 decrease_profile (basic_block bb, gcov_type count, int frequency)
790 edge e;
791 bb->count -= count;
792 if (bb->count < 0)
793 bb->count = 0;
794 bb->frequency -= frequency;
795 if (bb->frequency < 0)
796 bb->frequency = 0;
797 if (!single_succ_p (bb))
799 gcc_assert (!EDGE_COUNT (bb->succs));
800 return;
802 e = single_succ_edge (bb);
803 e->count -= count;
804 if (e->count < 0)
805 e->count = 0;
808 /* Returns true if argument PARAM of the tail recursive call needs to be copied
809 when the call is eliminated. */
811 static bool
812 arg_needs_copy_p (tree param)
814 tree def;
816 if (!is_gimple_reg (param))
817 return false;
819 /* Parameters that are only defined but never used need not be copied. */
820 def = ssa_default_def (cfun, param);
821 if (!def)
822 return false;
824 return true;
827 /* Eliminates tail call described by T. TMP_VARS is a list of
828 temporary variables used to copy the function arguments. */
830 static void
831 eliminate_tail_call (struct tailcall *t)
833 tree param, rslt;
834 gimple stmt, call;
835 tree arg;
836 size_t idx;
837 basic_block bb, first;
838 edge e;
839 gphi *phi;
840 gphi_iterator gpi;
841 gimple_stmt_iterator gsi;
842 gimple orig_stmt;
844 stmt = orig_stmt = gsi_stmt (t->call_gsi);
845 bb = gsi_bb (t->call_gsi);
847 if (dump_file && (dump_flags & TDF_DETAILS))
849 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
850 bb->index);
851 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
852 fprintf (dump_file, "\n");
855 gcc_assert (is_gimple_call (stmt));
857 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
859 /* Remove the code after call_gsi that will become unreachable. The
860 possibly unreachable code in other blocks is removed later in
861 cfg cleanup. */
862 gsi = t->call_gsi;
863 gsi_next (&gsi);
864 while (!gsi_end_p (gsi))
866 gimple t = gsi_stmt (gsi);
867 /* Do not remove the return statement, so that redirect_edge_and_branch
868 sees how the block ends. */
869 if (gimple_code (t) == GIMPLE_RETURN)
870 break;
872 gsi_remove (&gsi, true);
873 release_defs (t);
876 /* Number of executions of function has reduced by the tailcall. */
877 e = single_succ_edge (gsi_bb (t->call_gsi));
878 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), e->count, EDGE_FREQUENCY (e));
879 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), e->count,
880 EDGE_FREQUENCY (e));
881 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
882 decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
884 /* Replace the call by a jump to the start of function. */
885 e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
886 first);
887 gcc_assert (e);
888 PENDING_STMT (e) = NULL;
890 /* Add phi node entries for arguments. The ordering of the phi nodes should
891 be the same as the ordering of the arguments. */
892 for (param = DECL_ARGUMENTS (current_function_decl),
893 idx = 0, gpi = gsi_start_phis (first);
894 param;
895 param = DECL_CHAIN (param), idx++)
897 if (!arg_needs_copy_p (param))
898 continue;
900 arg = gimple_call_arg (stmt, idx);
901 phi = gpi.phi ();
902 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
904 add_phi_arg (phi, arg, e, gimple_location (stmt));
905 gsi_next (&gpi);
908 /* Update the values of accumulators. */
909 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
911 call = gsi_stmt (t->call_gsi);
912 rslt = gimple_call_lhs (call);
913 if (rslt != NULL_TREE)
915 /* Result of the call will no longer be defined. So adjust the
916 SSA_NAME_DEF_STMT accordingly. */
917 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
920 gsi_remove (&t->call_gsi, true);
921 release_defs (call);
924 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
925 mark the tailcalls for the sibcall optimization. */
927 static bool
928 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
930 if (t->tail_recursion)
932 eliminate_tail_call (t);
933 return true;
936 if (opt_tailcalls)
938 gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
940 gimple_call_set_tail (stmt, true);
941 cfun->tail_call_marked = true;
942 if (dump_file && (dump_flags & TDF_DETAILS))
944 fprintf (dump_file, "Found tail call ");
945 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
946 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
950 return false;
953 /* Creates a tail-call accumulator of the same type as the return type of the
954 current function. LABEL is the name used to creating the temporary
955 variable for the accumulator. The accumulator will be inserted in the
956 phis of a basic block BB with single predecessor with an initial value
957 INIT converted to the current function return type. */
959 static tree
960 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
962 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
963 if (POINTER_TYPE_P (ret_type))
964 ret_type = sizetype;
966 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
967 gphi *phi;
969 phi = create_phi_node (tmp, bb);
970 /* RET_TYPE can be a float when -ffast-maths is enabled. */
971 add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
972 UNKNOWN_LOCATION);
973 return PHI_RESULT (phi);
976 /* Optimizes tail calls in the function, turning the tail recursion
977 into iteration. */
979 static unsigned int
980 tree_optimize_tail_calls_1 (bool opt_tailcalls)
982 edge e;
983 bool phis_constructed = false;
984 struct tailcall *tailcalls = NULL, *act, *next;
985 bool changed = false;
986 basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
987 tree param;
988 gimple stmt;
989 edge_iterator ei;
991 if (!suitable_for_tail_opt_p ())
992 return 0;
993 if (opt_tailcalls)
994 opt_tailcalls = suitable_for_tail_call_opt_p ();
996 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
998 /* Only traverse the normal exits, i.e. those that end with return
999 statement. */
1000 stmt = last_stmt (e->src);
1002 if (stmt
1003 && gimple_code (stmt) == GIMPLE_RETURN)
1004 find_tail_calls (e->src, &tailcalls);
1007 /* Construct the phi nodes and accumulators if necessary. */
1008 a_acc = m_acc = NULL_TREE;
1009 for (act = tailcalls; act; act = act->next)
1011 if (!act->tail_recursion)
1012 continue;
1014 if (!phis_constructed)
1016 /* Ensure that there is only one predecessor of the block
1017 or if there are existing degenerate PHI nodes. */
1018 if (!single_pred_p (first)
1019 || !gimple_seq_empty_p (phi_nodes (first)))
1020 first =
1021 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1023 /* Copy the args if needed. */
1024 for (param = DECL_ARGUMENTS (current_function_decl);
1025 param;
1026 param = DECL_CHAIN (param))
1027 if (arg_needs_copy_p (param))
1029 tree name = ssa_default_def (cfun, param);
1030 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1031 gphi *phi;
1033 set_ssa_default_def (cfun, param, new_name);
1034 phi = create_phi_node (name, first);
1035 add_phi_arg (phi, new_name, single_pred_edge (first),
1036 EXPR_LOCATION (param));
1038 phis_constructed = true;
1041 if (act->add && !a_acc)
1042 a_acc = create_tailcall_accumulator ("add_acc", first,
1043 integer_zero_node);
1045 if (act->mult && !m_acc)
1046 m_acc = create_tailcall_accumulator ("mult_acc", first,
1047 integer_one_node);
1050 if (a_acc || m_acc)
1052 /* When the tail call elimination using accumulators is performed,
1053 statements adding the accumulated value are inserted at all exits.
1054 This turns all other tail calls to non-tail ones. */
1055 opt_tailcalls = false;
1058 for (; tailcalls; tailcalls = next)
1060 next = tailcalls->next;
1061 changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1062 free (tailcalls);
1065 if (a_acc || m_acc)
1067 /* Modify the remaining return statements. */
1068 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1070 stmt = last_stmt (e->src);
1072 if (stmt
1073 && gimple_code (stmt) == GIMPLE_RETURN)
1074 adjust_return_value (e->src, m_acc, a_acc);
1078 if (changed)
1080 /* We may have created new loops. Make them magically appear. */
1081 loops_state_set (LOOPS_NEED_FIXUP);
1082 free_dominance_info (CDI_DOMINATORS);
1085 /* Add phi nodes for the virtual operands defined in the function to the
1086 header of the loop created by tail recursion elimination. Do so
1087 by triggering the SSA renamer. */
1088 if (phis_constructed)
1089 mark_virtual_operands_for_renaming (cfun);
1091 if (changed)
1092 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1093 return 0;
1096 static bool
1097 gate_tail_calls (void)
1099 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1102 static unsigned int
1103 execute_tail_calls (void)
1105 return tree_optimize_tail_calls_1 (true);
1108 namespace {
1110 const pass_data pass_data_tail_recursion =
1112 GIMPLE_PASS, /* type */
1113 "tailr", /* name */
1114 OPTGROUP_NONE, /* optinfo_flags */
1115 TV_NONE, /* tv_id */
1116 ( PROP_cfg | PROP_ssa ), /* properties_required */
1117 0, /* properties_provided */
1118 0, /* properties_destroyed */
1119 0, /* todo_flags_start */
1120 0, /* todo_flags_finish */
1123 class pass_tail_recursion : public gimple_opt_pass
1125 public:
1126 pass_tail_recursion (gcc::context *ctxt)
1127 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1130 /* opt_pass methods: */
1131 opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1132 virtual bool gate (function *) { return gate_tail_calls (); }
1133 virtual unsigned int execute (function *)
1135 return tree_optimize_tail_calls_1 (false);
1138 }; // class pass_tail_recursion
1140 } // anon namespace
1142 gimple_opt_pass *
1143 make_pass_tail_recursion (gcc::context *ctxt)
1145 return new pass_tail_recursion (ctxt);
1148 namespace {
1150 const pass_data pass_data_tail_calls =
1152 GIMPLE_PASS, /* type */
1153 "tailc", /* name */
1154 OPTGROUP_NONE, /* optinfo_flags */
1155 TV_NONE, /* tv_id */
1156 ( PROP_cfg | PROP_ssa ), /* properties_required */
1157 0, /* properties_provided */
1158 0, /* properties_destroyed */
1159 0, /* todo_flags_start */
1160 0, /* todo_flags_finish */
1163 class pass_tail_calls : public gimple_opt_pass
1165 public:
1166 pass_tail_calls (gcc::context *ctxt)
1167 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1170 /* opt_pass methods: */
1171 virtual bool gate (function *) { return gate_tail_calls (); }
1172 virtual unsigned int execute (function *) { return execute_tail_calls (); }
1174 }; // class pass_tail_calls
1176 } // anon namespace
1178 gimple_opt_pass *
1179 make_pass_tail_calls (gcc::context *ctxt)
1181 return new pass_tail_calls (ctxt);