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