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