1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2025 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 "tree-pass.h"
31 #include "gimple-pretty-print.h"
32 #include "fold-const.h"
33 #include "stor-layout.h"
34 #include "gimple-iterator.h"
35 #include "gimplify-me.h"
37 #include "tree-into-ssa.h"
44 #include "common/common-target.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-live.h"
47 #include "diagnostic-core.h"
48 #include "gimple-range.h"
49 #include "alloc-pool.h"
51 #include "symbol-summary.h"
55 /* The file implements the tail recursion elimination. It is also used to
56 analyze the tail calls in general, passing the results to the rtl level
57 where they are used for sibcall optimization.
59 In addition to the standard tail recursion elimination, we handle the most
60 trivial cases of making the call tail recursive by creating accumulators.
61 For example the following function
66 return n + sum (n - 1);
83 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
84 when we reach the return x statement, we should return a_acc + x * m_acc
85 instead. They are initially initialized to 0 and 1, respectively,
86 so the semantics of the function is obviously preserved. If we are
87 guaranteed that the value of the accumulator never change, we
90 There are three cases how the function may exit. The first one is
91 handled in adjust_return_value, the other two in adjust_accumulator_values
92 (the second case is actually a special case of the third one and we
93 present it separately just for clarity):
95 1) Just return x, where x is not in any of the remaining special shapes.
96 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
98 2) return f (...), where f is the current function, is rewritten in a
99 classical tail-recursion elimination way, into assignment of arguments
100 and jump to the start of the function. Values of the accumulators
103 3) return a + m * f(...), where a and m do not depend on call to f.
104 To preserve the semantics described before we want this to be rewritten
105 in such a way that we finally return
107 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
109 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
110 eliminate the tail call to f. Special cases when the value is just
111 added or just multiplied are obtained by setting a = 0 or m = 1.
113 TODO -- it is possible to do similar tricks for other operations. */
115 /* A structure that describes the tailcall. */
119 /* The iterator pointing to the call statement. */
120 gimple_stmt_iterator call_gsi
;
122 /* True if it is a call to the current function. */
125 /* The return value of the caller is mult * f + add, where f is the return
126 value of the call. */
129 /* Next tailcall in the chain. */
130 struct tailcall
*next
;
133 /* The variables holding the value of multiplicative and additive
135 static tree m_acc
, a_acc
;
137 /* Bitmap with a bit for each function parameter which is set to true if we
138 have to copy the parameter for conversion of tail-recursive calls. */
140 static bitmap tailr_arg_needs_copy
;
142 static void maybe_error_musttail (gcall
*call
, const char *err
);
144 /* Returns false when the function is not suitable for tail call optimization
145 from some reason (e.g. if it takes variable number of arguments). CALL
146 is call to report for. */
149 suitable_for_tail_opt_p (gcall
*call
)
153 maybe_error_musttail (call
, _("caller uses stdargs"));
160 /* Returns false when the function is not suitable for tail call optimization
161 for some reason (e.g. if it takes variable number of arguments).
162 This test must pass in addition to suitable_for_tail_opt_p in order to make
163 tail call discovery happen. CALL is call to report error for. */
166 suitable_for_tail_call_opt_p (gcall
*call
)
170 /* alloca (until we have stack slot life analysis) inhibits
171 sibling call optimizations, but not tail recursion. */
172 if (cfun
->calls_alloca
)
174 maybe_error_musttail (call
, _("caller uses alloca"));
178 /* If we are using sjlj exceptions, we may need to add a call to
179 _Unwind_SjLj_Unregister at exit of the function. Which means
180 that we cannot do any sibcall transformations. */
181 if (targetm_common
.except_unwind_info (&global_options
) == UI_SJLJ
182 && current_function_has_exception_handlers ())
184 maybe_error_musttail (call
, _("caller uses sjlj exceptions"));
188 /* Any function that calls setjmp might have longjmp called from
189 any called function. ??? We really should represent this
190 properly in the CFG so that this needn't be special cased. */
191 if (cfun
->calls_setjmp
)
193 maybe_error_musttail (call
, _("caller uses setjmp"));
197 /* Various targets don't handle tail calls correctly in functions
198 that call __builtin_eh_return. */
199 if (cfun
->calls_eh_return
)
201 maybe_error_musttail (call
, _("caller uses __builtin_eh_return"));
205 /* ??? It is OK if the argument of a function is taken in some cases,
206 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
207 for (param
= DECL_ARGUMENTS (current_function_decl
);
209 param
= DECL_CHAIN (param
))
210 if (TREE_ADDRESSABLE (param
))
212 maybe_error_musttail (call
, _("address of caller arguments taken"));
219 /* Checks whether the expression EXPR in stmt AT is independent of the
220 statement pointed to by GSI (in a sense that we already know EXPR's value
221 at GSI). We use the fact that we are only called from the chain of
222 basic blocks that have only single successor. Returns the expression
223 containing the value of EXPR at GSI. */
226 independent_of_stmt_p (tree expr
, gimple
*at
, gimple_stmt_iterator gsi
,
229 basic_block bb
, call_bb
, at_bb
;
233 if (is_gimple_min_invariant (expr
))
236 if (TREE_CODE (expr
) != SSA_NAME
)
239 if (bitmap_bit_p (to_move
, SSA_NAME_VERSION (expr
)))
242 /* Mark the blocks in the chain leading to the end. */
243 at_bb
= gimple_bb (at
);
244 call_bb
= gimple_bb (gsi_stmt (gsi
));
245 for (bb
= call_bb
; bb
!= at_bb
; bb
= single_succ (bb
))
251 at
= SSA_NAME_DEF_STMT (expr
);
254 /* The default definition or defined before the chain. */
260 for (; !gsi_end_p (gsi
); gsi_next (&gsi
))
261 if (gsi_stmt (gsi
) == at
)
264 if (!gsi_end_p (gsi
))
269 if (gimple_code (at
) != GIMPLE_PHI
)
275 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
280 expr
= PHI_ARG_DEF_FROM_EDGE (at
, e
);
281 if (TREE_CODE (expr
) != SSA_NAME
)
283 /* The value is a constant. */
288 /* Unmark the blocks. */
289 for (bb
= call_bb
; bb
!= at_bb
; bb
= single_succ (bb
))
296 enum par
{ FAIL
, OK
, TRY_MOVE
};
298 /* Simulates the effect of an assignment STMT on the return value of the tail
299 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
300 additive factor for the real return value. */
303 process_assignment (gassign
*stmt
,
304 gimple_stmt_iterator call
, tree
*m
,
305 tree
*a
, tree
*ass_var
, bitmap to_move
)
307 tree op0
, op1
= NULL_TREE
, non_ass_var
= NULL_TREE
;
308 tree dest
= gimple_assign_lhs (stmt
);
309 enum tree_code code
= gimple_assign_rhs_code (stmt
);
310 enum gimple_rhs_class rhs_class
= get_gimple_rhs_class (code
);
311 tree src_var
= gimple_assign_rhs1 (stmt
);
313 /* See if this is a simple copy operation of an SSA name to the function
314 result. In that case we may have a simple tail call. Ignore type
315 conversions that can never produce extra code between the function
316 call and the function return. */
317 if ((rhs_class
== GIMPLE_SINGLE_RHS
|| gimple_assign_cast_p (stmt
))
318 && src_var
== *ass_var
)
320 /* Reject a tailcall if the type conversion might need
322 if (gimple_assign_cast_p (stmt
))
324 if (TYPE_MODE (TREE_TYPE (dest
)) != TYPE_MODE (TREE_TYPE (src_var
)))
327 /* Even if the type modes are the same, if the precision of the
328 type is smaller than mode's precision,
329 reduce_to_bit_field_precision would generate additional code. */
330 if (INTEGRAL_TYPE_P (TREE_TYPE (dest
))
331 && !type_has_mode_precision_p (TREE_TYPE (dest
)))
341 case GIMPLE_BINARY_RHS
:
342 op1
= gimple_assign_rhs2 (stmt
);
346 case GIMPLE_UNARY_RHS
:
347 op0
= gimple_assign_rhs1 (stmt
);
354 /* Accumulator optimizations will reverse the order of operations.
355 We can only do that for floating-point types if we're assuming
356 that addition and multiplication are associative. */
357 if (!flag_associative_math
)
358 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl
))))
361 if (rhs_class
== GIMPLE_UNARY_RHS
364 else if (op0
== *ass_var
365 && (non_ass_var
= independent_of_stmt_p (op1
, stmt
, call
,
370 && (non_ass_var
= independent_of_stmt_p (op0
, stmt
, call
,
383 case POINTER_PLUS_EXPR
:
396 *m
= build_minus_one_cst (TREE_TYPE (op0
));
402 *a
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (non_ass_var
), non_ass_var
);
405 *m
= build_minus_one_cst (TREE_TYPE (non_ass_var
));
406 *a
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (non_ass_var
), non_ass_var
);
417 /* Propagate VAR through phis on edge E. */
420 propagate_through_phis (tree var
, edge e
)
422 basic_block dest
= e
->dest
;
425 for (gsi
= gsi_start_phis (dest
); !gsi_end_p (gsi
); gsi_next (&gsi
))
427 gphi
*phi
= gsi
.phi ();
428 if (PHI_ARG_DEF_FROM_EDGE (phi
, e
) == var
)
429 return PHI_RESULT (phi
);
434 /* Report an error for failing to tail convert must call CALL
435 with error message ERR. Also clear the flag to prevent further
439 maybe_error_musttail (gcall
*call
, const char *err
)
441 if (gimple_call_must_tail_p (call
))
443 error_at (call
->location
, "cannot tail-call: %s", err
);
444 /* Avoid another error. ??? If there are multiple reasons why tail
445 calls fail it might be useful to report them all to avoid
446 whack-a-mole for the user. But currently there is too much
447 redundancy in the reporting, so keep it simple. */
448 gimple_call_set_must_tail (call
, false); /* Avoid another error. */
449 gimple_call_set_tail (call
, false);
453 print_gimple_stmt (dump_file
, call
, 0, TDF_SLIM
);
454 fprintf (dump_file
, "Cannot convert: %s\n", err
);
458 /* Argument for compute_live_vars/live_vars_at_stmt and what compute_live_vars
459 returns. Computed lazily, but just once for the function. */
460 static live_vars_map
*live_vars
;
461 static vec
<bitmap_head
> live_vars_vec
;
463 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
464 added to the start of RET. When ONLY_MUSTTAIL is set only handle musttail.
465 Update OPT_TAILCALLS as output parameter. */
468 find_tail_calls (basic_block bb
, struct tailcall
**ret
, bool only_musttail
,
471 tree ass_var
= NULL_TREE
, ret_var
, func
, param
;
474 gimple_stmt_iterator gsi
, agsi
;
483 if (!single_succ_p (bb
))
485 /* If there is an abnormal edge assume it's the only extra one.
486 Tolerate that case so that we can give better error messages
487 for musttail later. */
488 if (!has_abnormal_or_eh_outgoing_edge_p (bb
))
491 fprintf (dump_file
, "Basic block %d has extra exit edges\n",
495 if (!cfun
->has_musttail
)
499 bool bad_stmt
= false;
500 gimple
*last_stmt
= nullptr;
501 for (gsi
= gsi_last_bb (bb
); !gsi_end_p (gsi
); gsi_prev (&gsi
))
503 stmt
= gsi_stmt (gsi
);
505 /* Ignore labels, returns, nops, clobbers and debug stmts. */
506 if (gimple_code (stmt
) == GIMPLE_LABEL
507 || gimple_code (stmt
) == GIMPLE_RETURN
508 || gimple_code (stmt
) == GIMPLE_NOP
509 || gimple_code (stmt
) == GIMPLE_PREDICT
510 || gimple_clobber_p (stmt
)
511 || is_gimple_debug (stmt
))
516 /* Check for a call. */
517 if (is_gimple_call (stmt
))
519 call
= as_a
<gcall
*> (stmt
);
520 /* Handle only musttail calls when not optimizing. */
521 if (only_musttail
&& !gimple_call_must_tail_p (call
))
525 maybe_error_musttail (call
,
526 _("memory reference or volatile after "
530 ass_var
= gimple_call_lhs (call
);
534 /* Allow simple copies between local variables, even if they're
536 if (is_gimple_assign (stmt
)
537 && auto_var_in_fn_p (gimple_assign_lhs (stmt
), cfun
->decl
)
538 && auto_var_in_fn_p (gimple_assign_rhs1 (stmt
), cfun
->decl
))
541 /* If the statement references memory or volatile operands, fail. */
542 if (gimple_references_memory_p (stmt
)
543 || gimple_has_volatile_ops (stmt
))
547 fprintf (dump_file
, "Cannot handle ");
548 print_gimple_stmt (dump_file
, stmt
, 0);
551 if (!cfun
->has_musttail
)
562 /* Recurse to the predecessors. */
563 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
564 find_tail_calls (e
->src
, ret
, only_musttail
, opt_tailcalls
);
569 if (!suitable_for_tail_opt_p (call
))
572 if (!suitable_for_tail_call_opt_p (call
))
573 opt_tailcalls
= false;
575 /* If the LHS of our call is not just a simple register or local
576 variable, we can't transform this into a tail or sibling call.
577 This situation happens, in (e.g.) "*p = foo()" where foo returns a
578 struct. In this case we won't have a temporary here, but we need
579 to carry out the side effect anyway, so tailcall is impossible.
581 ??? In some situations (when the struct is returned in memory via
582 invisible argument) we could deal with this, e.g. by passing 'p'
583 itself as that argument to foo, but it's too early to do this here,
584 and expand_call() will not handle it anyway. If it ever can, then
585 we need to revisit this here, to allow that situation. */
587 && !is_gimple_reg (ass_var
)
588 && !auto_var_in_fn_p (ass_var
, cfun
->decl
))
590 maybe_error_musttail (call
, _("return value in memory"));
594 if (cfun
->calls_setjmp
)
596 maybe_error_musttail (call
, _("caller uses setjmp"));
600 /* If the call might throw an exception that wouldn't propagate out of
601 cfun, we can't transform to a tail or sibling call (82081). */
602 if ((stmt_could_throw_p (cfun
, stmt
)
603 && !stmt_can_throw_external (cfun
, stmt
)) || !single_succ_p (bb
))
605 if (stmt
== last_stmt
)
606 maybe_error_musttail (call
,
607 _("call may throw exception that does not "
610 maybe_error_musttail (call
, _("code between call and return"));
614 /* If the function returns a value, then at present, the tail call
615 must return the same type of value. There is conceptually a copy
616 between the object returned by the tail call candidate and the
617 object returned by CFUN itself.
619 This means that if we have:
621 lhs = f (&<retval>); // f reads from <retval>
622 // (lhs is usually also <retval>)
624 there is a copy between the temporary object returned by f and lhs,
625 meaning that any use of <retval> in f occurs before the assignment
626 to lhs begins. Thus the <retval> that is live on entry to the call
627 to f is really an independent local variable V that happens to be
628 stored in the RESULT_DECL rather than a local VAR_DECL.
630 Turning this into a tail call would remove the copy and make the
631 lifetimes of the return value and V overlap. The same applies to
632 tail recursion, since if f can read from <retval>, we have to assume
633 that CFUN might already have written to <retval> before the call.
635 The problem doesn't apply when <retval> is passed by value, but that
636 isn't a case we handle anyway. */
637 tree result_decl
= DECL_RESULT (cfun
->decl
);
639 && may_be_aliased (result_decl
)
640 && ref_maybe_used_by_stmt_p (call
, result_decl
, false))
642 maybe_error_musttail (call
, _("return value used after call"));
646 /* We found the call, check whether it is suitable. */
647 tail_recursion
= false;
648 func
= gimple_call_fndecl (call
);
650 && !fndecl_built_in_p (func
)
651 && recursive_call_p (current_function_decl
, func
)
656 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
657 param
&& idx
< gimple_call_num_args (call
);
658 param
= DECL_CHAIN (param
), idx
++)
660 arg
= gimple_call_arg (call
, idx
);
663 /* Make sure there are no problems with copying. The parameter
664 have a copyable type and the two arguments must have reasonably
665 equivalent types. The latter requirement could be relaxed if
666 we emitted a suitable type conversion statement. */
667 if (!is_gimple_reg_type (TREE_TYPE (param
))
668 || !useless_type_conversion_p (TREE_TYPE (param
),
672 /* The parameter should be a real operand, so that phi node
673 created for it at the start of the function has the meaning
674 of copying the value. This test implies is_gimple_reg_type
675 from the previous condition, however this one could be
676 relaxed by being more careful with copying the new value
677 of the parameter (emitting appropriate GIMPLE_ASSIGN and
678 updating the virtual operands). */
679 if (!is_gimple_reg (param
))
683 if (idx
== gimple_call_num_args (call
) && !param
)
684 tail_recursion
= true;
687 /* Compute live vars if not computed yet. */
688 if (live_vars
== NULL
)
690 unsigned int cnt
= 0;
691 FOR_EACH_LOCAL_DECL (cfun
, idx
, var
)
693 && auto_var_in_fn_p (var
, cfun
->decl
)
694 && may_be_aliased (var
))
696 if (live_vars
== NULL
)
697 live_vars
= new live_vars_map
;
698 live_vars
->put (DECL_UID (var
), cnt
++);
701 live_vars_vec
= compute_live_vars (cfun
, live_vars
);
704 /* Determine a bitmap of variables which are still in scope after the
706 bitmap local_live_vars
= NULL
;
708 local_live_vars
= live_vars_at_stmt (live_vars_vec
, live_vars
, call
);
710 /* Make sure the tail invocation of this function does not indirectly
711 refer to local variables. (Passing variables directly by value
713 FOR_EACH_LOCAL_DECL (cfun
, idx
, var
)
715 if (TREE_CODE (var
) != PARM_DECL
716 && auto_var_in_fn_p (var
, cfun
->decl
)
717 && may_be_aliased (var
)
718 && (ref_maybe_used_by_stmt_p (call
, var
, false)
719 || call_may_clobber_ref_p (call
, var
, false)))
724 BITMAP_FREE (local_live_vars
);
725 maybe_error_musttail (call
,
726 _("call invocation refers to locals"));
731 unsigned int *v
= live_vars
->get (DECL_UID (var
));
732 if (bitmap_bit_p (local_live_vars
, *v
))
734 BITMAP_FREE (local_live_vars
);
735 maybe_error_musttail (call
,
736 _("call invocation refers to locals"));
744 BITMAP_FREE (local_live_vars
);
746 /* Now check the statements after the call. None of them has virtual
747 operands, so they may only depend on the call through its return
748 value. The return value should also be dependent on each of them,
749 since we are running after dce. */
752 auto_bitmap to_move_defs
;
753 auto_vec
<gimple
*> to_move_stmts
;
759 tree tmp_a
= NULL_TREE
;
760 tree tmp_m
= NULL_TREE
;
763 while (gsi_end_p (agsi
))
765 ass_var
= propagate_through_phis (ass_var
, single_succ_edge (abb
));
766 abb
= single_succ (abb
);
767 agsi
= gsi_start_bb (abb
);
770 stmt
= gsi_stmt (agsi
);
771 if (gimple_code (stmt
) == GIMPLE_RETURN
)
774 if (gimple_code (stmt
) == GIMPLE_LABEL
775 || gimple_code (stmt
) == GIMPLE_NOP
776 || gimple_code (stmt
) == GIMPLE_PREDICT
777 || gimple_clobber_p (stmt
)
778 || is_gimple_debug (stmt
))
781 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
783 maybe_error_musttail (call
, _("unhandled code after call"));
787 /* This is a gimple assign. */
788 par ret
= process_assignment (as_a
<gassign
*> (stmt
), gsi
,
789 &tmp_m
, &tmp_a
, &ass_var
, to_move_defs
);
790 if (ret
== FAIL
|| (ret
== TRY_MOVE
&& !tail_recursion
))
792 maybe_error_musttail (call
, _("return value changed after call"));
795 else if (ret
== TRY_MOVE
)
797 /* Do not deal with checking dominance, the real fix is to
798 do path isolation for the transform phase anyway, removing
799 the need to compute the accumulators with new stmts. */
802 for (unsigned opno
= 1; opno
< gimple_num_ops (stmt
); ++opno
)
804 tree op
= gimple_op (stmt
, opno
);
805 if (independent_of_stmt_p (op
, stmt
, gsi
, to_move_defs
) != op
)
808 bitmap_set_bit (to_move_defs
,
809 SSA_NAME_VERSION (gimple_assign_lhs (stmt
)));
810 to_move_stmts
.safe_push (stmt
);
816 tree type
= TREE_TYPE (tmp_a
);
818 a
= fold_build2 (PLUS_EXPR
, type
, fold_convert (type
, a
), tmp_a
);
824 tree type
= TREE_TYPE (tmp_m
);
826 m
= fold_build2 (MULT_EXPR
, type
, fold_convert (type
, m
), tmp_m
);
831 a
= fold_build2 (MULT_EXPR
, type
, fold_convert (type
, a
), tmp_m
);
835 /* See if this is a tail call we can handle. */
836 ret_var
= gimple_return_retval (as_a
<greturn
*> (stmt
));
838 /* We may proceed if there either is no return value, or the return value
839 is identical to the call's return or if the return decl is an empty type
840 variable and the call's return was not assigned. */
842 && (ret_var
!= ass_var
843 && !(is_empty_type (TREE_TYPE (ret_var
)) && !ass_var
)))
848 /* If IPA-VRP proves called function always returns a singleton range,
849 the return value is replaced by the only value in that range.
850 For tail call purposes, pretend such replacement didn't happen. */
851 if (ass_var
== NULL_TREE
853 && TREE_CONSTANT (ret_var
))
854 if (tree type
= gimple_range_type (call
))
855 if (tree callee
= gimple_call_fndecl (call
))
856 if ((INTEGRAL_TYPE_P (type
) || SCALAR_FLOAT_TYPE_P (type
))
857 && useless_type_conversion_p (TREE_TYPE (TREE_TYPE (callee
)),
859 && useless_type_conversion_p (TREE_TYPE (ret_var
), type
)
860 && ipa_return_value_range (val
, callee
)
861 && val
.singleton_p (&valr
)
862 && operand_equal_p (ret_var
, valr
, 0))
866 maybe_error_musttail (call
,
867 _("call and return value are different"));
872 /* If this is not a tail recursive call, we cannot handle addends or
874 if (!tail_recursion
&& (m
|| a
))
876 maybe_error_musttail (call
,
877 _("operations after non tail recursive call"));
881 /* For pointers only allow additions. */
882 if (m
&& POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl
))))
884 maybe_error_musttail (call
,
885 _("tail recursion with pointers can only use "
890 /* Move queued defs. */
894 FOR_EACH_VEC_ELT (to_move_stmts
, i
, stmt
)
896 gimple_stmt_iterator mgsi
= gsi_for_stmt (stmt
);
897 gsi_move_before (&mgsi
, &gsi
);
899 if (!tailr_arg_needs_copy
)
900 tailr_arg_needs_copy
= BITMAP_ALLOC (NULL
);
901 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
903 param
= DECL_CHAIN (param
), idx
++)
905 tree ddef
, arg
= gimple_call_arg (call
, idx
);
906 if (is_gimple_reg (param
)
907 && (ddef
= ssa_default_def (cfun
, param
))
909 bitmap_set_bit (tailr_arg_needs_copy
, idx
);
913 nw
= XNEW (struct tailcall
);
917 nw
->tail_recursion
= tail_recursion
;
926 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
929 add_successor_phi_arg (edge e
, tree var
, tree phi_arg
)
933 for (gsi
= gsi_start_phis (e
->dest
); !gsi_end_p (gsi
); gsi_next (&gsi
))
934 if (PHI_RESULT (gsi
.phi ()) == var
)
937 gcc_assert (!gsi_end_p (gsi
));
938 add_phi_arg (gsi
.phi (), phi_arg
, e
, UNKNOWN_LOCATION
);
941 /* Creates a GIMPLE statement which computes the operation specified by
942 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
943 statement in the position specified by GSI. Returns the
944 tree node of the statement's result. */
947 adjust_return_value_with_ops (enum tree_code code
, const char *label
,
948 tree acc
, tree op1
, gimple_stmt_iterator gsi
)
951 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
952 tree result
= make_temp_ssa_name (ret_type
, NULL
, label
);
955 if (POINTER_TYPE_P (ret_type
))
957 gcc_assert (code
== PLUS_EXPR
&& TREE_TYPE (acc
) == sizetype
);
958 code
= POINTER_PLUS_EXPR
;
960 if (types_compatible_p (TREE_TYPE (acc
), TREE_TYPE (op1
))
961 && code
!= POINTER_PLUS_EXPR
)
962 stmt
= gimple_build_assign (result
, code
, acc
, op1
);
966 if (code
== POINTER_PLUS_EXPR
)
967 tem
= fold_build2 (code
, TREE_TYPE (op1
), op1
, acc
);
969 tem
= fold_build2 (code
, TREE_TYPE (op1
),
970 fold_convert (TREE_TYPE (op1
), acc
), op1
);
971 tree rhs
= fold_convert (ret_type
, tem
);
972 rhs
= force_gimple_operand_gsi (&gsi
, rhs
,
973 false, NULL
, true, GSI_SAME_STMT
);
974 stmt
= gimple_build_assign (result
, rhs
);
977 gsi_insert_before (&gsi
, stmt
, GSI_NEW_STMT
);
981 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
982 the computation specified by CODE and OP1 and insert the statement
983 at the position specified by GSI as a new statement. Returns new SSA name
984 of updated accumulator. */
987 update_accumulator_with_ops (enum tree_code code
, tree acc
, tree op1
,
988 gimple_stmt_iterator gsi
)
991 tree var
= copy_ssa_name (acc
);
992 if (types_compatible_p (TREE_TYPE (acc
), TREE_TYPE (op1
)))
993 stmt
= gimple_build_assign (var
, code
, acc
, op1
);
996 tree rhs
= fold_convert (TREE_TYPE (acc
),
999 fold_convert (TREE_TYPE (op1
), acc
),
1001 rhs
= force_gimple_operand_gsi (&gsi
, rhs
,
1002 false, NULL
, false, GSI_CONTINUE_LINKING
);
1003 stmt
= gimple_build_assign (var
, rhs
);
1005 gsi_insert_after (&gsi
, stmt
, GSI_NEW_STMT
);
1009 /* Adjust the accumulator values according to A and M after GSI, and update
1010 the phi nodes on edge BACK. */
1013 adjust_accumulator_values (gimple_stmt_iterator gsi
, tree m
, tree a
, edge back
)
1015 tree var
, a_acc_arg
, m_acc_arg
;
1018 m
= force_gimple_operand_gsi (&gsi
, m
, true, NULL
, true, GSI_SAME_STMT
);
1020 a
= force_gimple_operand_gsi (&gsi
, a
, true, NULL
, true, GSI_SAME_STMT
);
1028 if (integer_onep (a
))
1031 var
= adjust_return_value_with_ops (MULT_EXPR
, "acc_tmp", m_acc
,
1037 a_acc_arg
= update_accumulator_with_ops (PLUS_EXPR
, a_acc
, var
, gsi
);
1041 m_acc_arg
= update_accumulator_with_ops (MULT_EXPR
, m_acc
, m
, gsi
);
1044 add_successor_phi_arg (back
, a_acc
, a_acc_arg
);
1047 add_successor_phi_arg (back
, m_acc
, m_acc_arg
);
1050 /* Adjust value of the return at the end of BB according to M and A
1054 adjust_return_value (basic_block bb
, tree m
, tree a
)
1057 greturn
*ret_stmt
= as_a
<greturn
*> (gimple_seq_last_stmt (bb_seq (bb
)));
1058 gimple_stmt_iterator gsi
= gsi_last_bb (bb
);
1060 gcc_assert (gimple_code (ret_stmt
) == GIMPLE_RETURN
);
1062 retval
= gimple_return_retval (ret_stmt
);
1063 if (!retval
|| retval
== error_mark_node
)
1067 retval
= adjust_return_value_with_ops (MULT_EXPR
, "mul_tmp", m_acc
, retval
,
1070 retval
= adjust_return_value_with_ops (PLUS_EXPR
, "acc_tmp", a_acc
, retval
,
1072 gimple_return_set_retval (ret_stmt
, retval
);
1073 update_stmt (ret_stmt
);
1076 /* Subtract COUNT and FREQUENCY from the basic block and it's
1079 decrease_profile (basic_block bb
, profile_count count
)
1081 bb
->count
= bb
->count
- count
;
1082 if (!single_succ_p (bb
))
1084 gcc_assert (!EDGE_COUNT (bb
->succs
));
1089 /* Eliminates tail call described by T. TMP_VARS is a list of
1090 temporary variables used to copy the function arguments.
1091 Allocates *NEW_LOOP if not already done and initializes it. */
1094 eliminate_tail_call (struct tailcall
*t
, class loop
*&new_loop
)
1097 gimple
*stmt
, *call
;
1100 basic_block bb
, first
;
1104 gimple_stmt_iterator gsi
;
1107 stmt
= orig_stmt
= gsi_stmt (t
->call_gsi
);
1108 bb
= gsi_bb (t
->call_gsi
);
1110 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1112 fprintf (dump_file
, "Eliminated tail recursion in bb %d : ",
1114 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
1115 fprintf (dump_file
, "\n");
1118 gcc_assert (is_gimple_call (stmt
));
1120 first
= single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
1122 /* Remove the code after call_gsi that will become unreachable. The
1123 possibly unreachable code in other blocks is removed later in
1126 gimple_stmt_iterator gsi2
= gsi_last_bb (gimple_bb (gsi_stmt (gsi
)));
1127 while (gsi_stmt (gsi2
) != gsi_stmt (gsi
))
1129 gimple
*t
= gsi_stmt (gsi2
);
1130 /* Do not remove the return statement, so that redirect_edge_and_branch
1131 sees how the block ends. */
1132 if (gimple_code (t
) != GIMPLE_RETURN
)
1134 gimple_stmt_iterator gsi3
= gsi2
;
1136 gsi_remove (&gsi3
, true);
1143 /* Number of executions of function has reduced by the tailcall. */
1144 e
= single_succ_edge (gsi_bb (t
->call_gsi
));
1146 profile_count count
= e
->count ();
1148 /* When profile is inconsistent and the recursion edge is more frequent
1149 than number of executions of functions, scale it down, so we do not end
1150 up with 0 executions of entry block. */
1151 if (count
>= ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
)
1152 count
= ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
.apply_scale (7, 8);
1153 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun
), count
);
1154 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun
), count
);
1155 if (e
->dest
!= EXIT_BLOCK_PTR_FOR_FN (cfun
))
1156 decrease_profile (e
->dest
, count
);
1158 /* Replace the call by a jump to the start of function. */
1159 e
= redirect_edge_and_branch (single_succ_edge (gsi_bb (t
->call_gsi
)),
1162 PENDING_STMT (e
) = NULL
;
1164 /* Add the new loop. */
1167 new_loop
= alloc_loop ();
1168 new_loop
->header
= first
;
1169 new_loop
->finite_p
= true;
1172 gcc_assert (new_loop
->header
== first
);
1174 /* Add phi node entries for arguments. The ordering of the phi nodes should
1175 be the same as the ordering of the arguments. */
1176 for (param
= DECL_ARGUMENTS (current_function_decl
),
1177 idx
= 0, gpi
= gsi_start_phis (first
);
1179 param
= DECL_CHAIN (param
), idx
++)
1181 if (!bitmap_bit_p (tailr_arg_needs_copy
, idx
))
1184 arg
= gimple_call_arg (stmt
, idx
);
1186 gcc_assert (param
== SSA_NAME_VAR (PHI_RESULT (phi
)));
1188 add_phi_arg (phi
, arg
, e
, gimple_location (stmt
));
1192 /* Update the values of accumulators. */
1193 adjust_accumulator_values (t
->call_gsi
, t
->mult
, t
->add
, e
);
1195 call
= gsi_stmt (t
->call_gsi
);
1196 rslt
= gimple_call_lhs (call
);
1197 if (rslt
!= NULL_TREE
&& TREE_CODE (rslt
) == SSA_NAME
)
1199 /* Result of the call will no longer be defined. So adjust the
1200 SSA_NAME_DEF_STMT accordingly. */
1201 SSA_NAME_DEF_STMT (rslt
) = gimple_build_nop ();
1204 gsi_remove (&t
->call_gsi
, true);
1205 release_defs (call
);
1208 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
1209 mark the tailcalls for the sibcall optimization. */
1212 optimize_tail_call (struct tailcall
*t
, bool opt_tailcalls
,
1213 class loop
*&new_loop
)
1215 if (t
->tail_recursion
)
1217 eliminate_tail_call (t
, new_loop
);
1223 gcall
*stmt
= as_a
<gcall
*> (gsi_stmt (t
->call_gsi
));
1225 gimple_call_set_tail (stmt
, true);
1226 cfun
->tail_call_marked
= true;
1227 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1229 fprintf (dump_file
, "Found tail call ");
1230 print_gimple_stmt (dump_file
, stmt
, 0, dump_flags
);
1231 fprintf (dump_file
, " in bb %i\n", (gsi_bb (t
->call_gsi
))->index
);
1238 /* Creates a tail-call accumulator of the same type as the return type of the
1239 current function. LABEL is the name used to creating the temporary
1240 variable for the accumulator. The accumulator will be inserted in the
1241 phis of a basic block BB with single predecessor with an initial value
1242 INIT converted to the current function return type. */
1245 create_tailcall_accumulator (const char *label
, basic_block bb
, tree init
)
1247 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
1248 if (POINTER_TYPE_P (ret_type
))
1249 ret_type
= sizetype
;
1251 tree tmp
= make_temp_ssa_name (ret_type
, NULL
, label
);
1254 phi
= create_phi_node (tmp
, bb
);
1255 add_phi_arg (phi
, init
, single_pred_edge (bb
),
1257 return PHI_RESULT (phi
);
1260 /* Optimizes tail calls in the function, turning the tail recursion
1261 into iteration. When ONLY_MUSTCALL is true only optimize mustcall
1265 tree_optimize_tail_calls_1 (bool opt_tailcalls
, bool only_mustcall
)
1268 bool phis_constructed
= false;
1269 struct tailcall
*tailcalls
= NULL
, *act
, *next
;
1270 bool changed
= false;
1271 basic_block first
= single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
1275 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
1277 /* Only traverse the normal exits, i.e. those that end with return
1279 if (safe_is_a
<greturn
*> (*gsi_last_bb (e
->src
)))
1280 find_tail_calls (e
->src
, &tailcalls
, only_mustcall
, opt_tailcalls
);
1285 destroy_live_vars (live_vars_vec
);
1290 /* Construct the phi nodes and accumulators if necessary. */
1291 a_acc
= m_acc
= NULL_TREE
;
1292 for (act
= tailcalls
; act
; act
= act
->next
)
1294 if (!act
->tail_recursion
)
1297 if (!phis_constructed
)
1299 /* Ensure that there is only one predecessor of the block
1300 or if there are existing degenerate PHI nodes. */
1301 if (!single_pred_p (first
)
1302 || !gimple_seq_empty_p (phi_nodes (first
)))
1304 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun
)));
1306 /* Copy the args if needed. */
1308 for (param
= DECL_ARGUMENTS (current_function_decl
), idx
= 0;
1310 param
= DECL_CHAIN (param
), idx
++)
1311 if (bitmap_bit_p (tailr_arg_needs_copy
, idx
))
1313 tree name
= ssa_default_def (cfun
, param
);
1314 tree new_name
= make_ssa_name (param
, SSA_NAME_DEF_STMT (name
));
1317 set_ssa_default_def (cfun
, param
, new_name
);
1318 phi
= create_phi_node (name
, first
);
1319 add_phi_arg (phi
, new_name
, single_pred_edge (first
),
1320 EXPR_LOCATION (param
));
1322 phis_constructed
= true;
1324 tree ret_type
= TREE_TYPE (DECL_RESULT (current_function_decl
));
1325 if (POINTER_TYPE_P (ret_type
))
1326 ret_type
= sizetype
;
1328 if (act
->add
&& !a_acc
)
1329 a_acc
= create_tailcall_accumulator ("add_acc", first
,
1330 build_zero_cst (ret_type
));
1332 if (act
->mult
&& !m_acc
)
1333 m_acc
= create_tailcall_accumulator ("mult_acc", first
,
1334 build_one_cst (ret_type
));
1339 /* When the tail call elimination using accumulators is performed,
1340 statements adding the accumulated value are inserted at all exits.
1341 This turns all other tail calls to non-tail ones. */
1342 opt_tailcalls
= false;
1345 class loop
*new_loop
= NULL
;
1346 for (; tailcalls
; tailcalls
= next
)
1348 next
= tailcalls
->next
;
1349 changed
|= optimize_tail_call (tailcalls
, opt_tailcalls
, new_loop
);
1353 add_loop (new_loop
, loops_for_fn (cfun
)->tree_root
);
1357 /* Modify the remaining return statements. */
1358 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
1360 if (safe_is_a
<greturn
*> (*gsi_last_bb (e
->src
)))
1361 adjust_return_value (e
->src
, m_acc
, a_acc
);
1366 free_dominance_info (CDI_DOMINATORS
);
1368 /* Add phi nodes for the virtual operands defined in the function to the
1369 header of the loop created by tail recursion elimination. Do so
1370 by triggering the SSA renamer. */
1371 if (phis_constructed
)
1372 mark_virtual_operands_for_renaming (cfun
);
1374 if (tailr_arg_needs_copy
)
1375 BITMAP_FREE (tailr_arg_needs_copy
);
1378 return TODO_cleanup_cfg
| TODO_update_ssa_only_virtuals
;
1383 gate_tail_calls (void)
1385 return flag_optimize_sibling_calls
!= 0 && dbg_cnt (tail_call
);
1389 execute_tail_calls (void)
1391 return tree_optimize_tail_calls_1 (true, false);
1396 const pass_data pass_data_tail_recursion
=
1398 GIMPLE_PASS
, /* type */
1400 OPTGROUP_NONE
, /* optinfo_flags */
1401 TV_NONE
, /* tv_id */
1402 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1403 0, /* properties_provided */
1404 0, /* properties_destroyed */
1405 0, /* todo_flags_start */
1406 0, /* todo_flags_finish */
1409 class pass_tail_recursion
: public gimple_opt_pass
1412 pass_tail_recursion (gcc::context
*ctxt
)
1413 : gimple_opt_pass (pass_data_tail_recursion
, ctxt
)
1416 /* opt_pass methods: */
1417 opt_pass
* clone () final override
1419 return new pass_tail_recursion (m_ctxt
);
1421 bool gate (function
*) final override
{ return gate_tail_calls (); }
1422 unsigned int execute (function
*) final override
1424 return tree_optimize_tail_calls_1 (false, false);
1427 }; // class pass_tail_recursion
1432 make_pass_tail_recursion (gcc::context
*ctxt
)
1434 return new pass_tail_recursion (ctxt
);
1439 const pass_data pass_data_tail_calls
=
1441 GIMPLE_PASS
, /* type */
1443 OPTGROUP_NONE
, /* optinfo_flags */
1444 TV_NONE
, /* tv_id */
1445 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1446 0, /* properties_provided */
1447 0, /* properties_destroyed */
1448 0, /* todo_flags_start */
1449 0, /* todo_flags_finish */
1452 class pass_tail_calls
: public gimple_opt_pass
1455 pass_tail_calls (gcc::context
*ctxt
)
1456 : gimple_opt_pass (pass_data_tail_calls
, ctxt
)
1459 /* opt_pass methods: */
1460 bool gate (function
*) final override
{ return gate_tail_calls (); }
1461 unsigned int execute (function
*) final override
1463 return execute_tail_calls ();
1466 }; // class pass_tail_calls
1471 make_pass_tail_calls (gcc::context
*ctxt
)
1473 return new pass_tail_calls (ctxt
);
1478 const pass_data pass_data_musttail
=
1480 GIMPLE_PASS
, /* type */
1481 "musttail", /* name */
1482 OPTGROUP_NONE
, /* optinfo_flags */
1483 TV_NONE
, /* tv_id */
1484 ( PROP_cfg
| PROP_ssa
), /* properties_required */
1485 0, /* properties_provided */
1486 0, /* properties_destroyed */
1487 0, /* todo_flags_start */
1488 0, /* todo_flags_finish */
1491 class pass_musttail
: public gimple_opt_pass
1494 pass_musttail (gcc::context
*ctxt
)
1495 : gimple_opt_pass (pass_data_musttail
, ctxt
)
1498 /* opt_pass methods: */
1499 /* This pass is only used when the other tail call pass
1500 doesn't run to make [[musttail]] still work. But only
1501 run it when there is actually a musttail in the function. */
1502 bool gate (function
*f
) final override
1504 return !flag_optimize_sibling_calls
&& f
->has_musttail
;
1506 unsigned int execute (function
*) final override
1508 return tree_optimize_tail_calls_1 (true, true);
1511 }; // class pass_musttail
1516 make_pass_musttail (gcc::context
*ctxt
)
1518 return new pass_musttail (ctxt
);