libcpp, c, middle-end: Optimize initializers using #embed in C
[official-gcc.git] / gcc / tree-tailcall.cc
blob1901b1a13f9989ff92f988b008fb4f6e42e11e32
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2024 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 "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "cgraph.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"
36 #include "tree-cfg.h"
37 #include "tree-into-ssa.h"
38 #include "tree-dfa.h"
39 #include "except.h"
40 #include "tree-eh.h"
41 #include "dbgcnt.h"
42 #include "cfgloop.h"
43 #include "intl.h"
44 #include "common/common-target.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-live.h"
47 #include "diagnostic-core.h"
49 /* The file implements the tail recursion elimination. It is also used to
50 analyze the tail calls in general, passing the results to the rtl level
51 where they are used for sibcall optimization.
53 In addition to the standard tail recursion elimination, we handle the most
54 trivial cases of making the call tail recursive by creating accumulators.
55 For example the following function
57 int sum (int n)
59 if (n > 0)
60 return n + sum (n - 1);
61 else
62 return 0;
65 is transformed into
67 int sum (int n)
69 int acc = 0;
71 while (n > 0)
72 acc += n--;
74 return acc;
77 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
78 when we reach the return x statement, we should return a_acc + x * m_acc
79 instead. They are initially initialized to 0 and 1, respectively,
80 so the semantics of the function is obviously preserved. If we are
81 guaranteed that the value of the accumulator never change, we
82 omit the accumulator.
84 There are three cases how the function may exit. The first one is
85 handled in adjust_return_value, the other two in adjust_accumulator_values
86 (the second case is actually a special case of the third one and we
87 present it separately just for clarity):
89 1) Just return x, where x is not in any of the remaining special shapes.
90 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
92 2) return f (...), where f is the current function, is rewritten in a
93 classical tail-recursion elimination way, into assignment of arguments
94 and jump to the start of the function. Values of the accumulators
95 are unchanged.
97 3) return a + m * f(...), where a and m do not depend on call to f.
98 To preserve the semantics described before we want this to be rewritten
99 in such a way that we finally return
101 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
103 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
104 eliminate the tail call to f. Special cases when the value is just
105 added or just multiplied are obtained by setting a = 0 or m = 1.
107 TODO -- it is possible to do similar tricks for other operations. */
109 /* A structure that describes the tailcall. */
111 struct tailcall
113 /* The iterator pointing to the call statement. */
114 gimple_stmt_iterator call_gsi;
116 /* True if it is a call to the current function. */
117 bool tail_recursion;
119 /* The return value of the caller is mult * f + add, where f is the return
120 value of the call. */
121 tree mult, add;
123 /* Next tailcall in the chain. */
124 struct tailcall *next;
127 /* The variables holding the value of multiplicative and additive
128 accumulator. */
129 static tree m_acc, a_acc;
131 /* Bitmap with a bit for each function parameter which is set to true if we
132 have to copy the parameter for conversion of tail-recursive calls. */
134 static bitmap tailr_arg_needs_copy;
136 static void maybe_error_musttail (gcall *call, const char *err);
138 /* Returns false when the function is not suitable for tail call optimization
139 from some reason (e.g. if it takes variable number of arguments). CALL
140 is call to report for. */
142 static bool
143 suitable_for_tail_opt_p (gcall *call)
145 if (cfun->stdarg)
147 maybe_error_musttail (call, _("caller uses stdargs"));
148 return false;
151 return true;
154 /* Returns false when the function is not suitable for tail call optimization
155 for some reason (e.g. if it takes variable number of arguments).
156 This test must pass in addition to suitable_for_tail_opt_p in order to make
157 tail call discovery happen. CALL is call to report error for. */
159 static bool
160 suitable_for_tail_call_opt_p (gcall *call)
162 tree param;
164 /* alloca (until we have stack slot life analysis) inhibits
165 sibling call optimizations, but not tail recursion. */
166 if (cfun->calls_alloca)
168 maybe_error_musttail (call, _("caller uses alloca"));
169 return false;
172 /* If we are using sjlj exceptions, we may need to add a call to
173 _Unwind_SjLj_Unregister at exit of the function. Which means
174 that we cannot do any sibcall transformations. */
175 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
176 && current_function_has_exception_handlers ())
178 maybe_error_musttail (call, _("caller uses sjlj exceptions"));
179 return false;
182 /* Any function that calls setjmp might have longjmp called from
183 any called function. ??? We really should represent this
184 properly in the CFG so that this needn't be special cased. */
185 if (cfun->calls_setjmp)
187 maybe_error_musttail (call, _("caller uses setjmp"));
188 return false;
191 /* Various targets don't handle tail calls correctly in functions
192 that call __builtin_eh_return. */
193 if (cfun->calls_eh_return)
195 maybe_error_musttail (call, _("caller uses __builtin_eh_return"));
196 return false;
199 /* ??? It is OK if the argument of a function is taken in some cases,
200 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
201 for (param = DECL_ARGUMENTS (current_function_decl);
202 param;
203 param = DECL_CHAIN (param))
204 if (TREE_ADDRESSABLE (param))
206 maybe_error_musttail (call, _("address of caller arguments taken"));
207 return false;
210 return true;
213 /* Checks whether the expression EXPR in stmt AT is independent of the
214 statement pointed to by GSI (in a sense that we already know EXPR's value
215 at GSI). We use the fact that we are only called from the chain of
216 basic blocks that have only single successor. Returns the expression
217 containing the value of EXPR at GSI. */
219 static tree
220 independent_of_stmt_p (tree expr, gimple *at, gimple_stmt_iterator gsi,
221 bitmap to_move)
223 basic_block bb, call_bb, at_bb;
224 edge e;
225 edge_iterator ei;
227 if (is_gimple_min_invariant (expr))
228 return expr;
230 if (TREE_CODE (expr) != SSA_NAME)
231 return NULL_TREE;
233 if (bitmap_bit_p (to_move, SSA_NAME_VERSION (expr)))
234 return expr;
236 /* Mark the blocks in the chain leading to the end. */
237 at_bb = gimple_bb (at);
238 call_bb = gimple_bb (gsi_stmt (gsi));
239 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
240 bb->aux = &bb->aux;
241 bb->aux = &bb->aux;
243 while (1)
245 at = SSA_NAME_DEF_STMT (expr);
246 bb = gimple_bb (at);
248 /* The default definition or defined before the chain. */
249 if (!bb || !bb->aux)
250 break;
252 if (bb == call_bb)
254 for (; !gsi_end_p (gsi); gsi_next (&gsi))
255 if (gsi_stmt (gsi) == at)
256 break;
258 if (!gsi_end_p (gsi))
259 expr = NULL_TREE;
260 break;
263 if (gimple_code (at) != GIMPLE_PHI)
265 expr = NULL_TREE;
266 break;
269 FOR_EACH_EDGE (e, ei, bb->preds)
270 if (e->src->aux)
271 break;
272 gcc_assert (e);
274 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
275 if (TREE_CODE (expr) != SSA_NAME)
277 /* The value is a constant. */
278 break;
282 /* Unmark the blocks. */
283 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
284 bb->aux = NULL;
285 bb->aux = NULL;
287 return expr;
290 enum par { FAIL, OK, TRY_MOVE };
292 /* Simulates the effect of an assignment STMT on the return value of the tail
293 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
294 additive factor for the real return value. */
296 static par
297 process_assignment (gassign *stmt,
298 gimple_stmt_iterator call, tree *m,
299 tree *a, tree *ass_var, bitmap to_move)
301 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
302 tree dest = gimple_assign_lhs (stmt);
303 enum tree_code code = gimple_assign_rhs_code (stmt);
304 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
305 tree src_var = gimple_assign_rhs1 (stmt);
307 /* See if this is a simple copy operation of an SSA name to the function
308 result. In that case we may have a simple tail call. Ignore type
309 conversions that can never produce extra code between the function
310 call and the function return. */
311 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
312 && src_var == *ass_var)
314 /* Reject a tailcall if the type conversion might need
315 additional code. */
316 if (gimple_assign_cast_p (stmt))
318 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
319 return FAIL;
321 /* Even if the type modes are the same, if the precision of the
322 type is smaller than mode's precision,
323 reduce_to_bit_field_precision would generate additional code. */
324 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
325 && !type_has_mode_precision_p (TREE_TYPE (dest)))
326 return FAIL;
329 *ass_var = dest;
330 return OK;
333 switch (rhs_class)
335 case GIMPLE_BINARY_RHS:
336 op1 = gimple_assign_rhs2 (stmt);
338 /* Fall through. */
340 case GIMPLE_UNARY_RHS:
341 op0 = gimple_assign_rhs1 (stmt);
342 break;
344 default:
345 return FAIL;
348 /* Accumulator optimizations will reverse the order of operations.
349 We can only do that for floating-point types if we're assuming
350 that addition and multiplication are associative. */
351 if (!flag_associative_math)
352 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
353 return FAIL;
355 if (rhs_class == GIMPLE_UNARY_RHS
356 && op0 == *ass_var)
358 else if (op0 == *ass_var
359 && (non_ass_var = independent_of_stmt_p (op1, stmt, call,
360 to_move)))
362 else if (*ass_var
363 && op1 == *ass_var
364 && (non_ass_var = independent_of_stmt_p (op0, stmt, call,
365 to_move)))
367 else
368 return TRY_MOVE;
370 switch (code)
372 case PLUS_EXPR:
373 *a = non_ass_var;
374 *ass_var = dest;
375 return OK;
377 case POINTER_PLUS_EXPR:
378 if (op0 != *ass_var)
379 return FAIL;
380 *a = non_ass_var;
381 *ass_var = dest;
382 return OK;
384 case MULT_EXPR:
385 *m = non_ass_var;
386 *ass_var = dest;
387 return OK;
389 case NEGATE_EXPR:
390 *m = build_minus_one_cst (TREE_TYPE (op0));
391 *ass_var = dest;
392 return OK;
394 case MINUS_EXPR:
395 if (*ass_var == op0)
396 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
397 else
399 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
400 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
403 *ass_var = dest;
404 return OK;
406 default:
407 return FAIL;
411 /* Propagate VAR through phis on edge E. */
413 static tree
414 propagate_through_phis (tree var, edge e)
416 basic_block dest = e->dest;
417 gphi_iterator gsi;
419 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
421 gphi *phi = gsi.phi ();
422 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
423 return PHI_RESULT (phi);
425 return var;
428 /* Report an error for failing to tail convert must call CALL
429 with error message ERR. Also clear the flag to prevent further
430 errors. */
432 static void
433 maybe_error_musttail (gcall *call, const char *err)
435 if (gimple_call_must_tail_p (call))
437 error_at (call->location, "cannot tail-call: %s", err);
438 /* Avoid another error. ??? If there are multiple reasons why tail
439 calls fail it might be useful to report them all to avoid
440 whack-a-mole for the user. But currently there is too much
441 redundancy in the reporting, so keep it simple. */
442 gimple_call_set_must_tail (call, false); /* Avoid another error. */
443 gimple_call_set_tail (call, false);
445 if (dump_file)
447 print_gimple_stmt (dump_file, call, 0, TDF_SLIM);
448 fprintf (dump_file, "Cannot convert: %s\n", err);
452 /* Argument for compute_live_vars/live_vars_at_stmt and what compute_live_vars
453 returns. Computed lazily, but just once for the function. */
454 static live_vars_map *live_vars;
455 static vec<bitmap_head> live_vars_vec;
457 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
458 added to the start of RET. When ONLY_MUSTTAIL is set only handle musttail.
459 Update OPT_TAILCALLS as output parameter. */
461 static void
462 find_tail_calls (basic_block bb, struct tailcall **ret, bool only_musttail,
463 bool &opt_tailcalls)
465 tree ass_var = NULL_TREE, ret_var, func, param;
466 gimple *stmt;
467 gcall *call = NULL;
468 gimple_stmt_iterator gsi, agsi;
469 bool tail_recursion;
470 struct tailcall *nw;
471 edge e;
472 tree m, a;
473 basic_block abb;
474 size_t idx;
475 tree var;
477 if (!single_succ_p (bb))
479 /* If there is an abnormal edge assume it's the only extra one.
480 Tolerate that case so that we can give better error messages
481 for musttail later. */
482 if (!has_abnormal_or_eh_outgoing_edge_p (bb))
484 if (dump_file)
485 fprintf (dump_file, "Basic block %d has extra exit edges\n",
486 bb->index);
487 return;
489 if (!cfun->has_musttail)
490 return;
493 bool bad_stmt = false;
494 gimple *last_stmt = nullptr;
495 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
497 stmt = gsi_stmt (gsi);
499 /* Ignore labels, returns, nops, clobbers and debug stmts. */
500 if (gimple_code (stmt) == GIMPLE_LABEL
501 || gimple_code (stmt) == GIMPLE_RETURN
502 || gimple_code (stmt) == GIMPLE_NOP
503 || gimple_code (stmt) == GIMPLE_PREDICT
504 || gimple_clobber_p (stmt)
505 || is_gimple_debug (stmt))
506 continue;
508 if (!last_stmt)
509 last_stmt = stmt;
510 /* Check for a call. */
511 if (is_gimple_call (stmt))
513 call = as_a <gcall *> (stmt);
514 /* Handle only musttail calls when not optimizing. */
515 if (only_musttail && !gimple_call_must_tail_p (call))
516 return;
517 if (bad_stmt)
519 maybe_error_musttail (call,
520 _("memory reference or volatile after call"));
521 return;
523 ass_var = gimple_call_lhs (call);
524 break;
527 /* Allow simple copies between local variables, even if they're
528 aggregates. */
529 if (is_gimple_assign (stmt)
530 && auto_var_in_fn_p (gimple_assign_lhs (stmt), cfun->decl)
531 && auto_var_in_fn_p (gimple_assign_rhs1 (stmt), cfun->decl))
532 continue;
534 /* If the statement references memory or volatile operands, fail. */
535 if (gimple_references_memory_p (stmt)
536 || gimple_has_volatile_ops (stmt))
538 if (dump_file)
540 fprintf (dump_file, "Cannot handle ");
541 print_gimple_stmt (dump_file, stmt, 0);
543 bad_stmt = true;
544 if (!cfun->has_musttail)
545 break;
549 if (bad_stmt)
550 return;
552 if (gsi_end_p (gsi))
554 edge_iterator ei;
555 /* Recurse to the predecessors. */
556 FOR_EACH_EDGE (e, ei, bb->preds)
557 find_tail_calls (e->src, ret, only_musttail, opt_tailcalls);
559 return;
562 if (!suitable_for_tail_opt_p (call))
563 return;
565 if (!suitable_for_tail_call_opt_p (call))
566 opt_tailcalls = false;
568 /* If the LHS of our call is not just a simple register or local
569 variable, we can't transform this into a tail or sibling call.
570 This situation happens, in (e.g.) "*p = foo()" where foo returns a
571 struct. In this case we won't have a temporary here, but we need
572 to carry out the side effect anyway, so tailcall is impossible.
574 ??? In some situations (when the struct is returned in memory via
575 invisible argument) we could deal with this, e.g. by passing 'p'
576 itself as that argument to foo, but it's too early to do this here,
577 and expand_call() will not handle it anyway. If it ever can, then
578 we need to revisit this here, to allow that situation. */
579 if (ass_var
580 && !is_gimple_reg (ass_var)
581 && !auto_var_in_fn_p (ass_var, cfun->decl))
583 maybe_error_musttail (call, _("return value in memory"));
584 return;
587 if (cfun->calls_setjmp)
589 maybe_error_musttail (call, _("caller uses setjmp"));
590 return;
593 /* If the call might throw an exception that wouldn't propagate out of
594 cfun, we can't transform to a tail or sibling call (82081). */
595 if ((stmt_could_throw_p (cfun, stmt)
596 && !stmt_can_throw_external (cfun, stmt)) || !single_succ_p (bb))
598 if (stmt == last_stmt)
599 maybe_error_musttail (call,
600 _("call may throw exception that does not propagate"));
601 else
602 maybe_error_musttail (call,
603 _("code between call and return"));
604 return;
607 /* If the function returns a value, then at present, the tail call
608 must return the same type of value. There is conceptually a copy
609 between the object returned by the tail call candidate and the
610 object returned by CFUN itself.
612 This means that if we have:
614 lhs = f (&<retval>); // f reads from <retval>
615 // (lhs is usually also <retval>)
617 there is a copy between the temporary object returned by f and lhs,
618 meaning that any use of <retval> in f occurs before the assignment
619 to lhs begins. Thus the <retval> that is live on entry to the call
620 to f is really an independent local variable V that happens to be
621 stored in the RESULT_DECL rather than a local VAR_DECL.
623 Turning this into a tail call would remove the copy and make the
624 lifetimes of the return value and V overlap. The same applies to
625 tail recursion, since if f can read from <retval>, we have to assume
626 that CFUN might already have written to <retval> before the call.
628 The problem doesn't apply when <retval> is passed by value, but that
629 isn't a case we handle anyway. */
630 tree result_decl = DECL_RESULT (cfun->decl);
631 if (result_decl
632 && may_be_aliased (result_decl)
633 && ref_maybe_used_by_stmt_p (call, result_decl, false))
635 maybe_error_musttail (call, _("return value used after call"));
636 return;
639 /* We found the call, check whether it is suitable. */
640 tail_recursion = false;
641 func = gimple_call_fndecl (call);
642 if (func
643 && !fndecl_built_in_p (func)
644 && recursive_call_p (current_function_decl, func)
645 && !only_musttail)
647 tree arg;
649 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
650 param && idx < gimple_call_num_args (call);
651 param = DECL_CHAIN (param), idx ++)
653 arg = gimple_call_arg (call, idx);
654 if (param != arg)
656 /* Make sure there are no problems with copying. The parameter
657 have a copyable type and the two arguments must have reasonably
658 equivalent types. The latter requirement could be relaxed if
659 we emitted a suitable type conversion statement. */
660 if (!is_gimple_reg_type (TREE_TYPE (param))
661 || !useless_type_conversion_p (TREE_TYPE (param),
662 TREE_TYPE (arg)))
663 break;
665 /* The parameter should be a real operand, so that phi node
666 created for it at the start of the function has the meaning
667 of copying the value. This test implies is_gimple_reg_type
668 from the previous condition, however this one could be
669 relaxed by being more careful with copying the new value
670 of the parameter (emitting appropriate GIMPLE_ASSIGN and
671 updating the virtual operands). */
672 if (!is_gimple_reg (param))
673 break;
676 if (idx == gimple_call_num_args (call) && !param)
677 tail_recursion = true;
680 /* Compute live vars if not computed yet. */
681 if (live_vars == NULL)
683 unsigned int cnt = 0;
684 FOR_EACH_LOCAL_DECL (cfun, idx, var)
685 if (VAR_P (var)
686 && auto_var_in_fn_p (var, cfun->decl)
687 && may_be_aliased (var))
689 if (live_vars == NULL)
690 live_vars = new live_vars_map;
691 live_vars->put (DECL_UID (var), cnt++);
693 if (live_vars)
694 live_vars_vec = compute_live_vars (cfun, live_vars);
697 /* Determine a bitmap of variables which are still in scope after the
698 call. */
699 bitmap local_live_vars = NULL;
700 if (live_vars)
701 local_live_vars = live_vars_at_stmt (live_vars_vec, live_vars, call);
703 /* Make sure the tail invocation of this function does not indirectly
704 refer to local variables. (Passing variables directly by value
705 is OK.) */
706 FOR_EACH_LOCAL_DECL (cfun, idx, var)
708 if (TREE_CODE (var) != PARM_DECL
709 && auto_var_in_fn_p (var, cfun->decl)
710 && may_be_aliased (var)
711 && (ref_maybe_used_by_stmt_p (call, var, false)
712 || call_may_clobber_ref_p (call, var, false)))
714 if (!VAR_P (var))
716 if (local_live_vars)
717 BITMAP_FREE (local_live_vars);
718 maybe_error_musttail (call, _("call invocation refers to locals"));
719 return;
721 else
723 unsigned int *v = live_vars->get (DECL_UID (var));
724 if (bitmap_bit_p (local_live_vars, *v))
726 BITMAP_FREE (local_live_vars);
727 maybe_error_musttail (call, _("call invocation refers to locals"));
728 return;
734 if (local_live_vars)
735 BITMAP_FREE (local_live_vars);
737 /* Now check the statements after the call. None of them has virtual
738 operands, so they may only depend on the call through its return
739 value. The return value should also be dependent on each of them,
740 since we are running after dce. */
741 m = NULL_TREE;
742 a = NULL_TREE;
743 auto_bitmap to_move_defs;
744 auto_vec<gimple *> to_move_stmts;
746 abb = bb;
747 agsi = gsi;
748 while (1)
750 tree tmp_a = NULL_TREE;
751 tree tmp_m = NULL_TREE;
752 gsi_next (&agsi);
754 while (gsi_end_p (agsi))
756 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
757 abb = single_succ (abb);
758 agsi = gsi_start_bb (abb);
761 stmt = gsi_stmt (agsi);
762 if (gimple_code (stmt) == GIMPLE_RETURN)
763 break;
765 if (gimple_code (stmt) == GIMPLE_LABEL
766 || gimple_code (stmt) == GIMPLE_NOP
767 || gimple_code (stmt) == GIMPLE_PREDICT
768 || gimple_clobber_p (stmt)
769 || is_gimple_debug (stmt))
770 continue;
772 if (gimple_code (stmt) != GIMPLE_ASSIGN)
774 maybe_error_musttail (call, _("unhandled code after call"));
775 return;
778 /* This is a gimple assign. */
779 par ret = process_assignment (as_a <gassign *> (stmt), gsi,
780 &tmp_m, &tmp_a, &ass_var, to_move_defs);
781 if (ret == FAIL || (ret == TRY_MOVE && !tail_recursion))
783 maybe_error_musttail (call, _("return value changed after call"));
784 return;
786 else if (ret == TRY_MOVE)
788 /* Do not deal with checking dominance, the real fix is to
789 do path isolation for the transform phase anyway, removing
790 the need to compute the accumulators with new stmts. */
791 if (abb != bb)
792 return;
793 for (unsigned opno = 1; opno < gimple_num_ops (stmt); ++opno)
795 tree op = gimple_op (stmt, opno);
796 if (independent_of_stmt_p (op, stmt, gsi, to_move_defs) != op)
797 return;
799 bitmap_set_bit (to_move_defs,
800 SSA_NAME_VERSION (gimple_assign_lhs (stmt)));
801 to_move_stmts.safe_push (stmt);
802 continue;
805 if (tmp_a)
807 tree type = TREE_TYPE (tmp_a);
808 if (a)
809 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
810 else
811 a = tmp_a;
813 if (tmp_m)
815 tree type = TREE_TYPE (tmp_m);
816 if (m)
817 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
818 else
819 m = tmp_m;
821 if (a)
822 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
826 /* See if this is a tail call we can handle. */
827 ret_var = gimple_return_retval (as_a <greturn *> (stmt));
829 /* We may proceed if there either is no return value, or the return value
830 is identical to the call's return or if the return decl is an empty type
831 variable and the call's return was not assigned. */
832 if (ret_var
833 && (ret_var != ass_var
834 && !(is_empty_type (TREE_TYPE (ret_var)) && !ass_var)))
836 maybe_error_musttail (call, _("call uses return slot"));
837 return;
840 /* If this is not a tail recursive call, we cannot handle addends or
841 multiplicands. */
842 if (!tail_recursion && (m || a))
844 maybe_error_musttail (call, _("operations after non tail recursive call"));
845 return;
848 /* For pointers only allow additions. */
849 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
851 maybe_error_musttail (call,
852 _("tail recursion with pointers can only use additions"));
853 return;
856 /* Move queued defs. */
857 if (tail_recursion)
859 unsigned i;
860 FOR_EACH_VEC_ELT (to_move_stmts, i, stmt)
862 gimple_stmt_iterator mgsi = gsi_for_stmt (stmt);
863 gsi_move_before (&mgsi, &gsi);
865 if (!tailr_arg_needs_copy)
866 tailr_arg_needs_copy = BITMAP_ALLOC (NULL);
867 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
868 param;
869 param = DECL_CHAIN (param), idx++)
871 tree ddef, arg = gimple_call_arg (call, idx);
872 if (is_gimple_reg (param)
873 && (ddef = ssa_default_def (cfun, param))
874 && (arg != ddef))
875 bitmap_set_bit (tailr_arg_needs_copy, idx);
879 nw = XNEW (struct tailcall);
881 nw->call_gsi = gsi;
883 nw->tail_recursion = tail_recursion;
885 nw->mult = m;
886 nw->add = a;
888 nw->next = *ret;
889 *ret = nw;
892 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
894 static void
895 add_successor_phi_arg (edge e, tree var, tree phi_arg)
897 gphi_iterator gsi;
899 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
900 if (PHI_RESULT (gsi.phi ()) == var)
901 break;
903 gcc_assert (!gsi_end_p (gsi));
904 add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
907 /* Creates a GIMPLE statement which computes the operation specified by
908 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
909 statement in the position specified by GSI. Returns the
910 tree node of the statement's result. */
912 static tree
913 adjust_return_value_with_ops (enum tree_code code, const char *label,
914 tree acc, tree op1, gimple_stmt_iterator gsi)
917 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
918 tree result = make_temp_ssa_name (ret_type, NULL, label);
919 gassign *stmt;
921 if (POINTER_TYPE_P (ret_type))
923 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
924 code = POINTER_PLUS_EXPR;
926 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
927 && code != POINTER_PLUS_EXPR)
928 stmt = gimple_build_assign (result, code, acc, op1);
929 else
931 tree tem;
932 if (code == POINTER_PLUS_EXPR)
933 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
934 else
935 tem = fold_build2 (code, TREE_TYPE (op1),
936 fold_convert (TREE_TYPE (op1), acc), op1);
937 tree rhs = fold_convert (ret_type, tem);
938 rhs = force_gimple_operand_gsi (&gsi, rhs,
939 false, NULL, true, GSI_SAME_STMT);
940 stmt = gimple_build_assign (result, rhs);
943 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
944 return result;
947 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
948 the computation specified by CODE and OP1 and insert the statement
949 at the position specified by GSI as a new statement. Returns new SSA name
950 of updated accumulator. */
952 static tree
953 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
954 gimple_stmt_iterator gsi)
956 gassign *stmt;
957 tree var = copy_ssa_name (acc);
958 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
959 stmt = gimple_build_assign (var, code, acc, op1);
960 else
962 tree rhs = fold_convert (TREE_TYPE (acc),
963 fold_build2 (code,
964 TREE_TYPE (op1),
965 fold_convert (TREE_TYPE (op1), acc),
966 op1));
967 rhs = force_gimple_operand_gsi (&gsi, rhs,
968 false, NULL, false, GSI_CONTINUE_LINKING);
969 stmt = gimple_build_assign (var, rhs);
971 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
972 return var;
975 /* Adjust the accumulator values according to A and M after GSI, and update
976 the phi nodes on edge BACK. */
978 static void
979 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
981 tree var, a_acc_arg, m_acc_arg;
983 if (m)
984 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
985 if (a)
986 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
988 a_acc_arg = a_acc;
989 m_acc_arg = m_acc;
990 if (a)
992 if (m_acc)
994 if (integer_onep (a))
995 var = m_acc;
996 else
997 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
998 a, gsi);
1000 else
1001 var = a;
1003 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
1006 if (m)
1007 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
1009 if (a_acc)
1010 add_successor_phi_arg (back, a_acc, a_acc_arg);
1012 if (m_acc)
1013 add_successor_phi_arg (back, m_acc, m_acc_arg);
1016 /* Adjust value of the return at the end of BB according to M and A
1017 accumulators. */
1019 static void
1020 adjust_return_value (basic_block bb, tree m, tree a)
1022 tree retval;
1023 greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
1024 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1026 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
1028 retval = gimple_return_retval (ret_stmt);
1029 if (!retval || retval == error_mark_node)
1030 return;
1032 if (m)
1033 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
1034 gsi);
1035 if (a)
1036 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
1037 gsi);
1038 gimple_return_set_retval (ret_stmt, retval);
1039 update_stmt (ret_stmt);
1042 /* Subtract COUNT and FREQUENCY from the basic block and it's
1043 outgoing edge. */
1044 static void
1045 decrease_profile (basic_block bb, profile_count count)
1047 bb->count = bb->count - count;
1048 if (!single_succ_p (bb))
1050 gcc_assert (!EDGE_COUNT (bb->succs));
1051 return;
1055 /* Eliminates tail call described by T. TMP_VARS is a list of
1056 temporary variables used to copy the function arguments.
1057 Allocates *NEW_LOOP if not already done and initializes it. */
1059 static void
1060 eliminate_tail_call (struct tailcall *t, class loop *&new_loop)
1062 tree param, rslt;
1063 gimple *stmt, *call;
1064 tree arg;
1065 size_t idx;
1066 basic_block bb, first;
1067 edge e;
1068 gphi *phi;
1069 gphi_iterator gpi;
1070 gimple_stmt_iterator gsi;
1071 gimple *orig_stmt;
1073 stmt = orig_stmt = gsi_stmt (t->call_gsi);
1074 bb = gsi_bb (t->call_gsi);
1076 if (dump_file && (dump_flags & TDF_DETAILS))
1078 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
1079 bb->index);
1080 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1081 fprintf (dump_file, "\n");
1084 gcc_assert (is_gimple_call (stmt));
1086 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1088 /* Remove the code after call_gsi that will become unreachable. The
1089 possibly unreachable code in other blocks is removed later in
1090 cfg cleanup. */
1091 gsi = t->call_gsi;
1092 gimple_stmt_iterator gsi2 = gsi_last_bb (gimple_bb (gsi_stmt (gsi)));
1093 while (gsi_stmt (gsi2) != gsi_stmt (gsi))
1095 gimple *t = gsi_stmt (gsi2);
1096 /* Do not remove the return statement, so that redirect_edge_and_branch
1097 sees how the block ends. */
1098 if (gimple_code (t) != GIMPLE_RETURN)
1100 gimple_stmt_iterator gsi3 = gsi2;
1101 gsi_prev (&gsi2);
1102 gsi_remove (&gsi3, true);
1103 release_defs (t);
1105 else
1106 gsi_prev (&gsi2);
1109 /* Number of executions of function has reduced by the tailcall. */
1110 e = single_succ_edge (gsi_bb (t->call_gsi));
1112 profile_count count = e->count ();
1114 /* When profile is inconsistent and the recursion edge is more frequent
1115 than number of executions of functions, scale it down, so we do not end
1116 up with 0 executions of entry block. */
1117 if (count >= ENTRY_BLOCK_PTR_FOR_FN (cfun)->count)
1118 count = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.apply_scale (7, 8);
1119 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), count);
1120 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), count);
1121 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1122 decrease_profile (e->dest, count);
1124 /* Replace the call by a jump to the start of function. */
1125 e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
1126 first);
1127 gcc_assert (e);
1128 PENDING_STMT (e) = NULL;
1130 /* Add the new loop. */
1131 if (!new_loop)
1133 new_loop = alloc_loop ();
1134 new_loop->header = first;
1135 new_loop->finite_p = true;
1137 else
1138 gcc_assert (new_loop->header == first);
1140 /* Add phi node entries for arguments. The ordering of the phi nodes should
1141 be the same as the ordering of the arguments. */
1142 for (param = DECL_ARGUMENTS (current_function_decl),
1143 idx = 0, gpi = gsi_start_phis (first);
1144 param;
1145 param = DECL_CHAIN (param), idx++)
1147 if (!bitmap_bit_p (tailr_arg_needs_copy, idx))
1148 continue;
1150 arg = gimple_call_arg (stmt, idx);
1151 phi = gpi.phi ();
1152 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
1154 add_phi_arg (phi, arg, e, gimple_location (stmt));
1155 gsi_next (&gpi);
1158 /* Update the values of accumulators. */
1159 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
1161 call = gsi_stmt (t->call_gsi);
1162 rslt = gimple_call_lhs (call);
1163 if (rslt != NULL_TREE && TREE_CODE (rslt) == SSA_NAME)
1165 /* Result of the call will no longer be defined. So adjust the
1166 SSA_NAME_DEF_STMT accordingly. */
1167 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
1170 gsi_remove (&t->call_gsi, true);
1171 release_defs (call);
1174 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
1175 mark the tailcalls for the sibcall optimization. */
1177 static bool
1178 optimize_tail_call (struct tailcall *t, bool opt_tailcalls,
1179 class loop *&new_loop)
1181 if (t->tail_recursion)
1183 eliminate_tail_call (t, new_loop);
1184 return true;
1187 if (opt_tailcalls)
1189 gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
1191 gimple_call_set_tail (stmt, true);
1192 cfun->tail_call_marked = true;
1193 if (dump_file && (dump_flags & TDF_DETAILS))
1195 fprintf (dump_file, "Found tail call ");
1196 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1197 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
1201 return false;
1204 /* Creates a tail-call accumulator of the same type as the return type of the
1205 current function. LABEL is the name used to creating the temporary
1206 variable for the accumulator. The accumulator will be inserted in the
1207 phis of a basic block BB with single predecessor with an initial value
1208 INIT converted to the current function return type. */
1210 static tree
1211 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
1213 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
1214 if (POINTER_TYPE_P (ret_type))
1215 ret_type = sizetype;
1217 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
1218 gphi *phi;
1220 phi = create_phi_node (tmp, bb);
1221 add_phi_arg (phi, init, single_pred_edge (bb),
1222 UNKNOWN_LOCATION);
1223 return PHI_RESULT (phi);
1226 /* Optimizes tail calls in the function, turning the tail recursion
1227 into iteration. When ONLY_MUSTCALL is true only optimize mustcall
1228 marked calls. */
1230 static unsigned int
1231 tree_optimize_tail_calls_1 (bool opt_tailcalls, bool only_mustcall)
1233 edge e;
1234 bool phis_constructed = false;
1235 struct tailcall *tailcalls = NULL, *act, *next;
1236 bool changed = false;
1237 basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1238 tree param;
1239 edge_iterator ei;
1241 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1243 /* Only traverse the normal exits, i.e. those that end with return
1244 statement. */
1245 if (safe_is_a <greturn *> (*gsi_last_bb (e->src)))
1246 find_tail_calls (e->src, &tailcalls, only_mustcall, opt_tailcalls);
1249 if (live_vars)
1251 destroy_live_vars (live_vars_vec);
1252 delete live_vars;
1253 live_vars = NULL;
1256 /* Construct the phi nodes and accumulators if necessary. */
1257 a_acc = m_acc = NULL_TREE;
1258 for (act = tailcalls; act; act = act->next)
1260 if (!act->tail_recursion)
1261 continue;
1263 if (!phis_constructed)
1265 /* Ensure that there is only one predecessor of the block
1266 or if there are existing degenerate PHI nodes. */
1267 if (!single_pred_p (first)
1268 || !gimple_seq_empty_p (phi_nodes (first)))
1269 first =
1270 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1272 /* Copy the args if needed. */
1273 unsigned idx;
1274 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
1275 param;
1276 param = DECL_CHAIN (param), idx++)
1277 if (bitmap_bit_p (tailr_arg_needs_copy, idx))
1279 tree name = ssa_default_def (cfun, param);
1280 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1281 gphi *phi;
1283 set_ssa_default_def (cfun, param, new_name);
1284 phi = create_phi_node (name, first);
1285 add_phi_arg (phi, new_name, single_pred_edge (first),
1286 EXPR_LOCATION (param));
1288 phis_constructed = true;
1290 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
1291 if (POINTER_TYPE_P (ret_type))
1292 ret_type = sizetype;
1294 if (act->add && !a_acc)
1295 a_acc = create_tailcall_accumulator ("add_acc", first,
1296 build_zero_cst (ret_type));
1298 if (act->mult && !m_acc)
1299 m_acc = create_tailcall_accumulator ("mult_acc", first,
1300 build_one_cst (ret_type));
1303 if (a_acc || m_acc)
1305 /* When the tail call elimination using accumulators is performed,
1306 statements adding the accumulated value are inserted at all exits.
1307 This turns all other tail calls to non-tail ones. */
1308 opt_tailcalls = false;
1311 class loop *new_loop = NULL;
1312 for (; tailcalls; tailcalls = next)
1314 next = tailcalls->next;
1315 changed |= optimize_tail_call (tailcalls, opt_tailcalls, new_loop);
1316 free (tailcalls);
1318 if (new_loop)
1319 add_loop (new_loop, loops_for_fn (cfun)->tree_root);
1321 if (a_acc || m_acc)
1323 /* Modify the remaining return statements. */
1324 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1326 if (safe_is_a <greturn *> (*gsi_last_bb (e->src)))
1327 adjust_return_value (e->src, m_acc, a_acc);
1331 if (changed)
1332 free_dominance_info (CDI_DOMINATORS);
1334 /* Add phi nodes for the virtual operands defined in the function to the
1335 header of the loop created by tail recursion elimination. Do so
1336 by triggering the SSA renamer. */
1337 if (phis_constructed)
1338 mark_virtual_operands_for_renaming (cfun);
1340 if (tailr_arg_needs_copy)
1341 BITMAP_FREE (tailr_arg_needs_copy);
1343 if (changed)
1344 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1345 return 0;
1348 static bool
1349 gate_tail_calls (void)
1351 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1354 static unsigned int
1355 execute_tail_calls (void)
1357 return tree_optimize_tail_calls_1 (true, false);
1360 namespace {
1362 const pass_data pass_data_tail_recursion =
1364 GIMPLE_PASS, /* type */
1365 "tailr", /* name */
1366 OPTGROUP_NONE, /* optinfo_flags */
1367 TV_NONE, /* tv_id */
1368 ( PROP_cfg | PROP_ssa ), /* properties_required */
1369 0, /* properties_provided */
1370 0, /* properties_destroyed */
1371 0, /* todo_flags_start */
1372 0, /* todo_flags_finish */
1375 class pass_tail_recursion : public gimple_opt_pass
1377 public:
1378 pass_tail_recursion (gcc::context *ctxt)
1379 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1382 /* opt_pass methods: */
1383 opt_pass * clone () final override
1385 return new pass_tail_recursion (m_ctxt);
1387 bool gate (function *) final override { return gate_tail_calls (); }
1388 unsigned int execute (function *) final override
1390 return tree_optimize_tail_calls_1 (false, false);
1393 }; // class pass_tail_recursion
1395 } // anon namespace
1397 gimple_opt_pass *
1398 make_pass_tail_recursion (gcc::context *ctxt)
1400 return new pass_tail_recursion (ctxt);
1403 namespace {
1405 const pass_data pass_data_tail_calls =
1407 GIMPLE_PASS, /* type */
1408 "tailc", /* name */
1409 OPTGROUP_NONE, /* optinfo_flags */
1410 TV_NONE, /* tv_id */
1411 ( PROP_cfg | PROP_ssa ), /* properties_required */
1412 0, /* properties_provided */
1413 0, /* properties_destroyed */
1414 0, /* todo_flags_start */
1415 0, /* todo_flags_finish */
1418 class pass_tail_calls : public gimple_opt_pass
1420 public:
1421 pass_tail_calls (gcc::context *ctxt)
1422 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1425 /* opt_pass methods: */
1426 bool gate (function *) final override { return gate_tail_calls (); }
1427 unsigned int execute (function *) final override
1429 return execute_tail_calls ();
1432 }; // class pass_tail_calls
1434 } // anon namespace
1436 gimple_opt_pass *
1437 make_pass_tail_calls (gcc::context *ctxt)
1439 return new pass_tail_calls (ctxt);
1442 namespace {
1444 const pass_data pass_data_musttail =
1446 GIMPLE_PASS, /* type */
1447 "musttail", /* name */
1448 OPTGROUP_NONE, /* optinfo_flags */
1449 TV_NONE, /* tv_id */
1450 ( PROP_cfg | PROP_ssa ), /* properties_required */
1451 0, /* properties_provided */
1452 0, /* properties_destroyed */
1453 0, /* todo_flags_start */
1454 0, /* todo_flags_finish */
1457 class pass_musttail : public gimple_opt_pass
1459 public:
1460 pass_musttail (gcc::context *ctxt)
1461 : gimple_opt_pass (pass_data_musttail, ctxt)
1464 /* opt_pass methods: */
1465 /* This pass is only used when the other tail call pass
1466 doesn't run to make [[musttail]] still work. But only
1467 run it when there is actually a musttail in the function. */
1468 bool gate (function *f) final override
1470 return !flag_optimize_sibling_calls && f->has_musttail;
1472 unsigned int execute (function *) final override
1474 return tree_optimize_tail_calls_1 (true, true);
1477 }; // class pass_musttail
1479 } // anon namespace
1481 gimple_opt_pass *
1482 make_pass_musttail (gcc::context *ctxt)
1484 return new pass_musttail (ctxt);