Add selftest for pretty-print.c
[official-gcc.git] / gcc / ipa-cp.c
blob4b7f6bbf31c66229372b0445280dbcc5d44e0703
1 /* Interprocedural constant propagation
2 Copyright (C) 2005-2016 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 "backend.h"
107 #include "tree.h"
108 #include "gimple-expr.h"
109 #include "predict.h"
110 #include "alloc-pool.h"
111 #include "tree-pass.h"
112 #include "cgraph.h"
113 #include "diagnostic.h"
114 #include "fold-const.h"
115 #include "gimple-fold.h"
116 #include "symbol-summary.h"
117 #include "ipa-prop.h"
118 #include "tree-pretty-print.h"
119 #include "tree-inline.h"
120 #include "params.h"
121 #include "ipa-inline.h"
122 #include "ipa-utils.h"
124 template <typename valtype> class ipcp_value;
126 /* Describes a particular source for an IPA-CP value. */
128 template <typename valtype>
129 class ipcp_value_source
131 public:
132 /* Aggregate offset of the source, negative if the source is scalar value of
133 the argument itself. */
134 HOST_WIDE_INT offset;
135 /* The incoming edge that brought the value. */
136 cgraph_edge *cs;
137 /* If the jump function that resulted into his value was a pass-through or an
138 ancestor, this is the ipcp_value of the caller from which the described
139 value has been derived. Otherwise it is NULL. */
140 ipcp_value<valtype> *val;
141 /* Next pointer in a linked list of sources of a value. */
142 ipcp_value_source *next;
143 /* If the jump function that resulted into his value was a pass-through or an
144 ancestor, this is the index of the parameter of the caller the jump
145 function references. */
146 int index;
149 /* Common ancestor for all ipcp_value instantiations. */
151 class ipcp_value_base
153 public:
154 /* Time benefit and size cost that specializing the function for this value
155 would bring about in this function alone. */
156 int local_time_benefit, local_size_cost;
157 /* Time benefit and size cost that specializing the function for this value
158 can bring about in it's callees (transitively). */
159 int prop_time_benefit, prop_size_cost;
162 /* Describes one particular value stored in struct ipcp_lattice. */
164 template <typename valtype>
165 class ipcp_value : public ipcp_value_base
167 public:
168 /* The actual value for the given parameter. */
169 valtype value;
170 /* The list of sources from which this value originates. */
171 ipcp_value_source <valtype> *sources;
172 /* Next pointers in a linked list of all values in a lattice. */
173 ipcp_value *next;
174 /* Next pointers in a linked list of values in a strongly connected component
175 of values. */
176 ipcp_value *scc_next;
177 /* Next pointers in a linked list of SCCs of values sorted topologically
178 according their sources. */
179 ipcp_value *topo_next;
180 /* A specialized node created for this value, NULL if none has been (so far)
181 created. */
182 cgraph_node *spec_node;
183 /* Depth first search number and low link for topological sorting of
184 values. */
185 int dfs, low_link;
186 /* True if this valye is currently on the topo-sort stack. */
187 bool on_stack;
189 void add_source (cgraph_edge *cs, ipcp_value *src_val, int src_idx,
190 HOST_WIDE_INT offset);
193 /* Lattice describing potential values of a formal parameter of a function, or
194 a part of an aggreagate. TOP is represented by a lattice with zero values
195 and with contains_variable and bottom flags cleared. BOTTOM is represented
196 by a lattice with the bottom flag set. In that case, values and
197 contains_variable flag should be disregarded. */
199 template <typename valtype>
200 class ipcp_lattice
202 public:
203 /* The list of known values and types in this lattice. Note that values are
204 not deallocated if a lattice is set to bottom because there may be value
205 sources referencing them. */
206 ipcp_value<valtype> *values;
207 /* Number of known values and types in this lattice. */
208 int values_count;
209 /* The lattice contains a variable component (in addition to values). */
210 bool contains_variable;
211 /* The value of the lattice is bottom (i.e. variable and unusable for any
212 propagation). */
213 bool bottom;
215 inline bool is_single_const ();
216 inline bool set_to_bottom ();
217 inline bool set_contains_variable ();
218 bool add_value (valtype newval, cgraph_edge *cs,
219 ipcp_value<valtype> *src_val = NULL,
220 int src_idx = 0, HOST_WIDE_INT offset = -1);
221 void print (FILE * f, bool dump_sources, bool dump_benefits);
224 /* Lattice of tree values with an offset to describe a part of an
225 aggregate. */
227 class ipcp_agg_lattice : public ipcp_lattice<tree>
229 public:
230 /* Offset that is being described by this lattice. */
231 HOST_WIDE_INT offset;
232 /* Size so that we don't have to re-compute it every time we traverse the
233 list. Must correspond to TYPE_SIZE of all lat values. */
234 HOST_WIDE_INT size;
235 /* Next element of the linked list. */
236 struct ipcp_agg_lattice *next;
239 /* Lattice of pointer alignment. Unlike the previous types of lattices, this
240 one is only capable of holding one value. */
242 class ipcp_alignment_lattice
244 public:
245 /* If bottom and top are both false, these two fields hold values as given by
246 ptr_info_def and get_pointer_alignment_1. */
247 unsigned align;
248 unsigned misalign;
250 inline bool bottom_p () const;
251 inline bool top_p () const;
252 inline bool set_to_bottom ();
253 bool meet_with (unsigned new_align, unsigned new_misalign);
254 bool meet_with (const ipcp_alignment_lattice &other, HOST_WIDE_INT offset);
255 void print (FILE * f);
256 private:
257 /* If set, this lattice is bottom and all other fields should be
258 disregarded. */
259 bool bottom;
260 /* If bottom and not_top are false, the lattice is TOP. If not_top is true,
261 the known alignment is stored in the fields align and misalign. The field
262 is negated so that memset to zero initializes the lattice to TOP
263 state. */
264 bool not_top;
266 bool meet_with_1 (unsigned new_align, unsigned new_misalign);
269 /* Structure containing lattices for a parameter itself and for pieces of
270 aggregates that are passed in the parameter or by a reference in a parameter
271 plus some other useful flags. */
273 class ipcp_param_lattices
275 public:
276 /* Lattice describing the value of the parameter itself. */
277 ipcp_lattice<tree> itself;
278 /* Lattice describing the polymorphic contexts of a parameter. */
279 ipcp_lattice<ipa_polymorphic_call_context> ctxlat;
280 /* Lattices describing aggregate parts. */
281 ipcp_agg_lattice *aggs;
282 /* Lattice describing known alignment. */
283 ipcp_alignment_lattice alignment;
284 /* Number of aggregate lattices */
285 int aggs_count;
286 /* True if aggregate data were passed by reference (as opposed to by
287 value). */
288 bool aggs_by_ref;
289 /* All aggregate lattices contain a variable component (in addition to
290 values). */
291 bool aggs_contain_variable;
292 /* The value of all aggregate lattices is bottom (i.e. variable and unusable
293 for any propagation). */
294 bool aggs_bottom;
296 /* There is a virtual call based on this parameter. */
297 bool virt_call;
300 /* Allocation pools for values and their sources in ipa-cp. */
302 object_allocator<ipcp_value<tree> > ipcp_cst_values_pool
303 ("IPA-CP constant values");
305 object_allocator<ipcp_value<ipa_polymorphic_call_context> >
306 ipcp_poly_ctx_values_pool ("IPA-CP polymorphic contexts");
308 object_allocator<ipcp_value_source<tree> > ipcp_sources_pool
309 ("IPA-CP value sources");
311 object_allocator<ipcp_agg_lattice> ipcp_agg_lattice_pool
312 ("IPA_CP aggregate lattices");
314 /* Maximal count found in program. */
316 static gcov_type max_count;
318 /* Original overall size of the program. */
320 static long overall_size, max_new_size;
322 /* Return the param lattices structure corresponding to the Ith formal
323 parameter of the function described by INFO. */
324 static inline struct ipcp_param_lattices *
325 ipa_get_parm_lattices (struct ipa_node_params *info, int i)
327 gcc_assert (i >= 0 && i < ipa_get_param_count (info));
328 gcc_checking_assert (!info->ipcp_orig_node);
329 gcc_checking_assert (info->lattices);
330 return &(info->lattices[i]);
333 /* Return the lattice corresponding to the scalar value of the Ith formal
334 parameter of the function described by INFO. */
335 static inline ipcp_lattice<tree> *
336 ipa_get_scalar_lat (struct ipa_node_params *info, int i)
338 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
339 return &plats->itself;
342 /* Return the lattice corresponding to the scalar value of the Ith formal
343 parameter of the function described by INFO. */
344 static inline ipcp_lattice<ipa_polymorphic_call_context> *
345 ipa_get_poly_ctx_lat (struct ipa_node_params *info, int i)
347 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
348 return &plats->ctxlat;
351 /* Return whether LAT is a lattice with a single constant and without an
352 undefined value. */
354 template <typename valtype>
355 inline bool
356 ipcp_lattice<valtype>::is_single_const ()
358 if (bottom || contains_variable || values_count != 1)
359 return false;
360 else
361 return true;
364 /* Print V which is extracted from a value in a lattice to F. */
366 static void
367 print_ipcp_constant_value (FILE * f, tree v)
369 if (TREE_CODE (v) == ADDR_EXPR
370 && TREE_CODE (TREE_OPERAND (v, 0)) == CONST_DECL)
372 fprintf (f, "& ");
373 print_generic_expr (f, DECL_INITIAL (TREE_OPERAND (v, 0)), 0);
375 else
376 print_generic_expr (f, v, 0);
379 /* Print V which is extracted from a value in a lattice to F. */
381 static void
382 print_ipcp_constant_value (FILE * f, ipa_polymorphic_call_context v)
384 v.dump(f, false);
387 /* Print a lattice LAT to F. */
389 template <typename valtype>
390 void
391 ipcp_lattice<valtype>::print (FILE * f, bool dump_sources, bool dump_benefits)
393 ipcp_value<valtype> *val;
394 bool prev = false;
396 if (bottom)
398 fprintf (f, "BOTTOM\n");
399 return;
402 if (!values_count && !contains_variable)
404 fprintf (f, "TOP\n");
405 return;
408 if (contains_variable)
410 fprintf (f, "VARIABLE");
411 prev = true;
412 if (dump_benefits)
413 fprintf (f, "\n");
416 for (val = values; val; val = val->next)
418 if (dump_benefits && prev)
419 fprintf (f, " ");
420 else if (!dump_benefits && prev)
421 fprintf (f, ", ");
422 else
423 prev = true;
425 print_ipcp_constant_value (f, val->value);
427 if (dump_sources)
429 ipcp_value_source<valtype> *s;
431 fprintf (f, " [from:");
432 for (s = val->sources; s; s = s->next)
433 fprintf (f, " %i(%i)", s->cs->caller->order,
434 s->cs->frequency);
435 fprintf (f, "]");
438 if (dump_benefits)
439 fprintf (f, " [loc_time: %i, loc_size: %i, "
440 "prop_time: %i, prop_size: %i]\n",
441 val->local_time_benefit, val->local_size_cost,
442 val->prop_time_benefit, val->prop_size_cost);
444 if (!dump_benefits)
445 fprintf (f, "\n");
448 /* Print alignment lattice to F. */
450 void
451 ipcp_alignment_lattice::print (FILE * f)
453 if (top_p ())
454 fprintf (f, " Alignment unknown (TOP)\n");
455 else if (bottom_p ())
456 fprintf (f, " Alignment unusable (BOTTOM)\n");
457 else
458 fprintf (f, " Alignment %u, misalignment %u\n", align, misalign);
461 /* Print all ipcp_lattices of all functions to F. */
463 static void
464 print_all_lattices (FILE * f, bool dump_sources, bool dump_benefits)
466 struct cgraph_node *node;
467 int i, count;
469 fprintf (f, "\nLattices:\n");
470 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
472 struct ipa_node_params *info;
474 info = IPA_NODE_REF (node);
475 fprintf (f, " Node: %s/%i:\n", node->name (),
476 node->order);
477 count = ipa_get_param_count (info);
478 for (i = 0; i < count; i++)
480 struct ipcp_agg_lattice *aglat;
481 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
482 fprintf (f, " param [%d]: ", i);
483 plats->itself.print (f, dump_sources, dump_benefits);
484 fprintf (f, " ctxs: ");
485 plats->ctxlat.print (f, dump_sources, dump_benefits);
486 plats->alignment.print (f);
487 if (plats->virt_call)
488 fprintf (f, " virt_call flag set\n");
490 if (plats->aggs_bottom)
492 fprintf (f, " AGGS BOTTOM\n");
493 continue;
495 if (plats->aggs_contain_variable)
496 fprintf (f, " AGGS VARIABLE\n");
497 for (aglat = plats->aggs; aglat; aglat = aglat->next)
499 fprintf (f, " %soffset " HOST_WIDE_INT_PRINT_DEC ": ",
500 plats->aggs_by_ref ? "ref " : "", aglat->offset);
501 aglat->print (f, dump_sources, dump_benefits);
507 /* Determine whether it is at all technically possible to create clones of NODE
508 and store this information in the ipa_node_params structure associated
509 with NODE. */
511 static void
512 determine_versionability (struct cgraph_node *node,
513 struct ipa_node_params *info)
515 const char *reason = NULL;
517 /* There are a number of generic reasons functions cannot be versioned. We
518 also cannot remove parameters if there are type attributes such as fnspec
519 present. */
520 if (node->alias || node->thunk.thunk_p)
521 reason = "alias or thunk";
522 else if (!node->local.versionable)
523 reason = "not a tree_versionable_function";
524 else if (node->get_availability () <= AVAIL_INTERPOSABLE)
525 reason = "insufficient body availability";
526 else if (!opt_for_fn (node->decl, optimize)
527 || !opt_for_fn (node->decl, flag_ipa_cp))
528 reason = "non-optimized function";
529 else if (lookup_attribute ("omp declare simd", DECL_ATTRIBUTES (node->decl)))
531 /* Ideally we should clone the SIMD clones themselves and create
532 vector copies of them, so IPA-cp and SIMD clones can happily
533 coexist, but that may not be worth the effort. */
534 reason = "function has SIMD clones";
536 /* Don't clone decls local to a comdat group; it breaks and for C++
537 decloned constructors, inlining is always better anyway. */
538 else if (node->comdat_local_p ())
539 reason = "comdat-local function";
541 if (reason && dump_file && !node->alias && !node->thunk.thunk_p)
542 fprintf (dump_file, "Function %s/%i is not versionable, reason: %s.\n",
543 node->name (), node->order, reason);
545 info->versionable = (reason == NULL);
548 /* Return true if it is at all technically possible to create clones of a
549 NODE. */
551 static bool
552 ipcp_versionable_function_p (struct cgraph_node *node)
554 return IPA_NODE_REF (node)->versionable;
557 /* Structure holding accumulated information about callers of a node. */
559 struct caller_statistics
561 gcov_type count_sum;
562 int n_calls, n_hot_calls, freq_sum;
565 /* Initialize fields of STAT to zeroes. */
567 static inline void
568 init_caller_stats (struct caller_statistics *stats)
570 stats->count_sum = 0;
571 stats->n_calls = 0;
572 stats->n_hot_calls = 0;
573 stats->freq_sum = 0;
576 /* Worker callback of cgraph_for_node_and_aliases accumulating statistics of
577 non-thunk incoming edges to NODE. */
579 static bool
580 gather_caller_stats (struct cgraph_node *node, void *data)
582 struct caller_statistics *stats = (struct caller_statistics *) data;
583 struct cgraph_edge *cs;
585 for (cs = node->callers; cs; cs = cs->next_caller)
586 if (!cs->caller->thunk.thunk_p)
588 stats->count_sum += cs->count;
589 stats->freq_sum += cs->frequency;
590 stats->n_calls++;
591 if (cs->maybe_hot_p ())
592 stats->n_hot_calls ++;
594 return false;
598 /* Return true if this NODE is viable candidate for cloning. */
600 static bool
601 ipcp_cloning_candidate_p (struct cgraph_node *node)
603 struct caller_statistics stats;
605 gcc_checking_assert (node->has_gimple_body_p ());
607 if (!opt_for_fn (node->decl, flag_ipa_cp_clone))
609 if (dump_file)
610 fprintf (dump_file, "Not considering %s for cloning; "
611 "-fipa-cp-clone disabled.\n",
612 node->name ());
613 return false;
616 if (node->optimize_for_size_p ())
618 if (dump_file)
619 fprintf (dump_file, "Not considering %s for cloning; "
620 "optimizing it for size.\n",
621 node->name ());
622 return false;
625 init_caller_stats (&stats);
626 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats, false);
628 if (inline_summaries->get (node)->self_size < stats.n_calls)
630 if (dump_file)
631 fprintf (dump_file, "Considering %s for cloning; code might shrink.\n",
632 node->name ());
633 return true;
636 /* When profile is available and function is hot, propagate into it even if
637 calls seems cold; constant propagation can improve function's speed
638 significantly. */
639 if (max_count)
641 if (stats.count_sum > node->count * 90 / 100)
643 if (dump_file)
644 fprintf (dump_file, "Considering %s for cloning; "
645 "usually called directly.\n",
646 node->name ());
647 return true;
650 if (!stats.n_hot_calls)
652 if (dump_file)
653 fprintf (dump_file, "Not considering %s for cloning; no hot calls.\n",
654 node->name ());
655 return false;
657 if (dump_file)
658 fprintf (dump_file, "Considering %s for cloning.\n",
659 node->name ());
660 return true;
663 template <typename valtype>
664 class value_topo_info
666 public:
667 /* Head of the linked list of topologically sorted values. */
668 ipcp_value<valtype> *values_topo;
669 /* Stack for creating SCCs, represented by a linked list too. */
670 ipcp_value<valtype> *stack;
671 /* Counter driving the algorithm in add_val_to_toposort. */
672 int dfs_counter;
674 value_topo_info () : values_topo (NULL), stack (NULL), dfs_counter (0)
676 void add_val (ipcp_value<valtype> *cur_val);
677 void propagate_effects ();
680 /* Arrays representing a topological ordering of call graph nodes and a stack
681 of nodes used during constant propagation and also data required to perform
682 topological sort of values and propagation of benefits in the determined
683 order. */
685 class ipa_topo_info
687 public:
688 /* Array with obtained topological order of cgraph nodes. */
689 struct cgraph_node **order;
690 /* Stack of cgraph nodes used during propagation within SCC until all values
691 in the SCC stabilize. */
692 struct cgraph_node **stack;
693 int nnodes, stack_top;
695 value_topo_info<tree> constants;
696 value_topo_info<ipa_polymorphic_call_context> contexts;
698 ipa_topo_info () : order(NULL), stack(NULL), nnodes(0), stack_top(0),
699 constants ()
703 /* Allocate the arrays in TOPO and topologically sort the nodes into order. */
705 static void
706 build_toporder_info (struct ipa_topo_info *topo)
708 topo->order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
709 topo->stack = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
711 gcc_checking_assert (topo->stack_top == 0);
712 topo->nnodes = ipa_reduced_postorder (topo->order, true, true, NULL);
715 /* Free information about strongly connected components and the arrays in
716 TOPO. */
718 static void
719 free_toporder_info (struct ipa_topo_info *topo)
721 ipa_free_postorder_info ();
722 free (topo->order);
723 free (topo->stack);
726 /* Add NODE to the stack in TOPO, unless it is already there. */
728 static inline void
729 push_node_to_stack (struct ipa_topo_info *topo, struct cgraph_node *node)
731 struct ipa_node_params *info = IPA_NODE_REF (node);
732 if (info->node_enqueued)
733 return;
734 info->node_enqueued = 1;
735 topo->stack[topo->stack_top++] = node;
738 /* Pop a node from the stack in TOPO and return it or return NULL if the stack
739 is empty. */
741 static struct cgraph_node *
742 pop_node_from_stack (struct ipa_topo_info *topo)
744 if (topo->stack_top)
746 struct cgraph_node *node;
747 topo->stack_top--;
748 node = topo->stack[topo->stack_top];
749 IPA_NODE_REF (node)->node_enqueued = 0;
750 return node;
752 else
753 return NULL;
756 /* Set lattice LAT to bottom and return true if it previously was not set as
757 such. */
759 template <typename valtype>
760 inline bool
761 ipcp_lattice<valtype>::set_to_bottom ()
763 bool ret = !bottom;
764 bottom = true;
765 return ret;
768 /* Mark lattice as containing an unknown value and return true if it previously
769 was not marked as such. */
771 template <typename valtype>
772 inline bool
773 ipcp_lattice<valtype>::set_contains_variable ()
775 bool ret = !contains_variable;
776 contains_variable = true;
777 return ret;
780 /* Set all aggegate lattices in PLATS to bottom and return true if they were
781 not previously set as such. */
783 static inline bool
784 set_agg_lats_to_bottom (struct ipcp_param_lattices *plats)
786 bool ret = !plats->aggs_bottom;
787 plats->aggs_bottom = true;
788 return ret;
791 /* Mark all aggegate lattices in PLATS as containing an unknown value and
792 return true if they were not previously marked as such. */
794 static inline bool
795 set_agg_lats_contain_variable (struct ipcp_param_lattices *plats)
797 bool ret = !plats->aggs_contain_variable;
798 plats->aggs_contain_variable = true;
799 return ret;
802 /* Return true if alignment information in the lattice is yet unknown. */
804 bool
805 ipcp_alignment_lattice::top_p () const
807 return !bottom && !not_top;
810 /* Return true if alignment information in the lattice is known to be
811 unusable. */
813 bool
814 ipcp_alignment_lattice::bottom_p () const
816 return bottom;
819 /* Set alignment information in the lattice to bottom. Return true if it
820 previously was in a different state. */
822 bool
823 ipcp_alignment_lattice::set_to_bottom ()
825 if (bottom_p ())
826 return false;
827 bottom = true;
828 return true;
831 /* Meet the current value of the lattice with alignment described by NEW_ALIGN
832 and NEW_MISALIGN, assuming that we know the current value is neither TOP nor
833 BOTTOM. Return true if the value of lattice has changed. */
835 bool
836 ipcp_alignment_lattice::meet_with_1 (unsigned new_align, unsigned new_misalign)
838 gcc_checking_assert (new_align != 0);
839 if (align == new_align && misalign == new_misalign)
840 return false;
842 bool changed = false;
843 if (align > new_align)
845 align = new_align;
846 misalign = misalign % new_align;
847 changed = true;
849 if (misalign != (new_misalign % align))
851 int diff = abs ((int) misalign - (int) (new_misalign % align));
852 align = (unsigned) diff & -diff;
853 if (align)
854 misalign = misalign % align;
855 else
856 set_to_bottom ();
857 changed = true;
859 gcc_checking_assert (bottom_p () || align != 0);
860 return changed;
863 /* Meet the current value of the lattice with alignment described by NEW_ALIGN
864 and NEW_MISALIGN. Return true if the value of lattice has changed. */
866 bool
867 ipcp_alignment_lattice::meet_with (unsigned new_align, unsigned new_misalign)
869 gcc_assert (new_align != 0);
870 if (bottom_p ())
871 return false;
872 if (top_p ())
874 not_top = true;
875 align = new_align;
876 misalign = new_misalign;
877 return true;
879 return meet_with_1 (new_align, new_misalign);
882 /* Meet the current value of the lattice with OTHER, taking into account that
883 OFFSET has been added to the pointer value. Return true if the value of
884 lattice has changed. */
886 bool
887 ipcp_alignment_lattice::meet_with (const ipcp_alignment_lattice &other,
888 HOST_WIDE_INT offset)
890 if (other.bottom_p ())
891 return set_to_bottom ();
892 if (bottom_p () || other.top_p ())
893 return false;
895 unsigned adjusted_misalign = (other.misalign + offset) % other.align;
896 if (top_p ())
898 not_top = true;
899 align = other.align;
900 misalign = adjusted_misalign;
901 return true;
904 return meet_with_1 (other.align, adjusted_misalign);
907 /* Mark bot aggregate and scalar lattices as containing an unknown variable,
908 return true is any of them has not been marked as such so far. */
910 static inline bool
911 set_all_contains_variable (struct ipcp_param_lattices *plats)
913 bool ret;
914 ret = plats->itself.set_contains_variable ();
915 ret |= plats->ctxlat.set_contains_variable ();
916 ret |= set_agg_lats_contain_variable (plats);
917 ret |= plats->alignment.set_to_bottom ();
918 return ret;
921 /* Worker of call_for_symbol_thunks_and_aliases, increment the integer DATA
922 points to by the number of callers to NODE. */
924 static bool
925 count_callers (cgraph_node *node, void *data)
927 int *caller_count = (int *) data;
929 for (cgraph_edge *cs = node->callers; cs; cs = cs->next_caller)
930 /* Local thunks can be handled transparently, but if the thunk can not
931 be optimized out, count it as a real use. */
932 if (!cs->caller->thunk.thunk_p || !cs->caller->local.local)
933 ++*caller_count;
934 return false;
937 /* Worker of call_for_symbol_thunks_and_aliases, it is supposed to be called on
938 the one caller of some other node. Set the caller's corresponding flag. */
940 static bool
941 set_single_call_flag (cgraph_node *node, void *)
943 cgraph_edge *cs = node->callers;
944 /* Local thunks can be handled transparently, skip them. */
945 while (cs && cs->caller->thunk.thunk_p && cs->caller->local.local)
946 cs = cs->next_caller;
947 if (cs)
949 IPA_NODE_REF (cs->caller)->node_calling_single_call = true;
950 return true;
952 return false;
955 /* Initialize ipcp_lattices. */
957 static void
958 initialize_node_lattices (struct cgraph_node *node)
960 struct ipa_node_params *info = IPA_NODE_REF (node);
961 struct cgraph_edge *ie;
962 bool disable = false, variable = false;
963 int i;
965 gcc_checking_assert (node->has_gimple_body_p ());
966 if (cgraph_local_p (node))
968 int caller_count = 0;
969 node->call_for_symbol_thunks_and_aliases (count_callers, &caller_count,
970 true);
971 gcc_checking_assert (caller_count > 0);
972 if (caller_count == 1)
973 node->call_for_symbol_thunks_and_aliases (set_single_call_flag,
974 NULL, true);
976 else
978 /* When cloning is allowed, we can assume that externally visible
979 functions are not called. We will compensate this by cloning
980 later. */
981 if (ipcp_versionable_function_p (node)
982 && ipcp_cloning_candidate_p (node))
983 variable = true;
984 else
985 disable = true;
988 if (disable || variable)
990 for (i = 0; i < ipa_get_param_count (info) ; i++)
992 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
993 if (disable)
995 plats->itself.set_to_bottom ();
996 plats->ctxlat.set_to_bottom ();
997 set_agg_lats_to_bottom (plats);
998 plats->alignment.set_to_bottom ();
1000 else
1001 set_all_contains_variable (plats);
1003 if (dump_file && (dump_flags & TDF_DETAILS)
1004 && !node->alias && !node->thunk.thunk_p)
1005 fprintf (dump_file, "Marking all lattices of %s/%i as %s\n",
1006 node->name (), node->order,
1007 disable ? "BOTTOM" : "VARIABLE");
1010 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
1011 if (ie->indirect_info->polymorphic
1012 && ie->indirect_info->param_index >= 0)
1014 gcc_checking_assert (ie->indirect_info->param_index >= 0);
1015 ipa_get_parm_lattices (info,
1016 ie->indirect_info->param_index)->virt_call = 1;
1020 /* Return the result of a (possibly arithmetic) pass through jump function
1021 JFUNC on the constant value INPUT. Return NULL_TREE if that cannot be
1022 determined or be considered an interprocedural invariant. */
1024 static tree
1025 ipa_get_jf_pass_through_result (struct ipa_jump_func *jfunc, tree input)
1027 tree restype, res;
1029 if (ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
1030 return input;
1031 if (!is_gimple_ip_invariant (input))
1032 return NULL_TREE;
1034 if (TREE_CODE_CLASS (ipa_get_jf_pass_through_operation (jfunc))
1035 == tcc_comparison)
1036 restype = boolean_type_node;
1037 else
1038 restype = TREE_TYPE (input);
1039 res = fold_binary (ipa_get_jf_pass_through_operation (jfunc), restype,
1040 input, ipa_get_jf_pass_through_operand (jfunc));
1042 if (res && !is_gimple_ip_invariant (res))
1043 return NULL_TREE;
1045 return res;
1048 /* Return the result of an ancestor jump function JFUNC on the constant value
1049 INPUT. Return NULL_TREE if that cannot be determined. */
1051 static tree
1052 ipa_get_jf_ancestor_result (struct ipa_jump_func *jfunc, tree input)
1054 gcc_checking_assert (TREE_CODE (input) != TREE_BINFO);
1055 if (TREE_CODE (input) == ADDR_EXPR)
1057 tree t = TREE_OPERAND (input, 0);
1058 t = build_ref_for_offset (EXPR_LOCATION (t), t,
1059 ipa_get_jf_ancestor_offset (jfunc), false,
1060 ptr_type_node, NULL, false);
1061 return build_fold_addr_expr (t);
1063 else
1064 return NULL_TREE;
1067 /* Determine whether JFUNC evaluates to a single known constant value and if
1068 so, return it. Otherwise return NULL. INFO describes the caller node or
1069 the one it is inlined to, so that pass-through jump functions can be
1070 evaluated. */
1072 tree
1073 ipa_value_from_jfunc (struct ipa_node_params *info, struct ipa_jump_func *jfunc)
1075 if (jfunc->type == IPA_JF_CONST)
1076 return ipa_get_jf_constant (jfunc);
1077 else if (jfunc->type == IPA_JF_PASS_THROUGH
1078 || jfunc->type == IPA_JF_ANCESTOR)
1080 tree input;
1081 int idx;
1083 if (jfunc->type == IPA_JF_PASS_THROUGH)
1084 idx = ipa_get_jf_pass_through_formal_id (jfunc);
1085 else
1086 idx = ipa_get_jf_ancestor_formal_id (jfunc);
1088 if (info->ipcp_orig_node)
1089 input = info->known_csts[idx];
1090 else
1092 ipcp_lattice<tree> *lat;
1094 if (!info->lattices
1095 || idx >= ipa_get_param_count (info))
1096 return NULL_TREE;
1097 lat = ipa_get_scalar_lat (info, idx);
1098 if (!lat->is_single_const ())
1099 return NULL_TREE;
1100 input = lat->values->value;
1103 if (!input)
1104 return NULL_TREE;
1106 if (jfunc->type == IPA_JF_PASS_THROUGH)
1107 return ipa_get_jf_pass_through_result (jfunc, input);
1108 else
1109 return ipa_get_jf_ancestor_result (jfunc, input);
1111 else
1112 return NULL_TREE;
1115 /* Determie whether JFUNC evaluates to single known polymorphic context, given
1116 that INFO describes the caller node or the one it is inlined to, CS is the
1117 call graph edge corresponding to JFUNC and CSIDX index of the described
1118 parameter. */
1120 ipa_polymorphic_call_context
1121 ipa_context_from_jfunc (ipa_node_params *info, cgraph_edge *cs, int csidx,
1122 ipa_jump_func *jfunc)
1124 ipa_edge_args *args = IPA_EDGE_REF (cs);
1125 ipa_polymorphic_call_context ctx;
1126 ipa_polymorphic_call_context *edge_ctx
1127 = cs ? ipa_get_ith_polymorhic_call_context (args, csidx) : NULL;
1129 if (edge_ctx && !edge_ctx->useless_p ())
1130 ctx = *edge_ctx;
1132 if (jfunc->type == IPA_JF_PASS_THROUGH
1133 || jfunc->type == IPA_JF_ANCESTOR)
1135 ipa_polymorphic_call_context srcctx;
1136 int srcidx;
1137 bool type_preserved = true;
1138 if (jfunc->type == IPA_JF_PASS_THROUGH)
1140 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1141 return ctx;
1142 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
1143 srcidx = ipa_get_jf_pass_through_formal_id (jfunc);
1145 else
1147 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
1148 srcidx = ipa_get_jf_ancestor_formal_id (jfunc);
1150 if (info->ipcp_orig_node)
1152 if (info->known_contexts.exists ())
1153 srcctx = info->known_contexts[srcidx];
1155 else
1157 if (!info->lattices
1158 || srcidx >= ipa_get_param_count (info))
1159 return ctx;
1160 ipcp_lattice<ipa_polymorphic_call_context> *lat;
1161 lat = ipa_get_poly_ctx_lat (info, srcidx);
1162 if (!lat->is_single_const ())
1163 return ctx;
1164 srcctx = lat->values->value;
1166 if (srcctx.useless_p ())
1167 return ctx;
1168 if (jfunc->type == IPA_JF_ANCESTOR)
1169 srcctx.offset_by (ipa_get_jf_ancestor_offset (jfunc));
1170 if (!type_preserved)
1171 srcctx.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
1172 srcctx.combine_with (ctx);
1173 return srcctx;
1176 return ctx;
1179 /* If checking is enabled, verify that no lattice is in the TOP state, i.e. not
1180 bottom, not containing a variable component and without any known value at
1181 the same time. */
1183 DEBUG_FUNCTION void
1184 ipcp_verify_propagated_values (void)
1186 struct cgraph_node *node;
1188 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
1190 struct ipa_node_params *info = IPA_NODE_REF (node);
1191 int i, count = ipa_get_param_count (info);
1193 for (i = 0; i < count; i++)
1195 ipcp_lattice<tree> *lat = ipa_get_scalar_lat (info, i);
1197 if (!lat->bottom
1198 && !lat->contains_variable
1199 && lat->values_count == 0)
1201 if (dump_file)
1203 symtab_node::dump_table (dump_file);
1204 fprintf (dump_file, "\nIPA lattices after constant "
1205 "propagation, before gcc_unreachable:\n");
1206 print_all_lattices (dump_file, true, false);
1209 gcc_unreachable ();
1215 /* Return true iff X and Y should be considered equal values by IPA-CP. */
1217 static bool
1218 values_equal_for_ipcp_p (tree x, tree y)
1220 gcc_checking_assert (x != NULL_TREE && y != NULL_TREE);
1222 if (x == y)
1223 return true;
1225 if (TREE_CODE (x) == ADDR_EXPR
1226 && TREE_CODE (y) == ADDR_EXPR
1227 && TREE_CODE (TREE_OPERAND (x, 0)) == CONST_DECL
1228 && TREE_CODE (TREE_OPERAND (y, 0)) == CONST_DECL)
1229 return operand_equal_p (DECL_INITIAL (TREE_OPERAND (x, 0)),
1230 DECL_INITIAL (TREE_OPERAND (y, 0)), 0);
1231 else
1232 return operand_equal_p (x, y, 0);
1235 /* Return true iff X and Y should be considered equal contexts by IPA-CP. */
1237 static bool
1238 values_equal_for_ipcp_p (ipa_polymorphic_call_context x,
1239 ipa_polymorphic_call_context y)
1241 return x.equal_to (y);
1245 /* Add a new value source to the value represented by THIS, marking that a
1246 value comes from edge CS and (if the underlying jump function is a
1247 pass-through or an ancestor one) from a caller value SRC_VAL of a caller
1248 parameter described by SRC_INDEX. OFFSET is negative if the source was the
1249 scalar value of the parameter itself or the offset within an aggregate. */
1251 template <typename valtype>
1252 void
1253 ipcp_value<valtype>::add_source (cgraph_edge *cs, ipcp_value *src_val,
1254 int src_idx, HOST_WIDE_INT offset)
1256 ipcp_value_source<valtype> *src;
1258 src = new (ipcp_sources_pool.allocate ()) ipcp_value_source<valtype>;
1259 src->offset = offset;
1260 src->cs = cs;
1261 src->val = src_val;
1262 src->index = src_idx;
1264 src->next = sources;
1265 sources = src;
1268 /* Allocate a new ipcp_value holding a tree constant, initialize its value to
1269 SOURCE and clear all other fields. */
1271 static ipcp_value<tree> *
1272 allocate_and_init_ipcp_value (tree source)
1274 ipcp_value<tree> *val;
1276 val = ipcp_cst_values_pool.allocate ();
1277 memset (val, 0, sizeof (*val));
1278 val->value = source;
1279 return val;
1282 /* Allocate a new ipcp_value holding a polymorphic context, initialize its
1283 value to SOURCE and clear all other fields. */
1285 static ipcp_value<ipa_polymorphic_call_context> *
1286 allocate_and_init_ipcp_value (ipa_polymorphic_call_context source)
1288 ipcp_value<ipa_polymorphic_call_context> *val;
1290 // TODO
1291 val = ipcp_poly_ctx_values_pool.allocate ();
1292 memset (val, 0, sizeof (*val));
1293 val->value = source;
1294 return val;
1297 /* Try to add NEWVAL to LAT, potentially creating a new ipcp_value for it. CS,
1298 SRC_VAL SRC_INDEX and OFFSET are meant for add_source and have the same
1299 meaning. OFFSET -1 means the source is scalar and not a part of an
1300 aggregate. */
1302 template <typename valtype>
1303 bool
1304 ipcp_lattice<valtype>::add_value (valtype newval, cgraph_edge *cs,
1305 ipcp_value<valtype> *src_val,
1306 int src_idx, HOST_WIDE_INT offset)
1308 ipcp_value<valtype> *val;
1310 if (bottom)
1311 return false;
1313 for (val = values; val; val = val->next)
1314 if (values_equal_for_ipcp_p (val->value, newval))
1316 if (ipa_edge_within_scc (cs))
1318 ipcp_value_source<valtype> *s;
1319 for (s = val->sources; s ; s = s->next)
1320 if (s->cs == cs)
1321 break;
1322 if (s)
1323 return false;
1326 val->add_source (cs, src_val, src_idx, offset);
1327 return false;
1330 if (values_count == PARAM_VALUE (PARAM_IPA_CP_VALUE_LIST_SIZE))
1332 /* We can only free sources, not the values themselves, because sources
1333 of other values in this SCC might point to them. */
1334 for (val = values; val; val = val->next)
1336 while (val->sources)
1338 ipcp_value_source<valtype> *src = val->sources;
1339 val->sources = src->next;
1340 ipcp_sources_pool.remove ((ipcp_value_source<tree>*)src);
1344 values = NULL;
1345 return set_to_bottom ();
1348 values_count++;
1349 val = allocate_and_init_ipcp_value (newval);
1350 val->add_source (cs, src_val, src_idx, offset);
1351 val->next = values;
1352 values = val;
1353 return true;
1356 /* Propagate values through a pass-through jump function JFUNC associated with
1357 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
1358 is the index of the source parameter. */
1360 static bool
1361 propagate_vals_accross_pass_through (cgraph_edge *cs,
1362 ipa_jump_func *jfunc,
1363 ipcp_lattice<tree> *src_lat,
1364 ipcp_lattice<tree> *dest_lat,
1365 int src_idx)
1367 ipcp_value<tree> *src_val;
1368 bool ret = false;
1370 /* Do not create new values when propagating within an SCC because if there
1371 are arithmetic functions with circular dependencies, there is infinite
1372 number of them and we would just make lattices bottom. */
1373 if ((ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1374 && ipa_edge_within_scc (cs))
1375 ret = dest_lat->set_contains_variable ();
1376 else
1377 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1379 tree cstval = ipa_get_jf_pass_through_result (jfunc, src_val->value);
1381 if (cstval)
1382 ret |= dest_lat->add_value (cstval, cs, src_val, src_idx);
1383 else
1384 ret |= dest_lat->set_contains_variable ();
1387 return ret;
1390 /* Propagate values through an ancestor jump function JFUNC associated with
1391 edge CS, taking values from SRC_LAT and putting them into DEST_LAT. SRC_IDX
1392 is the index of the source parameter. */
1394 static bool
1395 propagate_vals_accross_ancestor (struct cgraph_edge *cs,
1396 struct ipa_jump_func *jfunc,
1397 ipcp_lattice<tree> *src_lat,
1398 ipcp_lattice<tree> *dest_lat,
1399 int src_idx)
1401 ipcp_value<tree> *src_val;
1402 bool ret = false;
1404 if (ipa_edge_within_scc (cs))
1405 return dest_lat->set_contains_variable ();
1407 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1409 tree t = ipa_get_jf_ancestor_result (jfunc, src_val->value);
1411 if (t)
1412 ret |= dest_lat->add_value (t, cs, src_val, src_idx);
1413 else
1414 ret |= dest_lat->set_contains_variable ();
1417 return ret;
1420 /* Propagate scalar values across jump function JFUNC that is associated with
1421 edge CS and put the values into DEST_LAT. */
1423 static bool
1424 propagate_scalar_accross_jump_function (struct cgraph_edge *cs,
1425 struct ipa_jump_func *jfunc,
1426 ipcp_lattice<tree> *dest_lat)
1428 if (dest_lat->bottom)
1429 return false;
1431 if (jfunc->type == IPA_JF_CONST)
1433 tree val = ipa_get_jf_constant (jfunc);
1434 return dest_lat->add_value (val, cs, NULL, 0);
1436 else if (jfunc->type == IPA_JF_PASS_THROUGH
1437 || jfunc->type == IPA_JF_ANCESTOR)
1439 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1440 ipcp_lattice<tree> *src_lat;
1441 int src_idx;
1442 bool ret;
1444 if (jfunc->type == IPA_JF_PASS_THROUGH)
1445 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1446 else
1447 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1449 src_lat = ipa_get_scalar_lat (caller_info, src_idx);
1450 if (src_lat->bottom)
1451 return dest_lat->set_contains_variable ();
1453 /* If we would need to clone the caller and cannot, do not propagate. */
1454 if (!ipcp_versionable_function_p (cs->caller)
1455 && (src_lat->contains_variable
1456 || (src_lat->values_count > 1)))
1457 return dest_lat->set_contains_variable ();
1459 if (jfunc->type == IPA_JF_PASS_THROUGH)
1460 ret = propagate_vals_accross_pass_through (cs, jfunc, src_lat,
1461 dest_lat, src_idx);
1462 else
1463 ret = propagate_vals_accross_ancestor (cs, jfunc, src_lat, dest_lat,
1464 src_idx);
1466 if (src_lat->contains_variable)
1467 ret |= dest_lat->set_contains_variable ();
1469 return ret;
1472 /* TODO: We currently do not handle member method pointers in IPA-CP (we only
1473 use it for indirect inlining), we should propagate them too. */
1474 return dest_lat->set_contains_variable ();
1477 /* Propagate scalar values across jump function JFUNC that is associated with
1478 edge CS and describes argument IDX and put the values into DEST_LAT. */
1480 static bool
1481 propagate_context_accross_jump_function (cgraph_edge *cs,
1482 ipa_jump_func *jfunc, int idx,
1483 ipcp_lattice<ipa_polymorphic_call_context> *dest_lat)
1485 ipa_edge_args *args = IPA_EDGE_REF (cs);
1486 if (dest_lat->bottom)
1487 return false;
1488 bool ret = false;
1489 bool added_sth = false;
1490 bool type_preserved = true;
1492 ipa_polymorphic_call_context edge_ctx, *edge_ctx_ptr
1493 = ipa_get_ith_polymorhic_call_context (args, idx);
1495 if (edge_ctx_ptr)
1496 edge_ctx = *edge_ctx_ptr;
1498 if (jfunc->type == IPA_JF_PASS_THROUGH
1499 || jfunc->type == IPA_JF_ANCESTOR)
1501 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1502 int src_idx;
1503 ipcp_lattice<ipa_polymorphic_call_context> *src_lat;
1505 /* TODO: Once we figure out how to propagate speculations, it will
1506 probably be a good idea to switch to speculation if type_preserved is
1507 not set instead of punting. */
1508 if (jfunc->type == IPA_JF_PASS_THROUGH)
1510 if (ipa_get_jf_pass_through_operation (jfunc) != NOP_EXPR)
1511 goto prop_fail;
1512 type_preserved = ipa_get_jf_pass_through_type_preserved (jfunc);
1513 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1515 else
1517 type_preserved = ipa_get_jf_ancestor_type_preserved (jfunc);
1518 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1521 src_lat = ipa_get_poly_ctx_lat (caller_info, src_idx);
1522 /* If we would need to clone the caller and cannot, do not propagate. */
1523 if (!ipcp_versionable_function_p (cs->caller)
1524 && (src_lat->contains_variable
1525 || (src_lat->values_count > 1)))
1526 goto prop_fail;
1528 ipcp_value<ipa_polymorphic_call_context> *src_val;
1529 for (src_val = src_lat->values; src_val; src_val = src_val->next)
1531 ipa_polymorphic_call_context cur = src_val->value;
1533 if (!type_preserved)
1534 cur.possible_dynamic_type_change (cs->in_polymorphic_cdtor);
1535 if (jfunc->type == IPA_JF_ANCESTOR)
1536 cur.offset_by (ipa_get_jf_ancestor_offset (jfunc));
1537 /* TODO: In cases we know how the context is going to be used,
1538 we can improve the result by passing proper OTR_TYPE. */
1539 cur.combine_with (edge_ctx);
1540 if (!cur.useless_p ())
1542 if (src_lat->contains_variable
1543 && !edge_ctx.equal_to (cur))
1544 ret |= dest_lat->set_contains_variable ();
1545 ret |= dest_lat->add_value (cur, cs, src_val, src_idx);
1546 added_sth = true;
1552 prop_fail:
1553 if (!added_sth)
1555 if (!edge_ctx.useless_p ())
1556 ret |= dest_lat->add_value (edge_ctx, cs);
1557 else
1558 ret |= dest_lat->set_contains_variable ();
1561 return ret;
1564 /* Propagate alignments across jump function JFUNC that is associated with
1565 edge CS and update DEST_LAT accordingly. */
1567 static bool
1568 propagate_alignment_accross_jump_function (cgraph_edge *cs,
1569 ipa_jump_func *jfunc,
1570 ipcp_alignment_lattice *dest_lat)
1572 if (dest_lat->bottom_p ())
1573 return false;
1575 if (jfunc->type == IPA_JF_PASS_THROUGH
1576 || jfunc->type == IPA_JF_ANCESTOR)
1578 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1579 HOST_WIDE_INT offset = 0;
1580 int src_idx;
1582 if (jfunc->type == IPA_JF_PASS_THROUGH)
1584 enum tree_code op = ipa_get_jf_pass_through_operation (jfunc);
1585 if (op != NOP_EXPR)
1587 if (op != POINTER_PLUS_EXPR
1588 && op != PLUS_EXPR)
1589 return dest_lat->set_to_bottom ();
1590 tree operand = ipa_get_jf_pass_through_operand (jfunc);
1591 if (!tree_fits_shwi_p (operand))
1592 return dest_lat->set_to_bottom ();
1593 offset = tree_to_shwi (operand);
1595 src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1597 else
1599 src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1600 offset = ipa_get_jf_ancestor_offset (jfunc) / BITS_PER_UNIT;
1603 struct ipcp_param_lattices *src_lats;
1604 src_lats = ipa_get_parm_lattices (caller_info, src_idx);
1605 return dest_lat->meet_with (src_lats->alignment, offset);
1607 else
1609 if (jfunc->alignment.known)
1610 return dest_lat->meet_with (jfunc->alignment.align,
1611 jfunc->alignment.misalign);
1612 else
1613 return dest_lat->set_to_bottom ();
1617 /* If DEST_PLATS already has aggregate items, check that aggs_by_ref matches
1618 NEW_AGGS_BY_REF and if not, mark all aggs as bottoms and return true (in all
1619 other cases, return false). If there are no aggregate items, set
1620 aggs_by_ref to NEW_AGGS_BY_REF. */
1622 static bool
1623 set_check_aggs_by_ref (struct ipcp_param_lattices *dest_plats,
1624 bool new_aggs_by_ref)
1626 if (dest_plats->aggs)
1628 if (dest_plats->aggs_by_ref != new_aggs_by_ref)
1630 set_agg_lats_to_bottom (dest_plats);
1631 return true;
1634 else
1635 dest_plats->aggs_by_ref = new_aggs_by_ref;
1636 return false;
1639 /* Walk aggregate lattices in DEST_PLATS from ***AGLAT on, until ***aglat is an
1640 already existing lattice for the given OFFSET and SIZE, marking all skipped
1641 lattices as containing variable and checking for overlaps. If there is no
1642 already existing lattice for the OFFSET and VAL_SIZE, create one, initialize
1643 it with offset, size and contains_variable to PRE_EXISTING, and return true,
1644 unless there are too many already. If there are two many, return false. If
1645 there are overlaps turn whole DEST_PLATS to bottom and return false. If any
1646 skipped lattices were newly marked as containing variable, set *CHANGE to
1647 true. */
1649 static bool
1650 merge_agg_lats_step (struct ipcp_param_lattices *dest_plats,
1651 HOST_WIDE_INT offset, HOST_WIDE_INT val_size,
1652 struct ipcp_agg_lattice ***aglat,
1653 bool pre_existing, bool *change)
1655 gcc_checking_assert (offset >= 0);
1657 while (**aglat && (**aglat)->offset < offset)
1659 if ((**aglat)->offset + (**aglat)->size > offset)
1661 set_agg_lats_to_bottom (dest_plats);
1662 return false;
1664 *change |= (**aglat)->set_contains_variable ();
1665 *aglat = &(**aglat)->next;
1668 if (**aglat && (**aglat)->offset == offset)
1670 if ((**aglat)->size != val_size
1671 || ((**aglat)->next
1672 && (**aglat)->next->offset < offset + val_size))
1674 set_agg_lats_to_bottom (dest_plats);
1675 return false;
1677 gcc_checking_assert (!(**aglat)->next
1678 || (**aglat)->next->offset >= offset + val_size);
1679 return true;
1681 else
1683 struct ipcp_agg_lattice *new_al;
1685 if (**aglat && (**aglat)->offset < offset + val_size)
1687 set_agg_lats_to_bottom (dest_plats);
1688 return false;
1690 if (dest_plats->aggs_count == PARAM_VALUE (PARAM_IPA_MAX_AGG_ITEMS))
1691 return false;
1692 dest_plats->aggs_count++;
1693 new_al = ipcp_agg_lattice_pool.allocate ();
1694 memset (new_al, 0, sizeof (*new_al));
1696 new_al->offset = offset;
1697 new_al->size = val_size;
1698 new_al->contains_variable = pre_existing;
1700 new_al->next = **aglat;
1701 **aglat = new_al;
1702 return true;
1706 /* Set all AGLAT and all other aggregate lattices reachable by next pointers as
1707 containing an unknown value. */
1709 static bool
1710 set_chain_of_aglats_contains_variable (struct ipcp_agg_lattice *aglat)
1712 bool ret = false;
1713 while (aglat)
1715 ret |= aglat->set_contains_variable ();
1716 aglat = aglat->next;
1718 return ret;
1721 /* Merge existing aggregate lattices in SRC_PLATS to DEST_PLATS, subtracting
1722 DELTA_OFFSET. CS is the call graph edge and SRC_IDX the index of the source
1723 parameter used for lattice value sources. Return true if DEST_PLATS changed
1724 in any way. */
1726 static bool
1727 merge_aggregate_lattices (struct cgraph_edge *cs,
1728 struct ipcp_param_lattices *dest_plats,
1729 struct ipcp_param_lattices *src_plats,
1730 int src_idx, HOST_WIDE_INT offset_delta)
1732 bool pre_existing = dest_plats->aggs != NULL;
1733 struct ipcp_agg_lattice **dst_aglat;
1734 bool ret = false;
1736 if (set_check_aggs_by_ref (dest_plats, src_plats->aggs_by_ref))
1737 return true;
1738 if (src_plats->aggs_bottom)
1739 return set_agg_lats_contain_variable (dest_plats);
1740 if (src_plats->aggs_contain_variable)
1741 ret |= set_agg_lats_contain_variable (dest_plats);
1742 dst_aglat = &dest_plats->aggs;
1744 for (struct ipcp_agg_lattice *src_aglat = src_plats->aggs;
1745 src_aglat;
1746 src_aglat = src_aglat->next)
1748 HOST_WIDE_INT new_offset = src_aglat->offset - offset_delta;
1750 if (new_offset < 0)
1751 continue;
1752 if (merge_agg_lats_step (dest_plats, new_offset, src_aglat->size,
1753 &dst_aglat, pre_existing, &ret))
1755 struct ipcp_agg_lattice *new_al = *dst_aglat;
1757 dst_aglat = &(*dst_aglat)->next;
1758 if (src_aglat->bottom)
1760 ret |= new_al->set_contains_variable ();
1761 continue;
1763 if (src_aglat->contains_variable)
1764 ret |= new_al->set_contains_variable ();
1765 for (ipcp_value<tree> *val = src_aglat->values;
1766 val;
1767 val = val->next)
1768 ret |= new_al->add_value (val->value, cs, val, src_idx,
1769 src_aglat->offset);
1771 else if (dest_plats->aggs_bottom)
1772 return true;
1774 ret |= set_chain_of_aglats_contains_variable (*dst_aglat);
1775 return ret;
1778 /* Determine whether there is anything to propagate FROM SRC_PLATS through a
1779 pass-through JFUNC and if so, whether it has conform and conforms to the
1780 rules about propagating values passed by reference. */
1782 static bool
1783 agg_pass_through_permissible_p (struct ipcp_param_lattices *src_plats,
1784 struct ipa_jump_func *jfunc)
1786 return src_plats->aggs
1787 && (!src_plats->aggs_by_ref
1788 || ipa_get_jf_pass_through_agg_preserved (jfunc));
1791 /* Propagate scalar values across jump function JFUNC that is associated with
1792 edge CS and put the values into DEST_LAT. */
1794 static bool
1795 propagate_aggs_accross_jump_function (struct cgraph_edge *cs,
1796 struct ipa_jump_func *jfunc,
1797 struct ipcp_param_lattices *dest_plats)
1799 bool ret = false;
1801 if (dest_plats->aggs_bottom)
1802 return false;
1804 if (jfunc->type == IPA_JF_PASS_THROUGH
1805 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
1807 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1808 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
1809 struct ipcp_param_lattices *src_plats;
1811 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
1812 if (agg_pass_through_permissible_p (src_plats, jfunc))
1814 /* Currently we do not produce clobber aggregate jump
1815 functions, replace with merging when we do. */
1816 gcc_assert (!jfunc->agg.items);
1817 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats,
1818 src_idx, 0);
1820 else
1821 ret |= set_agg_lats_contain_variable (dest_plats);
1823 else if (jfunc->type == IPA_JF_ANCESTOR
1824 && ipa_get_jf_ancestor_agg_preserved (jfunc))
1826 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
1827 int src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
1828 struct ipcp_param_lattices *src_plats;
1830 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
1831 if (src_plats->aggs && src_plats->aggs_by_ref)
1833 /* Currently we do not produce clobber aggregate jump
1834 functions, replace with merging when we do. */
1835 gcc_assert (!jfunc->agg.items);
1836 ret |= merge_aggregate_lattices (cs, dest_plats, src_plats, src_idx,
1837 ipa_get_jf_ancestor_offset (jfunc));
1839 else if (!src_plats->aggs_by_ref)
1840 ret |= set_agg_lats_to_bottom (dest_plats);
1841 else
1842 ret |= set_agg_lats_contain_variable (dest_plats);
1844 else if (jfunc->agg.items)
1846 bool pre_existing = dest_plats->aggs != NULL;
1847 struct ipcp_agg_lattice **aglat = &dest_plats->aggs;
1848 struct ipa_agg_jf_item *item;
1849 int i;
1851 if (set_check_aggs_by_ref (dest_plats, jfunc->agg.by_ref))
1852 return true;
1854 FOR_EACH_VEC_ELT (*jfunc->agg.items, i, item)
1856 HOST_WIDE_INT val_size;
1858 if (item->offset < 0)
1859 continue;
1860 gcc_checking_assert (is_gimple_ip_invariant (item->value));
1861 val_size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (item->value)));
1863 if (merge_agg_lats_step (dest_plats, item->offset, val_size,
1864 &aglat, pre_existing, &ret))
1866 ret |= (*aglat)->add_value (item->value, cs, NULL, 0, 0);
1867 aglat = &(*aglat)->next;
1869 else if (dest_plats->aggs_bottom)
1870 return true;
1873 ret |= set_chain_of_aglats_contains_variable (*aglat);
1875 else
1876 ret |= set_agg_lats_contain_variable (dest_plats);
1878 return ret;
1881 /* Return true if on the way cfrom CS->caller to the final (non-alias and
1882 non-thunk) destination, the call passes through a thunk. */
1884 static bool
1885 call_passes_through_thunk_p (cgraph_edge *cs)
1887 cgraph_node *alias_or_thunk = cs->callee;
1888 while (alias_or_thunk->alias)
1889 alias_or_thunk = alias_or_thunk->get_alias_target ();
1890 return alias_or_thunk->thunk.thunk_p;
1893 /* Propagate constants from the caller to the callee of CS. INFO describes the
1894 caller. */
1896 static bool
1897 propagate_constants_accross_call (struct cgraph_edge *cs)
1899 struct ipa_node_params *callee_info;
1900 enum availability availability;
1901 cgraph_node *callee;
1902 struct ipa_edge_args *args;
1903 bool ret = false;
1904 int i, args_count, parms_count;
1906 callee = cs->callee->function_symbol (&availability);
1907 if (!callee->definition)
1908 return false;
1909 gcc_checking_assert (callee->has_gimple_body_p ());
1910 callee_info = IPA_NODE_REF (callee);
1912 args = IPA_EDGE_REF (cs);
1913 args_count = ipa_get_cs_argument_count (args);
1914 parms_count = ipa_get_param_count (callee_info);
1915 if (parms_count == 0)
1916 return false;
1918 /* No propagation through instrumentation thunks is available yet.
1919 It should be possible with proper mapping of call args and
1920 instrumented callee params in the propagation loop below. But
1921 this case mostly occurs when legacy code calls instrumented code
1922 and it is not a primary target for optimizations.
1923 We detect instrumentation thunks in aliases and thunks chain by
1924 checking instrumentation_clone flag for chain source and target.
1925 Going through instrumentation thunks we always have it changed
1926 from 0 to 1 and all other nodes do not change it. */
1927 if (!cs->callee->instrumentation_clone
1928 && callee->instrumentation_clone)
1930 for (i = 0; i < parms_count; i++)
1931 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
1932 i));
1933 return ret;
1936 /* If this call goes through a thunk we must not propagate to the first (0th)
1937 parameter. However, we might need to uncover a thunk from below a series
1938 of aliases first. */
1939 if (call_passes_through_thunk_p (cs))
1941 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info,
1942 0));
1943 i = 1;
1945 else
1946 i = 0;
1948 for (; (i < args_count) && (i < parms_count); i++)
1950 struct ipa_jump_func *jump_func = ipa_get_ith_jump_func (args, i);
1951 struct ipcp_param_lattices *dest_plats;
1953 dest_plats = ipa_get_parm_lattices (callee_info, i);
1954 if (availability == AVAIL_INTERPOSABLE)
1955 ret |= set_all_contains_variable (dest_plats);
1956 else
1958 ret |= propagate_scalar_accross_jump_function (cs, jump_func,
1959 &dest_plats->itself);
1960 ret |= propagate_context_accross_jump_function (cs, jump_func, i,
1961 &dest_plats->ctxlat);
1962 ret |= propagate_alignment_accross_jump_function (cs, jump_func,
1963 &dest_plats->alignment);
1964 ret |= propagate_aggs_accross_jump_function (cs, jump_func,
1965 dest_plats);
1968 for (; i < parms_count; i++)
1969 ret |= set_all_contains_variable (ipa_get_parm_lattices (callee_info, i));
1971 return ret;
1974 /* If an indirect edge IE can be turned into a direct one based on KNOWN_VALS
1975 KNOWN_CONTEXTS, KNOWN_AGGS or AGG_REPS return the destination. The latter
1976 three can be NULL. If AGG_REPS is not NULL, KNOWN_AGGS is ignored. */
1978 static tree
1979 ipa_get_indirect_edge_target_1 (struct cgraph_edge *ie,
1980 vec<tree> known_csts,
1981 vec<ipa_polymorphic_call_context> known_contexts,
1982 vec<ipa_agg_jump_function_p> known_aggs,
1983 struct ipa_agg_replacement_value *agg_reps,
1984 bool *speculative)
1986 int param_index = ie->indirect_info->param_index;
1987 HOST_WIDE_INT anc_offset;
1988 tree t;
1989 tree target = NULL;
1991 *speculative = false;
1993 if (param_index == -1
1994 || known_csts.length () <= (unsigned int) param_index)
1995 return NULL_TREE;
1997 if (!ie->indirect_info->polymorphic)
1999 tree t;
2001 if (ie->indirect_info->agg_contents)
2003 t = NULL;
2004 if (agg_reps && ie->indirect_info->guaranteed_unmodified)
2006 while (agg_reps)
2008 if (agg_reps->index == param_index
2009 && agg_reps->offset == ie->indirect_info->offset
2010 && agg_reps->by_ref == ie->indirect_info->by_ref)
2012 t = agg_reps->value;
2013 break;
2015 agg_reps = agg_reps->next;
2018 if (!t)
2020 struct ipa_agg_jump_function *agg;
2021 if (known_aggs.length () > (unsigned int) param_index)
2022 agg = known_aggs[param_index];
2023 else
2024 agg = NULL;
2025 bool from_global_constant;
2026 t = ipa_find_agg_cst_for_param (agg, known_csts[param_index],
2027 ie->indirect_info->offset,
2028 ie->indirect_info->by_ref,
2029 &from_global_constant);
2030 if (t
2031 && !from_global_constant
2032 && !ie->indirect_info->guaranteed_unmodified)
2033 t = NULL_TREE;
2036 else
2037 t = known_csts[param_index];
2039 if (t &&
2040 TREE_CODE (t) == ADDR_EXPR
2041 && TREE_CODE (TREE_OPERAND (t, 0)) == FUNCTION_DECL)
2042 return TREE_OPERAND (t, 0);
2043 else
2044 return NULL_TREE;
2047 if (!opt_for_fn (ie->caller->decl, flag_devirtualize))
2048 return NULL_TREE;
2050 gcc_assert (!ie->indirect_info->agg_contents);
2051 anc_offset = ie->indirect_info->offset;
2053 t = NULL;
2055 /* Try to work out value of virtual table pointer value in replacemnets. */
2056 if (!t && agg_reps && !ie->indirect_info->by_ref)
2058 while (agg_reps)
2060 if (agg_reps->index == param_index
2061 && agg_reps->offset == ie->indirect_info->offset
2062 && agg_reps->by_ref)
2064 t = agg_reps->value;
2065 break;
2067 agg_reps = agg_reps->next;
2071 /* Try to work out value of virtual table pointer value in known
2072 aggregate values. */
2073 if (!t && known_aggs.length () > (unsigned int) param_index
2074 && !ie->indirect_info->by_ref)
2076 struct ipa_agg_jump_function *agg;
2077 agg = known_aggs[param_index];
2078 t = ipa_find_agg_cst_for_param (agg, known_csts[param_index],
2079 ie->indirect_info->offset,
2080 true);
2083 /* If we found the virtual table pointer, lookup the target. */
2084 if (t)
2086 tree vtable;
2087 unsigned HOST_WIDE_INT offset;
2088 if (vtable_pointer_value_to_vtable (t, &vtable, &offset))
2090 bool can_refer;
2091 target = gimple_get_virt_method_for_vtable (ie->indirect_info->otr_token,
2092 vtable, offset, &can_refer);
2093 if (can_refer)
2095 if (!target
2096 || (TREE_CODE (TREE_TYPE (target)) == FUNCTION_TYPE
2097 && DECL_FUNCTION_CODE (target) == BUILT_IN_UNREACHABLE)
2098 || !possible_polymorphic_call_target_p
2099 (ie, cgraph_node::get (target)))
2101 /* Do not speculate builtin_unreachable, it is stupid! */
2102 if (ie->indirect_info->vptr_changed)
2103 return NULL;
2104 target = ipa_impossible_devirt_target (ie, target);
2106 *speculative = ie->indirect_info->vptr_changed;
2107 if (!*speculative)
2108 return target;
2113 /* Do we know the constant value of pointer? */
2114 if (!t)
2115 t = known_csts[param_index];
2117 gcc_checking_assert (!t || TREE_CODE (t) != TREE_BINFO);
2119 ipa_polymorphic_call_context context;
2120 if (known_contexts.length () > (unsigned int) param_index)
2122 context = known_contexts[param_index];
2123 context.offset_by (anc_offset);
2124 if (ie->indirect_info->vptr_changed)
2125 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
2126 ie->indirect_info->otr_type);
2127 if (t)
2129 ipa_polymorphic_call_context ctx2 = ipa_polymorphic_call_context
2130 (t, ie->indirect_info->otr_type, anc_offset);
2131 if (!ctx2.useless_p ())
2132 context.combine_with (ctx2, ie->indirect_info->otr_type);
2135 else if (t)
2137 context = ipa_polymorphic_call_context (t, ie->indirect_info->otr_type,
2138 anc_offset);
2139 if (ie->indirect_info->vptr_changed)
2140 context.possible_dynamic_type_change (ie->in_polymorphic_cdtor,
2141 ie->indirect_info->otr_type);
2143 else
2144 return NULL_TREE;
2146 vec <cgraph_node *>targets;
2147 bool final;
2149 targets = possible_polymorphic_call_targets
2150 (ie->indirect_info->otr_type,
2151 ie->indirect_info->otr_token,
2152 context, &final);
2153 if (!final || targets.length () > 1)
2155 struct cgraph_node *node;
2156 if (*speculative)
2157 return target;
2158 if (!opt_for_fn (ie->caller->decl, flag_devirtualize_speculatively)
2159 || ie->speculative || !ie->maybe_hot_p ())
2160 return NULL;
2161 node = try_speculative_devirtualization (ie->indirect_info->otr_type,
2162 ie->indirect_info->otr_token,
2163 context);
2164 if (node)
2166 *speculative = true;
2167 target = node->decl;
2169 else
2170 return NULL;
2172 else
2174 *speculative = false;
2175 if (targets.length () == 1)
2176 target = targets[0]->decl;
2177 else
2178 target = ipa_impossible_devirt_target (ie, NULL_TREE);
2181 if (target && !possible_polymorphic_call_target_p (ie,
2182 cgraph_node::get (target)))
2184 if (*speculative)
2185 return NULL;
2186 target = ipa_impossible_devirt_target (ie, target);
2189 return target;
2193 /* If an indirect edge IE can be turned into a direct one based on KNOWN_CSTS,
2194 KNOWN_CONTEXTS (which can be vNULL) or KNOWN_AGGS (which also can be vNULL)
2195 return the destination. */
2197 tree
2198 ipa_get_indirect_edge_target (struct cgraph_edge *ie,
2199 vec<tree> known_csts,
2200 vec<ipa_polymorphic_call_context> known_contexts,
2201 vec<ipa_agg_jump_function_p> known_aggs,
2202 bool *speculative)
2204 return ipa_get_indirect_edge_target_1 (ie, known_csts, known_contexts,
2205 known_aggs, NULL, speculative);
2208 /* Calculate devirtualization time bonus for NODE, assuming we know KNOWN_CSTS
2209 and KNOWN_CONTEXTS. */
2211 static int
2212 devirtualization_time_bonus (struct cgraph_node *node,
2213 vec<tree> known_csts,
2214 vec<ipa_polymorphic_call_context> known_contexts,
2215 vec<ipa_agg_jump_function_p> known_aggs)
2217 struct cgraph_edge *ie;
2218 int res = 0;
2220 for (ie = node->indirect_calls; ie; ie = ie->next_callee)
2222 struct cgraph_node *callee;
2223 struct inline_summary *isummary;
2224 enum availability avail;
2225 tree target;
2226 bool speculative;
2228 target = ipa_get_indirect_edge_target (ie, known_csts, known_contexts,
2229 known_aggs, &speculative);
2230 if (!target)
2231 continue;
2233 /* Only bare minimum benefit for clearly un-inlineable targets. */
2234 res += 1;
2235 callee = cgraph_node::get (target);
2236 if (!callee || !callee->definition)
2237 continue;
2238 callee = callee->function_symbol (&avail);
2239 if (avail < AVAIL_AVAILABLE)
2240 continue;
2241 isummary = inline_summaries->get (callee);
2242 if (!isummary->inlinable)
2243 continue;
2245 /* FIXME: The values below need re-considering and perhaps also
2246 integrating into the cost metrics, at lest in some very basic way. */
2247 if (isummary->size <= MAX_INLINE_INSNS_AUTO / 4)
2248 res += 31 / ((int)speculative + 1);
2249 else if (isummary->size <= MAX_INLINE_INSNS_AUTO / 2)
2250 res += 15 / ((int)speculative + 1);
2251 else if (isummary->size <= MAX_INLINE_INSNS_AUTO
2252 || DECL_DECLARED_INLINE_P (callee->decl))
2253 res += 7 / ((int)speculative + 1);
2256 return res;
2259 /* Return time bonus incurred because of HINTS. */
2261 static int
2262 hint_time_bonus (inline_hints hints)
2264 int result = 0;
2265 if (hints & (INLINE_HINT_loop_iterations | INLINE_HINT_loop_stride))
2266 result += PARAM_VALUE (PARAM_IPA_CP_LOOP_HINT_BONUS);
2267 if (hints & INLINE_HINT_array_index)
2268 result += PARAM_VALUE (PARAM_IPA_CP_ARRAY_INDEX_HINT_BONUS);
2269 return result;
2272 /* If there is a reason to penalize the function described by INFO in the
2273 cloning goodness evaluation, do so. */
2275 static inline int64_t
2276 incorporate_penalties (ipa_node_params *info, int64_t evaluation)
2278 if (info->node_within_scc)
2279 evaluation = (evaluation
2280 * (100 - PARAM_VALUE (PARAM_IPA_CP_RECURSION_PENALTY))) / 100;
2282 if (info->node_calling_single_call)
2283 evaluation = (evaluation
2284 * (100 - PARAM_VALUE (PARAM_IPA_CP_SINGLE_CALL_PENALTY)))
2285 / 100;
2287 return evaluation;
2290 /* Return true if cloning NODE is a good idea, given the estimated TIME_BENEFIT
2291 and SIZE_COST and with the sum of frequencies of incoming edges to the
2292 potential new clone in FREQUENCIES. */
2294 static bool
2295 good_cloning_opportunity_p (struct cgraph_node *node, int time_benefit,
2296 int freq_sum, gcov_type count_sum, int size_cost)
2298 if (time_benefit == 0
2299 || !opt_for_fn (node->decl, flag_ipa_cp_clone)
2300 || node->optimize_for_size_p ())
2301 return false;
2303 gcc_assert (size_cost > 0);
2305 struct ipa_node_params *info = IPA_NODE_REF (node);
2306 if (max_count)
2308 int factor = (count_sum * 1000) / max_count;
2309 int64_t evaluation = (((int64_t) time_benefit * factor)
2310 / size_cost);
2311 evaluation = incorporate_penalties (info, evaluation);
2313 if (dump_file && (dump_flags & TDF_DETAILS))
2314 fprintf (dump_file, " good_cloning_opportunity_p (time: %i, "
2315 "size: %i, count_sum: " HOST_WIDE_INT_PRINT_DEC
2316 "%s%s) -> evaluation: " "%" PRId64
2317 ", threshold: %i\n",
2318 time_benefit, size_cost, (HOST_WIDE_INT) count_sum,
2319 info->node_within_scc ? ", scc" : "",
2320 info->node_calling_single_call ? ", single_call" : "",
2321 evaluation, PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD));
2323 return evaluation >= PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD);
2325 else
2327 int64_t evaluation = (((int64_t) time_benefit * freq_sum)
2328 / size_cost);
2329 evaluation = incorporate_penalties (info, evaluation);
2331 if (dump_file && (dump_flags & TDF_DETAILS))
2332 fprintf (dump_file, " good_cloning_opportunity_p (time: %i, "
2333 "size: %i, freq_sum: %i%s%s) -> evaluation: "
2334 "%" PRId64 ", threshold: %i\n",
2335 time_benefit, size_cost, freq_sum,
2336 info->node_within_scc ? ", scc" : "",
2337 info->node_calling_single_call ? ", single_call" : "",
2338 evaluation, PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD));
2340 return evaluation >= PARAM_VALUE (PARAM_IPA_CP_EVAL_THRESHOLD);
2344 /* Return all context independent values from aggregate lattices in PLATS in a
2345 vector. Return NULL if there are none. */
2347 static vec<ipa_agg_jf_item, va_gc> *
2348 context_independent_aggregate_values (struct ipcp_param_lattices *plats)
2350 vec<ipa_agg_jf_item, va_gc> *res = NULL;
2352 if (plats->aggs_bottom
2353 || plats->aggs_contain_variable
2354 || plats->aggs_count == 0)
2355 return NULL;
2357 for (struct ipcp_agg_lattice *aglat = plats->aggs;
2358 aglat;
2359 aglat = aglat->next)
2360 if (aglat->is_single_const ())
2362 struct ipa_agg_jf_item item;
2363 item.offset = aglat->offset;
2364 item.value = aglat->values->value;
2365 vec_safe_push (res, item);
2367 return res;
2370 /* Allocate KNOWN_CSTS, KNOWN_CONTEXTS and, if non-NULL, KNOWN_AGGS and
2371 populate them with values of parameters that are known independent of the
2372 context. INFO describes the function. If REMOVABLE_PARAMS_COST is
2373 non-NULL, the movement cost of all removable parameters will be stored in
2374 it. */
2376 static bool
2377 gather_context_independent_values (struct ipa_node_params *info,
2378 vec<tree> *known_csts,
2379 vec<ipa_polymorphic_call_context>
2380 *known_contexts,
2381 vec<ipa_agg_jump_function> *known_aggs,
2382 int *removable_params_cost)
2384 int i, count = ipa_get_param_count (info);
2385 bool ret = false;
2387 known_csts->create (0);
2388 known_contexts->create (0);
2389 known_csts->safe_grow_cleared (count);
2390 known_contexts->safe_grow_cleared (count);
2391 if (known_aggs)
2393 known_aggs->create (0);
2394 known_aggs->safe_grow_cleared (count);
2397 if (removable_params_cost)
2398 *removable_params_cost = 0;
2400 for (i = 0; i < count ; i++)
2402 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2403 ipcp_lattice<tree> *lat = &plats->itself;
2405 if (lat->is_single_const ())
2407 ipcp_value<tree> *val = lat->values;
2408 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
2409 (*known_csts)[i] = val->value;
2410 if (removable_params_cost)
2411 *removable_params_cost
2412 += estimate_move_cost (TREE_TYPE (val->value), false);
2413 ret = true;
2415 else if (removable_params_cost
2416 && !ipa_is_param_used (info, i))
2417 *removable_params_cost
2418 += ipa_get_param_move_cost (info, i);
2420 if (!ipa_is_param_used (info, i))
2421 continue;
2423 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2424 /* Do not account known context as reason for cloning. We can see
2425 if it permits devirtualization. */
2426 if (ctxlat->is_single_const ())
2427 (*known_contexts)[i] = ctxlat->values->value;
2429 if (known_aggs)
2431 vec<ipa_agg_jf_item, va_gc> *agg_items;
2432 struct ipa_agg_jump_function *ajf;
2434 agg_items = context_independent_aggregate_values (plats);
2435 ajf = &(*known_aggs)[i];
2436 ajf->items = agg_items;
2437 ajf->by_ref = plats->aggs_by_ref;
2438 ret |= agg_items != NULL;
2442 return ret;
2445 /* The current interface in ipa-inline-analysis requires a pointer vector.
2446 Create it.
2448 FIXME: That interface should be re-worked, this is slightly silly. Still,
2449 I'd like to discuss how to change it first and this demonstrates the
2450 issue. */
2452 static vec<ipa_agg_jump_function_p>
2453 agg_jmp_p_vec_for_t_vec (vec<ipa_agg_jump_function> known_aggs)
2455 vec<ipa_agg_jump_function_p> ret;
2456 struct ipa_agg_jump_function *ajf;
2457 int i;
2459 ret.create (known_aggs.length ());
2460 FOR_EACH_VEC_ELT (known_aggs, i, ajf)
2461 ret.quick_push (ajf);
2462 return ret;
2465 /* Perform time and size measurement of NODE with the context given in
2466 KNOWN_CSTS, KNOWN_CONTEXTS and KNOWN_AGGS, calculate the benefit and cost
2467 given BASE_TIME of the node without specialization, REMOVABLE_PARAMS_COST of
2468 all context-independent removable parameters and EST_MOVE_COST of estimated
2469 movement of the considered parameter and store it into VAL. */
2471 static void
2472 perform_estimation_of_a_value (cgraph_node *node, vec<tree> known_csts,
2473 vec<ipa_polymorphic_call_context> known_contexts,
2474 vec<ipa_agg_jump_function_p> known_aggs_ptrs,
2475 int base_time, int removable_params_cost,
2476 int est_move_cost, ipcp_value_base *val)
2478 int time, size, time_benefit;
2479 inline_hints hints;
2481 estimate_ipcp_clone_size_and_time (node, known_csts, known_contexts,
2482 known_aggs_ptrs, &size, &time,
2483 &hints);
2484 time_benefit = base_time - time
2485 + devirtualization_time_bonus (node, known_csts, known_contexts,
2486 known_aggs_ptrs)
2487 + hint_time_bonus (hints)
2488 + removable_params_cost + est_move_cost;
2490 gcc_checking_assert (size >=0);
2491 /* The inliner-heuristics based estimates may think that in certain
2492 contexts some functions do not have any size at all but we want
2493 all specializations to have at least a tiny cost, not least not to
2494 divide by zero. */
2495 if (size == 0)
2496 size = 1;
2498 val->local_time_benefit = time_benefit;
2499 val->local_size_cost = size;
2502 /* Iterate over known values of parameters of NODE and estimate the local
2503 effects in terms of time and size they have. */
2505 static void
2506 estimate_local_effects (struct cgraph_node *node)
2508 struct ipa_node_params *info = IPA_NODE_REF (node);
2509 int i, count = ipa_get_param_count (info);
2510 vec<tree> known_csts;
2511 vec<ipa_polymorphic_call_context> known_contexts;
2512 vec<ipa_agg_jump_function> known_aggs;
2513 vec<ipa_agg_jump_function_p> known_aggs_ptrs;
2514 bool always_const;
2515 int base_time = inline_summaries->get (node)->time;
2516 int removable_params_cost;
2518 if (!count || !ipcp_versionable_function_p (node))
2519 return;
2521 if (dump_file && (dump_flags & TDF_DETAILS))
2522 fprintf (dump_file, "\nEstimating effects for %s/%i, base_time: %i.\n",
2523 node->name (), node->order, base_time);
2525 always_const = gather_context_independent_values (info, &known_csts,
2526 &known_contexts, &known_aggs,
2527 &removable_params_cost);
2528 known_aggs_ptrs = agg_jmp_p_vec_for_t_vec (known_aggs);
2529 int devirt_bonus = devirtualization_time_bonus (node, known_csts,
2530 known_contexts, known_aggs_ptrs);
2531 if (always_const || devirt_bonus
2532 || (removable_params_cost && node->local.can_change_signature))
2534 struct caller_statistics stats;
2535 inline_hints hints;
2536 int time, size;
2538 init_caller_stats (&stats);
2539 node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
2540 false);
2541 estimate_ipcp_clone_size_and_time (node, known_csts, known_contexts,
2542 known_aggs_ptrs, &size, &time, &hints);
2543 time -= devirt_bonus;
2544 time -= hint_time_bonus (hints);
2545 time -= removable_params_cost;
2546 size -= stats.n_calls * removable_params_cost;
2548 if (dump_file)
2549 fprintf (dump_file, " - context independent values, size: %i, "
2550 "time_benefit: %i\n", size, base_time - time);
2552 if (size <= 0 || node->local.local)
2554 info->do_clone_for_all_contexts = true;
2555 base_time = time;
2557 if (dump_file)
2558 fprintf (dump_file, " Decided to specialize for all "
2559 "known contexts, code not going to grow.\n");
2561 else if (good_cloning_opportunity_p (node, base_time - time,
2562 stats.freq_sum, stats.count_sum,
2563 size))
2565 if (size + overall_size <= max_new_size)
2567 info->do_clone_for_all_contexts = true;
2568 base_time = time;
2569 overall_size += size;
2571 if (dump_file)
2572 fprintf (dump_file, " Decided to specialize for all "
2573 "known contexts, growth deemed beneficial.\n");
2575 else if (dump_file && (dump_flags & TDF_DETAILS))
2576 fprintf (dump_file, " Not cloning for all contexts because "
2577 "max_new_size would be reached with %li.\n",
2578 size + overall_size);
2580 else if (dump_file && (dump_flags & TDF_DETAILS))
2581 fprintf (dump_file, " Not cloning for all contexts because "
2582 "!good_cloning_opportunity_p.\n");
2586 for (i = 0; i < count ; i++)
2588 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2589 ipcp_lattice<tree> *lat = &plats->itself;
2590 ipcp_value<tree> *val;
2592 if (lat->bottom
2593 || !lat->values
2594 || known_csts[i])
2595 continue;
2597 for (val = lat->values; val; val = val->next)
2599 gcc_checking_assert (TREE_CODE (val->value) != TREE_BINFO);
2600 known_csts[i] = val->value;
2602 int emc = estimate_move_cost (TREE_TYPE (val->value), true);
2603 perform_estimation_of_a_value (node, known_csts, known_contexts,
2604 known_aggs_ptrs, base_time,
2605 removable_params_cost, emc, val);
2607 if (dump_file && (dump_flags & TDF_DETAILS))
2609 fprintf (dump_file, " - estimates for value ");
2610 print_ipcp_constant_value (dump_file, val->value);
2611 fprintf (dump_file, " for ");
2612 ipa_dump_param (dump_file, info, i);
2613 fprintf (dump_file, ": time_benefit: %i, size: %i\n",
2614 val->local_time_benefit, val->local_size_cost);
2617 known_csts[i] = NULL_TREE;
2620 for (i = 0; i < count; i++)
2622 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2624 if (!plats->virt_call)
2625 continue;
2627 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2628 ipcp_value<ipa_polymorphic_call_context> *val;
2630 if (ctxlat->bottom
2631 || !ctxlat->values
2632 || !known_contexts[i].useless_p ())
2633 continue;
2635 for (val = ctxlat->values; val; val = val->next)
2637 known_contexts[i] = val->value;
2638 perform_estimation_of_a_value (node, known_csts, known_contexts,
2639 known_aggs_ptrs, base_time,
2640 removable_params_cost, 0, val);
2642 if (dump_file && (dump_flags & TDF_DETAILS))
2644 fprintf (dump_file, " - estimates for polymorphic context ");
2645 print_ipcp_constant_value (dump_file, val->value);
2646 fprintf (dump_file, " for ");
2647 ipa_dump_param (dump_file, info, i);
2648 fprintf (dump_file, ": time_benefit: %i, size: %i\n",
2649 val->local_time_benefit, val->local_size_cost);
2652 known_contexts[i] = ipa_polymorphic_call_context ();
2655 for (i = 0; i < count ; i++)
2657 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2658 struct ipa_agg_jump_function *ajf;
2659 struct ipcp_agg_lattice *aglat;
2661 if (plats->aggs_bottom || !plats->aggs)
2662 continue;
2664 ajf = &known_aggs[i];
2665 for (aglat = plats->aggs; aglat; aglat = aglat->next)
2667 ipcp_value<tree> *val;
2668 if (aglat->bottom || !aglat->values
2669 /* If the following is true, the one value is in known_aggs. */
2670 || (!plats->aggs_contain_variable
2671 && aglat->is_single_const ()))
2672 continue;
2674 for (val = aglat->values; val; val = val->next)
2676 struct ipa_agg_jf_item item;
2678 item.offset = aglat->offset;
2679 item.value = val->value;
2680 vec_safe_push (ajf->items, item);
2682 perform_estimation_of_a_value (node, known_csts, known_contexts,
2683 known_aggs_ptrs, base_time,
2684 removable_params_cost, 0, val);
2686 if (dump_file && (dump_flags & TDF_DETAILS))
2688 fprintf (dump_file, " - estimates for value ");
2689 print_ipcp_constant_value (dump_file, val->value);
2690 fprintf (dump_file, " for ");
2691 ipa_dump_param (dump_file, info, i);
2692 fprintf (dump_file, "[%soffset: " HOST_WIDE_INT_PRINT_DEC
2693 "]: time_benefit: %i, size: %i\n",
2694 plats->aggs_by_ref ? "ref " : "",
2695 aglat->offset,
2696 val->local_time_benefit, val->local_size_cost);
2699 ajf->items->pop ();
2704 for (i = 0; i < count ; i++)
2705 vec_free (known_aggs[i].items);
2707 known_csts.release ();
2708 known_contexts.release ();
2709 known_aggs.release ();
2710 known_aggs_ptrs.release ();
2714 /* Add value CUR_VAL and all yet-unsorted values it is dependent on to the
2715 topological sort of values. */
2717 template <typename valtype>
2718 void
2719 value_topo_info<valtype>::add_val (ipcp_value<valtype> *cur_val)
2721 ipcp_value_source<valtype> *src;
2723 if (cur_val->dfs)
2724 return;
2726 dfs_counter++;
2727 cur_val->dfs = dfs_counter;
2728 cur_val->low_link = dfs_counter;
2730 cur_val->topo_next = stack;
2731 stack = cur_val;
2732 cur_val->on_stack = true;
2734 for (src = cur_val->sources; src; src = src->next)
2735 if (src->val)
2737 if (src->val->dfs == 0)
2739 add_val (src->val);
2740 if (src->val->low_link < cur_val->low_link)
2741 cur_val->low_link = src->val->low_link;
2743 else if (src->val->on_stack
2744 && src->val->dfs < cur_val->low_link)
2745 cur_val->low_link = src->val->dfs;
2748 if (cur_val->dfs == cur_val->low_link)
2750 ipcp_value<valtype> *v, *scc_list = NULL;
2754 v = stack;
2755 stack = v->topo_next;
2756 v->on_stack = false;
2758 v->scc_next = scc_list;
2759 scc_list = v;
2761 while (v != cur_val);
2763 cur_val->topo_next = values_topo;
2764 values_topo = cur_val;
2768 /* Add all values in lattices associated with NODE to the topological sort if
2769 they are not there yet. */
2771 static void
2772 add_all_node_vals_to_toposort (cgraph_node *node, ipa_topo_info *topo)
2774 struct ipa_node_params *info = IPA_NODE_REF (node);
2775 int i, count = ipa_get_param_count (info);
2777 for (i = 0; i < count ; i++)
2779 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
2780 ipcp_lattice<tree> *lat = &plats->itself;
2781 struct ipcp_agg_lattice *aglat;
2783 if (!lat->bottom)
2785 ipcp_value<tree> *val;
2786 for (val = lat->values; val; val = val->next)
2787 topo->constants.add_val (val);
2790 if (!plats->aggs_bottom)
2791 for (aglat = plats->aggs; aglat; aglat = aglat->next)
2792 if (!aglat->bottom)
2794 ipcp_value<tree> *val;
2795 for (val = aglat->values; val; val = val->next)
2796 topo->constants.add_val (val);
2799 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
2800 if (!ctxlat->bottom)
2802 ipcp_value<ipa_polymorphic_call_context> *ctxval;
2803 for (ctxval = ctxlat->values; ctxval; ctxval = ctxval->next)
2804 topo->contexts.add_val (ctxval);
2809 /* One pass of constants propagation along the call graph edges, from callers
2810 to callees (requires topological ordering in TOPO), iterate over strongly
2811 connected components. */
2813 static void
2814 propagate_constants_topo (struct ipa_topo_info *topo)
2816 int i;
2818 for (i = topo->nnodes - 1; i >= 0; i--)
2820 unsigned j;
2821 struct cgraph_node *v, *node = topo->order[i];
2822 vec<cgraph_node *> cycle_nodes = ipa_get_nodes_in_cycle (node);
2824 /* First, iteratively propagate within the strongly connected component
2825 until all lattices stabilize. */
2826 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
2827 if (v->has_gimple_body_p ())
2828 push_node_to_stack (topo, v);
2830 v = pop_node_from_stack (topo);
2831 while (v)
2833 struct cgraph_edge *cs;
2835 for (cs = v->callees; cs; cs = cs->next_callee)
2836 if (ipa_edge_within_scc (cs))
2838 IPA_NODE_REF (v)->node_within_scc = true;
2839 if (propagate_constants_accross_call (cs))
2840 push_node_to_stack (topo, cs->callee->function_symbol ());
2842 v = pop_node_from_stack (topo);
2845 /* Afterwards, propagate along edges leading out of the SCC, calculates
2846 the local effects of the discovered constants and all valid values to
2847 their topological sort. */
2848 FOR_EACH_VEC_ELT (cycle_nodes, j, v)
2849 if (v->has_gimple_body_p ())
2851 struct cgraph_edge *cs;
2853 estimate_local_effects (v);
2854 add_all_node_vals_to_toposort (v, topo);
2855 for (cs = v->callees; cs; cs = cs->next_callee)
2856 if (!ipa_edge_within_scc (cs))
2857 propagate_constants_accross_call (cs);
2859 cycle_nodes.release ();
2864 /* Return the sum of A and B if none of them is bigger than INT_MAX/2, return
2865 the bigger one if otherwise. */
2867 static int
2868 safe_add (int a, int b)
2870 if (a > INT_MAX/2 || b > INT_MAX/2)
2871 return a > b ? a : b;
2872 else
2873 return a + b;
2877 /* Propagate the estimated effects of individual values along the topological
2878 from the dependent values to those they depend on. */
2880 template <typename valtype>
2881 void
2882 value_topo_info<valtype>::propagate_effects ()
2884 ipcp_value<valtype> *base;
2886 for (base = values_topo; base; base = base->topo_next)
2888 ipcp_value_source<valtype> *src;
2889 ipcp_value<valtype> *val;
2890 int time = 0, size = 0;
2892 for (val = base; val; val = val->scc_next)
2894 time = safe_add (time,
2895 val->local_time_benefit + val->prop_time_benefit);
2896 size = safe_add (size, val->local_size_cost + val->prop_size_cost);
2899 for (val = base; val; val = val->scc_next)
2900 for (src = val->sources; src; src = src->next)
2901 if (src->val
2902 && src->cs->maybe_hot_p ())
2904 src->val->prop_time_benefit = safe_add (time,
2905 src->val->prop_time_benefit);
2906 src->val->prop_size_cost = safe_add (size,
2907 src->val->prop_size_cost);
2913 /* Propagate constants, polymorphic contexts and their effects from the
2914 summaries interprocedurally. */
2916 static void
2917 ipcp_propagate_stage (struct ipa_topo_info *topo)
2919 struct cgraph_node *node;
2921 if (dump_file)
2922 fprintf (dump_file, "\n Propagating constants:\n\n");
2924 if (in_lto_p)
2925 ipa_update_after_lto_read ();
2928 FOR_EACH_DEFINED_FUNCTION (node)
2930 struct ipa_node_params *info = IPA_NODE_REF (node);
2932 determine_versionability (node, info);
2933 if (node->has_gimple_body_p ())
2935 info->lattices = XCNEWVEC (struct ipcp_param_lattices,
2936 ipa_get_param_count (info));
2937 initialize_node_lattices (node);
2939 if (node->definition && !node->alias)
2940 overall_size += inline_summaries->get (node)->self_size;
2941 if (node->count > max_count)
2942 max_count = node->count;
2945 max_new_size = overall_size;
2946 if (max_new_size < PARAM_VALUE (PARAM_LARGE_UNIT_INSNS))
2947 max_new_size = PARAM_VALUE (PARAM_LARGE_UNIT_INSNS);
2948 max_new_size += max_new_size * PARAM_VALUE (PARAM_IPCP_UNIT_GROWTH) / 100 + 1;
2950 if (dump_file)
2951 fprintf (dump_file, "\noverall_size: %li, max_new_size: %li\n",
2952 overall_size, max_new_size);
2954 propagate_constants_topo (topo);
2955 if (flag_checking)
2956 ipcp_verify_propagated_values ();
2957 topo->constants.propagate_effects ();
2958 topo->contexts.propagate_effects ();
2960 if (dump_file)
2962 fprintf (dump_file, "\nIPA lattices after all propagation:\n");
2963 print_all_lattices (dump_file, (dump_flags & TDF_DETAILS), true);
2967 /* Discover newly direct outgoing edges from NODE which is a new clone with
2968 known KNOWN_CSTS and make them direct. */
2970 static void
2971 ipcp_discover_new_direct_edges (struct cgraph_node *node,
2972 vec<tree> known_csts,
2973 vec<ipa_polymorphic_call_context>
2974 known_contexts,
2975 struct ipa_agg_replacement_value *aggvals)
2977 struct cgraph_edge *ie, *next_ie;
2978 bool found = false;
2980 for (ie = node->indirect_calls; ie; ie = next_ie)
2982 tree target;
2983 bool speculative;
2985 next_ie = ie->next_callee;
2986 target = ipa_get_indirect_edge_target_1 (ie, known_csts, known_contexts,
2987 vNULL, aggvals, &speculative);
2988 if (target)
2990 bool agg_contents = ie->indirect_info->agg_contents;
2991 bool polymorphic = ie->indirect_info->polymorphic;
2992 int param_index = ie->indirect_info->param_index;
2993 struct cgraph_edge *cs = ipa_make_edge_direct_to_target (ie, target,
2994 speculative);
2995 found = true;
2997 if (cs && !agg_contents && !polymorphic)
2999 struct ipa_node_params *info = IPA_NODE_REF (node);
3000 int c = ipa_get_controlled_uses (info, param_index);
3001 if (c != IPA_UNDESCRIBED_USE)
3003 struct ipa_ref *to_del;
3005 c--;
3006 ipa_set_controlled_uses (info, param_index, c);
3007 if (dump_file && (dump_flags & TDF_DETAILS))
3008 fprintf (dump_file, " controlled uses count of param "
3009 "%i bumped down to %i\n", param_index, c);
3010 if (c == 0
3011 && (to_del = node->find_reference (cs->callee, NULL, 0)))
3013 if (dump_file && (dump_flags & TDF_DETAILS))
3014 fprintf (dump_file, " and even removing its "
3015 "cloning-created reference\n");
3016 to_del->remove_reference ();
3022 /* Turning calls to direct calls will improve overall summary. */
3023 if (found)
3024 inline_update_overall_summary (node);
3027 /* Vector of pointers which for linked lists of clones of an original crgaph
3028 edge. */
3030 static vec<cgraph_edge *> next_edge_clone;
3031 static vec<cgraph_edge *> prev_edge_clone;
3033 static inline void
3034 grow_edge_clone_vectors (void)
3036 if (next_edge_clone.length ()
3037 <= (unsigned) symtab->edges_max_uid)
3038 next_edge_clone.safe_grow_cleared (symtab->edges_max_uid + 1);
3039 if (prev_edge_clone.length ()
3040 <= (unsigned) symtab->edges_max_uid)
3041 prev_edge_clone.safe_grow_cleared (symtab->edges_max_uid + 1);
3044 /* Edge duplication hook to grow the appropriate linked list in
3045 next_edge_clone. */
3047 static void
3048 ipcp_edge_duplication_hook (struct cgraph_edge *src, struct cgraph_edge *dst,
3049 void *)
3051 grow_edge_clone_vectors ();
3053 struct cgraph_edge *old_next = next_edge_clone[src->uid];
3054 if (old_next)
3055 prev_edge_clone[old_next->uid] = dst;
3056 prev_edge_clone[dst->uid] = src;
3058 next_edge_clone[dst->uid] = old_next;
3059 next_edge_clone[src->uid] = dst;
3062 /* Hook that is called by cgraph.c when an edge is removed. */
3064 static void
3065 ipcp_edge_removal_hook (struct cgraph_edge *cs, void *)
3067 grow_edge_clone_vectors ();
3069 struct cgraph_edge *prev = prev_edge_clone[cs->uid];
3070 struct cgraph_edge *next = next_edge_clone[cs->uid];
3071 if (prev)
3072 next_edge_clone[prev->uid] = next;
3073 if (next)
3074 prev_edge_clone[next->uid] = prev;
3077 /* See if NODE is a clone with a known aggregate value at a given OFFSET of a
3078 parameter with the given INDEX. */
3080 static tree
3081 get_clone_agg_value (struct cgraph_node *node, HOST_WIDE_INT offset,
3082 int index)
3084 struct ipa_agg_replacement_value *aggval;
3086 aggval = ipa_get_agg_replacements_for_node (node);
3087 while (aggval)
3089 if (aggval->offset == offset
3090 && aggval->index == index)
3091 return aggval->value;
3092 aggval = aggval->next;
3094 return NULL_TREE;
3097 /* Return true is NODE is DEST or its clone for all contexts. */
3099 static bool
3100 same_node_or_its_all_contexts_clone_p (cgraph_node *node, cgraph_node *dest)
3102 if (node == dest)
3103 return true;
3105 struct ipa_node_params *info = IPA_NODE_REF (node);
3106 return info->is_all_contexts_clone && info->ipcp_orig_node == dest;
3109 /* Return true if edge CS does bring about the value described by SRC to node
3110 DEST or its clone for all contexts. */
3112 static bool
3113 cgraph_edge_brings_value_p (cgraph_edge *cs, ipcp_value_source<tree> *src,
3114 cgraph_node *dest)
3116 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3117 enum availability availability;
3118 cgraph_node *real_dest = cs->callee->function_symbol (&availability);
3120 if (!same_node_or_its_all_contexts_clone_p (real_dest, dest)
3121 || availability <= AVAIL_INTERPOSABLE
3122 || caller_info->node_dead)
3123 return false;
3124 if (!src->val)
3125 return true;
3127 if (caller_info->ipcp_orig_node)
3129 tree t;
3130 if (src->offset == -1)
3131 t = caller_info->known_csts[src->index];
3132 else
3133 t = get_clone_agg_value (cs->caller, src->offset, src->index);
3134 return (t != NULL_TREE
3135 && values_equal_for_ipcp_p (src->val->value, t));
3137 else
3139 struct ipcp_agg_lattice *aglat;
3140 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
3141 src->index);
3142 if (src->offset == -1)
3143 return (plats->itself.is_single_const ()
3144 && values_equal_for_ipcp_p (src->val->value,
3145 plats->itself.values->value));
3146 else
3148 if (plats->aggs_bottom || plats->aggs_contain_variable)
3149 return false;
3150 for (aglat = plats->aggs; aglat; aglat = aglat->next)
3151 if (aglat->offset == src->offset)
3152 return (aglat->is_single_const ()
3153 && values_equal_for_ipcp_p (src->val->value,
3154 aglat->values->value));
3156 return false;
3160 /* Return true if edge CS does bring about the value described by SRC to node
3161 DEST or its clone for all contexts. */
3163 static bool
3164 cgraph_edge_brings_value_p (cgraph_edge *cs,
3165 ipcp_value_source<ipa_polymorphic_call_context> *src,
3166 cgraph_node *dest)
3168 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3169 cgraph_node *real_dest = cs->callee->function_symbol ();
3171 if (!same_node_or_its_all_contexts_clone_p (real_dest, dest)
3172 || caller_info->node_dead)
3173 return false;
3174 if (!src->val)
3175 return true;
3177 if (caller_info->ipcp_orig_node)
3178 return (caller_info->known_contexts.length () > (unsigned) src->index)
3179 && values_equal_for_ipcp_p (src->val->value,
3180 caller_info->known_contexts[src->index]);
3182 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (caller_info,
3183 src->index);
3184 return plats->ctxlat.is_single_const ()
3185 && values_equal_for_ipcp_p (src->val->value,
3186 plats->ctxlat.values->value);
3189 /* Get the next clone in the linked list of clones of an edge. */
3191 static inline struct cgraph_edge *
3192 get_next_cgraph_edge_clone (struct cgraph_edge *cs)
3194 return next_edge_clone[cs->uid];
3197 /* Given VAL that is intended for DEST, iterate over all its sources and if
3198 they still hold, add their edge frequency and their number into *FREQUENCY
3199 and *CALLER_COUNT respectively. */
3201 template <typename valtype>
3202 static bool
3203 get_info_about_necessary_edges (ipcp_value<valtype> *val, cgraph_node *dest,
3204 int *freq_sum,
3205 gcov_type *count_sum, int *caller_count)
3207 ipcp_value_source<valtype> *src;
3208 int freq = 0, count = 0;
3209 gcov_type cnt = 0;
3210 bool hot = false;
3212 for (src = val->sources; src; src = src->next)
3214 struct cgraph_edge *cs = src->cs;
3215 while (cs)
3217 if (cgraph_edge_brings_value_p (cs, src, dest))
3219 count++;
3220 freq += cs->frequency;
3221 cnt += cs->count;
3222 hot |= cs->maybe_hot_p ();
3224 cs = get_next_cgraph_edge_clone (cs);
3228 *freq_sum = freq;
3229 *count_sum = cnt;
3230 *caller_count = count;
3231 return hot;
3234 /* Return a vector of incoming edges that do bring value VAL to node DEST. It
3235 is assumed their number is known and equal to CALLER_COUNT. */
3237 template <typename valtype>
3238 static vec<cgraph_edge *>
3239 gather_edges_for_value (ipcp_value<valtype> *val, cgraph_node *dest,
3240 int caller_count)
3242 ipcp_value_source<valtype> *src;
3243 vec<cgraph_edge *> ret;
3245 ret.create (caller_count);
3246 for (src = val->sources; src; src = src->next)
3248 struct cgraph_edge *cs = src->cs;
3249 while (cs)
3251 if (cgraph_edge_brings_value_p (cs, src, dest))
3252 ret.quick_push (cs);
3253 cs = get_next_cgraph_edge_clone (cs);
3257 return ret;
3260 /* Construct a replacement map for a know VALUE for a formal parameter PARAM.
3261 Return it or NULL if for some reason it cannot be created. */
3263 static struct ipa_replace_map *
3264 get_replacement_map (struct ipa_node_params *info, tree value, int parm_num)
3266 struct ipa_replace_map *replace_map;
3269 replace_map = ggc_alloc<ipa_replace_map> ();
3270 if (dump_file)
3272 fprintf (dump_file, " replacing ");
3273 ipa_dump_param (dump_file, info, parm_num);
3275 fprintf (dump_file, " with const ");
3276 print_generic_expr (dump_file, value, 0);
3277 fprintf (dump_file, "\n");
3279 replace_map->old_tree = NULL;
3280 replace_map->parm_num = parm_num;
3281 replace_map->new_tree = value;
3282 replace_map->replace_p = true;
3283 replace_map->ref_p = false;
3285 return replace_map;
3288 /* Dump new profiling counts */
3290 static void
3291 dump_profile_updates (struct cgraph_node *orig_node,
3292 struct cgraph_node *new_node)
3294 struct cgraph_edge *cs;
3296 fprintf (dump_file, " setting count of the specialized node to "
3297 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) new_node->count);
3298 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3299 fprintf (dump_file, " edge to %s has count "
3300 HOST_WIDE_INT_PRINT_DEC "\n",
3301 cs->callee->name (), (HOST_WIDE_INT) cs->count);
3303 fprintf (dump_file, " setting count of the original node to "
3304 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) orig_node->count);
3305 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3306 fprintf (dump_file, " edge to %s is left with "
3307 HOST_WIDE_INT_PRINT_DEC "\n",
3308 cs->callee->name (), (HOST_WIDE_INT) cs->count);
3311 /* After a specialized NEW_NODE version of ORIG_NODE has been created, update
3312 their profile information to reflect this. */
3314 static void
3315 update_profiling_info (struct cgraph_node *orig_node,
3316 struct cgraph_node *new_node)
3318 struct cgraph_edge *cs;
3319 struct caller_statistics stats;
3320 gcov_type new_sum, orig_sum;
3321 gcov_type remainder, orig_node_count = orig_node->count;
3323 if (orig_node_count == 0)
3324 return;
3326 init_caller_stats (&stats);
3327 orig_node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
3328 false);
3329 orig_sum = stats.count_sum;
3330 init_caller_stats (&stats);
3331 new_node->call_for_symbol_thunks_and_aliases (gather_caller_stats, &stats,
3332 false);
3333 new_sum = stats.count_sum;
3335 if (orig_node_count < orig_sum + new_sum)
3337 if (dump_file)
3338 fprintf (dump_file, " Problem: node %s/%i has too low count "
3339 HOST_WIDE_INT_PRINT_DEC " while the sum of incoming "
3340 "counts is " HOST_WIDE_INT_PRINT_DEC "\n",
3341 orig_node->name (), orig_node->order,
3342 (HOST_WIDE_INT) orig_node_count,
3343 (HOST_WIDE_INT) (orig_sum + new_sum));
3345 orig_node_count = (orig_sum + new_sum) * 12 / 10;
3346 if (dump_file)
3347 fprintf (dump_file, " proceeding by pretending it was "
3348 HOST_WIDE_INT_PRINT_DEC "\n",
3349 (HOST_WIDE_INT) orig_node_count);
3352 new_node->count = new_sum;
3353 remainder = orig_node_count - new_sum;
3354 orig_node->count = remainder;
3356 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3357 if (cs->frequency)
3358 cs->count = apply_probability (cs->count,
3359 GCOV_COMPUTE_SCALE (new_sum,
3360 orig_node_count));
3361 else
3362 cs->count = 0;
3364 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3365 cs->count = apply_probability (cs->count,
3366 GCOV_COMPUTE_SCALE (remainder,
3367 orig_node_count));
3369 if (dump_file)
3370 dump_profile_updates (orig_node, new_node);
3373 /* Update the respective profile of specialized NEW_NODE and the original
3374 ORIG_NODE after additional edges with cumulative count sum REDIRECTED_SUM
3375 have been redirected to the specialized version. */
3377 static void
3378 update_specialized_profile (struct cgraph_node *new_node,
3379 struct cgraph_node *orig_node,
3380 gcov_type redirected_sum)
3382 struct cgraph_edge *cs;
3383 gcov_type new_node_count, orig_node_count = orig_node->count;
3385 if (dump_file)
3386 fprintf (dump_file, " the sum of counts of redirected edges is "
3387 HOST_WIDE_INT_PRINT_DEC "\n", (HOST_WIDE_INT) redirected_sum);
3388 if (orig_node_count == 0)
3389 return;
3391 gcc_assert (orig_node_count >= redirected_sum);
3393 new_node_count = new_node->count;
3394 new_node->count += redirected_sum;
3395 orig_node->count -= redirected_sum;
3397 for (cs = new_node->callees; cs ; cs = cs->next_callee)
3398 if (cs->frequency)
3399 cs->count += apply_probability (cs->count,
3400 GCOV_COMPUTE_SCALE (redirected_sum,
3401 new_node_count));
3402 else
3403 cs->count = 0;
3405 for (cs = orig_node->callees; cs ; cs = cs->next_callee)
3407 gcov_type dec = apply_probability (cs->count,
3408 GCOV_COMPUTE_SCALE (redirected_sum,
3409 orig_node_count));
3410 if (dec < cs->count)
3411 cs->count -= dec;
3412 else
3413 cs->count = 0;
3416 if (dump_file)
3417 dump_profile_updates (orig_node, new_node);
3420 /* Create a specialized version of NODE with known constants in KNOWN_CSTS,
3421 known contexts in KNOWN_CONTEXTS and known aggregate values in AGGVALS and
3422 redirect all edges in CALLERS to it. */
3424 static struct cgraph_node *
3425 create_specialized_node (struct cgraph_node *node,
3426 vec<tree> known_csts,
3427 vec<ipa_polymorphic_call_context> known_contexts,
3428 struct ipa_agg_replacement_value *aggvals,
3429 vec<cgraph_edge *> callers)
3431 struct ipa_node_params *new_info, *info = IPA_NODE_REF (node);
3432 vec<ipa_replace_map *, va_gc> *replace_trees = NULL;
3433 struct ipa_agg_replacement_value *av;
3434 struct cgraph_node *new_node;
3435 int i, count = ipa_get_param_count (info);
3436 bitmap args_to_skip;
3438 gcc_assert (!info->ipcp_orig_node);
3440 if (node->local.can_change_signature)
3442 args_to_skip = BITMAP_GGC_ALLOC ();
3443 for (i = 0; i < count; i++)
3445 tree t = known_csts[i];
3447 if (t || !ipa_is_param_used (info, i))
3448 bitmap_set_bit (args_to_skip, i);
3451 else
3453 args_to_skip = NULL;
3454 if (dump_file && (dump_flags & TDF_DETAILS))
3455 fprintf (dump_file, " cannot change function signature\n");
3458 for (i = 0; i < count ; i++)
3460 tree t = known_csts[i];
3461 if (t)
3463 struct ipa_replace_map *replace_map;
3465 gcc_checking_assert (TREE_CODE (t) != TREE_BINFO);
3466 replace_map = get_replacement_map (info, t, i);
3467 if (replace_map)
3468 vec_safe_push (replace_trees, replace_map);
3472 new_node = node->create_virtual_clone (callers, replace_trees,
3473 args_to_skip, "constprop");
3474 ipa_set_node_agg_value_chain (new_node, aggvals);
3475 for (av = aggvals; av; av = av->next)
3476 new_node->maybe_create_reference (av->value, IPA_REF_ADDR, NULL);
3478 if (dump_file && (dump_flags & TDF_DETAILS))
3480 fprintf (dump_file, " the new node is %s/%i.\n",
3481 new_node->name (), new_node->order);
3482 if (known_contexts.exists ())
3484 for (i = 0; i < count ; i++)
3485 if (!known_contexts[i].useless_p ())
3487 fprintf (dump_file, " known ctx %i is ", i);
3488 known_contexts[i].dump (dump_file);
3491 if (aggvals)
3492 ipa_dump_agg_replacement_values (dump_file, aggvals);
3494 ipa_check_create_node_params ();
3495 update_profiling_info (node, new_node);
3496 new_info = IPA_NODE_REF (new_node);
3497 new_info->ipcp_orig_node = node;
3498 new_info->known_csts = known_csts;
3499 new_info->known_contexts = known_contexts;
3501 ipcp_discover_new_direct_edges (new_node, known_csts, known_contexts, aggvals);
3503 callers.release ();
3504 return new_node;
3507 /* Given a NODE, and a subset of its CALLERS, try to populate blanks slots in
3508 KNOWN_CSTS with constants that are also known for all of the CALLERS. */
3510 static void
3511 find_more_scalar_values_for_callers_subset (struct cgraph_node *node,
3512 vec<tree> known_csts,
3513 vec<cgraph_edge *> callers)
3515 struct ipa_node_params *info = IPA_NODE_REF (node);
3516 int i, count = ipa_get_param_count (info);
3518 for (i = 0; i < count ; i++)
3520 struct cgraph_edge *cs;
3521 tree newval = NULL_TREE;
3522 int j;
3523 bool first = true;
3525 if (ipa_get_scalar_lat (info, i)->bottom || known_csts[i])
3526 continue;
3528 FOR_EACH_VEC_ELT (callers, j, cs)
3530 struct ipa_jump_func *jump_func;
3531 tree t;
3533 if (i >= ipa_get_cs_argument_count (IPA_EDGE_REF (cs))
3534 || (i == 0
3535 && call_passes_through_thunk_p (cs))
3536 || (!cs->callee->instrumentation_clone
3537 && cs->callee->function_symbol ()->instrumentation_clone))
3539 newval = NULL_TREE;
3540 break;
3542 jump_func = ipa_get_ith_jump_func (IPA_EDGE_REF (cs), i);
3543 t = ipa_value_from_jfunc (IPA_NODE_REF (cs->caller), jump_func);
3544 if (!t
3545 || (newval
3546 && !values_equal_for_ipcp_p (t, newval))
3547 || (!first && !newval))
3549 newval = NULL_TREE;
3550 break;
3552 else
3553 newval = t;
3554 first = false;
3557 if (newval)
3559 if (dump_file && (dump_flags & TDF_DETAILS))
3561 fprintf (dump_file, " adding an extra known scalar value ");
3562 print_ipcp_constant_value (dump_file, newval);
3563 fprintf (dump_file, " for ");
3564 ipa_dump_param (dump_file, info, i);
3565 fprintf (dump_file, "\n");
3568 known_csts[i] = newval;
3573 /* Given a NODE and a subset of its CALLERS, try to populate plank slots in
3574 KNOWN_CONTEXTS with polymorphic contexts that are also known for all of the
3575 CALLERS. */
3577 static void
3578 find_more_contexts_for_caller_subset (cgraph_node *node,
3579 vec<ipa_polymorphic_call_context>
3580 *known_contexts,
3581 vec<cgraph_edge *> callers)
3583 ipa_node_params *info = IPA_NODE_REF (node);
3584 int i, count = ipa_get_param_count (info);
3586 for (i = 0; i < count ; i++)
3588 cgraph_edge *cs;
3590 if (ipa_get_poly_ctx_lat (info, i)->bottom
3591 || (known_contexts->exists ()
3592 && !(*known_contexts)[i].useless_p ()))
3593 continue;
3595 ipa_polymorphic_call_context newval;
3596 bool first = true;
3597 int j;
3599 FOR_EACH_VEC_ELT (callers, j, cs)
3601 if (i >= ipa_get_cs_argument_count (IPA_EDGE_REF (cs)))
3602 return;
3603 ipa_jump_func *jfunc = ipa_get_ith_jump_func (IPA_EDGE_REF (cs),
3605 ipa_polymorphic_call_context ctx;
3606 ctx = ipa_context_from_jfunc (IPA_NODE_REF (cs->caller), cs, i,
3607 jfunc);
3608 if (first)
3610 newval = ctx;
3611 first = false;
3613 else
3614 newval.meet_with (ctx);
3615 if (newval.useless_p ())
3616 break;
3619 if (!newval.useless_p ())
3621 if (dump_file && (dump_flags & TDF_DETAILS))
3623 fprintf (dump_file, " adding an extra known polymorphic "
3624 "context ");
3625 print_ipcp_constant_value (dump_file, newval);
3626 fprintf (dump_file, " for ");
3627 ipa_dump_param (dump_file, info, i);
3628 fprintf (dump_file, "\n");
3631 if (!known_contexts->exists ())
3632 known_contexts->safe_grow_cleared (ipa_get_param_count (info));
3633 (*known_contexts)[i] = newval;
3639 /* Go through PLATS and create a vector of values consisting of values and
3640 offsets (minus OFFSET) of lattices that contain only a single value. */
3642 static vec<ipa_agg_jf_item>
3643 copy_plats_to_inter (struct ipcp_param_lattices *plats, HOST_WIDE_INT offset)
3645 vec<ipa_agg_jf_item> res = vNULL;
3647 if (!plats->aggs || plats->aggs_contain_variable || plats->aggs_bottom)
3648 return vNULL;
3650 for (struct ipcp_agg_lattice *aglat = plats->aggs; aglat; aglat = aglat->next)
3651 if (aglat->is_single_const ())
3653 struct ipa_agg_jf_item ti;
3654 ti.offset = aglat->offset - offset;
3655 ti.value = aglat->values->value;
3656 res.safe_push (ti);
3658 return res;
3661 /* Intersect all values in INTER with single value lattices in PLATS (while
3662 subtracting OFFSET). */
3664 static void
3665 intersect_with_plats (struct ipcp_param_lattices *plats,
3666 vec<ipa_agg_jf_item> *inter,
3667 HOST_WIDE_INT offset)
3669 struct ipcp_agg_lattice *aglat;
3670 struct ipa_agg_jf_item *item;
3671 int k;
3673 if (!plats->aggs || plats->aggs_contain_variable || plats->aggs_bottom)
3675 inter->release ();
3676 return;
3679 aglat = plats->aggs;
3680 FOR_EACH_VEC_ELT (*inter, k, item)
3682 bool found = false;
3683 if (!item->value)
3684 continue;
3685 while (aglat)
3687 if (aglat->offset - offset > item->offset)
3688 break;
3689 if (aglat->offset - offset == item->offset)
3691 gcc_checking_assert (item->value);
3692 if (values_equal_for_ipcp_p (item->value, aglat->values->value))
3693 found = true;
3694 break;
3696 aglat = aglat->next;
3698 if (!found)
3699 item->value = NULL_TREE;
3703 /* Copy agggregate replacement values of NODE (which is an IPA-CP clone) to the
3704 vector result while subtracting OFFSET from the individual value offsets. */
3706 static vec<ipa_agg_jf_item>
3707 agg_replacements_to_vector (struct cgraph_node *node, int index,
3708 HOST_WIDE_INT offset)
3710 struct ipa_agg_replacement_value *av;
3711 vec<ipa_agg_jf_item> res = vNULL;
3713 for (av = ipa_get_agg_replacements_for_node (node); av; av = av->next)
3714 if (av->index == index
3715 && (av->offset - offset) >= 0)
3717 struct ipa_agg_jf_item item;
3718 gcc_checking_assert (av->value);
3719 item.offset = av->offset - offset;
3720 item.value = av->value;
3721 res.safe_push (item);
3724 return res;
3727 /* Intersect all values in INTER with those that we have already scheduled to
3728 be replaced in parameter number INDEX of NODE, which is an IPA-CP clone
3729 (while subtracting OFFSET). */
3731 static void
3732 intersect_with_agg_replacements (struct cgraph_node *node, int index,
3733 vec<ipa_agg_jf_item> *inter,
3734 HOST_WIDE_INT offset)
3736 struct ipa_agg_replacement_value *srcvals;
3737 struct ipa_agg_jf_item *item;
3738 int i;
3740 srcvals = ipa_get_agg_replacements_for_node (node);
3741 if (!srcvals)
3743 inter->release ();
3744 return;
3747 FOR_EACH_VEC_ELT (*inter, i, item)
3749 struct ipa_agg_replacement_value *av;
3750 bool found = false;
3751 if (!item->value)
3752 continue;
3753 for (av = srcvals; av; av = av->next)
3755 gcc_checking_assert (av->value);
3756 if (av->index == index
3757 && av->offset - offset == item->offset)
3759 if (values_equal_for_ipcp_p (item->value, av->value))
3760 found = true;
3761 break;
3764 if (!found)
3765 item->value = NULL_TREE;
3769 /* Intersect values in INTER with aggregate values that come along edge CS to
3770 parameter number INDEX and return it. If INTER does not actually exist yet,
3771 copy all incoming values to it. If we determine we ended up with no values
3772 whatsoever, return a released vector. */
3774 static vec<ipa_agg_jf_item>
3775 intersect_aggregates_with_edge (struct cgraph_edge *cs, int index,
3776 vec<ipa_agg_jf_item> inter)
3778 struct ipa_jump_func *jfunc;
3779 jfunc = ipa_get_ith_jump_func (IPA_EDGE_REF (cs), index);
3780 if (jfunc->type == IPA_JF_PASS_THROUGH
3781 && ipa_get_jf_pass_through_operation (jfunc) == NOP_EXPR)
3783 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3784 int src_idx = ipa_get_jf_pass_through_formal_id (jfunc);
3786 if (caller_info->ipcp_orig_node)
3788 struct cgraph_node *orig_node = caller_info->ipcp_orig_node;
3789 struct ipcp_param_lattices *orig_plats;
3790 orig_plats = ipa_get_parm_lattices (IPA_NODE_REF (orig_node),
3791 src_idx);
3792 if (agg_pass_through_permissible_p (orig_plats, jfunc))
3794 if (!inter.exists ())
3795 inter = agg_replacements_to_vector (cs->caller, src_idx, 0);
3796 else
3797 intersect_with_agg_replacements (cs->caller, src_idx,
3798 &inter, 0);
3800 else
3802 inter.release ();
3803 return vNULL;
3806 else
3808 struct ipcp_param_lattices *src_plats;
3809 src_plats = ipa_get_parm_lattices (caller_info, src_idx);
3810 if (agg_pass_through_permissible_p (src_plats, jfunc))
3812 /* Currently we do not produce clobber aggregate jump
3813 functions, adjust when we do. */
3814 gcc_checking_assert (!jfunc->agg.items);
3815 if (!inter.exists ())
3816 inter = copy_plats_to_inter (src_plats, 0);
3817 else
3818 intersect_with_plats (src_plats, &inter, 0);
3820 else
3822 inter.release ();
3823 return vNULL;
3827 else if (jfunc->type == IPA_JF_ANCESTOR
3828 && ipa_get_jf_ancestor_agg_preserved (jfunc))
3830 struct ipa_node_params *caller_info = IPA_NODE_REF (cs->caller);
3831 int src_idx = ipa_get_jf_ancestor_formal_id (jfunc);
3832 struct ipcp_param_lattices *src_plats;
3833 HOST_WIDE_INT delta = ipa_get_jf_ancestor_offset (jfunc);
3835 if (caller_info->ipcp_orig_node)
3837 if (!inter.exists ())
3838 inter = agg_replacements_to_vector (cs->caller, src_idx, delta);
3839 else
3840 intersect_with_agg_replacements (cs->caller, src_idx, &inter,
3841 delta);
3843 else
3845 src_plats = ipa_get_parm_lattices (caller_info, src_idx);;
3846 /* Currently we do not produce clobber aggregate jump
3847 functions, adjust when we do. */
3848 gcc_checking_assert (!src_plats->aggs || !jfunc->agg.items);
3849 if (!inter.exists ())
3850 inter = copy_plats_to_inter (src_plats, delta);
3851 else
3852 intersect_with_plats (src_plats, &inter, delta);
3855 else if (jfunc->agg.items)
3857 struct ipa_agg_jf_item *item;
3858 int k;
3860 if (!inter.exists ())
3861 for (unsigned i = 0; i < jfunc->agg.items->length (); i++)
3862 inter.safe_push ((*jfunc->agg.items)[i]);
3863 else
3864 FOR_EACH_VEC_ELT (inter, k, item)
3866 int l = 0;
3867 bool found = false;;
3869 if (!item->value)
3870 continue;
3872 while ((unsigned) l < jfunc->agg.items->length ())
3874 struct ipa_agg_jf_item *ti;
3875 ti = &(*jfunc->agg.items)[l];
3876 if (ti->offset > item->offset)
3877 break;
3878 if (ti->offset == item->offset)
3880 gcc_checking_assert (ti->value);
3881 if (values_equal_for_ipcp_p (item->value,
3882 ti->value))
3883 found = true;
3884 break;
3886 l++;
3888 if (!found)
3889 item->value = NULL;
3892 else
3894 inter.release ();
3895 return vec<ipa_agg_jf_item>();
3897 return inter;
3900 /* Look at edges in CALLERS and collect all known aggregate values that arrive
3901 from all of them. */
3903 static struct ipa_agg_replacement_value *
3904 find_aggregate_values_for_callers_subset (struct cgraph_node *node,
3905 vec<cgraph_edge *> callers)
3907 struct ipa_node_params *dest_info = IPA_NODE_REF (node);
3908 struct ipa_agg_replacement_value *res;
3909 struct ipa_agg_replacement_value **tail = &res;
3910 struct cgraph_edge *cs;
3911 int i, j, count = ipa_get_param_count (dest_info);
3913 FOR_EACH_VEC_ELT (callers, j, cs)
3915 int c = ipa_get_cs_argument_count (IPA_EDGE_REF (cs));
3916 if (c < count)
3917 count = c;
3920 for (i = 0; i < count ; i++)
3922 struct cgraph_edge *cs;
3923 vec<ipa_agg_jf_item> inter = vNULL;
3924 struct ipa_agg_jf_item *item;
3925 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (dest_info, i);
3926 int j;
3928 /* Among other things, the following check should deal with all by_ref
3929 mismatches. */
3930 if (plats->aggs_bottom)
3931 continue;
3933 FOR_EACH_VEC_ELT (callers, j, cs)
3935 inter = intersect_aggregates_with_edge (cs, i, inter);
3937 if (!inter.exists ())
3938 goto next_param;
3941 FOR_EACH_VEC_ELT (inter, j, item)
3943 struct ipa_agg_replacement_value *v;
3945 if (!item->value)
3946 continue;
3948 v = ggc_alloc<ipa_agg_replacement_value> ();
3949 v->index = i;
3950 v->offset = item->offset;
3951 v->value = item->value;
3952 v->by_ref = plats->aggs_by_ref;
3953 *tail = v;
3954 tail = &v->next;
3957 next_param:
3958 if (inter.exists ())
3959 inter.release ();
3961 *tail = NULL;
3962 return res;
3965 /* Turn KNOWN_AGGS into a list of aggreate replacement values. */
3967 static struct ipa_agg_replacement_value *
3968 known_aggs_to_agg_replacement_list (vec<ipa_agg_jump_function> known_aggs)
3970 struct ipa_agg_replacement_value *res;
3971 struct ipa_agg_replacement_value **tail = &res;
3972 struct ipa_agg_jump_function *aggjf;
3973 struct ipa_agg_jf_item *item;
3974 int i, j;
3976 FOR_EACH_VEC_ELT (known_aggs, i, aggjf)
3977 FOR_EACH_VEC_SAFE_ELT (aggjf->items, j, item)
3979 struct ipa_agg_replacement_value *v;
3980 v = ggc_alloc<ipa_agg_replacement_value> ();
3981 v->index = i;
3982 v->offset = item->offset;
3983 v->value = item->value;
3984 v->by_ref = aggjf->by_ref;
3985 *tail = v;
3986 tail = &v->next;
3988 *tail = NULL;
3989 return res;
3992 /* Determine whether CS also brings all scalar values that the NODE is
3993 specialized for. */
3995 static bool
3996 cgraph_edge_brings_all_scalars_for_node (struct cgraph_edge *cs,
3997 struct cgraph_node *node)
3999 struct ipa_node_params *dest_info = IPA_NODE_REF (node);
4000 int count = ipa_get_param_count (dest_info);
4001 struct ipa_node_params *caller_info;
4002 struct ipa_edge_args *args;
4003 int i;
4005 caller_info = IPA_NODE_REF (cs->caller);
4006 args = IPA_EDGE_REF (cs);
4007 for (i = 0; i < count; i++)
4009 struct ipa_jump_func *jump_func;
4010 tree val, t;
4012 val = dest_info->known_csts[i];
4013 if (!val)
4014 continue;
4016 if (i >= ipa_get_cs_argument_count (args))
4017 return false;
4018 jump_func = ipa_get_ith_jump_func (args, i);
4019 t = ipa_value_from_jfunc (caller_info, jump_func);
4020 if (!t || !values_equal_for_ipcp_p (val, t))
4021 return false;
4023 return true;
4026 /* Determine whether CS also brings all aggregate values that NODE is
4027 specialized for. */
4028 static bool
4029 cgraph_edge_brings_all_agg_vals_for_node (struct cgraph_edge *cs,
4030 struct cgraph_node *node)
4032 struct ipa_node_params *orig_caller_info = IPA_NODE_REF (cs->caller);
4033 struct ipa_node_params *orig_node_info;
4034 struct ipa_agg_replacement_value *aggval;
4035 int i, ec, count;
4037 aggval = ipa_get_agg_replacements_for_node (node);
4038 if (!aggval)
4039 return true;
4041 count = ipa_get_param_count (IPA_NODE_REF (node));
4042 ec = ipa_get_cs_argument_count (IPA_EDGE_REF (cs));
4043 if (ec < count)
4044 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4045 if (aggval->index >= ec)
4046 return false;
4048 orig_node_info = IPA_NODE_REF (IPA_NODE_REF (node)->ipcp_orig_node);
4049 if (orig_caller_info->ipcp_orig_node)
4050 orig_caller_info = IPA_NODE_REF (orig_caller_info->ipcp_orig_node);
4052 for (i = 0; i < count; i++)
4054 static vec<ipa_agg_jf_item> values = vec<ipa_agg_jf_item>();
4055 struct ipcp_param_lattices *plats;
4056 bool interesting = false;
4057 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4058 if (aggval->index == i)
4060 interesting = true;
4061 break;
4063 if (!interesting)
4064 continue;
4066 plats = ipa_get_parm_lattices (orig_node_info, aggval->index);
4067 if (plats->aggs_bottom)
4068 return false;
4070 values = intersect_aggregates_with_edge (cs, i, values);
4071 if (!values.exists ())
4072 return false;
4074 for (struct ipa_agg_replacement_value *av = aggval; av; av = av->next)
4075 if (aggval->index == i)
4077 struct ipa_agg_jf_item *item;
4078 int j;
4079 bool found = false;
4080 FOR_EACH_VEC_ELT (values, j, item)
4081 if (item->value
4082 && item->offset == av->offset
4083 && values_equal_for_ipcp_p (item->value, av->value))
4085 found = true;
4086 break;
4088 if (!found)
4090 values.release ();
4091 return false;
4095 return true;
4098 /* Given an original NODE and a VAL for which we have already created a
4099 specialized clone, look whether there are incoming edges that still lead
4100 into the old node but now also bring the requested value and also conform to
4101 all other criteria such that they can be redirected the special node.
4102 This function can therefore redirect the final edge in a SCC. */
4104 template <typename valtype>
4105 static void
4106 perhaps_add_new_callers (cgraph_node *node, ipcp_value<valtype> *val)
4108 ipcp_value_source<valtype> *src;
4109 gcov_type redirected_sum = 0;
4111 for (src = val->sources; src; src = src->next)
4113 struct cgraph_edge *cs = src->cs;
4114 while (cs)
4116 if (cgraph_edge_brings_value_p (cs, src, node)
4117 && cgraph_edge_brings_all_scalars_for_node (cs, val->spec_node)
4118 && cgraph_edge_brings_all_agg_vals_for_node (cs, val->spec_node))
4120 if (dump_file)
4121 fprintf (dump_file, " - adding an extra caller %s/%i"
4122 " of %s/%i\n",
4123 xstrdup_for_dump (cs->caller->name ()),
4124 cs->caller->order,
4125 xstrdup_for_dump (val->spec_node->name ()),
4126 val->spec_node->order);
4128 cs->redirect_callee_duplicating_thunks (val->spec_node);
4129 val->spec_node->expand_all_artificial_thunks ();
4130 redirected_sum += cs->count;
4132 cs = get_next_cgraph_edge_clone (cs);
4136 if (redirected_sum)
4137 update_specialized_profile (val->spec_node, node, redirected_sum);
4140 /* Return true if KNOWN_CONTEXTS contain at least one useful context. */
4142 static bool
4143 known_contexts_useful_p (vec<ipa_polymorphic_call_context> known_contexts)
4145 ipa_polymorphic_call_context *ctx;
4146 int i;
4148 FOR_EACH_VEC_ELT (known_contexts, i, ctx)
4149 if (!ctx->useless_p ())
4150 return true;
4151 return false;
4154 /* Return a copy of KNOWN_CSTS if it is not empty, otherwise return vNULL. */
4156 static vec<ipa_polymorphic_call_context>
4157 copy_useful_known_contexts (vec<ipa_polymorphic_call_context> known_contexts)
4159 if (known_contexts_useful_p (known_contexts))
4160 return known_contexts.copy ();
4161 else
4162 return vNULL;
4165 /* Copy KNOWN_CSTS and modify the copy according to VAL and INDEX. If
4166 non-empty, replace KNOWN_CONTEXTS with its copy too. */
4168 static void
4169 modify_known_vectors_with_val (vec<tree> *known_csts,
4170 vec<ipa_polymorphic_call_context> *known_contexts,
4171 ipcp_value<tree> *val,
4172 int index)
4174 *known_csts = known_csts->copy ();
4175 *known_contexts = copy_useful_known_contexts (*known_contexts);
4176 (*known_csts)[index] = val->value;
4179 /* Replace KNOWN_CSTS with its copy. Also copy KNOWN_CONTEXTS and modify the
4180 copy according to VAL and INDEX. */
4182 static void
4183 modify_known_vectors_with_val (vec<tree> *known_csts,
4184 vec<ipa_polymorphic_call_context> *known_contexts,
4185 ipcp_value<ipa_polymorphic_call_context> *val,
4186 int index)
4188 *known_csts = known_csts->copy ();
4189 *known_contexts = known_contexts->copy ();
4190 (*known_contexts)[index] = val->value;
4193 /* Return true if OFFSET indicates this was not an aggregate value or there is
4194 a replacement equivalent to VALUE, INDEX and OFFSET among those in the
4195 AGGVALS list. */
4197 DEBUG_FUNCTION bool
4198 ipcp_val_agg_replacement_ok_p (ipa_agg_replacement_value *aggvals,
4199 int index, HOST_WIDE_INT offset, tree value)
4201 if (offset == -1)
4202 return true;
4204 while (aggvals)
4206 if (aggvals->index == index
4207 && aggvals->offset == offset
4208 && values_equal_for_ipcp_p (aggvals->value, value))
4209 return true;
4210 aggvals = aggvals->next;
4212 return false;
4215 /* Return true if offset is minus one because source of a polymorphic contect
4216 cannot be an aggregate value. */
4218 DEBUG_FUNCTION bool
4219 ipcp_val_agg_replacement_ok_p (ipa_agg_replacement_value *,
4220 int , HOST_WIDE_INT offset,
4221 ipa_polymorphic_call_context)
4223 return offset == -1;
4226 /* Decide wheter to create a special version of NODE for value VAL of parameter
4227 at the given INDEX. If OFFSET is -1, the value is for the parameter itself,
4228 otherwise it is stored at the given OFFSET of the parameter. KNOWN_CSTS,
4229 KNOWN_CONTEXTS and KNOWN_AGGS describe the other already known values. */
4231 template <typename valtype>
4232 static bool
4233 decide_about_value (struct cgraph_node *node, int index, HOST_WIDE_INT offset,
4234 ipcp_value<valtype> *val, vec<tree> known_csts,
4235 vec<ipa_polymorphic_call_context> known_contexts)
4237 struct ipa_agg_replacement_value *aggvals;
4238 int freq_sum, caller_count;
4239 gcov_type count_sum;
4240 vec<cgraph_edge *> callers;
4242 if (val->spec_node)
4244 perhaps_add_new_callers (node, val);
4245 return false;
4247 else if (val->local_size_cost + overall_size > max_new_size)
4249 if (dump_file && (dump_flags & TDF_DETAILS))
4250 fprintf (dump_file, " Ignoring candidate value because "
4251 "max_new_size would be reached with %li.\n",
4252 val->local_size_cost + overall_size);
4253 return false;
4255 else if (!get_info_about_necessary_edges (val, node, &freq_sum, &count_sum,
4256 &caller_count))
4257 return false;
4259 if (dump_file && (dump_flags & TDF_DETAILS))
4261 fprintf (dump_file, " - considering value ");
4262 print_ipcp_constant_value (dump_file, val->value);
4263 fprintf (dump_file, " for ");
4264 ipa_dump_param (dump_file, IPA_NODE_REF (node), index);
4265 if (offset != -1)
4266 fprintf (dump_file, ", offset: " HOST_WIDE_INT_PRINT_DEC, offset);
4267 fprintf (dump_file, " (caller_count: %i)\n", caller_count);
4270 if (!good_cloning_opportunity_p (node, val->local_time_benefit,
4271 freq_sum, count_sum,
4272 val->local_size_cost)
4273 && !good_cloning_opportunity_p (node,
4274 val->local_time_benefit
4275 + val->prop_time_benefit,
4276 freq_sum, count_sum,
4277 val->local_size_cost
4278 + val->prop_size_cost))
4279 return false;
4281 if (dump_file)
4282 fprintf (dump_file, " Creating a specialized node of %s/%i.\n",
4283 node->name (), node->order);
4285 callers = gather_edges_for_value (val, node, caller_count);
4286 if (offset == -1)
4287 modify_known_vectors_with_val (&known_csts, &known_contexts, val, index);
4288 else
4290 known_csts = known_csts.copy ();
4291 known_contexts = copy_useful_known_contexts (known_contexts);
4293 find_more_scalar_values_for_callers_subset (node, known_csts, callers);
4294 find_more_contexts_for_caller_subset (node, &known_contexts, callers);
4295 aggvals = find_aggregate_values_for_callers_subset (node, callers);
4296 gcc_checking_assert (ipcp_val_agg_replacement_ok_p (aggvals, index,
4297 offset, val->value));
4298 val->spec_node = create_specialized_node (node, known_csts, known_contexts,
4299 aggvals, callers);
4300 overall_size += val->local_size_cost;
4302 /* TODO: If for some lattice there is only one other known value
4303 left, make a special node for it too. */
4305 return true;
4308 /* Decide whether and what specialized clones of NODE should be created. */
4310 static bool
4311 decide_whether_version_node (struct cgraph_node *node)
4313 struct ipa_node_params *info = IPA_NODE_REF (node);
4314 int i, count = ipa_get_param_count (info);
4315 vec<tree> known_csts;
4316 vec<ipa_polymorphic_call_context> known_contexts;
4317 vec<ipa_agg_jump_function> known_aggs = vNULL;
4318 bool ret = false;
4320 if (count == 0)
4321 return false;
4323 if (dump_file && (dump_flags & TDF_DETAILS))
4324 fprintf (dump_file, "\nEvaluating opportunities for %s/%i.\n",
4325 node->name (), node->order);
4327 gather_context_independent_values (info, &known_csts, &known_contexts,
4328 info->do_clone_for_all_contexts ? &known_aggs
4329 : NULL, NULL);
4331 for (i = 0; i < count ;i++)
4333 struct ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4334 ipcp_lattice<tree> *lat = &plats->itself;
4335 ipcp_lattice<ipa_polymorphic_call_context> *ctxlat = &plats->ctxlat;
4337 if (!lat->bottom
4338 && !known_csts[i])
4340 ipcp_value<tree> *val;
4341 for (val = lat->values; val; val = val->next)
4342 ret |= decide_about_value (node, i, -1, val, known_csts,
4343 known_contexts);
4346 if (!plats->aggs_bottom)
4348 struct ipcp_agg_lattice *aglat;
4349 ipcp_value<tree> *val;
4350 for (aglat = plats->aggs; aglat; aglat = aglat->next)
4351 if (!aglat->bottom && aglat->values
4352 /* If the following is false, the one value is in
4353 known_aggs. */
4354 && (plats->aggs_contain_variable
4355 || !aglat->is_single_const ()))
4356 for (val = aglat->values; val; val = val->next)
4357 ret |= decide_about_value (node, i, aglat->offset, val,
4358 known_csts, known_contexts);
4361 if (!ctxlat->bottom
4362 && known_contexts[i].useless_p ())
4364 ipcp_value<ipa_polymorphic_call_context> *val;
4365 for (val = ctxlat->values; val; val = val->next)
4366 ret |= decide_about_value (node, i, -1, val, known_csts,
4367 known_contexts);
4370 info = IPA_NODE_REF (node);
4373 if (info->do_clone_for_all_contexts)
4375 struct cgraph_node *clone;
4376 vec<cgraph_edge *> callers;
4378 if (dump_file)
4379 fprintf (dump_file, " - Creating a specialized node of %s/%i "
4380 "for all known contexts.\n", node->name (),
4381 node->order);
4383 callers = node->collect_callers ();
4385 if (!known_contexts_useful_p (known_contexts))
4387 known_contexts.release ();
4388 known_contexts = vNULL;
4390 clone = create_specialized_node (node, known_csts, known_contexts,
4391 known_aggs_to_agg_replacement_list (known_aggs),
4392 callers);
4393 info = IPA_NODE_REF (node);
4394 info->do_clone_for_all_contexts = false;
4395 IPA_NODE_REF (clone)->is_all_contexts_clone = true;
4396 for (i = 0; i < count ; i++)
4397 vec_free (known_aggs[i].items);
4398 known_aggs.release ();
4399 ret = true;
4401 else
4403 known_csts.release ();
4404 known_contexts.release ();
4407 return ret;
4410 /* Transitively mark all callees of NODE within the same SCC as not dead. */
4412 static void
4413 spread_undeadness (struct cgraph_node *node)
4415 struct cgraph_edge *cs;
4417 for (cs = node->callees; cs; cs = cs->next_callee)
4418 if (ipa_edge_within_scc (cs))
4420 struct cgraph_node *callee;
4421 struct ipa_node_params *info;
4423 callee = cs->callee->function_symbol (NULL);
4424 info = IPA_NODE_REF (callee);
4426 if (info->node_dead)
4428 info->node_dead = 0;
4429 spread_undeadness (callee);
4434 /* Return true if NODE has a caller from outside of its SCC that is not
4435 dead. Worker callback for cgraph_for_node_and_aliases. */
4437 static bool
4438 has_undead_caller_from_outside_scc_p (struct cgraph_node *node,
4439 void *data ATTRIBUTE_UNUSED)
4441 struct cgraph_edge *cs;
4443 for (cs = node->callers; cs; cs = cs->next_caller)
4444 if (cs->caller->thunk.thunk_p
4445 && cs->caller->call_for_symbol_thunks_and_aliases
4446 (has_undead_caller_from_outside_scc_p, NULL, true))
4447 return true;
4448 else if (!ipa_edge_within_scc (cs)
4449 && !IPA_NODE_REF (cs->caller)->node_dead)
4450 return true;
4451 return false;
4455 /* Identify nodes within the same SCC as NODE which are no longer needed
4456 because of new clones and will be removed as unreachable. */
4458 static void
4459 identify_dead_nodes (struct cgraph_node *node)
4461 struct cgraph_node *v;
4462 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4463 if (v->local.local
4464 && !v->call_for_symbol_thunks_and_aliases
4465 (has_undead_caller_from_outside_scc_p, NULL, true))
4466 IPA_NODE_REF (v)->node_dead = 1;
4468 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4469 if (!IPA_NODE_REF (v)->node_dead)
4470 spread_undeadness (v);
4472 if (dump_file && (dump_flags & TDF_DETAILS))
4474 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4475 if (IPA_NODE_REF (v)->node_dead)
4476 fprintf (dump_file, " Marking node as dead: %s/%i.\n",
4477 v->name (), v->order);
4481 /* The decision stage. Iterate over the topological order of call graph nodes
4482 TOPO and make specialized clones if deemed beneficial. */
4484 static void
4485 ipcp_decision_stage (struct ipa_topo_info *topo)
4487 int i;
4489 if (dump_file)
4490 fprintf (dump_file, "\nIPA decision stage:\n\n");
4492 for (i = topo->nnodes - 1; i >= 0; i--)
4494 struct cgraph_node *node = topo->order[i];
4495 bool change = false, iterate = true;
4497 while (iterate)
4499 struct cgraph_node *v;
4500 iterate = false;
4501 for (v = node; v ; v = ((struct ipa_dfs_info *) v->aux)->next_cycle)
4502 if (v->has_gimple_body_p ()
4503 && ipcp_versionable_function_p (v))
4504 iterate |= decide_whether_version_node (v);
4506 change |= iterate;
4508 if (change)
4509 identify_dead_nodes (node);
4513 /* Look up all alignment information that we have discovered and copy it over
4514 to the transformation summary. */
4516 static void
4517 ipcp_store_alignment_results (void)
4519 cgraph_node *node;
4521 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
4523 ipa_node_params *info = IPA_NODE_REF (node);
4524 bool dumped_sth = false;
4525 bool found_useful_result = false;
4527 if (!opt_for_fn (node->decl, flag_ipa_cp_alignment))
4529 if (dump_file)
4530 fprintf (dump_file, "Not considering %s for alignment discovery "
4531 "and propagate; -fipa-cp-alignment: disabled.\n",
4532 node->name ());
4533 continue;
4536 if (info->ipcp_orig_node)
4537 info = IPA_NODE_REF (info->ipcp_orig_node);
4539 unsigned count = ipa_get_param_count (info);
4540 for (unsigned i = 0; i < count ; i++)
4542 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4543 if (!plats->alignment.bottom_p ()
4544 && !plats->alignment.top_p ())
4546 gcc_checking_assert (plats->alignment.align > 0);
4547 found_useful_result = true;
4548 break;
4551 if (!found_useful_result)
4552 continue;
4554 ipcp_grow_transformations_if_necessary ();
4555 ipcp_transformation_summary *ts = ipcp_get_transformation_summary (node);
4556 vec_safe_reserve_exact (ts->alignments, count);
4558 for (unsigned i = 0; i < count ; i++)
4560 ipcp_param_lattices *plats = ipa_get_parm_lattices (info, i);
4561 ipa_alignment al;
4563 if (!plats->alignment.bottom_p ()
4564 && !plats->alignment.top_p ())
4566 al.known = true;
4567 al.align = plats->alignment.align;
4568 al.misalign = plats->alignment.misalign;
4570 else
4571 al.known = false;
4573 ts->alignments->quick_push (al);
4574 if (!dump_file || !al.known)
4575 continue;
4576 if (!dumped_sth)
4578 fprintf (dump_file, "Propagated alignment info for function %s/%i:\n",
4579 node->name (), node->order);
4580 dumped_sth = true;
4582 fprintf (dump_file, " param %i: align: %u, misalign: %u\n",
4583 i, al.align, al.misalign);
4588 /* The IPCP driver. */
4590 static unsigned int
4591 ipcp_driver (void)
4593 struct cgraph_2edge_hook_list *edge_duplication_hook_holder;
4594 struct cgraph_edge_hook_list *edge_removal_hook_holder;
4595 struct ipa_topo_info topo;
4597 ipa_check_create_node_params ();
4598 ipa_check_create_edge_args ();
4599 grow_edge_clone_vectors ();
4600 edge_duplication_hook_holder =
4601 symtab->add_edge_duplication_hook (&ipcp_edge_duplication_hook, NULL);
4602 edge_removal_hook_holder =
4603 symtab->add_edge_removal_hook (&ipcp_edge_removal_hook, NULL);
4605 if (dump_file)
4607 fprintf (dump_file, "\nIPA structures before propagation:\n");
4608 if (dump_flags & TDF_DETAILS)
4609 ipa_print_all_params (dump_file);
4610 ipa_print_all_jump_functions (dump_file);
4613 /* Topological sort. */
4614 build_toporder_info (&topo);
4615 /* Do the interprocedural propagation. */
4616 ipcp_propagate_stage (&topo);
4617 /* Decide what constant propagation and cloning should be performed. */
4618 ipcp_decision_stage (&topo);
4619 /* Store results of alignment propagation. */
4620 ipcp_store_alignment_results ();
4622 /* Free all IPCP structures. */
4623 free_toporder_info (&topo);
4624 next_edge_clone.release ();
4625 prev_edge_clone.release ();
4626 symtab->remove_edge_removal_hook (edge_removal_hook_holder);
4627 symtab->remove_edge_duplication_hook (edge_duplication_hook_holder);
4628 ipa_free_all_structures_after_ipa_cp ();
4629 if (dump_file)
4630 fprintf (dump_file, "\nIPA constant propagation end\n");
4631 return 0;
4634 /* Initialization and computation of IPCP data structures. This is the initial
4635 intraprocedural analysis of functions, which gathers information to be
4636 propagated later on. */
4638 static void
4639 ipcp_generate_summary (void)
4641 struct cgraph_node *node;
4643 if (dump_file)
4644 fprintf (dump_file, "\nIPA constant propagation start:\n");
4645 ipa_register_cgraph_hooks ();
4647 FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
4648 ipa_analyze_node (node);
4651 /* Write ipcp summary for nodes in SET. */
4653 static void
4654 ipcp_write_summary (void)
4656 ipa_prop_write_jump_functions ();
4659 /* Read ipcp summary. */
4661 static void
4662 ipcp_read_summary (void)
4664 ipa_prop_read_jump_functions ();
4667 namespace {
4669 const pass_data pass_data_ipa_cp =
4671 IPA_PASS, /* type */
4672 "cp", /* name */
4673 OPTGROUP_NONE, /* optinfo_flags */
4674 TV_IPA_CONSTANT_PROP, /* tv_id */
4675 0, /* properties_required */
4676 0, /* properties_provided */
4677 0, /* properties_destroyed */
4678 0, /* todo_flags_start */
4679 ( TODO_dump_symtab | TODO_remove_functions ), /* todo_flags_finish */
4682 class pass_ipa_cp : public ipa_opt_pass_d
4684 public:
4685 pass_ipa_cp (gcc::context *ctxt)
4686 : ipa_opt_pass_d (pass_data_ipa_cp, ctxt,
4687 ipcp_generate_summary, /* generate_summary */
4688 ipcp_write_summary, /* write_summary */
4689 ipcp_read_summary, /* read_summary */
4690 ipcp_write_transformation_summaries, /*
4691 write_optimization_summary */
4692 ipcp_read_transformation_summaries, /*
4693 read_optimization_summary */
4694 NULL, /* stmt_fixup */
4695 0, /* function_transform_todo_flags_start */
4696 ipcp_transform_function, /* function_transform */
4697 NULL) /* variable_transform */
4700 /* opt_pass methods: */
4701 virtual bool gate (function *)
4703 /* FIXME: We should remove the optimize check after we ensure we never run
4704 IPA passes when not optimizing. */
4705 return (flag_ipa_cp && optimize) || in_lto_p;
4708 virtual unsigned int execute (function *) { return ipcp_driver (); }
4710 }; // class pass_ipa_cp
4712 } // anon namespace
4714 ipa_opt_pass_d *
4715 make_pass_ipa_cp (gcc::context *ctxt)
4717 return new pass_ipa_cp (ctxt);
4720 /* Reset all state within ipa-cp.c so that we can rerun the compiler
4721 within the same process. For use by toplev::finalize. */
4723 void
4724 ipa_cp_c_finalize (void)
4726 max_count = 0;
4727 overall_size = 0;
4728 max_new_size = 0;