compiler: Check for initialization cycles in bound method expressions.
[official-gcc.git] / gcc / tree-tailcall.c
blob9e54a466cb853dad1700a18e36ac46a44c05a29b
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "stor-layout.h"
26 #include "tm_p.h"
27 #include "basic-block.h"
28 #include "hashtab.h"
29 #include "hash-set.h"
30 #include "vec.h"
31 #include "machmode.h"
32 #include "hard-reg-set.h"
33 #include "input.h"
34 #include "function.h"
35 #include "tree-ssa-alias.h"
36 #include "internal-fn.h"
37 #include "gimple-expr.h"
38 #include "is-a.h"
39 #include "gimple.h"
40 #include "gimple-iterator.h"
41 #include "gimplify-me.h"
42 #include "gimple-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-phinodes.h"
45 #include "stringpool.h"
46 #include "tree-ssanames.h"
47 #include "tree-into-ssa.h"
48 #include "expr.h"
49 #include "tree-dfa.h"
50 #include "gimple-pretty-print.h"
51 #include "except.h"
52 #include "tree-pass.h"
53 #include "flags.h"
54 #include "langhooks.h"
55 #include "dbgcnt.h"
56 #include "target.h"
57 #include "cfgloop.h"
58 #include "common/common-target.h"
59 #include "ipa-utils.h"
61 /* The file implements the tail recursion elimination. It is also used to
62 analyze the tail calls in general, passing the results to the rtl level
63 where they are used for sibcall optimization.
65 In addition to the standard tail recursion elimination, we handle the most
66 trivial cases of making the call tail recursive by creating accumulators.
67 For example the following function
69 int sum (int n)
71 if (n > 0)
72 return n + sum (n - 1);
73 else
74 return 0;
77 is transformed into
79 int sum (int n)
81 int acc = 0;
83 while (n > 0)
84 acc += n--;
86 return acc;
89 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
90 when we reach the return x statement, we should return a_acc + x * m_acc
91 instead. They are initially initialized to 0 and 1, respectively,
92 so the semantics of the function is obviously preserved. If we are
93 guaranteed that the value of the accumulator never change, we
94 omit the accumulator.
96 There are three cases how the function may exit. The first one is
97 handled in adjust_return_value, the other two in adjust_accumulator_values
98 (the second case is actually a special case of the third one and we
99 present it separately just for clarity):
101 1) Just return x, where x is not in any of the remaining special shapes.
102 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
104 2) return f (...), where f is the current function, is rewritten in a
105 classical tail-recursion elimination way, into assignment of arguments
106 and jump to the start of the function. Values of the accumulators
107 are unchanged.
109 3) return a + m * f(...), where a and m do not depend on call to f.
110 To preserve the semantics described before we want this to be rewritten
111 in such a way that we finally return
113 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
115 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
116 eliminate the tail call to f. Special cases when the value is just
117 added or just multiplied are obtained by setting a = 0 or m = 1.
119 TODO -- it is possible to do similar tricks for other operations. */
121 /* A structure that describes the tailcall. */
123 struct tailcall
125 /* The iterator pointing to the call statement. */
126 gimple_stmt_iterator call_gsi;
128 /* True if it is a call to the current function. */
129 bool tail_recursion;
131 /* The return value of the caller is mult * f + add, where f is the return
132 value of the call. */
133 tree mult, add;
135 /* Next tailcall in the chain. */
136 struct tailcall *next;
139 /* The variables holding the value of multiplicative and additive
140 accumulator. */
141 static tree m_acc, a_acc;
143 static bool suitable_for_tail_opt_p (void);
144 static bool optimize_tail_call (struct tailcall *, bool);
145 static void eliminate_tail_call (struct tailcall *);
146 static void find_tail_calls (basic_block, struct tailcall **);
148 /* Returns false when the function is not suitable for tail call optimization
149 from some reason (e.g. if it takes variable number of arguments). */
151 static bool
152 suitable_for_tail_opt_p (void)
154 if (cfun->stdarg)
155 return false;
157 return true;
159 /* Returns false when the function is not suitable for tail call optimization
160 from some reason (e.g. if it takes variable number of arguments).
161 This test must pass in addition to suitable_for_tail_opt_p in order to make
162 tail call discovery happen. */
164 static bool
165 suitable_for_tail_call_opt_p (void)
167 tree param;
169 /* alloca (until we have stack slot life analysis) inhibits
170 sibling call optimizations, but not tail recursion. */
171 if (cfun->calls_alloca)
172 return false;
174 /* If we are using sjlj exceptions, we may need to add a call to
175 _Unwind_SjLj_Unregister at exit of the function. Which means
176 that we cannot do any sibcall transformations. */
177 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
178 && current_function_has_exception_handlers ())
179 return false;
181 /* Any function that calls setjmp might have longjmp called from
182 any called function. ??? We really should represent this
183 properly in the CFG so that this needn't be special cased. */
184 if (cfun->calls_setjmp)
185 return false;
187 /* ??? It is OK if the argument of a function is taken in some cases,
188 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
189 for (param = DECL_ARGUMENTS (current_function_decl);
190 param;
191 param = DECL_CHAIN (param))
192 if (TREE_ADDRESSABLE (param))
193 return false;
195 return true;
198 /* Checks whether the expression EXPR in stmt AT is independent of the
199 statement pointed to by GSI (in a sense that we already know EXPR's value
200 at GSI). We use the fact that we are only called from the chain of
201 basic blocks that have only single successor. Returns the expression
202 containing the value of EXPR at GSI. */
204 static tree
205 independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
207 basic_block bb, call_bb, at_bb;
208 edge e;
209 edge_iterator ei;
211 if (is_gimple_min_invariant (expr))
212 return expr;
214 if (TREE_CODE (expr) != SSA_NAME)
215 return NULL_TREE;
217 /* Mark the blocks in the chain leading to the end. */
218 at_bb = gimple_bb (at);
219 call_bb = gimple_bb (gsi_stmt (gsi));
220 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
221 bb->aux = &bb->aux;
222 bb->aux = &bb->aux;
224 while (1)
226 at = SSA_NAME_DEF_STMT (expr);
227 bb = gimple_bb (at);
229 /* The default definition or defined before the chain. */
230 if (!bb || !bb->aux)
231 break;
233 if (bb == call_bb)
235 for (; !gsi_end_p (gsi); gsi_next (&gsi))
236 if (gsi_stmt (gsi) == at)
237 break;
239 if (!gsi_end_p (gsi))
240 expr = NULL_TREE;
241 break;
244 if (gimple_code (at) != GIMPLE_PHI)
246 expr = NULL_TREE;
247 break;
250 FOR_EACH_EDGE (e, ei, bb->preds)
251 if (e->src->aux)
252 break;
253 gcc_assert (e);
255 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
256 if (TREE_CODE (expr) != SSA_NAME)
258 /* The value is a constant. */
259 break;
263 /* Unmark the blocks. */
264 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
265 bb->aux = NULL;
266 bb->aux = NULL;
268 return expr;
271 /* Simulates the effect of an assignment STMT on the return value of the tail
272 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
273 additive factor for the real return value. */
275 static bool
276 process_assignment (gimple stmt, gimple_stmt_iterator call, tree *m,
277 tree *a, tree *ass_var)
279 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
280 tree dest = gimple_assign_lhs (stmt);
281 enum tree_code code = gimple_assign_rhs_code (stmt);
282 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
283 tree src_var = gimple_assign_rhs1 (stmt);
285 /* See if this is a simple copy operation of an SSA name to the function
286 result. In that case we may have a simple tail call. Ignore type
287 conversions that can never produce extra code between the function
288 call and the function return. */
289 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
290 && (TREE_CODE (src_var) == SSA_NAME))
292 /* Reject a tailcall if the type conversion might need
293 additional code. */
294 if (gimple_assign_cast_p (stmt))
296 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
297 return false;
299 /* Even if the type modes are the same, if the precision of the
300 type is smaller than mode's precision,
301 reduce_to_bit_field_precision would generate additional code. */
302 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
303 && (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (dest)))
304 > TYPE_PRECISION (TREE_TYPE (dest))))
305 return false;
308 if (src_var != *ass_var)
309 return false;
311 *ass_var = dest;
312 return true;
315 switch (rhs_class)
317 case GIMPLE_BINARY_RHS:
318 op1 = gimple_assign_rhs2 (stmt);
320 /* Fall through. */
322 case GIMPLE_UNARY_RHS:
323 op0 = gimple_assign_rhs1 (stmt);
324 break;
326 default:
327 return false;
330 /* Accumulator optimizations will reverse the order of operations.
331 We can only do that for floating-point types if we're assuming
332 that addition and multiplication are associative. */
333 if (!flag_associative_math)
334 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
335 return false;
337 if (rhs_class == GIMPLE_UNARY_RHS)
339 else if (op0 == *ass_var
340 && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
342 else if (op1 == *ass_var
343 && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
345 else
346 return false;
348 switch (code)
350 case PLUS_EXPR:
351 *a = non_ass_var;
352 *ass_var = dest;
353 return true;
355 case POINTER_PLUS_EXPR:
356 if (op0 != *ass_var)
357 return false;
358 *a = non_ass_var;
359 *ass_var = dest;
360 return true;
362 case MULT_EXPR:
363 *m = non_ass_var;
364 *ass_var = dest;
365 return true;
367 case NEGATE_EXPR:
368 *m = build_minus_one_cst (TREE_TYPE (op0));
369 *ass_var = dest;
370 return true;
372 case MINUS_EXPR:
373 if (*ass_var == op0)
374 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
375 else
377 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
378 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
381 *ass_var = dest;
382 return true;
384 /* TODO -- Handle POINTER_PLUS_EXPR. */
386 default:
387 return false;
391 /* Propagate VAR through phis on edge E. */
393 static tree
394 propagate_through_phis (tree var, edge e)
396 basic_block dest = e->dest;
397 gimple_stmt_iterator gsi;
399 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
401 gimple phi = gsi_stmt (gsi);
402 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
403 return PHI_RESULT (phi);
405 return var;
408 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
409 added to the start of RET. */
411 static void
412 find_tail_calls (basic_block bb, struct tailcall **ret)
414 tree ass_var = NULL_TREE, ret_var, func, param;
415 gimple stmt, call = NULL;
416 gimple_stmt_iterator gsi, agsi;
417 bool tail_recursion;
418 struct tailcall *nw;
419 edge e;
420 tree m, a;
421 basic_block abb;
422 size_t idx;
423 tree var;
425 if (!single_succ_p (bb))
426 return;
428 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
430 stmt = gsi_stmt (gsi);
432 /* Ignore labels, returns, clobbers and debug stmts. */
433 if (gimple_code (stmt) == GIMPLE_LABEL
434 || gimple_code (stmt) == GIMPLE_RETURN
435 || gimple_clobber_p (stmt)
436 || is_gimple_debug (stmt))
437 continue;
439 /* Check for a call. */
440 if (is_gimple_call (stmt))
442 call = stmt;
443 ass_var = gimple_call_lhs (stmt);
444 break;
447 /* If the statement references memory or volatile operands, fail. */
448 if (gimple_references_memory_p (stmt)
449 || gimple_has_volatile_ops (stmt))
450 return;
453 if (gsi_end_p (gsi))
455 edge_iterator ei;
456 /* Recurse to the predecessors. */
457 FOR_EACH_EDGE (e, ei, bb->preds)
458 find_tail_calls (e->src, ret);
460 return;
463 /* If the LHS of our call is not just a simple register, we can't
464 transform this into a tail or sibling call. This situation happens,
465 in (e.g.) "*p = foo()" where foo returns a struct. In this case
466 we won't have a temporary here, but we need to carry out the side
467 effect anyway, so tailcall is impossible.
469 ??? In some situations (when the struct is returned in memory via
470 invisible argument) we could deal with this, e.g. by passing 'p'
471 itself as that argument to foo, but it's too early to do this here,
472 and expand_call() will not handle it anyway. If it ever can, then
473 we need to revisit this here, to allow that situation. */
474 if (ass_var && !is_gimple_reg (ass_var))
475 return;
477 /* We found the call, check whether it is suitable. */
478 tail_recursion = false;
479 func = gimple_call_fndecl (call);
480 if (func
481 && !DECL_BUILT_IN (func)
482 && recursive_call_p (current_function_decl, func))
484 tree arg;
486 for (param = DECL_ARGUMENTS (func), idx = 0;
487 param && idx < gimple_call_num_args (call);
488 param = DECL_CHAIN (param), idx ++)
490 arg = gimple_call_arg (call, idx);
491 if (param != arg)
493 /* Make sure there are no problems with copying. The parameter
494 have a copyable type and the two arguments must have reasonably
495 equivalent types. The latter requirement could be relaxed if
496 we emitted a suitable type conversion statement. */
497 if (!is_gimple_reg_type (TREE_TYPE (param))
498 || !useless_type_conversion_p (TREE_TYPE (param),
499 TREE_TYPE (arg)))
500 break;
502 /* The parameter should be a real operand, so that phi node
503 created for it at the start of the function has the meaning
504 of copying the value. This test implies is_gimple_reg_type
505 from the previous condition, however this one could be
506 relaxed by being more careful with copying the new value
507 of the parameter (emitting appropriate GIMPLE_ASSIGN and
508 updating the virtual operands). */
509 if (!is_gimple_reg (param))
510 break;
513 if (idx == gimple_call_num_args (call) && !param)
514 tail_recursion = true;
517 /* Make sure the tail invocation of this function does not refer
518 to local variables. */
519 FOR_EACH_LOCAL_DECL (cfun, idx, var)
521 if (TREE_CODE (var) != PARM_DECL
522 && auto_var_in_fn_p (var, cfun->decl)
523 && (ref_maybe_used_by_stmt_p (call, var)
524 || call_may_clobber_ref_p (call, var)))
525 return;
528 /* Now check the statements after the call. None of them has virtual
529 operands, so they may only depend on the call through its return
530 value. The return value should also be dependent on each of them,
531 since we are running after dce. */
532 m = NULL_TREE;
533 a = NULL_TREE;
535 abb = bb;
536 agsi = gsi;
537 while (1)
539 tree tmp_a = NULL_TREE;
540 tree tmp_m = NULL_TREE;
541 gsi_next (&agsi);
543 while (gsi_end_p (agsi))
545 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
546 abb = single_succ (abb);
547 agsi = gsi_start_bb (abb);
550 stmt = gsi_stmt (agsi);
552 if (gimple_code (stmt) == GIMPLE_LABEL)
553 continue;
555 if (gimple_code (stmt) == GIMPLE_RETURN)
556 break;
558 if (gimple_clobber_p (stmt))
559 continue;
561 if (is_gimple_debug (stmt))
562 continue;
564 if (gimple_code (stmt) != GIMPLE_ASSIGN)
565 return;
567 /* This is a gimple assign. */
568 if (! process_assignment (stmt, gsi, &tmp_m, &tmp_a, &ass_var))
569 return;
571 if (tmp_a)
573 tree type = TREE_TYPE (tmp_a);
574 if (a)
575 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
576 else
577 a = tmp_a;
579 if (tmp_m)
581 tree type = TREE_TYPE (tmp_m);
582 if (m)
583 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
584 else
585 m = tmp_m;
587 if (a)
588 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
592 /* See if this is a tail call we can handle. */
593 ret_var = gimple_return_retval (stmt);
595 /* We may proceed if there either is no return value, or the return value
596 is identical to the call's return. */
597 if (ret_var
598 && (ret_var != ass_var))
599 return;
601 /* If this is not a tail recursive call, we cannot handle addends or
602 multiplicands. */
603 if (!tail_recursion && (m || a))
604 return;
606 /* For pointers only allow additions. */
607 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
608 return;
610 nw = XNEW (struct tailcall);
612 nw->call_gsi = gsi;
614 nw->tail_recursion = tail_recursion;
616 nw->mult = m;
617 nw->add = a;
619 nw->next = *ret;
620 *ret = nw;
623 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
625 static void
626 add_successor_phi_arg (edge e, tree var, tree phi_arg)
628 gimple_stmt_iterator gsi;
630 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
631 if (PHI_RESULT (gsi_stmt (gsi)) == var)
632 break;
634 gcc_assert (!gsi_end_p (gsi));
635 add_phi_arg (gsi_stmt (gsi), phi_arg, e, UNKNOWN_LOCATION);
638 /* Creates a GIMPLE statement which computes the operation specified by
639 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
640 statement in the position specified by GSI. Returns the
641 tree node of the statement's result. */
643 static tree
644 adjust_return_value_with_ops (enum tree_code code, const char *label,
645 tree acc, tree op1, gimple_stmt_iterator gsi)
648 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
649 tree result = make_temp_ssa_name (ret_type, NULL, label);
650 gimple stmt;
652 if (POINTER_TYPE_P (ret_type))
654 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
655 code = POINTER_PLUS_EXPR;
657 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
658 && code != POINTER_PLUS_EXPR)
659 stmt = gimple_build_assign_with_ops (code, result, acc, op1);
660 else
662 tree tem;
663 if (code == POINTER_PLUS_EXPR)
664 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
665 else
666 tem = fold_build2 (code, TREE_TYPE (op1),
667 fold_convert (TREE_TYPE (op1), acc), op1);
668 tree rhs = fold_convert (ret_type, tem);
669 rhs = force_gimple_operand_gsi (&gsi, rhs,
670 false, NULL, true, GSI_SAME_STMT);
671 stmt = gimple_build_assign (result, rhs);
674 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
675 return result;
678 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
679 the computation specified by CODE and OP1 and insert the statement
680 at the position specified by GSI as a new statement. Returns new SSA name
681 of updated accumulator. */
683 static tree
684 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
685 gimple_stmt_iterator gsi)
687 gimple stmt;
688 tree var = copy_ssa_name (acc, NULL);
689 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
690 stmt = gimple_build_assign_with_ops (code, var, acc, op1);
691 else
693 tree rhs = fold_convert (TREE_TYPE (acc),
694 fold_build2 (code,
695 TREE_TYPE (op1),
696 fold_convert (TREE_TYPE (op1), acc),
697 op1));
698 rhs = force_gimple_operand_gsi (&gsi, rhs,
699 false, NULL, false, GSI_CONTINUE_LINKING);
700 stmt = gimple_build_assign (var, rhs);
702 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
703 return var;
706 /* Adjust the accumulator values according to A and M after GSI, and update
707 the phi nodes on edge BACK. */
709 static void
710 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
712 tree var, a_acc_arg, m_acc_arg;
714 if (m)
715 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
716 if (a)
717 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
719 a_acc_arg = a_acc;
720 m_acc_arg = m_acc;
721 if (a)
723 if (m_acc)
725 if (integer_onep (a))
726 var = m_acc;
727 else
728 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
729 a, gsi);
731 else
732 var = a;
734 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
737 if (m)
738 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
740 if (a_acc)
741 add_successor_phi_arg (back, a_acc, a_acc_arg);
743 if (m_acc)
744 add_successor_phi_arg (back, m_acc, m_acc_arg);
747 /* Adjust value of the return at the end of BB according to M and A
748 accumulators. */
750 static void
751 adjust_return_value (basic_block bb, tree m, tree a)
753 tree retval;
754 gimple ret_stmt = gimple_seq_last_stmt (bb_seq (bb));
755 gimple_stmt_iterator gsi = gsi_last_bb (bb);
757 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
759 retval = gimple_return_retval (ret_stmt);
760 if (!retval || retval == error_mark_node)
761 return;
763 if (m)
764 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
765 gsi);
766 if (a)
767 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
768 gsi);
769 gimple_return_set_retval (ret_stmt, retval);
770 update_stmt (ret_stmt);
773 /* Subtract COUNT and FREQUENCY from the basic block and it's
774 outgoing edge. */
775 static void
776 decrease_profile (basic_block bb, gcov_type count, int frequency)
778 edge e;
779 bb->count -= count;
780 if (bb->count < 0)
781 bb->count = 0;
782 bb->frequency -= frequency;
783 if (bb->frequency < 0)
784 bb->frequency = 0;
785 if (!single_succ_p (bb))
787 gcc_assert (!EDGE_COUNT (bb->succs));
788 return;
790 e = single_succ_edge (bb);
791 e->count -= count;
792 if (e->count < 0)
793 e->count = 0;
796 /* Returns true if argument PARAM of the tail recursive call needs to be copied
797 when the call is eliminated. */
799 static bool
800 arg_needs_copy_p (tree param)
802 tree def;
804 if (!is_gimple_reg (param))
805 return false;
807 /* Parameters that are only defined but never used need not be copied. */
808 def = ssa_default_def (cfun, param);
809 if (!def)
810 return false;
812 return true;
815 /* Eliminates tail call described by T. TMP_VARS is a list of
816 temporary variables used to copy the function arguments. */
818 static void
819 eliminate_tail_call (struct tailcall *t)
821 tree param, rslt;
822 gimple stmt, call;
823 tree arg;
824 size_t idx;
825 basic_block bb, first;
826 edge e;
827 gimple phi;
828 gimple_stmt_iterator gsi;
829 gimple orig_stmt;
831 stmt = orig_stmt = gsi_stmt (t->call_gsi);
832 bb = gsi_bb (t->call_gsi);
834 if (dump_file && (dump_flags & TDF_DETAILS))
836 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
837 bb->index);
838 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
839 fprintf (dump_file, "\n");
842 gcc_assert (is_gimple_call (stmt));
844 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
846 /* Remove the code after call_gsi that will become unreachable. The
847 possibly unreachable code in other blocks is removed later in
848 cfg cleanup. */
849 gsi = t->call_gsi;
850 gsi_next (&gsi);
851 while (!gsi_end_p (gsi))
853 gimple t = gsi_stmt (gsi);
854 /* Do not remove the return statement, so that redirect_edge_and_branch
855 sees how the block ends. */
856 if (gimple_code (t) == GIMPLE_RETURN)
857 break;
859 gsi_remove (&gsi, true);
860 release_defs (t);
863 /* Number of executions of function has reduced by the tailcall. */
864 e = single_succ_edge (gsi_bb (t->call_gsi));
865 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), e->count, EDGE_FREQUENCY (e));
866 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), e->count,
867 EDGE_FREQUENCY (e));
868 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
869 decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
871 /* Replace the call by a jump to the start of function. */
872 e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
873 first);
874 gcc_assert (e);
875 PENDING_STMT (e) = NULL;
877 /* Add phi node entries for arguments. The ordering of the phi nodes should
878 be the same as the ordering of the arguments. */
879 for (param = DECL_ARGUMENTS (current_function_decl),
880 idx = 0, gsi = gsi_start_phis (first);
881 param;
882 param = DECL_CHAIN (param), idx++)
884 if (!arg_needs_copy_p (param))
885 continue;
887 arg = gimple_call_arg (stmt, idx);
888 phi = gsi_stmt (gsi);
889 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
891 add_phi_arg (phi, arg, e, gimple_location (stmt));
892 gsi_next (&gsi);
895 /* Update the values of accumulators. */
896 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
898 call = gsi_stmt (t->call_gsi);
899 rslt = gimple_call_lhs (call);
900 if (rslt != NULL_TREE)
902 /* Result of the call will no longer be defined. So adjust the
903 SSA_NAME_DEF_STMT accordingly. */
904 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
907 gsi_remove (&t->call_gsi, true);
908 release_defs (call);
911 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
912 mark the tailcalls for the sibcall optimization. */
914 static bool
915 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
917 if (t->tail_recursion)
919 eliminate_tail_call (t);
920 return true;
923 if (opt_tailcalls)
925 gimple stmt = gsi_stmt (t->call_gsi);
927 gimple_call_set_tail (stmt, true);
928 cfun->tail_call_marked = true;
929 if (dump_file && (dump_flags & TDF_DETAILS))
931 fprintf (dump_file, "Found tail call ");
932 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
933 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
937 return false;
940 /* Creates a tail-call accumulator of the same type as the return type of the
941 current function. LABEL is the name used to creating the temporary
942 variable for the accumulator. The accumulator will be inserted in the
943 phis of a basic block BB with single predecessor with an initial value
944 INIT converted to the current function return type. */
946 static tree
947 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
949 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
950 if (POINTER_TYPE_P (ret_type))
951 ret_type = sizetype;
953 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
954 gimple phi;
956 phi = create_phi_node (tmp, bb);
957 /* RET_TYPE can be a float when -ffast-maths is enabled. */
958 add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
959 UNKNOWN_LOCATION);
960 return PHI_RESULT (phi);
963 /* Optimizes tail calls in the function, turning the tail recursion
964 into iteration. */
966 static unsigned int
967 tree_optimize_tail_calls_1 (bool opt_tailcalls)
969 edge e;
970 bool phis_constructed = false;
971 struct tailcall *tailcalls = NULL, *act, *next;
972 bool changed = false;
973 basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
974 tree param;
975 gimple stmt;
976 edge_iterator ei;
978 if (!suitable_for_tail_opt_p ())
979 return 0;
980 if (opt_tailcalls)
981 opt_tailcalls = suitable_for_tail_call_opt_p ();
983 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
985 /* Only traverse the normal exits, i.e. those that end with return
986 statement. */
987 stmt = last_stmt (e->src);
989 if (stmt
990 && gimple_code (stmt) == GIMPLE_RETURN)
991 find_tail_calls (e->src, &tailcalls);
994 /* Construct the phi nodes and accumulators if necessary. */
995 a_acc = m_acc = NULL_TREE;
996 for (act = tailcalls; act; act = act->next)
998 if (!act->tail_recursion)
999 continue;
1001 if (!phis_constructed)
1003 /* Ensure that there is only one predecessor of the block
1004 or if there are existing degenerate PHI nodes. */
1005 if (!single_pred_p (first)
1006 || !gimple_seq_empty_p (phi_nodes (first)))
1007 first =
1008 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1010 /* Copy the args if needed. */
1011 for (param = DECL_ARGUMENTS (current_function_decl);
1012 param;
1013 param = DECL_CHAIN (param))
1014 if (arg_needs_copy_p (param))
1016 tree name = ssa_default_def (cfun, param);
1017 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1018 gimple phi;
1020 set_ssa_default_def (cfun, param, new_name);
1021 phi = create_phi_node (name, first);
1022 add_phi_arg (phi, new_name, single_pred_edge (first),
1023 EXPR_LOCATION (param));
1025 phis_constructed = true;
1028 if (act->add && !a_acc)
1029 a_acc = create_tailcall_accumulator ("add_acc", first,
1030 integer_zero_node);
1032 if (act->mult && !m_acc)
1033 m_acc = create_tailcall_accumulator ("mult_acc", first,
1034 integer_one_node);
1037 if (a_acc || m_acc)
1039 /* When the tail call elimination using accumulators is performed,
1040 statements adding the accumulated value are inserted at all exits.
1041 This turns all other tail calls to non-tail ones. */
1042 opt_tailcalls = false;
1045 for (; tailcalls; tailcalls = next)
1047 next = tailcalls->next;
1048 changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1049 free (tailcalls);
1052 if (a_acc || m_acc)
1054 /* Modify the remaining return statements. */
1055 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1057 stmt = last_stmt (e->src);
1059 if (stmt
1060 && gimple_code (stmt) == GIMPLE_RETURN)
1061 adjust_return_value (e->src, m_acc, a_acc);
1065 if (changed)
1067 /* We may have created new loops. Make them magically appear. */
1068 loops_state_set (LOOPS_NEED_FIXUP);
1069 free_dominance_info (CDI_DOMINATORS);
1072 /* Add phi nodes for the virtual operands defined in the function to the
1073 header of the loop created by tail recursion elimination. Do so
1074 by triggering the SSA renamer. */
1075 if (phis_constructed)
1076 mark_virtual_operands_for_renaming (cfun);
1078 if (changed)
1079 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1080 return 0;
1083 static bool
1084 gate_tail_calls (void)
1086 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1089 static unsigned int
1090 execute_tail_calls (void)
1092 return tree_optimize_tail_calls_1 (true);
1095 namespace {
1097 const pass_data pass_data_tail_recursion =
1099 GIMPLE_PASS, /* type */
1100 "tailr", /* name */
1101 OPTGROUP_NONE, /* optinfo_flags */
1102 TV_NONE, /* tv_id */
1103 ( PROP_cfg | PROP_ssa ), /* properties_required */
1104 0, /* properties_provided */
1105 0, /* properties_destroyed */
1106 0, /* todo_flags_start */
1107 0, /* todo_flags_finish */
1110 class pass_tail_recursion : public gimple_opt_pass
1112 public:
1113 pass_tail_recursion (gcc::context *ctxt)
1114 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1117 /* opt_pass methods: */
1118 opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1119 virtual bool gate (function *) { return gate_tail_calls (); }
1120 virtual unsigned int execute (function *)
1122 return tree_optimize_tail_calls_1 (false);
1125 }; // class pass_tail_recursion
1127 } // anon namespace
1129 gimple_opt_pass *
1130 make_pass_tail_recursion (gcc::context *ctxt)
1132 return new pass_tail_recursion (ctxt);
1135 namespace {
1137 const pass_data pass_data_tail_calls =
1139 GIMPLE_PASS, /* type */
1140 "tailc", /* name */
1141 OPTGROUP_NONE, /* optinfo_flags */
1142 TV_NONE, /* tv_id */
1143 ( PROP_cfg | PROP_ssa ), /* properties_required */
1144 0, /* properties_provided */
1145 0, /* properties_destroyed */
1146 0, /* todo_flags_start */
1147 0, /* todo_flags_finish */
1150 class pass_tail_calls : public gimple_opt_pass
1152 public:
1153 pass_tail_calls (gcc::context *ctxt)
1154 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1157 /* opt_pass methods: */
1158 virtual bool gate (function *) { return gate_tail_calls (); }
1159 virtual unsigned int execute (function *) { return execute_tail_calls (); }
1161 }; // class pass_tail_calls
1163 } // anon namespace
1165 gimple_opt_pass *
1166 make_pass_tail_calls (gcc::context *ctxt)
1168 return new pass_tail_calls (ctxt);