Debian Codegraph @

gcc/tree-tailcall.cc

raw
1 /* Tail call optimization on trees.
2 Copyright (C) 2003-2025 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 "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "cgraph.h"
31 #include "gimple-pretty-print.h"
32 #include "fold-const.h"
33 #include "stor-layout.h"
34 #include "gimple-iterator.h"
35 #include "gimplify-me.h"
36 #include "tree-cfg.h"
37 #include "tree-into-ssa.h"
38 #include "tree-dfa.h"
39 #include "except.h"
40 #include "tree-eh.h"
41 #include "dbgcnt.h"
42 #include "cfgloop.h"
43 #include "intl.h"
44 #include "common/common-target.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-live.h"
47 #include "diagnostic-core.h"
48 #include "gimple-range.h"
49 #include "alloc-pool.h"
50 #include "sreal.h"
51 #include "symbol-summary.h"
52 #include "ipa-cp.h"
53 #include "ipa-prop.h"
54 #include "attribs.h"
55 #include "asan.h"
56
57 /* The file implements the tail recursion elimination. It is also used to
58 analyze the tail calls in general, passing the results to the rtl level
59 where they are used for sibcall optimization.
60
61 In addition to the standard tail recursion elimination, we handle the most
62 trivial cases of making the call tail recursive by creating accumulators.
63 For example the following function
64
65 int sum (int n)
66 {
67 if (n > 0)
68 return n + sum (n - 1);
69 else
70 return 0;
71 }
72
73 is transformed into
74
75 int sum (int n)
76 {
77 int acc = 0;
78
79 while (n > 0)
80 acc += n--;
81
82 return acc;
83 }
84
85 To do this, we maintain two accumulators (a_acc and m_acc) that indicate
86 when we reach the return x statement, we should return a_acc + x * m_acc
87 instead. They are initially initialized to 0 and 1, respectively,
88 so the semantics of the function is obviously preserved. If we are
89 guaranteed that the value of the accumulator never change, we
90 omit the accumulator.
91
92 There are three cases how the function may exit. The first one is
93 handled in adjust_return_value, the other two in adjust_accumulator_values
94 (the second case is actually a special case of the third one and we
95 present it separately just for clarity):
96
97 1) Just return x, where x is not in any of the remaining special shapes.
98 We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
99
100 2) return f (...), where f is the current function, is rewritten in a
101 classical tail-recursion elimination way, into assignment of arguments
102 and jump to the start of the function. Values of the accumulators
103 are unchanged.
104
105 3) return a + m * f(...), where a and m do not depend on call to f.
106 To preserve the semantics described before we want this to be rewritten
107 in such a way that we finally return
108
109 a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
110
111 I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
112 eliminate the tail call to f. Special cases when the value is just
113 added or just multiplied are obtained by setting a = 0 or m = 1.
114
115 TODO -- it is possible to do similar tricks for other operations. */
116
117 /* A structure that describes the tailcall. */
118
119 struct tailcall
120 {
121 /* The iterator pointing to the call statement. */
122 gimple_stmt_iterator call_gsi;
123
124 /* True if it is a call to the current function. */
125 bool tail_recursion;
126
127 /* True if there is __tsan_func_exit call after the call. */
128 bool has_tsan_func_exit;
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 /* Bitmap with a bit for each function parameter which is set to true if we
143 have to copy the parameter for conversion of tail-recursive calls. */
144
145 static bitmap tailr_arg_needs_copy;
146
147 static void maybe_error_musttail (gcall *call, const char *err, bool);
148
149 /* Returns false when the function is not suitable for tail call optimization
150 from some reason (e.g. if it takes variable number of arguments). CALL
151 is call to report for. */
152
153 static bool
154 suitable_for_tail_opt_p (gcall *call, bool diag_musttail)
155 {
156 if (cfun->stdarg)
157 {
158 maybe_error_musttail (call, _("caller uses stdargs"), diag_musttail);
159 return false;
160 }
161
162 return true;
163 }
164
165 /* Returns false when the function is not suitable for tail call optimization
166 for some reason (e.g. if it takes variable number of arguments).
167 This test must pass in addition to suitable_for_tail_opt_p in order to make
168 tail call discovery happen. CALL is call to report error for. */
169
170 static bool
171 suitable_for_tail_call_opt_p (gcall *call, bool diag_musttail)
172 {
173 /* alloca (until we have stack slot life analysis) inhibits
174 sibling call optimizations, but not tail recursion. */
175 if (cfun->calls_alloca)
176 {
177 maybe_error_musttail (call, _("caller uses alloca"), diag_musttail);
178 return false;
179 }
180
181 /* If we are using sjlj exceptions, we may need to add a call to
182 _Unwind_SjLj_Unregister at exit of the function. Which means
183 that we cannot do any sibcall transformations. */
184 if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
185 && current_function_has_exception_handlers ())
186 {
187 maybe_error_musttail (call, _("caller uses sjlj exceptions"),
188 diag_musttail);
189 return false;
190 }
191
192 /* Any function that calls setjmp might have longjmp called from
193 any called function. ??? We really should represent this
194 properly in the CFG so that this needn't be special cased. */
195 if (cfun->calls_setjmp)
196 {
197 maybe_error_musttail (call, _("caller uses setjmp"), diag_musttail);
198 return false;
199 }
200
201 /* Various targets don't handle tail calls correctly in functions
202 that call __builtin_eh_return. */
203 if (cfun->calls_eh_return)
204 {
205 maybe_error_musttail (call, _("caller uses __builtin_eh_return"),
206 diag_musttail);
207 return false;
208 }
209
210 if (diag_musttail
211 && gimple_call_must_tail_p (call)
212 && warn_musttail_local_addr)
213 for (unsigned int i = 0; i < gimple_call_num_args (call); i++)
214 {
215 tree arg = gimple_call_arg (call, i);
216 if (!POINTER_TYPE_P (TREE_TYPE (arg)))
217 continue;
218 if (TREE_CODE (arg) == ADDR_EXPR)
219 {
220 arg = get_base_address (TREE_OPERAND (arg, 0));
221 if (auto_var_in_fn_p (arg, current_function_decl))
222 {
223 if (TREE_CODE (arg) == LABEL_DECL)
224 warning_at (gimple_location (call), OPT_Wmusttail_local_addr,
225 "address of label passed to %<musttail%> "
226 "call argument");
227 else if (TREE_CODE (arg) == PARM_DECL)
228 warning_at (gimple_location (call), OPT_Wmusttail_local_addr,
229 "address of parameter %qD passed to "
230 "%<musttail%> call argument", arg);
231 else if (!DECL_ARTIFICIAL (arg) && DECL_NAME (arg))
232 warning_at (gimple_location (call), OPT_Wmusttail_local_addr,
233 "address of automatic variable %qD passed to "
234 "%<musttail%> call argument", arg);
235 else
236 warning_at (gimple_location (call), OPT_Wmusttail_local_addr,
237 "address of local variable passed to "
238 "%<musttail%> call argument");
239 suppress_warning (call, OPT_Wmaybe_musttail_local_addr);
240 }
241 }
242 }
243
244 return true;
245 }
246
247 /* Return single successor edge ignoring EDGE_EH edges. */
248
249 static edge
250 single_non_eh_succ_edge (basic_block bb)
251 {
252 edge e, ret = NULL;
253 edge_iterator ei;
254 FOR_EACH_EDGE (e, ei, bb->succs)
255 if ((e->flags & EDGE_EH) == 0)
256 {
257 gcc_assert (ret == NULL);
258 ret = e;
259 }
260 gcc_assert (ret);
261 return ret;
262 }
263
264 /* Checks whether the expression EXPR in stmt AT is independent of the
265 statement pointed to by GSI (in a sense that we already know EXPR's value
266 at GSI). We use the fact that we are only called from the chain of
267 basic blocks that have only single successor. Returns the expression
268 containing the value of EXPR at GSI. */
269
270 static tree
271 independent_of_stmt_p (tree expr, gimple *at, gimple_stmt_iterator gsi,
272 bitmap to_move)
273 {
274 basic_block bb, call_bb, at_bb;
275 edge e;
276 edge_iterator ei;
277
278 if (is_gimple_min_invariant (expr))
279 return expr;
280
281 if (TREE_CODE (expr) != SSA_NAME)
282 return NULL_TREE;
283
284 if (bitmap_bit_p (to_move, SSA_NAME_VERSION (expr)))
285 return expr;
286
287 /* Mark the blocks in the chain leading to the end. */
288 at_bb = gimple_bb (at);
289 call_bb = gimple_bb (gsi_stmt (gsi));
290 for (bb = call_bb; bb != at_bb; bb = single_non_eh_succ_edge (bb)->dest)
291 bb->aux = &bb->aux;
292 bb->aux = &bb->aux;
293
294 while (1)
295 {
296 at = SSA_NAME_DEF_STMT (expr);
297 bb = gimple_bb (at);
298
299 /* The default definition or defined before the chain. */
300 if (!bb || !bb->aux)
301 break;
302
303 if (bb == call_bb)
304 {
305 for (; !gsi_end_p (gsi); gsi_next (&gsi))
306 if (gsi_stmt (gsi) == at)
307 break;
308
309 if (!gsi_end_p (gsi))
310 expr = NULL_TREE;
311 break;
312 }
313
314 if (gimple_code (at) != GIMPLE_PHI)
315 {
316 expr = NULL_TREE;
317 break;
318 }
319
320 FOR_EACH_EDGE (e, ei, bb->preds)
321 if (e->src->aux)
322 break;
323 gcc_assert (e);
324
325 expr = PHI_ARG_DEF_FROM_EDGE (at, e);
326 if (TREE_CODE (expr) != SSA_NAME)
327 {
328 /* The value is a constant. */
329 break;
330 }
331 }
332
333 /* Unmark the blocks. */
334 for (bb = call_bb; bb != at_bb; bb = single_non_eh_succ_edge (bb)->dest)
335 bb->aux = NULL;
336 bb->aux = NULL;
337
338 return expr;
339 }
340
341 enum par { FAIL, OK, TRY_MOVE };
342
343 /* Simulates the effect of an assignment STMT on the return value of the tail
344 recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
345 additive factor for the real return value. */
346
347 static par
348 process_assignment (gassign *stmt,
349 gimple_stmt_iterator call, tree *m,
350 tree *a, tree *ass_var, bitmap to_move)
351 {
352 tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
353 tree dest = gimple_assign_lhs (stmt);
354 enum tree_code code = gimple_assign_rhs_code (stmt);
355 enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
356 tree src_var = gimple_assign_rhs1 (stmt);
357
358 /* See if this is a simple copy operation of an SSA name to the function
359 result. In that case we may have a simple tail call. Ignore type
360 conversions that can never produce extra code between the function
361 call and the function return. */
362 if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
363 && src_var == *ass_var)
364 {
365 /* Reject a tailcall if the type conversion might need
366 additional code. */
367 if (gimple_assign_cast_p (stmt))
368 {
369 if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
370 return FAIL;
371
372 /* Even if the type modes are the same, if the precision of the
373 type is smaller than mode's precision,
374 reduce_to_bit_field_precision would generate additional code. */
375 if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
376 && !type_has_mode_precision_p (TREE_TYPE (dest)))
377 return FAIL;
378 }
379
380 *ass_var = dest;
381 return OK;
382 }
383
384 switch (rhs_class)
385 {
386 case GIMPLE_BINARY_RHS:
387 op1 = gimple_assign_rhs2 (stmt);
388
389 /* Fall through. */
390
391 case GIMPLE_UNARY_RHS:
392 op0 = gimple_assign_rhs1 (stmt);
393 break;
394
395 default:
396 return FAIL;
397 }
398
399 /* Accumulator optimizations will reverse the order of operations.
400 We can only do that for floating-point types if we're assuming
401 that addition and multiplication are associative. */
402 if (!flag_associative_math)
403 if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
404 return FAIL;
405
406 /* We at least cannot build -1 for all fixed point types. */
407 if (FIXED_POINT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
408 return FAIL;
409
410 if (rhs_class == GIMPLE_UNARY_RHS
411 && op0 == *ass_var)
412 ;
413 else if (op0 == *ass_var
414 && (non_ass_var = independent_of_stmt_p (op1, stmt, call,
415 to_move)))
416 ;
417 else if (*ass_var
418 && op1 == *ass_var
419 && (non_ass_var = independent_of_stmt_p (op0, stmt, call,
420 to_move)))
421 ;
422 else
423 return TRY_MOVE;
424
425 switch (code)
426 {
427 case PLUS_EXPR:
428 *a = non_ass_var;
429 *ass_var = dest;
430 return OK;
431
432 case POINTER_PLUS_EXPR:
433 if (op0 != *ass_var)
434 return FAIL;
435 *a = non_ass_var;
436 *ass_var = dest;
437 return OK;
438
439 case MULT_EXPR:
440 *m = non_ass_var;
441 *ass_var = dest;
442 return OK;
443
444 case NEGATE_EXPR:
445 *m = build_minus_one_cst (TREE_TYPE (op0));
446 *ass_var = dest;
447 return OK;
448
449 case MINUS_EXPR:
450 if (*ass_var == op0)
451 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
452 else
453 {
454 *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
455 *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
456 }
457
458 *ass_var = dest;
459 return OK;
460
461 default:
462 return FAIL;
463 }
464 }
465
466 /* Propagate VAR through phis on edge E. */
467
468 static tree
469 propagate_through_phis (tree var, edge e)
470 {
471 basic_block dest = e->dest;
472 gphi_iterator gsi;
473
474 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
475 {
476 gphi *phi = gsi.phi ();
477 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
478 return PHI_RESULT (phi);
479 }
480 return var;
481 }
482
483 /* Report an error for failing to tail convert must call CALL
484 with error message ERR. Also clear the flag to prevent further
485 errors. */
486
487 static void
488 maybe_error_musttail (gcall *call, const char *err, bool diag_musttail)
489 {
490 if (gimple_call_must_tail_p (call) && diag_musttail)
491 {
492 error_at (gimple_location (call), "cannot tail-call: %s", err);
493 /* Avoid another error. ??? If there are multiple reasons why tail
494 calls fail it might be useful to report them all to avoid
495 whack-a-mole for the user. But currently there is too much
496 redundancy in the reporting, so keep it simple. */
497 gimple_call_set_must_tail (call, false); /* Avoid another error. */
498 gimple_call_set_tail (call, false);
499 }
500 if (dump_file && (dump_flags & TDF_DETAILS))
501 {
502 fprintf (dump_file, "Cannot tail-call: %s: ", err);
503 print_gimple_stmt (dump_file, call, 0, TDF_SLIM);
504 }
505 }
506
507 /* Return true if there is no real work performed in the exception
508 path starting at BB and it will in the end result in external exception.
509 Search at most CNT basic blocks (so that we don't need to do trivial
510 loop discovery). */
511 static bool
512 empty_eh_cleanup (basic_block bb, int *eh_has_tsan_func_exit, int cnt)
513 {
514 if (EDGE_COUNT (bb->succs) > 1)
515 return false;
516
517 for (gimple_stmt_iterator gsi = gsi_after_labels (bb); !gsi_end_p (gsi);
518 gsi_next (&gsi))
519 {
520 gimple *g = gsi_stmt (gsi);
521 if (is_gimple_debug (g) || gimple_clobber_p (g))
522 continue;
523 if (eh_has_tsan_func_exit
524 && !*eh_has_tsan_func_exit
525 && sanitize_flags_p (SANITIZE_THREAD)
526 && gimple_call_builtin_p (g, BUILT_IN_TSAN_FUNC_EXIT))
527 {
528 *eh_has_tsan_func_exit = 1;
529 continue;
530 }
531 if (eh_has_tsan_func_exit
532 && sanitize_flags_p (SANITIZE_ADDRESS)
533 && asan_mark_p (g, ASAN_MARK_POISON))
534 continue;
535 if (is_gimple_resx (g))
536 {
537 if (stmt_can_throw_external (cfun, g))
538 return true;
539 if (single_succ_p (bb)
540 && (single_succ_edge (bb)->flags & EDGE_EH)
541 && cnt > 1)
542 return empty_eh_cleanup (single_succ (bb), eh_has_tsan_func_exit,
543 cnt - 1);
544 }
545 return false;
546 }
547 if (!single_succ_p (bb))
548 return false;
549 if (cnt == 1)
550 return false;
551 return empty_eh_cleanup (single_succ (bb), eh_has_tsan_func_exit, cnt - 1);
552 }
553
554 /* Argument for compute_live_vars/live_vars_at_stmt and what compute_live_vars
555 returns. Computed lazily, but just once for the function. */
556 static live_vars_map *live_vars;
557 static vec<bitmap_head> live_vars_vec;
558
559 /* Finds tailcalls falling into basic block BB when coming from edge ESUCC (or
560 NULL). The list of found tailcalls is added to the start of RET.
561 When ONLY_MUSTTAIL is set only handle musttail.
562 Update OPT_TAILCALLS as output parameter. If DIAG_MUSTTAIL, diagnose
563 failures for musttail calls. RETRY_TSAN_FUNC_EXIT is initially 0 and
564 in that case the last call is attempted to be tail called, including
565 __tsan_func_exit with -fsanitize=thread. It is set to -1 if we
566 detect __tsan_func_exit call and in that case tree_optimize_tail_calls_1
567 will retry with it set to 1 (regardless of whether turning the
568 __tsan_func_exit was successfully detected as tail call or not) and that
569 will allow turning musttail calls before that call into tail calls as well
570 by adding __tsan_func_exit call before the call.
571 IGNORED_EDGES and MUST_SEE_BBS are used in recursive calls when handling
572 GIMPLE_CONDs for cleanups. */
573
574 static void
575 find_tail_calls (basic_block bb, edge esucc, struct tailcall **ret,
576 bool only_musttail, bool &opt_tailcalls, bool diag_musttail,
577 int &retry_tsan_func_exit, hash_set<edge> *ignored_edges,
578 hash_set<basic_block> *must_see_bbs)
579 {
580 tree ass_var = NULL_TREE, ret_var, func, param;
581 gimple *stmt;
582 gcall *call = NULL;
583 gimple_stmt_iterator gsi, agsi;
584 bool tail_recursion;
585 struct tailcall *nw;
586 edge e;
587 tree m, a;
588 basic_block abb;
589 size_t idx;
590 tree var;
591 bool only_tailr = false;
592 bool has_tsan_func_exit = false;
593 int eh_has_tsan_func_exit = -1;
594 bool delete_ignored_edges = false;
595
596 if (!single_succ_p (bb)
597 && (EDGE_COUNT (bb->succs) || !cfun->has_musttail || !diag_musttail))
598 {
599 if (EDGE_COUNT (bb->succs) == 2
600 && esucc
601 && cfun->has_musttail
602 && diag_musttail
603 && (EDGE_SUCC (bb, 0)->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))
604 && (EDGE_SUCC (bb, 1)->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))
605 && (stmt = last_nondebug_stmt (bb))
606 && gimple_code (stmt) == GIMPLE_COND)
607 ;
608 else if (esucc
609 && cfun->has_musttail
610 && diag_musttail
611 && (stmt = last_nondebug_stmt (bb))
612 && gimple_code (stmt) == GIMPLE_SWITCH)
613 ;
614 /* If there is an abnormal edge assume it's the only extra one.
615 Tolerate that case so that we can give better error messages
616 for musttail later. */
617 else if (!has_abnormal_or_eh_outgoing_edge_p (bb))
618 {
619 if (dump_file)
620 fprintf (dump_file, "Basic block %d has extra exit edges\n",
621 bb->index);
622 return;
623 }
624 if (!cfun->has_musttail)
625 return;
626 }
627
628 bool bad_stmt = false;
629 gimple *last_stmt = nullptr;
630 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
631 {
632 stmt = gsi_stmt (gsi);
633
634 /* Ignore labels, returns, nops, clobbers and debug stmts. */
635 if (gimple_code (stmt) == GIMPLE_LABEL
636 || gimple_code (stmt) == GIMPLE_RETURN
637 || gimple_code (stmt) == GIMPLE_NOP
638 || gimple_code (stmt) == GIMPLE_PREDICT
639 || gimple_clobber_p (stmt)
640 || is_gimple_debug (stmt))
641 continue;
642
643 if (cfun->has_musttail
644 && sanitize_flags_p (SANITIZE_THREAD)
645 && gimple_call_builtin_p (stmt, BUILT_IN_TSAN_FUNC_EXIT)
646 && diag_musttail)
647 {
648 if (retry_tsan_func_exit == 0)
649 retry_tsan_func_exit = -1;
650 else if (retry_tsan_func_exit == 1)
651 continue;
652 }
653
654 if (cfun->has_musttail
655 && sanitize_flags_p (SANITIZE_ADDRESS)
656 && asan_mark_p (stmt, ASAN_MARK_POISON)
657 && diag_musttail)
658 continue;
659
660 /* Especially at -O0 with -fsanitize=address we can end up with
661 code like
662 _26 = foo (x_24(D)); [must tail call]
663 finally_tmp.3_27 = 0;
664 goto <bb 5>; [INV]
665
666 ...
667
668 <bb 5> :
669 # _6 = PHI <_26(3), _23(D)(4)>
670 # finally_tmp.3_8 = PHI <finally_tmp.3_27(3), finally_tmp.3_22(4)>
671 .ASAN_MARK (POISON, &c, 4);
672 if (finally_tmp.3_8 == 1)
673 goto <bb 7>; [INV]
674 else
675 goto <bb 6>; [INV]
676 When walking backwards, ESUCC is the edge we are coming from,
677 depending on its EDGE_TRUE_FLAG, comparison code
678 and value compared against try to find out through which edge
679 we need to go and which edge should be ignored. The code handles
680 both INTEGER_CST PHI arguments and SSA_NAMEs set to constants
681 (for -O0 where those aren't propagated). */
682 if (cfun->has_musttail
683 && diag_musttail
684 && esucc
685 && gimple_code (stmt) == GIMPLE_COND
686 && TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
687 && TREE_CODE (gimple_cond_rhs (stmt)) == INTEGER_CST
688 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
689 && tree_int_cst_sgn (gimple_cond_rhs (stmt)) >= 0)
690 {
691 tree lhs = gimple_cond_lhs (stmt);
692 tree_code ccode = gimple_cond_code (stmt);
693 tree rhsv = gimple_cond_rhs (stmt);
694 if ((esucc->flags & EDGE_FALSE_VALUE) != 0)
695 ccode = invert_tree_comparison (ccode, false);
696 if (!ignored_edges)
697 {
698 ignored_edges = new hash_set<edge>;
699 must_see_bbs = new hash_set<basic_block>;
700 delete_ignored_edges = true;
701 }
702 if (is_gimple_assign (SSA_NAME_DEF_STMT (lhs))
703 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (lhs))
704 == INTEGER_CST))
705 {
706 tree lhsv = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (lhs));
707
708 if (const_binop (ccode, boolean_type_node, lhsv, rhsv)
709 == boolean_true_node)
710 continue;
711 }
712 else if (gimple_code (SSA_NAME_DEF_STMT (lhs)) == GIMPLE_PHI)
713 {
714 gimple *phi = SSA_NAME_DEF_STMT (lhs);
715 basic_block pbb = gimple_bb (phi);
716 must_see_bbs->add (pbb);
717 edge_iterator ei;
718 FOR_EACH_EDGE (e, ei, pbb->preds)
719 {
720 tree lhsv = gimple_phi_arg_def_from_edge (phi, e);
721 if (TREE_CODE (lhsv) == SSA_NAME
722 && is_gimple_assign (SSA_NAME_DEF_STMT (lhsv))
723 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (lhsv))
724 == INTEGER_CST))
725 lhsv = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (lhsv));
726 if (TREE_CODE (lhsv) != INTEGER_CST
727 || const_binop (ccode, boolean_type_node,
728 lhsv, rhsv) != boolean_true_node)
729 ignored_edges->add (e);
730 }
731 continue;
732 }
733 }
734 if (cfun->has_musttail
735 && diag_musttail
736 && esucc
737 && gimple_code (stmt) == GIMPLE_SWITCH
738 && (TREE_CODE (gimple_switch_index (as_a <gswitch *> (stmt)))
739 == SSA_NAME))
740 {
741 gswitch *swtch = as_a <gswitch *> (stmt);
742 tree idx = gimple_switch_index (swtch);
743 if (!ignored_edges)
744 {
745 ignored_edges = new hash_set<edge>;
746 must_see_bbs = new hash_set<basic_block>;
747 delete_ignored_edges = true;
748 }
749 if (is_gimple_assign (SSA_NAME_DEF_STMT (idx))
750 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (idx))
751 == INTEGER_CST))
752 {
753 tree val = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (idx));
754 if (find_taken_edge_switch_expr (swtch, val) == esucc)
755 continue;
756 }
757 else if (gimple_code (SSA_NAME_DEF_STMT (idx)) == GIMPLE_PHI)
758 {
759 gimple *phi = SSA_NAME_DEF_STMT (idx);
760 basic_block pbb = gimple_bb (phi);
761 must_see_bbs->add (pbb);
762 edge_iterator ei;
763 FOR_EACH_EDGE (e, ei, pbb->preds)
764 {
765 tree val = gimple_phi_arg_def_from_edge (phi, e);
766 if (TREE_CODE (val) == SSA_NAME
767 && is_gimple_assign (SSA_NAME_DEF_STMT (val))
768 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (val))
769 == INTEGER_CST))
770 val = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (val));
771 if (TREE_CODE (val) != INTEGER_CST
772 || find_taken_edge_switch_expr (swtch, val) != esucc)
773 ignored_edges->add (e);
774 }
775 continue;
776 }
777 }
778
779 if (!last_stmt)
780 last_stmt = stmt;
781 /* Check for a call. */
782 if (is_gimple_call (stmt))
783 {
784 call = as_a <gcall *> (stmt);
785 /* Handle only musttail calls when not optimizing. */
786 if (only_musttail && !gimple_call_must_tail_p (call))
787 {
788 maybe_delete_ignored_edges:
789 if (delete_ignored_edges)
790 {
791 delete ignored_edges;
792 delete must_see_bbs;
793 }
794 return;
795 }
796 if (bad_stmt)
797 {
798 maybe_error_musttail (call, _("memory reference or volatile "
799 "after call"), diag_musttail);
800 goto maybe_delete_ignored_edges;
801 }
802 ass_var = gimple_call_lhs (call);
803 break;
804 }
805
806 /* Allow simple copies between local variables, even if they're
807 aggregates. */
808 if (is_gimple_assign (stmt)
809 && auto_var_in_fn_p (gimple_assign_lhs (stmt), cfun->decl)
810 && auto_var_in_fn_p (gimple_assign_rhs1 (stmt), cfun->decl))
811 continue;
812
813 /* If the statement references memory or volatile operands, fail. */
814 if (gimple_references_memory_p (stmt)
815 || gimple_has_volatile_ops (stmt))
816 {
817 if (dump_file)
818 {
819 fprintf (dump_file, "Cannot handle ");
820 print_gimple_stmt (dump_file, stmt, 0);
821 }
822 bad_stmt = true;
823 if (!cfun->has_musttail)
824 break;
825 }
826 }
827
828 if (bad_stmt)
829 goto maybe_delete_ignored_edges;
830
831 if (gsi_end_p (gsi))
832 {
833 if (must_see_bbs)
834 must_see_bbs->remove (bb);
835
836 edge_iterator ei;
837 /* Recurse to the predecessors. */
838 FOR_EACH_EDGE (e, ei, bb->preds)
839 {
840 if (ignored_edges && ignored_edges->contains (e))
841 continue;
842 find_tail_calls (e->src, e, ret, only_musttail, opt_tailcalls,
843 diag_musttail, retry_tsan_func_exit, ignored_edges,
844 must_see_bbs);
845 }
846
847 goto maybe_delete_ignored_edges;
848 }
849
850 if (must_see_bbs && !must_see_bbs->is_empty ())
851 goto maybe_delete_ignored_edges;
852
853 if (delete_ignored_edges)
854 {
855 delete ignored_edges;
856 delete must_see_bbs;
857 }
858
859 if (!suitable_for_tail_opt_p (call, diag_musttail))
860 return;
861
862 if (!suitable_for_tail_call_opt_p (call, diag_musttail))
863 opt_tailcalls = false;
864
865 /* ??? It is OK if the argument of a function is taken in some cases,
866 but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
867 if (!diag_musttail || !gimple_call_must_tail_p (call))
868 for (param = DECL_ARGUMENTS (current_function_decl);
869 param; param = DECL_CHAIN (param))
870 if (TREE_ADDRESSABLE (param))
871 {
872 maybe_error_musttail (call, _("address of caller arguments taken"),
873 diag_musttail);
874 /* If current function has musttail calls, we can't disable tail
875 calls altogether for the whole caller, because those might be
876 actually fine. So just punt if this exact call is not
877 a tail recursion. */
878 if (cfun->has_musttail)
879 only_tailr = true;
880 else
881 opt_tailcalls = false;
882 }
883
884 /* If the LHS of our call is not just a simple register or local
885 variable, we can't transform this into a tail or sibling call.
886 This situation happens, in (e.g.) "*p = foo()" where foo returns a
887 struct. In this case we won't have a temporary here, but we need
888 to carry out the side effect anyway, so tailcall is impossible.
889
890 ??? In some situations (when the struct is returned in memory via
891 invisible argument) we could deal with this, e.g. by passing 'p'
892 itself as that argument to foo, but it's too early to do this here,
893 and expand_call() will not handle it anyway. If it ever can, then
894 we need to revisit this here, to allow that situation. */
895 if (ass_var
896 && !is_gimple_reg (ass_var)
897 && !auto_var_in_fn_p (ass_var, cfun->decl))
898 {
899 maybe_error_musttail (call, _("return value in memory"), diag_musttail);
900 return;
901 }
902
903 if (cfun->calls_setjmp)
904 {
905 maybe_error_musttail (call, _("caller uses setjmp"), diag_musttail);
906 return;
907 }
908
909 /* If the call might throw an exception that wouldn't propagate out of
910 cfun, we can't transform to a tail or sibling call (82081). */
911 if ((stmt_could_throw_p (cfun, stmt)
912 && !stmt_can_throw_external (cfun, stmt)) || EDGE_COUNT (bb->succs) > 1)
913 {
914 if (stmt != last_stmt)
915 {
916 maybe_error_musttail (call, _("code between call and return"),
917 diag_musttail);
918 return;
919 }
920
921 edge e;
922 edge_iterator ei;
923 FOR_EACH_EDGE (e, ei, bb->succs)
924 if (e->flags & EDGE_EH)
925 break;
926
927 if (!e)
928 {
929 maybe_error_musttail (call, _("call may throw exception that does not "
930 "propagate"), diag_musttail);
931 return;
932 }
933
934 if (diag_musttail && gimple_call_must_tail_p (call))
935 eh_has_tsan_func_exit = 0;
936 if (!gimple_call_must_tail_p (call)
937 || !empty_eh_cleanup (e->dest,
938 eh_has_tsan_func_exit
939 ? NULL : &eh_has_tsan_func_exit, 20)
940 || EDGE_COUNT (bb->succs) > 2)
941 {
942 maybe_error_musttail (call, _("call may throw exception caught "
943 "locally or perform cleanups"),
944 diag_musttail);
945 return;
946 }
947 }
948
949 /* If the function returns a value, then at present, the tail call
950 must return the same type of value. There is conceptually a copy
951 between the object returned by the tail call candidate and the
952 object returned by CFUN itself.
953
954 This means that if we have:
955
956 lhs = f (&<retval>); // f reads from <retval>
957 // (lhs is usually also <retval>)
958
959 there is a copy between the temporary object returned by f and lhs,
960 meaning that any use of <retval> in f occurs before the assignment
961 to lhs begins. Thus the <retval> that is live on entry to the call
962 to f is really an independent local variable V that happens to be
963 stored in the RESULT_DECL rather than a local VAR_DECL.
964
965 Turning this into a tail call would remove the copy and make the
966 lifetimes of the return value and V overlap. The same applies to
967 tail recursion, since if f can read from <retval>, we have to assume
968 that CFUN might already have written to <retval> before the call.
969
970 The problem doesn't apply when <retval> is passed by value, but that
971 isn't a case we handle anyway. */
972 tree result_decl = DECL_RESULT (cfun->decl);
973 if (result_decl
974 && may_be_aliased (result_decl)
975 && ref_maybe_used_by_stmt_p (call, result_decl, false))
976 {
977 maybe_error_musttail (call, _("return value used after call"),
978 diag_musttail);
979 return;
980 }
981
982 /* We found the call, check whether it is suitable. */
983 tail_recursion = false;
984 func = gimple_call_fndecl (call);
985 if (func
986 && !fndecl_built_in_p (func)
987 && recursive_call_p (current_function_decl, func)
988 && !only_musttail)
989 {
990 tree arg;
991
992 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
993 param && idx < gimple_call_num_args (call);
994 param = DECL_CHAIN (param), idx ++)
995 {
996 arg = gimple_call_arg (call, idx);
997 if (param != arg)
998 {
999 /* Make sure there are no problems with copying. The parameter
1000 have a copyable type and the two arguments must have reasonably
1001 equivalent types. The latter requirement could be relaxed if
1002 we emitted a suitable type conversion statement. */
1003 if (TREE_ADDRESSABLE (TREE_TYPE (param))
1004 || !useless_type_conversion_p (TREE_TYPE (param),
1005 TREE_TYPE (arg)))
1006 break;
1007
1008 if (is_gimple_reg_type (TREE_TYPE (param))
1009 ? !is_gimple_reg (param)
1010 : (!is_gimple_variable (param)
1011 || TREE_THIS_VOLATILE (param)
1012 || may_be_aliased (param)
1013 || !gimple_call_must_tail_p (call)))
1014 break;
1015 }
1016 }
1017 if (idx == gimple_call_num_args (call) && !param)
1018 tail_recursion = true;
1019 }
1020
1021 if (only_tailr && !tail_recursion)
1022 return;
1023
1024 /* Compute live vars if not computed yet. */
1025 if (live_vars == NULL)
1026 {
1027 unsigned int cnt = 0;
1028 FOR_EACH_LOCAL_DECL (cfun, idx, var)
1029 if (VAR_P (var)
1030 && auto_var_in_fn_p (var, cfun->decl)
1031 && may_be_aliased (var))
1032 {
1033 if (live_vars == NULL)
1034 live_vars = new live_vars_map;
1035 live_vars->put (DECL_UID (var), cnt++);
1036 }
1037 if (live_vars)
1038 live_vars_vec = compute_live_vars (cfun, live_vars);
1039 }
1040
1041 /* Determine a bitmap of variables which are still in scope after the
1042 call. */
1043 bitmap local_live_vars = NULL;
1044 if (live_vars)
1045 local_live_vars = live_vars_at_stmt (live_vars_vec, live_vars, call);
1046
1047 /* Make sure the tail invocation of this function does not indirectly
1048 refer to local variables. (Passing variables directly by value
1049 is OK.) */
1050 FOR_EACH_LOCAL_DECL (cfun, idx, var)
1051 {
1052 if (TREE_CODE (var) != PARM_DECL
1053 && auto_var_in_fn_p (var, cfun->decl)
1054 && may_be_aliased (var)
1055 && (ref_maybe_used_by_stmt_p (call, var, false)
1056 || call_may_clobber_ref_p (call, var, false)))
1057 {
1058 if (!VAR_P (var))
1059 {
1060 if (diag_musttail && gimple_call_must_tail_p (call))
1061 {
1062 auto opt = OPT_Wmaybe_musttail_local_addr;
1063 if (!warning_suppressed_p (call,
1064 opt))
1065 {
1066 warning_at (gimple_location (call), opt,
1067 "address of local variable can escape to "
1068 "%<musttail%> call");
1069 suppress_warning (call, opt);
1070 }
1071 continue;
1072 }
1073 if (local_live_vars)
1074 BITMAP_FREE (local_live_vars);
1075 maybe_error_musttail (call, _("call invocation refers to "
1076 "locals"), diag_musttail);
1077 return;
1078 }
1079 else
1080 {
1081 unsigned int *v = live_vars->get (DECL_UID (var));
1082 if (bitmap_bit_p (local_live_vars, *v))
1083 {
1084 if (diag_musttail && gimple_call_must_tail_p (call))
1085 {
1086 auto opt = OPT_Wmaybe_musttail_local_addr;
1087 if (!warning_suppressed_p (call, opt))
1088 {
1089 if (!DECL_ARTIFICIAL (var) && DECL_NAME (var))
1090 warning_at (gimple_location (call), opt,
1091 "address of automatic variable %qD "
1092 "can escape to %<musttail%> call",
1093 var);
1094 else
1095 warning_at (gimple_location (call), opt,
1096 "address of local variable can escape "
1097 "to %<musttail%> call");
1098 suppress_warning (call, opt);
1099 }
1100 continue;
1101 }
1102 BITMAP_FREE (local_live_vars);
1103 maybe_error_musttail (call, _("call invocation refers to "
1104 "locals"), diag_musttail);
1105 return;
1106 }
1107 }
1108 }
1109 }
1110 if (diag_musttail
1111 && gimple_call_must_tail_p (call)
1112 && !warning_suppressed_p (call, OPT_Wmaybe_musttail_local_addr))
1113 for (tree param = DECL_ARGUMENTS (current_function_decl);
1114 param; param = DECL_CHAIN (param))
1115 if (may_be_aliased (param)
1116 && (ref_maybe_used_by_stmt_p (call, param, false)
1117 || call_may_clobber_ref_p (call, param, false)))
1118 {
1119 auto opt = OPT_Wmaybe_musttail_local_addr;
1120 warning_at (gimple_location (call), opt,
1121 "address of parameter %qD can escape to "
1122 "%<musttail%> call", param);
1123 suppress_warning (call, opt);
1124 break;
1125 }
1126
1127 if (local_live_vars)
1128 BITMAP_FREE (local_live_vars);
1129
1130 /* Now check the statements after the call. None of them has virtual
1131 operands, so they may only depend on the call through its return
1132 value. The return value should also be dependent on each of them,
1133 since we are running after dce. */
1134 m = NULL_TREE;
1135 a = NULL_TREE;
1136 auto_bitmap to_move_defs;
1137 auto_vec<gimple *> to_move_stmts;
1138 bool is_noreturn = gimple_call_noreturn_p (call);
1139 auto_vec<edge> edges;
1140
1141 abb = bb;
1142 agsi = gsi;
1143 while (!is_noreturn)
1144 {
1145 tree tmp_a = NULL_TREE;
1146 tree tmp_m = NULL_TREE;
1147 gsi_next (&agsi);
1148
1149 new_bb:
1150 while (gsi_end_p (agsi))
1151 {
1152 edge e = single_non_eh_succ_edge (abb);
1153 ass_var = propagate_through_phis (ass_var, e);
1154 if (!ass_var || ignored_edges)
1155 edges.safe_push (e);
1156 abb = e->dest;
1157 agsi = gsi_start_bb (abb);
1158 }
1159
1160 stmt = gsi_stmt (agsi);
1161 if (gimple_code (stmt) == GIMPLE_RETURN)
1162 break;
1163
1164 if (gimple_code (stmt) == GIMPLE_LABEL
1165 || gimple_code (stmt) == GIMPLE_NOP
1166 || gimple_code (stmt) == GIMPLE_PREDICT
1167 || gimple_clobber_p (stmt)
1168 || is_gimple_debug (stmt))
1169 continue;
1170
1171 if (cfun->has_musttail
1172 && sanitize_flags_p (SANITIZE_THREAD)
1173 && retry_tsan_func_exit == 1
1174 && gimple_call_builtin_p (stmt, BUILT_IN_TSAN_FUNC_EXIT)
1175 && !has_tsan_func_exit
1176 && gimple_call_must_tail_p (call))
1177 {
1178 has_tsan_func_exit = true;
1179 continue;
1180 }
1181
1182 if (cfun->has_musttail
1183 && sanitize_flags_p (SANITIZE_ADDRESS)
1184 && asan_mark_p (stmt, ASAN_MARK_POISON)
1185 && diag_musttail)
1186 continue;
1187
1188 /* See earlier comment on GIMPLE_CONDs. Here we need to propagate
1189 through on the forward walk, so based on the edges vector we've
1190 walked through determine which edge to follow. */
1191 if (ignored_edges)
1192 {
1193 if (is_gimple_assign (stmt)
1194 && gimple_assign_rhs_code (stmt) == INTEGER_CST
1195 && tree_int_cst_sgn (gimple_assign_rhs1 (stmt)) >= 0)
1196 {
1197 use_operand_p use_p;
1198 imm_use_iterator imm_iter;
1199 bool bad_p = false;
1200 FOR_EACH_IMM_USE_FAST (use_p, imm_iter,
1201 gimple_assign_lhs (stmt))
1202 {
1203 gimple *use_stmt = USE_STMT (use_p);
1204 if (is_gimple_debug (use_stmt)
1205 || gimple_code (use_stmt) == GIMPLE_COND
1206 || gimple_code (use_stmt) == GIMPLE_SWITCH)
1207 continue;
1208 if (gimple_code (use_stmt) == GIMPLE_PHI)
1209 {
1210 use_operand_p use_p2;
1211 imm_use_iterator imm_iter2;
1212 FOR_EACH_IMM_USE_FAST (use_p2, imm_iter2,
1213 gimple_phi_result (use_stmt))
1214 {
1215 gimple *use_stmt2 = USE_STMT (use_p2);
1216 if (is_gimple_debug (use_stmt2)
1217 || gimple_code (use_stmt2) == GIMPLE_COND
1218 || gimple_code (use_stmt2) == GIMPLE_SWITCH)
1219 continue;
1220 bad_p = true;
1221 break;
1222 }
1223 if (bad_p)
1224 break;
1225 }
1226 else
1227 {
1228 bad_p = true;
1229 break;
1230 }
1231 }
1232 if (!bad_p)
1233 continue;
1234 }
1235 if (gimple_code (stmt) == GIMPLE_COND
1236 && TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
1237 && TREE_CODE (gimple_cond_rhs (stmt)) == INTEGER_CST
1238 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
1239 && tree_int_cst_sgn (gimple_cond_rhs (stmt)) >= 0)
1240 {
1241 edge e = NULL, et, ef;
1242 enum tree_code ccode = gimple_cond_code (stmt);
1243 tree lhs = gimple_cond_lhs (stmt);
1244 tree rhsv = gimple_cond_rhs (stmt);
1245 extract_true_false_edges_from_block (gimple_bb (stmt), &et, &ef);
1246 if (is_gimple_assign (SSA_NAME_DEF_STMT (lhs))
1247 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (lhs))
1248 == INTEGER_CST))
1249 {
1250 tree lhsv = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (lhs));
1251 tree r = const_binop (ccode, boolean_type_node, lhsv, rhsv);
1252 if (r == boolean_true_node)
1253 e = et;
1254 else if (r == boolean_false_node)
1255 e = ef;
1256 }
1257 else if (gimple_code (SSA_NAME_DEF_STMT (lhs)) == GIMPLE_PHI)
1258 {
1259 gimple *phi = SSA_NAME_DEF_STMT (lhs);
1260 basic_block pbb = gimple_bb (phi);
1261 for (edge e2 : edges)
1262 if (e2->dest == pbb)
1263 {
1264 tree lhsv = gimple_phi_arg_def_from_edge (phi, e2);
1265 if (TREE_CODE (lhsv) == SSA_NAME)
1266 if (gimple *g = SSA_NAME_DEF_STMT (lhsv))
1267 if (is_gimple_assign (g)
1268 && gimple_assign_rhs_code (g) == INTEGER_CST)
1269 lhsv = gimple_assign_rhs1 (g);
1270 tree r = const_binop (ccode, boolean_type_node,
1271 lhsv, rhsv);
1272 if (r == boolean_true_node)
1273 e = et;
1274 else if (r == boolean_false_node)
1275 e = ef;
1276 break;
1277 }
1278 }
1279 if (e)
1280 {
1281 ass_var = propagate_through_phis (ass_var, e);
1282 if (!ass_var || ignored_edges)
1283 edges.safe_push (e);
1284 abb = e->dest;
1285 agsi = gsi_start_bb (abb);
1286 goto new_bb;
1287 }
1288 }
1289 if (gimple_code (stmt) == GIMPLE_SWITCH
1290 && (TREE_CODE (gimple_switch_index (as_a <gswitch *> (stmt)))
1291 == SSA_NAME))
1292 {
1293 edge e = NULL;
1294 gswitch *swtch = as_a <gswitch *> (stmt);
1295 tree idx = gimple_switch_index (swtch);
1296 if (is_gimple_assign (SSA_NAME_DEF_STMT (idx))
1297 && (gimple_assign_rhs_code (SSA_NAME_DEF_STMT (idx))
1298 == INTEGER_CST))
1299 {
1300 tree val = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (idx));
1301 e = find_taken_edge_switch_expr (swtch, val);
1302 }
1303 else if (gimple_code (SSA_NAME_DEF_STMT (idx)) == GIMPLE_PHI)
1304 {
1305 gimple *phi = SSA_NAME_DEF_STMT (idx);
1306 basic_block pbb = gimple_bb (phi);
1307 for (edge e2 : edges)
1308 if (e2->dest == pbb)
1309 {
1310 tree val = gimple_phi_arg_def_from_edge (phi, e2);
1311 if (TREE_CODE (val) == SSA_NAME)
1312 if (gimple *g = SSA_NAME_DEF_STMT (val))
1313 if (is_gimple_assign (g)
1314 && gimple_assign_rhs_code (g) == INTEGER_CST)
1315 val = gimple_assign_rhs1 (g);
1316 if (TREE_CODE (val) == INTEGER_CST)
1317 e = find_taken_edge_switch_expr (swtch, val);
1318 break;
1319 }
1320 }
1321 if (e)
1322 {
1323 ass_var = propagate_through_phis (ass_var, e);
1324 if (!ass_var || ignored_edges)
1325 edges.safe_push (e);
1326 abb = e->dest;
1327 agsi = gsi_start_bb (abb);
1328 goto new_bb;
1329 }
1330 }
1331 }
1332
1333 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1334 {
1335 maybe_error_musttail (call, _("unhandled code after call"),
1336 diag_musttail);
1337 return;
1338 }
1339
1340 /* This is a gimple assign. */
1341 par ret = process_assignment (as_a <gassign *> (stmt), gsi,
1342 &tmp_m, &tmp_a, &ass_var, to_move_defs);
1343 if (ret == FAIL || (ret == TRY_MOVE && !tail_recursion))
1344 {
1345 maybe_error_musttail (call, _("return value changed after call"),
1346 diag_musttail);
1347 return;
1348 }
1349 else if (ret == TRY_MOVE)
1350 {
1351 /* Do not deal with checking dominance, the real fix is to
1352 do path isolation for the transform phase anyway, removing
1353 the need to compute the accumulators with new stmts. */
1354 if (abb != bb)
1355 return;
1356 for (unsigned opno = 1; opno < gimple_num_ops (stmt); ++opno)
1357 {
1358 tree op = gimple_op (stmt, opno);
1359 if (independent_of_stmt_p (op, stmt, gsi, to_move_defs) != op)
1360 return;
1361 }
1362 bitmap_set_bit (to_move_defs,
1363 SSA_NAME_VERSION (gimple_assign_lhs (stmt)));
1364 to_move_stmts.safe_push (stmt);
1365 continue;
1366 }
1367
1368 if (tmp_a)
1369 {
1370 tree type = TREE_TYPE (tmp_a);
1371 if (a)
1372 a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
1373 else
1374 a = tmp_a;
1375 }
1376 if (tmp_m)
1377 {
1378 tree type = TREE_TYPE (tmp_m);
1379 if (m)
1380 m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
1381 else
1382 m = tmp_m;
1383
1384 if (a)
1385 a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
1386 }
1387 }
1388
1389 /* See if this is a tail call we can handle. */
1390 if (is_noreturn)
1391 {
1392 if (gimple_call_internal_p (call))
1393 {
1394 maybe_error_musttail (call, _("internal call"), diag_musttail);
1395 return;
1396 }
1397 tree rettype = TREE_TYPE (TREE_TYPE (current_function_decl));
1398 tree calltype = TREE_TYPE (gimple_call_fntype (call));
1399 if (!VOID_TYPE_P (rettype)
1400 && !useless_type_conversion_p (rettype, calltype))
1401 {
1402 maybe_error_musttail (call, _("call and return value are different"),
1403 diag_musttail);
1404 return;
1405 }
1406 ret_var = NULL_TREE;
1407 }
1408 else
1409 ret_var = gimple_return_retval (as_a <greturn *> (stmt));
1410
1411 /* We may proceed if there either is no return value, or the return value
1412 is identical to the call's return or if the return decl is an empty type
1413 variable and the call's return was not assigned. */
1414 if (ret_var
1415 && (ret_var != ass_var
1416 && !(is_empty_type (TREE_TYPE (ret_var)) && !ass_var)))
1417 {
1418 bool ok = false;
1419 value_range val;
1420 tree valr;
1421 /* If IPA-VRP proves called function always returns a singleton range,
1422 the return value is replaced by the only value in that range.
1423 For tail call purposes, pretend such replacement didn't happen. */
1424 if (ass_var == NULL_TREE && !tail_recursion)
1425 if (tree type = gimple_range_type (call))
1426 if (tree callee = gimple_call_fndecl (call))
1427 if ((INTEGRAL_TYPE_P (type)
1428 || SCALAR_FLOAT_TYPE_P (type)
1429 || POINTER_TYPE_P (type))
1430 && useless_type_conversion_p (TREE_TYPE (TREE_TYPE (callee)),
1431 type)
1432 && useless_type_conversion_p (TREE_TYPE (ret_var), type)
1433 && ipa_return_value_range (val, callee)
1434 && val.singleton_p (&valr))
1435 {
1436 tree rv = ret_var;
1437 unsigned int i = edges.length ();
1438 /* If ret_var is equal to valr, we can tail optimize. */
1439 if (operand_equal_p (ret_var, valr, 0))
1440 ok = true;
1441 else
1442 /* Otherwise, if ret_var is a PHI result, try to find out
1443 if valr isn't propagated through PHIs on the path from
1444 call's bb to SSA_NAME_DEF_STMT (ret_var)'s bb. */
1445 while (TREE_CODE (rv) == SSA_NAME
1446 && gimple_code (SSA_NAME_DEF_STMT (rv)) == GIMPLE_PHI)
1447 {
1448 tree nrv = NULL_TREE;
1449 gimple *g = SSA_NAME_DEF_STMT (rv);
1450 for (; i; --i)
1451 {
1452 if (edges[i - 1]->dest == gimple_bb (g))
1453 {
1454 nrv
1455 = gimple_phi_arg_def_from_edge (g,
1456 edges[i - 1]);
1457 --i;
1458 break;
1459 }
1460 }
1461 if (nrv == NULL_TREE)
1462 break;
1463 if (operand_equal_p (nrv, valr, 0))
1464 {
1465 ok = true;
1466 break;
1467 }
1468 rv = nrv;
1469 }
1470 }
1471 if (!ok)
1472 {
1473 maybe_error_musttail (call, _("call and return value are different"),
1474 diag_musttail);
1475 return;
1476 }
1477 }
1478
1479 /* If this is not a tail recursive call, we cannot handle addends or
1480 multiplicands. */
1481 if (!tail_recursion && (m || a))
1482 {
1483 maybe_error_musttail (call, _("operations after non tail recursive "
1484 "call"), diag_musttail);
1485 return;
1486 }
1487
1488 /* For pointers only allow additions. */
1489 if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
1490 {
1491 maybe_error_musttail (call, _("tail recursion with pointers can only "
1492 "use additions"), diag_musttail);
1493 return;
1494 }
1495
1496 if (eh_has_tsan_func_exit != -1
1497 && eh_has_tsan_func_exit != has_tsan_func_exit)
1498 {
1499 if (eh_has_tsan_func_exit)
1500 maybe_error_musttail (call, _("call may throw exception caught "
1501 "locally or perform cleanups"),
1502 diag_musttail);
1503 else
1504 maybe_error_musttail (call, _("exception cleanups omit "
1505 "__tsan_func_exit call"), diag_musttail);
1506 return;
1507 }
1508
1509 /* Move queued defs. */
1510 if (tail_recursion)
1511 {
1512 unsigned i;
1513 FOR_EACH_VEC_ELT (to_move_stmts, i, stmt)
1514 {
1515 gimple_stmt_iterator mgsi = gsi_for_stmt (stmt);
1516 gsi_move_before (&mgsi, &gsi);
1517 }
1518 if (!tailr_arg_needs_copy)
1519 tailr_arg_needs_copy = BITMAP_ALLOC (NULL);
1520 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
1521 param;
1522 param = DECL_CHAIN (param), idx++)
1523 {
1524 tree ddef, arg = gimple_call_arg (call, idx);
1525 if (!is_gimple_reg (param)
1526 || ((ddef = ssa_default_def (cfun, param))
1527 && arg != ddef))
1528 bitmap_set_bit (tailr_arg_needs_copy, idx);
1529 }
1530 }
1531
1532 nw = XNEW (struct tailcall);
1533
1534 nw->call_gsi = gsi;
1535
1536 nw->tail_recursion = tail_recursion;
1537 nw->has_tsan_func_exit = has_tsan_func_exit;
1538
1539 nw->mult = m;
1540 nw->add = a;
1541
1542 nw->next = *ret;
1543 *ret = nw;
1544 }
1545
1546 /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
1547
1548 static void
1549 add_successor_phi_arg (edge e, tree var, tree phi_arg)
1550 {
1551 gphi_iterator gsi;
1552
1553 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
1554 if (PHI_RESULT (gsi.phi ()) == var)
1555 break;
1556
1557 gcc_assert (!gsi_end_p (gsi));
1558 add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
1559 }
1560
1561 /* Creates a GIMPLE statement which computes the operation specified by
1562 CODE, ACC and OP1 to a new variable with name LABEL and inserts the
1563 statement in the position specified by GSI. Returns the
1564 tree node of the statement's result. */
1565
1566 static tree
1567 adjust_return_value_with_ops (enum tree_code code, const char *label,
1568 tree acc, tree op1, gimple_stmt_iterator gsi)
1569 {
1570
1571 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
1572 tree result = make_temp_ssa_name (ret_type, NULL, label);
1573 gassign *stmt;
1574
1575 if (POINTER_TYPE_P (ret_type))
1576 {
1577 gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
1578 code = POINTER_PLUS_EXPR;
1579 }
1580 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
1581 && code != POINTER_PLUS_EXPR)
1582 stmt = gimple_build_assign (result, code, acc, op1);
1583 else
1584 {
1585 tree tem;
1586 if (code == POINTER_PLUS_EXPR)
1587 tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
1588 else
1589 tem = fold_build2 (code, TREE_TYPE (op1),
1590 fold_convert (TREE_TYPE (op1), acc), op1);
1591 tree rhs = fold_convert (ret_type, tem);
1592 rhs = force_gimple_operand_gsi (&gsi, rhs,
1593 false, NULL, true, GSI_SAME_STMT);
1594 stmt = gimple_build_assign (result, rhs);
1595 }
1596
1597 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1598 return result;
1599 }
1600
1601 /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
1602 the computation specified by CODE and OP1 and insert the statement
1603 at the position specified by GSI as a new statement. Returns new SSA name
1604 of updated accumulator. */
1605
1606 static tree
1607 update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
1608 gimple_stmt_iterator gsi)
1609 {
1610 gassign *stmt;
1611 tree var = copy_ssa_name (acc);
1612 if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
1613 stmt = gimple_build_assign (var, code, acc, op1);
1614 else
1615 {
1616 tree rhs = fold_convert (TREE_TYPE (acc),
1617 fold_build2 (code,
1618 TREE_TYPE (op1),
1619 fold_convert (TREE_TYPE (op1), acc),
1620 op1));
1621 rhs = force_gimple_operand_gsi (&gsi, rhs,
1622 false, NULL, false, GSI_CONTINUE_LINKING);
1623 stmt = gimple_build_assign (var, rhs);
1624 }
1625 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1626 return var;
1627 }
1628
1629 /* Adjust the accumulator values according to A and M after GSI, and update
1630 the phi nodes on edge BACK. */
1631
1632 static void
1633 adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
1634 {
1635 tree var, a_acc_arg, m_acc_arg;
1636
1637 if (m)
1638 m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
1639 if (a)
1640 a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
1641
1642 a_acc_arg = a_acc;
1643 m_acc_arg = m_acc;
1644 if (a)
1645 {
1646 if (m_acc)
1647 {
1648 if (integer_onep (a))
1649 var = m_acc;
1650 else
1651 var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
1652 a, gsi);
1653 }
1654 else
1655 var = a;
1656
1657 a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
1658 }
1659
1660 if (m)
1661 m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
1662
1663 if (a_acc)
1664 add_successor_phi_arg (back, a_acc, a_acc_arg);
1665
1666 if (m_acc)
1667 add_successor_phi_arg (back, m_acc, m_acc_arg);
1668 }
1669
1670 /* Adjust value of the return at the end of BB according to M and A
1671 accumulators. */
1672
1673 static void
1674 adjust_return_value (basic_block bb, tree m, tree a)
1675 {
1676 tree retval;
1677 greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
1678 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1679
1680 gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
1681
1682 retval = gimple_return_retval (ret_stmt);
1683 if (!retval || retval == error_mark_node)
1684 return;
1685
1686 if (m)
1687 retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
1688 gsi);
1689 if (a)
1690 retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
1691 gsi);
1692 gimple_return_set_retval (ret_stmt, retval);
1693 update_stmt (ret_stmt);
1694 }
1695
1696 /* Subtract COUNT and FREQUENCY from the basic block and it's
1697 outgoing edge. */
1698 static void
1699 decrease_profile (basic_block bb, profile_count count)
1700 {
1701 bb->count = bb->count - count;
1702 }
1703
1704 /* Eliminates tail call described by T. TMP_VARS is a list of
1705 temporary variables used to copy the function arguments.
1706 Allocates *NEW_LOOP if not already done and initializes it. */
1707
1708 static void
1709 eliminate_tail_call (struct tailcall *t, class loop *&new_loop)
1710 {
1711 tree param, rslt;
1712 gimple *stmt, *call;
1713 tree arg;
1714 size_t idx;
1715 basic_block bb, first;
1716 edge e;
1717 gphi *phi;
1718 gphi_iterator gpi;
1719 gimple_stmt_iterator gsi;
1720 gimple *orig_stmt;
1721
1722 stmt = orig_stmt = gsi_stmt (t->call_gsi);
1723 bb = gsi_bb (t->call_gsi);
1724
1725 if (dump_file && (dump_flags & TDF_DETAILS))
1726 {
1727 fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
1728 bb->index);
1729 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1730 fprintf (dump_file, "\n");
1731 }
1732
1733 gcc_assert (is_gimple_call (stmt));
1734
1735 first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1736
1737 /* Remove the code after call_gsi that will become unreachable. The
1738 possibly unreachable code in other blocks is removed later in
1739 cfg cleanup. */
1740 gsi = t->call_gsi;
1741 gimple_stmt_iterator gsi2 = gsi_last_bb (gimple_bb (gsi_stmt (gsi)));
1742 while (gsi_stmt (gsi2) != gsi_stmt (gsi))
1743 {
1744 gimple *t = gsi_stmt (gsi2);
1745 /* Do not remove the return statement, so that redirect_edge_and_branch
1746 sees how the block ends. */
1747 if (gimple_code (t) != GIMPLE_RETURN)
1748 {
1749 gimple_stmt_iterator gsi3 = gsi2;
1750 gsi_prev (&gsi2);
1751 gsi_remove (&gsi3, true);
1752 release_defs (t);
1753 }
1754 else
1755 gsi_prev (&gsi2);
1756 }
1757
1758 if (gimple_call_noreturn_p (as_a <gcall *> (stmt)))
1759 {
1760 e = make_edge (gsi_bb (t->call_gsi), first, EDGE_FALLTHRU);
1761 e->probability = profile_probability::always ();
1762 }
1763 else
1764 {
1765 /* Number of executions of function has reduced by the tailcall. */
1766 e = single_non_eh_succ_edge (gsi_bb (t->call_gsi));
1767
1768 profile_count count = e->count ();
1769
1770 /* When profile is inconsistent and the recursion edge is more frequent
1771 than number of executions of functions, scale it down, so we do not
1772 end up with 0 executions of entry block. */
1773 if (count >= ENTRY_BLOCK_PTR_FOR_FN (cfun)->count)
1774 count = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.apply_scale (7, 8);
1775 decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), count);
1776 decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), count);
1777 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1778 decrease_profile (e->dest, count);
1779
1780 /* Replace the call by a jump to the start of function. */
1781 e = redirect_edge_and_branch (e, first);
1782 }
1783 gcc_assert (e);
1784 PENDING_STMT (e) = NULL;
1785
1786 /* Add the new loop. */
1787 if (!new_loop)
1788 {
1789 new_loop = alloc_loop ();
1790 new_loop->header = first;
1791 new_loop->finite_p = true;
1792 }
1793 else
1794 gcc_assert (new_loop->header == first);
1795
1796 /* Add phi node entries for arguments. The ordering of the phi nodes should
1797 be the same as the ordering of the arguments. */
1798 auto_vec<tree> copies;
1799 for (param = DECL_ARGUMENTS (current_function_decl),
1800 idx = 0, gpi = gsi_start_phis (first);
1801 param;
1802 param = DECL_CHAIN (param), idx++)
1803 {
1804 if (!bitmap_bit_p (tailr_arg_needs_copy, idx))
1805 continue;
1806
1807 if (!is_gimple_reg_type (TREE_TYPE (param)))
1808 {
1809 if (param == gimple_call_arg (stmt, idx))
1810 continue;
1811 /* First check if param isn't used by any of the following
1812 call arguments. If it is, we need to copy first to
1813 a temporary and only after doing all the assignments copy it
1814 to param. */
1815 size_t idx2 = idx + 1;
1816 tree param2 = DECL_CHAIN (param);
1817 for (; param2; param2 = DECL_CHAIN (param2), idx2++)
1818 if (!is_gimple_reg_type (TREE_TYPE (param)))
1819 {
1820 tree base = get_base_address (gimple_call_arg (stmt, idx2));
1821 if (base == param)
1822 break;
1823 }
1824 tree tmp = param;
1825 if (param2)
1826 {
1827 tmp = create_tmp_var (TREE_TYPE (param));
1828 copies.safe_push (param);
1829 copies.safe_push (tmp);
1830 }
1831 gimple *g = gimple_build_assign (tmp, gimple_call_arg (stmt, idx));
1832 gsi_insert_before (&t->call_gsi, g, GSI_SAME_STMT);
1833 continue;
1834 }
1835
1836 arg = gimple_call_arg (stmt, idx);
1837 phi = gpi.phi ();
1838 gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
1839
1840 add_phi_arg (phi, arg, e, gimple_location (stmt));
1841 gsi_next (&gpi);
1842 }
1843 for (unsigned i = 0; i < copies.length (); i += 2)
1844 {
1845 gimple *g = gimple_build_assign (copies[i], copies[i + 1]);
1846 gsi_insert_before (&t->call_gsi, g, GSI_SAME_STMT);
1847 }
1848
1849 /* Update the values of accumulators. */
1850 adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
1851
1852 call = gsi_stmt (t->call_gsi);
1853 rslt = gimple_call_lhs (call);
1854 if (rslt != NULL_TREE && TREE_CODE (rslt) == SSA_NAME)
1855 {
1856 /* Result of the call will no longer be defined. So adjust the
1857 SSA_NAME_DEF_STMT accordingly. */
1858 SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
1859 }
1860
1861 gsi_remove (&t->call_gsi, true);
1862 release_defs (call);
1863 }
1864
1865 /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
1866 mark the tailcalls for the sibcall optimization. */
1867
1868 static bool
1869 optimize_tail_call (struct tailcall *t, bool opt_tailcalls,
1870 class loop *&new_loop)
1871 {
1872 if (t->has_tsan_func_exit && (t->tail_recursion || opt_tailcalls))
1873 {
1874 tree builtin_decl = builtin_decl_implicit (BUILT_IN_TSAN_FUNC_EXIT);
1875 gimple *g = gimple_build_call (builtin_decl, 0);
1876 gimple_set_location (g, cfun->function_end_locus);
1877 gsi_insert_before (&t->call_gsi, g, GSI_SAME_STMT);
1878 }
1879
1880 if (t->tail_recursion)
1881 {
1882 eliminate_tail_call (t, new_loop);
1883 return true;
1884 }
1885
1886 if (opt_tailcalls)
1887 {
1888 gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
1889
1890 gimple_call_set_tail (stmt, true);
1891 cfun->tail_call_marked = true;
1892 if (dump_file && (dump_flags & TDF_DETAILS))
1893 {
1894 fprintf (dump_file, "Found tail call ");
1895 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1896 fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
1897 }
1898 return t->has_tsan_func_exit;
1899 }
1900
1901 return false;
1902 }
1903
1904 /* Creates a tail-call accumulator of the same type as the return type of the
1905 current function. LABEL is the name used to creating the temporary
1906 variable for the accumulator. The accumulator will be inserted in the
1907 phis of a basic block BB with single predecessor with an initial value
1908 INIT converted to the current function return type. */
1909
1910 static tree
1911 create_tailcall_accumulator (const char *label, basic_block bb, tree init)
1912 {
1913 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
1914 if (POINTER_TYPE_P (ret_type))
1915 ret_type = sizetype;
1916
1917 tree tmp = make_temp_ssa_name (ret_type, NULL, label);
1918 gphi *phi;
1919
1920 phi = create_phi_node (tmp, bb);
1921 add_phi_arg (phi, init, single_pred_edge (bb),
1922 UNKNOWN_LOCATION);
1923 return PHI_RESULT (phi);
1924 }
1925
1926 /* Optimizes tail calls in the function, turning the tail recursion
1927 into iteration. When ONLY_MUSTTAIL is true only optimize musttail
1928 marked calls. When DIAG_MUSTTAIL, diagnose if musttail calls can't
1929 be tail call optimized. */
1930
1931 static unsigned int
1932 tree_optimize_tail_calls_1 (bool opt_tailcalls, bool only_musttail,
1933 bool diag_musttail)
1934 {
1935 edge e;
1936 bool phis_constructed = false;
1937 struct tailcall *tailcalls = NULL, *act, *next;
1938 bool changed = false;
1939 basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1940 tree param;
1941 edge_iterator ei;
1942
1943 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1944 {
1945 /* Only traverse the normal exits, i.e. those that end with return
1946 statement. */
1947 if (safe_is_a <greturn *> (*gsi_last_bb (e->src)))
1948 {
1949 int retry_tsan_func_exit = 0;
1950 find_tail_calls (e->src, e, &tailcalls, only_musttail, opt_tailcalls,
1951 diag_musttail, retry_tsan_func_exit, NULL, NULL);
1952 if (retry_tsan_func_exit == -1)
1953 {
1954 retry_tsan_func_exit = 1;
1955 find_tail_calls (e->src, e, &tailcalls, only_musttail,
1956 opt_tailcalls, diag_musttail,
1957 retry_tsan_func_exit, NULL, NULL);
1958 }
1959 }
1960 }
1961 if (cfun->has_musttail && diag_musttail)
1962 {
1963 basic_block bb;
1964 int retry_tsan_func_exit = 0;
1965 FOR_EACH_BB_FN (bb, cfun)
1966 if (EDGE_COUNT (bb->succs) == 0
1967 || (single_succ_p (bb)
1968 && (single_succ_edge (bb)->flags & EDGE_EH)))
1969 if (gimple *c = last_nondebug_stmt (bb))
1970 if (is_gimple_call (c)
1971 && gimple_call_must_tail_p (as_a <gcall *> (c))
1972 && gimple_call_noreturn_p (as_a <gcall *> (c)))
1973 find_tail_calls (bb, NULL, &tailcalls, only_musttail,
1974 opt_tailcalls, diag_musttail,
1975 retry_tsan_func_exit, NULL, NULL);
1976 }
1977
1978 if (live_vars)
1979 {
1980 destroy_live_vars (live_vars_vec);
1981 delete live_vars;
1982 live_vars = NULL;
1983 }
1984
1985 if (cfun->has_musttail)
1986 {
1987 /* We can't mix non-recursive must tail calls with tail recursive
1988 calls which require accumulators, because in that case we have to
1989 emit code in between the musttail calls and return, which prevent
1990 calling them as tail calls. So, in that case give up on the
1991 tail recursion. */
1992 for (act = tailcalls; act; act = act->next)
1993 if (!act->tail_recursion)
1994 {
1995 gcall *call = as_a <gcall *> (gsi_stmt (act->call_gsi));
1996 if (gimple_call_must_tail_p (call))
1997 break;
1998 }
1999 if (act)
2000 for (struct tailcall **p = &tailcalls; *p; )
2001 {
2002 if ((*p)->tail_recursion && ((*p)->add || (*p)->mult))
2003 {
2004 struct tailcall *a = *p;
2005 *p = (*p)->next;
2006 gcall *call = as_a <gcall *> (gsi_stmt (a->call_gsi));
2007 maybe_error_musttail (call, _("tail recursion with "
2008 "accumulation mixed with "
2009 "musttail non-recursive call"),
2010 diag_musttail);
2011 free (a);
2012 }
2013 else
2014 p = &(*p)->next;
2015 }
2016 }
2017 /* Construct the phi nodes and accumulators if necessary. */
2018 a_acc = m_acc = NULL_TREE;
2019 for (act = tailcalls; act; act = act->next)
2020 {
2021 if (!act->tail_recursion)
2022 continue;
2023
2024 if (!phis_constructed)
2025 {
2026 /* Ensure that there is only one predecessor of the block
2027 or if there are existing degenerate PHI nodes. */
2028 if (!single_pred_p (first)
2029 || !gimple_seq_empty_p (phi_nodes (first)))
2030 first
2031 = split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
2032
2033 /* Copy the args if needed. */
2034 unsigned idx;
2035 for (param = DECL_ARGUMENTS (current_function_decl), idx = 0;
2036 param;
2037 param = DECL_CHAIN (param), idx++)
2038 if (bitmap_bit_p (tailr_arg_needs_copy, idx))
2039 {
2040 if (!is_gimple_reg_type (TREE_TYPE (param)))
2041 continue;
2042 tree name = ssa_default_def (cfun, param);
2043 tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
2044 gphi *phi;
2045
2046 set_ssa_default_def (cfun, param, new_name);
2047 phi = create_phi_node (name, first);
2048 add_phi_arg (phi, new_name, single_pred_edge (first),
2049 EXPR_LOCATION (param));
2050 }
2051 phis_constructed = true;
2052 }
2053 tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
2054 if (POINTER_TYPE_P (ret_type))
2055 ret_type = sizetype;
2056
2057 if (act->add && !a_acc)
2058 a_acc = create_tailcall_accumulator ("add_acc", first,
2059 build_zero_cst (ret_type));
2060
2061 if (act->mult && !m_acc)
2062 m_acc = create_tailcall_accumulator ("mult_acc", first,
2063 build_one_cst (ret_type));
2064 }
2065
2066 if (a_acc || m_acc)
2067 {
2068 /* When the tail call elimination using accumulators is performed,
2069 statements adding the accumulated value are inserted at all exits.
2070 This turns all other tail calls to non-tail ones. */
2071 opt_tailcalls = false;
2072 }
2073
2074 class loop *new_loop = NULL;
2075 for (; tailcalls; tailcalls = next)
2076 {
2077 next = tailcalls->next;
2078 changed |= optimize_tail_call (tailcalls, opt_tailcalls, new_loop);
2079 free (tailcalls);
2080 }
2081 if (new_loop)
2082 add_loop (new_loop, loops_for_fn (cfun)->tree_root);
2083
2084 if (a_acc || m_acc)
2085 {
2086 /* Modify the remaining return statements. */
2087 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2088 {
2089 if (safe_is_a <greturn *> (*gsi_last_bb (e->src)))
2090 adjust_return_value (e->src, m_acc, a_acc);
2091 }
2092 }
2093
2094 if (changed)
2095 free_dominance_info (CDI_DOMINATORS);
2096
2097 /* Add phi nodes for the virtual operands defined in the function to the
2098 header of the loop created by tail recursion elimination. Do so
2099 by triggering the SSA renamer. */
2100 if (phis_constructed)
2101 mark_virtual_operands_for_renaming (cfun);
2102
2103 if (tailr_arg_needs_copy)
2104 BITMAP_FREE (tailr_arg_needs_copy);
2105
2106 if (diag_musttail)
2107 cfun->has_musttail = false;
2108
2109 if (changed)
2110 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
2111 return 0;
2112 }
2113
2114 static bool
2115 gate_tail_calls (void)
2116 {
2117 return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
2118 }
2119
2120 static unsigned int
2121 execute_tail_calls (void)
2122 {
2123 return tree_optimize_tail_calls_1 (true, false, true);
2124 }
2125
2126 namespace {
2127
2128 const pass_data pass_data_tail_recursion =
2129 {
2130 GIMPLE_PASS, /* type */
2131 "tailr", /* name */
2132 OPTGROUP_NONE, /* optinfo_flags */
2133 TV_NONE, /* tv_id */
2134 ( PROP_cfg | PROP_ssa ), /* properties_required */
2135 0, /* properties_provided */
2136 0, /* properties_destroyed */
2137 0, /* todo_flags_start */
2138 0, /* todo_flags_finish */
2139 };
2140
2141 class pass_tail_recursion : public gimple_opt_pass
2142 {
2143 public:
2144 pass_tail_recursion (gcc::context *ctxt)
2145 : gimple_opt_pass (pass_data_tail_recursion, ctxt)
2146 {}
2147
2148 /* opt_pass methods: */
2149 opt_pass * clone () final override
2150 {
2151 return new pass_tail_recursion (m_ctxt);
2152 }
2153 bool gate (function *) final override { return gate_tail_calls (); }
2154 unsigned int execute (function *) final override
2155 {
2156 return tree_optimize_tail_calls_1 (false, false, false);
2157 }
2158
2159 }; // class pass_tail_recursion
2160
2161 } // anon namespace
2162
2163 gimple_opt_pass *
2164 make_pass_tail_recursion (gcc::context *ctxt)
2165 {
2166 return new pass_tail_recursion (ctxt);
2167 }
2168
2169 namespace {
2170
2171 const pass_data pass_data_tail_calls =
2172 {
2173 GIMPLE_PASS, /* type */
2174 "tailc", /* name */
2175 OPTGROUP_NONE, /* optinfo_flags */
2176 TV_NONE, /* tv_id */
2177 ( PROP_cfg | PROP_ssa ), /* properties_required */
2178 0, /* properties_provided */
2179 0, /* properties_destroyed */
2180 0, /* todo_flags_start */
2181 0, /* todo_flags_finish */
2182 };
2183
2184 class pass_tail_calls : public gimple_opt_pass
2185 {
2186 public:
2187 pass_tail_calls (gcc::context *ctxt)
2188 : gimple_opt_pass (pass_data_tail_calls, ctxt)
2189 {}
2190
2191 /* opt_pass methods: */
2192 bool gate (function *) final override { return gate_tail_calls (); }
2193 unsigned int execute (function *) final override
2194 {
2195 return execute_tail_calls ();
2196 }
2197
2198 }; // class pass_tail_calls
2199
2200 } // anon namespace
2201
2202 gimple_opt_pass *
2203 make_pass_tail_calls (gcc::context *ctxt)
2204 {
2205 return new pass_tail_calls (ctxt);
2206 }
2207
2208 namespace {
2209
2210 const pass_data pass_data_musttail =
2211 {
2212 GIMPLE_PASS, /* type */
2213 "musttail", /* name */
2214 OPTGROUP_NONE, /* optinfo_flags */
2215 TV_NONE, /* tv_id */
2216 ( PROP_cfg | PROP_ssa ), /* properties_required */
2217 0, /* properties_provided */
2218 0, /* properties_destroyed */
2219 0, /* todo_flags_start */
2220 0, /* todo_flags_finish */
2221 };
2222
2223 class pass_musttail : public gimple_opt_pass
2224 {
2225 public:
2226 pass_musttail (gcc::context *ctxt)
2227 : gimple_opt_pass (pass_data_musttail, ctxt)
2228 {}
2229
2230 /* opt_pass methods: */
2231 /* This pass is only used when the other tail call pass
2232 doesn't run to make [[musttail]] still work. But only
2233 run it when there is actually a musttail in the function. */
2234 bool gate (function *f) final override
2235 {
2236 return f->has_musttail;
2237 }
2238 unsigned int execute (function *) final override
2239 {
2240 return tree_optimize_tail_calls_1 (true, true, true);
2241 }
2242
2243 }; // class pass_musttail
2244
2245 } // anon namespace
2246
2247 gimple_opt_pass *
2248 make_pass_musttail (gcc::context *ctxt)
2249 {
2250 return new pass_musttail (ctxt);
2251 }