2015-10-18 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / ipa-cp.c
blobd9d81f1e0967fd6cbe29fe129b33802c26fd6eef
1 /* Interprocedural constant propagation
2 Copyright (C) 2005-2015 Free Software Foundation, Inc.
4 Contributed by Razya Ladelsky <RAZYA@il.ibm.com> and Martin Jambor
5 <mjambor@suse.cz>
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 /* Interprocedural constant propagation (IPA-CP).
25 The goal of this transformation is to
27 1) discover functions which are always invoked with some arguments with the
28 same known constant values and modify the functions so that the
29 subsequent optimizations can take advantage of the knowledge, and
31 2) partial specialization - create specialized versions of functions
32 transformed in this way if some parameters are known constants only in
33 certain contexts but the estimated tradeoff between speedup and cost size
34 is deemed good.
36 The algorithm also propagates types and attempts to perform type based
37 devirtualization. Types are propagated much like constants.
39 The algorithm basically consists of three stages. In the first, functions
40 are analyzed one at a time and jump functions are constructed for all known
41 call-sites. In the second phase, the pass propagates information from the
42 jump functions across the call to reveal what values are available at what
43 call sites, performs estimations of effects of known values on functions and
44 their callees, and finally decides what specialized extra versions should be
45 created. In the third, the special versions materialize and appropriate
46 calls are redirected.
48 The algorithm used is to a certain extent based on "Interprocedural Constant
49 Propagation", by David Callahan, Keith D Cooper, Ken Kennedy, Linda Torczon,
50 Comp86, pg 152-161 and "A Methodology for Procedure Cloning" by Keith D
51 Cooper, Mary W. Hall, and Ken Kennedy.
54 First stage - intraprocedural analysis
55 =======================================
57 This phase computes jump_function and modification flags.
59 A jump function for a call-site represents the values passed as an actual
60 arguments of a given call-site. In principle, there are three types of
61 values:
63 Pass through - the caller's formal parameter is passed as an actual
64 argument, plus an operation on it can be performed.
65 Constant - a constant is passed as an actual argument.
66 Unknown - neither of the above.
68 All jump function types are described in detail in ipa-prop.h, together with
69 the data structures that represent them and methods of accessing them.
71 ipcp_generate_summary() is the main function of the first stage.
73 Second stage - interprocedural analysis
74 ========================================
76 This stage is itself divided into two phases. In the first, we propagate
77 known values over the call graph, in the second, we make cloning decisions.
78 It uses a different algorithm than the original Callahan's paper.
80 First, we traverse the functions topologically from callers to callees and,
81 for each strongly connected component (SCC), we propagate constants
82 according to previously computed jump functions. We also record what known
83 values depend on other known values and estimate local effects. Finally, we
84 propagate cumulative information about these effects from dependent values
85 to those on which they depend.
87 Second, we again traverse the call graph in the same topological order and
88 make clones for functions which we know are called with the same values in
89 all contexts and decide about extra specialized clones of functions just for
90 some contexts - these decisions are based on both local estimates and
91 cumulative estimates propagated from callees.
93 ipcp_propagate_stage() and ipcp_decision_stage() together constitute the
94 third stage.
96 Third phase - materialization of clones, call statement updates.
97 ============================================
99 This stage is currently performed by call graph code (mainly in cgraphunit.c
100 and tree-inline.c) according to instructions inserted to the call graph by
101 the second stage. */
103 #include "config.h"
104 #include "system.h"
105 #include "coretypes.h"
106 #include "alias.h"
107 #include "tree.h"
108 #include "options.h"
109 #include "fold-const.h"
110 #include "gimple-fold.h"
111 #include "gimple-expr.h"
112 #include "target.h"
113 #include "backend.h"
114 #include "predict.h"
115 #include "hard-reg-set.h"
116 #include "cgraph.h"
117 #include "alloc-pool.h"
118 #include "symbol-summary.h"
119 #include "ipa-prop.h"
120 #include "tree-pass.h"
121 #include "flags.h"
122 #include "diagnostic.h"
123 #include "tree-pretty-print.h"
124 #include "tree-inline.h"
125 #include "params.h"
126 #include "ipa-inline.h"
127 #include "ipa-utils.h"
129 template <typename valtype> class ipcp_value;
131 /* Describes a particular source for an IPA-CP value. */
133 template <typename valtype>
134 class ipcp_value_source
136 public:
137 /* Aggregate offset of the source, negative if the source is scalar value of
138 the argument itself. */
139 HOST_WIDE_INT offset;
140 /* The incoming edge that brought the value. */
141 cgraph_edge *cs;
142 /* If the jump function that resulted into his value was a pass-through or an
143 ancestor, this is the ipcp_value of the caller from which the described
144 value has been derived. Otherwise it is NULL. */
145 ipcp_value<valtype> *val;
146 /* Next pointer in a linked list of sources of a value. */
147 ipcp_value_source *next;
148 /* If the jump function that resulted into his value was a pass-through or an
149 ancestor, this is the index of the parameter of the caller the jump
150 function references. */
151 int index;
154 /* Common ancestor for all ipcp_value instantiations. */
156 class ipcp_value_base
158 public:
159 /* Time benefit and size cost that specializing the function for this value
160 would bring about in this function alone. */
161 int local_time_benefit, local_size_cost;
162 /* Time benefit and size cost that specializing the function for this value
163 can bring about in it's callees (transitively). */
164 int prop_time_benefit, prop_size_cost;
167 /* Describes one particular value stored in struct ipcp_lattice. */
169 template <typename valtype>
170 class ipcp_value : public ipcp_value_base
172 public:
173 /* The actual value for the given parameter. */
174 valtype value;
175 /* The list of sources from which this value originates. */
176 ipcp_value_source <valtype> *sources;
177 /* Next pointers in a linked list of all values in a lattice. */
178 ipcp_value *next;
179 /* Next pointers in a linked list of values in a strongly connected component
180 of values. */
181 ipcp_value *scc_next;
182 /* Next pointers in a linked list of SCCs of values sorted topologically
183 according their sources. */
184 ipcp_value *topo_next;
185 /* A specialized node created for this value, NULL if none has been (so far)
186 created. */
187 cgraph_node *spec_node;
188 /* Depth first search number and low link for topological sorting of
189 values. */
190 int dfs, low_link;
191 /* True if this valye is currently on the topo-sort stack. */
192 bool on_stack;
194 void add_source (cgraph_edge *cs, ipcp_value *src_val, int src_idx,
195 HOST_WIDE_INT offset);
198 /* Lattice describing potential values of a formal parameter of a function, or
199 a part of an aggreagate. TOP is represented by a lattice with zero values
200 and with contains_variable and bottom flags cleared. BOTTOM is represented
201 by a lattice with the bottom flag set. In that case, values and
202 contains_variable flag should be disregarded. */
204 template <typename valtype>
205 class ipcp_lattice
207 public:
208 /* The list of known values and types in this lattice. Note that values are
209 not deallocated if a lattice is set to bottom because there may be value
210 sources referencing them. */
211 ipcp_value<valtype> *values;
212 /* Number of known values and types in this lattice. */
213 int values_count;
214 /* The lattice contains a variable component (in addition to values). */
215 bool contains_variable;
216 /* The value of the lattice is bottom (i.e. variable and unusable for any
217 propagation). */
218 bool bottom;
220 inline bool is_single_const ();
221 inline bool set_to_bottom ();
222 inline bool set_contains_variable ();
223 bool add_value (valtype newval, cgraph_edge *cs,
224 ipcp_value<valtype> *src_val = NULL,
225 int src_idx = 0, HOST_WIDE_INT offset = -1);
226 void print (FILE * f, bool dump_sources, bool dump_benefits);
229 /* Lattice of tree values with an offset to describe a part of an
230 aggregate. */
232 class ipcp_agg_lattice : public ipcp_lattice<tree>
234 public:
235 /* Offset that is being described by this lattice. */
236 HOST_WIDE_INT offset;
237 /* Size so that we don't have to re-compute it every time we traverse the
238 list. Must correspond to TYPE_SIZE of all lat values. */
239 HOST_WIDE_INT size;
240 /* Next element of the linked list. */
241 struct ipcp_agg_lattice *next;
244 /* Lattice of pointer alignment. Unlike the previous types of lattices, this
245 one is only capable of holding one value. */
247 class ipcp_alignment_lattice
249 public:
250 /* If bottom and top are both false, these two fields hold values as given by
251 ptr_info_def and get_pointer_alignment_1. */
252 unsigned align;
253 unsigned misalign;
255 inline bool bottom_p () const;
256 inline bool top_p () const;
257 inline bool set_to_bottom ();
258 bool meet_with (unsigned new_align, unsigned new_misalign);
259 bool meet_with (const ipcp_alignment_lattice &other, HOST_WIDE_INT offset);
260 void print (FILE * f);
261 private:
262 /* If set, this lattice is bottom and all other fields should be
263 disregarded. */
264 bool bottom;
265 /* If bottom and not_top are false, the lattice is TOP. If not_top is true,
266 the known alignment is stored in the fields align and misalign. The field
267 is negated so that memset to zero initializes the lattice to TOP
268 state. */
269 bool not_top;
271 bool meet_with_1 (unsigned new_align, unsigned new_misalign);
274 /* Structure containing lattices for a parameter itself and for pieces of
275 aggregates that are passed in the parameter or by a reference in a parameter
276 plus some other useful flags. */
278 class ipcp_param_lattices
280 public:
281 /* Lattice describing the value of the parameter itself. */
282 ipcp_lattice<tree> itself;
283 /* Lattice describing the polymorphic contexts of a parameter. */
284 ipcp_lattice<ipa_polymorphic_call_context> ctxlat;
285 /* Lattices describing aggregate parts. */
286 ipcp_agg_lattice *aggs;
287 /* Lattice describing known alignment. */
288 ipcp_alignment_lattice alignment;
289 /* Number of aggregate lattices */
290 int aggs_count;
291 /* True if aggregate data were passed by reference (as opposed to by
292 value). */
293 bool aggs_by_ref;
294 /* All aggregate lattices contain a variable component (in addition to
295 values). */
296 bool aggs_contain_variable;
297 /* The value of all aggregate lattices is bottom (i.e. variable and unusable
298 for any propagation). */
299 bool aggs_bottom;
301 /* There is a virtual call based on this parameter. */
302 bool virt_call;
305 /* Allocation pools for values and their sources in ipa-cp. */
307 object_allocator<ipcp_value<tree> > ipcp_cst_values_pool
308 ("IPA-CP constant values");
310 object_allocator<ipcp_value<ipa_polymorphic_call_context> >
311 ipcp_poly_ctx_values_pool ("IPA-CP polymorphic contexts");
313 object_allocator<ipcp_value_source<tree> > ipcp_sources_pool
314 ("IPA-CP value sources");
316 object_allocator<ipcp_agg_lattice> ipcp_agg_lattice_pool
317 ("IPA_CP aggregate lattices");
319 /* Maximal count found in program. */
321 static gcov_type max_count;
323 /* Original overall size of the program. */
325 static long overall_size, max_new_size;
327 /* Return the param lattices structure corresponding to the Ith formal
328 parameter of the function described by INFO. */
329 static inline struct ipcp_param_lattices *
330 ipa_get_parm_lattices (struct ipa_node_params *info, int i)
332 gcc_assert (i >= 0 && i < ipa_get_param_count (info));
333 gcc_checking_assert (!info->ipcp_orig_node);
334 gcc_checking_assert (info->lattices);
335 return &(info->lattices[i]);
338 /* Return the lattice corresponding to the scalar value of the Ith formal
339 parameter of the function described by INFO. */
340 static inline ipcp_lattice<tree> *
341 ipa_get_scalar_lat (struct ipa_node_params *info, int i)
343 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
344 return &plats->itself;
347 /* Return the lattice corresponding to the scalar value of the Ith formal
348 parameter of the function described by INFO. */
349 static inline ipcp_lattice<ipa_polymorphic_call_context> *
350 ipa_get_poly_ctx_lat (struct ipa_node_params *info, int i)
352 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
353 return &plats->ctxlat;
356 /* Return whether LAT is a lattice with a single constant and without an
357 undefined value. */
359 template <typename valtype>
360 inline bool
361 ipcp_lattice<valtype>::is_single_const ()
363 if (bottom || contains_variable || values_count != 1)
364 return false;
365 else
366 return true;
369 /* Print V which is extracted from a value in a lattice to F. */
371 static void
372 print_ipcp_constant_value (FILE * f, tree v)
374 if (TREE_CODE (v) == ADDR_EXPR
375 && TREE_CODE (TREE_OPERAND (v, 0)) == CONST_DECL)
377 fprintf (f, "& ");
378 print_generic_expr (f, DECL_INITIAL (TREE_OPERAND (v, 0)), 0);
380 else
381 print_generic_expr (f, v, 0);
384 /* Print V which is extracted from a value in a lattice to F. */
386 static void
387 print_ipcp_constant_value (FILE * f, ipa_polymorphic_call_context v)
389 v.dump(f, false);
392 /* Print a lattice LAT to F. */
394 template <typename valtype>
395 void
396 ipcp_lattice<valtype>::print (FILE * f, bool dump_sources, bool dump_benefits)
398 ipcp_value<valtype> *val;
399 bool prev = false;
401 if (bottom)
403 fprintf (f, "BOTTOM\n");
404 return;
407 if (!values_count && !contains_variable)
409 fprintf (f, "TOP\n");
410 return;
413 if (contains_variable)
415 fprintf (f, "VARIABLE");
416 prev = true;
417 if (dump_benefits)
418 fprintf (f, "\n");
421 for (val = values; val; val = val->next)
423 if (dump_benefits && prev)
424 fprintf (f, " ");
425 else if (!dump_benefits && prev)
426 fprintf (f, ", ");
427 else
428 prev = true;
430 print_ipcp_constant_value (f, val->value);
432 if (dump_sources)
434 ipcp_value_source<valtype> *s;
436 fprintf (f, " [from:");
437 for (s = val->sources; s; s = s->next)
438 fprintf (f, " %i(%i)", s->cs->caller->order,
439 s->cs->frequency);
440 fprintf (f, "]");
443 if (dump_benefits)
444 fprintf (f, " [loc_time: %i, loc_size: %i, "
445 "prop_time: %i, prop_size: %i]\n",
446 val->local_time_benefit, val->local_size_cost,
447 val->prop_time_benefit, val->prop_size_cost);
449 if (!dump_benefits)
450 fprintf (f, "\n");
453 /* Print alignment lattice to F. */
455 void
456 ipcp_alignment_lattice::print (FILE * f)
458 if (top_p ())
459 fprintf (f, " Alignment unknown (TOP)\n");
460 else if (bottom_p ())
461 fprintf (f, " Alignment unusable (BOTTOM)\n");
462 else
463 fprintf (f, " Alignment %u, misalignment %u\n", align, misalign);
466 /* Print all ipcp_lattices of all functions to F. */
468 static void
469 print_all_lattices (FILE * f, bool dump_sources, bool dump_benefits)
471 struct cgraph_node *node;
472 int i, count;
474 fprintf (f, "\nLattices:\n");
475 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
477 struct ipa_node_params *info;
479 info = IPA_NODE_REF (node);
480 fprintf (f, " Node: %s/%i:\n", node->name (),
481 node->order);
482 count = ipa_get_param_count (info);
483 for (i = 0; i < count; i++)
485 struct ipcp_agg_lattice *aglat;
486 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
487 fprintf (f, " param [%d]: ", i);
488 plats->itself.print (f, dump_sources, dump_benefits);
489 fprintf (f, " ctxs: ");
490 plats->ctxlat.print (f, dump_sources, dump_benefits);
491 plats->alignment.print (f);
492 if (plats->virt_call)
493 fprintf (f, " virt_call flag set\n");
495 if (plats->aggs_bottom)
497 fprintf (f, " AGGS BOTTOM\n");
498 continue;
500 if (plats->aggs_contain_variable)
501 fprintf (f, " AGGS VARIABLE\n");
502 for (aglat = plats->aggs; aglat; aglat = aglat->next)
504 fprintf (f, " %soffset " HOST_WIDE_INT_PRINT_DEC ": ",
505 plats->aggs_by_ref ? "ref " : "", aglat->offset);
506 aglat->print (f, dump_sources, dump_benefits);
512 /* Determine whether it is at all technically possible to create clones of NODE
513 and store this information in the ipa_node_params structure associated
514 with NODE. */
516 static void
517 determine_versionability (struct cgraph_node *node)
519 const char *reason = NULL;
521 /* There are a number of generic reasons functions cannot be versioned. We
522 also cannot remove parameters if there are type attributes such as fnspec
523 present. */
524 if (node->alias || node->thunk.thunk_p)
525 reason = "alias or thunk";
526 else if (!node->local.versionable)
527 reason = "not a tree_versionable_function";
528 else if (node->get_availability () <= AVAIL_INTERPOSABLE)
529 reason = "insufficient body availability";
530 else if (!opt_for_fn (node->decl, optimize)
531 || !opt_for_fn (node->decl, flag_ipa_cp))
532 reason = "non-optimized function";
533 else if (lookup_attribute ("omp declare simd", DECL_ATTRIBUTES (node->decl)))
535 /* Ideally we should clone the SIMD clones themselves and create
536 vector copies of them, so IPA-cp and SIMD clones can happily
537 coexist, but that may not be worth the effort. */
538 reason = "function has SIMD clones";
540 /* Don't clone decls local to a comdat group; it breaks and for C++
541 decloned constructors, inlining is always better anyway. */
542 else if (node->comdat_local_p ())
543 reason = "comdat-local function";
545 if (reason && dump_file && !node->alias && !node->thunk.thunk_p)
546 fprintf (dump_file, "Function %s/%i is not versionable, reason: %s.\n",
547 node->name (), node->order, reason);
549 node->local.versionable = (reason == NULL);
552 /* Return true if it is at all technically possible to create clones of a
553 NODE. */
555 static bool
556 ipcp_versionable_function_p (struct cgraph_node *node)
558 return node->local.versionable;
561 /* Structure holding accumulated information about callers of a node. */
563 struct caller_statistics
565 gcov_type count_sum;
566 int n_calls, n_hot_calls, freq_sum;
569 /* Initialize fields of STAT to zeroes. */
571 static inline void
572 init_caller_stats (struct caller_statistics *stats)
574 stats->count_sum = 0;
575 stats->n_calls = 0;
576 stats->n_hot_calls = 0;
577 stats->freq_sum = 0;
580 /* Worker callback of cgraph_for_node_and_aliases accumulating statistics of
581 non-thunk incoming edges to NODE. */
583 static bool
584 gather_caller_stats (struct cgraph_node *node, void *data)
586 struct caller_statistics *stats = (struct caller_statistics *) data;
587 struct cgraph_edge *cs;
589 for (cs = node->callers; cs; cs = cs->next_caller)
590 if (!cs->caller->thunk.thunk_p)
592 stats->count_sum += cs->count;
593 stats->freq_sum += cs->frequency;
594 stats->n_calls++;
595 if (cs->maybe_hot_p ())
596 stats->n_hot_calls ++;
598 return false;
602 /* Return true if this NODE is viable candidate for cloning. */
604 static bool
605 ipcp_cloning_candidate_p (struct cgraph_node *node)
607 struct caller_statistics stats;
609 gcc_checking_assert (node->has_gimple_body_p ());
611 if (!opt_for_fn (node->decl, flag_ipa_cp_clone))
613 if (dump_file)
614 fprintf (dump_file, "Not considering %s for cloning; "
615 "-fipa-cp-clone disabled.\n",
616 node->name ());
617 return false;
620 if (!optimize_function_for_speed_p (DECL_STRUCT_FUNCTION (node->decl)))
622 if (dump_file)
623 fprintf (dump_file, "Not considering %s for cloning; "
624 "optimizing it for size.\n",
625 node->name ());
626 return false;
629 init_caller_stats (&stats);
630 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats, false);
632 if (inline_summaries->get (node)->self_size < stats.n_calls)
634 if (dump_file)
635 fprintf (dump_file, "Considering %s for cloning; code might shrink.\n",
636 node->name ());
637 return true;
640 /* When profile is available and function is hot, propagate into it even if
641 calls seems cold; constant propagation can improve function's speed
642 significantly. */
643 if (max_count)
645 if (stats.count_sum > node->count * 90 / 100)
647 if (dump_file)
648 fprintf (dump_file, "Considering %s for cloning; "
649 "usually called directly.\n",
650 node->name ());
651 return true;
654 if (!stats.n_hot_calls)
656 if (dump_file)
657 fprintf (dump_file, "Not considering %s for cloning; no hot calls.\n",
658 node->name ());
659 return false;
661 if (dump_file)
662 fprintf (dump_file, "Considering %s for cloning.\n",
663 node->name ());
664 return true;
667 template <typename valtype>
668 class value_topo_info
670 public:
671 /* Head of the linked list of topologically sorted values. */
672 ipcp_value<valtype> *values_topo;
673 /* Stack for creating SCCs, represented by a linked list too. */
674 ipcp_value<valtype> *stack;
675 /* Counter driving the algorithm in add_val_to_toposort. */
676 int dfs_counter;
678 value_topo_info () : values_topo (NULL), stack (NULL), dfs_counter (0)
680 void add_val (ipcp_value<valtype> *cur_val);
681 void propagate_effects ();
684 /* Arrays representing a topological ordering of call graph nodes and a stack
685 of nodes used during constant propagation and also data required to perform
686 topological sort of values and propagation of benefits in the determined
687 order. */
689 class ipa_topo_info
691 public:
692 /* Array with obtained topological order of cgraph nodes. */
693 struct cgraph_node **order;
694 /* Stack of cgraph nodes used during propagation within SCC until all values
695 in the SCC stabilize. */
696 struct cgraph_node **stack;
697 int nnodes, stack_top;
699 value_topo_info<tree> constants;
700 value_topo_info<ipa_polymorphic_call_context> contexts;
702 ipa_topo_info () : order(NULL), stack(NULL), nnodes(0), stack_top(0),
703 constants ()
707 /* Allocate the arrays in TOPO and topologically sort the nodes into order. */
709 static void
710 build_toporder_info (struct ipa_topo_info *topo)
712 topo->order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
713 topo->stack = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
715 gcc_checking_assert (topo->stack_top == 0);
716 topo->nnodes = ipa_reduced_postorder (topo->order, true, true, NULL);
719 /* Free information about strongly connected components and the arrays in
720 TOPO. */
722 static void
723 free_toporder_info (struct ipa_topo_info *topo)
725 ipa_free_postorder_info ();
726 free (topo->order);
727 free (topo->stack);
730 /* Add NODE to the stack in TOPO, unless it is already there. */
732 static inline void
733 push_node_to_stack (struct ipa_topo_info *topo, struct cgraph_node *node)
735 struct ipa_node_params *info = IPA_NODE_REF (node);
736 if (info->node_enqueued)
737 return;
738 info->node_enqueued = 1;
739 topo->stack[topo->stack_top++] = node;
742 /* Pop a node from the stack in TOPO and return it or return NULL if the stack
743 is empty. */
745 static struct cgraph_node *
746 pop_node_from_stack (struct ipa_topo_info *topo)
748 if (topo->stack_top)
750 struct cgraph_node *node;
751 topo->stack_top--;
752 node = topo->stack[topo->stack_top];
753 IPA_NODE_REF (node)->node_enqueued = 0;
754 return node;
756 else
757 return NULL;
760 /* Set lattice LAT to bottom and return true if it previously was not set as
761 such. */
763 template <typename valtype>
764 inline bool
765 ipcp_lattice<valtype>::set_to_bottom ()
767 bool ret = !bottom;
768 bottom = true;
769 return ret;
772 /* Mark lattice as containing an unknown value and return true if it previously
773 was not marked as such. */
775 template <typename valtype>
776 inline bool
777 ipcp_lattice<valtype>::set_contains_variable ()
779 bool ret = !contains_variable;
780 contains_variable = true;
781 return ret;
784 /* Set all aggegate lattices in PLATS to bottom and return true if they were
785 not previously set as such. */
787 static inline bool
788 set_agg_lats_to_bottom (struct ipcp_param_lattices *plats)
790 bool ret = !plats->aggs_bottom;
791 plats->aggs_bottom = true;
792 return ret;
795 /* Mark all aggegate lattices in PLATS as containing an unknown value and
796 return true if they were not previously marked as such. */
798 static inline bool
799 set_agg_lats_contain_variable (struct ipcp_param_lattices *plats)
801 bool ret = !plats->aggs_contain_variable;
802 plats->aggs_contain_variable = true;
803 return ret;
806 /* Return true if alignment information in the lattice is yet unknown. */
808 bool
809 ipcp_alignment_lattice::top_p () const
811 return !bottom && !not_top;
814 /* Return true if alignment information in the lattice is known to be
815 unusable. */
817 bool
818 ipcp_alignment_lattice::bottom_p () const
820 return bottom;
823 /* Set alignment information in the lattice to bottom. Return true if it
824 previously was in a different state. */
826 bool
827 ipcp_alignment_lattice::set_to_bottom ()
829 if (bottom_p ())
830 return false;
831 bottom = true;
832 return true;
835 /* Meet the current value of the lattice with alignment described by NEW_ALIGN
836 and NEW_MISALIGN, assuming that we know the current value is neither TOP nor
837 BOTTOM. Return true if the value of lattice has changed. */
839 bool
840 ipcp_alignment_lattice::meet_with_1 (unsigned new_align, unsigned new_misalign)
842 gcc_checking_assert (new_align != 0);
843 if (align == new_align && misalign == new_misalign)
844 return false;
846 bool changed = false;
847 if (align > new_align)
849 align = new_align;
850 misalign = misalign % new_align;
851 changed = true;
853 if (misalign != (new_misalign % align))
855 int diff = abs ((int) misalign - (int) (new_misalign % align));
856 align = (unsigned) diff & -diff;
857 if (align)
858 misalign = misalign % align;
859 else
860 set_to_bottom ();
861 changed = true;
863 gcc_checking_assert (bottom_p () || align != 0);
864 return changed;
867 /* Meet the current value of the lattice with alignment described by NEW_ALIGN
868 and NEW_MISALIGN. Return true if the value of lattice has changed. */
870 bool
871 ipcp_alignment_lattice::meet_with (unsigned new_align, unsigned new_misalign)
873 gcc_assert (new_align != 0);
874 if (bottom_p ())
875 return false;
876 if (top_p ())
878 not_top = true;
879 align = new_align;
880 misalign = new_misalign;
881 return true;
883 return meet_with_1 (new_align, new_misalign);
886 /* Meet the current value of the lattice with OTHER, taking into account that
887 OFFSET has been added to the pointer value. Return true if the value of
888 lattice has changed. */
890 bool
891 ipcp_alignment_lattice::meet_with (const ipcp_alignment_lattice &other,
892 HOST_WIDE_INT offset)
894 if (other.bottom_p ())
895 return set_to_bottom ();
896 if (bottom_p () || other.top_p ())
897 return false;
899 unsigned adjusted_misalign = (other.misalign + offset) % other.align;
900 if (top_p ())
902 not_top = true;
903 align = other.align;
904 misalign = adjusted_misalign;
905 return true;
908 return meet_with_1 (other.align, adjusted_misalign);
911 /* Mark bot aggregate and scalar lattices as containing an unknown variable,
912 return true is any of them has not been marked as such so far. */
914 static inline bool
915 set_all_contains_variable (struct ipcp_param_lattices *plats)
917 bool ret;
918 ret = plats->itself.set_contains_variable ();
919 ret |= plats->ctxlat.set_contains_variable ();
920 ret |= set_agg_lats_contain_variable (plats);
921 ret |= plats->alignment.set_to_bottom ();
922 return ret;
925 /* Worker of call_for_symbol_thunks_and_aliases, increment the integer DATA
926 points to by the number of callers to NODE. */
928 static bool
929 count_callers (cgraph_node *node, void *data)
931 int *caller_count = (int *) data;
933 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
934 /* Local thunks can be handled transparently, but if the thunk can not
935 be optimized out, count it as a real use. */
936 if (!cs->caller->thunk.thunk_p || !cs->caller->local.local)
937 ++*caller_count;
938 return false;
941 /* Worker of call_for_symbol_thunks_and_aliases, it is supposed to be called on
942 the one caller of some other node. Set the caller's corresponding flag. */
944 static bool
945 set_single_call_flag (cgraph_node *node, void *)
947 cgraph_edge *cs = node->callers;
948 /* Local thunks can be handled transparently, skip them. */
949 while (cs && cs->caller->thunk.thunk_p && cs->caller->local.local)
950 cs = cs->next_caller;
951 if (cs)
953 IPA_NODE_REF (cs->caller)->node_calling_single_call = true;
954 return true;
956 return false;
959 /* Initialize ipcp_lattices. */
961 static void
962 initialize_node_lattices (struct cgraph_node *node)
964 struct ipa_node_params *info = IPA_NODE_REF (node);
965 struct cgraph_edge *ie;
966 bool disable = false, variable = false;
967 int i;
969 gcc_checking_assert (node->has_gimple_body_p ());
970 if (cgraph_local_p (node))
972 int caller_count = 0;
973 node->call_for_symbol_thunks_and_aliases (count_callers, &caller_count,
974 true);
975 gcc_checking_assert (caller_count > 0);
976 if (caller_count == 1)
977 node->call_for_symbol_thunks_and_aliases (set_single_call_flag,
978 NULL, true);
980 else
982 /* When cloning is allowed, we can assume that externally visible
983 functions are not called. We will compensate this by cloning
984 later. */
985 if (ipcp_versionable_function_p (node)
986 && ipcp_cloning_candidate_p (node))
987 variable = true;
988 else
989 disable = true;
992 if (disable || variable)
994 for (i = 0; i < ipa_get_param_count (info) ; i++)
996 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
997 if (disable)
999 plats->itself.set_to_bottom ();
1000 plats->ctxlat.set_to_bottom ();
1001 set_agg_lats_to_bottom (plats);
1002 plats->alignment.set_to_bottom ();
1004 else
1005 set_all_contains_variable (plats);
1007 if (dump_file && (dump_flags & TDF_DETAILS)
1008 && !node->alias && !node->thunk.thunk_p)
1009 fprintf (dump_file, "Marking all lattices of %s/%i as %s\n",
1010 node->name (), node->order,
1011 disable ? "BOTTOM" : "VARIABLE");
1014 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
1015 if (ie->indirect_info->polymorphic
1016 && ie->indirect_info->param_index >= 0)
1018 gcc_checking_assert (ie->indirect_info->param_index >= 0);
1019 ipa_get_parm_lattices (info,
1020 ie->indirect_info->param_index)->virt_call = 1;
1024 /* Return the result of a (possibly arithmetic) pass through jump function
1025 JFUNC on the constant value INPUT. Return NULL_TREE if that cannot be
1026 determined or be considered an interprocedural invariant. */
1028 static tree
1029 ipa_get_jf_pass_through_result (struct ipa_jump_func *jfunc, tree input)
1031 tree restype, res;
1033 gcc_checking_assert (is_gimple_ip_invariant (input));
1034 if (ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
1035 return input;
1037 if (TREE_CODE_CLASS (ipa_get_jf_pass_through_operation (jfunc))
1038 == tcc_comparison)
1039 restype = boolean_type_node;
1040 else
1041 restype = TREE_TYPE (input);
1042 res = fold_binary (ipa_get_jf_pass_through_operation (jfunc), restype,
1043 input, ipa_get_jf_pass_through_operand (jfunc));
1045 if (res && !is_gimple_ip_invariant (res))
1046 return NULL_TREE;
1048 return res;
1051 /* Return the result of an ancestor jump function JFUNC on the constant value
1052 INPUT. Return NULL_TREE if that cannot be determined. */
1054 static tree
1055 ipa_get_jf_ancestor_result (struct ipa_jump_func *jfunc, tree input)
1057 gcc_checking_assert (TREE_CODE (input) != TREE_BINFO);
1058 if (TREE_CODE (input) == ADDR_EXPR)
1060 tree t = TREE_OPERAND (input, 0);
1061 t = build_ref_for_offset (EXPR_LOCATION (t), t,
1062 ipa_get_jf_ancestor_offset (jfunc),
1063 ptr_type_node, NULL, false);
1064 return build_fold_addr_expr (t);
1066 else
1067 return NULL_TREE;
1070 /* Determine whether JFUNC evaluates to a single known constant value and if
1071 so, return it. Otherwise return NULL. INFO describes the caller node or
1072 the one it is inlined to, so that pass-through jump functions can be
1073 evaluated. */
1075 tree
1076 ipa_value_from_jfunc (struct ipa_node_params *info, struct ipa_jump_func *jfunc)
1078 if (jfunc->type == IPA_JF_CONST)
1079 return ipa_get_jf_constant (jfunc);
1080 else if (jfunc->type == IPA_JF_PASS_THROUGH
1081 || jfunc->type == IPA_JF_ANCESTOR)
1083 tree input;
1084 int idx;
1086 if (jfunc->type == IPA_JF_PASS_THROUGH)
1087 idx = ipa_get_jf_pass_through_formal_id (jfunc);
1088 else
1089 idx = ipa_get_jf_ancestor_formal_id (jfunc);
1091 if (info->ipcp_orig_node)
1092 input = info->known_csts[idx];
1093 else
1095 ipcp_lattice<tree> *lat;
1097 if (!info->lattices
1098 || idx >= ipa_get_param_count (info))
1099 return NULL_TREE;
1100 lat = ipa_get_scalar_lat (info, idx);
1101 if (!lat->is_single_const ())
1102 return NULL_TREE;
1103 input = lat->values->value;
1106 if (!input)
1107 return NULL_TREE;
1109 if (jfunc->type == IPA_JF_PASS_THROUGH)
1110 return ipa_get_jf_pass_through_result (jfunc, input);
1111 else
1112 return ipa_get_jf_ancestor_result (jfunc, input);
1114 else
1115 return NULL_TREE;
1118 /* Determie whether JFUNC evaluates to single known polymorphic context, given
1119 that INFO describes the caller node or the one it is inlined to, CS is the
1120 call graph edge corresponding to JFUNC and CSIDX index of the described
1121 parameter. */
1123 ipa_polymorphic_call_context
1124 ipa_context_from_jfunc (ipa_node_params *info, cgraph_edge *cs, int csidx,
1125 ipa_jump_func *jfunc)
1127 ipa_edge_args *args = IPA_EDGE_REF (cs);
1128 ipa_polymorphic_call_context ctx;
1129 ipa_polymorphic_call_context *edge_ctx
1130 = cs ? ipa_get_ith_polymorhic_call_context (args, csidx) : NULL;
1132 if (edge_ctx && !edge_ctx->useless_p ())
1133 ctx = *edge_ctx;
1135 if (jfunc->type == IPA_JF_PASS_THROUGH
1136 || jfunc->type == IPA_JF_ANCESTOR)
1138 ipa_polymorphic_call_context srcctx;
1139 int srcidx;
1140 bool type_preserved = true;
1141 if (jfunc->type == IPA_JF_PASS_THROUGH)
1143 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1144 return ctx;
1145 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
1146 srcidx = ipa_get_jf_pass_through_formal_id (jfunc);
1148 else
1150 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
1151 srcidx = ipa_get_jf_ancestor_formal_id (jfunc);
1153 if (info->ipcp_orig_node)
1155 if (info->known_contexts.exists ())
1156 srcctx = info->known_contexts[srcidx];
1158 else
1160 if (!info->lattices
1161 || srcidx >= ipa_get_param_count (info))
1162 return ctx;
1163 ipcp_lattice<ipa_polymorphic_call_context> *lat;
1164 lat = ipa_get_poly_ctx_lat (info, srcidx);
1165 if (!lat->is_single_const ())
1166 return ctx;
1167 srcctx = lat->values->value;
1169 if (srcctx.useless_p ())
1170 return ctx;
1171 if (jfunc->type == IPA_JF_ANCESTOR)
1172 srcctx.offset_by (ipa_get_jf_ancestor_offset (jfunc));
1173 if (!type_preserved)
1174 srcctx.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
1175 srcctx.combine_with (ctx);
1176 return srcctx;
1179 return ctx;
1182 /* If checking is enabled, verify that no lattice is in the TOP state, i.e. not
1183 bottom, not containing a variable component and without any known value at
1184 the same time. */
1186 DEBUG_FUNCTION void
1187 ipcp_verify_propagated_values (void)
1189 struct cgraph_node *node;
1191 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
1193 struct ipa_node_params *info = IPA_NODE_REF (node);
1194 int i, count = ipa_get_param_count (info);
1196 for (i = 0; i < count; i++)
1198 ipcp_lattice<tree> *lat = ipa_get_scalar_lat (info, i);
1200 if (!lat->bottom
1201 && !lat->contains_variable
1202 && lat->values_count == 0)
1204 if (dump_file)
1206 symtab_node::dump_table (dump_file);
1207 fprintf (dump_file, "\nIPA lattices after constant "
1208 "propagation, before gcc_unreachable:\n");
1209 print_all_lattices (dump_file, true, false);
1212 gcc_unreachable ();
1218 /* Return true iff X and Y should be considered equal values by IPA-CP. */
1220 static bool
1221 values_equal_for_ipcp_p (tree x, tree y)
1223 gcc_checking_assert (x != NULL_TREE && y != NULL_TREE);
1225 if (x == y)
1226 return true;
1228 if (TREE_CODE (x) == ADDR_EXPR
1229 && TREE_CODE (y) == ADDR_EXPR
1230 && TREE_CODE (TREE_OPERAND (x, 0)) == CONST_DECL
1231 && TREE_CODE (TREE_OPERAND (y, 0)) == CONST_DECL)
1232 return operand_equal_p (DECL_INITIAL (TREE_OPERAND (x, 0)),
1233 DECL_INITIAL (TREE_OPERAND (y, 0)), 0);
1234 else
1235 return operand_equal_p (x, y, 0);
1238 /* Return true iff X and Y should be considered equal contexts by IPA-CP. */
1240 static bool
1241 values_equal_for_ipcp_p (ipa_polymorphic_call_context x,
1242 ipa_polymorphic_call_context y)
1244 return x.equal_to (y);
1248 /* Add a new value source to the value represented by THIS, marking that a
1249 value comes from edge CS and (if the underlying jump function is a
1250 pass-through or an ancestor one) from a caller value SRC_VAL of a caller
1251 parameter described by SRC_INDEX. OFFSET is negative if the source was the
1252 scalar value of the parameter itself or the offset within an aggregate. */
1254 template <typename valtype>
1255 void
1256 ipcp_value<valtype>::add_source (cgraph_edge *cs, ipcp_value *src_val,
1257 int src_idx, HOST_WIDE_INT offset)
1259 ipcp_value_source<valtype> *src;
1261 src = new (ipcp_sources_pool.allocate ()) ipcp_value_source<valtype>;
1262 src->offset = offset;
1263 src->cs = cs;
1264 src->val = src_val;
1265 src->index = src_idx;
1267 src->next = sources;
1268 sources = src;
1271 /* Allocate a new ipcp_value holding a tree constant, initialize its value to
1272 SOURCE and clear all other fields. */
1274 static ipcp_value<tree> *
1275 allocate_and_init_ipcp_value (tree source)
1277 ipcp_value<tree> *val;
1279 val = ipcp_cst_values_pool.allocate ();
1280 memset (val, 0, sizeof (*val));
1281 val->value = source;
1282 return val;
1285 /* Allocate a new ipcp_value holding a polymorphic context, initialize its
1286 value to SOURCE and clear all other fields. */
1288 static ipcp_value<ipa_polymorphic_call_context> *
1289 allocate_and_init_ipcp_value (ipa_polymorphic_call_context source)
1291 ipcp_value<ipa_polymorphic_call_context> *val;
1293 // TODO
1294 val = ipcp_poly_ctx_values_pool.allocate ();
1295 memset (val, 0, sizeof (*val));
1296 val->value = source;
1297 return val;
1300 /* Try to add NEWVAL to LAT, potentially creating a new ipcp_value for it. CS,
1301 SRC_VAL SRC_INDEX and OFFSET are meant for add_source and have the same
1302 meaning. OFFSET -1 means the source is scalar and not a part of an
1303 aggregate. */
1305 template <typename valtype>
1306 bool
1307 ipcp_lattice<valtype>::add_value (valtype newval, cgraph_edge *cs,
1308 ipcp_value<valtype> *src_val,
1309 int src_idx, HOST_WIDE_INT offset)
1311 ipcp_value<valtype> *val;
1313 if (bottom)
1314 return false;
1316 for (val = values; val; val = val->next)
1317 if (values_equal_for_ipcp_p (val->value, newval))
1319 if (ipa_edge_within_scc (cs))
1321 ipcp_value_source<valtype> *s;
1322 for (s = val->sources; s ; s = s->next)
1323 if (s->cs == cs)
1324 break;
1325 if (s)
1326 return false;
1329 val->add_source (cs, src_val, src_idx, offset);
1330 return false;
1333 if (values_count == PARAM_VALUE (PARAM_IPA_CP_VALUE_LIST_SIZE))
1335 /* We can only free sources, not the values themselves, because sources
1336 of other values in this SCC might point to them. */
1337 for (val = values; val; val = val->next)
1339 while (val->sources)
1341 ipcp_value_source<valtype> *src = val->sources;
1342 val->sources = src->next;
1343 ipcp_sources_pool.remove ((ipcp_value_source<tree>*)src);
1347 values = NULL;
1348 return set_to_bottom ();
1351 values_count++;
1352 val = allocate_and_init_ipcp_value (newval);
1353 val->add_source (cs, src_val, src_idx, offset);
1354 val->next = values;
1355 values = val;
1356 return true;
1359 /* Propagate values through a pass-through jump function JFUNC associated with
1360 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
1361 is the index of the source parameter. */
1363 static bool
1364 propagate_vals_accross_pass_through (cgraph_edge *cs,
1365 ipa_jump_func *jfunc,
1366 ipcp_lattice<tree> *src_lat,
1367 ipcp_lattice<tree> *dest_lat,
1368 int src_idx)
1370 ipcp_value<tree> *src_val;
1371 bool ret = false;
1373 /* Do not create new values when propagating within an SCC because if there
1374 are arithmetic functions with circular dependencies, there is infinite
1375 number of them and we would just make lattices bottom. */
1376 if ((ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1377 && ipa_edge_within_scc (cs))
1378 ret = dest_lat->set_contains_variable ();
1379 else
1380 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1382 tree cstval = ipa_get_jf_pass_through_result (jfunc, src_val->value);
1384 if (cstval)
1385 ret |= dest_lat->add_value (cstval, cs, src_val, src_idx);
1386 else
1387 ret |= dest_lat->set_contains_variable ();
1390 return ret;
1393 /* Propagate values through an ancestor jump function JFUNC associated with
1394 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
1395 is the index of the source parameter. */
1397 static bool
1398 propagate_vals_accross_ancestor (struct cgraph_edge *cs,
1399 struct ipa_jump_func *jfunc,
1400 ipcp_lattice<tree> *src_lat,
1401 ipcp_lattice<tree> *dest_lat,
1402 int src_idx)
1404 ipcp_value<tree> *src_val;
1405 bool ret = false;
1407 if (ipa_edge_within_scc (cs))
1408 return dest_lat->set_contains_variable ();
1410 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1412 tree t = ipa_get_jf_ancestor_result (jfunc, src_val->value);
1414 if (t)
1415 ret |= dest_lat->add_value (t, cs, src_val, src_idx);
1416 else
1417 ret |= dest_lat->set_contains_variable ();
1420 return ret;
1423 /* Propagate scalar values across jump function JFUNC that is associated with
1424 edge CS and put the values into DEST_LAT. */
1426 static bool
1427 propagate_scalar_accross_jump_function (struct cgraph_edge *cs,
1428 struct ipa_jump_func *jfunc,
1429 ipcp_lattice<tree> *dest_lat)
1431 if (dest_lat->bottom)
1432 return false;
1434 if (jfunc->type == IPA_JF_CONST)
1436 tree val = ipa_get_jf_constant (jfunc);
1437 return dest_lat->add_value (val, cs, NULL, 0);
1439 else if (jfunc->type == IPA_JF_PASS_THROUGH
1440 || jfunc->type == IPA_JF_ANCESTOR)
1442 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1443 ipcp_lattice<tree> *src_lat;
1444 int src_idx;
1445 bool ret;
1447 if (jfunc->type == IPA_JF_PASS_THROUGH)
1448 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1449 else
1450 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1452 src_lat = ipa_get_scalar_lat (caller_info, src_idx);
1453 if (src_lat->bottom)
1454 return dest_lat->set_contains_variable ();
1456 /* If we would need to clone the caller and cannot, do not propagate. */
1457 if (!ipcp_versionable_function_p (cs->caller)
1458 && (src_lat->contains_variable
1459 || (src_lat->values_count > 1)))
1460 return dest_lat->set_contains_variable ();
1462 if (jfunc->type == IPA_JF_PASS_THROUGH)
1463 ret = propagate_vals_accross_pass_through (cs, jfunc, src_lat,
1464 dest_lat, src_idx);
1465 else
1466 ret = propagate_vals_accross_ancestor (cs, jfunc, src_lat, dest_lat,
1467 src_idx);
1469 if (src_lat->contains_variable)
1470 ret |= dest_lat->set_contains_variable ();
1472 return ret;
1475 /* TODO: We currently do not handle member method pointers in IPA-CP (we only
1476 use it for indirect inlining), we should propagate them too. */
1477 return dest_lat->set_contains_variable ();
1480 /* Propagate scalar values across jump function JFUNC that is associated with
1481 edge CS and describes argument IDX and put the values into DEST_LAT. */
1483 static bool
1484 propagate_context_accross_jump_function (cgraph_edge *cs,
1485 ipa_jump_func *jfunc, int idx,
1486 ipcp_lattice<ipa_polymorphic_call_context> *dest_lat)
1488 ipa_edge_args *args = IPA_EDGE_REF (cs);
1489 if (dest_lat->bottom)
1490 return false;
1491 bool ret = false;
1492 bool added_sth = false;
1493 bool type_preserved = true;
1495 ipa_polymorphic_call_context edge_ctx, *edge_ctx_ptr
1496 = ipa_get_ith_polymorhic_call_context (args, idx);
1498 if (edge_ctx_ptr)
1499 edge_ctx = *edge_ctx_ptr;
1501 if (jfunc->type == IPA_JF_PASS_THROUGH
1502 || jfunc->type == IPA_JF_ANCESTOR)
1504 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1505 int src_idx;
1506 ipcp_lattice<ipa_polymorphic_call_context> *src_lat;
1508 /* TODO: Once we figure out how to propagate speculations, it will
1509 probably be a good idea to switch to speculation if type_preserved is
1510 not set instead of punting. */
1511 if (jfunc->type == IPA_JF_PASS_THROUGH)
1513 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1514 goto prop_fail;
1515 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
1516 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1518 else
1520 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
1521 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1524 src_lat = ipa_get_poly_ctx_lat (caller_info, src_idx);
1525 /* If we would need to clone the caller and cannot, do not propagate. */
1526 if (!ipcp_versionable_function_p (cs->caller)
1527 && (src_lat->contains_variable
1528 || (src_lat->values_count > 1)))
1529 goto prop_fail;
1531 ipcp_value<ipa_polymorphic_call_context> *src_val;
1532 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1534 ipa_polymorphic_call_context cur = src_val->value;
1536 if (!type_preserved)
1537 cur.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
1538 if (jfunc->type == IPA_JF_ANCESTOR)
1539 cur.offset_by (ipa_get_jf_ancestor_offset (jfunc));
1540 /* TODO: In cases we know how the context is going to be used,
1541 we can improve the result by passing proper OTR_TYPE. */
1542 cur.combine_with (edge_ctx);
1543 if (!cur.useless_p ())
1545 if (src_lat->contains_variable
1546 && !edge_ctx.equal_to (cur))
1547 ret |= dest_lat->set_contains_variable ();
1548 ret |= dest_lat->add_value (cur, cs, src_val, src_idx);
1549 added_sth = true;
1555 prop_fail:
1556 if (!added_sth)
1558 if (!edge_ctx.useless_p ())
1559 ret |= dest_lat->add_value (edge_ctx, cs);
1560 else
1561 ret |= dest_lat->set_contains_variable ();
1564 return ret;
1567 /* Propagate alignments across jump function JFUNC that is associated with
1568 edge CS and update DEST_LAT accordingly. */
1570 static bool
1571 propagate_alignment_accross_jump_function (cgraph_edge *cs,
1572 ipa_jump_func *jfunc,
1573 ipcp_alignment_lattice *dest_lat)
1575 if (dest_lat->bottom_p ())
1576 return false;
1578 if (jfunc->type == IPA_JF_PASS_THROUGH
1579 || jfunc->type == IPA_JF_ANCESTOR)
1581 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1582 HOST_WIDE_INT offset = 0;
1583 int src_idx;
1585 if (jfunc->type == IPA_JF_PASS_THROUGH)
1587 enum tree_code op = ipa_get_jf_pass_through_operation (jfunc);
1588 if (op != NOP_EXPR)
1590 if (op != POINTER_PLUS_EXPR
1591 && op != PLUS_EXPR)
1592 return dest_lat->set_to_bottom ();
1593 tree operand = ipa_get_jf_pass_through_operand (jfunc);
1594 if (!tree_fits_shwi_p (operand))
1595 return dest_lat->set_to_bottom ();
1596 offset = tree_to_shwi (operand);
1598 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1600 else
1602 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1603 offset = ipa_get_jf_ancestor_offset (jfunc) / BITS_PER_UNIT;
1606 struct ipcp_param_lattices *src_lats;
1607 src_lats = ipa_get_parm_lattices (caller_info, src_idx);
1608 return dest_lat->meet_with (src_lats->alignment, offset);
1610 else
1612 if (jfunc->alignment.known)
1613 return dest_lat->meet_with (jfunc->alignment.align,
1614 jfunc->alignment.misalign);
1615 else
1616 return dest_lat->set_to_bottom ();
1620 /* If DEST_PLATS already has aggregate items, check that aggs_by_ref matches
1621 NEW_AGGS_BY_REF and if not, mark all aggs as bottoms and return true (in all
1622 other cases, return false). If there are no aggregate items, set
1623 aggs_by_ref to NEW_AGGS_BY_REF. */
1625 static bool
1626 set_check_aggs_by_ref (struct ipcp_param_lattices *dest_plats,
1627 bool new_aggs_by_ref)
1629 if (dest_plats->aggs)
1631 if (dest_plats->aggs_by_ref != new_aggs_by_ref)
1633 set_agg_lats_to_bottom (dest_plats);
1634 return true;
1637 else
1638 dest_plats->aggs_by_ref = new_aggs_by_ref;
1639 return false;
1642 /* Walk aggregate lattices in DEST_PLATS from ***AGLAT on, until ***aglat is an
1643 already existing lattice for the given OFFSET and SIZE, marking all skipped
1644 lattices as containing variable and checking for overlaps. If there is no
1645 already existing lattice for the OFFSET and VAL_SIZE, create one, initialize
1646 it with offset, size and contains_variable to PRE_EXISTING, and return true,
1647 unless there are too many already. If there are two many, return false. If
1648 there are overlaps turn whole DEST_PLATS to bottom and return false. If any
1649 skipped lattices were newly marked as containing variable, set *CHANGE to
1650 true. */
1652 static bool
1653 merge_agg_lats_step (struct ipcp_param_lattices *dest_plats,
1654 HOST_WIDE_INT offset, HOST_WIDE_INT val_size,
1655 struct ipcp_agg_lattice ***aglat,
1656 bool pre_existing, bool *change)
1658 gcc_checking_assert (offset >= 0);
1660 while (**aglat && (**aglat)->offset < offset)
1662 if ((**aglat)->offset + (**aglat)->size > offset)
1664 set_agg_lats_to_bottom (dest_plats);
1665 return false;
1667 *change |= (**aglat)->set_contains_variable ();
1668 *aglat = &(**aglat)->next;
1671 if (**aglat && (**aglat)->offset == offset)
1673 if ((**aglat)->size != val_size
1674 || ((**aglat)->next
1675 && (**aglat)->next->offset < offset + val_size))
1677 set_agg_lats_to_bottom (dest_plats);
1678 return false;
1680 gcc_checking_assert (!(**aglat)->next
1681 || (**aglat)->next->offset >= offset + val_size);
1682 return true;
1684 else
1686 struct ipcp_agg_lattice *new_al;
1688 if (**aglat && (**aglat)->offset < offset + val_size)
1690 set_agg_lats_to_bottom (dest_plats);
1691 return false;
1693 if (dest_plats->aggs_count == PARAM_VALUE (PARAM_IPA_MAX_AGG_ITEMS))
1694 return false;
1695 dest_plats->aggs_count++;
1696 new_al = ipcp_agg_lattice_pool.allocate ();
1697 memset (new_al, 0, sizeof (*new_al));
1699 new_al->offset = offset;
1700 new_al->size = val_size;
1701 new_al->contains_variable = pre_existing;
1703 new_al->next = **aglat;
1704 **aglat = new_al;
1705 return true;
1709 /* Set all AGLAT and all other aggregate lattices reachable by next pointers as
1710 containing an unknown value. */
1712 static bool
1713 set_chain_of_aglats_contains_variable (struct ipcp_agg_lattice *aglat)
1715 bool ret = false;
1716 while (aglat)
1718 ret |= aglat->set_contains_variable ();
1719 aglat = aglat->next;
1721 return ret;
1724 /* Merge existing aggregate lattices in SRC_PLATS to DEST_PLATS, subtracting
1725 DELTA_OFFSET. CS is the call graph edge and SRC_IDX the index of the source
1726 parameter used for lattice value sources. Return true if DEST_PLATS changed
1727 in any way. */
1729 static bool
1730 merge_aggregate_lattices (struct cgraph_edge *cs,
1731 struct ipcp_param_lattices *dest_plats,
1732 struct ipcp_param_lattices *src_plats,
1733 int src_idx, HOST_WIDE_INT offset_delta)
1735 bool pre_existing = dest_plats->aggs != NULL;
1736 struct ipcp_agg_lattice **dst_aglat;
1737 bool ret = false;
1739 if (set_check_aggs_by_ref (dest_plats, src_plats->aggs_by_ref))
1740 return true;
1741 if (src_plats->aggs_bottom)
1742 return set_agg_lats_contain_variable (dest_plats);
1743 if (src_plats->aggs_contain_variable)
1744 ret |= set_agg_lats_contain_variable (dest_plats);
1745 dst_aglat = &dest_plats->aggs;
1747 for (struct ipcp_agg_lattice *src_aglat = src_plats->aggs;
1748 src_aglat;
1749 src_aglat = src_aglat->next)
1751 HOST_WIDE_INT new_offset = src_aglat->offset - offset_delta;
1753 if (new_offset < 0)
1754 continue;
1755 if (merge_agg_lats_step (dest_plats, new_offset, src_aglat->size,
1756 &dst_aglat, pre_existing, &ret))
1758 struct ipcp_agg_lattice *new_al = *dst_aglat;
1760 dst_aglat = &(*dst_aglat)->next;
1761 if (src_aglat->bottom)
1763 ret |= new_al->set_contains_variable ();
1764 continue;
1766 if (src_aglat->contains_variable)
1767 ret |= new_al->set_contains_variable ();
1768 for (ipcp_value<tree> *val = src_aglat->values;
1769 val;
1770 val = val->next)
1771 ret |= new_al->add_value (val->value, cs, val, src_idx,
1772 src_aglat->offset);
1774 else if (dest_plats->aggs_bottom)
1775 return true;
1777 ret |= set_chain_of_aglats_contains_variable (*dst_aglat);
1778 return ret;
1781 /* Determine whether there is anything to propagate FROM SRC_PLATS through a
1782 pass-through JFUNC and if so, whether it has conform and conforms to the
1783 rules about propagating values passed by reference. */
1785 static bool
1786 agg_pass_through_permissible_p (struct ipcp_param_lattices *src_plats,
1787 struct ipa_jump_func *jfunc)
1789 return src_plats->aggs
1790 && (!src_plats->aggs_by_ref
1791 || ipa_get_jf_pass_through_agg_preserved (jfunc));
1794 /* Propagate scalar values across jump function JFUNC that is associated with
1795 edge CS and put the values into DEST_LAT. */
1797 static bool
1798 propagate_aggs_accross_jump_function (struct cgraph_edge *cs,
1799 struct ipa_jump_func *jfunc,
1800 struct ipcp_param_lattices *dest_plats)
1802 bool ret = false;
1804 if (dest_plats->aggs_bottom)
1805 return false;
1807 if (jfunc->type == IPA_JF_PASS_THROUGH
1808 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
1810 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1811 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1812 struct ipcp_param_lattices *src_plats;
1814 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
1815 if (agg_pass_through_permissible_p (src_plats, jfunc))
1817 /* Currently we do not produce clobber aggregate jump
1818 functions, replace with merging when we do. */
1819 gcc_assert (!jfunc->agg.items);
1820 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats,
1821 src_idx, 0);
1823 else
1824 ret |= set_agg_lats_contain_variable (dest_plats);
1826 else if (jfunc->type == IPA_JF_ANCESTOR
1827 && ipa_get_jf_ancestor_agg_preserved (jfunc))
1829 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1830 int src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1831 struct ipcp_param_lattices *src_plats;
1833 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
1834 if (src_plats->aggs && src_plats->aggs_by_ref)
1836 /* Currently we do not produce clobber aggregate jump
1837 functions, replace with merging when we do. */
1838 gcc_assert (!jfunc->agg.items);
1839 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats, src_idx,
1840 ipa_get_jf_ancestor_offset (jfunc));
1842 else if (!src_plats->aggs_by_ref)
1843 ret |= set_agg_lats_to_bottom (dest_plats);
1844 else
1845 ret |= set_agg_lats_contain_variable (dest_plats);
1847 else if (jfunc->agg.items)
1849 bool pre_existing = dest_plats->aggs != NULL;
1850 struct ipcp_agg_lattice **aglat = &dest_plats->aggs;
1851 struct ipa_agg_jf_item *item;
1852 int i;
1854 if (set_check_aggs_by_ref (dest_plats, jfunc->agg.by_ref))
1855 return true;
1857 FOR_EACH_VEC_ELT (*jfunc->agg.items, i, item)
1859 HOST_WIDE_INT val_size;
1861 if (item->offset < 0)
1862 continue;
1863 gcc_checking_assert (is_gimple_ip_invariant (item->value));
1864 val_size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (item->value)));
1866 if (merge_agg_lats_step (dest_plats, item->offset, val_size,
1867 &aglat, pre_existing, &ret))
1869 ret |= (*aglat)->add_value (item->value, cs, NULL, 0, 0);
1870 aglat = &(*aglat)->next;
1872 else if (dest_plats->aggs_bottom)
1873 return true;
1876 ret |= set_chain_of_aglats_contains_variable (*aglat);
1878 else
1879 ret |= set_agg_lats_contain_variable (dest_plats);
1881 return ret;
1884 /* Propagate constants from the caller to the callee of CS. INFO describes the
1885 caller. */
1887 static bool
1888 propagate_constants_accross_call (struct cgraph_edge *cs)
1890 struct ipa_node_params *callee_info;
1891 enum availability availability;
1892 struct cgraph_node *callee, *alias_or_thunk;
1893 struct ipa_edge_args *args;
1894 bool ret = false;
1895 int i, args_count, parms_count;
1897 callee = cs->callee->function_symbol (&availability);
1898 if (!callee->definition)
1899 return false;
1900 gcc_checking_assert (callee->has_gimple_body_p ());
1901 callee_info = IPA_NODE_REF (callee);
1903 args = IPA_EDGE_REF (cs);
1904 args_count = ipa_get_cs_argument_count (args);
1905 parms_count = ipa_get_param_count (callee_info);
1906 if (parms_count == 0)
1907 return false;
1909 /* No propagation through instrumentation thunks is available yet.
1910 It should be possible with proper mapping of call args and
1911 instrumented callee params in the propagation loop below. But
1912 this case mostly occurs when legacy code calls instrumented code
1913 and it is not a primary target for optimizations.
1914 We detect instrumentation thunks in aliases and thunks chain by
1915 checking instrumentation_clone flag for chain source and target.
1916 Going through instrumentation thunks we always have it changed
1917 from 0 to 1 and all other nodes do not change it. */
1918 if (!cs->callee->instrumentation_clone
1919 && callee->instrumentation_clone)
1921 for (i = 0; i < parms_count; i++)
1922 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
1923 i));
1924 return ret;
1927 /* If this call goes through a thunk we must not propagate to the first (0th)
1928 parameter. However, we might need to uncover a thunk from below a series
1929 of aliases first. */
1930 alias_or_thunk = cs->callee;
1931 while (alias_or_thunk->alias)
1932 alias_or_thunk = alias_or_thunk->get_alias_target ();
1933 if (alias_or_thunk->thunk.thunk_p)
1935 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
1936 0));
1937 i = 1;
1939 else
1940 i = 0;
1942 for (; (i < args_count) && (i < parms_count); i++)
1944 struct ipa_jump_func *jump_func = ipa_get_ith_jump_func (args, i);
1945 struct ipcp_param_lattices *dest_plats;
1947 dest_plats = ipa_get_parm_lattices (callee_info, i);
1948 if (availability == AVAIL_INTERPOSABLE)
1949 ret |= set_all_contains_variable (dest_plats);
1950 else
1952 ret |= propagate_scalar_accross_jump_function (cs, jump_func,
1953 &dest_plats->itself);
1954 ret |= propagate_context_accross_jump_function (cs, jump_func, i,
1955 &dest_plats->ctxlat);
1956 ret |= propagate_alignment_accross_jump_function (cs, jump_func,
1957 &dest_plats->alignment);
1958 ret |= propagate_aggs_accross_jump_function (cs, jump_func,
1959 dest_plats);
1962 for (; i < parms_count; i++)
1963 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info, i));
1965 return ret;
1968 /* If an indirect edge IE can be turned into a direct one based on KNOWN_VALS
1969 KNOWN_CONTEXTS, KNOWN_AGGS or AGG_REPS return the destination. The latter
1970 three can be NULL. If AGG_REPS is not NULL, KNOWN_AGGS is ignored. */
1972 static tree
1973 ipa_get_indirect_edge_target_1 (struct cgraph_edge *ie,
1974 vec<tree> known_csts,
1975 vec<ipa_polymorphic_call_context> known_contexts,
1976 vec<ipa_agg_jump_function_p> known_aggs,
1977 struct ipa_agg_replacement_value *agg_reps,
1978 bool *speculative)
1980 int param_index = ie->indirect_info->param_index;
1981 HOST_WIDE_INT anc_offset;
1982 tree t;
1983 tree target = NULL;
1985 *speculative = false;
1987 if (param_index == -1
1988 || known_csts.length () <= (unsigned int) param_index)
1989 return NULL_TREE;
1991 if (!ie->indirect_info->polymorphic)
1993 tree t;
1995 if (ie->indirect_info->agg_contents)
1997 if (agg_reps)
1999 t = NULL;
2000 while (agg_reps)
2002 if (agg_reps->index == param_index
2003 && agg_reps->offset == ie->indirect_info->offset
2004 && agg_reps->by_ref == ie->indirect_info->by_ref)
2006 t = agg_reps->value;
2007 break;
2009 agg_reps = agg_reps->next;
2012 else if (known_aggs.length () > (unsigned int) param_index)
2014 struct ipa_agg_jump_function *agg;
2015 agg = known_aggs[param_index];
2016 t = ipa_find_agg_cst_for_param (agg, ie->indirect_info->offset,
2017 ie->indirect_info->by_ref);
2019 else
2020 t = NULL;
2022 else
2023 t = known_csts[param_index];
2025 if (t &&
2026 TREE_CODE (t) == ADDR_EXPR
2027 && TREE_CODE (TREE_OPERAND (t, 0)) == FUNCTION_DECL)
2028 return TREE_OPERAND (t, 0);
2029 else
2030 return NULL_TREE;
2033 if (!opt_for_fn (ie->caller->decl, flag_devirtualize))
2034 return NULL_TREE;
2036 gcc_assert (!ie->indirect_info->agg_contents);
2037 anc_offset = ie->indirect_info->offset;
2039 t = NULL;
2041 /* Try to work out value of virtual table pointer value in replacemnets. */
2042 if (!t && agg_reps && !ie->indirect_info->by_ref)
2044 while (agg_reps)
2046 if (agg_reps->index == param_index
2047 && agg_reps->offset == ie->indirect_info->offset
2048 && agg_reps->by_ref)
2050 t = agg_reps->value;
2051 break;
2053 agg_reps = agg_reps->next;
2057 /* Try to work out value of virtual table pointer value in known
2058 aggregate values. */
2059 if (!t && known_aggs.length () > (unsigned int) param_index
2060 && !ie->indirect_info->by_ref)
2062 struct ipa_agg_jump_function *agg;
2063 agg = known_aggs[param_index];
2064 t = ipa_find_agg_cst_for_param (agg, ie->indirect_info->offset,
2065 true);
2068 /* If we found the virtual table pointer, lookup the target. */
2069 if (t)
2071 tree vtable;
2072 unsigned HOST_WIDE_INT offset;
2073 if (vtable_pointer_value_to_vtable (t, &vtable, &offset))
2075 target = gimple_get_virt_method_for_vtable (ie->indirect_info->otr_token,
2076 vtable, offset);
2077 if (target)
2079 if ((TREE_CODE (TREE_TYPE (target)) == FUNCTION_TYPE
2080 && DECL_FUNCTION_CODE (target) == BUILT_IN_UNREACHABLE)
2081 || !possible_polymorphic_call_target_p
2082 (ie, cgraph_node::get (target)))
2083 target = ipa_impossible_devirt_target (ie, target);
2084 *speculative = ie->indirect_info->vptr_changed;
2085 if (!*speculative)
2086 return target;
2091 /* Do we know the constant value of pointer? */
2092 if (!t)
2093 t = known_csts[param_index];
2095 gcc_checking_assert (!t || TREE_CODE (t) != TREE_BINFO);
2097 ipa_polymorphic_call_context context;
2098 if (known_contexts.length () > (unsigned int) param_index)
2100 context = known_contexts[param_index];
2101 context.offset_by (anc_offset);
2102 if (ie->indirect_info->vptr_changed)
2103 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
2104 ie->indirect_info->otr_type);
2105 if (t)
2107 ipa_polymorphic_call_context ctx2 = ipa_polymorphic_call_context
2108 (t, ie->indirect_info->otr_type, anc_offset);
2109 if (!ctx2.useless_p ())
2110 context.combine_with (ctx2, ie->indirect_info->otr_type);
2113 else if (t)
2115 context = ipa_polymorphic_call_context (t, ie->indirect_info->otr_type,
2116 anc_offset);
2117 if (ie->indirect_info->vptr_changed)
2118 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
2119 ie->indirect_info->otr_type);
2121 else
2122 return NULL_TREE;
2124 vec <cgraph_node *>targets;
2125 bool final;
2127 targets = possible_polymorphic_call_targets
2128 (ie->indirect_info->otr_type,
2129 ie->indirect_info->otr_token,
2130 context, &final);
2131 if (!final || targets.length () > 1)
2133 struct cgraph_node *node;
2134 if (*speculative)
2135 return target;
2136 if (!opt_for_fn (ie->caller->decl, flag_devirtualize_speculatively)
2137 || ie->speculative || !ie->maybe_hot_p ())
2138 return NULL;
2139 node = try_speculative_devirtualization (ie->indirect_info->otr_type,
2140 ie->indirect_info->otr_token,
2141 context);
2142 if (node)
2144 *speculative = true;
2145 target = node->decl;
2147 else
2148 return NULL;
2150 else
2152 *speculative = false;
2153 if (targets.length () == 1)
2154 target = targets[0]->decl;
2155 else
2156 target = ipa_impossible_devirt_target (ie, NULL_TREE);
2159 if (target && !possible_polymorphic_call_target_p (ie,
2160 cgraph_node::get (target)))
2161 target = ipa_impossible_devirt_target (ie, target);
2163 return target;
2167 /* If an indirect edge IE can be turned into a direct one based on KNOWN_CSTS,
2168 KNOWN_CONTEXTS (which can be vNULL) or KNOWN_AGGS (which also can be vNULL)
2169 return the destination. */
2171 tree
2172 ipa_get_indirect_edge_target (struct cgraph_edge *ie,
2173 vec<tree> known_csts,
2174 vec<ipa_polymorphic_call_context> known_contexts,
2175 vec<ipa_agg_jump_function_p> known_aggs,
2176 bool *speculative)
2178 return ipa_get_indirect_edge_target_1 (ie, known_csts, known_contexts,
2179 known_aggs, NULL, speculative);
2182 /* Calculate devirtualization time bonus for NODE, assuming we know KNOWN_CSTS
2183 and KNOWN_CONTEXTS. */
2185 static int
2186 devirtualization_time_bonus (struct cgraph_node *node,
2187 vec<tree> known_csts,
2188 vec<ipa_polymorphic_call_context> known_contexts,
2189 vec<ipa_agg_jump_function_p> known_aggs)
2191 struct cgraph_edge *ie;
2192 int res = 0;
2194 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
2196 struct cgraph_node *callee;
2197 struct inline_summary *isummary;
2198 enum availability avail;
2199 tree target;
2200 bool speculative;
2202 target = ipa_get_indirect_edge_target (ie, known_csts, known_contexts,
2203 known_aggs, &speculative);
2204 if (!target)
2205 continue;
2207 /* Only bare minimum benefit for clearly un-inlineable targets. */
2208 res += 1;
2209 callee = cgraph_node::get (target);
2210 if (!callee || !callee->definition)
2211 continue;
2212 callee = callee->function_symbol (&avail);
2213 if (avail < AVAIL_AVAILABLE)
2214 continue;
2215 isummary = inline_summaries->get (callee);
2216 if (!isummary->inlinable)
2217 continue;
2219 /* FIXME: The values below need re-considering and perhaps also
2220 integrating into the cost metrics, at lest in some very basic way. */
2221 if (isummary->size <= MAX_INLINE_INSNS_AUTO / 4)
2222 res += 31 / ((int)speculative + 1);
2223 else if (isummary->size <= MAX_INLINE_INSNS_AUTO / 2)
2224 res += 15 / ((int)speculative + 1);
2225 else if (isummary->size <= MAX_INLINE_INSNS_AUTO
2226 || DECL_DECLARED_INLINE_P (callee->decl))
2227 res += 7 / ((int)speculative + 1);
2230 return res;
2233 /* Return time bonus incurred because of HINTS. */
2235 static int
2236 hint_time_bonus (inline_hints hints)
2238 int result = 0;
2239 if (hints & (INLINE_HINT_loop_iterations | INLINE_HINT_loop_stride))
2240 result += PARAM_VALUE (PARAM_IPA_CP_LOOP_HINT_BONUS);
2241 if (hints & INLINE_HINT_array_index)
2242 result += PARAM_VALUE (PARAM_IPA_CP_ARRAY_INDEX_HINT_BONUS);
2243 return result;
2246 /* If there is a reason to penalize the function described by INFO in the
2247 cloning goodness evaluation, do so. */
2249 static inline int64_t
2250 incorporate_penalties (ipa_node_params *info, int64_t evaluation)
2252 if (info->node_within_scc)
2253 evaluation = (evaluation
2254 * (100 - PARAM_VALUE (PARAM_IPA_CP_RECURSION_PENALTY))) / 100;
2256 if (info->node_calling_single_call)
2257 evaluation = (evaluation
2258 * (100 - PARAM_VALUE (PARAM_IPA_CP_SINGLE_CALL_PENALTY)))
2259 / 100;
2261 return evaluation;
2264 /* Return true if cloning NODE is a good idea, given the estimated TIME_BENEFIT
2265 and SIZE_COST and with the sum of frequencies of incoming edges to the
2266 potential new clone in FREQUENCIES. */
2268 static bool
2269 good_cloning_opportunity_p (struct cgraph_node *node, int time_benefit,
2270 int freq_sum, gcov_type count_sum, int size_cost)
2272 if (time_benefit == 0
2273 || !opt_for_fn (node->decl, flag_ipa_cp_clone)
2274 || !optimize_function_for_speed_p (DECL_STRUCT_FUNCTION (node->decl)))
2275 return false;
2277 gcc_assert (size_cost > 0);
2279 struct ipa_node_params *info = IPA_NODE_REF (node);
2280 if (max_count)
2282 int factor = (count_sum * 1000) / max_count;
2283 int64_t evaluation = (((int64_t) time_benefit * factor)
2284 / size_cost);
2285 evaluation = incorporate_penalties (info, evaluation);
2287 if (dump_file && (dump_flags & TDF_DETAILS))
2288 fprintf (dump_file, " good_cloning_opportunity_p (time: %i, "
2289 "size: %i, count_sum: " HOST_WIDE_INT_PRINT_DEC
2290 "%s%s) -> evaluation: " "%" PRId64
2291 ", threshold: %i\n",
2292 time_benefit, size_cost, (HOST_WIDE_INT) count_sum,
2293 info->node_within_scc ? ", scc" : "",
2294 info->node_calling_single_call ? ", single_call" : "",
2295 evaluation, PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD));
2297 return evaluation >= PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD);
2299 else
2301 int64_t evaluation = (((int64_t) time_benefit * freq_sum)
2302 / size_cost);
2303 evaluation = incorporate_penalties (info, evaluation);
2305 if (dump_file && (dump_flags & TDF_DETAILS))
2306 fprintf (dump_file, " good_cloning_opportunity_p (time: %i, "
2307 "size: %i, freq_sum: %i%s%s) -> evaluation: "
2308 "%" PRId64 ", threshold: %i\n",
2309 time_benefit, size_cost, freq_sum,
2310 info->node_within_scc ? ", scc" : "",
2311 info->node_calling_single_call ? ", single_call" : "",
2312 evaluation, PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD));
2314 return evaluation >= PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD);
2318 /* Return all context independent values from aggregate lattices in PLATS in a
2319 vector. Return NULL if there are none. */
2321 static vec<ipa_agg_jf_item, va_gc> *
2322 context_independent_aggregate_values (struct ipcp_param_lattices *plats)
2324 vec<ipa_agg_jf_item, va_gc> *res = NULL;
2326 if (plats->aggs_bottom
2327 || plats->aggs_contain_variable
2328 || plats->aggs_count == 0)
2329 return NULL;
2331 for (struct ipcp_agg_lattice *aglat = plats->aggs;
2332 aglat;
2333 aglat = aglat->next)
2334 if (aglat->is_single_const ())
2336 struct ipa_agg_jf_item item;
2337 item.offset = aglat->offset;
2338 item.value = aglat->values->value;
2339 vec_safe_push (res, item);
2341 return res;
2344 /* Allocate KNOWN_CSTS, KNOWN_CONTEXTS and, if non-NULL, KNOWN_AGGS and
2345 populate them with values of parameters that are known independent of the
2346 context. INFO describes the function. If REMOVABLE_PARAMS_COST is
2347 non-NULL, the movement cost of all removable parameters will be stored in
2348 it. */
2350 static bool
2351 gather_context_independent_values (struct ipa_node_params *info,
2352 vec<tree> *known_csts,
2353 vec<ipa_polymorphic_call_context>
2354 *known_contexts,
2355 vec<ipa_agg_jump_function> *known_aggs,
2356 int *removable_params_cost)
2358 int i, count = ipa_get_param_count (info);
2359 bool ret = false;
2361 known_csts->create (0);
2362 known_contexts->create (0);
2363 known_csts->safe_grow_cleared (count);
2364 known_contexts->safe_grow_cleared (count);
2365 if (known_aggs)
2367 known_aggs->create (0);
2368 known_aggs->safe_grow_cleared (count);
2371 if (removable_params_cost)
2372 *removable_params_cost = 0;
2374 for (i = 0; i < count ; i++)
2376 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2377 ipcp_lattice<tree> *lat = &plats->itself;
2379 if (lat->is_single_const ())
2381 ipcp_value<tree> *val = lat->values;
2382 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
2383 (*known_csts)[i] = val->value;
2384 if (removable_params_cost)
2385 *removable_params_cost
2386 += estimate_move_cost (TREE_TYPE (val->value), false);
2387 ret = true;
2389 else if (removable_params_cost
2390 && !ipa_is_param_used (info, i))
2391 *removable_params_cost
2392 += ipa_get_param_move_cost (info, i);
2394 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2395 if (ctxlat->is_single_const ())
2397 (*known_contexts)[i] = ctxlat->values->value;
2398 ret = true;
2401 if (known_aggs)
2403 vec<ipa_agg_jf_item, va_gc> *agg_items;
2404 struct ipa_agg_jump_function *ajf;
2406 agg_items = context_independent_aggregate_values (plats);
2407 ajf = &(*known_aggs)[i];
2408 ajf->items = agg_items;
2409 ajf->by_ref = plats->aggs_by_ref;
2410 ret |= agg_items != NULL;
2414 return ret;
2417 /* The current interface in ipa-inline-analysis requires a pointer vector.
2418 Create it.
2420 FIXME: That interface should be re-worked, this is slightly silly. Still,
2421 I'd like to discuss how to change it first and this demonstrates the
2422 issue. */
2424 static vec<ipa_agg_jump_function_p>
2425 agg_jmp_p_vec_for_t_vec (vec<ipa_agg_jump_function> known_aggs)
2427 vec<ipa_agg_jump_function_p> ret;
2428 struct ipa_agg_jump_function *ajf;
2429 int i;
2431 ret.create (known_aggs.length ());
2432 FOR_EACH_VEC_ELT (known_aggs, i, ajf)
2433 ret.quick_push (ajf);
2434 return ret;
2437 /* Perform time and size measurement of NODE with the context given in
2438 KNOWN_CSTS, KNOWN_CONTEXTS and KNOWN_AGGS, calculate the benefit and cost
2439 given BASE_TIME of the node without specialization, REMOVABLE_PARAMS_COST of
2440 all context-independent removable parameters and EST_MOVE_COST of estimated
2441 movement of the considered parameter and store it into VAL. */
2443 static void
2444 perform_estimation_of_a_value (cgraph_node *node, vec<tree> known_csts,
2445 vec<ipa_polymorphic_call_context> known_contexts,
2446 vec<ipa_agg_jump_function_p> known_aggs_ptrs,
2447 int base_time, int removable_params_cost,
2448 int est_move_cost, ipcp_value_base *val)
2450 int time, size, time_benefit;
2451 inline_hints hints;
2453 estimate_ipcp_clone_size_and_time (node, known_csts, known_contexts,
2454 known_aggs_ptrs, &size, &time,
2455 &hints);
2456 time_benefit = base_time - time
2457 + devirtualization_time_bonus (node, known_csts, known_contexts,
2458 known_aggs_ptrs)
2459 + hint_time_bonus (hints)
2460 + removable_params_cost + est_move_cost;
2462 gcc_checking_assert (size >=0);
2463 /* The inliner-heuristics based estimates may think that in certain
2464 contexts some functions do not have any size at all but we want
2465 all specializations to have at least a tiny cost, not least not to
2466 divide by zero. */
2467 if (size == 0)
2468 size = 1;
2470 val->local_time_benefit = time_benefit;
2471 val->local_size_cost = size;
2474 /* Iterate over known values of parameters of NODE and estimate the local
2475 effects in terms of time and size they have. */
2477 static void
2478 estimate_local_effects (struct cgraph_node *node)
2480 struct ipa_node_params *info = IPA_NODE_REF (node);
2481 int i, count = ipa_get_param_count (info);
2482 vec<tree> known_csts;
2483 vec<ipa_polymorphic_call_context> known_contexts;
2484 vec<ipa_agg_jump_function> known_aggs;
2485 vec<ipa_agg_jump_function_p> known_aggs_ptrs;
2486 bool always_const;
2487 int base_time = inline_summaries->get (node)->time;
2488 int removable_params_cost;
2490 if (!count || !ipcp_versionable_function_p (node))
2491 return;
2493 if (dump_file && (dump_flags & TDF_DETAILS))
2494 fprintf (dump_file, "\nEstimating effects for %s/%i, base_time: %i.\n",
2495 node->name (), node->order, base_time);
2497 always_const = gather_context_independent_values (info, &known_csts,
2498 &known_contexts, &known_aggs,
2499 &removable_params_cost);
2500 known_aggs_ptrs = agg_jmp_p_vec_for_t_vec (known_aggs);
2501 if (always_const)
2503 struct caller_statistics stats;
2504 inline_hints hints;
2505 int time, size;
2507 init_caller_stats (&stats);
2508 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
2509 false);
2510 estimate_ipcp_clone_size_and_time (node, known_csts, known_contexts,
2511 known_aggs_ptrs, &size, &time, &hints);
2512 time -= devirtualization_time_bonus (node, known_csts, known_contexts,
2513 known_aggs_ptrs);
2514 time -= hint_time_bonus (hints);
2515 time -= removable_params_cost;
2516 size -= stats.n_calls * removable_params_cost;
2518 if (dump_file)
2519 fprintf (dump_file, " - context independent values, size: %i, "
2520 "time_benefit: %i\n", size, base_time - time);
2522 if (size <= 0
2523 || node->will_be_removed_from_program_if_no_direct_calls_p ())
2525 info->do_clone_for_all_contexts = true;
2526 base_time = time;
2528 if (dump_file)
2529 fprintf (dump_file, " Decided to specialize for all "
2530 "known contexts, code not going to grow.\n");
2532 else if (good_cloning_opportunity_p (node, base_time - time,
2533 stats.freq_sum, stats.count_sum,
2534 size))
2536 if (size + overall_size <= max_new_size)
2538 info->do_clone_for_all_contexts = true;
2539 base_time = time;
2540 overall_size += size;
2542 if (dump_file)
2543 fprintf (dump_file, " Decided to specialize for all "
2544 "known contexts, growth deemed beneficial.\n");
2546 else if (dump_file && (dump_flags & TDF_DETAILS))
2547 fprintf (dump_file, " Not cloning for all contexts because "
2548 "max_new_size would be reached with %li.\n",
2549 size + overall_size);
2553 for (i = 0; i < count ; i++)
2555 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2556 ipcp_lattice<tree> *lat = &plats->itself;
2557 ipcp_value<tree> *val;
2559 if (lat->bottom
2560 || !lat->values
2561 || known_csts[i])
2562 continue;
2564 for (val = lat->values; val; val = val->next)
2566 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
2567 known_csts[i] = val->value;
2569 int emc = estimate_move_cost (TREE_TYPE (val->value), true);
2570 perform_estimation_of_a_value (node, known_csts, known_contexts,
2571 known_aggs_ptrs, base_time,
2572 removable_params_cost, emc, val);
2574 if (dump_file && (dump_flags & TDF_DETAILS))
2576 fprintf (dump_file, " - estimates for value ");
2577 print_ipcp_constant_value (dump_file, val->value);
2578 fprintf (dump_file, " for ");
2579 ipa_dump_param (dump_file, info, i);
2580 fprintf (dump_file, ": time_benefit: %i, size: %i\n",
2581 val->local_time_benefit, val->local_size_cost);
2584 known_csts[i] = NULL_TREE;
2587 for (i = 0; i < count; i++)
2589 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2591 if (!plats->virt_call)
2592 continue;
2594 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2595 ipcp_value<ipa_polymorphic_call_context> *val;
2597 if (ctxlat->bottom
2598 || !ctxlat->values
2599 || !known_contexts[i].useless_p ())
2600 continue;
2602 for (val = ctxlat->values; val; val = val->next)
2604 known_contexts[i] = val->value;
2605 perform_estimation_of_a_value (node, known_csts, known_contexts,
2606 known_aggs_ptrs, base_time,
2607 removable_params_cost, 0, val);
2609 if (dump_file && (dump_flags & TDF_DETAILS))
2611 fprintf (dump_file, " - estimates for polymorphic context ");
2612 print_ipcp_constant_value (dump_file, val->value);
2613 fprintf (dump_file, " for ");
2614 ipa_dump_param (dump_file, info, i);
2615 fprintf (dump_file, ": time_benefit: %i, size: %i\n",
2616 val->local_time_benefit, val->local_size_cost);
2619 known_contexts[i] = ipa_polymorphic_call_context ();
2622 for (i = 0; i < count ; i++)
2624 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2625 struct ipa_agg_jump_function *ajf;
2626 struct ipcp_agg_lattice *aglat;
2628 if (plats->aggs_bottom || !plats->aggs)
2629 continue;
2631 ajf = &known_aggs[i];
2632 for (aglat = plats->aggs; aglat; aglat = aglat->next)
2634 ipcp_value<tree> *val;
2635 if (aglat->bottom || !aglat->values
2636 /* If the following is true, the one value is in known_aggs. */
2637 || (!plats->aggs_contain_variable
2638 && aglat->is_single_const ()))
2639 continue;
2641 for (val = aglat->values; val; val = val->next)
2643 struct ipa_agg_jf_item item;
2645 item.offset = aglat->offset;
2646 item.value = val->value;
2647 vec_safe_push (ajf->items, item);
2649 perform_estimation_of_a_value (node, known_csts, known_contexts,
2650 known_aggs_ptrs, base_time,
2651 removable_params_cost, 0, val);
2653 if (dump_file && (dump_flags & TDF_DETAILS))
2655 fprintf (dump_file, " - estimates for value ");
2656 print_ipcp_constant_value (dump_file, val->value);
2657 fprintf (dump_file, " for ");
2658 ipa_dump_param (dump_file, info, i);
2659 fprintf (dump_file, "[%soffset: " HOST_WIDE_INT_PRINT_DEC
2660 "]: time_benefit: %i, size: %i\n",
2661 plats->aggs_by_ref ? "ref " : "",
2662 aglat->offset,
2663 val->local_time_benefit, val->local_size_cost);
2666 ajf->items->pop ();
2671 for (i = 0; i < count ; i++)
2672 vec_free (known_aggs[i].items);
2674 known_csts.release ();
2675 known_contexts.release ();
2676 known_aggs.release ();
2677 known_aggs_ptrs.release ();
2681 /* Add value CUR_VAL and all yet-unsorted values it is dependent on to the
2682 topological sort of values. */
2684 template <typename valtype>
2685 void
2686 value_topo_info<valtype>::add_val (ipcp_value<valtype> *cur_val)
2688 ipcp_value_source<valtype> *src;
2690 if (cur_val->dfs)
2691 return;
2693 dfs_counter++;
2694 cur_val->dfs = dfs_counter;
2695 cur_val->low_link = dfs_counter;
2697 cur_val->topo_next = stack;
2698 stack = cur_val;
2699 cur_val->on_stack = true;
2701 for (src = cur_val->sources; src; src = src->next)
2702 if (src->val)
2704 if (src->val->dfs == 0)
2706 add_val (src->val);
2707 if (src->val->low_link < cur_val->low_link)
2708 cur_val->low_link = src->val->low_link;
2710 else if (src->val->on_stack
2711 && src->val->dfs < cur_val->low_link)
2712 cur_val->low_link = src->val->dfs;
2715 if (cur_val->dfs == cur_val->low_link)
2717 ipcp_value<valtype> *v, *scc_list = NULL;
2721 v = stack;
2722 stack = v->topo_next;
2723 v->on_stack = false;
2725 v->scc_next = scc_list;
2726 scc_list = v;
2728 while (v != cur_val);
2730 cur_val->topo_next = values_topo;
2731 values_topo = cur_val;
2735 /* Add all values in lattices associated with NODE to the topological sort if
2736 they are not there yet. */
2738 static void
2739 add_all_node_vals_to_toposort (cgraph_node *node, ipa_topo_info *topo)
2741 struct ipa_node_params *info = IPA_NODE_REF (node);
2742 int i, count = ipa_get_param_count (info);
2744 for (i = 0; i < count ; i++)
2746 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2747 ipcp_lattice<tree> *lat = &plats->itself;
2748 struct ipcp_agg_lattice *aglat;
2750 if (!lat->bottom)
2752 ipcp_value<tree> *val;
2753 for (val = lat->values; val; val = val->next)
2754 topo->constants.add_val (val);
2757 if (!plats->aggs_bottom)
2758 for (aglat = plats->aggs; aglat; aglat = aglat->next)
2759 if (!aglat->bottom)
2761 ipcp_value<tree> *val;
2762 for (val = aglat->values; val; val = val->next)
2763 topo->constants.add_val (val);
2766 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2767 if (!ctxlat->bottom)
2769 ipcp_value<ipa_polymorphic_call_context> *ctxval;
2770 for (ctxval = ctxlat->values; ctxval; ctxval = ctxval->next)
2771 topo->contexts.add_val (ctxval);
2776 /* One pass of constants propagation along the call graph edges, from callers
2777 to callees (requires topological ordering in TOPO), iterate over strongly
2778 connected components. */
2780 static void
2781 propagate_constants_topo (struct ipa_topo_info *topo)
2783 int i;
2785 for (i = topo->nnodes - 1; i >= 0; i--)
2787 unsigned j;
2788 struct cgraph_node *v, *node = topo->order[i];
2789 vec<cgraph_node *> cycle_nodes = ipa_get_nodes_in_cycle (node);
2791 /* First, iteratively propagate within the strongly connected component
2792 until all lattices stabilize. */
2793 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
2794 if (v->has_gimple_body_p ())
2795 push_node_to_stack (topo, v);
2797 v = pop_node_from_stack (topo);
2798 while (v)
2800 struct cgraph_edge *cs;
2802 for (cs = v->callees; cs; cs = cs->next_callee)
2803 if (ipa_edge_within_scc (cs))
2805 IPA_NODE_REF (v)->node_within_scc = true;
2806 if (propagate_constants_accross_call (cs))
2807 push_node_to_stack (topo, cs->callee->function_symbol ());
2809 v = pop_node_from_stack (topo);
2812 /* Afterwards, propagate along edges leading out of the SCC, calculates
2813 the local effects of the discovered constants and all valid values to
2814 their topological sort. */
2815 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
2816 if (v->has_gimple_body_p ())
2818 struct cgraph_edge *cs;
2820 estimate_local_effects (v);
2821 add_all_node_vals_to_toposort (v, topo);
2822 for (cs = v->callees; cs; cs = cs->next_callee)
2823 if (!ipa_edge_within_scc (cs))
2824 propagate_constants_accross_call (cs);
2826 cycle_nodes.release ();
2831 /* Return the sum of A and B if none of them is bigger than INT_MAX/2, return
2832 the bigger one if otherwise. */
2834 static int
2835 safe_add (int a, int b)
2837 if (a > INT_MAX/2 || b > INT_MAX/2)
2838 return a > b ? a : b;
2839 else
2840 return a + b;
2844 /* Propagate the estimated effects of individual values along the topological
2845 from the dependent values to those they depend on. */
2847 template <typename valtype>
2848 void
2849 value_topo_info<valtype>::propagate_effects ()
2851 ipcp_value<valtype> *base;
2853 for (base = values_topo; base; base = base->topo_next)
2855 ipcp_value_source<valtype> *src;
2856 ipcp_value<valtype> *val;
2857 int time = 0, size = 0;
2859 for (val = base; val; val = val->scc_next)
2861 time = safe_add (time,
2862 val->local_time_benefit + val->prop_time_benefit);
2863 size = safe_add (size, val->local_size_cost + val->prop_size_cost);
2866 for (val = base; val; val = val->scc_next)
2867 for (src = val->sources; src; src = src->next)
2868 if (src->val
2869 && src->cs->maybe_hot_p ())
2871 src->val->prop_time_benefit = safe_add (time,
2872 src->val->prop_time_benefit);
2873 src->val->prop_size_cost = safe_add (size,
2874 src->val->prop_size_cost);
2880 /* Propagate constants, polymorphic contexts and their effects from the
2881 summaries interprocedurally. */
2883 static void
2884 ipcp_propagate_stage (struct ipa_topo_info *topo)
2886 struct cgraph_node *node;
2888 if (dump_file)
2889 fprintf (dump_file, "\n Propagating constants:\n\n");
2891 if (in_lto_p)
2892 ipa_update_after_lto_read ();
2895 FOR_EACH_DEFINED_FUNCTION (node)
2897 struct ipa_node_params *info = IPA_NODE_REF (node);
2899 determine_versionability (node);
2900 if (node->has_gimple_body_p ())
2902 info->lattices = XCNEWVEC (struct ipcp_param_lattices,
2903 ipa_get_param_count (info));
2904 initialize_node_lattices (node);
2906 if (node->definition && !node->alias)
2907 overall_size += inline_summaries->get (node)->self_size;
2908 if (node->count > max_count)
2909 max_count = node->count;
2912 max_new_size = overall_size;
2913 if (max_new_size < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
2914 max_new_size = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
2915 max_new_size += max_new_size * PARAM_VALUE (PARAM_IPCP_UNIT_GROWTH) / 100 + 1;
2917 if (dump_file)
2918 fprintf (dump_file, "\noverall_size: %li, max_new_size: %li\n",
2919 overall_size, max_new_size);
2921 propagate_constants_topo (topo);
2922 #ifdef ENABLE_CHECKING
2923 ipcp_verify_propagated_values ();
2924 #endif
2925 topo->constants.propagate_effects ();
2926 topo->contexts.propagate_effects ();
2928 if (dump_file)
2930 fprintf (dump_file, "\nIPA lattices after all propagation:\n");
2931 print_all_lattices (dump_file, (dump_flags & TDF_DETAILS), true);
2935 /* Discover newly direct outgoing edges from NODE which is a new clone with
2936 known KNOWN_CSTS and make them direct. */
2938 static void
2939 ipcp_discover_new_direct_edges (struct cgraph_node *node,
2940 vec<tree> known_csts,
2941 vec<ipa_polymorphic_call_context>
2942 known_contexts,
2943 struct ipa_agg_replacement_value *aggvals)
2945 struct cgraph_edge *ie, *next_ie;
2946 bool found = false;
2948 for (ie = node->indirect_calls; ie; ie = next_ie)
2950 tree target;
2951 bool speculative;
2953 next_ie = ie->next_callee;
2954 target = ipa_get_indirect_edge_target_1 (ie, known_csts, known_contexts,
2955 vNULL, aggvals, &speculative);
2956 if (target)
2958 bool agg_contents = ie->indirect_info->agg_contents;
2959 bool polymorphic = ie->indirect_info->polymorphic;
2960 int param_index = ie->indirect_info->param_index;
2961 struct cgraph_edge *cs = ipa_make_edge_direct_to_target (ie, target,
2962 speculative);
2963 found = true;
2965 if (cs && !agg_contents && !polymorphic)
2967 struct ipa_node_params *info = IPA_NODE_REF (node);
2968 int c = ipa_get_controlled_uses (info, param_index);
2969 if (c != IPA_UNDESCRIBED_USE)
2971 struct ipa_ref *to_del;
2973 c--;
2974 ipa_set_controlled_uses (info, param_index, c);
2975 if (dump_file && (dump_flags & TDF_DETAILS))
2976 fprintf (dump_file, " controlled uses count of param "
2977 "%i bumped down to %i\n", param_index, c);
2978 if (c == 0
2979 && (to_del = node->find_reference (cs->callee, NULL, 0)))
2981 if (dump_file && (dump_flags & TDF_DETAILS))
2982 fprintf (dump_file, " and even removing its "
2983 "cloning-created reference\n");
2984 to_del->remove_reference ();
2990 /* Turning calls to direct calls will improve overall summary. */
2991 if (found)
2992 inline_update_overall_summary (node);
2995 /* Vector of pointers which for linked lists of clones of an original crgaph
2996 edge. */
2998 static vec<cgraph_edge *> next_edge_clone;
2999 static vec<cgraph_edge *> prev_edge_clone;
3001 static inline void
3002 grow_edge_clone_vectors (void)
3004 if (next_edge_clone.length ()
3005 <= (unsigned) symtab->edges_max_uid)
3006 next_edge_clone.safe_grow_cleared (symtab->edges_max_uid + 1);
3007 if (prev_edge_clone.length ()
3008 <= (unsigned) symtab->edges_max_uid)
3009 prev_edge_clone.safe_grow_cleared (symtab->edges_max_uid + 1);
3012 /* Edge duplication hook to grow the appropriate linked list in
3013 next_edge_clone. */
3015 static void
3016 ipcp_edge_duplication_hook (struct cgraph_edge *src, struct cgraph_edge *dst,
3017 void *)
3019 grow_edge_clone_vectors ();
3021 struct cgraph_edge *old_next = next_edge_clone[src->uid];
3022 if (old_next)
3023 prev_edge_clone[old_next->uid] = dst;
3024 prev_edge_clone[dst->uid] = src;
3026 next_edge_clone[dst->uid] = old_next;
3027 next_edge_clone[src->uid] = dst;
3030 /* Hook that is called by cgraph.c when an edge is removed. */
3032 static void
3033 ipcp_edge_removal_hook (struct cgraph_edge *cs, void *)
3035 grow_edge_clone_vectors ();
3037 struct cgraph_edge *prev = prev_edge_clone[cs->uid];
3038 struct cgraph_edge *next = next_edge_clone[cs->uid];
3039 if (prev)
3040 next_edge_clone[prev->uid] = next;
3041 if (next)
3042 prev_edge_clone[next->uid] = prev;
3045 /* See if NODE is a clone with a known aggregate value at a given OFFSET of a
3046 parameter with the given INDEX. */
3048 static tree
3049 get_clone_agg_value (struct cgraph_node *node, HOST_WIDE_INT offset,
3050 int index)
3052 struct ipa_agg_replacement_value *aggval;
3054 aggval = ipa_get_agg_replacements_for_node (node);
3055 while (aggval)
3057 if (aggval->offset == offset
3058 && aggval->index == index)
3059 return aggval->value;
3060 aggval = aggval->next;
3062 return NULL_TREE;
3065 /* Return true is NODE is DEST or its clone for all contexts. */
3067 static bool
3068 same_node_or_its_all_contexts_clone_p (cgraph_node *node, cgraph_node *dest)
3070 if (node == dest)
3071 return true;
3073 struct ipa_node_params *info = IPA_NODE_REF (node);
3074 return info->is_all_contexts_clone && info->ipcp_orig_node == dest;
3077 /* Return true if edge CS does bring about the value described by SRC to node
3078 DEST or its clone for all contexts. */
3080 static bool
3081 cgraph_edge_brings_value_p (cgraph_edge *cs, ipcp_value_source<tree> *src,
3082 cgraph_node *dest)
3084 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3085 enum availability availability;
3086 cgraph_node *real_dest = cs->callee->function_symbol (&availability);
3088 if (!same_node_or_its_all_contexts_clone_p (real_dest, dest)
3089 || availability <= AVAIL_INTERPOSABLE
3090 || caller_info->node_dead)
3091 return false;
3092 if (!src->val)
3093 return true;
3095 if (caller_info->ipcp_orig_node)
3097 tree t;
3098 if (src->offset == -1)
3099 t = caller_info->known_csts[src->index];
3100 else
3101 t = get_clone_agg_value (cs->caller, src->offset, src->index);
3102 return (t != NULL_TREE
3103 && values_equal_for_ipcp_p (src->val->value, t));
3105 else
3107 struct ipcp_agg_lattice *aglat;
3108 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
3109 src->index);
3110 if (src->offset == -1)
3111 return (plats->itself.is_single_const ()
3112 && values_equal_for_ipcp_p (src->val->value,
3113 plats->itself.values->value));
3114 else
3116 if (plats->aggs_bottom || plats->aggs_contain_variable)
3117 return false;
3118 for (aglat = plats->aggs; aglat; aglat = aglat->next)
3119 if (aglat->offset == src->offset)
3120 return (aglat->is_single_const ()
3121 && values_equal_for_ipcp_p (src->val->value,
3122 aglat->values->value));
3124 return false;
3128 /* Return true if edge CS does bring about the value described by SRC to node
3129 DEST or its clone for all contexts. */
3131 static bool
3132 cgraph_edge_brings_value_p (cgraph_edge *cs,
3133 ipcp_value_source<ipa_polymorphic_call_context> *src,
3134 cgraph_node *dest)
3136 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3137 cgraph_node *real_dest = cs->callee->function_symbol ();
3139 if (!same_node_or_its_all_contexts_clone_p (real_dest, dest)
3140 || caller_info->node_dead)
3141 return false;
3142 if (!src->val)
3143 return true;
3145 if (caller_info->ipcp_orig_node)
3146 return (caller_info->known_contexts.length () > (unsigned) src->index)
3147 && values_equal_for_ipcp_p (src->val->value,
3148 caller_info->known_contexts[src->index]);
3150 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
3151 src->index);
3152 return plats->ctxlat.is_single_const ()
3153 && values_equal_for_ipcp_p (src->val->value,
3154 plats->ctxlat.values->value);
3157 /* Get the next clone in the linked list of clones of an edge. */
3159 static inline struct cgraph_edge *
3160 get_next_cgraph_edge_clone (struct cgraph_edge *cs)
3162 return next_edge_clone[cs->uid];
3165 /* Given VAL that is intended for DEST, iterate over all its sources and if
3166 they still hold, add their edge frequency and their number into *FREQUENCY
3167 and *CALLER_COUNT respectively. */
3169 template <typename valtype>
3170 static bool
3171 get_info_about_necessary_edges (ipcp_value<valtype> *val, cgraph_node *dest,
3172 int *freq_sum,
3173 gcov_type *count_sum, int *caller_count)
3175 ipcp_value_source<valtype> *src;
3176 int freq = 0, count = 0;
3177 gcov_type cnt = 0;
3178 bool hot = false;
3180 for (src = val->sources; src; src = src->next)
3182 struct cgraph_edge *cs = src->cs;
3183 while (cs)
3185 if (cgraph_edge_brings_value_p (cs, src, dest))
3187 count++;
3188 freq += cs->frequency;
3189 cnt += cs->count;
3190 hot |= cs->maybe_hot_p ();
3192 cs = get_next_cgraph_edge_clone (cs);
3196 *freq_sum = freq;
3197 *count_sum = cnt;
3198 *caller_count = count;
3199 return hot;
3202 /* Return a vector of incoming edges that do bring value VAL to node DEST. It
3203 is assumed their number is known and equal to CALLER_COUNT. */
3205 template <typename valtype>
3206 static vec<cgraph_edge *>
3207 gather_edges_for_value (ipcp_value<valtype> *val, cgraph_node *dest,
3208 int caller_count)
3210 ipcp_value_source<valtype> *src;
3211 vec<cgraph_edge *> ret;
3213 ret.create (caller_count);
3214 for (src = val->sources; src; src = src->next)
3216 struct cgraph_edge *cs = src->cs;
3217 while (cs)
3219 if (cgraph_edge_brings_value_p (cs, src, dest))
3220 ret.quick_push (cs);
3221 cs = get_next_cgraph_edge_clone (cs);
3225 return ret;
3228 /* Construct a replacement map for a know VALUE for a formal parameter PARAM.
3229 Return it or NULL if for some reason it cannot be created. */
3231 static struct ipa_replace_map *
3232 get_replacement_map (struct ipa_node_params *info, tree value, int parm_num)
3234 struct ipa_replace_map *replace_map;
3237 replace_map = ggc_alloc<ipa_replace_map> ();
3238 if (dump_file)
3240 fprintf (dump_file, " replacing ");
3241 ipa_dump_param (dump_file, info, parm_num);
3243 fprintf (dump_file, " with const ");
3244 print_generic_expr (dump_file, value, 0);
3245 fprintf (dump_file, "\n");
3247 replace_map->old_tree = NULL;
3248 replace_map->parm_num = parm_num;
3249 replace_map->new_tree = value;
3250 replace_map->replace_p = true;
3251 replace_map->ref_p = false;
3253 return replace_map;
3256 /* Dump new profiling counts */
3258 static void
3259 dump_profile_updates (struct cgraph_node *orig_node,
3260 struct cgraph_node *new_node)
3262 struct cgraph_edge *cs;
3264 fprintf (dump_file, " setting count of the specialized node to "
3265 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) new_node->count);
3266 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3267 fprintf (dump_file, " edge to %s has count "
3268 HOST_WIDE_INT_PRINT_DEC "\n",
3269 cs->callee->name (), (HOST_WIDE_INT) cs->count);
3271 fprintf (dump_file, " setting count of the original node to "
3272 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) orig_node->count);
3273 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3274 fprintf (dump_file, " edge to %s is left with "
3275 HOST_WIDE_INT_PRINT_DEC "\n",
3276 cs->callee->name (), (HOST_WIDE_INT) cs->count);
3279 /* After a specialized NEW_NODE version of ORIG_NODE has been created, update
3280 their profile information to reflect this. */
3282 static void
3283 update_profiling_info (struct cgraph_node *orig_node,
3284 struct cgraph_node *new_node)
3286 struct cgraph_edge *cs;
3287 struct caller_statistics stats;
3288 gcov_type new_sum, orig_sum;
3289 gcov_type remainder, orig_node_count = orig_node->count;
3291 if (orig_node_count == 0)
3292 return;
3294 init_caller_stats (&stats);
3295 orig_node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
3296 false);
3297 orig_sum = stats.count_sum;
3298 init_caller_stats (&stats);
3299 new_node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
3300 false);
3301 new_sum = stats.count_sum;
3303 if (orig_node_count < orig_sum + new_sum)
3305 if (dump_file)
3306 fprintf (dump_file, " Problem: node %s/%i has too low count "
3307 HOST_WIDE_INT_PRINT_DEC " while the sum of incoming "
3308 "counts is " HOST_WIDE_INT_PRINT_DEC "\n",
3309 orig_node->name (), orig_node->order,
3310 (HOST_WIDE_INT) orig_node_count,
3311 (HOST_WIDE_INT) (orig_sum + new_sum));
3313 orig_node_count = (orig_sum + new_sum) * 12 / 10;
3314 if (dump_file)
3315 fprintf (dump_file, " proceeding by pretending it was "
3316 HOST_WIDE_INT_PRINT_DEC "\n",
3317 (HOST_WIDE_INT) orig_node_count);
3320 new_node->count = new_sum;
3321 remainder = orig_node_count - new_sum;
3322 orig_node->count = remainder;
3324 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3325 if (cs->frequency)
3326 cs->count = apply_probability (cs->count,
3327 GCOV_COMPUTE_SCALE (new_sum,
3328 orig_node_count));
3329 else
3330 cs->count = 0;
3332 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3333 cs->count = apply_probability (cs->count,
3334 GCOV_COMPUTE_SCALE (remainder,
3335 orig_node_count));
3337 if (dump_file)
3338 dump_profile_updates (orig_node, new_node);
3341 /* Update the respective profile of specialized NEW_NODE and the original
3342 ORIG_NODE after additional edges with cumulative count sum REDIRECTED_SUM
3343 have been redirected to the specialized version. */
3345 static void
3346 update_specialized_profile (struct cgraph_node *new_node,
3347 struct cgraph_node *orig_node,
3348 gcov_type redirected_sum)
3350 struct cgraph_edge *cs;
3351 gcov_type new_node_count, orig_node_count = orig_node->count;
3353 if (dump_file)
3354 fprintf (dump_file, " the sum of counts of redirected edges is "
3355 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) redirected_sum);
3356 if (orig_node_count == 0)
3357 return;
3359 gcc_assert (orig_node_count >= redirected_sum);
3361 new_node_count = new_node->count;
3362 new_node->count += redirected_sum;
3363 orig_node->count -= redirected_sum;
3365 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3366 if (cs->frequency)
3367 cs->count += apply_probability (cs->count,
3368 GCOV_COMPUTE_SCALE (redirected_sum,
3369 new_node_count));
3370 else
3371 cs->count = 0;
3373 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3375 gcov_type dec = apply_probability (cs->count,
3376 GCOV_COMPUTE_SCALE (redirected_sum,
3377 orig_node_count));
3378 if (dec < cs->count)
3379 cs->count -= dec;
3380 else
3381 cs->count = 0;
3384 if (dump_file)
3385 dump_profile_updates (orig_node, new_node);
3388 /* Create a specialized version of NODE with known constants in KNOWN_CSTS,
3389 known contexts in KNOWN_CONTEXTS and known aggregate values in AGGVALS and
3390 redirect all edges in CALLERS to it. */
3392 static struct cgraph_node *
3393 create_specialized_node (struct cgraph_node *node,
3394 vec<tree> known_csts,
3395 vec<ipa_polymorphic_call_context> known_contexts,
3396 struct ipa_agg_replacement_value *aggvals,
3397 vec<cgraph_edge *> callers)
3399 struct ipa_node_params *new_info, *info = IPA_NODE_REF (node);
3400 vec<ipa_replace_map *, va_gc> *replace_trees = NULL;
3401 struct ipa_agg_replacement_value *av;
3402 struct cgraph_node *new_node;
3403 int i, count = ipa_get_param_count (info);
3404 bitmap args_to_skip;
3406 gcc_assert (!info->ipcp_orig_node);
3408 if (node->local.can_change_signature)
3410 args_to_skip = BITMAP_GGC_ALLOC ();
3411 for (i = 0; i < count; i++)
3413 tree t = known_csts[i];
3415 if (t || !ipa_is_param_used (info, i))
3416 bitmap_set_bit (args_to_skip, i);
3419 else
3421 args_to_skip = NULL;
3422 if (dump_file && (dump_flags & TDF_DETAILS))
3423 fprintf (dump_file, " cannot change function signature\n");
3426 for (i = 0; i < count ; i++)
3428 tree t = known_csts[i];
3429 if (t)
3431 struct ipa_replace_map *replace_map;
3433 gcc_checking_assert (TREE_CODE (t) != TREE_BINFO);
3434 replace_map = get_replacement_map (info, t, i);
3435 if (replace_map)
3436 vec_safe_push (replace_trees, replace_map);
3440 new_node = node->create_virtual_clone (callers, replace_trees,
3441 args_to_skip, "constprop");
3442 ipa_set_node_agg_value_chain (new_node, aggvals);
3443 for (av = aggvals; av; av = av->next)
3444 new_node->maybe_create_reference (av->value, IPA_REF_ADDR, NULL);
3446 if (dump_file && (dump_flags & TDF_DETAILS))
3448 fprintf (dump_file, " the new node is %s/%i.\n",
3449 new_node->name (), new_node->order);
3450 if (known_contexts.exists ())
3452 for (i = 0; i < count ; i++)
3453 if (!known_contexts[i].useless_p ())
3455 fprintf (dump_file, " known ctx %i is ", i);
3456 known_contexts[i].dump (dump_file);
3459 if (aggvals)
3460 ipa_dump_agg_replacement_values (dump_file, aggvals);
3462 ipa_check_create_node_params ();
3463 update_profiling_info (node, new_node);
3464 new_info = IPA_NODE_REF (new_node);
3465 new_info->ipcp_orig_node = node;
3466 new_info->known_csts = known_csts;
3467 new_info->known_contexts = known_contexts;
3469 ipcp_discover_new_direct_edges (new_node, known_csts, known_contexts, aggvals);
3471 callers.release ();
3472 return new_node;
3475 /* Given a NODE, and a subset of its CALLERS, try to populate blanks slots in
3476 KNOWN_CSTS with constants that are also known for all of the CALLERS. */
3478 static void
3479 find_more_scalar_values_for_callers_subset (struct cgraph_node *node,
3480 vec<tree> known_csts,
3481 vec<cgraph_edge *> callers)
3483 struct ipa_node_params *info = IPA_NODE_REF (node);
3484 int i, count = ipa_get_param_count (info);
3486 for (i = 0; i < count ; i++)
3488 struct cgraph_edge *cs;
3489 tree newval = NULL_TREE;
3490 int j;
3491 bool first = true;
3493 if (ipa_get_scalar_lat (info, i)->bottom || known_csts[i])
3494 continue;
3496 FOR_EACH_VEC_ELT (callers, j, cs)
3498 struct ipa_jump_func *jump_func;
3499 tree t;
3501 if (i >= ipa_get_cs_argument_count (IPA_EDGE_REF (cs)))
3503 newval = NULL_TREE;
3504 break;
3506 jump_func = ipa_get_ith_jump_func (IPA_EDGE_REF (cs), i);
3507 t = ipa_value_from_jfunc (IPA_NODE_REF (cs->caller), jump_func);
3508 if (!t
3509 || (newval
3510 && !values_equal_for_ipcp_p (t, newval))
3511 || (!first && !newval))
3513 newval = NULL_TREE;
3514 break;
3516 else
3517 newval = t;
3518 first = false;
3521 if (newval)
3523 if (dump_file && (dump_flags & TDF_DETAILS))
3525 fprintf (dump_file, " adding an extra known scalar value ");
3526 print_ipcp_constant_value (dump_file, newval);
3527 fprintf (dump_file, " for ");
3528 ipa_dump_param (dump_file, info, i);
3529 fprintf (dump_file, "\n");
3532 known_csts[i] = newval;
3537 /* Given a NODE and a subset of its CALLERS, try to populate plank slots in
3538 KNOWN_CONTEXTS with polymorphic contexts that are also known for all of the
3539 CALLERS. */
3541 static void
3542 find_more_contexts_for_caller_subset (cgraph_node *node,
3543 vec<ipa_polymorphic_call_context>
3544 *known_contexts,
3545 vec<cgraph_edge *> callers)
3547 ipa_node_params *info = IPA_NODE_REF (node);
3548 int i, count = ipa_get_param_count (info);
3550 for (i = 0; i < count ; i++)
3552 cgraph_edge *cs;
3554 if (ipa_get_poly_ctx_lat (info, i)->bottom
3555 || (known_contexts->exists ()
3556 && !(*known_contexts)[i].useless_p ()))
3557 continue;
3559 ipa_polymorphic_call_context newval;
3560 bool first = true;
3561 int j;
3563 FOR_EACH_VEC_ELT (callers, j, cs)
3565 if (i >= ipa_get_cs_argument_count (IPA_EDGE_REF (cs)))
3566 return;
3567 ipa_jump_func *jfunc = ipa_get_ith_jump_func (IPA_EDGE_REF (cs),
3569 ipa_polymorphic_call_context ctx;
3570 ctx = ipa_context_from_jfunc (IPA_NODE_REF (cs->caller), cs, i,
3571 jfunc);
3572 if (first)
3574 newval = ctx;
3575 first = false;
3577 else
3578 newval.meet_with (ctx);
3579 if (newval.useless_p ())
3580 break;
3583 if (!newval.useless_p ())
3585 if (dump_file && (dump_flags & TDF_DETAILS))
3587 fprintf (dump_file, " adding an extra known polymorphic "
3588 "context ");
3589 print_ipcp_constant_value (dump_file, newval);
3590 fprintf (dump_file, " for ");
3591 ipa_dump_param (dump_file, info, i);
3592 fprintf (dump_file, "\n");
3595 if (!known_contexts->exists ())
3596 known_contexts->safe_grow_cleared (ipa_get_param_count (info));
3597 (*known_contexts)[i] = newval;
3603 /* Go through PLATS and create a vector of values consisting of values and
3604 offsets (minus OFFSET) of lattices that contain only a single value. */
3606 static vec<ipa_agg_jf_item>
3607 copy_plats_to_inter (struct ipcp_param_lattices *plats, HOST_WIDE_INT offset)
3609 vec<ipa_agg_jf_item> res = vNULL;
3611 if (!plats->aggs || plats->aggs_contain_variable || plats->aggs_bottom)
3612 return vNULL;
3614 for (struct ipcp_agg_lattice *aglat = plats->aggs; aglat; aglat = aglat->next)
3615 if (aglat->is_single_const ())
3617 struct ipa_agg_jf_item ti;
3618 ti.offset = aglat->offset - offset;
3619 ti.value = aglat->values->value;
3620 res.safe_push (ti);
3622 return res;
3625 /* Intersect all values in INTER with single value lattices in PLATS (while
3626 subtracting OFFSET). */
3628 static void
3629 intersect_with_plats (struct ipcp_param_lattices *plats,
3630 vec<ipa_agg_jf_item> *inter,
3631 HOST_WIDE_INT offset)
3633 struct ipcp_agg_lattice *aglat;
3634 struct ipa_agg_jf_item *item;
3635 int k;
3637 if (!plats->aggs || plats->aggs_contain_variable || plats->aggs_bottom)
3639 inter->release ();
3640 return;
3643 aglat = plats->aggs;
3644 FOR_EACH_VEC_ELT (*inter, k, item)
3646 bool found = false;
3647 if (!item->value)
3648 continue;
3649 while (aglat)
3651 if (aglat->offset - offset > item->offset)
3652 break;
3653 if (aglat->offset - offset == item->offset)
3655 gcc_checking_assert (item->value);
3656 if (values_equal_for_ipcp_p (item->value, aglat->values->value))
3657 found = true;
3658 break;
3660 aglat = aglat->next;
3662 if (!found)
3663 item->value = NULL_TREE;
3667 /* Copy agggregate replacement values of NODE (which is an IPA-CP clone) to the
3668 vector result while subtracting OFFSET from the individual value offsets. */
3670 static vec<ipa_agg_jf_item>
3671 agg_replacements_to_vector (struct cgraph_node *node, int index,
3672 HOST_WIDE_INT offset)
3674 struct ipa_agg_replacement_value *av;
3675 vec<ipa_agg_jf_item> res = vNULL;
3677 for (av = ipa_get_agg_replacements_for_node (node); av; av = av->next)
3678 if (av->index == index
3679 && (av->offset - offset) >= 0)
3681 struct ipa_agg_jf_item item;
3682 gcc_checking_assert (av->value);
3683 item.offset = av->offset - offset;
3684 item.value = av->value;
3685 res.safe_push (item);
3688 return res;
3691 /* Intersect all values in INTER with those that we have already scheduled to
3692 be replaced in parameter number INDEX of NODE, which is an IPA-CP clone
3693 (while subtracting OFFSET). */
3695 static void
3696 intersect_with_agg_replacements (struct cgraph_node *node, int index,
3697 vec<ipa_agg_jf_item> *inter,
3698 HOST_WIDE_INT offset)
3700 struct ipa_agg_replacement_value *srcvals;
3701 struct ipa_agg_jf_item *item;
3702 int i;
3704 srcvals = ipa_get_agg_replacements_for_node (node);
3705 if (!srcvals)
3707 inter->release ();
3708 return;
3711 FOR_EACH_VEC_ELT (*inter, i, item)
3713 struct ipa_agg_replacement_value *av;
3714 bool found = false;
3715 if (!item->value)
3716 continue;
3717 for (av = srcvals; av; av = av->next)
3719 gcc_checking_assert (av->value);
3720 if (av->index == index
3721 && av->offset - offset == item->offset)
3723 if (values_equal_for_ipcp_p (item->value, av->value))
3724 found = true;
3725 break;
3728 if (!found)
3729 item->value = NULL_TREE;
3733 /* Intersect values in INTER with aggregate values that come along edge CS to
3734 parameter number INDEX and return it. If INTER does not actually exist yet,
3735 copy all incoming values to it. If we determine we ended up with no values
3736 whatsoever, return a released vector. */
3738 static vec<ipa_agg_jf_item>
3739 intersect_aggregates_with_edge (struct cgraph_edge *cs, int index,
3740 vec<ipa_agg_jf_item> inter)
3742 struct ipa_jump_func *jfunc;
3743 jfunc = ipa_get_ith_jump_func (IPA_EDGE_REF (cs), index);
3744 if (jfunc->type == IPA_JF_PASS_THROUGH
3745 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
3747 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3748 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
3750 if (caller_info->ipcp_orig_node)
3752 struct cgraph_node *orig_node = caller_info->ipcp_orig_node;
3753 struct ipcp_param_lattices *orig_plats;
3754 orig_plats = ipa_get_parm_lattices (IPA_NODE_REF (orig_node),
3755 src_idx);
3756 if (agg_pass_through_permissible_p (orig_plats, jfunc))
3758 if (!inter.exists ())
3759 inter = agg_replacements_to_vector (cs->caller, src_idx, 0);
3760 else
3761 intersect_with_agg_replacements (cs->caller, src_idx,
3762 &inter, 0);
3764 else
3766 inter.release ();
3767 return vNULL;
3770 else
3772 struct ipcp_param_lattices *src_plats;
3773 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
3774 if (agg_pass_through_permissible_p (src_plats, jfunc))
3776 /* Currently we do not produce clobber aggregate jump
3777 functions, adjust when we do. */
3778 gcc_checking_assert (!jfunc->agg.items);
3779 if (!inter.exists ())
3780 inter = copy_plats_to_inter (src_plats, 0);
3781 else
3782 intersect_with_plats (src_plats, &inter, 0);
3784 else
3786 inter.release ();
3787 return vNULL;
3791 else if (jfunc->type == IPA_JF_ANCESTOR
3792 && ipa_get_jf_ancestor_agg_preserved (jfunc))
3794 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3795 int src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
3796 struct ipcp_param_lattices *src_plats;
3797 HOST_WIDE_INT delta = ipa_get_jf_ancestor_offset (jfunc);
3799 if (caller_info->ipcp_orig_node)
3801 if (!inter.exists ())
3802 inter = agg_replacements_to_vector (cs->caller, src_idx, delta);
3803 else
3804 intersect_with_agg_replacements (cs->caller, src_idx, &inter,
3805 delta);
3807 else
3809 src_plats = ipa_get_parm_lattices (caller_info, src_idx);;
3810 /* Currently we do not produce clobber aggregate jump
3811 functions, adjust when we do. */
3812 gcc_checking_assert (!src_plats->aggs || !jfunc->agg.items);
3813 if (!inter.exists ())
3814 inter = copy_plats_to_inter (src_plats, delta);
3815 else
3816 intersect_with_plats (src_plats, &inter, delta);
3819 else if (jfunc->agg.items)
3821 struct ipa_agg_jf_item *item;
3822 int k;
3824 if (!inter.exists ())
3825 for (unsigned i = 0; i < jfunc->agg.items->length (); i++)
3826 inter.safe_push ((*jfunc->agg.items)[i]);
3827 else
3828 FOR_EACH_VEC_ELT (inter, k, item)
3830 int l = 0;
3831 bool found = false;;
3833 if (!item->value)
3834 continue;
3836 while ((unsigned) l < jfunc->agg.items->length ())
3838 struct ipa_agg_jf_item *ti;
3839 ti = &(*jfunc->agg.items)[l];
3840 if (ti->offset > item->offset)
3841 break;
3842 if (ti->offset == item->offset)
3844 gcc_checking_assert (ti->value);
3845 if (values_equal_for_ipcp_p (item->value,
3846 ti->value))
3847 found = true;
3848 break;
3850 l++;
3852 if (!found)
3853 item->value = NULL;
3856 else
3858 inter.release ();
3859 return vec<ipa_agg_jf_item>();
3861 return inter;
3864 /* Look at edges in CALLERS and collect all known aggregate values that arrive
3865 from all of them. */
3867 static struct ipa_agg_replacement_value *
3868 find_aggregate_values_for_callers_subset (struct cgraph_node *node,
3869 vec<cgraph_edge *> callers)
3871 struct ipa_node_params *dest_info = IPA_NODE_REF (node);
3872 struct ipa_agg_replacement_value *res;
3873 struct ipa_agg_replacement_value **tail = &res;
3874 struct cgraph_edge *cs;
3875 int i, j, count = ipa_get_param_count (dest_info);
3877 FOR_EACH_VEC_ELT (callers, j, cs)
3879 int c = ipa_get_cs_argument_count (IPA_EDGE_REF (cs));
3880 if (c < count)
3881 count = c;
3884 for (i = 0; i < count ; i++)
3886 struct cgraph_edge *cs;
3887 vec<ipa_agg_jf_item> inter = vNULL;
3888 struct ipa_agg_jf_item *item;
3889 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (dest_info, i);
3890 int j;
3892 /* Among other things, the following check should deal with all by_ref
3893 mismatches. */
3894 if (plats->aggs_bottom)
3895 continue;
3897 FOR_EACH_VEC_ELT (callers, j, cs)
3899 inter = intersect_aggregates_with_edge (cs, i, inter);
3901 if (!inter.exists ())
3902 goto next_param;
3905 FOR_EACH_VEC_ELT (inter, j, item)
3907 struct ipa_agg_replacement_value *v;
3909 if (!item->value)
3910 continue;
3912 v = ggc_alloc<ipa_agg_replacement_value> ();
3913 v->index = i;
3914 v->offset = item->offset;
3915 v->value = item->value;
3916 v->by_ref = plats->aggs_by_ref;
3917 *tail = v;
3918 tail = &v->next;
3921 next_param:
3922 if (inter.exists ())
3923 inter.release ();
3925 *tail = NULL;
3926 return res;
3929 /* Turn KNOWN_AGGS into a list of aggreate replacement values. */
3931 static struct ipa_agg_replacement_value *
3932 known_aggs_to_agg_replacement_list (vec<ipa_agg_jump_function> known_aggs)
3934 struct ipa_agg_replacement_value *res;
3935 struct ipa_agg_replacement_value **tail = &res;
3936 struct ipa_agg_jump_function *aggjf;
3937 struct ipa_agg_jf_item *item;
3938 int i, j;
3940 FOR_EACH_VEC_ELT (known_aggs, i, aggjf)
3941 FOR_EACH_VEC_SAFE_ELT (aggjf->items, j, item)
3943 struct ipa_agg_replacement_value *v;
3944 v = ggc_alloc<ipa_agg_replacement_value> ();
3945 v->index = i;
3946 v->offset = item->offset;
3947 v->value = item->value;
3948 v->by_ref = aggjf->by_ref;
3949 *tail = v;
3950 tail = &v->next;
3952 *tail = NULL;
3953 return res;
3956 /* Determine whether CS also brings all scalar values that the NODE is
3957 specialized for. */
3959 static bool
3960 cgraph_edge_brings_all_scalars_for_node (struct cgraph_edge *cs,
3961 struct cgraph_node *node)
3963 struct ipa_node_params *dest_info = IPA_NODE_REF (node);
3964 int count = ipa_get_param_count (dest_info);
3965 struct ipa_node_params *caller_info;
3966 struct ipa_edge_args *args;
3967 int i;
3969 caller_info = IPA_NODE_REF (cs->caller);
3970 args = IPA_EDGE_REF (cs);
3971 for (i = 0; i < count; i++)
3973 struct ipa_jump_func *jump_func;
3974 tree val, t;
3976 val = dest_info->known_csts[i];
3977 if (!val)
3978 continue;
3980 if (i >= ipa_get_cs_argument_count (args))
3981 return false;
3982 jump_func = ipa_get_ith_jump_func (args, i);
3983 t = ipa_value_from_jfunc (caller_info, jump_func);
3984 if (!t || !values_equal_for_ipcp_p (val, t))
3985 return false;
3987 return true;
3990 /* Determine whether CS also brings all aggregate values that NODE is
3991 specialized for. */
3992 static bool
3993 cgraph_edge_brings_all_agg_vals_for_node (struct cgraph_edge *cs,
3994 struct cgraph_node *node)
3996 struct ipa_node_params *orig_caller_info = IPA_NODE_REF (cs->caller);
3997 struct ipa_node_params *orig_node_info;
3998 struct ipa_agg_replacement_value *aggval;
3999 int i, ec, count;
4001 aggval = ipa_get_agg_replacements_for_node (node);
4002 if (!aggval)
4003 return true;
4005 count = ipa_get_param_count (IPA_NODE_REF (node));
4006 ec = ipa_get_cs_argument_count (IPA_EDGE_REF (cs));
4007 if (ec < count)
4008 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4009 if (aggval->index >= ec)
4010 return false;
4012 orig_node_info = IPA_NODE_REF (IPA_NODE_REF (node)->ipcp_orig_node);
4013 if (orig_caller_info->ipcp_orig_node)
4014 orig_caller_info = IPA_NODE_REF (orig_caller_info->ipcp_orig_node);
4016 for (i = 0; i < count; i++)
4018 static vec<ipa_agg_jf_item> values = vec<ipa_agg_jf_item>();
4019 struct ipcp_param_lattices *plats;
4020 bool interesting = false;
4021 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4022 if (aggval->index == i)
4024 interesting = true;
4025 break;
4027 if (!interesting)
4028 continue;
4030 plats = ipa_get_parm_lattices (orig_node_info, aggval->index);
4031 if (plats->aggs_bottom)
4032 return false;
4034 values = intersect_aggregates_with_edge (cs, i, values);
4035 if (!values.exists ())
4036 return false;
4038 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4039 if (aggval->index == i)
4041 struct ipa_agg_jf_item *item;
4042 int j;
4043 bool found = false;
4044 FOR_EACH_VEC_ELT (values, j, item)
4045 if (item->value
4046 && item->offset == av->offset
4047 && values_equal_for_ipcp_p (item->value, av->value))
4049 found = true;
4050 break;
4052 if (!found)
4054 values.release ();
4055 return false;
4059 return true;
4062 /* Given an original NODE and a VAL for which we have already created a
4063 specialized clone, look whether there are incoming edges that still lead
4064 into the old node but now also bring the requested value and also conform to
4065 all other criteria such that they can be redirected the special node.
4066 This function can therefore redirect the final edge in a SCC. */
4068 template <typename valtype>
4069 static void
4070 perhaps_add_new_callers (cgraph_node *node, ipcp_value<valtype> *val)
4072 ipcp_value_source<valtype> *src;
4073 gcov_type redirected_sum = 0;
4075 for (src = val->sources; src; src = src->next)
4077 struct cgraph_edge *cs = src->cs;
4078 while (cs)
4080 if (cgraph_edge_brings_value_p (cs, src, node)
4081 && cgraph_edge_brings_all_scalars_for_node (cs, val->spec_node)
4082 && cgraph_edge_brings_all_agg_vals_for_node (cs, val->spec_node))
4084 if (dump_file)
4085 fprintf (dump_file, " - adding an extra caller %s/%i"
4086 " of %s/%i\n",
4087 xstrdup_for_dump (cs->caller->name ()),
4088 cs->caller->order,
4089 xstrdup_for_dump (val->spec_node->name ()),
4090 val->spec_node->order);
4092 cs->redirect_callee_duplicating_thunks (val->spec_node);
4093 val->spec_node->expand_all_artificial_thunks ();
4094 redirected_sum += cs->count;
4096 cs = get_next_cgraph_edge_clone (cs);
4100 if (redirected_sum)
4101 update_specialized_profile (val->spec_node, node, redirected_sum);
4104 /* Return true if KNOWN_CONTEXTS contain at least one useful context. */
4106 static bool
4107 known_contexts_useful_p (vec<ipa_polymorphic_call_context> known_contexts)
4109 ipa_polymorphic_call_context *ctx;
4110 int i;
4112 FOR_EACH_VEC_ELT (known_contexts, i, ctx)
4113 if (!ctx->useless_p ())
4114 return true;
4115 return false;
4118 /* Return a copy of KNOWN_CSTS if it is not empty, otherwise return vNULL. */
4120 static vec<ipa_polymorphic_call_context>
4121 copy_useful_known_contexts (vec<ipa_polymorphic_call_context> known_contexts)
4123 if (known_contexts_useful_p (known_contexts))
4124 return known_contexts.copy ();
4125 else
4126 return vNULL;
4129 /* Copy KNOWN_CSTS and modify the copy according to VAL and INDEX. If
4130 non-empty, replace KNOWN_CONTEXTS with its copy too. */
4132 static void
4133 modify_known_vectors_with_val (vec<tree> *known_csts,
4134 vec<ipa_polymorphic_call_context> *known_contexts,
4135 ipcp_value<tree> *val,
4136 int index)
4138 *known_csts = known_csts->copy ();
4139 *known_contexts = copy_useful_known_contexts (*known_contexts);
4140 (*known_csts)[index] = val->value;
4143 /* Replace KNOWN_CSTS with its copy. Also copy KNOWN_CONTEXTS and modify the
4144 copy according to VAL and INDEX. */
4146 static void
4147 modify_known_vectors_with_val (vec<tree> *known_csts,
4148 vec<ipa_polymorphic_call_context> *known_contexts,
4149 ipcp_value<ipa_polymorphic_call_context> *val,
4150 int index)
4152 *known_csts = known_csts->copy ();
4153 *known_contexts = known_contexts->copy ();
4154 (*known_contexts)[index] = val->value;
4157 /* Return true if OFFSET indicates this was not an aggregate value or there is
4158 a replacement equivalent to VALUE, INDEX and OFFSET among those in the
4159 AGGVALS list. */
4161 DEBUG_FUNCTION bool
4162 ipcp_val_agg_replacement_ok_p (ipa_agg_replacement_value *aggvals,
4163 int index, HOST_WIDE_INT offset, tree value)
4165 if (offset == -1)
4166 return true;
4168 while (aggvals)
4170 if (aggvals->index == index
4171 && aggvals->offset == offset
4172 && values_equal_for_ipcp_p (aggvals->value, value))
4173 return true;
4174 aggvals = aggvals->next;
4176 return false;
4179 /* Return true if offset is minus one because source of a polymorphic contect
4180 cannot be an aggregate value. */
4182 DEBUG_FUNCTION bool
4183 ipcp_val_agg_replacement_ok_p (ipa_agg_replacement_value *,
4184 int , HOST_WIDE_INT offset,
4185 ipa_polymorphic_call_context)
4187 return offset == -1;
4190 /* Decide wheter to create a special version of NODE for value VAL of parameter
4191 at the given INDEX. If OFFSET is -1, the value is for the parameter itself,
4192 otherwise it is stored at the given OFFSET of the parameter. KNOWN_CSTS,
4193 KNOWN_CONTEXTS and KNOWN_AGGS describe the other already known values. */
4195 template <typename valtype>
4196 static bool
4197 decide_about_value (struct cgraph_node *node, int index, HOST_WIDE_INT offset,
4198 ipcp_value<valtype> *val, vec<tree> known_csts,
4199 vec<ipa_polymorphic_call_context> known_contexts)
4201 struct ipa_agg_replacement_value *aggvals;
4202 int freq_sum, caller_count;
4203 gcov_type count_sum;
4204 vec<cgraph_edge *> callers;
4206 if (val->spec_node)
4208 perhaps_add_new_callers (node, val);
4209 return false;
4211 else if (val->local_size_cost + overall_size > max_new_size)
4213 if (dump_file && (dump_flags & TDF_DETAILS))
4214 fprintf (dump_file, " Ignoring candidate value because "
4215 "max_new_size would be reached with %li.\n",
4216 val->local_size_cost + overall_size);
4217 return false;
4219 else if (!get_info_about_necessary_edges (val, node, &freq_sum, &count_sum,
4220 &caller_count))
4221 return false;
4223 if (dump_file && (dump_flags & TDF_DETAILS))
4225 fprintf (dump_file, " - considering value ");
4226 print_ipcp_constant_value (dump_file, val->value);
4227 fprintf (dump_file, " for ");
4228 ipa_dump_param (dump_file, IPA_NODE_REF (node), index);
4229 if (offset != -1)
4230 fprintf (dump_file, ", offset: " HOST_WIDE_INT_PRINT_DEC, offset);
4231 fprintf (dump_file, " (caller_count: %i)\n", caller_count);
4234 if (!good_cloning_opportunity_p (node, val->local_time_benefit,
4235 freq_sum, count_sum,
4236 val->local_size_cost)
4237 && !good_cloning_opportunity_p (node,
4238 val->local_time_benefit
4239 + val->prop_time_benefit,
4240 freq_sum, count_sum,
4241 val->local_size_cost
4242 + val->prop_size_cost))
4243 return false;
4245 if (dump_file)
4246 fprintf (dump_file, " Creating a specialized node of %s/%i.\n",
4247 node->name (), node->order);
4249 callers = gather_edges_for_value (val, node, caller_count);
4250 if (offset == -1)
4251 modify_known_vectors_with_val (&known_csts, &known_contexts, val, index);
4252 else
4254 known_csts = known_csts.copy ();
4255 known_contexts = copy_useful_known_contexts (known_contexts);
4257 find_more_scalar_values_for_callers_subset (node, known_csts, callers);
4258 find_more_contexts_for_caller_subset (node, &known_contexts, callers);
4259 aggvals = find_aggregate_values_for_callers_subset (node, callers);
4260 gcc_checking_assert (ipcp_val_agg_replacement_ok_p (aggvals, index,
4261 offset, val->value));
4262 val->spec_node = create_specialized_node (node, known_csts, known_contexts,
4263 aggvals, callers);
4264 overall_size += val->local_size_cost;
4266 /* TODO: If for some lattice there is only one other known value
4267 left, make a special node for it too. */
4269 return true;
4272 /* Decide whether and what specialized clones of NODE should be created. */
4274 static bool
4275 decide_whether_version_node (struct cgraph_node *node)
4277 struct ipa_node_params *info = IPA_NODE_REF (node);
4278 int i, count = ipa_get_param_count (info);
4279 vec<tree> known_csts;
4280 vec<ipa_polymorphic_call_context> known_contexts;
4281 vec<ipa_agg_jump_function> known_aggs = vNULL;
4282 bool ret = false;
4284 if (count == 0)
4285 return false;
4287 if (dump_file && (dump_flags & TDF_DETAILS))
4288 fprintf (dump_file, "\nEvaluating opportunities for %s/%i.\n",
4289 node->name (), node->order);
4291 gather_context_independent_values (info, &known_csts, &known_contexts,
4292 info->do_clone_for_all_contexts ? &known_aggs
4293 : NULL, NULL);
4295 for (i = 0; i < count ;i++)
4297 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4298 ipcp_lattice<tree> *lat = &plats->itself;
4299 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
4301 if (!lat->bottom
4302 && !known_csts[i])
4304 ipcp_value<tree> *val;
4305 for (val = lat->values; val; val = val->next)
4306 ret |= decide_about_value (node, i, -1, val, known_csts,
4307 known_contexts);
4310 if (!plats->aggs_bottom)
4312 struct ipcp_agg_lattice *aglat;
4313 ipcp_value<tree> *val;
4314 for (aglat = plats->aggs; aglat; aglat = aglat->next)
4315 if (!aglat->bottom && aglat->values
4316 /* If the following is false, the one value is in
4317 known_aggs. */
4318 && (plats->aggs_contain_variable
4319 || !aglat->is_single_const ()))
4320 for (val = aglat->values; val; val = val->next)
4321 ret |= decide_about_value (node, i, aglat->offset, val,
4322 known_csts, known_contexts);
4325 if (!ctxlat->bottom
4326 && known_contexts[i].useless_p ())
4328 ipcp_value<ipa_polymorphic_call_context> *val;
4329 for (val = ctxlat->values; val; val = val->next)
4330 ret |= decide_about_value (node, i, -1, val, known_csts,
4331 known_contexts);
4334 info = IPA_NODE_REF (node);
4337 if (info->do_clone_for_all_contexts)
4339 struct cgraph_node *clone;
4340 vec<cgraph_edge *> callers;
4342 if (dump_file)
4343 fprintf (dump_file, " - Creating a specialized node of %s/%i "
4344 "for all known contexts.\n", node->name (),
4345 node->order);
4347 callers = node->collect_callers ();
4349 if (!known_contexts_useful_p (known_contexts))
4351 known_contexts.release ();
4352 known_contexts = vNULL;
4354 clone = create_specialized_node (node, known_csts, known_contexts,
4355 known_aggs_to_agg_replacement_list (known_aggs),
4356 callers);
4357 info = IPA_NODE_REF (node);
4358 info->do_clone_for_all_contexts = false;
4359 IPA_NODE_REF (clone)->is_all_contexts_clone = true;
4360 for (i = 0; i < count ; i++)
4361 vec_free (known_aggs[i].items);
4362 known_aggs.release ();
4363 ret = true;
4365 else
4367 known_csts.release ();
4368 known_contexts.release ();
4371 return ret;
4374 /* Transitively mark all callees of NODE within the same SCC as not dead. */
4376 static void
4377 spread_undeadness (struct cgraph_node *node)
4379 struct cgraph_edge *cs;
4381 for (cs = node->callees; cs; cs = cs->next_callee)
4382 if (ipa_edge_within_scc (cs))
4384 struct cgraph_node *callee;
4385 struct ipa_node_params *info;
4387 callee = cs->callee->function_symbol (NULL);
4388 info = IPA_NODE_REF (callee);
4390 if (info->node_dead)
4392 info->node_dead = 0;
4393 spread_undeadness (callee);
4398 /* Return true if NODE has a caller from outside of its SCC that is not
4399 dead. Worker callback for cgraph_for_node_and_aliases. */
4401 static bool
4402 has_undead_caller_from_outside_scc_p (struct cgraph_node *node,
4403 void *data ATTRIBUTE_UNUSED)
4405 struct cgraph_edge *cs;
4407 for (cs = node->callers; cs; cs = cs->next_caller)
4408 if (cs->caller->thunk.thunk_p
4409 && cs->caller->call_for_symbol_thunks_and_aliases
4410 (has_undead_caller_from_outside_scc_p, NULL, true))
4411 return true;
4412 else if (!ipa_edge_within_scc (cs)
4413 && !IPA_NODE_REF (cs->caller)->node_dead)
4414 return true;
4415 return false;
4419 /* Identify nodes within the same SCC as NODE which are no longer needed
4420 because of new clones and will be removed as unreachable. */
4422 static void
4423 identify_dead_nodes (struct cgraph_node *node)
4425 struct cgraph_node *v;
4426 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4427 if (v->will_be_removed_from_program_if_no_direct_calls_p ()
4428 && !v->call_for_symbol_thunks_and_aliases
4429 (has_undead_caller_from_outside_scc_p, NULL, true))
4430 IPA_NODE_REF (v)->node_dead = 1;
4432 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4433 if (!IPA_NODE_REF (v)->node_dead)
4434 spread_undeadness (v);
4436 if (dump_file && (dump_flags & TDF_DETAILS))
4438 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4439 if (IPA_NODE_REF (v)->node_dead)
4440 fprintf (dump_file, " Marking node as dead: %s/%i.\n",
4441 v->name (), v->order);
4445 /* The decision stage. Iterate over the topological order of call graph nodes
4446 TOPO and make specialized clones if deemed beneficial. */
4448 static void
4449 ipcp_decision_stage (struct ipa_topo_info *topo)
4451 int i;
4453 if (dump_file)
4454 fprintf (dump_file, "\nIPA decision stage:\n\n");
4456 for (i = topo->nnodes - 1; i >= 0; i--)
4458 struct cgraph_node *node = topo->order[i];
4459 bool change = false, iterate = true;
4461 while (iterate)
4463 struct cgraph_node *v;
4464 iterate = false;
4465 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4466 if (v->has_gimple_body_p ()
4467 && ipcp_versionable_function_p (v))
4468 iterate |= decide_whether_version_node (v);
4470 change |= iterate;
4472 if (change)
4473 identify_dead_nodes (node);
4477 /* Look up all alignment information that we have discovered and copy it over
4478 to the transformation summary. */
4480 static void
4481 ipcp_store_alignment_results (void)
4483 cgraph_node *node;
4485 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
4487 ipa_node_params *info = IPA_NODE_REF (node);
4488 bool dumped_sth = false;
4489 bool found_useful_result = false;
4491 if (!opt_for_fn (node->decl, flag_ipa_cp_alignment))
4493 if (dump_file)
4494 fprintf (dump_file, "Not considering %s for alignment discovery "
4495 "and propagate; -fipa-cp-alignment: disabled.\n",
4496 node->name ());
4497 continue;
4500 if (info->ipcp_orig_node)
4501 info = IPA_NODE_REF (info->ipcp_orig_node);
4503 unsigned count = ipa_get_param_count (info);
4504 for (unsigned i = 0; i < count ; i++)
4506 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4507 if (!plats->alignment.bottom_p ()
4508 && !plats->alignment.top_p ())
4510 gcc_checking_assert (plats->alignment.align > 0);
4511 found_useful_result = true;
4512 break;
4515 if (!found_useful_result)
4516 continue;
4518 ipcp_grow_transformations_if_necessary ();
4519 ipcp_transformation_summary *ts = ipcp_get_transformation_summary (node);
4520 vec_safe_reserve_exact (ts->alignments, count);
4522 for (unsigned i = 0; i < count ; i++)
4524 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4525 ipa_alignment al;
4527 if (!plats->alignment.bottom_p ()
4528 && !plats->alignment.top_p ())
4530 al.known = true;
4531 al.align = plats->alignment.align;
4532 al.misalign = plats->alignment.misalign;
4534 else
4535 al.known = false;
4537 ts->alignments->quick_push (al);
4538 if (!dump_file || !al.known)
4539 continue;
4540 if (!dumped_sth)
4542 fprintf (dump_file, "Propagated alignment info for function %s/%i:\n",
4543 node->name (), node->order);
4544 dumped_sth = true;
4546 fprintf (dump_file, " param %i: align: %u, misalign: %u\n",
4547 i, al.align, al.misalign);
4552 /* The IPCP driver. */
4554 static unsigned int
4555 ipcp_driver (void)
4557 struct cgraph_2edge_hook_list *edge_duplication_hook_holder;
4558 struct cgraph_edge_hook_list *edge_removal_hook_holder;
4559 struct ipa_topo_info topo;
4561 ipa_check_create_node_params ();
4562 ipa_check_create_edge_args ();
4563 grow_edge_clone_vectors ();
4564 edge_duplication_hook_holder =
4565 symtab->add_edge_duplication_hook (&ipcp_edge_duplication_hook, NULL);
4566 edge_removal_hook_holder =
4567 symtab->add_edge_removal_hook (&ipcp_edge_removal_hook, NULL);
4569 if (dump_file)
4571 fprintf (dump_file, "\nIPA structures before propagation:\n");
4572 if (dump_flags & TDF_DETAILS)
4573 ipa_print_all_params (dump_file);
4574 ipa_print_all_jump_functions (dump_file);
4577 /* Topological sort. */
4578 build_toporder_info (&topo);
4579 /* Do the interprocedural propagation. */
4580 ipcp_propagate_stage (&topo);
4581 /* Decide what constant propagation and cloning should be performed. */
4582 ipcp_decision_stage (&topo);
4583 /* Store results of alignment propagation. */
4584 ipcp_store_alignment_results ();
4586 /* Free all IPCP structures. */
4587 free_toporder_info (&topo);
4588 next_edge_clone.release ();
4589 prev_edge_clone.release ();
4590 symtab->remove_edge_removal_hook (edge_removal_hook_holder);
4591 symtab->remove_edge_duplication_hook (edge_duplication_hook_holder);
4592 ipa_free_all_structures_after_ipa_cp ();
4593 if (dump_file)
4594 fprintf (dump_file, "\nIPA constant propagation end\n");
4595 return 0;
4598 /* Initialization and computation of IPCP data structures. This is the initial
4599 intraprocedural analysis of functions, which gathers information to be
4600 propagated later on. */
4602 static void
4603 ipcp_generate_summary (void)
4605 struct cgraph_node *node;
4607 if (dump_file)
4608 fprintf (dump_file, "\nIPA constant propagation start:\n");
4609 ipa_register_cgraph_hooks ();
4611 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
4613 node->local.versionable
4614 = tree_versionable_function_p (node->decl);
4615 ipa_analyze_node (node);
4619 /* Write ipcp summary for nodes in SET. */
4621 static void
4622 ipcp_write_summary (void)
4624 ipa_prop_write_jump_functions ();
4627 /* Read ipcp summary. */
4629 static void
4630 ipcp_read_summary (void)
4632 ipa_prop_read_jump_functions ();
4635 namespace {
4637 const pass_data pass_data_ipa_cp =
4639 IPA_PASS, /* type */
4640 "cp", /* name */
4641 OPTGROUP_NONE, /* optinfo_flags */
4642 TV_IPA_CONSTANT_PROP, /* tv_id */
4643 0, /* properties_required */
4644 0, /* properties_provided */
4645 0, /* properties_destroyed */
4646 0, /* todo_flags_start */
4647 ( TODO_dump_symtab | TODO_remove_functions ), /* todo_flags_finish */
4650 class pass_ipa_cp : public ipa_opt_pass_d
4652 public:
4653 pass_ipa_cp (gcc::context *ctxt)
4654 : ipa_opt_pass_d (pass_data_ipa_cp, ctxt,
4655 ipcp_generate_summary, /* generate_summary */
4656 ipcp_write_summary, /* write_summary */
4657 ipcp_read_summary, /* read_summary */
4658 ipcp_write_transformation_summaries, /*
4659 write_optimization_summary */
4660 ipcp_read_transformation_summaries, /*
4661 read_optimization_summary */
4662 NULL, /* stmt_fixup */
4663 0, /* function_transform_todo_flags_start */
4664 ipcp_transform_function, /* function_transform */
4665 NULL) /* variable_transform */
4668 /* opt_pass methods: */
4669 virtual bool gate (function *)
4671 /* FIXME: We should remove the optimize check after we ensure we never run
4672 IPA passes when not optimizing. */
4673 return (flag_ipa_cp && optimize) || in_lto_p;
4676 virtual unsigned int execute (function *) { return ipcp_driver (); }
4678 }; // class pass_ipa_cp
4680 } // anon namespace
4682 ipa_opt_pass_d *
4683 make_pass_ipa_cp (gcc::context *ctxt)
4685 return new pass_ipa_cp (ctxt);
4688 /* Reset all state within ipa-cp.c so that we can rerun the compiler
4689 within the same process. For use by toplev::finalize. */
4691 void
4692 ipa_cp_c_finalize (void)
4694 max_count = 0;
4695 overall_size = 0;
4696 max_new_size = 0;