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)
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/>. */
22 #include "coretypes.h"
28 #include "fold-const.h"
29 #include "stor-layout.h"
32 #include "hard-reg-set.h"
34 #include "dominance.h"
36 #include "basic-block.h"
37 #include "tree-ssa-alias.h"
38 #include "internal-fn.h"
39 #include "gimple-expr.h"
42 #include "gimple-iterator.h"
43 #include "gimplify-me.h"
44 #include "gimple-ssa.h"
46 #include "tree-phinodes.h"
47 #include "stringpool.h"
48 #include "tree-ssanames.h"
49 #include "tree-into-ssa.h"
52 #include "insn-config.h"
62 #include "gimple-pretty-print.h"
64 #include "tree-pass.h"
65 #include "langhooks.h"
69 #include "common/common-target.h"
70 #include "plugin-api.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
86 return n + sum (n - 1);
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
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. */
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. */
145 /* The return value of the caller is mult * f + add, where f is the return
146 value of the call. */
149 /* Next tailcall in the chain. */
150 struct tailcall
*next
;
153 /* The variables holding the value of multiplicative and additive
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). */
164 suitable_for_tail_opt_p (void)
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. */
177 suitable_for_tail_call_opt_p (void)
181 /* alloca (until we have stack slot life analysis) inhibits
182 sibling call optimizations, but not tail recursion. */
183 if (cfun
->calls_alloca
)
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 ())
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
)
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
);
203 param
= DECL_CHAIN (param
))
204 if (TREE_ADDRESSABLE (param
))
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. */
217 independent_of_stmt_p (tree expr
, gimple at
, gimple_stmt_iterator gsi
)
219 basic_block bb
, call_bb
, at_bb
;
223 if (is_gimple_min_invariant (expr
))
226 if (TREE_CODE (expr
) != SSA_NAME
)
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
))
238 at
= SSA_NAME_DEF_STMT (expr
);
241 /* The default definition or defined before the chain. */
247 for (; !gsi_end_p (gsi
); gsi_next (&gsi
))
248 if (gsi_stmt (gsi
) == at
)
251 if (!gsi_end_p (gsi
))
256 if (gimple_code (at
) != GIMPLE_PHI
)
262 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
267 expr
= PHI_ARG_DEF_FROM_EDGE (at
, e
);
268 if (TREE_CODE (expr
) != SSA_NAME
)
270 /* The value is a constant. */
275 /* Unmark the blocks. */
276 for (bb
= call_bb
; bb
!= at_bb
; bb
= single_succ (bb
))
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. */
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
306 if (gimple_assign_cast_p (stmt
))
308 if (TYPE_MODE (TREE_TYPE (dest
)) != TYPE_MODE (TREE_TYPE (src_var
)))
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
))))
320 if (src_var
!= *ass_var
)
329 case GIMPLE_BINARY_RHS
:
330 op1
= gimple_assign_rhs2 (stmt
);
334 case GIMPLE_UNARY_RHS
:
335 op0
= gimple_assign_rhs1 (stmt
);
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
))))
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
)))
367 case POINTER_PLUS_EXPR
:
380 *m
= build_minus_one_cst (TREE_TYPE (op0
));
386 *a
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (non_ass_var
), non_ass_var
);
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
);
396 /* TODO -- Handle POINTER_PLUS_EXPR. */
403 /* Propagate VAR through phis on edge E. */
406 propagate_through_phis (tree var
, edge e
)
408 basic_block dest
= e
->dest
;
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
);
420 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
421 added to the start of RET. */
424 find_tail_calls (basic_block bb
, struct tailcall
**ret
)
426 tree ass_var
= NULL_TREE
, ret_var
, func
, param
;
429 gimple_stmt_iterator gsi
, agsi
;
438 if (!single_succ_p (bb
))
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
))
452 /* Check for a call. */
453 if (is_gimple_call (stmt
))
455 call
= as_a
<gcall
*> (stmt
);
456 ass_var
= gimple_call_lhs (call
);
460 /* If the statement references memory or volatile operands, fail. */
461 if (gimple_references_memory_p (stmt
)
462 || gimple_has_volatile_ops (stmt
))
469 /* Recurse to the predecessors. */
470 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
471 find_tail_calls (e
->src
, ret
);
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
))
490 /* We found the call, check whether it is suitable. */
491 tail_recursion
= false;
492 func
= gimple_call_fndecl (call
);
494 && !DECL_BUILT_IN (func
)
495 && recursive_call_p (current_function_decl
, func
))
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
);
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
),
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
))
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
)))
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. */
552 tree tmp_a
= NULL_TREE
;
553 tree tmp_m
= NULL_TREE
;
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
)
568 if (gimple_code (stmt
) == GIMPLE_RETURN
)
571 if (gimple_clobber_p (stmt
))
574 if (is_gimple_debug (stmt
))
577 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
580 /* This is a gimple assign. */
581 if (! process_assignment (as_a
<gassign
*> (stmt
), gsi
, &tmp_m
,
587 tree type
= TREE_TYPE (tmp_a
);
589 a
= fold_build2 (PLUS_EXPR
, type
, fold_convert (type
, a
), tmp_a
);
595 tree type
= TREE_TYPE (tmp_m
);
597 m
= fold_build2 (MULT_EXPR
, type
, fold_convert (type
, m
), tmp_m
);
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. */
612 && (ret_var
!= ass_var
))
615 /* If this is not a tail recursive call, we cannot handle addends or
617 if (!tail_recursion
&& (m
|| a
))
620 /* For pointers only allow additions. */
621 if (m
&& POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl
))))
624 nw
= XNEW (struct tailcall
);
628 nw
->tail_recursion
= tail_recursion
;
637 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
640 add_successor_phi_arg (edge e
, tree var
, tree phi_arg
)
644 for (gsi
= gsi_start_phis (e
->dest
); !gsi_end_p (gsi
); gsi_next (&gsi
))
645 if (PHI_RESULT (gsi
.phi ()) == var
)
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. */
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
);
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
);
677 if (code
== POINTER_PLUS_EXPR
)
678 tem
= fold_build2 (code
, TREE_TYPE (op1
), op1
, acc
);
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
);
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. */
698 update_accumulator_with_ops (enum tree_code code
, tree acc
, tree op1
,
699 gimple_stmt_iterator gsi
)
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
);
707 tree rhs
= fold_convert (TREE_TYPE (acc
),
710 fold_convert (TREE_TYPE (op1
), acc
),
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
);
720 /* Adjust the accumulator values according to A and M after GSI, and update
721 the phi nodes on edge BACK. */
724 adjust_accumulator_values (gimple_stmt_iterator gsi
, tree m
, tree a
, edge back
)
726 tree var
, a_acc_arg
, m_acc_arg
;
729 m
= force_gimple_operand_gsi (&gsi
, m
, true, NULL
, true, GSI_SAME_STMT
);
731 a
= force_gimple_operand_gsi (&gsi
, a
, true, NULL
, true, GSI_SAME_STMT
);
739 if (integer_onep (a
))
742 var
= adjust_return_value_with_ops (MULT_EXPR
, "acc_tmp", m_acc
,
748 a_acc_arg
= update_accumulator_with_ops (PLUS_EXPR
, a_acc
, var
, gsi
);
752 m_acc_arg
= update_accumulator_with_ops (MULT_EXPR
, m_acc
, m
, gsi
);
755 add_successor_phi_arg (back
, a_acc
, a_acc_arg
);
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
765 adjust_return_value (basic_block bb
, tree m
, tree a
)
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
)
778 retval
= adjust_return_value_with_ops (MULT_EXPR
, "mul_tmp", m_acc
, retval
,
781 retval
= adjust_return_value_with_ops (PLUS_EXPR
, "acc_tmp", a_acc
, retval
,
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
790 decrease_profile (basic_block bb
, gcov_type count
, int frequency
)
796 bb
->frequency
-= frequency
;
797 if (bb
->frequency
< 0)
799 if (!single_succ_p (bb
))
801 gcc_assert (!EDGE_COUNT (bb
->succs
));
804 e
= single_succ_edge (bb
);
810 /* Returns true if argument PARAM of the tail recursive call needs to be copied
811 when the call is eliminated. */
814 arg_needs_copy_p (tree param
)
818 if (!is_gimple_reg (param
))
821 /* Parameters that are only defined but never used need not be copied. */
822 def
= ssa_default_def (cfun
, param
);
829 /* Eliminates tail call described by T. TMP_VARS is a list of
830 temporary variables used to copy the function arguments. */
833 eliminate_tail_call (struct tailcall
*t
)
839 basic_block bb
, first
;
843 gimple_stmt_iterator gsi
;
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 : ",
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
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
)
874 gsi_remove (&gsi
, true);
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
,
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
)),
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
);
897 param
= DECL_CHAIN (param
), idx
++)
899 if (!arg_needs_copy_p (param
))
902 arg
= gimple_call_arg (stmt
, idx
);
904 gcc_assert (param
== SSA_NAME_VAR (PHI_RESULT (phi
)));
906 add_phi_arg (phi
, arg
, e
, gimple_location (stmt
));
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);
926 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
927 mark the tailcalls for the sibcall optimization. */
930 optimize_tail_call (struct tailcall
*t
, bool opt_tailcalls
)
932 if (t
->tail_recursion
)
934 eliminate_tail_call (t
);
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
);
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. */
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
))
968 tree tmp
= make_temp_ssa_name (ret_type
, NULL
, label
);
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
),
975 return PHI_RESULT (phi
);
978 /* Optimizes tail calls in the function, turning the tail recursion
982 tree_optimize_tail_calls_1 (bool opt_tailcalls
)
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
));
993 if (!suitable_for_tail_opt_p ())
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
1002 stmt
= last_stmt (e
->src
);
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
)
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
)))
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
);
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
));
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
,
1047 if (act
->mult
&& !m_acc
)
1048 m_acc
= create_tailcall_accumulator ("mult_acc", first
,
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
);
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
);
1075 && gimple_code (stmt
) == GIMPLE_RETURN
)
1076 adjust_return_value (e
->src
, m_acc
, a_acc
);
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
);
1094 return TODO_cleanup_cfg
| TODO_update_ssa_only_virtuals
;
1099 gate_tail_calls (void)
1101 return flag_optimize_sibling_calls
!= 0 && dbg_cnt (tail_call
);
1105 execute_tail_calls (void)
1107 return tree_optimize_tail_calls_1 (true);
1112 const pass_data pass_data_tail_recursion
=
1114 GIMPLE_PASS
, /* type */
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
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
1145 make_pass_tail_recursion (gcc::context
*ctxt
)
1147 return new pass_tail_recursion (ctxt
);
1152 const pass_data pass_data_tail_calls
=
1154 GIMPLE_PASS
, /* type */
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
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
1181 make_pass_tail_calls (gcc::context
*ctxt
)
1183 return new pass_tail_calls (ctxt
);