PR target/65871
[official-gcc.git] / gcc / ipa-inline.c
blob1427761e4fa36cfec90d4724f6fa28668d0f4df5
1 /* Inlining decision heuristics.
2 Copyright (C) 2003-2015 Free Software Foundation, Inc.
3 Contributed by Jan Hubicka
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* Inlining decision heuristics
23 The implementation of inliner is organized as follows:
25 inlining heuristics limits
27 can_inline_edge_p allow to check that particular inlining is allowed
28 by the limits specified by user (allowed function growth, growth and so
29 on).
31 Functions are inlined when it is obvious the result is profitable (such
32 as functions called once or when inlining reduce code size).
33 In addition to that we perform inlining of small functions and recursive
34 inlining.
36 inlining heuristics
38 The inliner itself is split into two passes:
40 pass_early_inlining
42 Simple local inlining pass inlining callees into current function.
43 This pass makes no use of whole unit analysis and thus it can do only
44 very simple decisions based on local properties.
46 The strength of the pass is that it is run in topological order
47 (reverse postorder) on the callgraph. Functions are converted into SSA
48 form just before this pass and optimized subsequently. As a result, the
49 callees of the function seen by the early inliner was already optimized
50 and results of early inlining adds a lot of optimization opportunities
51 for the local optimization.
53 The pass handle the obvious inlining decisions within the compilation
54 unit - inlining auto inline functions, inlining for size and
55 flattening.
57 main strength of the pass is the ability to eliminate abstraction
58 penalty in C++ code (via combination of inlining and early
59 optimization) and thus improve quality of analysis done by real IPA
60 optimizers.
62 Because of lack of whole unit knowledge, the pass can not really make
63 good code size/performance tradeoffs. It however does very simple
64 speculative inlining allowing code size to grow by
65 EARLY_INLINING_INSNS when callee is leaf function. In this case the
66 optimizations performed later are very likely to eliminate the cost.
68 pass_ipa_inline
70 This is the real inliner able to handle inlining with whole program
71 knowledge. It performs following steps:
73 1) inlining of small functions. This is implemented by greedy
74 algorithm ordering all inlinable cgraph edges by their badness and
75 inlining them in this order as long as inline limits allows doing so.
77 This heuristics is not very good on inlining recursive calls. Recursive
78 calls can be inlined with results similar to loop unrolling. To do so,
79 special purpose recursive inliner is executed on function when
80 recursive edge is met as viable candidate.
82 2) Unreachable functions are removed from callgraph. Inlining leads
83 to devirtualization and other modification of callgraph so functions
84 may become unreachable during the process. Also functions declared as
85 extern inline or virtual functions are removed, since after inlining
86 we no longer need the offline bodies.
88 3) Functions called once and not exported from the unit are inlined.
89 This should almost always lead to reduction of code size by eliminating
90 the need for offline copy of the function. */
92 #include "config.h"
93 #include "system.h"
94 #include "coretypes.h"
95 #include "tm.h"
96 #include "hash-set.h"
97 #include "machmode.h"
98 #include "vec.h"
99 #include "double-int.h"
100 #include "input.h"
101 #include "alias.h"
102 #include "symtab.h"
103 #include "wide-int.h"
104 #include "inchash.h"
105 #include "tree.h"
106 #include "fold-const.h"
107 #include "trans-mem.h"
108 #include "calls.h"
109 #include "tree-inline.h"
110 #include "langhooks.h"
111 #include "flags.h"
112 #include "diagnostic.h"
113 #include "gimple-pretty-print.h"
114 #include "params.h"
115 #include "intl.h"
116 #include "tree-pass.h"
117 #include "coverage.h"
118 #include "rtl.h"
119 #include "bitmap.h"
120 #include "profile.h"
121 #include "predict.h"
122 #include "hard-reg-set.h"
123 #include "input.h"
124 #include "function.h"
125 #include "basic-block.h"
126 #include "tree-ssa-alias.h"
127 #include "internal-fn.h"
128 #include "gimple-expr.h"
129 #include "is-a.h"
130 #include "gimple.h"
131 #include "gimple-ssa.h"
132 #include "hash-map.h"
133 #include "plugin-api.h"
134 #include "ipa-ref.h"
135 #include "cgraph.h"
136 #include "alloc-pool.h"
137 #include "symbol-summary.h"
138 #include "ipa-prop.h"
139 #include "except.h"
140 #include "target.h"
141 #include "ipa-inline.h"
142 #include "ipa-utils.h"
143 #include "sreal.h"
144 #include "auto-profile.h"
145 #include "builtins.h"
146 #include "fibonacci_heap.h"
147 #include "lto-streamer.h"
149 typedef fibonacci_heap <sreal, cgraph_edge> edge_heap_t;
150 typedef fibonacci_node <sreal, cgraph_edge> edge_heap_node_t;
152 /* Statistics we collect about inlining algorithm. */
153 static int overall_size;
154 static gcov_type max_count;
155 static gcov_type spec_rem;
157 /* Pre-computed constants 1/CGRAPH_FREQ_BASE and 1/100. */
158 static sreal cgraph_freq_base_rec, percent_rec;
160 /* Return false when inlining edge E would lead to violating
161 limits on function unit growth or stack usage growth.
163 The relative function body growth limit is present generally
164 to avoid problems with non-linear behavior of the compiler.
165 To allow inlining huge functions into tiny wrapper, the limit
166 is always based on the bigger of the two functions considered.
168 For stack growth limits we always base the growth in stack usage
169 of the callers. We want to prevent applications from segfaulting
170 on stack overflow when functions with huge stack frames gets
171 inlined. */
173 static bool
174 caller_growth_limits (struct cgraph_edge *e)
176 struct cgraph_node *to = e->caller;
177 struct cgraph_node *what = e->callee->ultimate_alias_target ();
178 int newsize;
179 int limit = 0;
180 HOST_WIDE_INT stack_size_limit = 0, inlined_stack;
181 inline_summary *info, *what_info, *outer_info = inline_summaries->get (to);
183 /* Look for function e->caller is inlined to. While doing
184 so work out the largest function body on the way. As
185 described above, we want to base our function growth
186 limits based on that. Not on the self size of the
187 outer function, not on the self size of inline code
188 we immediately inline to. This is the most relaxed
189 interpretation of the rule "do not grow large functions
190 too much in order to prevent compiler from exploding". */
191 while (true)
193 info = inline_summaries->get (to);
194 if (limit < info->self_size)
195 limit = info->self_size;
196 if (stack_size_limit < info->estimated_self_stack_size)
197 stack_size_limit = info->estimated_self_stack_size;
198 if (to->global.inlined_to)
199 to = to->callers->caller;
200 else
201 break;
204 what_info = inline_summaries->get (what);
206 if (limit < what_info->self_size)
207 limit = what_info->self_size;
209 limit += limit * PARAM_VALUE (PARAM_LARGE_FUNCTION_GROWTH) / 100;
211 /* Check the size after inlining against the function limits. But allow
212 the function to shrink if it went over the limits by forced inlining. */
213 newsize = estimate_size_after_inlining (to, e);
214 if (newsize >= info->size
215 && newsize > PARAM_VALUE (PARAM_LARGE_FUNCTION_INSNS)
216 && newsize > limit)
218 e->inline_failed = CIF_LARGE_FUNCTION_GROWTH_LIMIT;
219 return false;
222 if (!what_info->estimated_stack_size)
223 return true;
225 /* FIXME: Stack size limit often prevents inlining in Fortran programs
226 due to large i/o datastructures used by the Fortran front-end.
227 We ought to ignore this limit when we know that the edge is executed
228 on every invocation of the caller (i.e. its call statement dominates
229 exit block). We do not track this information, yet. */
230 stack_size_limit += ((gcov_type)stack_size_limit
231 * PARAM_VALUE (PARAM_STACK_FRAME_GROWTH) / 100);
233 inlined_stack = (outer_info->stack_frame_offset
234 + outer_info->estimated_self_stack_size
235 + what_info->estimated_stack_size);
236 /* Check new stack consumption with stack consumption at the place
237 stack is used. */
238 if (inlined_stack > stack_size_limit
239 /* If function already has large stack usage from sibling
240 inline call, we can inline, too.
241 This bit overoptimistically assume that we are good at stack
242 packing. */
243 && inlined_stack > info->estimated_stack_size
244 && inlined_stack > PARAM_VALUE (PARAM_LARGE_STACK_FRAME))
246 e->inline_failed = CIF_LARGE_STACK_FRAME_GROWTH_LIMIT;
247 return false;
249 return true;
252 /* Dump info about why inlining has failed. */
254 static void
255 report_inline_failed_reason (struct cgraph_edge *e)
257 if (dump_file)
259 fprintf (dump_file, " not inlinable: %s/%i -> %s/%i, %s\n",
260 xstrdup_for_dump (e->caller->name ()), e->caller->order,
261 xstrdup_for_dump (e->callee->name ()), e->callee->order,
262 cgraph_inline_failed_string (e->inline_failed));
263 if ((e->inline_failed == CIF_TARGET_OPTION_MISMATCH
264 || e->inline_failed == CIF_OPTIMIZATION_MISMATCH)
265 && e->caller->lto_file_data
266 && e->callee->function_symbol ()->lto_file_data)
268 fprintf (dump_file, " LTO objects: %s, %s\n",
269 e->caller->lto_file_data->file_name,
270 e->callee->function_symbol ()->lto_file_data->file_name);
272 if (e->inline_failed == CIF_TARGET_OPTION_MISMATCH)
273 cl_target_option_print_diff
274 (dump_file, 2, target_opts_for_fn (e->caller->decl),
275 target_opts_for_fn (e->callee->ultimate_alias_target ()->decl));
276 if (e->inline_failed == CIF_OPTIMIZATION_MISMATCH)
277 cl_optimization_print_diff
278 (dump_file, 2, opts_for_fn (e->caller->decl),
279 opts_for_fn (e->callee->ultimate_alias_target ()->decl));
283 /* Decide whether sanitizer-related attributes allow inlining. */
285 static bool
286 sanitize_attrs_match_for_inline_p (const_tree caller, const_tree callee)
288 /* Don't care if sanitizer is disabled */
289 if (!(flag_sanitize & SANITIZE_ADDRESS))
290 return true;
292 if (!caller || !callee)
293 return true;
295 return !!lookup_attribute ("no_sanitize_address",
296 DECL_ATTRIBUTES (caller)) ==
297 !!lookup_attribute ("no_sanitize_address",
298 DECL_ATTRIBUTES (callee));
301 /* Used for flags where it is safe to inline when caller's value is
302 grater than callee's. */
303 #define check_maybe_up(flag) \
304 (opts_for_fn (caller->decl)->x_##flag \
305 != opts_for_fn (callee->decl)->x_##flag \
306 && (!always_inline \
307 || opts_for_fn (caller->decl)->x_##flag \
308 < opts_for_fn (callee->decl)->x_##flag))
309 /* Used for flags where it is safe to inline when caller's value is
310 smaller than callee's. */
311 #define check_maybe_down(flag) \
312 (opts_for_fn (caller->decl)->x_##flag \
313 != opts_for_fn (callee->decl)->x_##flag \
314 && (!always_inline \
315 || opts_for_fn (caller->decl)->x_##flag \
316 > opts_for_fn (callee->decl)->x_##flag))
317 /* Used for flags where exact match is needed for correctness. */
318 #define check_match(flag) \
319 (opts_for_fn (caller->decl)->x_##flag \
320 != opts_for_fn (callee->decl)->x_##flag)
322 /* Decide if we can inline the edge and possibly update
323 inline_failed reason.
324 We check whether inlining is possible at all and whether
325 caller growth limits allow doing so.
327 if REPORT is true, output reason to the dump file.
329 if DISREGARD_LIMITS is true, ignore size limits.*/
331 static bool
332 can_inline_edge_p (struct cgraph_edge *e, bool report,
333 bool disregard_limits = false, bool early = false)
335 gcc_checking_assert (e->inline_failed);
337 if (cgraph_inline_failed_type (e->inline_failed) == CIF_FINAL_ERROR)
339 if (report)
340 report_inline_failed_reason (e);
341 return false;
344 bool inlinable = true;
345 enum availability avail;
346 cgraph_node *callee = e->callee->ultimate_alias_target (&avail);
347 cgraph_node *caller = e->caller->global.inlined_to
348 ? e->caller->global.inlined_to : e->caller;
349 tree caller_tree = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (caller->decl);
350 tree callee_tree
351 = callee ? DECL_FUNCTION_SPECIFIC_OPTIMIZATION (callee->decl) : NULL;
353 if (!callee->definition)
355 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
356 inlinable = false;
358 else if (callee->calls_comdat_local)
360 e->inline_failed = CIF_USES_COMDAT_LOCAL;
361 inlinable = false;
363 else if (avail <= AVAIL_INTERPOSABLE)
365 e->inline_failed = CIF_OVERWRITABLE;
366 inlinable = false;
368 else if (e->call_stmt_cannot_inline_p)
370 if (e->inline_failed != CIF_FUNCTION_NOT_OPTIMIZED)
371 e->inline_failed = CIF_MISMATCHED_ARGUMENTS;
372 inlinable = false;
374 /* Don't inline if the functions have different EH personalities. */
375 else if (DECL_FUNCTION_PERSONALITY (caller->decl)
376 && DECL_FUNCTION_PERSONALITY (callee->decl)
377 && (DECL_FUNCTION_PERSONALITY (caller->decl)
378 != DECL_FUNCTION_PERSONALITY (callee->decl)))
380 e->inline_failed = CIF_EH_PERSONALITY;
381 inlinable = false;
383 /* TM pure functions should not be inlined into non-TM_pure
384 functions. */
385 else if (is_tm_pure (callee->decl) && !is_tm_pure (caller->decl))
387 e->inline_failed = CIF_UNSPECIFIED;
388 inlinable = false;
390 /* Check compatibility of target optimization options. */
391 else if (!targetm.target_option.can_inline_p (caller->decl,
392 callee->decl))
394 e->inline_failed = CIF_TARGET_OPTION_MISMATCH;
395 inlinable = false;
397 else if (!inline_summaries->get (callee)->inlinable)
399 e->inline_failed = CIF_FUNCTION_NOT_INLINABLE;
400 inlinable = false;
402 else if (inline_summaries->get (caller)->contains_cilk_spawn)
404 e->inline_failed = CIF_CILK_SPAWN;
405 inlinable = false;
407 /* Don't inline a function with mismatched sanitization attributes. */
408 else if (!sanitize_attrs_match_for_inline_p (caller->decl, callee->decl))
410 e->inline_failed = CIF_ATTRIBUTE_MISMATCH;
411 inlinable = false;
413 /* Check if caller growth allows the inlining. */
414 else if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl)
415 && !disregard_limits
416 && !lookup_attribute ("flatten",
417 DECL_ATTRIBUTES (caller->decl))
418 && !caller_growth_limits (e))
419 inlinable = false;
420 /* Don't inline a function with a higher optimization level than the
421 caller. FIXME: this is really just tip of iceberg of handling
422 optimization attribute. */
423 else if (caller_tree != callee_tree)
425 bool always_inline =
426 (DECL_DISREGARD_INLINE_LIMITS (callee->decl)
427 && lookup_attribute ("always_inline",
428 DECL_ATTRIBUTES (callee->decl)));
430 /* There are some options that change IL semantics which means
431 we cannot inline in these cases for correctness reason.
432 Not even for always_inline declared functions. */
433 /* Strictly speaking only when the callee contains signed integer
434 math where overflow is undefined. */
435 if ((check_maybe_up (flag_strict_overflow)
436 /* this flag is set by optimize. Allow inlining across
437 optimize boundary. */
438 && (!opt_for_fn (caller->decl, optimize)
439 == !opt_for_fn (callee->decl, optimize) || !always_inline))
440 || check_match (flag_wrapv)
441 || check_match (flag_trapv)
442 /* Strictly speaking only when the callee uses FP math. */
443 || check_maybe_up (flag_rounding_math)
444 || check_maybe_up (flag_trapping_math)
445 || check_maybe_down (flag_unsafe_math_optimizations)
446 || check_maybe_down (flag_finite_math_only)
447 || check_maybe_up (flag_signaling_nans)
448 || check_maybe_down (flag_cx_limited_range)
449 || check_maybe_up (flag_signed_zeros)
450 || check_maybe_down (flag_associative_math)
451 || check_maybe_down (flag_reciprocal_math)
452 /* We do not want to make code compiled with exceptions to be brought
453 into a non-EH function unless we know that the callee does not
454 throw. This is tracked by DECL_FUNCTION_PERSONALITY. */
455 || (check_match (flag_non_call_exceptions)
456 /* TODO: We also may allow bringing !flag_non_call_exceptions
457 to flag_non_call_exceptions function, but that may need
458 extra work in tree-inline to add the extra EH edges. */
459 && (!opt_for_fn (callee->decl, flag_non_call_exceptions)
460 || DECL_FUNCTION_PERSONALITY (callee->decl)))
461 || (check_maybe_up (flag_exceptions)
462 && DECL_FUNCTION_PERSONALITY (callee->decl))
463 /* Strictly speaking only when the callee contains function
464 calls that may end up setting errno. */
465 || check_maybe_up (flag_errno_math)
466 /* When devirtualization is diabled for callee, it is not safe
467 to inline it as we possibly mangled the type info.
468 Allow early inlining of always inlines. */
469 || (!early && check_maybe_down (flag_devirtualize)))
471 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
472 inlinable = false;
474 /* gcc.dg/pr43564.c. Apply user-forced inline even at -O0. */
475 else if (always_inline)
477 /* When user added an attribute to the callee honor it. */
478 else if (lookup_attribute ("optimize", DECL_ATTRIBUTES (callee->decl))
479 && opts_for_fn (caller->decl) != opts_for_fn (callee->decl))
481 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
482 inlinable = false;
484 /* If mismatch is caused by merging two LTO units with different
485 optimizationflags we want to be bit nicer. However never inline
486 if one of functions is not optimized at all. */
487 else if (!opt_for_fn (callee->decl, optimize)
488 || !opt_for_fn (caller->decl, optimize))
490 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
491 inlinable = false;
493 /* If callee is optimized for size and caller is not, allow inlining if
494 code shrinks or we are in MAX_INLINE_INSNS_SINGLE limit and callee
495 is inline (and thus likely an unified comdat). This will allow caller
496 to run faster. */
497 else if (opt_for_fn (callee->decl, optimize_size)
498 > opt_for_fn (caller->decl, optimize_size))
500 int growth = estimate_edge_growth (e);
501 if (growth > 0
502 && (!DECL_DECLARED_INLINE_P (callee->decl)
503 && growth >= MAX (MAX_INLINE_INSNS_SINGLE,
504 MAX_INLINE_INSNS_AUTO)))
506 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
507 inlinable = false;
510 /* If callee is more aggressively optimized for performance than caller,
511 we generally want to inline only cheap (runtime wise) functions. */
512 else if (opt_for_fn (callee->decl, optimize_size)
513 < opt_for_fn (caller->decl, optimize_size)
514 || (opt_for_fn (callee->decl, optimize)
515 > opt_for_fn (caller->decl, optimize)))
517 if (estimate_edge_time (e)
518 >= 20 + inline_edge_summary (e)->call_stmt_time)
520 e->inline_failed = CIF_OPTIMIZATION_MISMATCH;
521 inlinable = false;
527 if (!inlinable && report)
528 report_inline_failed_reason (e);
529 return inlinable;
533 /* Return true if the edge E is inlinable during early inlining. */
535 static bool
536 can_early_inline_edge_p (struct cgraph_edge *e)
538 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
539 /* Early inliner might get called at WPA stage when IPA pass adds new
540 function. In this case we can not really do any of early inlining
541 because function bodies are missing. */
542 if (!gimple_has_body_p (callee->decl))
544 e->inline_failed = CIF_BODY_NOT_AVAILABLE;
545 return false;
547 /* In early inliner some of callees may not be in SSA form yet
548 (i.e. the callgraph is cyclic and we did not process
549 the callee by early inliner, yet). We don't have CIF code for this
550 case; later we will re-do the decision in the real inliner. */
551 if (!gimple_in_ssa_p (DECL_STRUCT_FUNCTION (e->caller->decl))
552 || !gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
554 if (dump_file)
555 fprintf (dump_file, " edge not inlinable: not in SSA form\n");
556 return false;
558 if (!can_inline_edge_p (e, true, false, true))
559 return false;
560 return true;
564 /* Return number of calls in N. Ignore cheap builtins. */
566 static int
567 num_calls (struct cgraph_node *n)
569 struct cgraph_edge *e;
570 int num = 0;
572 for (e = n->callees; e; e = e->next_callee)
573 if (!is_inexpensive_builtin (e->callee->decl))
574 num++;
575 return num;
579 /* Return true if we are interested in inlining small function. */
581 static bool
582 want_early_inline_function_p (struct cgraph_edge *e)
584 bool want_inline = true;
585 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
587 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
589 /* For AutoFDO, we need to make sure that before profile summary, all
590 hot paths' IR look exactly the same as profiled binary. As a result,
591 in einliner, we will disregard size limit and inline those callsites
592 that are:
593 * inlined in the profiled binary, and
594 * the cloned callee has enough samples to be considered "hot". */
595 else if (flag_auto_profile && afdo_callsite_hot_enough_for_early_inline (e))
597 else if (!DECL_DECLARED_INLINE_P (callee->decl)
598 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
600 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
601 report_inline_failed_reason (e);
602 want_inline = false;
604 else
606 int growth = estimate_edge_growth (e);
607 int n;
609 if (growth <= 0)
611 else if (!e->maybe_hot_p ()
612 && growth > 0)
614 if (dump_file)
615 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
616 "call is cold and code would grow by %i\n",
617 xstrdup_for_dump (e->caller->name ()),
618 e->caller->order,
619 xstrdup_for_dump (callee->name ()), callee->order,
620 growth);
621 want_inline = false;
623 else if (growth > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
625 if (dump_file)
626 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
627 "growth %i exceeds --param early-inlining-insns\n",
628 xstrdup_for_dump (e->caller->name ()),
629 e->caller->order,
630 xstrdup_for_dump (callee->name ()), callee->order,
631 growth);
632 want_inline = false;
634 else if ((n = num_calls (callee)) != 0
635 && growth * (n + 1) > PARAM_VALUE (PARAM_EARLY_INLINING_INSNS))
637 if (dump_file)
638 fprintf (dump_file, " will not early inline: %s/%i->%s/%i, "
639 "growth %i exceeds --param early-inlining-insns "
640 "divided by number of calls\n",
641 xstrdup_for_dump (e->caller->name ()),
642 e->caller->order,
643 xstrdup_for_dump (callee->name ()), callee->order,
644 growth);
645 want_inline = false;
648 return want_inline;
651 /* Compute time of the edge->caller + edge->callee execution when inlining
652 does not happen. */
654 inline sreal
655 compute_uninlined_call_time (struct inline_summary *callee_info,
656 struct cgraph_edge *edge)
658 sreal uninlined_call_time = (sreal)callee_info->time;
659 cgraph_node *caller = (edge->caller->global.inlined_to
660 ? edge->caller->global.inlined_to
661 : edge->caller);
663 if (edge->count && caller->count)
664 uninlined_call_time *= (sreal)edge->count / caller->count;
665 if (edge->frequency)
666 uninlined_call_time *= cgraph_freq_base_rec * edge->frequency;
667 else
668 uninlined_call_time = uninlined_call_time >> 11;
670 int caller_time = inline_summaries->get (caller)->time;
671 return uninlined_call_time + caller_time;
674 /* Same as compute_uinlined_call_time but compute time when inlining
675 does happen. */
677 inline sreal
678 compute_inlined_call_time (struct cgraph_edge *edge,
679 int edge_time)
681 cgraph_node *caller = (edge->caller->global.inlined_to
682 ? edge->caller->global.inlined_to
683 : edge->caller);
684 int caller_time = inline_summaries->get (caller)->time;
685 sreal time = edge_time;
687 if (edge->count && caller->count)
688 time *= (sreal)edge->count / caller->count;
689 if (edge->frequency)
690 time *= cgraph_freq_base_rec * edge->frequency;
691 else
692 time = time >> 11;
694 /* This calculation should match one in ipa-inline-analysis.
695 FIXME: Once ipa-inline-analysis is converted to sreal this can be
696 simplified. */
697 time -= (sreal) ((gcov_type) edge->frequency
698 * inline_edge_summary (edge)->call_stmt_time
699 * (INLINE_TIME_SCALE / CGRAPH_FREQ_BASE)) / INLINE_TIME_SCALE;
700 time += caller_time;
701 if (time <= 0)
702 time = ((sreal) 1) >> 8;
703 gcc_checking_assert (time >= 0);
704 return time;
707 /* Return true if the speedup for inlining E is bigger than
708 PARAM_MAX_INLINE_MIN_SPEEDUP. */
710 static bool
711 big_speedup_p (struct cgraph_edge *e)
713 sreal time = compute_uninlined_call_time (inline_summaries->get (e->callee),
715 sreal inlined_time = compute_inlined_call_time (e, estimate_edge_time (e));
717 if (time - inlined_time
718 > (sreal) time * PARAM_VALUE (PARAM_INLINE_MIN_SPEEDUP)
719 * percent_rec)
720 return true;
721 return false;
724 /* Return true if we are interested in inlining small function.
725 When REPORT is true, report reason to dump file. */
727 static bool
728 want_inline_small_function_p (struct cgraph_edge *e, bool report)
730 bool want_inline = true;
731 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
733 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
735 else if (!DECL_DECLARED_INLINE_P (callee->decl)
736 && !opt_for_fn (e->caller->decl, flag_inline_small_functions))
738 e->inline_failed = CIF_FUNCTION_NOT_INLINE_CANDIDATE;
739 want_inline = false;
741 /* Do fast and conservative check if the function can be good
742 inline candidate. At the moment we allow inline hints to
743 promote non-inline functions to inline and we increase
744 MAX_INLINE_INSNS_SINGLE 16-fold for inline functions. */
745 else if ((!DECL_DECLARED_INLINE_P (callee->decl)
746 && (!e->count || !e->maybe_hot_p ()))
747 && inline_summaries->get (callee)->min_size
748 - inline_edge_summary (e)->call_stmt_size
749 > MAX (MAX_INLINE_INSNS_SINGLE, MAX_INLINE_INSNS_AUTO))
751 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
752 want_inline = false;
754 else if ((DECL_DECLARED_INLINE_P (callee->decl) || e->count)
755 && inline_summaries->get (callee)->min_size
756 - inline_edge_summary (e)->call_stmt_size
757 > 16 * MAX_INLINE_INSNS_SINGLE)
759 e->inline_failed = (DECL_DECLARED_INLINE_P (callee->decl)
760 ? CIF_MAX_INLINE_INSNS_SINGLE_LIMIT
761 : CIF_MAX_INLINE_INSNS_AUTO_LIMIT);
762 want_inline = false;
764 else
766 int growth = estimate_edge_growth (e);
767 inline_hints hints = estimate_edge_hints (e);
768 bool big_speedup = big_speedup_p (e);
770 if (growth <= 0)
772 /* Apply MAX_INLINE_INSNS_SINGLE limit. Do not do so when
773 hints suggests that inlining given function is very profitable. */
774 else if (DECL_DECLARED_INLINE_P (callee->decl)
775 && growth >= MAX_INLINE_INSNS_SINGLE
776 && ((!big_speedup
777 && !(hints & (INLINE_HINT_indirect_call
778 | INLINE_HINT_known_hot
779 | INLINE_HINT_loop_iterations
780 | INLINE_HINT_array_index
781 | INLINE_HINT_loop_stride)))
782 || growth >= MAX_INLINE_INSNS_SINGLE * 16))
784 e->inline_failed = CIF_MAX_INLINE_INSNS_SINGLE_LIMIT;
785 want_inline = false;
787 else if (!DECL_DECLARED_INLINE_P (callee->decl)
788 && !opt_for_fn (e->caller->decl, flag_inline_functions))
790 /* growth_likely_positive is expensive, always test it last. */
791 if (growth >= MAX_INLINE_INSNS_SINGLE
792 || growth_likely_positive (callee, growth))
794 e->inline_failed = CIF_NOT_DECLARED_INLINED;
795 want_inline = false;
798 /* Apply MAX_INLINE_INSNS_AUTO limit for functions not declared inline
799 Upgrade it to MAX_INLINE_INSNS_SINGLE when hints suggests that
800 inlining given function is very profitable. */
801 else if (!DECL_DECLARED_INLINE_P (callee->decl)
802 && !big_speedup
803 && !(hints & INLINE_HINT_known_hot)
804 && growth >= ((hints & (INLINE_HINT_indirect_call
805 | INLINE_HINT_loop_iterations
806 | INLINE_HINT_array_index
807 | INLINE_HINT_loop_stride))
808 ? MAX (MAX_INLINE_INSNS_AUTO,
809 MAX_INLINE_INSNS_SINGLE)
810 : MAX_INLINE_INSNS_AUTO))
812 /* growth_likely_positive is expensive, always test it last. */
813 if (growth >= MAX_INLINE_INSNS_SINGLE
814 || growth_likely_positive (callee, growth))
816 e->inline_failed = CIF_MAX_INLINE_INSNS_AUTO_LIMIT;
817 want_inline = false;
820 /* If call is cold, do not inline when function body would grow. */
821 else if (!e->maybe_hot_p ()
822 && (growth >= MAX_INLINE_INSNS_SINGLE
823 || growth_likely_positive (callee, growth)))
825 e->inline_failed = CIF_UNLIKELY_CALL;
826 want_inline = false;
829 if (!want_inline && report)
830 report_inline_failed_reason (e);
831 return want_inline;
834 /* EDGE is self recursive edge.
835 We hand two cases - when function A is inlining into itself
836 or when function A is being inlined into another inliner copy of function
837 A within function B.
839 In first case OUTER_NODE points to the toplevel copy of A, while
840 in the second case OUTER_NODE points to the outermost copy of A in B.
842 In both cases we want to be extra selective since
843 inlining the call will just introduce new recursive calls to appear. */
845 static bool
846 want_inline_self_recursive_call_p (struct cgraph_edge *edge,
847 struct cgraph_node *outer_node,
848 bool peeling,
849 int depth)
851 char const *reason = NULL;
852 bool want_inline = true;
853 int caller_freq = CGRAPH_FREQ_BASE;
854 int max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH_AUTO);
856 if (DECL_DECLARED_INLINE_P (edge->caller->decl))
857 max_depth = PARAM_VALUE (PARAM_MAX_INLINE_RECURSIVE_DEPTH);
859 if (!edge->maybe_hot_p ())
861 reason = "recursive call is cold";
862 want_inline = false;
864 else if (max_count && !outer_node->count)
866 reason = "not executed in profile";
867 want_inline = false;
869 else if (depth > max_depth)
871 reason = "--param max-inline-recursive-depth exceeded.";
872 want_inline = false;
875 if (outer_node->global.inlined_to)
876 caller_freq = outer_node->callers->frequency;
878 if (!caller_freq)
880 reason = "function is inlined and unlikely";
881 want_inline = false;
884 if (!want_inline)
886 /* Inlining of self recursive function into copy of itself within other function
887 is transformation similar to loop peeling.
889 Peeling is profitable if we can inline enough copies to make probability
890 of actual call to the self recursive function very small. Be sure that
891 the probability of recursion is small.
893 We ensure that the frequency of recursing is at most 1 - (1/max_depth).
894 This way the expected number of recision is at most max_depth. */
895 else if (peeling)
897 int max_prob = CGRAPH_FREQ_BASE - ((CGRAPH_FREQ_BASE + max_depth - 1)
898 / max_depth);
899 int i;
900 for (i = 1; i < depth; i++)
901 max_prob = max_prob * max_prob / CGRAPH_FREQ_BASE;
902 if (max_count
903 && (edge->count * CGRAPH_FREQ_BASE / outer_node->count
904 >= max_prob))
906 reason = "profile of recursive call is too large";
907 want_inline = false;
909 if (!max_count
910 && (edge->frequency * CGRAPH_FREQ_BASE / caller_freq
911 >= max_prob))
913 reason = "frequency of recursive call is too large";
914 want_inline = false;
917 /* Recursive inlining, i.e. equivalent of unrolling, is profitable if recursion
918 depth is large. We reduce function call overhead and increase chances that
919 things fit in hardware return predictor.
921 Recursive inlining might however increase cost of stack frame setup
922 actually slowing down functions whose recursion tree is wide rather than
923 deep.
925 Deciding reliably on when to do recursive inlining without profile feedback
926 is tricky. For now we disable recursive inlining when probability of self
927 recursion is low.
929 Recursive inlining of self recursive call within loop also results in large loop
930 depths that generally optimize badly. We may want to throttle down inlining
931 in those cases. In particular this seems to happen in one of libstdc++ rb tree
932 methods. */
933 else
935 if (max_count
936 && (edge->count * 100 / outer_node->count
937 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
939 reason = "profile of recursive call is too small";
940 want_inline = false;
942 else if (!max_count
943 && (edge->frequency * 100 / caller_freq
944 <= PARAM_VALUE (PARAM_MIN_INLINE_RECURSIVE_PROBABILITY)))
946 reason = "frequency of recursive call is too small";
947 want_inline = false;
950 if (!want_inline && dump_file)
951 fprintf (dump_file, " not inlining recursively: %s\n", reason);
952 return want_inline;
955 /* Return true when NODE has uninlinable caller;
956 set HAS_HOT_CALL if it has hot call.
957 Worker for cgraph_for_node_and_aliases. */
959 static bool
960 check_callers (struct cgraph_node *node, void *has_hot_call)
962 struct cgraph_edge *e;
963 for (e = node->callers; e; e = e->next_caller)
965 if (!opt_for_fn (e->caller->decl, flag_inline_functions_called_once))
966 return true;
967 if (!can_inline_edge_p (e, true))
968 return true;
969 if (e->recursive_p ())
970 return true;
971 if (!(*(bool *)has_hot_call) && e->maybe_hot_p ())
972 *(bool *)has_hot_call = true;
974 return false;
977 /* If NODE has a caller, return true. */
979 static bool
980 has_caller_p (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
982 if (node->callers)
983 return true;
984 return false;
987 /* Decide if inlining NODE would reduce unit size by eliminating
988 the offline copy of function.
989 When COLD is true the cold calls are considered, too. */
991 static bool
992 want_inline_function_to_all_callers_p (struct cgraph_node *node, bool cold)
994 bool has_hot_call = false;
996 /* Aliases gets inlined along with the function they alias. */
997 if (node->alias)
998 return false;
999 /* Already inlined? */
1000 if (node->global.inlined_to)
1001 return false;
1002 /* Does it have callers? */
1003 if (!node->call_for_symbol_and_aliases (has_caller_p, NULL, true))
1004 return false;
1005 /* Inlining into all callers would increase size? */
1006 if (estimate_growth (node) > 0)
1007 return false;
1008 /* All inlines must be possible. */
1009 if (node->call_for_symbol_and_aliases (check_callers, &has_hot_call,
1010 true))
1011 return false;
1012 if (!cold && !has_hot_call)
1013 return false;
1014 return true;
1017 /* A cost model driving the inlining heuristics in a way so the edges with
1018 smallest badness are inlined first. After each inlining is performed
1019 the costs of all caller edges of nodes affected are recomputed so the
1020 metrics may accurately depend on values such as number of inlinable callers
1021 of the function or function body size. */
1023 static sreal
1024 edge_badness (struct cgraph_edge *edge, bool dump)
1026 sreal badness;
1027 int growth, edge_time;
1028 struct cgraph_node *callee = edge->callee->ultimate_alias_target ();
1029 struct inline_summary *callee_info = inline_summaries->get (callee);
1030 inline_hints hints;
1031 cgraph_node *caller = (edge->caller->global.inlined_to
1032 ? edge->caller->global.inlined_to
1033 : edge->caller);
1035 growth = estimate_edge_growth (edge);
1036 edge_time = estimate_edge_time (edge);
1037 hints = estimate_edge_hints (edge);
1038 gcc_checking_assert (edge_time >= 0);
1039 gcc_checking_assert (edge_time <= callee_info->time);
1040 gcc_checking_assert (growth <= callee_info->size);
1042 if (dump)
1044 fprintf (dump_file, " Badness calculation for %s/%i -> %s/%i\n",
1045 xstrdup_for_dump (edge->caller->name ()),
1046 edge->caller->order,
1047 xstrdup_for_dump (callee->name ()),
1048 edge->callee->order);
1049 fprintf (dump_file, " size growth %i, time %i ",
1050 growth,
1051 edge_time);
1052 dump_inline_hints (dump_file, hints);
1053 if (big_speedup_p (edge))
1054 fprintf (dump_file, " big_speedup");
1055 fprintf (dump_file, "\n");
1058 /* Always prefer inlining saving code size. */
1059 if (growth <= 0)
1061 badness = (sreal) (-SREAL_MIN_SIG + growth) << (SREAL_MAX_EXP / 256);
1062 if (dump)
1063 fprintf (dump_file, " %f: Growth %d <= 0\n", badness.to_double (),
1064 growth);
1066 /* Inlining into EXTERNAL functions is not going to change anything unless
1067 they are themselves inlined. */
1068 else if (DECL_EXTERNAL (caller->decl))
1070 if (dump)
1071 fprintf (dump_file, " max: function is external\n");
1072 return sreal::max ();
1074 /* When profile is available. Compute badness as:
1076 time_saved * caller_count
1077 goodness = -------------------------------------------------
1078 growth_of_caller * overall_growth * combined_size
1080 badness = - goodness
1082 Again use negative value to make calls with profile appear hotter
1083 then calls without.
1085 else if (opt_for_fn (caller->decl, flag_guess_branch_prob) || caller->count)
1087 sreal numerator, denominator;
1088 int overall_growth;
1090 numerator = (compute_uninlined_call_time (callee_info, edge)
1091 - compute_inlined_call_time (edge, edge_time));
1092 if (numerator == 0)
1093 numerator = ((sreal) 1 >> 8);
1094 if (caller->count)
1095 numerator *= caller->count;
1096 else if (opt_for_fn (caller->decl, flag_branch_probabilities))
1097 numerator = numerator >> 11;
1098 denominator = growth;
1100 overall_growth = callee_info->growth;
1102 /* Look for inliner wrappers of the form:
1104 inline_caller ()
1106 do_fast_job...
1107 if (need_more_work)
1108 noninline_callee ();
1110 Withhout panilizing this case, we usually inline noninline_callee
1111 into the inline_caller because overall_growth is small preventing
1112 further inlining of inline_caller.
1114 Penalize only callgraph edges to functions with small overall
1115 growth ...
1117 if (growth > overall_growth
1118 /* ... and having only one caller which is not inlined ... */
1119 && callee_info->single_caller
1120 && !edge->caller->global.inlined_to
1121 /* ... and edges executed only conditionally ... */
1122 && edge->frequency < CGRAPH_FREQ_BASE
1123 /* ... consider case where callee is not inline but caller is ... */
1124 && ((!DECL_DECLARED_INLINE_P (edge->callee->decl)
1125 && DECL_DECLARED_INLINE_P (caller->decl))
1126 /* ... or when early optimizers decided to split and edge
1127 frequency still indicates splitting is a win ... */
1128 || (callee->split_part && !caller->split_part
1129 && edge->frequency
1130 < CGRAPH_FREQ_BASE
1131 * PARAM_VALUE
1132 (PARAM_PARTIAL_INLINING_ENTRY_PROBABILITY) / 100
1133 /* ... and do not overwrite user specified hints. */
1134 && (!DECL_DECLARED_INLINE_P (edge->callee->decl)
1135 || DECL_DECLARED_INLINE_P (caller->decl)))))
1137 struct inline_summary *caller_info = inline_summaries->get (caller);
1138 int caller_growth = caller_info->growth;
1140 /* Only apply the penalty when caller looks like inline candidate,
1141 and it is not called once and. */
1142 if (!caller_info->single_caller && overall_growth < caller_growth
1143 && caller_info->inlinable
1144 && caller_info->size
1145 < (DECL_DECLARED_INLINE_P (caller->decl)
1146 ? MAX_INLINE_INSNS_SINGLE : MAX_INLINE_INSNS_AUTO))
1148 if (dump)
1149 fprintf (dump_file,
1150 " Wrapper penalty. Increasing growth %i to %i\n",
1151 overall_growth, caller_growth);
1152 overall_growth = caller_growth;
1155 if (overall_growth > 0)
1157 /* Strongly preffer functions with few callers that can be inlined
1158 fully. The square root here leads to smaller binaries at average.
1159 Watch however for extreme cases and return to linear function
1160 when growth is large. */
1161 if (overall_growth < 256)
1162 overall_growth *= overall_growth;
1163 else
1164 overall_growth += 256 * 256 - 256;
1165 denominator *= overall_growth;
1167 denominator *= inline_summaries->get (caller)->self_size + growth;
1169 badness = - numerator / denominator;
1171 if (dump)
1173 fprintf (dump_file,
1174 " %f: guessed profile. frequency %f, count %"PRId64
1175 " caller count %"PRId64
1176 " time w/o inlining %f, time w inlining %f"
1177 " overall growth %i (current) %i (original)"
1178 " %i (compensated)\n",
1179 badness.to_double (),
1180 (double)edge->frequency / CGRAPH_FREQ_BASE,
1181 edge->count, caller->count,
1182 compute_uninlined_call_time (callee_info, edge).to_double (),
1183 compute_inlined_call_time (edge, edge_time).to_double (),
1184 estimate_growth (callee),
1185 callee_info->growth, overall_growth);
1188 /* When function local profile is not available or it does not give
1189 useful information (ie frequency is zero), base the cost on
1190 loop nest and overall size growth, so we optimize for overall number
1191 of functions fully inlined in program. */
1192 else
1194 int nest = MIN (inline_edge_summary (edge)->loop_depth, 8);
1195 badness = growth;
1197 /* Decrease badness if call is nested. */
1198 if (badness > 0)
1199 badness = badness >> nest;
1200 else
1201 badness = badness << nest;
1202 if (dump)
1203 fprintf (dump_file, " %f: no profile. nest %i\n",
1204 badness.to_double (), nest);
1206 gcc_checking_assert (badness != 0);
1208 if (edge->recursive_p ())
1209 badness = badness.shift (badness > 0 ? 4 : -4);
1210 if ((hints & (INLINE_HINT_indirect_call
1211 | INLINE_HINT_loop_iterations
1212 | INLINE_HINT_array_index
1213 | INLINE_HINT_loop_stride))
1214 || callee_info->growth <= 0)
1215 badness = badness.shift (badness > 0 ? -2 : 2);
1216 if (hints & (INLINE_HINT_same_scc))
1217 badness = badness.shift (badness > 0 ? 3 : -3);
1218 else if (hints & (INLINE_HINT_in_scc))
1219 badness = badness.shift (badness > 0 ? 2 : -2);
1220 else if (hints & (INLINE_HINT_cross_module))
1221 badness = badness.shift (badness > 0 ? 1 : -1);
1222 if (DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1223 badness = badness.shift (badness > 0 ? -4 : 4);
1224 else if ((hints & INLINE_HINT_declared_inline))
1225 badness = badness.shift (badness > 0 ? -3 : 3);
1226 if (dump)
1227 fprintf (dump_file, " Adjusted by hints %f\n", badness.to_double ());
1228 return badness;
1231 /* Recompute badness of EDGE and update its key in HEAP if needed. */
1232 static inline void
1233 update_edge_key (edge_heap_t *heap, struct cgraph_edge *edge)
1235 sreal badness = edge_badness (edge, false);
1236 if (edge->aux)
1238 edge_heap_node_t *n = (edge_heap_node_t *) edge->aux;
1239 gcc_checking_assert (n->get_data () == edge);
1241 /* fibonacci_heap::replace_key does busy updating of the
1242 heap that is unnecesarily expensive.
1243 We do lazy increases: after extracting minimum if the key
1244 turns out to be out of date, it is re-inserted into heap
1245 with correct value. */
1246 if (badness < n->get_key ())
1248 if (dump_file && (dump_flags & TDF_DETAILS))
1250 fprintf (dump_file,
1251 " decreasing badness %s/%i -> %s/%i, %f"
1252 " to %f\n",
1253 xstrdup_for_dump (edge->caller->name ()),
1254 edge->caller->order,
1255 xstrdup_for_dump (edge->callee->name ()),
1256 edge->callee->order,
1257 n->get_key ().to_double (),
1258 badness.to_double ());
1260 heap->decrease_key (n, badness);
1263 else
1265 if (dump_file && (dump_flags & TDF_DETAILS))
1267 fprintf (dump_file,
1268 " enqueuing call %s/%i -> %s/%i, badness %f\n",
1269 xstrdup_for_dump (edge->caller->name ()),
1270 edge->caller->order,
1271 xstrdup_for_dump (edge->callee->name ()),
1272 edge->callee->order,
1273 badness.to_double ());
1275 edge->aux = heap->insert (badness, edge);
1280 /* NODE was inlined.
1281 All caller edges needs to be resetted because
1282 size estimates change. Similarly callees needs reset
1283 because better context may be known. */
1285 static void
1286 reset_edge_caches (struct cgraph_node *node)
1288 struct cgraph_edge *edge;
1289 struct cgraph_edge *e = node->callees;
1290 struct cgraph_node *where = node;
1291 struct ipa_ref *ref;
1293 if (where->global.inlined_to)
1294 where = where->global.inlined_to;
1296 for (edge = where->callers; edge; edge = edge->next_caller)
1297 if (edge->inline_failed)
1298 reset_edge_growth_cache (edge);
1300 FOR_EACH_ALIAS (where, ref)
1301 reset_edge_caches (dyn_cast <cgraph_node *> (ref->referring));
1303 if (!e)
1304 return;
1306 while (true)
1307 if (!e->inline_failed && e->callee->callees)
1308 e = e->callee->callees;
1309 else
1311 if (e->inline_failed)
1312 reset_edge_growth_cache (e);
1313 if (e->next_callee)
1314 e = e->next_callee;
1315 else
1319 if (e->caller == node)
1320 return;
1321 e = e->caller->callers;
1323 while (!e->next_callee);
1324 e = e->next_callee;
1329 /* Recompute HEAP nodes for each of caller of NODE.
1330 UPDATED_NODES track nodes we already visited, to avoid redundant work.
1331 When CHECK_INLINABLITY_FOR is set, re-check for specified edge that
1332 it is inlinable. Otherwise check all edges. */
1334 static void
1335 update_caller_keys (edge_heap_t *heap, struct cgraph_node *node,
1336 bitmap updated_nodes,
1337 struct cgraph_edge *check_inlinablity_for)
1339 struct cgraph_edge *edge;
1340 struct ipa_ref *ref;
1342 if ((!node->alias && !inline_summaries->get (node)->inlinable)
1343 || node->global.inlined_to)
1344 return;
1345 if (!bitmap_set_bit (updated_nodes, node->uid))
1346 return;
1348 FOR_EACH_ALIAS (node, ref)
1350 struct cgraph_node *alias = dyn_cast <cgraph_node *> (ref->referring);
1351 update_caller_keys (heap, alias, updated_nodes, check_inlinablity_for);
1354 for (edge = node->callers; edge; edge = edge->next_caller)
1355 if (edge->inline_failed)
1357 if (!check_inlinablity_for
1358 || check_inlinablity_for == edge)
1360 if (can_inline_edge_p (edge, false)
1361 && want_inline_small_function_p (edge, false))
1362 update_edge_key (heap, edge);
1363 else if (edge->aux)
1365 report_inline_failed_reason (edge);
1366 heap->delete_node ((edge_heap_node_t *) edge->aux);
1367 edge->aux = NULL;
1370 else if (edge->aux)
1371 update_edge_key (heap, edge);
1375 /* Recompute HEAP nodes for each uninlined call in NODE.
1376 This is used when we know that edge badnesses are going only to increase
1377 (we introduced new call site) and thus all we need is to insert newly
1378 created edges into heap. */
1380 static void
1381 update_callee_keys (edge_heap_t *heap, struct cgraph_node *node,
1382 bitmap updated_nodes)
1384 struct cgraph_edge *e = node->callees;
1386 if (!e)
1387 return;
1388 while (true)
1389 if (!e->inline_failed && e->callee->callees)
1390 e = e->callee->callees;
1391 else
1393 enum availability avail;
1394 struct cgraph_node *callee;
1395 /* We do not reset callee growth cache here. Since we added a new call,
1396 growth chould have just increased and consequentely badness metric
1397 don't need updating. */
1398 if (e->inline_failed
1399 && (callee = e->callee->ultimate_alias_target (&avail))
1400 && inline_summaries->get (callee)->inlinable
1401 && avail >= AVAIL_AVAILABLE
1402 && !bitmap_bit_p (updated_nodes, callee->uid))
1404 if (can_inline_edge_p (e, false)
1405 && want_inline_small_function_p (e, false))
1406 update_edge_key (heap, e);
1407 else if (e->aux)
1409 report_inline_failed_reason (e);
1410 heap->delete_node ((edge_heap_node_t *) e->aux);
1411 e->aux = NULL;
1414 if (e->next_callee)
1415 e = e->next_callee;
1416 else
1420 if (e->caller == node)
1421 return;
1422 e = e->caller->callers;
1424 while (!e->next_callee);
1425 e = e->next_callee;
1430 /* Enqueue all recursive calls from NODE into priority queue depending on
1431 how likely we want to recursively inline the call. */
1433 static void
1434 lookup_recursive_calls (struct cgraph_node *node, struct cgraph_node *where,
1435 edge_heap_t *heap)
1437 struct cgraph_edge *e;
1438 enum availability avail;
1440 for (e = where->callees; e; e = e->next_callee)
1441 if (e->callee == node
1442 || (e->callee->ultimate_alias_target (&avail) == node
1443 && avail > AVAIL_INTERPOSABLE))
1445 /* When profile feedback is available, prioritize by expected number
1446 of calls. */
1447 heap->insert (!max_count ? -e->frequency
1448 : -(e->count / ((max_count + (1<<24) - 1) / (1<<24))),
1451 for (e = where->callees; e; e = e->next_callee)
1452 if (!e->inline_failed)
1453 lookup_recursive_calls (node, e->callee, heap);
1456 /* Decide on recursive inlining: in the case function has recursive calls,
1457 inline until body size reaches given argument. If any new indirect edges
1458 are discovered in the process, add them to *NEW_EDGES, unless NEW_EDGES
1459 is NULL. */
1461 static bool
1462 recursive_inlining (struct cgraph_edge *edge,
1463 vec<cgraph_edge *> *new_edges)
1465 int limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE_AUTO);
1466 edge_heap_t heap (sreal::min ());
1467 struct cgraph_node *node;
1468 struct cgraph_edge *e;
1469 struct cgraph_node *master_clone = NULL, *next;
1470 int depth = 0;
1471 int n = 0;
1473 node = edge->caller;
1474 if (node->global.inlined_to)
1475 node = node->global.inlined_to;
1477 if (DECL_DECLARED_INLINE_P (node->decl))
1478 limit = PARAM_VALUE (PARAM_MAX_INLINE_INSNS_RECURSIVE);
1480 /* Make sure that function is small enough to be considered for inlining. */
1481 if (estimate_size_after_inlining (node, edge) >= limit)
1482 return false;
1483 lookup_recursive_calls (node, node, &heap);
1484 if (heap.empty ())
1485 return false;
1487 if (dump_file)
1488 fprintf (dump_file,
1489 " Performing recursive inlining on %s\n",
1490 node->name ());
1492 /* Do the inlining and update list of recursive call during process. */
1493 while (!heap.empty ())
1495 struct cgraph_edge *curr = heap.extract_min ();
1496 struct cgraph_node *cnode, *dest = curr->callee;
1498 if (!can_inline_edge_p (curr, true))
1499 continue;
1501 /* MASTER_CLONE is produced in the case we already started modified
1502 the function. Be sure to redirect edge to the original body before
1503 estimating growths otherwise we will be seeing growths after inlining
1504 the already modified body. */
1505 if (master_clone)
1507 curr->redirect_callee (master_clone);
1508 reset_edge_growth_cache (curr);
1511 if (estimate_size_after_inlining (node, curr) > limit)
1513 curr->redirect_callee (dest);
1514 reset_edge_growth_cache (curr);
1515 break;
1518 depth = 1;
1519 for (cnode = curr->caller;
1520 cnode->global.inlined_to; cnode = cnode->callers->caller)
1521 if (node->decl
1522 == curr->callee->ultimate_alias_target ()->decl)
1523 depth++;
1525 if (!want_inline_self_recursive_call_p (curr, node, false, depth))
1527 curr->redirect_callee (dest);
1528 reset_edge_growth_cache (curr);
1529 continue;
1532 if (dump_file)
1534 fprintf (dump_file,
1535 " Inlining call of depth %i", depth);
1536 if (node->count)
1538 fprintf (dump_file, " called approx. %.2f times per call",
1539 (double)curr->count / node->count);
1541 fprintf (dump_file, "\n");
1543 if (!master_clone)
1545 /* We need original clone to copy around. */
1546 master_clone = node->create_clone (node->decl, node->count,
1547 CGRAPH_FREQ_BASE, false, vNULL,
1548 true, NULL, NULL);
1549 for (e = master_clone->callees; e; e = e->next_callee)
1550 if (!e->inline_failed)
1551 clone_inlined_nodes (e, true, false, NULL, CGRAPH_FREQ_BASE);
1552 curr->redirect_callee (master_clone);
1553 reset_edge_growth_cache (curr);
1556 inline_call (curr, false, new_edges, &overall_size, true);
1557 lookup_recursive_calls (node, curr->callee, &heap);
1558 n++;
1561 if (!heap.empty () && dump_file)
1562 fprintf (dump_file, " Recursive inlining growth limit met.\n");
1564 if (!master_clone)
1565 return false;
1567 if (dump_file)
1568 fprintf (dump_file,
1569 "\n Inlined %i times, "
1570 "body grown from size %i to %i, time %i to %i\n", n,
1571 inline_summaries->get (master_clone)->size, inline_summaries->get (node)->size,
1572 inline_summaries->get (master_clone)->time, inline_summaries->get (node)->time);
1574 /* Remove master clone we used for inlining. We rely that clones inlined
1575 into master clone gets queued just before master clone so we don't
1576 need recursion. */
1577 for (node = symtab->first_function (); node != master_clone;
1578 node = next)
1580 next = symtab->next_function (node);
1581 if (node->global.inlined_to == master_clone)
1582 node->remove ();
1584 master_clone->remove ();
1585 return true;
1589 /* Given whole compilation unit estimate of INSNS, compute how large we can
1590 allow the unit to grow. */
1592 static int
1593 compute_max_insns (int insns)
1595 int max_insns = insns;
1596 if (max_insns < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
1597 max_insns = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
1599 return ((int64_t) max_insns
1600 * (100 + PARAM_VALUE (PARAM_INLINE_UNIT_GROWTH)) / 100);
1604 /* Compute badness of all edges in NEW_EDGES and add them to the HEAP. */
1606 static void
1607 add_new_edges_to_heap (edge_heap_t *heap, vec<cgraph_edge *> new_edges)
1609 while (new_edges.length () > 0)
1611 struct cgraph_edge *edge = new_edges.pop ();
1613 gcc_assert (!edge->aux);
1614 if (edge->inline_failed
1615 && can_inline_edge_p (edge, true)
1616 && want_inline_small_function_p (edge, true))
1617 edge->aux = heap->insert (edge_badness (edge, false), edge);
1621 /* Remove EDGE from the fibheap. */
1623 static void
1624 heap_edge_removal_hook (struct cgraph_edge *e, void *data)
1626 if (e->aux)
1628 ((edge_heap_t *)data)->delete_node ((edge_heap_node_t *)e->aux);
1629 e->aux = NULL;
1633 /* Return true if speculation of edge E seems useful.
1634 If ANTICIPATE_INLINING is true, be conservative and hope that E
1635 may get inlined. */
1637 bool
1638 speculation_useful_p (struct cgraph_edge *e, bool anticipate_inlining)
1640 enum availability avail;
1641 struct cgraph_node *target = e->callee->ultimate_alias_target (&avail);
1642 struct cgraph_edge *direct, *indirect;
1643 struct ipa_ref *ref;
1645 gcc_assert (e->speculative && !e->indirect_unknown_callee);
1647 if (!e->maybe_hot_p ())
1648 return false;
1650 /* See if IP optimizations found something potentially useful about the
1651 function. For now we look only for CONST/PURE flags. Almost everything
1652 else we propagate is useless. */
1653 if (avail >= AVAIL_AVAILABLE)
1655 int ecf_flags = flags_from_decl_or_type (target->decl);
1656 if (ecf_flags & ECF_CONST)
1658 e->speculative_call_info (direct, indirect, ref);
1659 if (!(indirect->indirect_info->ecf_flags & ECF_CONST))
1660 return true;
1662 else if (ecf_flags & ECF_PURE)
1664 e->speculative_call_info (direct, indirect, ref);
1665 if (!(indirect->indirect_info->ecf_flags & ECF_PURE))
1666 return true;
1669 /* If we did not managed to inline the function nor redirect
1670 to an ipa-cp clone (that are seen by having local flag set),
1671 it is probably pointless to inline it unless hardware is missing
1672 indirect call predictor. */
1673 if (!anticipate_inlining && e->inline_failed && !target->local.local)
1674 return false;
1675 /* For overwritable targets there is not much to do. */
1676 if (e->inline_failed && !can_inline_edge_p (e, false, true))
1677 return false;
1678 /* OK, speculation seems interesting. */
1679 return true;
1682 /* We know that EDGE is not going to be inlined.
1683 See if we can remove speculation. */
1685 static void
1686 resolve_noninline_speculation (edge_heap_t *edge_heap, struct cgraph_edge *edge)
1688 if (edge->speculative && !speculation_useful_p (edge, false))
1690 struct cgraph_node *node = edge->caller;
1691 struct cgraph_node *where = node->global.inlined_to
1692 ? node->global.inlined_to : node;
1693 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1695 spec_rem += edge->count;
1696 edge->resolve_speculation ();
1697 reset_edge_caches (where);
1698 inline_update_overall_summary (where);
1699 update_caller_keys (edge_heap, where,
1700 updated_nodes, NULL);
1701 update_callee_keys (edge_heap, where,
1702 updated_nodes);
1703 BITMAP_FREE (updated_nodes);
1707 /* Return true if NODE should be accounted for overall size estimate.
1708 Skip all nodes optimized for size so we can measure the growth of hot
1709 part of program no matter of the padding. */
1711 bool
1712 inline_account_function_p (struct cgraph_node *node)
1714 return (!DECL_EXTERNAL (node->decl)
1715 && !opt_for_fn (node->decl, optimize_size)
1716 && node->frequency != NODE_FREQUENCY_UNLIKELY_EXECUTED);
1719 /* Count number of callers of NODE and store it into DATA (that
1720 points to int. Worker for cgraph_for_node_and_aliases. */
1722 static bool
1723 sum_callers (struct cgraph_node *node, void *data)
1725 struct cgraph_edge *e;
1726 int *num_calls = (int *)data;
1728 for (e = node->callers; e; e = e->next_caller)
1729 (*num_calls)++;
1730 return false;
1733 /* We use greedy algorithm for inlining of small functions:
1734 All inline candidates are put into prioritized heap ordered in
1735 increasing badness.
1737 The inlining of small functions is bounded by unit growth parameters. */
1739 static void
1740 inline_small_functions (void)
1742 struct cgraph_node *node;
1743 struct cgraph_edge *edge;
1744 edge_heap_t edge_heap (sreal::min ());
1745 bitmap updated_nodes = BITMAP_ALLOC (NULL);
1746 int min_size, max_size;
1747 auto_vec<cgraph_edge *> new_indirect_edges;
1748 int initial_size = 0;
1749 struct cgraph_node **order = XCNEWVEC (cgraph_node *, symtab->cgraph_count);
1750 struct cgraph_edge_hook_list *edge_removal_hook_holder;
1751 new_indirect_edges.create (8);
1753 edge_removal_hook_holder
1754 = symtab->add_edge_removal_hook (&heap_edge_removal_hook, &edge_heap);
1756 /* Compute overall unit size and other global parameters used by badness
1757 metrics. */
1759 max_count = 0;
1760 ipa_reduced_postorder (order, true, true, NULL);
1761 free (order);
1763 FOR_EACH_DEFINED_FUNCTION (node)
1764 if (!node->global.inlined_to)
1766 if (!node->alias && node->analyzed
1767 && (node->has_gimple_body_p () || node->thunk.thunk_p))
1769 struct inline_summary *info = inline_summaries->get (node);
1770 struct ipa_dfs_info *dfs = (struct ipa_dfs_info *) node->aux;
1772 /* Do not account external functions, they will be optimized out
1773 if not inlined. Also only count the non-cold portion of program. */
1774 if (inline_account_function_p (node))
1775 initial_size += info->size;
1776 info->growth = estimate_growth (node);
1778 int num_calls = 0;
1779 node->call_for_symbol_and_aliases (sum_callers, &num_calls,
1780 true);
1781 if (num_calls == 1)
1782 info->single_caller = true;
1783 if (dfs && dfs->next_cycle)
1785 struct cgraph_node *n2;
1786 int id = dfs->scc_no + 1;
1787 for (n2 = node; n2;
1788 n2 = ((struct ipa_dfs_info *) node->aux)->next_cycle)
1790 struct inline_summary *info2 = inline_summaries->get (n2);
1791 if (info2->scc_no)
1792 break;
1793 info2->scc_no = id;
1798 for (edge = node->callers; edge; edge = edge->next_caller)
1799 if (max_count < edge->count)
1800 max_count = edge->count;
1802 ipa_free_postorder_info ();
1803 initialize_growth_caches ();
1805 if (dump_file)
1806 fprintf (dump_file,
1807 "\nDeciding on inlining of small functions. Starting with size %i.\n",
1808 initial_size);
1810 overall_size = initial_size;
1811 max_size = compute_max_insns (overall_size);
1812 min_size = overall_size;
1814 /* Populate the heap with all edges we might inline. */
1816 FOR_EACH_DEFINED_FUNCTION (node)
1818 bool update = false;
1819 struct cgraph_edge *next = NULL;
1820 bool has_speculative = false;
1822 if (dump_file)
1823 fprintf (dump_file, "Enqueueing calls in %s/%i.\n",
1824 node->name (), node->order);
1826 for (edge = node->callees; edge; edge = next)
1828 next = edge->next_callee;
1829 if (edge->inline_failed
1830 && !edge->aux
1831 && can_inline_edge_p (edge, true)
1832 && want_inline_small_function_p (edge, true)
1833 && edge->inline_failed)
1835 gcc_assert (!edge->aux);
1836 update_edge_key (&edge_heap, edge);
1838 if (edge->speculative)
1839 has_speculative = true;
1841 if (has_speculative)
1842 for (edge = node->callees; edge; edge = next)
1843 if (edge->speculative && !speculation_useful_p (edge,
1844 edge->aux != NULL))
1846 edge->resolve_speculation ();
1847 update = true;
1849 if (update)
1851 struct cgraph_node *where = node->global.inlined_to
1852 ? node->global.inlined_to : node;
1853 inline_update_overall_summary (where);
1854 reset_edge_caches (where);
1855 update_caller_keys (&edge_heap, where,
1856 updated_nodes, NULL);
1857 update_callee_keys (&edge_heap, where,
1858 updated_nodes);
1859 bitmap_clear (updated_nodes);
1863 gcc_assert (in_lto_p
1864 || !max_count
1865 || (profile_info && flag_branch_probabilities));
1867 while (!edge_heap.empty ())
1869 int old_size = overall_size;
1870 struct cgraph_node *where, *callee;
1871 sreal badness = edge_heap.min_key ();
1872 sreal current_badness;
1873 int growth;
1875 edge = edge_heap.extract_min ();
1876 gcc_assert (edge->aux);
1877 edge->aux = NULL;
1878 if (!edge->inline_failed || !edge->callee->analyzed)
1879 continue;
1881 #ifdef ENABLE_CHECKING
1882 /* Be sure that caches are maintained consistent. */
1883 sreal cached_badness = edge_badness (edge, false);
1885 int old_size_est = estimate_edge_size (edge);
1886 int old_time_est = estimate_edge_time (edge);
1887 int old_hints_est = estimate_edge_hints (edge);
1889 reset_edge_growth_cache (edge);
1890 gcc_assert (old_size_est == estimate_edge_size (edge));
1891 gcc_assert (old_time_est == estimate_edge_time (edge));
1892 /* FIXME:
1894 gcc_assert (old_hints_est == estimate_edge_hints (edge));
1896 fails with profile feedback because some hints depends on
1897 maybe_hot_edge_p predicate and because callee gets inlined to other
1898 calls, the edge may become cold.
1899 This ought to be fixed by computing relative probabilities
1900 for given invocation but that will be better done once whole
1901 code is converted to sreals. Disable for now and revert to "wrong"
1902 value so enable/disable checking paths agree. */
1903 edge_growth_cache[edge->uid].hints = old_hints_est + 1;
1905 /* When updating the edge costs, we only decrease badness in the keys.
1906 Increases of badness are handled lazilly; when we see key with out
1907 of date value on it, we re-insert it now. */
1908 current_badness = edge_badness (edge, false);
1909 /* Disable checking for profile because roundoff errors may cause slight
1910 deviations in the order. */
1911 gcc_assert (max_count || cached_badness == current_badness);
1912 gcc_assert (current_badness >= badness);
1913 #else
1914 current_badness = edge_badness (edge, false);
1915 #endif
1916 if (current_badness != badness)
1918 if (edge_heap.min () && current_badness > edge_heap.min_key ())
1920 edge->aux = edge_heap.insert (current_badness, edge);
1921 continue;
1923 else
1924 badness = current_badness;
1927 if (!can_inline_edge_p (edge, true))
1929 resolve_noninline_speculation (&edge_heap, edge);
1930 continue;
1933 callee = edge->callee->ultimate_alias_target ();
1934 growth = estimate_edge_growth (edge);
1935 if (dump_file)
1937 fprintf (dump_file,
1938 "\nConsidering %s/%i with %i size\n",
1939 callee->name (), callee->order,
1940 inline_summaries->get (callee)->size);
1941 fprintf (dump_file,
1942 " to be inlined into %s/%i in %s:%i\n"
1943 " Estimated badness is %f, frequency %.2f.\n",
1944 edge->caller->name (), edge->caller->order,
1945 edge->call_stmt
1946 && (LOCATION_LOCUS (gimple_location ((const_gimple)
1947 edge->call_stmt))
1948 > BUILTINS_LOCATION)
1949 ? gimple_filename ((const_gimple) edge->call_stmt)
1950 : "unknown",
1951 edge->call_stmt
1952 ? gimple_lineno ((const_gimple) edge->call_stmt)
1953 : -1,
1954 badness.to_double (),
1955 edge->frequency / (double)CGRAPH_FREQ_BASE);
1956 if (edge->count)
1957 fprintf (dump_file," Called %"PRId64"x\n",
1958 edge->count);
1959 if (dump_flags & TDF_DETAILS)
1960 edge_badness (edge, true);
1963 if (overall_size + growth > max_size
1964 && !DECL_DISREGARD_INLINE_LIMITS (callee->decl))
1966 edge->inline_failed = CIF_INLINE_UNIT_GROWTH_LIMIT;
1967 report_inline_failed_reason (edge);
1968 resolve_noninline_speculation (&edge_heap, edge);
1969 continue;
1972 if (!want_inline_small_function_p (edge, true))
1974 resolve_noninline_speculation (&edge_heap, edge);
1975 continue;
1978 /* Heuristics for inlining small functions work poorly for
1979 recursive calls where we do effects similar to loop unrolling.
1980 When inlining such edge seems profitable, leave decision on
1981 specific inliner. */
1982 if (edge->recursive_p ())
1984 where = edge->caller;
1985 if (where->global.inlined_to)
1986 where = where->global.inlined_to;
1987 if (!recursive_inlining (edge,
1988 opt_for_fn (edge->caller->decl,
1989 flag_indirect_inlining)
1990 ? &new_indirect_edges : NULL))
1992 edge->inline_failed = CIF_RECURSIVE_INLINING;
1993 resolve_noninline_speculation (&edge_heap, edge);
1994 continue;
1996 reset_edge_caches (where);
1997 /* Recursive inliner inlines all recursive calls of the function
1998 at once. Consequently we need to update all callee keys. */
1999 if (opt_for_fn (edge->caller->decl, flag_indirect_inlining))
2000 add_new_edges_to_heap (&edge_heap, new_indirect_edges);
2001 update_callee_keys (&edge_heap, where, updated_nodes);
2002 bitmap_clear (updated_nodes);
2004 else
2006 struct cgraph_node *outer_node = NULL;
2007 int depth = 0;
2009 /* Consider the case where self recursive function A is inlined
2010 into B. This is desired optimization in some cases, since it
2011 leads to effect similar of loop peeling and we might completely
2012 optimize out the recursive call. However we must be extra
2013 selective. */
2015 where = edge->caller;
2016 while (where->global.inlined_to)
2018 if (where->decl == callee->decl)
2019 outer_node = where, depth++;
2020 where = where->callers->caller;
2022 if (outer_node
2023 && !want_inline_self_recursive_call_p (edge, outer_node,
2024 true, depth))
2026 edge->inline_failed
2027 = (DECL_DISREGARD_INLINE_LIMITS (edge->callee->decl)
2028 ? CIF_RECURSIVE_INLINING : CIF_UNSPECIFIED);
2029 resolve_noninline_speculation (&edge_heap, edge);
2030 continue;
2032 else if (depth && dump_file)
2033 fprintf (dump_file, " Peeling recursion with depth %i\n", depth);
2035 gcc_checking_assert (!callee->global.inlined_to);
2036 inline_call (edge, true, &new_indirect_edges, &overall_size, true);
2037 add_new_edges_to_heap (&edge_heap, new_indirect_edges);
2039 reset_edge_caches (edge->callee->function_symbol ());
2041 update_callee_keys (&edge_heap, where, updated_nodes);
2043 where = edge->caller;
2044 if (where->global.inlined_to)
2045 where = where->global.inlined_to;
2047 /* Our profitability metric can depend on local properties
2048 such as number of inlinable calls and size of the function body.
2049 After inlining these properties might change for the function we
2050 inlined into (since it's body size changed) and for the functions
2051 called by function we inlined (since number of it inlinable callers
2052 might change). */
2053 update_caller_keys (&edge_heap, where, updated_nodes, NULL);
2054 /* Offline copy count has possibly changed, recompute if profile is
2055 available. */
2056 if (max_count)
2058 struct cgraph_node *n = cgraph_node::get (edge->callee->decl);
2059 if (n != edge->callee && n->analyzed)
2060 update_callee_keys (&edge_heap, n, updated_nodes);
2062 bitmap_clear (updated_nodes);
2064 if (dump_file)
2066 fprintf (dump_file,
2067 " Inlined into %s which now has time %i and size %i,"
2068 "net change of %+i.\n",
2069 edge->caller->name (),
2070 inline_summaries->get (edge->caller)->time,
2071 inline_summaries->get (edge->caller)->size,
2072 overall_size - old_size);
2074 if (min_size > overall_size)
2076 min_size = overall_size;
2077 max_size = compute_max_insns (min_size);
2079 if (dump_file)
2080 fprintf (dump_file, "New minimal size reached: %i\n", min_size);
2084 free_growth_caches ();
2085 if (dump_file)
2086 fprintf (dump_file,
2087 "Unit growth for small function inlining: %i->%i (%i%%)\n",
2088 initial_size, overall_size,
2089 initial_size ? overall_size * 100 / (initial_size) - 100: 0);
2090 BITMAP_FREE (updated_nodes);
2091 symtab->remove_edge_removal_hook (edge_removal_hook_holder);
2094 /* Flatten NODE. Performed both during early inlining and
2095 at IPA inlining time. */
2097 static void
2098 flatten_function (struct cgraph_node *node, bool early)
2100 struct cgraph_edge *e;
2102 /* We shouldn't be called recursively when we are being processed. */
2103 gcc_assert (node->aux == NULL);
2105 node->aux = (void *) node;
2107 for (e = node->callees; e; e = e->next_callee)
2109 struct cgraph_node *orig_callee;
2110 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2112 /* We've hit cycle? It is time to give up. */
2113 if (callee->aux)
2115 if (dump_file)
2116 fprintf (dump_file,
2117 "Not inlining %s into %s to avoid cycle.\n",
2118 xstrdup_for_dump (callee->name ()),
2119 xstrdup_for_dump (e->caller->name ()));
2120 e->inline_failed = CIF_RECURSIVE_INLINING;
2121 continue;
2124 /* When the edge is already inlined, we just need to recurse into
2125 it in order to fully flatten the leaves. */
2126 if (!e->inline_failed)
2128 flatten_function (callee, early);
2129 continue;
2132 /* Flatten attribute needs to be processed during late inlining. For
2133 extra code quality we however do flattening during early optimization,
2134 too. */
2135 if (!early
2136 ? !can_inline_edge_p (e, true)
2137 : !can_early_inline_edge_p (e))
2138 continue;
2140 if (e->recursive_p ())
2142 if (dump_file)
2143 fprintf (dump_file, "Not inlining: recursive call.\n");
2144 continue;
2147 if (gimple_in_ssa_p (DECL_STRUCT_FUNCTION (node->decl))
2148 != gimple_in_ssa_p (DECL_STRUCT_FUNCTION (callee->decl)))
2150 if (dump_file)
2151 fprintf (dump_file, "Not inlining: SSA form does not match.\n");
2152 continue;
2155 /* Inline the edge and flatten the inline clone. Avoid
2156 recursing through the original node if the node was cloned. */
2157 if (dump_file)
2158 fprintf (dump_file, " Inlining %s into %s.\n",
2159 xstrdup_for_dump (callee->name ()),
2160 xstrdup_for_dump (e->caller->name ()));
2161 orig_callee = callee;
2162 inline_call (e, true, NULL, NULL, false);
2163 if (e->callee != orig_callee)
2164 orig_callee->aux = (void *) node;
2165 flatten_function (e->callee, early);
2166 if (e->callee != orig_callee)
2167 orig_callee->aux = NULL;
2170 node->aux = NULL;
2171 if (!node->global.inlined_to)
2172 inline_update_overall_summary (node);
2175 /* Inline NODE to all callers. Worker for cgraph_for_node_and_aliases.
2176 DATA points to number of calls originally found so we avoid infinite
2177 recursion. */
2179 static bool
2180 inline_to_all_callers (struct cgraph_node *node, void *data)
2182 int *num_calls = (int *)data;
2183 bool callee_removed = false;
2185 while (node->callers && !node->global.inlined_to)
2187 struct cgraph_node *caller = node->callers->caller;
2189 if (!can_inline_edge_p (node->callers, true)
2190 || node->callers->recursive_p ())
2192 if (dump_file)
2193 fprintf (dump_file, "Uninlinable call found; giving up.\n");
2194 *num_calls = 0;
2195 return false;
2198 if (dump_file)
2200 fprintf (dump_file,
2201 "\nInlining %s size %i.\n",
2202 node->name (),
2203 inline_summaries->get (node)->size);
2204 fprintf (dump_file,
2205 " Called once from %s %i insns.\n",
2206 node->callers->caller->name (),
2207 inline_summaries->get (node->callers->caller)->size);
2210 inline_call (node->callers, true, NULL, NULL, true, &callee_removed);
2211 if (dump_file)
2212 fprintf (dump_file,
2213 " Inlined into %s which now has %i size\n",
2214 caller->name (),
2215 inline_summaries->get (caller)->size);
2216 if (!(*num_calls)--)
2218 if (dump_file)
2219 fprintf (dump_file, "New calls found; giving up.\n");
2220 return callee_removed;
2222 if (callee_removed)
2223 return true;
2225 return false;
2228 /* Output overall time estimate. */
2229 static void
2230 dump_overall_stats (void)
2232 int64_t sum_weighted = 0, sum = 0;
2233 struct cgraph_node *node;
2235 FOR_EACH_DEFINED_FUNCTION (node)
2236 if (!node->global.inlined_to
2237 && !node->alias)
2239 int time = inline_summaries->get (node)->time;
2240 sum += time;
2241 sum_weighted += time * node->count;
2243 fprintf (dump_file, "Overall time estimate: "
2244 "%"PRId64" weighted by profile: "
2245 "%"PRId64"\n", sum, sum_weighted);
2248 /* Output some useful stats about inlining. */
2250 static void
2251 dump_inline_stats (void)
2253 int64_t inlined_cnt = 0, inlined_indir_cnt = 0;
2254 int64_t inlined_virt_cnt = 0, inlined_virt_indir_cnt = 0;
2255 int64_t noninlined_cnt = 0, noninlined_indir_cnt = 0;
2256 int64_t noninlined_virt_cnt = 0, noninlined_virt_indir_cnt = 0;
2257 int64_t inlined_speculative = 0, inlined_speculative_ply = 0;
2258 int64_t indirect_poly_cnt = 0, indirect_cnt = 0;
2259 int64_t reason[CIF_N_REASONS][3];
2260 int i;
2261 struct cgraph_node *node;
2263 memset (reason, 0, sizeof (reason));
2264 FOR_EACH_DEFINED_FUNCTION (node)
2266 struct cgraph_edge *e;
2267 for (e = node->callees; e; e = e->next_callee)
2269 if (e->inline_failed)
2271 reason[(int) e->inline_failed][0] += e->count;
2272 reason[(int) e->inline_failed][1] += e->frequency;
2273 reason[(int) e->inline_failed][2] ++;
2274 if (DECL_VIRTUAL_P (e->callee->decl))
2276 if (e->indirect_inlining_edge)
2277 noninlined_virt_indir_cnt += e->count;
2278 else
2279 noninlined_virt_cnt += e->count;
2281 else
2283 if (e->indirect_inlining_edge)
2284 noninlined_indir_cnt += e->count;
2285 else
2286 noninlined_cnt += e->count;
2289 else
2291 if (e->speculative)
2293 if (DECL_VIRTUAL_P (e->callee->decl))
2294 inlined_speculative_ply += e->count;
2295 else
2296 inlined_speculative += e->count;
2298 else if (DECL_VIRTUAL_P (e->callee->decl))
2300 if (e->indirect_inlining_edge)
2301 inlined_virt_indir_cnt += e->count;
2302 else
2303 inlined_virt_cnt += e->count;
2305 else
2307 if (e->indirect_inlining_edge)
2308 inlined_indir_cnt += e->count;
2309 else
2310 inlined_cnt += e->count;
2314 for (e = node->indirect_calls; e; e = e->next_callee)
2315 if (e->indirect_info->polymorphic)
2316 indirect_poly_cnt += e->count;
2317 else
2318 indirect_cnt += e->count;
2320 if (max_count)
2322 fprintf (dump_file,
2323 "Inlined %"PRId64 " + speculative "
2324 "%"PRId64 " + speculative polymorphic "
2325 "%"PRId64 " + previously indirect "
2326 "%"PRId64 " + virtual "
2327 "%"PRId64 " + virtual and previously indirect "
2328 "%"PRId64 "\n" "Not inlined "
2329 "%"PRId64 " + previously indirect "
2330 "%"PRId64 " + virtual "
2331 "%"PRId64 " + virtual and previously indirect "
2332 "%"PRId64 " + stil indirect "
2333 "%"PRId64 " + still indirect polymorphic "
2334 "%"PRId64 "\n", inlined_cnt,
2335 inlined_speculative, inlined_speculative_ply,
2336 inlined_indir_cnt, inlined_virt_cnt, inlined_virt_indir_cnt,
2337 noninlined_cnt, noninlined_indir_cnt, noninlined_virt_cnt,
2338 noninlined_virt_indir_cnt, indirect_cnt, indirect_poly_cnt);
2339 fprintf (dump_file,
2340 "Removed speculations %"PRId64 "\n",
2341 spec_rem);
2343 dump_overall_stats ();
2344 fprintf (dump_file, "\nWhy inlining failed?\n");
2345 for (i = 0; i < CIF_N_REASONS; i++)
2346 if (reason[i][2])
2347 fprintf (dump_file, "%-50s: %8i calls, %8i freq, %"PRId64" count\n",
2348 cgraph_inline_failed_string ((cgraph_inline_failed_t) i),
2349 (int) reason[i][2], (int) reason[i][1], reason[i][0]);
2352 /* Decide on the inlining. We do so in the topological order to avoid
2353 expenses on updating data structures. */
2355 static unsigned int
2356 ipa_inline (void)
2358 struct cgraph_node *node;
2359 int nnodes;
2360 struct cgraph_node **order;
2361 int i;
2362 int cold;
2363 bool remove_functions = false;
2365 if (!optimize)
2366 return 0;
2368 cgraph_freq_base_rec = (sreal) 1 / (sreal) CGRAPH_FREQ_BASE;
2369 percent_rec = (sreal) 1 / (sreal) 100;
2371 order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
2373 if (in_lto_p && optimize)
2374 ipa_update_after_lto_read ();
2376 if (dump_file)
2377 dump_inline_summaries (dump_file);
2379 nnodes = ipa_reverse_postorder (order);
2381 FOR_EACH_FUNCTION (node)
2383 node->aux = 0;
2385 /* Recompute the default reasons for inlining because they may have
2386 changed during merging. */
2387 if (in_lto_p)
2389 for (cgraph_edge *e = node->callees; e; e = e->next_callee)
2391 gcc_assert (e->inline_failed);
2392 initialize_inline_failed (e);
2394 for (cgraph_edge *e = node->indirect_calls; e; e = e->next_callee)
2395 initialize_inline_failed (e);
2399 if (dump_file)
2400 fprintf (dump_file, "\nFlattening functions:\n");
2402 /* In the first pass handle functions to be flattened. Do this with
2403 a priority so none of our later choices will make this impossible. */
2404 for (i = nnodes - 1; i >= 0; i--)
2406 node = order[i];
2408 /* Handle nodes to be flattened.
2409 Ideally when processing callees we stop inlining at the
2410 entry of cycles, possibly cloning that entry point and
2411 try to flatten itself turning it into a self-recursive
2412 function. */
2413 if (lookup_attribute ("flatten",
2414 DECL_ATTRIBUTES (node->decl)) != NULL)
2416 if (dump_file)
2417 fprintf (dump_file,
2418 "Flattening %s\n", node->name ());
2419 flatten_function (node, false);
2422 if (dump_file)
2423 dump_overall_stats ();
2425 inline_small_functions ();
2427 gcc_assert (symtab->state == IPA_SSA);
2428 symtab->state = IPA_SSA_AFTER_INLINING;
2429 /* Do first after-inlining removal. We want to remove all "stale" extern
2430 inline functions and virtual functions so we really know what is called
2431 once. */
2432 symtab->remove_unreachable_nodes (dump_file);
2433 free (order);
2435 /* Inline functions with a property that after inlining into all callers the
2436 code size will shrink because the out-of-line copy is eliminated.
2437 We do this regardless on the callee size as long as function growth limits
2438 are met. */
2439 if (dump_file)
2440 fprintf (dump_file,
2441 "\nDeciding on functions to be inlined into all callers and "
2442 "removing useless speculations:\n");
2444 /* Inlining one function called once has good chance of preventing
2445 inlining other function into the same callee. Ideally we should
2446 work in priority order, but probably inlining hot functions first
2447 is good cut without the extra pain of maintaining the queue.
2449 ??? this is not really fitting the bill perfectly: inlining function
2450 into callee often leads to better optimization of callee due to
2451 increased context for optimization.
2452 For example if main() function calls a function that outputs help
2453 and then function that does the main optmization, we should inline
2454 the second with priority even if both calls are cold by themselves.
2456 We probably want to implement new predicate replacing our use of
2457 maybe_hot_edge interpreted as maybe_hot_edge || callee is known
2458 to be hot. */
2459 for (cold = 0; cold <= 1; cold ++)
2461 FOR_EACH_DEFINED_FUNCTION (node)
2463 struct cgraph_edge *edge, *next;
2464 bool update=false;
2466 for (edge = node->callees; edge; edge = next)
2468 next = edge->next_callee;
2469 if (edge->speculative && !speculation_useful_p (edge, false))
2471 edge->resolve_speculation ();
2472 spec_rem += edge->count;
2473 update = true;
2474 remove_functions = true;
2477 if (update)
2479 struct cgraph_node *where = node->global.inlined_to
2480 ? node->global.inlined_to : node;
2481 reset_edge_caches (where);
2482 inline_update_overall_summary (where);
2484 if (want_inline_function_to_all_callers_p (node, cold))
2486 int num_calls = 0;
2487 node->call_for_symbol_and_aliases (sum_callers, &num_calls,
2488 true);
2489 while (node->call_for_symbol_and_aliases
2490 (inline_to_all_callers, &num_calls, true))
2492 remove_functions = true;
2497 /* Free ipa-prop structures if they are no longer needed. */
2498 if (optimize)
2499 ipa_free_all_structures_after_iinln ();
2501 if (dump_file)
2503 fprintf (dump_file,
2504 "\nInlined %i calls, eliminated %i functions\n\n",
2505 ncalls_inlined, nfunctions_inlined);
2506 dump_inline_stats ();
2509 if (dump_file)
2510 dump_inline_summaries (dump_file);
2511 /* In WPA we use inline summaries for partitioning process. */
2512 if (!flag_wpa)
2513 inline_free_summary ();
2514 return remove_functions ? TODO_remove_functions : 0;
2517 /* Inline always-inline function calls in NODE. */
2519 static bool
2520 inline_always_inline_functions (struct cgraph_node *node)
2522 struct cgraph_edge *e;
2523 bool inlined = false;
2525 for (e = node->callees; e; e = e->next_callee)
2527 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2528 if (!DECL_DISREGARD_INLINE_LIMITS (callee->decl))
2529 continue;
2531 if (e->recursive_p ())
2533 if (dump_file)
2534 fprintf (dump_file, " Not inlining recursive call to %s.\n",
2535 e->callee->name ());
2536 e->inline_failed = CIF_RECURSIVE_INLINING;
2537 continue;
2540 if (!can_early_inline_edge_p (e))
2542 /* Set inlined to true if the callee is marked "always_inline" but
2543 is not inlinable. This will allow flagging an error later in
2544 expand_call_inline in tree-inline.c. */
2545 if (lookup_attribute ("always_inline",
2546 DECL_ATTRIBUTES (callee->decl)) != NULL)
2547 inlined = true;
2548 continue;
2551 if (dump_file)
2552 fprintf (dump_file, " Inlining %s into %s (always_inline).\n",
2553 xstrdup_for_dump (e->callee->name ()),
2554 xstrdup_for_dump (e->caller->name ()));
2555 inline_call (e, true, NULL, NULL, false);
2556 inlined = true;
2558 if (inlined)
2559 inline_update_overall_summary (node);
2561 return inlined;
2564 /* Decide on the inlining. We do so in the topological order to avoid
2565 expenses on updating data structures. */
2567 static bool
2568 early_inline_small_functions (struct cgraph_node *node)
2570 struct cgraph_edge *e;
2571 bool inlined = false;
2573 for (e = node->callees; e; e = e->next_callee)
2575 struct cgraph_node *callee = e->callee->ultimate_alias_target ();
2576 if (!inline_summaries->get (callee)->inlinable
2577 || !e->inline_failed)
2578 continue;
2580 /* Do not consider functions not declared inline. */
2581 if (!DECL_DECLARED_INLINE_P (callee->decl)
2582 && !opt_for_fn (node->decl, flag_inline_small_functions)
2583 && !opt_for_fn (node->decl, flag_inline_functions))
2584 continue;
2586 if (dump_file)
2587 fprintf (dump_file, "Considering inline candidate %s.\n",
2588 callee->name ());
2590 if (!can_early_inline_edge_p (e))
2591 continue;
2593 if (e->recursive_p ())
2595 if (dump_file)
2596 fprintf (dump_file, " Not inlining: recursive call.\n");
2597 continue;
2600 if (!want_early_inline_function_p (e))
2601 continue;
2603 if (dump_file)
2604 fprintf (dump_file, " Inlining %s into %s.\n",
2605 xstrdup_for_dump (callee->name ()),
2606 xstrdup_for_dump (e->caller->name ()));
2607 inline_call (e, true, NULL, NULL, true);
2608 inlined = true;
2611 return inlined;
2614 unsigned int
2615 early_inliner (function *fun)
2617 struct cgraph_node *node = cgraph_node::get (current_function_decl);
2618 struct cgraph_edge *edge;
2619 unsigned int todo = 0;
2620 int iterations = 0;
2621 bool inlined = false;
2623 if (seen_error ())
2624 return 0;
2626 /* Do nothing if datastructures for ipa-inliner are already computed. This
2627 happens when some pass decides to construct new function and
2628 cgraph_add_new_function calls lowering passes and early optimization on
2629 it. This may confuse ourself when early inliner decide to inline call to
2630 function clone, because function clones don't have parameter list in
2631 ipa-prop matching their signature. */
2632 if (ipa_node_params_sum)
2633 return 0;
2635 #ifdef ENABLE_CHECKING
2636 node->verify ();
2637 #endif
2638 node->remove_all_references ();
2640 /* Rebuild this reference because it dosn't depend on
2641 function's body and it's required to pass cgraph_node
2642 verification. */
2643 if (node->instrumented_version
2644 && !node->instrumentation_clone)
2645 node->create_reference (node->instrumented_version, IPA_REF_CHKP, NULL);
2647 /* Even when not optimizing or not inlining inline always-inline
2648 functions. */
2649 inlined = inline_always_inline_functions (node);
2651 if (!optimize
2652 || flag_no_inline
2653 || !flag_early_inlining
2654 /* Never inline regular functions into always-inline functions
2655 during incremental inlining. This sucks as functions calling
2656 always inline functions will get less optimized, but at the
2657 same time inlining of functions calling always inline
2658 function into an always inline function might introduce
2659 cycles of edges to be always inlined in the callgraph.
2661 We might want to be smarter and just avoid this type of inlining. */
2662 || (DECL_DISREGARD_INLINE_LIMITS (node->decl)
2663 && lookup_attribute ("always_inline",
2664 DECL_ATTRIBUTES (node->decl))))
2666 else if (lookup_attribute ("flatten",
2667 DECL_ATTRIBUTES (node->decl)) != NULL)
2669 /* When the function is marked to be flattened, recursively inline
2670 all calls in it. */
2671 if (dump_file)
2672 fprintf (dump_file,
2673 "Flattening %s\n", node->name ());
2674 flatten_function (node, true);
2675 inlined = true;
2677 else
2679 /* If some always_inline functions was inlined, apply the changes.
2680 This way we will not account always inline into growth limits and
2681 moreover we will inline calls from always inlines that we skipped
2682 previously becuase of conditional above. */
2683 if (inlined)
2685 timevar_push (TV_INTEGRATION);
2686 todo |= optimize_inline_calls (current_function_decl);
2687 /* optimize_inline_calls call above might have introduced new
2688 statements that don't have inline parameters computed. */
2689 for (edge = node->callees; edge; edge = edge->next_callee)
2691 if (inline_edge_summary_vec.length () > (unsigned) edge->uid)
2693 struct inline_edge_summary *es = inline_edge_summary (edge);
2694 es->call_stmt_size
2695 = estimate_num_insns (edge->call_stmt, &eni_size_weights);
2696 es->call_stmt_time
2697 = estimate_num_insns (edge->call_stmt, &eni_time_weights);
2700 inline_update_overall_summary (node);
2701 inlined = false;
2702 timevar_pop (TV_INTEGRATION);
2704 /* We iterate incremental inlining to get trivial cases of indirect
2705 inlining. */
2706 while (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS)
2707 && early_inline_small_functions (node))
2709 timevar_push (TV_INTEGRATION);
2710 todo |= optimize_inline_calls (current_function_decl);
2712 /* Technically we ought to recompute inline parameters so the new
2713 iteration of early inliner works as expected. We however have
2714 values approximately right and thus we only need to update edge
2715 info that might be cleared out for newly discovered edges. */
2716 for (edge = node->callees; edge; edge = edge->next_callee)
2718 /* We have no summary for new bound store calls yet. */
2719 if (inline_edge_summary_vec.length () > (unsigned)edge->uid)
2721 struct inline_edge_summary *es = inline_edge_summary (edge);
2722 es->call_stmt_size
2723 = estimate_num_insns (edge->call_stmt, &eni_size_weights);
2724 es->call_stmt_time
2725 = estimate_num_insns (edge->call_stmt, &eni_time_weights);
2727 if (edge->callee->decl
2728 && !gimple_check_call_matching_types (
2729 edge->call_stmt, edge->callee->decl, false))
2730 edge->call_stmt_cannot_inline_p = true;
2732 if (iterations < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS) - 1)
2733 inline_update_overall_summary (node);
2734 timevar_pop (TV_INTEGRATION);
2735 iterations++;
2736 inlined = false;
2738 if (dump_file)
2739 fprintf (dump_file, "Iterations: %i\n", iterations);
2742 if (inlined)
2744 timevar_push (TV_INTEGRATION);
2745 todo |= optimize_inline_calls (current_function_decl);
2746 timevar_pop (TV_INTEGRATION);
2749 fun->always_inline_functions_inlined = true;
2751 return todo;
2754 /* Do inlining of small functions. Doing so early helps profiling and other
2755 passes to be somewhat more effective and avoids some code duplication in
2756 later real inlining pass for testcases with very many function calls. */
2758 namespace {
2760 const pass_data pass_data_early_inline =
2762 GIMPLE_PASS, /* type */
2763 "einline", /* name */
2764 OPTGROUP_INLINE, /* optinfo_flags */
2765 TV_EARLY_INLINING, /* tv_id */
2766 PROP_ssa, /* properties_required */
2767 0, /* properties_provided */
2768 0, /* properties_destroyed */
2769 0, /* todo_flags_start */
2770 0, /* todo_flags_finish */
2773 class pass_early_inline : public gimple_opt_pass
2775 public:
2776 pass_early_inline (gcc::context *ctxt)
2777 : gimple_opt_pass (pass_data_early_inline, ctxt)
2780 /* opt_pass methods: */
2781 virtual unsigned int execute (function *);
2783 }; // class pass_early_inline
2785 unsigned int
2786 pass_early_inline::execute (function *fun)
2788 return early_inliner (fun);
2791 } // anon namespace
2793 gimple_opt_pass *
2794 make_pass_early_inline (gcc::context *ctxt)
2796 return new pass_early_inline (ctxt);
2799 namespace {
2801 const pass_data pass_data_ipa_inline =
2803 IPA_PASS, /* type */
2804 "inline", /* name */
2805 OPTGROUP_INLINE, /* optinfo_flags */
2806 TV_IPA_INLINING, /* tv_id */
2807 0, /* properties_required */
2808 0, /* properties_provided */
2809 0, /* properties_destroyed */
2810 0, /* todo_flags_start */
2811 ( TODO_dump_symtab ), /* todo_flags_finish */
2814 class pass_ipa_inline : public ipa_opt_pass_d
2816 public:
2817 pass_ipa_inline (gcc::context *ctxt)
2818 : ipa_opt_pass_d (pass_data_ipa_inline, ctxt,
2819 inline_generate_summary, /* generate_summary */
2820 inline_write_summary, /* write_summary */
2821 inline_read_summary, /* read_summary */
2822 NULL, /* write_optimization_summary */
2823 NULL, /* read_optimization_summary */
2824 NULL, /* stmt_fixup */
2825 0, /* function_transform_todo_flags_start */
2826 inline_transform, /* function_transform */
2827 NULL) /* variable_transform */
2830 /* opt_pass methods: */
2831 virtual unsigned int execute (function *) { return ipa_inline (); }
2833 }; // class pass_ipa_inline
2835 } // anon namespace
2837 ipa_opt_pass_d *
2838 make_pass_ipa_inline (gcc::context *ctxt)
2840 return new pass_ipa_inline (ctxt);