]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-tailcall.c
replace several uses of the anon namespace with GCC_FINAL
[thirdparty/gcc.git] / gcc / tree-tailcall.c
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "cfghooks.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "rtl.h"
28 #include "ssa.h"
29 #include "alias.h"
30 #include "fold-const.h"
31 #include "stor-layout.h"
32 #include "tm_p.h"
33 #include "internal-fn.h"
34 #include "gimple-iterator.h"
35 #include "gimplify-me.h"
36 #include "tree-cfg.h"
37 #include "tree-into-ssa.h"
38 #include "flags.h"
39 #include "insn-config.h"
40 #include "expmed.h"
41 #include "dojump.h"
42 #include "explow.h"
43 #include "calls.h"
44 #include "emit-rtl.h"
45 #include "varasm.h"
46 #include "stmt.h"
47 #include "expr.h"
48 #include "tree-dfa.h"
49 #include "gimple-pretty-print.h"
50 #include "except.h"
51 #include "tree-pass.h"
52 #include "langhooks.h"
53 #include "dbgcnt.h"
54 #include "target.h"
55 #include "cfgloop.h"
56 #include "common/common-target.h"
57 #include "cgraph.h"
58 #include "ipa-utils.h"
59
60 /* The file implements the tail recursion elimination. It is also used to
61 analyze the tail calls in general, passing the results to the rtl level
62 where they are used for sibcall optimization.
63
64 In addition to the standard tail recursion elimination, we handle the most
65 trivial cases of making the call tail recursive by creating accumulators.
66 For example the following function
67
68 int sum (int n)
69 {
70 if (n > 0)
71 return n + sum (n - 1);
72 else
73 return 0;
74 }
75
76 is transformed into
77
78 int sum (int n)
79 {
80 int acc = 0;
81
82 while (n > 0)
83 acc += n--;
84
85 return acc;
86 }
87
88 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
89 when we reach the return x statement, we should return a_acc + x * m_acc
90 instead. They are initially initialized to 0 and 1, respectively,
91 so the semantics of the function is obviously preserved. If we are
92 guaranteed that the value of the accumulator never change, we
93 omit the accumulator.
94
95 There are three cases how the function may exit. The first one is
96 handled in adjust_return_value, the other two in adjust_accumulator_values
97 (the second case is actually a special case of the third one and we
98 present it separately just for clarity):
99
100 1) Just return x, where x is not in any of the remaining special shapes.
101 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
102
103 2) return f (...), where f is the current function, is rewritten in a
104 classical tail-recursion elimination way, into assignment of arguments
105 and jump to the start of the function. Values of the accumulators
106 are unchanged.
107
108 3) return a + m * f(...), where a and m do not depend on call to f.
109 To preserve the semantics described before we want this to be rewritten
110 in such a way that we finally return
111
112 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
113
114 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
115 eliminate the tail call to f. Special cases when the value is just
116 added or just multiplied are obtained by setting a = 0 or m = 1.
117
118 TODO -- it is possible to do similar tricks for other operations. */
119
120 /* A structure that describes the tailcall. */
121
122 struct tailcall
123 {
124 /* The iterator pointing to the call statement. */
125 gimple_stmt_iterator call_gsi;
126
127 /* True if it is a call to the current function. */
128 bool tail_recursion;
129
130 /* The return value of the caller is mult * f + add, where f is the return
131 value of the call. */
132 tree mult, add;
133
134 /* Next tailcall in the chain. */
135 struct tailcall *next;
136 };
137
138 /* The variables holding the value of multiplicative and additive
139 accumulator. */
140 static tree m_acc, a_acc;
141
142 static bool optimize_tail_call (struct tailcall *, bool);
143 static void eliminate_tail_call (struct tailcall *);
144
145 /* Returns false when the function is not suitable for tail call optimization
146 from some reason (e.g. if it takes variable number of arguments). */
147
148 static bool
149 suitable_for_tail_opt_p (void)
150 {
151 if (cfun->stdarg)
152 return false;
153
154 return true;
155 }
156 /* Returns false when the function is not suitable for tail call optimization
157 for some reason (e.g. if it takes variable number of arguments).
158 This test must pass in addition to suitable_for_tail_opt_p in order to make
159 tail call discovery happen. */
160
161 static bool
162 suitable_for_tail_call_opt_p (void)
163 {
164 tree param;
165
166 /* alloca (until we have stack slot life analysis) inhibits
167 sibling call optimizations, but not tail recursion. */
168 if (cfun->calls_alloca)
169 return false;
170
171 /* If we are using sjlj exceptions, we may need to add a call to
172 _Unwind_SjLj_Unregister at exit of the function. Which means
173 that we cannot do any sibcall transformations. */
174 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
175 && current_function_has_exception_handlers ())
176 return false;
177
178 /* Any function that calls setjmp might have longjmp called from
179 any called function. ??? We really should represent this
180 properly in the CFG so that this needn't be special cased. */
181 if (cfun->calls_setjmp)
182 return false;
183
184 /* ??? It is OK if the argument of a function is taken in some cases,
185 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
186 for (param = DECL_ARGUMENTS (current_function_decl);
187 param;
188 param = DECL_CHAIN (param))
189 if (TREE_ADDRESSABLE (param))
190 return false;
191
192 return true;
193 }
194
195 /* Checks whether the expression EXPR in stmt AT is independent of the
196 statement pointed to by GSI (in a sense that we already know EXPR's value
197 at GSI). We use the fact that we are only called from the chain of
198 basic blocks that have only single successor. Returns the expression
199 containing the value of EXPR at GSI. */
200
201 static tree
202 independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
203 {
204 basic_block bb, call_bb, at_bb;
205 edge e;
206 edge_iterator ei;
207
208 if (is_gimple_min_invariant (expr))
209 return expr;
210
211 if (TREE_CODE (expr) != SSA_NAME)
212 return NULL_TREE;
213
214 /* Mark the blocks in the chain leading to the end. */
215 at_bb = gimple_bb (at);
216 call_bb = gimple_bb (gsi_stmt (gsi));
217 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
218 bb->aux = &bb->aux;
219 bb->aux = &bb->aux;
220
221 while (1)
222 {
223 at = SSA_NAME_DEF_STMT (expr);
224 bb = gimple_bb (at);
225
226 /* The default definition or defined before the chain. */
227 if (!bb || !bb->aux)
228 break;
229
230 if (bb == call_bb)
231 {
232 for (; !gsi_end_p (gsi); gsi_next (&gsi))
233 if (gsi_stmt (gsi) == at)
234 break;
235
236 if (!gsi_end_p (gsi))
237 expr = NULL_TREE;
238 break;
239 }
240
241 if (gimple_code (at) != GIMPLE_PHI)
242 {
243 expr = NULL_TREE;
244 break;
245 }
246
247 FOR_EACH_EDGE (e, ei, bb->preds)
248 if (e->src->aux)
249 break;
250 gcc_assert (e);
251
252 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
253 if (TREE_CODE (expr) != SSA_NAME)
254 {
255 /* The value is a constant. */
256 break;
257 }
258 }
259
260 /* Unmark the blocks. */
261 for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
262 bb->aux = NULL;
263 bb->aux = NULL;
264
265 return expr;
266 }
267
268 /* Simulates the effect of an assignment STMT on the return value of the tail
269 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
270 additive factor for the real return value. */
271
272 static bool
273 process_assignment (gassign *stmt, gimple_stmt_iterator call, tree *m,
274 tree *a, tree *ass_var)
275 {
276 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
277 tree dest = gimple_assign_lhs (stmt);
278 enum tree_code code = gimple_assign_rhs_code (stmt);
279 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
280 tree src_var = gimple_assign_rhs1 (stmt);
281
282 /* See if this is a simple copy operation of an SSA name to the function
283 result. In that case we may have a simple tail call. Ignore type
284 conversions that can never produce extra code between the function
285 call and the function return. */
286 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
287 && (TREE_CODE (src_var) == SSA_NAME))
288 {
289 /* Reject a tailcall if the type conversion might need
290 additional code. */
291 if (gimple_assign_cast_p (stmt))
292 {
293 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
294 return false;
295
296 /* Even if the type modes are the same, if the precision of the
297 type is smaller than mode's precision,
298 reduce_to_bit_field_precision would generate additional code. */
299 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
300 && (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (dest)))
301 > TYPE_PRECISION (TREE_TYPE (dest))))
302 return false;
303 }
304
305 if (src_var != *ass_var)
306 return false;
307
308 *ass_var = dest;
309 return true;
310 }
311
312 switch (rhs_class)
313 {
314 case GIMPLE_BINARY_RHS:
315 op1 = gimple_assign_rhs2 (stmt);
316
317 /* Fall through. */
318
319 case GIMPLE_UNARY_RHS:
320 op0 = gimple_assign_rhs1 (stmt);
321 break;
322
323 default:
324 return false;
325 }
326
327 /* Accumulator optimizations will reverse the order of operations.
328 We can only do that for floating-point types if we're assuming
329 that addition and multiplication are associative. */
330 if (!flag_associative_math)
331 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
332 return false;
333
334 if (rhs_class == GIMPLE_UNARY_RHS)
335 ;
336 else if (op0 == *ass_var
337 && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
338 ;
339 else if (op1 == *ass_var
340 && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
341 ;
342 else
343 return false;
344
345 switch (code)
346 {
347 case PLUS_EXPR:
348 *a = non_ass_var;
349 *ass_var = dest;
350 return true;
351
352 case POINTER_PLUS_EXPR:
353 if (op0 != *ass_var)
354 return false;
355 *a = non_ass_var;
356 *ass_var = dest;
357 return true;
358
359 case MULT_EXPR:
360 *m = non_ass_var;
361 *ass_var = dest;
362 return true;
363
364 case NEGATE_EXPR:
365 *m = build_minus_one_cst (TREE_TYPE (op0));
366 *ass_var = dest;
367 return true;
368
369 case MINUS_EXPR:
370 if (*ass_var == op0)
371 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
372 else
373 {
374 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
375 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
376 }
377
378 *ass_var = dest;
379 return true;
380
381 /* TODO -- Handle POINTER_PLUS_EXPR. */
382
383 default:
384 return false;
385 }
386 }
387
388 /* Propagate VAR through phis on edge E. */
389
390 static tree
391 propagate_through_phis (tree var, edge e)
392 {
393 basic_block dest = e->dest;
394 gphi_iterator gsi;
395
396 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
397 {
398 gphi *phi = gsi.phi ();
399 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
400 return PHI_RESULT (phi);
401 }
402 return var;
403 }
404
405 /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
406 added to the start of RET. */
407
408 static void
409 find_tail_calls (basic_block bb, struct tailcall **ret)
410 {
411 tree ass_var = NULL_TREE, ret_var, func, param;
412 gimple stmt;
413 gcall *call = NULL;
414 gimple_stmt_iterator gsi, agsi;
415 bool tail_recursion;
416 struct tailcall *nw;
417 edge e;
418 tree m, a;
419 basic_block abb;
420 size_t idx;
421 tree var;
422
423 if (!single_succ_p (bb))
424 return;
425
426 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
427 {
428 stmt = gsi_stmt (gsi);
429
430 /* Ignore labels, returns, clobbers and debug stmts. */
431 if (gimple_code (stmt) == GIMPLE_LABEL
432 || gimple_code (stmt) == GIMPLE_RETURN
433 || gimple_clobber_p (stmt)
434 || is_gimple_debug (stmt))
435 continue;
436
437 /* Check for a call. */
438 if (is_gimple_call (stmt))
439 {
440 call = as_a <gcall *> (stmt);
441 ass_var = gimple_call_lhs (call);
442 break;
443 }
444
445 /* If the statement references memory or volatile operands, fail. */
446 if (gimple_references_memory_p (stmt)
447 || gimple_has_volatile_ops (stmt))
448 return;
449 }
450
451 if (gsi_end_p (gsi))
452 {
453 edge_iterator ei;
454 /* Recurse to the predecessors. */
455 FOR_EACH_EDGE (e, ei, bb->preds)
456 find_tail_calls (e->src, ret);
457
458 return;
459 }
460
461 /* If the LHS of our call is not just a simple register, we can't
462 transform this into a tail or sibling call. This situation happens,
463 in (e.g.) "*p = foo()" where foo returns a struct. In this case
464 we won't have a temporary here, but we need to carry out the side
465 effect anyway, so tailcall is impossible.
466
467 ??? In some situations (when the struct is returned in memory via
468 invisible argument) we could deal with this, e.g. by passing 'p'
469 itself as that argument to foo, but it's too early to do this here,
470 and expand_call() will not handle it anyway. If it ever can, then
471 we need to revisit this here, to allow that situation. */
472 if (ass_var && !is_gimple_reg (ass_var))
473 return;
474
475 /* We found the call, check whether it is suitable. */
476 tail_recursion = false;
477 func = gimple_call_fndecl (call);
478 if (func
479 && !DECL_BUILT_IN (func)
480 && recursive_call_p (current_function_decl, func))
481 {
482 tree arg;
483
484 for (param = DECL_ARGUMENTS (func), idx = 0;
485 param && idx < gimple_call_num_args (call);
486 param = DECL_CHAIN (param), idx ++)
487 {
488 arg = gimple_call_arg (call, idx);
489 if (param != arg)
490 {
491 /* Make sure there are no problems with copying. The parameter
492 have a copyable type and the two arguments must have reasonably
493 equivalent types. The latter requirement could be relaxed if
494 we emitted a suitable type conversion statement. */
495 if (!is_gimple_reg_type (TREE_TYPE (param))
496 || !useless_type_conversion_p (TREE_TYPE (param),
497 TREE_TYPE (arg)))
498 break;
499
500 /* The parameter should be a real operand, so that phi node
501 created for it at the start of the function has the meaning
502 of copying the value. This test implies is_gimple_reg_type
503 from the previous condition, however this one could be
504 relaxed by being more careful with copying the new value
505 of the parameter (emitting appropriate GIMPLE_ASSIGN and
506 updating the virtual operands). */
507 if (!is_gimple_reg (param))
508 break;
509 }
510 }
511 if (idx == gimple_call_num_args (call) && !param)
512 tail_recursion = true;
513 }
514
515 /* Make sure the tail invocation of this function does not refer
516 to local variables. */
517 FOR_EACH_LOCAL_DECL (cfun, idx, var)
518 {
519 if (TREE_CODE (var) != PARM_DECL
520 && auto_var_in_fn_p (var, cfun->decl)
521 && (ref_maybe_used_by_stmt_p (call, var)
522 || call_may_clobber_ref_p (call, var)))
523 return;
524 }
525
526 /* Now check the statements after the call. None of them has virtual
527 operands, so they may only depend on the call through its return
528 value. The return value should also be dependent on each of them,
529 since we are running after dce. */
530 m = NULL_TREE;
531 a = NULL_TREE;
532
533 abb = bb;
534 agsi = gsi;
535 while (1)
536 {
537 tree tmp_a = NULL_TREE;
538 tree tmp_m = NULL_TREE;
539 gsi_next (&agsi);
540
541 while (gsi_end_p (agsi))
542 {
543 ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
544 abb = single_succ (abb);
545 agsi = gsi_start_bb (abb);
546 }
547
548 stmt = gsi_stmt (agsi);
549
550 if (gimple_code (stmt) == GIMPLE_LABEL)
551 continue;
552
553 if (gimple_code (stmt) == GIMPLE_RETURN)
554 break;
555
556 if (gimple_clobber_p (stmt))
557 continue;
558
559 if (is_gimple_debug (stmt))
560 continue;
561
562 if (gimple_code (stmt) != GIMPLE_ASSIGN)
563 return;
564
565 /* This is a gimple assign. */
566 if (! process_assignment (as_a <gassign *> (stmt), gsi, &tmp_m,
567 &tmp_a, &ass_var))
568 return;
569
570 if (tmp_a)
571 {
572 tree type = TREE_TYPE (tmp_a);
573 if (a)
574 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
575 else
576 a = tmp_a;
577 }
578 if (tmp_m)
579 {
580 tree type = TREE_TYPE (tmp_m);
581 if (m)
582 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
583 else
584 m = tmp_m;
585
586 if (a)
587 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
588 }
589 }
590
591 /* See if this is a tail call we can handle. */
592 ret_var = gimple_return_retval (as_a <greturn *> (stmt));
593
594 /* We may proceed if there either is no return value, or the return value
595 is identical to the call's return. */
596 if (ret_var
597 && (ret_var != ass_var))
598 return;
599
600 /* If this is not a tail recursive call, we cannot handle addends or
601 multiplicands. */
602 if (!tail_recursion && (m || a))
603 return;
604
605 /* For pointers only allow additions. */
606 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
607 return;
608
609 nw = XNEW (struct tailcall);
610
611 nw->call_gsi = gsi;
612
613 nw->tail_recursion = tail_recursion;
614
615 nw->mult = m;
616 nw->add = a;
617
618 nw->next = *ret;
619 *ret = nw;
620 }
621
622 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
623
624 static void
625 add_successor_phi_arg (edge e, tree var, tree phi_arg)
626 {
627 gphi_iterator gsi;
628
629 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
630 if (PHI_RESULT (gsi.phi ()) == var)
631 break;
632
633 gcc_assert (!gsi_end_p (gsi));
634 add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
635 }
636
637 /* Creates a GIMPLE statement which computes the operation specified by
638 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
639 statement in the position specified by GSI. Returns the
640 tree node of the statement's result. */
641
642 static tree
643 adjust_return_value_with_ops (enum tree_code code, const char *label,
644 tree acc, tree op1, gimple_stmt_iterator gsi)
645 {
646
647 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
648 tree result = make_temp_ssa_name (ret_type, NULL, label);
649 gassign *stmt;
650
651 if (POINTER_TYPE_P (ret_type))
652 {
653 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
654 code = POINTER_PLUS_EXPR;
655 }
656 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
657 && code != POINTER_PLUS_EXPR)
658 stmt = gimple_build_assign (result, code, acc, op1);
659 else
660 {
661 tree tem;
662 if (code == POINTER_PLUS_EXPR)
663 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
664 else
665 tem = fold_build2 (code, TREE_TYPE (op1),
666 fold_convert (TREE_TYPE (op1), acc), op1);
667 tree rhs = fold_convert (ret_type, tem);
668 rhs = force_gimple_operand_gsi (&gsi, rhs,
669 false, NULL, true, GSI_SAME_STMT);
670 stmt = gimple_build_assign (result, rhs);
671 }
672
673 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
674 return result;
675 }
676
677 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
678 the computation specified by CODE and OP1 and insert the statement
679 at the position specified by GSI as a new statement. Returns new SSA name
680 of updated accumulator. */
681
682 static tree
683 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
684 gimple_stmt_iterator gsi)
685 {
686 gassign *stmt;
687 tree var = copy_ssa_name (acc);
688 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
689 stmt = gimple_build_assign (var, code, acc, op1);
690 else
691 {
692 tree rhs = fold_convert (TREE_TYPE (acc),
693 fold_build2 (code,
694 TREE_TYPE (op1),
695 fold_convert (TREE_TYPE (op1), acc),
696 op1));
697 rhs = force_gimple_operand_gsi (&gsi, rhs,
698 false, NULL, false, GSI_CONTINUE_LINKING);
699 stmt = gimple_build_assign (var, rhs);
700 }
701 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
702 return var;
703 }
704
705 /* Adjust the accumulator values according to A and M after GSI, and update
706 the phi nodes on edge BACK. */
707
708 static void
709 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
710 {
711 tree var, a_acc_arg, m_acc_arg;
712
713 if (m)
714 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
715 if (a)
716 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
717
718 a_acc_arg = a_acc;
719 m_acc_arg = m_acc;
720 if (a)
721 {
722 if (m_acc)
723 {
724 if (integer_onep (a))
725 var = m_acc;
726 else
727 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
728 a, gsi);
729 }
730 else
731 var = a;
732
733 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
734 }
735
736 if (m)
737 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
738
739 if (a_acc)
740 add_successor_phi_arg (back, a_acc, a_acc_arg);
741
742 if (m_acc)
743 add_successor_phi_arg (back, m_acc, m_acc_arg);
744 }
745
746 /* Adjust value of the return at the end of BB according to M and A
747 accumulators. */
748
749 static void
750 adjust_return_value (basic_block bb, tree m, tree a)
751 {
752 tree retval;
753 greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
754 gimple_stmt_iterator gsi = gsi_last_bb (bb);
755
756 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
757
758 retval = gimple_return_retval (ret_stmt);
759 if (!retval || retval == error_mark_node)
760 return;
761
762 if (m)
763 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
764 gsi);
765 if (a)
766 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
767 gsi);
768 gimple_return_set_retval (ret_stmt, retval);
769 update_stmt (ret_stmt);
770 }
771
772 /* Subtract COUNT and FREQUENCY from the basic block and it's
773 outgoing edge. */
774 static void
775 decrease_profile (basic_block bb, gcov_type count, int frequency)
776 {
777 edge e;
778 bb->count -= count;
779 if (bb->count < 0)
780 bb->count = 0;
781 bb->frequency -= frequency;
782 if (bb->frequency < 0)
783 bb->frequency = 0;
784 if (!single_succ_p (bb))
785 {
786 gcc_assert (!EDGE_COUNT (bb->succs));
787 return;
788 }
789 e = single_succ_edge (bb);
790 e->count -= count;
791 if (e->count < 0)
792 e->count = 0;
793 }
794
795 /* Returns true if argument PARAM of the tail recursive call needs to be copied
796 when the call is eliminated. */
797
798 static bool
799 arg_needs_copy_p (tree param)
800 {
801 tree def;
802
803 if (!is_gimple_reg (param))
804 return false;
805
806 /* Parameters that are only defined but never used need not be copied. */
807 def = ssa_default_def (cfun, param);
808 if (!def)
809 return false;
810
811 return true;
812 }
813
814 /* Eliminates tail call described by T. TMP_VARS is a list of
815 temporary variables used to copy the function arguments. */
816
817 static void
818 eliminate_tail_call (struct tailcall *t)
819 {
820 tree param, rslt;
821 gimple stmt, call;
822 tree arg;
823 size_t idx;
824 basic_block bb, first;
825 edge e;
826 gphi *phi;
827 gphi_iterator gpi;
828 gimple_stmt_iterator gsi;
829 gimple orig_stmt;
830
831 stmt = orig_stmt = gsi_stmt (t->call_gsi);
832 bb = gsi_bb (t->call_gsi);
833
834 if (dump_file && (dump_flags & TDF_DETAILS))
835 {
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");
840 }
841
842 gcc_assert (is_gimple_call (stmt));
843
844 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
845
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))
852 {
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;
858
859 gsi_remove (&gsi, true);
860 release_defs (t);
861 }
862
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));
870
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;
876
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, gpi = gsi_start_phis (first);
881 param;
882 param = DECL_CHAIN (param), idx++)
883 {
884 if (!arg_needs_copy_p (param))
885 continue;
886
887 arg = gimple_call_arg (stmt, idx);
888 phi = gpi.phi ();
889 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
890
891 add_phi_arg (phi, arg, e, gimple_location (stmt));
892 gsi_next (&gpi);
893 }
894
895 /* Update the values of accumulators. */
896 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
897
898 call = gsi_stmt (t->call_gsi);
899 rslt = gimple_call_lhs (call);
900 if (rslt != NULL_TREE)
901 {
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 ();
905 }
906
907 gsi_remove (&t->call_gsi, true);
908 release_defs (call);
909 }
910
911 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
912 mark the tailcalls for the sibcall optimization. */
913
914 static bool
915 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
916 {
917 if (t->tail_recursion)
918 {
919 eliminate_tail_call (t);
920 return true;
921 }
922
923 if (opt_tailcalls)
924 {
925 gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
926
927 gimple_call_set_tail (stmt, true);
928 cfun->tail_call_marked = true;
929 if (dump_file && (dump_flags & TDF_DETAILS))
930 {
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);
934 }
935 }
936
937 return false;
938 }
939
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. */
945
946 static tree
947 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
948 {
949 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
950 if (POINTER_TYPE_P (ret_type))
951 ret_type = sizetype;
952
953 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
954 gphi *phi;
955
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);
961 }
962
963 /* Optimizes tail calls in the function, turning the tail recursion
964 into iteration. */
965
966 static unsigned int
967 tree_optimize_tail_calls_1 (bool opt_tailcalls)
968 {
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;
977
978 if (!suitable_for_tail_opt_p ())
979 return 0;
980 if (opt_tailcalls)
981 opt_tailcalls = suitable_for_tail_call_opt_p ();
982
983 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
984 {
985 /* Only traverse the normal exits, i.e. those that end with return
986 statement. */
987 stmt = last_stmt (e->src);
988
989 if (stmt
990 && gimple_code (stmt) == GIMPLE_RETURN)
991 find_tail_calls (e->src, &tailcalls);
992 }
993
994 /* Construct the phi nodes and accumulators if necessary. */
995 a_acc = m_acc = NULL_TREE;
996 for (act = tailcalls; act; act = act->next)
997 {
998 if (!act->tail_recursion)
999 continue;
1000
1001 if (!phis_constructed)
1002 {
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)));
1009
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))
1015 {
1016 tree name = ssa_default_def (cfun, param);
1017 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1018 gphi *phi;
1019
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));
1024 }
1025 phis_constructed = true;
1026 }
1027
1028 if (act->add && !a_acc)
1029 a_acc = create_tailcall_accumulator ("add_acc", first,
1030 integer_zero_node);
1031
1032 if (act->mult && !m_acc)
1033 m_acc = create_tailcall_accumulator ("mult_acc", first,
1034 integer_one_node);
1035 }
1036
1037 if (a_acc || m_acc)
1038 {
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;
1043 }
1044
1045 for (; tailcalls; tailcalls = next)
1046 {
1047 next = tailcalls->next;
1048 changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1049 free (tailcalls);
1050 }
1051
1052 if (a_acc || m_acc)
1053 {
1054 /* Modify the remaining return statements. */
1055 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1056 {
1057 stmt = last_stmt (e->src);
1058
1059 if (stmt
1060 && gimple_code (stmt) == GIMPLE_RETURN)
1061 adjust_return_value (e->src, m_acc, a_acc);
1062 }
1063 }
1064
1065 if (changed)
1066 {
1067 /* We may have created new loops. Make them magically appear. */
1068 loops_state_set (LOOPS_NEED_FIXUP);
1069 free_dominance_info (CDI_DOMINATORS);
1070 }
1071
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);
1077
1078 if (changed)
1079 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1080 return 0;
1081 }
1082
1083 static bool
1084 gate_tail_calls (void)
1085 {
1086 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1087 }
1088
1089 static unsigned int
1090 execute_tail_calls (void)
1091 {
1092 return tree_optimize_tail_calls_1 (true);
1093 }
1094
1095 static const pass_data pass_data_tail_recursion =
1096 {
1097 GIMPLE_PASS, /* type */
1098 "tailr", /* name */
1099 OPTGROUP_NONE, /* optinfo_flags */
1100 TV_NONE, /* tv_id */
1101 ( PROP_cfg | PROP_ssa ), /* properties_required */
1102 0, /* properties_provided */
1103 0, /* properties_destroyed */
1104 0, /* todo_flags_start */
1105 0, /* todo_flags_finish */
1106 };
1107
1108 class pass_tail_recursion GCC_FINAL : public gimple_opt_pass
1109 {
1110 public:
1111 pass_tail_recursion (gcc::context *ctxt)
1112 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1113 {}
1114
1115 /* opt_pass methods: */
1116 opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1117 virtual bool gate (function *) { return gate_tail_calls (); }
1118 virtual unsigned int execute (function *)
1119 {
1120 return tree_optimize_tail_calls_1 (false);
1121 }
1122
1123 }; // class pass_tail_recursion
1124
1125 gimple_opt_pass *
1126 make_pass_tail_recursion (gcc::context *ctxt)
1127 {
1128 return new pass_tail_recursion (ctxt);
1129 }
1130
1131 static const pass_data pass_data_tail_calls =
1132 {
1133 GIMPLE_PASS, /* type */
1134 "tailc", /* name */
1135 OPTGROUP_NONE, /* optinfo_flags */
1136 TV_NONE, /* tv_id */
1137 ( PROP_cfg | PROP_ssa ), /* properties_required */
1138 0, /* properties_provided */
1139 0, /* properties_destroyed */
1140 0, /* todo_flags_start */
1141 0, /* todo_flags_finish */
1142 };
1143
1144 class pass_tail_calls GCC_FINAL : public gimple_opt_pass
1145 {
1146 public:
1147 pass_tail_calls (gcc::context *ctxt)
1148 : gimple_opt_pass (pass_data_tail_calls, ctxt)
1149 {}
1150
1151 /* opt_pass methods: */
1152 virtual bool gate (function *) { return gate_tail_calls (); }
1153 virtual unsigned int execute (function *) { return execute_tail_calls (); }
1154
1155 }; // class pass_tail_calls
1156
1157 gimple_opt_pass *
1158 make_pass_tail_calls (gcc::context *ctxt)
1159 {
1160 return new pass_tail_calls (ctxt);
1161 }