alias.c: Reorder #include statements and remove duplicates.
[platform/upstream/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 "target.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "cfghooks.h"
29 #include "tree-pass.h"
30 #include "tm_p.h"
31 #include "ssa.h"
32 #include "expmed.h"
33 #include "insn-config.h"
34 #include "emit-rtl.h"
35 #include "cgraph.h"
36 #include "gimple-pretty-print.h"
37 #include "alias.h"
38 #include "fold-const.h"
39 #include "stor-layout.h"
40 #include "internal-fn.h"
41 #include "gimple-iterator.h"
42 #include "gimplify-me.h"
43 #include "tree-cfg.h"
44 #include "tree-into-ssa.h"
45 #include "flags.h"
46 #include "dojump.h"
47 #include "explow.h"
48 #include "calls.h"
49 #include "varasm.h"
50 #include "stmt.h"
51 #include "expr.h"
52 #include "tree-dfa.h"
53 #include "except.h"
54 #include "langhooks.h"
55 #include "dbgcnt.h"
56 #include "cfgloop.h"
57 #include "common/common-target.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   gimple_stmt_iterator gsi2 = gsi_last_bb (gimple_bb (gsi_stmt (gsi)));
851   while (gsi_stmt (gsi2) != gsi_stmt (gsi))
852     {
853       gimple *t = gsi_stmt (gsi2);
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         {
858           gimple_stmt_iterator gsi3 = gsi2;
859           gsi_prev (&gsi2);
860           gsi_remove (&gsi3, true);
861           release_defs (t);
862         }
863       else
864         gsi_prev (&gsi2);
865     }
866
867   /* Number of executions of function has reduced by the tailcall.  */
868   e = single_succ_edge (gsi_bb (t->call_gsi));
869   decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), e->count, EDGE_FREQUENCY (e));
870   decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), e->count,
871                     EDGE_FREQUENCY (e));
872   if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
873     decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
874
875   /* Replace the call by a jump to the start of function.  */
876   e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
877                                 first);
878   gcc_assert (e);
879   PENDING_STMT (e) = NULL;
880
881   /* Add phi node entries for arguments.  The ordering of the phi nodes should
882      be the same as the ordering of the arguments.  */
883   for (param = DECL_ARGUMENTS (current_function_decl),
884          idx = 0, gpi = gsi_start_phis (first);
885        param;
886        param = DECL_CHAIN (param), idx++)
887     {
888       if (!arg_needs_copy_p (param))
889         continue;
890
891       arg = gimple_call_arg (stmt, idx);
892       phi = gpi.phi ();
893       gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
894
895       add_phi_arg (phi, arg, e, gimple_location (stmt));
896       gsi_next (&gpi);
897     }
898
899   /* Update the values of accumulators.  */
900   adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
901
902   call = gsi_stmt (t->call_gsi);
903   rslt = gimple_call_lhs (call);
904   if (rslt != NULL_TREE)
905     {
906       /* Result of the call will no longer be defined.  So adjust the
907          SSA_NAME_DEF_STMT accordingly.  */
908       SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
909     }
910
911   gsi_remove (&t->call_gsi, true);
912   release_defs (call);
913 }
914
915 /* Optimizes the tailcall described by T.  If OPT_TAILCALLS is true, also
916    mark the tailcalls for the sibcall optimization.  */
917
918 static bool
919 optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
920 {
921   if (t->tail_recursion)
922     {
923       eliminate_tail_call (t);
924       return true;
925     }
926
927   if (opt_tailcalls)
928     {
929       gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
930
931       gimple_call_set_tail (stmt, true);
932       cfun->tail_call_marked = true;
933       if (dump_file && (dump_flags & TDF_DETAILS))
934         {
935           fprintf (dump_file, "Found tail call ");
936           print_gimple_stmt (dump_file, stmt, 0, dump_flags);
937           fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
938         }
939     }
940
941   return false;
942 }
943
944 /* Creates a tail-call accumulator of the same type as the return type of the
945    current function.  LABEL is the name used to creating the temporary
946    variable for the accumulator.  The accumulator will be inserted in the
947    phis of a basic block BB with single predecessor with an initial value
948    INIT converted to the current function return type.  */
949
950 static tree
951 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
952 {
953   tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
954   if (POINTER_TYPE_P (ret_type))
955     ret_type = sizetype;
956
957   tree tmp = make_temp_ssa_name (ret_type, NULL, label);
958   gphi *phi;
959
960   phi = create_phi_node (tmp, bb);
961   /* RET_TYPE can be a float when -ffast-maths is enabled.  */
962   add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
963                UNKNOWN_LOCATION);
964   return PHI_RESULT (phi);
965 }
966
967 /* Optimizes tail calls in the function, turning the tail recursion
968    into iteration.  */
969
970 static unsigned int
971 tree_optimize_tail_calls_1 (bool opt_tailcalls)
972 {
973   edge e;
974   bool phis_constructed = false;
975   struct tailcall *tailcalls = NULL, *act, *next;
976   bool changed = false;
977   basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
978   tree param;
979   gimple *stmt;
980   edge_iterator ei;
981
982   if (!suitable_for_tail_opt_p ())
983     return 0;
984   if (opt_tailcalls)
985     opt_tailcalls = suitable_for_tail_call_opt_p ();
986
987   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
988     {
989       /* Only traverse the normal exits, i.e. those that end with return
990          statement.  */
991       stmt = last_stmt (e->src);
992
993       if (stmt
994           && gimple_code (stmt) == GIMPLE_RETURN)
995         find_tail_calls (e->src, &tailcalls);
996     }
997
998   /* Construct the phi nodes and accumulators if necessary.  */
999   a_acc = m_acc = NULL_TREE;
1000   for (act = tailcalls; act; act = act->next)
1001     {
1002       if (!act->tail_recursion)
1003         continue;
1004
1005       if (!phis_constructed)
1006         {
1007           /* Ensure that there is only one predecessor of the block
1008              or if there are existing degenerate PHI nodes.  */
1009           if (!single_pred_p (first)
1010               || !gimple_seq_empty_p (phi_nodes (first)))
1011             first =
1012               split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1013
1014           /* Copy the args if needed.  */
1015           for (param = DECL_ARGUMENTS (current_function_decl);
1016                param;
1017                param = DECL_CHAIN (param))
1018             if (arg_needs_copy_p (param))
1019               {
1020                 tree name = ssa_default_def (cfun, param);
1021                 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
1022                 gphi *phi;
1023
1024                 set_ssa_default_def (cfun, param, new_name);
1025                 phi = create_phi_node (name, first);
1026                 add_phi_arg (phi, new_name, single_pred_edge (first),
1027                              EXPR_LOCATION (param));
1028               }
1029           phis_constructed = true;
1030         }
1031
1032       if (act->add && !a_acc)
1033         a_acc = create_tailcall_accumulator ("add_acc", first,
1034                                              integer_zero_node);
1035
1036       if (act->mult && !m_acc)
1037         m_acc = create_tailcall_accumulator ("mult_acc", first,
1038                                              integer_one_node);
1039     }
1040
1041   if (a_acc || m_acc)
1042     {
1043       /* When the tail call elimination using accumulators is performed,
1044          statements adding the accumulated value are inserted at all exits.
1045          This turns all other tail calls to non-tail ones.  */
1046       opt_tailcalls = false;
1047     }
1048
1049   for (; tailcalls; tailcalls = next)
1050     {
1051       next = tailcalls->next;
1052       changed |= optimize_tail_call (tailcalls, opt_tailcalls);
1053       free (tailcalls);
1054     }
1055
1056   if (a_acc || m_acc)
1057     {
1058       /* Modify the remaining return statements.  */
1059       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1060         {
1061           stmt = last_stmt (e->src);
1062
1063           if (stmt
1064               && gimple_code (stmt) == GIMPLE_RETURN)
1065             adjust_return_value (e->src, m_acc, a_acc);
1066         }
1067     }
1068
1069   if (changed)
1070     {
1071       /* We may have created new loops.  Make them magically appear.  */
1072       loops_state_set (LOOPS_NEED_FIXUP);
1073       free_dominance_info (CDI_DOMINATORS);
1074     }
1075
1076   /* Add phi nodes for the virtual operands defined in the function to the
1077      header of the loop created by tail recursion elimination.  Do so
1078      by triggering the SSA renamer.  */
1079   if (phis_constructed)
1080     mark_virtual_operands_for_renaming (cfun);
1081
1082   if (changed)
1083     return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
1084   return 0;
1085 }
1086
1087 static bool
1088 gate_tail_calls (void)
1089 {
1090   return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
1091 }
1092
1093 static unsigned int
1094 execute_tail_calls (void)
1095 {
1096   return tree_optimize_tail_calls_1 (true);
1097 }
1098
1099 namespace {
1100
1101 const pass_data pass_data_tail_recursion =
1102 {
1103   GIMPLE_PASS, /* type */
1104   "tailr", /* name */
1105   OPTGROUP_NONE, /* optinfo_flags */
1106   TV_NONE, /* tv_id */
1107   ( PROP_cfg | PROP_ssa ), /* properties_required */
1108   0, /* properties_provided */
1109   0, /* properties_destroyed */
1110   0, /* todo_flags_start */
1111   0, /* todo_flags_finish */
1112 };
1113
1114 class pass_tail_recursion : public gimple_opt_pass
1115 {
1116 public:
1117   pass_tail_recursion (gcc::context *ctxt)
1118     : gimple_opt_pass (pass_data_tail_recursion, ctxt)
1119   {}
1120
1121   /* opt_pass methods: */
1122   opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
1123   virtual bool gate (function *) { return gate_tail_calls (); }
1124   virtual unsigned int execute (function *)
1125     {
1126       return tree_optimize_tail_calls_1 (false);
1127     }
1128
1129 }; // class pass_tail_recursion
1130
1131 } // anon namespace
1132
1133 gimple_opt_pass *
1134 make_pass_tail_recursion (gcc::context *ctxt)
1135 {
1136   return new pass_tail_recursion (ctxt);
1137 }
1138
1139 namespace {
1140
1141 const pass_data pass_data_tail_calls =
1142 {
1143   GIMPLE_PASS, /* type */
1144   "tailc", /* name */
1145   OPTGROUP_NONE, /* optinfo_flags */
1146   TV_NONE, /* tv_id */
1147   ( PROP_cfg | PROP_ssa ), /* properties_required */
1148   0, /* properties_provided */
1149   0, /* properties_destroyed */
1150   0, /* todo_flags_start */
1151   0, /* todo_flags_finish */
1152 };
1153
1154 class pass_tail_calls : public gimple_opt_pass
1155 {
1156 public:
1157   pass_tail_calls (gcc::context *ctxt)
1158     : gimple_opt_pass (pass_data_tail_calls, ctxt)
1159   {}
1160
1161   /* opt_pass methods: */
1162   virtual bool gate (function *) { return gate_tail_calls (); }
1163   virtual unsigned int execute (function *) { return execute_tail_calls (); }
1164
1165 }; // class pass_tail_calls
1166
1167 } // anon namespace
1168
1169 gimple_opt_pass *
1170 make_pass_tail_calls (gcc::context *ctxt)
1171 {
1172   return new pass_tail_calls (ctxt);
1173 }