Update gcc-50 to SVN version 220677
[dragonfly.git] / contrib / gcc-5.0 / gcc / ipa-devirt.c
1 /* Basic IPA utilities for type inheritance graph construction and
2    devirtualization.
3    Copyright (C) 2013-2015 Free Software Foundation, Inc.
4    Contributed by Jan Hubicka
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Brief vocabulary:
23      ODR = One Definition Rule
24         In short, the ODR states that:
25         1 In any translation unit, a template, type, function, or object can
26           have no more than one definition. Some of these can have any number
27           of declarations. A definition provides an instance.
28         2 In the entire program, an object or non-inline function cannot have
29           more than one definition; if an object or function is used, it must
30           have exactly one definition. You can declare an object or function
31           that is never used, in which case you don't have to provide
32           a definition. In no event can there be more than one definition.
33         3 Some things, like types, templates, and extern inline functions, can
34           be defined in more than one translation unit. For a given entity,
35           each definition must be the same. Non-extern objects and functions
36           in different translation units are different entities, even if their
37           names and types are the same.
38
39      OTR = OBJ_TYPE_REF
40        This is the Gimple representation of type information of a polymorphic call.
41        It contains two parameters:
42          otr_type is a type of class whose method is called.
43          otr_token is the index into virtual table where address is taken.
44
45      BINFO
46        This is the type inheritance information attached to each tree
47        RECORD_TYPE by the C++ frontend.  It provides information about base
48        types and virtual tables.
49
50        BINFO is linked to the RECORD_TYPE by TYPE_BINFO.
51        BINFO also links to its type by BINFO_TYPE and to the virtual table by
52        BINFO_VTABLE.
53
54        Base types of a given type are enumerated by BINFO_BASE_BINFO
55        vector.  Members of this vectors are not BINFOs associated
56        with a base type.  Rather they are new copies of BINFOs
57        (base BINFOs). Their virtual tables may differ from
58        virtual table of the base type.  Also BINFO_OFFSET specifies
59        offset of the base within the type.
60
61        In the case of single inheritance, the virtual table is shared
62        and BINFO_VTABLE of base BINFO is NULL.  In the case of multiple
63        inheritance the individual virtual tables are pointer to by
64        BINFO_VTABLE of base binfos (that differs of BINFO_VTABLE of 
65        binfo associated to the base type).
66
67        BINFO lookup for a given base type and offset can be done by
68        get_binfo_at_offset.  It returns proper BINFO whose virtual table
69        can be used for lookup of virtual methods associated with the
70        base type.
71
72      token
73        This is an index of virtual method in virtual table associated
74        to the type defining it. Token can be looked up from OBJ_TYPE_REF
75        or from DECL_VINDEX of a given virtual table.
76
77      polymorphic (indirect) call
78        This is callgraph representation of virtual method call.  Every
79        polymorphic call contains otr_type and otr_token taken from
80        original OBJ_TYPE_REF at callgraph construction time.
81
82    What we do here:
83
84    build_type_inheritance_graph triggers a construction of the type inheritance
85    graph.
86
87      We reconstruct it based on types of methods we see in the unit.
88      This means that the graph is not complete. Types with no methods are not
89      inserted into the graph.  Also types without virtual methods are not
90      represented at all, though it may be easy to add this.
91   
92      The inheritance graph is represented as follows:
93
94        Vertices are structures odr_type.  Every odr_type may correspond
95        to one or more tree type nodes that are equivalent by ODR rule.
96        (the multiple type nodes appear only with linktime optimization)
97
98        Edges are represented by odr_type->base and odr_type->derived_types.
99        At the moment we do not track offsets of types for multiple inheritance.
100        Adding this is easy.
101
102   possible_polymorphic_call_targets returns, given an parameters found in
103   indirect polymorphic edge all possible polymorphic call targets of the call.
104
105   pass_ipa_devirt performs simple speculative devirtualization.
106 */
107
108 #include "config.h"
109 #include "system.h"
110 #include "coretypes.h"
111 #include "tm.h"
112 #include "hash-set.h"
113 #include "machmode.h"
114 #include "hash-map.h"
115 #include "vec.h"
116 #include "double-int.h"
117 #include "input.h"
118 #include "alias.h"
119 #include "symtab.h"
120 #include "wide-int.h"
121 #include "inchash.h"
122 #include "tree.h"
123 #include "fold-const.h"
124 #include "print-tree.h"
125 #include "calls.h"
126 #include "predict.h"
127 #include "basic-block.h"
128 #include "is-a.h"
129 #include "plugin-api.h"
130 #include "hard-reg-set.h"
131 #include "function.h"
132 #include "ipa-ref.h"
133 #include "cgraph.h"
134 #include "hashtab.h"
135 #include "rtl.h"
136 #include "flags.h"
137 #include "statistics.h"
138 #include "real.h"
139 #include "fixed-value.h"
140 #include "insn-config.h"
141 #include "expmed.h"
142 #include "dojump.h"
143 #include "explow.h"
144 #include "emit-rtl.h"
145 #include "varasm.h"
146 #include "stmt.h"
147 #include "expr.h"
148 #include "tree-pass.h"
149 #include "target.h"
150 #include "hash-table.h"
151 #include "tree-pretty-print.h"
152 #include "ipa-utils.h"
153 #include "tree-ssa-alias.h"
154 #include "internal-fn.h"
155 #include "gimple-fold.h"
156 #include "gimple-expr.h"
157 #include "gimple.h"
158 #include "alloc-pool.h"
159 #include "symbol-summary.h"
160 #include "ipa-prop.h"
161 #include "ipa-inline.h"
162 #include "diagnostic.h"
163 #include "tree-dfa.h"
164 #include "demangle.h"
165 #include "dbgcnt.h"
166 #include "gimple-pretty-print.h"
167 #include "stor-layout.h"
168 #include "intl.h"
169
170 /* Hash based set of pairs of types.  */
171 typedef struct
172 {
173   tree first;
174   tree second;
175 } type_pair;
176
177 struct pair_traits : default_hashset_traits
178 {
179   static hashval_t
180   hash (type_pair p)
181   {
182     return TYPE_UID (p.first) ^ TYPE_UID (p.second);
183   }
184   static bool
185   is_empty (type_pair p)
186   {
187     return p.first == NULL;
188   }
189   static bool
190   is_deleted (type_pair p ATTRIBUTE_UNUSED)
191     {
192       return false;
193     }
194   static bool
195   equal (const type_pair &a, const type_pair &b)
196     {
197       return a.first==b.first && a.second == b.second;
198     }
199   static void
200   mark_empty (type_pair &e)
201     {
202       e.first = NULL;
203     }
204 };
205
206 static bool odr_types_equivalent_p (tree, tree, bool, bool *,
207                                     hash_set<type_pair,pair_traits> *);
208
209 static bool odr_violation_reported = false;
210
211
212 /* Pointer set of all call targets appearing in the cache.  */
213 static hash_set<cgraph_node *> *cached_polymorphic_call_targets;
214
215 /* The node of type inheritance graph.  For each type unique in
216    One Definition Rule (ODR) sense, we produce one node linking all 
217    main variants of types equivalent to it, bases and derived types.  */
218
219 struct GTY(()) odr_type_d
220 {
221   /* leader type.  */
222   tree type;
223   /* All bases; built only for main variants of types.  */
224   vec<odr_type> GTY((skip)) bases;
225   /* All derived types with virtual methods seen in unit;
226      built only for main variants of types.  */
227   vec<odr_type> GTY((skip)) derived_types;
228
229   /* All equivalent types, if more than one.  */
230   vec<tree, va_gc> *types;
231   /* Set of all equivalent types, if NON-NULL.  */
232   hash_set<tree> * GTY((skip)) types_set;
233
234   /* Unique ID indexing the type in odr_types array.  */
235   int id;
236   /* Is it in anonymous namespace? */
237   bool anonymous_namespace;
238   /* Do we know about all derivations of given type?  */
239   bool all_derivations_known;
240   /* Did we report ODR violation here?  */
241   bool odr_violated;
242 };
243
244 /* Return TRUE if all derived types of T are known and thus
245    we may consider the walk of derived type complete.
246
247    This is typically true only for final anonymous namespace types and types
248    defined within functions (that may be COMDAT and thus shared across units,
249    but with the same set of derived types).  */
250
251 bool
252 type_all_derivations_known_p (const_tree t)
253 {
254   if (TYPE_FINAL_P (t))
255     return true;
256   if (flag_ltrans)
257     return false;
258   /* Non-C++ types may have IDENTIFIER_NODE here, do not crash.  */
259   if (!TYPE_NAME (t) || TREE_CODE (TYPE_NAME (t)) != TYPE_DECL)
260     return true;
261   if (type_in_anonymous_namespace_p (t))
262     return true;
263   return (decl_function_context (TYPE_NAME (t)) != NULL);
264 }
265
266 /* Return TRUE if type's constructors are all visible.  */
267
268 static bool
269 type_all_ctors_visible_p (tree t)
270 {
271   return !flag_ltrans
272          && symtab->state >= CONSTRUCTION
273          /* We can not always use type_all_derivations_known_p.
274             For function local types we must assume case where
275             the function is COMDAT and shared in between units. 
276
277             TODO: These cases are quite easy to get, but we need
278             to keep track of C++ privatizing via -Wno-weak
279             as well as the  IPA privatizing.  */
280          && type_in_anonymous_namespace_p (t);
281 }
282
283 /* Return TRUE if type may have instance.  */
284
285 static bool
286 type_possibly_instantiated_p (tree t)
287 {
288   tree vtable;
289   varpool_node *vnode;
290
291   /* TODO: Add abstract types here.  */
292   if (!type_all_ctors_visible_p (t))
293     return true;
294
295   vtable = BINFO_VTABLE (TYPE_BINFO (t));
296   if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
297     vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
298   vnode = varpool_node::get (vtable);
299   return vnode && vnode->definition;
300 }
301
302 /* One Definition Rule hashtable helpers.  */
303
304 struct odr_hasher 
305 {
306   typedef odr_type_d value_type;
307   typedef union tree_node compare_type;
308   static inline hashval_t hash (const value_type *);
309   static inline bool equal (const value_type *, const compare_type *);
310   static inline void remove (value_type *);
311 };
312
313 /* Return type that was declared with T's name so that T is an
314    qualified variant of it.  */
315
316 static inline tree
317 main_odr_variant (const_tree t)
318 {
319   if (TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL)
320     return TREE_TYPE (TYPE_NAME (t));
321   /* Unnamed types and non-C++ produced types can be compared by variants.  */
322   else
323     return TYPE_MAIN_VARIANT (t);
324 }
325
326 /* Produce hash based on type name.  */
327
328 static hashval_t
329 hash_type_name (tree t)
330 {
331   gcc_checking_assert (main_odr_variant (t) == t);
332
333   /* If not in LTO, all main variants are unique, so we can do
334      pointer hash.  */
335   if (!in_lto_p)
336     return htab_hash_pointer (t);
337
338   /* Anonymous types are unique.  */
339   if (type_in_anonymous_namespace_p (t))
340     return htab_hash_pointer (t);
341
342   /* ODR types have name specified.  */
343   if (TYPE_NAME (t)
344       && DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (t)))
345     return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME (TYPE_NAME (t)));
346
347   /* For polymorphic types that was compiled with -fno-lto-odr-type-merging
348      we can simply hash the virtual table.  */
349   if (TREE_CODE (t) == RECORD_TYPE
350       && TYPE_BINFO (t) && BINFO_VTABLE (TYPE_BINFO (t)))
351     {
352       tree v = BINFO_VTABLE (TYPE_BINFO (t));
353       hashval_t hash = 0;
354
355       if (TREE_CODE (v) == POINTER_PLUS_EXPR)
356         {
357           hash = TREE_INT_CST_LOW (TREE_OPERAND (v, 1));
358           v = TREE_OPERAND (TREE_OPERAND (v, 0), 0);
359         }
360
361       v = DECL_ASSEMBLER_NAME (v);
362       hash = iterative_hash_hashval_t (hash, htab_hash_pointer (v));
363       return hash;
364     }
365
366   /* Builtin types may appear as main variants of ODR types and are unique.
367      Sanity check we do not get anything that looks non-builtin.  */
368   gcc_checking_assert (TREE_CODE (t) == INTEGER_TYPE
369                        || TREE_CODE (t) == VOID_TYPE
370                        || TREE_CODE (t) == COMPLEX_TYPE
371                        || TREE_CODE (t) == REAL_TYPE
372                        || TREE_CODE (t) == POINTER_TYPE);
373   return htab_hash_pointer (t);
374 }
375
376 /* Return the computed hashcode for ODR_TYPE.  */
377
378 inline hashval_t
379 odr_hasher::hash (const value_type *odr_type)
380 {
381   return hash_type_name (odr_type->type);
382 }
383
384 /* For languages with One Definition Rule, work out if
385    types are the same based on their name.
386  
387    This is non-trivial for LTO where minor differences in
388    the type representation may have prevented type merging
389    to merge two copies of otherwise equivalent type.
390
391    Until we start streaming mangled type names, this function works
392    only for polymorphic types.  */
393
394 bool
395 types_same_for_odr (const_tree type1, const_tree type2)
396 {
397   gcc_checking_assert (TYPE_P (type1) && TYPE_P (type2));
398
399   type1 = main_odr_variant (type1);
400   type2 = main_odr_variant (type2);
401
402   if (type1 == type2)
403     return true;
404
405   if (!in_lto_p)
406     return false;
407
408   /* Check for anonymous namespaces. Those have !TREE_PUBLIC
409      on the corresponding TYPE_STUB_DECL.  */
410   if (type_in_anonymous_namespace_p (type1)
411       || type_in_anonymous_namespace_p (type2))
412     return false;
413
414
415   /* ODR name of the type is set in DECL_ASSEMBLER_NAME of its TYPE_NAME.
416
417      Ideally we should never need types without ODR names here.  It can however
418      happen in two cases:
419
420        1) for builtin types that are not streamed but rebuilt in lto/lto-lang.c
421           Here testing for equivalence is safe, since their MAIN_VARIANTs are
422           unique.
423        2) for units streamed with -fno-lto-odr-type-merging.  Here we can't
424           establish precise ODR equivalency, but for correctness we care only
425           about equivalency on complete polymorphic types.  For these we can
426           compare assembler names of their virtual tables.  */
427   if ((!TYPE_NAME (type1) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type1)))
428       || (!TYPE_NAME (type2) || !DECL_ASSEMBLER_NAME_SET_P (TYPE_NAME (type2))))
429     {
430       /* See if types are obviously different (i.e. different codes
431          or polymorphic wrt non-polymorphic).  This is not strictly correct
432          for ODR violating programs, but we can't do better without streaming
433          ODR names.  */
434       if (TREE_CODE (type1) != TREE_CODE (type2))
435         return false;
436       if (TREE_CODE (type1) == RECORD_TYPE
437           && (TYPE_BINFO (type1) == NULL_TREE) != (TYPE_BINFO (type1) == NULL_TREE))
438         return false;
439       if (TREE_CODE (type1) == RECORD_TYPE && TYPE_BINFO (type1)
440           && (BINFO_VTABLE (TYPE_BINFO (type1)) == NULL_TREE)
441              != (BINFO_VTABLE (TYPE_BINFO (type2)) == NULL_TREE))
442         return false;
443
444       /* At the moment we have no way to establish ODR equivalence at LTO
445          other than comparing virtual table pointers of polymorphic types.
446          Eventually we should start saving mangled names in TYPE_NAME.
447          Then this condition will become non-trivial.  */
448
449       if (TREE_CODE (type1) == RECORD_TYPE
450           && TYPE_BINFO (type1) && TYPE_BINFO (type2)
451           && BINFO_VTABLE (TYPE_BINFO (type1))
452           && BINFO_VTABLE (TYPE_BINFO (type2)))
453         {
454           tree v1 = BINFO_VTABLE (TYPE_BINFO (type1));
455           tree v2 = BINFO_VTABLE (TYPE_BINFO (type2));
456           gcc_assert (TREE_CODE (v1) == POINTER_PLUS_EXPR
457                       && TREE_CODE (v2) == POINTER_PLUS_EXPR);
458           return (operand_equal_p (TREE_OPERAND (v1, 1),
459                                    TREE_OPERAND (v2, 1), 0)
460                   && DECL_ASSEMBLER_NAME
461                          (TREE_OPERAND (TREE_OPERAND (v1, 0), 0))
462                      == DECL_ASSEMBLER_NAME
463                          (TREE_OPERAND (TREE_OPERAND (v2, 0), 0)));
464         }
465       gcc_unreachable ();
466     }
467   return (DECL_ASSEMBLER_NAME (TYPE_NAME (type1))
468           == DECL_ASSEMBLER_NAME (TYPE_NAME (type2)));
469 }
470
471 /* Return true if we can decide on ODR equivalency.
472
473    In non-LTO it is always decide, in LTO however it depends in the type has
474    ODR info attached.  */
475
476 bool
477 types_odr_comparable (tree t1, tree t2)
478 {
479   return (!in_lto_p
480           || main_odr_variant (t1) == main_odr_variant (t2)
481           || (odr_type_p (t1) && odr_type_p (t2))
482           || (TREE_CODE (t1) == RECORD_TYPE && TREE_CODE (t2) == RECORD_TYPE
483               && TYPE_BINFO (t1) && TYPE_BINFO (t2)
484               && polymorphic_type_binfo_p (TYPE_BINFO (t1))
485               && polymorphic_type_binfo_p (TYPE_BINFO (t2))));
486 }
487
488 /* Return true if T1 and T2 are ODR equivalent.  If ODR equivalency is not
489    known, be conservative and return false.  */
490
491 bool
492 types_must_be_same_for_odr (tree t1, tree t2)
493 {
494   if (types_odr_comparable (t1, t2))
495     return types_same_for_odr (t1, t2);
496   else
497     return main_odr_variant (t1) == main_odr_variant (t2);
498 }
499
500 /* Compare types T1 and T2 and return true if they are
501    equivalent.  */
502
503 inline bool
504 odr_hasher::equal (const value_type *t1, const compare_type *ct2)
505 {
506   tree t2 = const_cast <tree> (ct2);
507
508   gcc_checking_assert (main_odr_variant (t2) == t2);
509   if (t1->type == t2)
510     return true;
511   if (!in_lto_p)
512     return false;
513   return types_same_for_odr (t1->type, t2);
514 }
515
516 /* Free ODR type V.  */
517
518 inline void
519 odr_hasher::remove (value_type *v)
520 {
521   v->bases.release ();
522   v->derived_types.release ();
523   if (v->types_set)
524     delete v->types_set;
525   ggc_free (v);
526 }
527
528 /* ODR type hash used to look up ODR type based on tree type node.  */
529
530 typedef hash_table<odr_hasher> odr_hash_type;
531 static odr_hash_type *odr_hash;
532
533 /* ODR types are also stored into ODR_TYPE vector to allow consistent
534    walking.  Bases appear before derived types.  Vector is garbage collected
535    so we won't end up visiting empty types.  */
536
537 static GTY(()) vec <odr_type, va_gc> *odr_types_ptr;
538 #define odr_types (*odr_types_ptr)
539
540 /* Set TYPE_BINFO of TYPE and its variants to BINFO.  */
541 void
542 set_type_binfo (tree type, tree binfo)
543 {
544   for (; type; type = TYPE_NEXT_VARIANT (type))
545     if (COMPLETE_TYPE_P (type))
546       TYPE_BINFO (type) = binfo;
547     else
548       gcc_assert (!TYPE_BINFO (type));
549 }
550
551 /* Compare T2 and T2 based on name or structure.  */
552
553 static bool
554 odr_subtypes_equivalent_p (tree t1, tree t2, hash_set<type_pair,pair_traits> *visited)
555 {
556   bool an1, an2;
557
558   /* This can happen in incomplete types that should be handled earlier.  */
559   gcc_assert (t1 && t2);
560
561   t1 = main_odr_variant (t1);
562   t2 = main_odr_variant (t2);
563   if (t1 == t2)
564     return true;
565
566   /* Anonymous namespace types must match exactly.  */
567   an1 = type_in_anonymous_namespace_p (t1);
568   an2 = type_in_anonymous_namespace_p (t2);
569   if (an1 != an2 || an1)
570     return false;
571
572   /* For ODR types be sure to compare their names.
573      To support -wno-odr-type-merging we allow one type to be non-ODR
574      and other ODR even though it is a violation.  */
575   if (types_odr_comparable (t1, t2))
576     {
577       if (!types_same_for_odr (t1, t2))
578         return false;
579       /* Limit recursion: If subtypes are ODR types and we know
580          that they are same, be happy.  */
581       if (!get_odr_type (t1, true)->odr_violated)
582         return true;
583     }
584
585   /* Component types, builtins and possibly violating ODR types
586      have to be compared structurally.  */
587   if (TREE_CODE (t1) != TREE_CODE (t2))
588     return false;
589   if ((TYPE_NAME (t1) == NULL_TREE) != (TYPE_NAME (t2) == NULL_TREE))
590     return false;
591   if (TYPE_NAME (t1) && DECL_NAME (TYPE_NAME (t1)) != DECL_NAME (TYPE_NAME (t2)))
592     return false;
593
594   type_pair pair={t1,t2};
595   if (TYPE_UID (t1) > TYPE_UID (t2))
596     {
597       pair.first = t2;
598       pair.second = t1;
599     }
600   if (visited->add (pair))
601     return true;
602   return odr_types_equivalent_p (t1, t2, false, NULL, visited);
603 }
604
605 /* Compare two virtual tables, PREVAILING and VTABLE and output ODR
606    violation warnings.  */
607
608 void
609 compare_virtual_tables (varpool_node *prevailing, varpool_node *vtable)
610 {
611   int n1, n2;
612   if (DECL_VIRTUAL_P (prevailing->decl) != DECL_VIRTUAL_P (vtable->decl))
613     {
614       odr_violation_reported = true;
615       if (DECL_VIRTUAL_P (prevailing->decl))
616         {
617           varpool_node *tmp = prevailing;
618           prevailing = vtable;
619           vtable = tmp;
620         }
621       if (warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (vtable->decl))),
622                       OPT_Wodr,
623                       "virtual table of type %qD violates one definition rule",
624                       DECL_CONTEXT (vtable->decl)))
625         inform (DECL_SOURCE_LOCATION (prevailing->decl),
626                 "variable of same assembler name as the virtual table is "
627                 "defined in another translation unit");
628       return;
629     }
630   if (!prevailing->definition || !vtable->definition)
631     return;
632   for (n1 = 0, n2 = 0; true; n1++, n2++)
633     {
634       struct ipa_ref *ref1, *ref2;
635       bool end1, end2;
636       end1 = !prevailing->iterate_reference (n1, ref1);
637       end2 = !vtable->iterate_reference (n2, ref2);
638       if (end1 && end2)
639         return;
640       if (!end1 && !end2
641           && DECL_ASSEMBLER_NAME (ref1->referred->decl)
642              != DECL_ASSEMBLER_NAME (ref2->referred->decl)
643           && !n2
644           && !DECL_VIRTUAL_P (ref2->referred->decl)
645           && DECL_VIRTUAL_P (ref1->referred->decl))
646         {
647           if (warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
648                           "virtual table of type %qD contains RTTI information",
649                           DECL_CONTEXT (vtable->decl)))
650             {
651               inform (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
652                       "but is prevailed by one without from other translation unit");
653               inform (DECL_SOURCE_LOCATION (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
654                       "RTTI will not work on this type");
655             }
656           n2++;
657           end2 = !vtable->iterate_reference (n2, ref2);
658         }
659       if (!end1 && !end2
660           && DECL_ASSEMBLER_NAME (ref1->referred->decl)
661              != DECL_ASSEMBLER_NAME (ref2->referred->decl)
662           && !n1
663           && !DECL_VIRTUAL_P (ref1->referred->decl)
664           && DECL_VIRTUAL_P (ref2->referred->decl))
665         {
666           n1++;
667           end1 = !vtable->iterate_reference (n1, ref1);
668         }
669       if (end1 || end2)
670         {
671           if (end1)
672             {
673               varpool_node *tmp = prevailing;
674               prevailing = vtable;
675               vtable = tmp;
676               ref1 = ref2;
677             }
678           if (warning_at (DECL_SOURCE_LOCATION
679                             (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
680                           "virtual table of type %qD violates "
681                           "one definition rule",
682                           DECL_CONTEXT (vtable->decl)))
683             {
684               inform (DECL_SOURCE_LOCATION
685                        (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
686                       "the conflicting type defined in another translation "
687                       "unit");
688               inform (DECL_SOURCE_LOCATION
689                         (TYPE_NAME (DECL_CONTEXT (ref1->referring->decl))),
690                       "contains additional virtual method %qD",
691                       ref1->referred->decl);
692             }
693           return;
694         }
695       if (DECL_ASSEMBLER_NAME (ref1->referred->decl)
696           != DECL_ASSEMBLER_NAME (ref2->referred->decl))
697         {
698           if (warning_at (DECL_SOURCE_LOCATION
699                             (TYPE_NAME (DECL_CONTEXT (vtable->decl))), 0,
700                           "virtual table of type %qD violates "
701                           "one definition rule  ",
702                           DECL_CONTEXT (vtable->decl)))
703             {
704               inform (DECL_SOURCE_LOCATION 
705                         (TYPE_NAME (DECL_CONTEXT (prevailing->decl))),
706                       "the conflicting type defined in another translation "
707                       "unit");
708               inform (DECL_SOURCE_LOCATION (ref1->referred->decl),
709                       "virtual method %qD", ref1->referred->decl);
710               inform (DECL_SOURCE_LOCATION (ref2->referred->decl),
711                       "ought to match virtual method %qD but does not",
712                       ref2->referred->decl);
713               return;
714             }
715         }
716     }
717 }
718
719 /* Output ODR violation warning about T1 and T2 with REASON.
720    Display location of ST1 and ST2 if REASON speaks about field or
721    method of the type.
722    If WARN is false, do nothing. Set WARNED if warning was indeed
723    output.  */
724
725 void
726 warn_odr (tree t1, tree t2, tree st1, tree st2,
727           bool warn, bool *warned, const char *reason)
728 {
729   tree decl2 = TYPE_NAME (t2);
730
731   if (!warn)
732     return;
733   if (!warning_at (DECL_SOURCE_LOCATION (TYPE_NAME (t1)), OPT_Wodr,
734                    "type %qT violates one definition rule",
735                    t1))
736     return;
737   if (!st1 && !st2)
738     ;
739   /* For FIELD_DECL support also case where one of fields is
740      NULL - this is used when the structures have mismatching number of
741      elements.  */
742   else if (!st1 || TREE_CODE (st1) == FIELD_DECL)
743     {
744       inform (DECL_SOURCE_LOCATION (decl2),
745               "a different type is defined in another translation unit");
746       if (!st1)
747         {
748           st1 = st2;
749           st2 = NULL;
750         }
751       inform (DECL_SOURCE_LOCATION (st1),
752               "the first difference of corresponding definitions is field %qD",
753               st1);
754       if (st2)
755         decl2 = st2;
756     }
757   else if (TREE_CODE (st1) == FUNCTION_DECL)
758     {
759       inform (DECL_SOURCE_LOCATION (decl2),
760               "a different type is defined in another translation unit");
761       inform (DECL_SOURCE_LOCATION (st1),
762               "the first difference of corresponding definitions is method %qD",
763               st1);
764       decl2 = st2;
765     }
766   else
767     return;
768   inform (DECL_SOURCE_LOCATION (decl2), reason);
769
770   if (warned)
771     *warned = true;
772 }
773
774 /* We already warned about ODR mismatch.  T1 and T2 ought to be equivalent
775    because they are used on same place in ODR matching types.
776    They are not; inform the user.  */
777
778 void
779 warn_types_mismatch (tree t1, tree t2)
780 {
781   if (!TYPE_NAME (t1) || !TYPE_NAME (t2))
782     return;
783   /* In Firefox it is a common bug to have same types but in
784      different namespaces.  Be a bit more informative on
785      this.  */
786   if (TYPE_CONTEXT (t1) && TYPE_CONTEXT (t2)
787       && (((TREE_CODE (TYPE_CONTEXT (t1)) == NAMESPACE_DECL)
788             != (TREE_CODE (TYPE_CONTEXT (t2)) == NAMESPACE_DECL))
789            || (TREE_CODE (TYPE_CONTEXT (t1)) == NAMESPACE_DECL
790                && (DECL_NAME (TYPE_CONTEXT (t1)) !=
791                    DECL_NAME (TYPE_CONTEXT (t2))))))
792     inform (DECL_SOURCE_LOCATION (TYPE_NAME (t1)),
793             "type %qT should match type %qT but is defined "
794             "in different namespace  ",
795             t1, t2);
796   else
797     inform (DECL_SOURCE_LOCATION (TYPE_NAME (t1)),
798             "type %qT should match type %qT",
799             t1, t2);
800   inform (DECL_SOURCE_LOCATION (TYPE_NAME (t2)),
801           "the incompatible type is defined here");
802 }
803
804 /* Compare T1 and T2, report ODR violations if WARN is true and set
805    WARNED to true if anything is reported.  Return true if types match.
806    If true is returned, the types are also compatible in the sense of
807    gimple_canonical_types_compatible_p.  */
808
809 static bool
810 odr_types_equivalent_p (tree t1, tree t2, bool warn, bool *warned,
811                         hash_set<type_pair,pair_traits> *visited)
812 {
813   /* Check first for the obvious case of pointer identity.  */
814   if (t1 == t2)
815     return true;
816   gcc_assert (!type_in_anonymous_namespace_p (t1));
817   gcc_assert (!type_in_anonymous_namespace_p (t2));
818
819   /* Can't be the same type if the types don't have the same code.  */
820   if (TREE_CODE (t1) != TREE_CODE (t2))
821     {
822       warn_odr (t1, t2, NULL, NULL, warn, warned,
823                 G_("a different type is defined in another translation unit"));
824       return false;
825     }
826
827   if (TYPE_QUALS (t1) != TYPE_QUALS (t2))
828     {
829       warn_odr (t1, t2, NULL, NULL, warn, warned,
830                 G_("a type with different qualifiers is defined in another "
831                    "translation unit"));
832       return false;
833     }
834
835   if (comp_type_attributes (t1, t2) != 1)
836     {
837       warn_odr (t1, t2, NULL, NULL, warn, warned,
838                 G_("a type with attributes "
839                    "is defined in another translation unit"));
840       return false;
841     }
842
843   if (TREE_CODE (t1) == ENUMERAL_TYPE)
844     {
845       tree v1, v2;
846       for (v1 = TYPE_VALUES (t1), v2 = TYPE_VALUES (t2);
847            v1 && v2 ; v1 = TREE_CHAIN (v1), v2 = TREE_CHAIN (v2))
848         {
849           if (TREE_PURPOSE (v1) != TREE_PURPOSE (v2))
850             {
851               warn_odr (t1, t2, NULL, NULL, warn, warned,
852                         G_("an enum with different value name"
853                            " is defined in another translation unit"));
854               return false;
855             }
856           if (TREE_VALUE (v1) != TREE_VALUE (v2)
857               && !operand_equal_p (DECL_INITIAL (TREE_VALUE (v1)),
858                                    DECL_INITIAL (TREE_VALUE (v2)), 0))
859             {
860               warn_odr (t1, t2, NULL, NULL, warn, warned,
861                         G_("an enum with different values is defined"
862                            " in another translation unit"));
863               return false;
864             }
865         }
866       if (v1 || v2)
867         {
868           warn_odr (t1, t2, NULL, NULL, warn, warned,
869                     G_("an enum with mismatching number of values "
870                        "is defined in another translation unit"));
871           return false;
872         }
873     }
874
875   /* Non-aggregate types can be handled cheaply.  */
876   if (INTEGRAL_TYPE_P (t1)
877       || SCALAR_FLOAT_TYPE_P (t1)
878       || FIXED_POINT_TYPE_P (t1)
879       || TREE_CODE (t1) == VECTOR_TYPE
880       || TREE_CODE (t1) == COMPLEX_TYPE
881       || TREE_CODE (t1) == OFFSET_TYPE
882       || POINTER_TYPE_P (t1))
883     {
884       if (TYPE_PRECISION (t1) != TYPE_PRECISION (t2))
885         {
886           warn_odr (t1, t2, NULL, NULL, warn, warned,
887                     G_("a type with different precision is defined "
888                        "in another translation unit"));
889           return false;
890         }
891       if (TYPE_UNSIGNED (t1) != TYPE_UNSIGNED (t2))
892         {
893           warn_odr (t1, t2, NULL, NULL, warn, warned,
894                     G_("a type with different signedness is defined "
895                        "in another translation unit"));
896           return false;
897         }
898
899       if (TREE_CODE (t1) == INTEGER_TYPE
900           && TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2))
901         {
902           /* char WRT uint_8?  */
903           warn_odr (t1, t2, NULL, NULL, warn, warned,
904                     G_("a different type is defined in another "
905                        "translation unit"));
906           return false;
907         }
908
909       /* For canonical type comparisons we do not want to build SCCs
910          so we cannot compare pointed-to types.  But we can, for now,
911          require the same pointed-to type kind and match what
912          useless_type_conversion_p would do.  */
913       if (POINTER_TYPE_P (t1))
914         {
915           if (TYPE_ADDR_SPACE (TREE_TYPE (t1))
916               != TYPE_ADDR_SPACE (TREE_TYPE (t2)))
917             {
918               warn_odr (t1, t2, NULL, NULL, warn, warned,
919                         G_("it is defined as a pointer in different address "
920                            "space in another translation unit"));
921               return false;
922             }
923
924           if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
925             {
926               warn_odr (t1, t2, NULL, NULL, warn, warned,
927                         G_("it is defined as a pointer to different type "
928                            "in another translation unit"));
929               if (warn && warned)
930                 warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
931               return false;
932             }
933         }
934
935       if ((TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE)
936           && !odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
937         {
938           /* Probably specific enough.  */
939           warn_odr (t1, t2, NULL, NULL, warn, warned,
940                     G_("a different type is defined "
941                        "in another translation unit"));
942           if (warn && warned)
943             warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
944           return false;
945         }
946     }
947   /* Do type-specific comparisons.  */
948   else switch (TREE_CODE (t1))
949     {
950     case ARRAY_TYPE:
951       {
952         /* Array types are the same if the element types are the same and
953            the number of elements are the same.  */
954         if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
955           {
956             warn_odr (t1, t2, NULL, NULL, warn, warned,
957                       G_("a different type is defined in another "
958                          "translation unit"));
959             if (warn && warned)
960               warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
961           }
962         gcc_assert (TYPE_STRING_FLAG (t1) == TYPE_STRING_FLAG (t2));
963         gcc_assert (TYPE_NONALIASED_COMPONENT (t1)
964                     == TYPE_NONALIASED_COMPONENT (t2));
965
966         tree i1 = TYPE_DOMAIN (t1);
967         tree i2 = TYPE_DOMAIN (t2);
968
969         /* For an incomplete external array, the type domain can be
970            NULL_TREE.  Check this condition also.  */
971         if (i1 == NULL_TREE || i2 == NULL_TREE)
972           return true;
973
974         tree min1 = TYPE_MIN_VALUE (i1);
975         tree min2 = TYPE_MIN_VALUE (i2);
976         tree max1 = TYPE_MAX_VALUE (i1);
977         tree max2 = TYPE_MAX_VALUE (i2);
978
979         /* In C++, minimums should be always 0.  */
980         gcc_assert (min1 == min2);
981         if (!operand_equal_p (max1, max2, 0))
982           {
983             warn_odr (t1, t2, NULL, NULL, warn, warned,
984                       G_("an array of different size is defined "
985                          "in another translation unit"));
986             return false;
987           }
988       }
989     break;
990
991     case METHOD_TYPE:
992     case FUNCTION_TYPE:
993       /* Function types are the same if the return type and arguments types
994          are the same.  */
995       if (!odr_subtypes_equivalent_p (TREE_TYPE (t1), TREE_TYPE (t2), visited))
996         {
997           warn_odr (t1, t2, NULL, NULL, warn, warned,
998                     G_("has different return value "
999                        "in another translation unit"));
1000           if (warn && warned)
1001             warn_types_mismatch (TREE_TYPE (t1), TREE_TYPE (t2));
1002           return false;
1003         }
1004
1005       if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2))
1006         return true;
1007       else
1008         {
1009           tree parms1, parms2;
1010
1011           for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2);
1012                parms1 && parms2;
1013                parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2))
1014             {
1015               if (!odr_subtypes_equivalent_p
1016                      (TREE_VALUE (parms1), TREE_VALUE (parms2), visited))
1017                 {
1018                   warn_odr (t1, t2, NULL, NULL, warn, warned,
1019                             G_("has different parameters in another "
1020                                "translation unit"));
1021                   if (warn && warned)
1022                     warn_types_mismatch (TREE_VALUE (parms1),
1023                                          TREE_VALUE (parms2));
1024                   return false;
1025                 }
1026             }
1027
1028           if (parms1 || parms2)
1029             {
1030               warn_odr (t1, t2, NULL, NULL, warn, warned,
1031                         G_("has different parameters "
1032                            "in another translation unit"));
1033               return false;
1034             }
1035
1036           return true;
1037         }
1038
1039     case RECORD_TYPE:
1040     case UNION_TYPE:
1041     case QUAL_UNION_TYPE:
1042       {
1043         tree f1, f2;
1044
1045         /* For aggregate types, all the fields must be the same.  */
1046         if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2))
1047           {
1048             for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2);
1049                  f1 || f2;
1050                  f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2))
1051               {
1052                 /* Skip non-fields.  */
1053                 while (f1 && TREE_CODE (f1) != FIELD_DECL)
1054                   f1 = TREE_CHAIN (f1);
1055                 while (f2 && TREE_CODE (f2) != FIELD_DECL)
1056                   f2 = TREE_CHAIN (f2);
1057                 if (!f1 || !f2)
1058                   break;
1059                 if (DECL_ARTIFICIAL (f1) != DECL_ARTIFICIAL (f2))
1060                   break;
1061                 if (DECL_NAME (f1) != DECL_NAME (f2)
1062                     && !DECL_ARTIFICIAL (f1))
1063                   {
1064                     warn_odr (t1, t2, f1, f2, warn, warned,
1065                               G_("a field with different name is defined "
1066                                  "in another translation unit"));
1067                     return false;
1068                   }
1069                 if (!odr_subtypes_equivalent_p (TREE_TYPE (f1), TREE_TYPE (f2), visited))
1070                   {
1071                     /* Do not warn about artificial fields and just go into generic
1072                        field mismatch warning.  */
1073                     if (DECL_ARTIFICIAL (f1))
1074                       break;
1075
1076                     warn_odr (t1, t2, f1, f2, warn, warned,
1077                               G_("a field of same name but different type "
1078                                  "is defined in another translation unit"));
1079                     if (warn && warned)
1080                       warn_types_mismatch (TREE_TYPE (f1), TREE_TYPE (f2));
1081                     return false;
1082                   }
1083                 if (!gimple_compare_field_offset (f1, f2))
1084                   {
1085                     /* Do not warn about artificial fields and just go into generic
1086                        field mismatch warning.  */
1087                     if (DECL_ARTIFICIAL (f1))
1088                       break;
1089                     warn_odr (t1, t2, t1, t2, warn, warned,
1090                               G_("fields has different layout "
1091                                  "in another translation unit"));
1092                     return false;
1093                   }
1094                 gcc_assert (DECL_NONADDRESSABLE_P (f1)
1095                             == DECL_NONADDRESSABLE_P (f2));
1096               }
1097
1098             /* If one aggregate has more fields than the other, they
1099                are not the same.  */
1100             if (f1 || f2)
1101               {
1102                 if (f1 && DECL_ARTIFICIAL (f1))
1103                   f1 = NULL;
1104                 if (f2 && DECL_ARTIFICIAL (f2))
1105                   f2 = NULL;
1106                 if (f1 || f2)
1107                   warn_odr (t1, t2, f1, f2, warn, warned,
1108                             G_("a type with different number of fields "
1109                                "is defined in another translation unit"));
1110                 /* Ideally we should never get this generic message.  */
1111                 else
1112                   warn_odr (t1, t2, f1, f2, warn, warned,
1113                             G_("a type with different memory representation "
1114                                "is defined in another translation unit"));
1115                 
1116                 return false;
1117               }
1118             if ((TYPE_MAIN_VARIANT (t1) == t1 || TYPE_MAIN_VARIANT (t2) == t2)
1119                 && (TYPE_METHODS (TYPE_MAIN_VARIANT (t1))
1120                     != TYPE_METHODS (TYPE_MAIN_VARIANT (t2))))
1121               {
1122                 for (f1 = TYPE_METHODS (TYPE_MAIN_VARIANT (t1)),
1123                      f2 = TYPE_METHODS (TYPE_MAIN_VARIANT (t2));
1124                      f1 && f2 ; f1 = DECL_CHAIN (f1), f2 = DECL_CHAIN (f2))
1125                   {
1126                     if (DECL_ASSEMBLER_NAME (f1) != DECL_ASSEMBLER_NAME (f2))
1127                       {
1128                         warn_odr (t1, t2, f1, f2, warn, warned,
1129                                   G_("a different method of same type "
1130                                      "is defined in another translation unit"));
1131                         return false;
1132                       }
1133                     if (DECL_VIRTUAL_P (f1) != DECL_VIRTUAL_P (f2))
1134                       {
1135                         warn_odr (t1, t2, f1, f2, warn, warned,
1136                                   G_("s definition that differs by virtual "
1137                                      "keyword in another translation unit"));
1138                         return false;
1139                       }
1140                     if (DECL_VINDEX (f1) != DECL_VINDEX (f2))
1141                       {
1142                         warn_odr (t1, t2, f1, f2, warn, warned,
1143                                   G_("virtual table layout differs in another "
1144                                      "translation unit"));
1145                         return false;
1146                       }
1147                     if (odr_subtypes_equivalent_p (TREE_TYPE (f1), TREE_TYPE (f2), visited))
1148                       {
1149                         warn_odr (t1, t2, f1, f2, warn, warned,
1150                                   G_("method with incompatible type is defined "
1151                                      "in another translation unit"));
1152                         return false;
1153                       }
1154                   }
1155                 if (f1 || f2)
1156                   {
1157                     warn_odr (t1, t2, NULL, NULL, warn, warned,
1158                               G_("a type with different number of methods "
1159                                  "is defined in another translation unit"));
1160                     return false;
1161                   }
1162               }
1163           }
1164         break;
1165       }
1166     case VOID_TYPE:
1167       break;
1168
1169     default:
1170       debug_tree (t1);
1171       gcc_unreachable ();
1172     }
1173
1174   /* Those are better to come last as they are utterly uninformative.  */
1175   if (TYPE_SIZE (t1) && TYPE_SIZE (t2)
1176       && !operand_equal_p (TYPE_SIZE (t1), TYPE_SIZE (t2), 0))
1177     {
1178       warn_odr (t1, t2, NULL, NULL, warn, warned,
1179                 G_("a type with different size "
1180                    "is defined in another translation unit"));
1181       return false;
1182     }
1183   if (COMPLETE_TYPE_P (t1) && COMPLETE_TYPE_P (t2)
1184       && TYPE_ALIGN (t1) != TYPE_ALIGN (t2))
1185     {
1186       warn_odr (t1, t2, NULL, NULL, warn, warned,
1187                 G_("a type with different alignment "
1188                    "is defined in another translation unit"));
1189       return false;
1190     }
1191   gcc_assert (!TYPE_SIZE_UNIT (t1) || !TYPE_SIZE_UNIT (t2)
1192               || operand_equal_p (TYPE_SIZE_UNIT (t1),
1193                                   TYPE_SIZE_UNIT (t2), 0));
1194   return true;
1195 }
1196
1197 /* TYPE is equivalent to VAL by ODR, but its tree representation differs
1198    from VAL->type.  This may happen in LTO where tree merging did not merge
1199    all variants of the same type.  It may or may not mean the ODR violation.
1200    Add it to the list of duplicates and warn on some violations.  */
1201
1202 static bool
1203 add_type_duplicate (odr_type val, tree type)
1204 {
1205   bool build_bases = false;
1206   if (!val->types_set)
1207     val->types_set = new hash_set<tree>;
1208
1209   /* Always prefer complete type to be the leader.  */
1210   if ((!COMPLETE_TYPE_P (val->type) || !TYPE_BINFO (val->type))
1211       && (COMPLETE_TYPE_P (type) && TYPE_BINFO (val->type)))
1212     {
1213       tree tmp = type;
1214
1215       build_bases = true;
1216       type = val->type;
1217       val->type = tmp;
1218     }
1219
1220   /* See if this duplicate is new.  */
1221   if (!val->types_set->add (type))
1222     {
1223       bool merge = true;
1224       bool base_mismatch = false;
1225       unsigned int i;
1226       bool warned = false;
1227       hash_set<type_pair,pair_traits> visited;
1228
1229       gcc_assert (in_lto_p);
1230       vec_safe_push (val->types, type);
1231
1232       /* First we compare memory layout.  */
1233       if (!odr_types_equivalent_p (val->type, type,
1234                                    !flag_ltrans && !val->odr_violated,
1235                                    &warned, &visited))
1236         {
1237           merge = false;
1238           odr_violation_reported = true;
1239           val->odr_violated = true;
1240           if (symtab->dump_file)
1241             {
1242               fprintf (symtab->dump_file, "ODR violation\n");
1243             
1244               print_node (symtab->dump_file, "", val->type, 0);
1245               putc ('\n',symtab->dump_file);
1246               print_node (symtab->dump_file, "", type, 0);
1247               putc ('\n',symtab->dump_file);
1248             }
1249         }
1250
1251       /* Next sanity check that bases are the same.  If not, we will end
1252          up producing wrong answers.  */
1253       if (COMPLETE_TYPE_P (type) && COMPLETE_TYPE_P (val->type)
1254           && TREE_CODE (val->type) == RECORD_TYPE
1255           && TREE_CODE (type) == RECORD_TYPE
1256           && TYPE_BINFO (val->type) && TYPE_BINFO (type))
1257         {
1258           if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
1259               != BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
1260             {
1261               if (!warned && !val->odr_violated)
1262                 {
1263                   tree extra_base;
1264                   warn_odr (type, val->type, NULL, NULL, !warned, &warned,
1265                             "a type with the same name but different "
1266                             "number of polymorphic bases is "
1267                             "defined in another translation unit");
1268                   if (BINFO_N_BASE_BINFOS (TYPE_BINFO (type))
1269                       > BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)))
1270                     extra_base = BINFO_BASE_BINFO
1271                                  (TYPE_BINFO (type),
1272                                   BINFO_N_BASE_BINFOS (TYPE_BINFO (val->type)));
1273                   else
1274                     extra_base = BINFO_BASE_BINFO
1275                                  (TYPE_BINFO (val->type),
1276                                   BINFO_N_BASE_BINFOS (TYPE_BINFO (type)));
1277                   inform (DECL_SOURCE_LOCATION 
1278                             (TYPE_NAME (DECL_CONTEXT (extra_base))),
1279                           "the extra base is defined here ");
1280                 }
1281               base_mismatch = true;
1282             }
1283           else
1284             for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
1285               {
1286                 tree base1 = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
1287                 tree base2 = BINFO_BASE_BINFO (TYPE_BINFO (val->type), i);
1288                 tree type1 = BINFO_TYPE (base1);
1289                 tree type2 = BINFO_TYPE (base2);
1290
1291                 if (types_odr_comparable (type1, type2))
1292                   {
1293                     if (!types_same_for_odr (type1, type2))
1294                       base_mismatch = true;
1295                   }
1296                 else
1297                   {
1298                     hash_set<type_pair,pair_traits> visited;
1299                     if (!odr_types_equivalent_p (type1, type2, false, NULL,
1300                                                  &visited))
1301                       base_mismatch = true;
1302                   }
1303                 if (base_mismatch)
1304                   {
1305                     if (!warned && !val->odr_violated)
1306                       warn_odr (type, val->type, NULL, NULL,
1307                                 !warned, &warned,
1308                                 "a type with the same name but different base "
1309                                 "type is defined in another translation unit");
1310                     warn_types_mismatch (type1, type2);
1311                     break;
1312                   }
1313                 if (BINFO_OFFSET (base1) != BINFO_OFFSET (base2))
1314                   {
1315                     base_mismatch = true;
1316                     if (!warned && !val->odr_violated)
1317                       warn_odr (type, val->type, NULL, NULL,
1318                                 !warned, &warned,
1319                                 "a type with the same name but different base "
1320                                 "layout is defined in another translation unit");
1321                     break;
1322                   }
1323               }
1324 #ifdef ENABLE_CHECKING
1325           /* Sanity check that all bases will be build same way again.  */
1326           if (!base_mismatch && val->bases.length ())
1327             {
1328               unsigned int num_poly_bases = 0;
1329               unsigned int j;
1330
1331               for (i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type)); i++)
1332                 if (polymorphic_type_binfo_p (BINFO_BASE_BINFO
1333                                                  (TYPE_BINFO (type), i)))
1334                   num_poly_bases++;
1335               gcc_assert (num_poly_bases == val->bases.length ());
1336               for (j = 0, i = 0; i < BINFO_N_BASE_BINFOS (TYPE_BINFO (type));
1337                    i++)
1338                 if (polymorphic_type_binfo_p (BINFO_BASE_BINFO 
1339                                                (TYPE_BINFO (type), i)))
1340                   {
1341                     odr_type base = get_odr_type
1342                                        (BINFO_TYPE
1343                                           (BINFO_BASE_BINFO (TYPE_BINFO (type),
1344                                                              i)),
1345                                         true);
1346                     gcc_assert (val->bases[j] == base);
1347                     j++;
1348                   }
1349             }
1350 #endif
1351           if (base_mismatch)
1352             {
1353               merge = false;
1354               odr_violation_reported = true;
1355               val->odr_violated = true;
1356
1357               if (symtab->dump_file)
1358                 {
1359                   fprintf (symtab->dump_file, "ODR base violation\n");
1360                 
1361                   print_node (symtab->dump_file, "", val->type, 0);
1362                   putc ('\n',symtab->dump_file);
1363                   print_node (symtab->dump_file, "", type, 0);
1364                   putc ('\n',symtab->dump_file);
1365                 }
1366             }
1367         }
1368
1369       /* Regularize things a little.  During LTO same types may come with
1370          different BINFOs.  Either because their virtual table was
1371          not merged by tree merging and only later at decl merging or
1372          because one type comes with external vtable, while other
1373          with internal.  We want to merge equivalent binfos to conserve
1374          memory and streaming overhead.
1375
1376          The external vtables are more harmful: they contain references
1377          to external declarations of methods that may be defined in the
1378          merged LTO unit.  For this reason we absolutely need to remove
1379          them and replace by internal variants. Not doing so will lead
1380          to incomplete answers from possible_polymorphic_call_targets.
1381
1382          FIXME: disable for now; because ODR types are now build during
1383          streaming in, the variants do not need to be linked to the type,
1384          yet.  We need to do the merging in cleanup pass to be implemented
1385          soon.  */
1386       if (!flag_ltrans && merge
1387           && 0
1388           && TREE_CODE (val->type) == RECORD_TYPE
1389           && TREE_CODE (type) == RECORD_TYPE
1390           && TYPE_BINFO (val->type) && TYPE_BINFO (type)
1391           && TYPE_MAIN_VARIANT (type) == type
1392           && TYPE_MAIN_VARIANT (val->type) == val->type
1393           && BINFO_VTABLE (TYPE_BINFO (val->type))
1394           && BINFO_VTABLE (TYPE_BINFO (type)))
1395         {
1396           tree master_binfo = TYPE_BINFO (val->type);
1397           tree v1 = BINFO_VTABLE (master_binfo);
1398           tree v2 = BINFO_VTABLE (TYPE_BINFO (type));
1399
1400           if (TREE_CODE (v1) == POINTER_PLUS_EXPR)
1401             {
1402               gcc_assert (TREE_CODE (v2) == POINTER_PLUS_EXPR
1403                           && operand_equal_p (TREE_OPERAND (v1, 1),
1404                                               TREE_OPERAND (v2, 1), 0));
1405               v1 = TREE_OPERAND (TREE_OPERAND (v1, 0), 0);
1406               v2 = TREE_OPERAND (TREE_OPERAND (v2, 0), 0);
1407             }
1408           gcc_assert (DECL_ASSEMBLER_NAME (v1)
1409                       == DECL_ASSEMBLER_NAME (v2));
1410
1411           if (DECL_EXTERNAL (v1) && !DECL_EXTERNAL (v2))
1412             {
1413               unsigned int i;
1414
1415               set_type_binfo (val->type, TYPE_BINFO (type));
1416               for (i = 0; i < val->types->length (); i++)
1417                 {
1418                   if (TYPE_BINFO ((*val->types)[i])
1419                       == master_binfo)
1420                     set_type_binfo ((*val->types)[i], TYPE_BINFO (type));
1421                 }
1422               BINFO_TYPE (TYPE_BINFO (type)) = val->type;
1423             }
1424           else
1425             set_type_binfo (type, master_binfo);
1426         }
1427     }
1428   return build_bases;
1429 }
1430
1431 /* Get ODR type hash entry for TYPE.  If INSERT is true, create
1432    possibly new entry.  */
1433
1434 odr_type
1435 get_odr_type (tree type, bool insert)
1436 {
1437   odr_type_d **slot;
1438   odr_type val;
1439   hashval_t hash;
1440   bool build_bases = false;
1441   bool insert_to_odr_array = false;
1442   int base_id = -1;
1443
1444   type = main_odr_variant (type);
1445
1446   hash = hash_type_name (type);
1447   slot = odr_hash->find_slot_with_hash (type, hash,
1448                                         insert ? INSERT : NO_INSERT);
1449   if (!slot)
1450     return NULL;
1451
1452   /* See if we already have entry for type.  */
1453   if (*slot)
1454     {
1455       val = *slot;
1456
1457       /* With LTO we need to support multiple tree representation of
1458          the same ODR type.  */
1459       if (val->type != type)
1460         build_bases = add_type_duplicate (val, type);
1461     }
1462   else
1463     {
1464       val = ggc_cleared_alloc<odr_type_d> ();
1465       val->type = type;
1466       val->bases = vNULL;
1467       val->derived_types = vNULL;
1468       val->anonymous_namespace = type_in_anonymous_namespace_p (type);
1469       build_bases = COMPLETE_TYPE_P (val->type);
1470       insert_to_odr_array = true;
1471     }
1472
1473   if (build_bases && TREE_CODE (type) == RECORD_TYPE && TYPE_BINFO (type)
1474       && type == TYPE_MAIN_VARIANT (type))
1475     {
1476       tree binfo = TYPE_BINFO (type);
1477       unsigned int i;
1478
1479       gcc_assert (BINFO_TYPE (TYPE_BINFO (val->type)) = type);
1480   
1481       val->all_derivations_known = type_all_derivations_known_p (type);
1482       *slot = val;
1483       for (i = 0; i < BINFO_N_BASE_BINFOS (binfo); i++)
1484         /* For now record only polymorphic types. other are
1485            pointless for devirtualization and we can not precisely
1486            determine ODR equivalency of these during LTO.  */
1487         if (polymorphic_type_binfo_p (BINFO_BASE_BINFO (binfo, i)))
1488           {
1489             odr_type base = get_odr_type (BINFO_TYPE (BINFO_BASE_BINFO (binfo,
1490                                                                         i)),
1491                                           true);
1492             gcc_assert (TYPE_MAIN_VARIANT (base->type) == base->type);
1493             base->derived_types.safe_push (val);
1494             val->bases.safe_push (base);
1495             if (base->id > base_id)
1496               base_id = base->id;
1497           }
1498       }
1499   /* Ensure that type always appears after bases.  */
1500   if (insert_to_odr_array)
1501     {
1502       if (odr_types_ptr)
1503         val->id = odr_types.length ();
1504       vec_safe_push (odr_types_ptr, val);
1505     }
1506   else if (base_id > val->id)
1507     {
1508       odr_types[val->id] = 0;
1509       /* Be sure we did not recorded any derived types; these may need
1510          renumbering too.  */
1511       gcc_assert (val->derived_types.length() == 0);
1512       if (odr_types_ptr)
1513         val->id = odr_types.length ();
1514       vec_safe_push (odr_types_ptr, val);
1515     }
1516   return val;
1517 }
1518
1519 /* Add TYPE od ODR type hash.  */
1520
1521 void
1522 register_odr_type (tree type)
1523 {
1524   if (!odr_hash)
1525     odr_hash = new odr_hash_type (23);
1526   /* Arrange things to be nicer and insert main variants first.  */
1527   if (odr_type_p (TYPE_MAIN_VARIANT (type)))
1528     get_odr_type (TYPE_MAIN_VARIANT (type), true);
1529   if (TYPE_MAIN_VARIANT (type) != type)
1530     get_odr_type (type, true);
1531 }
1532
1533 /* Return true if type is known to have no derivations.  */
1534
1535 bool
1536 type_known_to_have_no_deriavations_p (tree t)
1537 {
1538   return (type_all_derivations_known_p (t)
1539           && (TYPE_FINAL_P (t)
1540               || (odr_hash
1541                   && !get_odr_type (t, true)->derived_types.length())));
1542 }
1543
1544 /* Dump ODR type T and all its derived types.  INDENT specifies indentation for
1545    recursive printing.  */
1546
1547 static void
1548 dump_odr_type (FILE *f, odr_type t, int indent=0)
1549 {
1550   unsigned int i;
1551   fprintf (f, "%*s type %i: ", indent * 2, "", t->id);
1552   print_generic_expr (f, t->type, TDF_SLIM);
1553   fprintf (f, "%s", t->anonymous_namespace ? " (anonymous namespace)":"");
1554   fprintf (f, "%s\n", t->all_derivations_known ? " (derivations known)":"");
1555   if (TYPE_NAME (t->type))
1556     {
1557       fprintf (f, "%*s defined at: %s:%i\n", indent * 2, "",
1558                DECL_SOURCE_FILE (TYPE_NAME (t->type)),
1559                DECL_SOURCE_LINE (TYPE_NAME (t->type)));
1560     }
1561   if (t->bases.length ())
1562     {
1563       fprintf (f, "%*s base odr type ids: ", indent * 2, "");
1564       for (i = 0; i < t->bases.length (); i++)
1565         fprintf (f, " %i", t->bases[i]->id);
1566       fprintf (f, "\n");
1567     }
1568   if (t->derived_types.length ())
1569     {
1570       fprintf (f, "%*s derived types:\n", indent * 2, "");
1571       for (i = 0; i < t->derived_types.length (); i++)
1572         dump_odr_type (f, t->derived_types[i], indent + 1);
1573     }
1574   fprintf (f, "\n");
1575 }
1576
1577 /* Dump the type inheritance graph.  */
1578
1579 static void
1580 dump_type_inheritance_graph (FILE *f)
1581 {
1582   unsigned int i;
1583   if (!odr_types_ptr)
1584     return;
1585   fprintf (f, "\n\nType inheritance graph:\n");
1586   for (i = 0; i < odr_types.length (); i++)
1587     {
1588       if (odr_types[i] && odr_types[i]->bases.length () == 0)
1589         dump_odr_type (f, odr_types[i]);
1590     }
1591   for (i = 0; i < odr_types.length (); i++)
1592     {
1593       if (odr_types[i] && odr_types[i]->types && odr_types[i]->types->length ())
1594         {
1595           unsigned int j;
1596           fprintf (f, "Duplicate tree types for odr type %i\n", i);
1597           print_node (f, "", odr_types[i]->type, 0);
1598           for (j = 0; j < odr_types[i]->types->length (); j++)
1599             {
1600               tree t;
1601               fprintf (f, "duplicate #%i\n", j);
1602               print_node (f, "", (*odr_types[i]->types)[j], 0);
1603               t = (*odr_types[i]->types)[j];
1604               while (TYPE_P (t) && TYPE_CONTEXT (t))
1605                 {
1606                   t = TYPE_CONTEXT (t);
1607                   print_node (f, "", t, 0);
1608                 }
1609               putc ('\n',f);
1610             }
1611         }
1612     }
1613 }
1614
1615 /* Given method type T, return type of class it belongs to.
1616    Look up this pointer and get its type.    */
1617
1618 tree
1619 method_class_type (const_tree t)
1620 {
1621   tree first_parm_type = TREE_VALUE (TYPE_ARG_TYPES (t));
1622   gcc_assert (TREE_CODE (t) == METHOD_TYPE);
1623
1624   return TREE_TYPE (first_parm_type);
1625 }
1626
1627 /* Initialize IPA devirt and build inheritance tree graph.  */
1628
1629 void
1630 build_type_inheritance_graph (void)
1631 {
1632   struct symtab_node *n;
1633   FILE *inheritance_dump_file;
1634   int flags;
1635
1636   if (odr_hash)
1637     return;
1638   timevar_push (TV_IPA_INHERITANCE);
1639   inheritance_dump_file = dump_begin (TDI_inheritance, &flags);
1640   odr_hash = new odr_hash_type (23);
1641
1642   /* We reconstruct the graph starting of types of all methods seen in the
1643      the unit.  */
1644   FOR_EACH_SYMBOL (n)
1645     if (is_a <cgraph_node *> (n)
1646         && DECL_VIRTUAL_P (n->decl)
1647         && n->real_symbol_p ())
1648       get_odr_type (TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (n->decl))),
1649                     true);
1650
1651     /* Look also for virtual tables of types that do not define any methods.
1652  
1653        We need it in a case where class B has virtual base of class A
1654        re-defining its virtual method and there is class C with no virtual
1655        methods with B as virtual base.
1656
1657        Here we output B's virtual method in two variant - for non-virtual
1658        and virtual inheritance.  B's virtual table has non-virtual version,
1659        while C's has virtual.
1660
1661        For this reason we need to know about C in order to include both
1662        variants of B.  More correctly, record_target_from_binfo should
1663        add both variants of the method when walking B, but we have no
1664        link in between them.
1665
1666        We rely on fact that either the method is exported and thus we
1667        assume it is called externally or C is in anonymous namespace and
1668        thus we will see the vtable.  */
1669
1670     else if (is_a <varpool_node *> (n)
1671              && DECL_VIRTUAL_P (n->decl)
1672              && TREE_CODE (DECL_CONTEXT (n->decl)) == RECORD_TYPE
1673              && TYPE_BINFO (DECL_CONTEXT (n->decl))
1674              && polymorphic_type_binfo_p (TYPE_BINFO (DECL_CONTEXT (n->decl))))
1675       get_odr_type (TYPE_MAIN_VARIANT (DECL_CONTEXT (n->decl)), true);
1676   if (inheritance_dump_file)
1677     {
1678       dump_type_inheritance_graph (inheritance_dump_file);
1679       dump_end (TDI_inheritance, inheritance_dump_file);
1680     }
1681   timevar_pop (TV_IPA_INHERITANCE);
1682 }
1683
1684 /* Return true if N has reference from live virtual table
1685    (and thus can be a destination of polymorphic call). 
1686    Be conservatively correct when callgraph is not built or
1687    if the method may be referred externally.  */
1688
1689 static bool
1690 referenced_from_vtable_p (struct cgraph_node *node)
1691 {
1692   int i;
1693   struct ipa_ref *ref;
1694   bool found = false;
1695
1696   if (node->externally_visible
1697       || DECL_EXTERNAL (node->decl)
1698       || node->used_from_other_partition)
1699     return true;
1700
1701   /* Keep this test constant time.
1702      It is unlikely this can happen except for the case where speculative
1703      devirtualization introduced many speculative edges to this node. 
1704      In this case the target is very likely alive anyway.  */
1705   if (node->ref_list.referring.length () > 100)
1706     return true;
1707
1708   /* We need references built.  */
1709   if (symtab->state <= CONSTRUCTION)
1710     return true;
1711
1712   for (i = 0; node->iterate_referring (i, ref); i++)
1713         
1714     if ((ref->use == IPA_REF_ALIAS
1715          && referenced_from_vtable_p (dyn_cast<cgraph_node *> (ref->referring)))
1716         || (ref->use == IPA_REF_ADDR
1717             && TREE_CODE (ref->referring->decl) == VAR_DECL
1718             && DECL_VIRTUAL_P (ref->referring->decl)))
1719       {
1720         found = true;
1721         break;
1722       }
1723   return found;
1724 }
1725
1726 /* If TARGET has associated node, record it in the NODES array.
1727    CAN_REFER specify if program can refer to the target directly.
1728    if TARGET is unknown (NULL) or it can not be inserted (for example because
1729    its body was already removed and there is no way to refer to it), clear
1730    COMPLETEP.  */
1731
1732 static void
1733 maybe_record_node (vec <cgraph_node *> &nodes,
1734                    tree target, hash_set<tree> *inserted,
1735                    bool can_refer,
1736                    bool *completep)
1737 {
1738   struct cgraph_node *target_node, *alias_target;
1739   enum availability avail;
1740
1741   /* cxa_pure_virtual and __builtin_unreachable do not need to be added into
1742      list of targets; the runtime effect of calling them is undefined.
1743      Only "real" virtual methods should be accounted.  */
1744   if (target && TREE_CODE (TREE_TYPE (target)) != METHOD_TYPE)
1745     return;
1746
1747   if (!can_refer)
1748     {
1749       /* The only case when method of anonymous namespace becomes unreferable
1750          is when we completely optimized it out.  */
1751       if (flag_ltrans
1752           || !target 
1753           || !type_in_anonymous_namespace_p (DECL_CONTEXT (target)))
1754         *completep = false;
1755       return;
1756     }
1757
1758   if (!target)
1759     return;
1760
1761   target_node = cgraph_node::get (target);
1762
1763   /* Prefer alias target over aliases, so we do not get confused by
1764      fake duplicates.  */
1765   if (target_node)
1766     {
1767       alias_target = target_node->ultimate_alias_target (&avail);
1768       if (target_node != alias_target
1769           && avail >= AVAIL_AVAILABLE
1770           && target_node->get_availability ())
1771         target_node = alias_target;
1772     }
1773
1774   /* Method can only be called by polymorphic call if any
1775      of vtables referring to it are alive. 
1776
1777      While this holds for non-anonymous functions, too, there are
1778      cases where we want to keep them in the list; for example
1779      inline functions with -fno-weak are static, but we still
1780      may devirtualize them when instance comes from other unit.
1781      The same holds for LTO.
1782
1783      Currently we ignore these functions in speculative devirtualization.
1784      ??? Maybe it would make sense to be more aggressive for LTO even
1785      elsewhere.  */
1786   if (!flag_ltrans
1787       && type_in_anonymous_namespace_p (DECL_CONTEXT (target))
1788       && (!target_node
1789           || !referenced_from_vtable_p (target_node)))
1790     ;
1791   /* See if TARGET is useful function we can deal with.  */
1792   else if (target_node != NULL
1793            && (TREE_PUBLIC (target)
1794                || DECL_EXTERNAL (target)
1795                || target_node->definition)
1796            && target_node->real_symbol_p ())
1797     {
1798       gcc_assert (!target_node->global.inlined_to);
1799       gcc_assert (target_node->real_symbol_p ());
1800       if (!inserted->add (target))
1801         {
1802           cached_polymorphic_call_targets->add (target_node);
1803           nodes.safe_push (target_node);
1804         }
1805     }
1806   else if (completep
1807            && (!type_in_anonymous_namespace_p
1808                  (DECL_CONTEXT (target))
1809                || flag_ltrans))
1810     *completep = false;
1811 }
1812
1813 /* See if BINFO's type matches OUTER_TYPE.  If so, look up 
1814    BINFO of subtype of OTR_TYPE at OFFSET and in that BINFO find
1815    method in vtable and insert method to NODES array
1816    or BASES_TO_CONSIDER if this array is non-NULL.
1817    Otherwise recurse to base BINFOs.
1818    This matches what get_binfo_at_offset does, but with offset
1819    being unknown.
1820
1821    TYPE_BINFOS is a stack of BINFOS of types with defined
1822    virtual table seen on way from class type to BINFO.
1823
1824    MATCHED_VTABLES tracks virtual tables we already did lookup
1825    for virtual function in. INSERTED tracks nodes we already
1826    inserted.
1827
1828    ANONYMOUS is true if BINFO is part of anonymous namespace.
1829
1830    Clear COMPLETEP when we hit unreferable target.
1831   */
1832
1833 static void
1834 record_target_from_binfo (vec <cgraph_node *> &nodes,
1835                           vec <tree> *bases_to_consider,
1836                           tree binfo,
1837                           tree otr_type,
1838                           vec <tree> &type_binfos,
1839                           HOST_WIDE_INT otr_token,
1840                           tree outer_type,
1841                           HOST_WIDE_INT offset,
1842                           hash_set<tree> *inserted,
1843                           hash_set<tree> *matched_vtables,
1844                           bool anonymous,
1845                           bool *completep)
1846 {
1847   tree type = BINFO_TYPE (binfo);
1848   int i;
1849   tree base_binfo;
1850
1851
1852   if (BINFO_VTABLE (binfo))
1853     type_binfos.safe_push (binfo);
1854   if (types_same_for_odr (type, outer_type))
1855     {
1856       int i;
1857       tree type_binfo = NULL;
1858
1859       /* Look up BINFO with virtual table.  For normal types it is always last
1860          binfo on stack.  */
1861       for (i = type_binfos.length () - 1; i >= 0; i--)
1862         if (BINFO_OFFSET (type_binfos[i]) == BINFO_OFFSET (binfo))
1863           {
1864             type_binfo = type_binfos[i];
1865             break;
1866           }
1867       if (BINFO_VTABLE (binfo))
1868         type_binfos.pop ();
1869       /* If this is duplicated BINFO for base shared by virtual inheritance,
1870          we may not have its associated vtable.  This is not a problem, since
1871          we will walk it on the other path.  */
1872       if (!type_binfo)
1873         return;
1874       tree inner_binfo = get_binfo_at_offset (type_binfo,
1875                                               offset, otr_type);
1876       if (!inner_binfo)
1877         {
1878           gcc_assert (odr_violation_reported);
1879           return;
1880         }
1881       /* For types in anonymous namespace first check if the respective vtable
1882          is alive. If not, we know the type can't be called.  */
1883       if (!flag_ltrans && anonymous)
1884         {
1885           tree vtable = BINFO_VTABLE (inner_binfo);
1886           varpool_node *vnode;
1887
1888           if (TREE_CODE (vtable) == POINTER_PLUS_EXPR)
1889             vtable = TREE_OPERAND (TREE_OPERAND (vtable, 0), 0);
1890           vnode = varpool_node::get (vtable);
1891           if (!vnode || !vnode->definition)
1892             return;
1893         }
1894       gcc_assert (inner_binfo);
1895       if (bases_to_consider
1896           ? !matched_vtables->contains (BINFO_VTABLE (inner_binfo))
1897           : !matched_vtables->add (BINFO_VTABLE (inner_binfo)))
1898         {
1899           bool can_refer;
1900           tree target = gimple_get_virt_method_for_binfo (otr_token,
1901                                                           inner_binfo,
1902                                                           &can_refer);
1903           if (!bases_to_consider)
1904             maybe_record_node (nodes, target, inserted, can_refer, completep);
1905           /* Destructors are never called via construction vtables.  */
1906           else if (!target || !DECL_CXX_DESTRUCTOR_P (target))
1907             bases_to_consider->safe_push (target);
1908         }
1909       return;
1910     }
1911
1912   /* Walk bases.  */
1913   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
1914     /* Walking bases that have no virtual method is pointless exercise.  */
1915     if (polymorphic_type_binfo_p (base_binfo))
1916       record_target_from_binfo (nodes, bases_to_consider, base_binfo, otr_type,
1917                                 type_binfos, 
1918                                 otr_token, outer_type, offset, inserted,
1919                                 matched_vtables, anonymous, completep);
1920   if (BINFO_VTABLE (binfo))
1921     type_binfos.pop ();
1922 }
1923      
1924 /* Look up virtual methods matching OTR_TYPE (with OFFSET and OTR_TOKEN)
1925    of TYPE, insert them to NODES, recurse into derived nodes. 
1926    INSERTED is used to avoid duplicate insertions of methods into NODES.
1927    MATCHED_VTABLES are used to avoid duplicate walking vtables.
1928    Clear COMPLETEP if unreferable target is found.
1929  
1930    If CONSIDER_CONSTRUCTION is true, record to BASES_TO_CONSIDER
1931    all cases where BASE_SKIPPED is true (because the base is abstract
1932    class).  */
1933
1934 static void
1935 possible_polymorphic_call_targets_1 (vec <cgraph_node *> &nodes,
1936                                      hash_set<tree> *inserted,
1937                                      hash_set<tree> *matched_vtables,
1938                                      tree otr_type,
1939                                      odr_type type,
1940                                      HOST_WIDE_INT otr_token,
1941                                      tree outer_type,
1942                                      HOST_WIDE_INT offset,
1943                                      bool *completep,
1944                                      vec <tree> &bases_to_consider,
1945                                      bool consider_construction)
1946 {
1947   tree binfo = TYPE_BINFO (type->type);
1948   unsigned int i;
1949   auto_vec <tree, 8> type_binfos;
1950   bool possibly_instantiated = type_possibly_instantiated_p (type->type);
1951
1952   /* We may need to consider types w/o instances because of possible derived
1953      types using their methods either directly or via construction vtables.
1954      We are safe to skip them when all derivations are known, since we will
1955      handle them later.
1956      This is done by recording them to BASES_TO_CONSIDER array.  */
1957   if (possibly_instantiated || consider_construction)
1958     {
1959       record_target_from_binfo (nodes,
1960                                 (!possibly_instantiated
1961                                  && type_all_derivations_known_p (type->type))
1962                                 ? &bases_to_consider : NULL,
1963                                 binfo, otr_type, type_binfos, otr_token,
1964                                 outer_type, offset,
1965                                 inserted, matched_vtables,
1966                                 type->anonymous_namespace, completep);
1967     }
1968   for (i = 0; i < type->derived_types.length (); i++)
1969     possible_polymorphic_call_targets_1 (nodes, inserted, 
1970                                          matched_vtables,
1971                                          otr_type,
1972                                          type->derived_types[i],
1973                                          otr_token, outer_type, offset, completep,
1974                                          bases_to_consider, consider_construction);
1975 }
1976
1977 /* Cache of queries for polymorphic call targets.
1978
1979    Enumerating all call targets may get expensive when there are many
1980    polymorphic calls in the program, so we memoize all the previous
1981    queries and avoid duplicated work.  */
1982
1983 struct polymorphic_call_target_d
1984 {
1985   HOST_WIDE_INT otr_token;
1986   ipa_polymorphic_call_context context;
1987   odr_type type;
1988   vec <cgraph_node *> targets;
1989   tree decl_warning;
1990   int type_warning;
1991   bool complete;
1992   bool speculative;
1993 };
1994
1995 /* Polymorphic call target cache helpers.  */
1996
1997 struct polymorphic_call_target_hasher 
1998 {
1999   typedef polymorphic_call_target_d value_type;
2000   typedef polymorphic_call_target_d compare_type;
2001   static inline hashval_t hash (const value_type *);
2002   static inline bool equal (const value_type *, const compare_type *);
2003   static inline void remove (value_type *);
2004 };
2005
2006 /* Return the computed hashcode for ODR_QUERY.  */
2007
2008 inline hashval_t
2009 polymorphic_call_target_hasher::hash (const value_type *odr_query)
2010 {
2011   inchash::hash hstate (odr_query->otr_token);
2012
2013   hstate.add_wide_int (odr_query->type->id);
2014   hstate.merge_hash (TYPE_UID (odr_query->context.outer_type));
2015   hstate.add_wide_int (odr_query->context.offset);
2016
2017   if (odr_query->context.speculative_outer_type)
2018     {
2019       hstate.merge_hash (TYPE_UID (odr_query->context.speculative_outer_type));
2020       hstate.add_wide_int (odr_query->context.speculative_offset);
2021     }
2022   hstate.add_flag (odr_query->speculative);
2023   hstate.add_flag (odr_query->context.maybe_in_construction);
2024   hstate.add_flag (odr_query->context.maybe_derived_type);
2025   hstate.add_flag (odr_query->context.speculative_maybe_derived_type);
2026   hstate.commit_flag ();
2027   return hstate.end ();
2028 }
2029
2030 /* Compare cache entries T1 and T2.  */
2031
2032 inline bool
2033 polymorphic_call_target_hasher::equal (const value_type *t1,
2034                                        const compare_type *t2)
2035 {
2036   return (t1->type == t2->type && t1->otr_token == t2->otr_token
2037           && t1->speculative == t2->speculative
2038           && t1->context.offset == t2->context.offset
2039           && t1->context.speculative_offset == t2->context.speculative_offset
2040           && t1->context.outer_type == t2->context.outer_type
2041           && t1->context.speculative_outer_type == t2->context.speculative_outer_type
2042           && t1->context.maybe_in_construction
2043               == t2->context.maybe_in_construction
2044           && t1->context.maybe_derived_type == t2->context.maybe_derived_type
2045           && (t1->context.speculative_maybe_derived_type
2046               == t2->context.speculative_maybe_derived_type));
2047 }
2048
2049 /* Remove entry in polymorphic call target cache hash.  */
2050
2051 inline void
2052 polymorphic_call_target_hasher::remove (value_type *v)
2053 {
2054   v->targets.release ();
2055   free (v);
2056 }
2057
2058 /* Polymorphic call target query cache.  */
2059
2060 typedef hash_table<polymorphic_call_target_hasher>
2061    polymorphic_call_target_hash_type;
2062 static polymorphic_call_target_hash_type *polymorphic_call_target_hash;
2063
2064 /* Destroy polymorphic call target query cache.  */
2065
2066 static void
2067 free_polymorphic_call_targets_hash ()
2068 {
2069   if (cached_polymorphic_call_targets)
2070     {
2071       delete polymorphic_call_target_hash;
2072       polymorphic_call_target_hash = NULL;
2073       delete cached_polymorphic_call_targets;
2074       cached_polymorphic_call_targets = NULL;
2075     }
2076 }
2077
2078 /* When virtual function is removed, we may need to flush the cache.  */
2079
2080 static void
2081 devirt_node_removal_hook (struct cgraph_node *n, void *d ATTRIBUTE_UNUSED)
2082 {
2083   if (cached_polymorphic_call_targets
2084       && cached_polymorphic_call_targets->contains (n))
2085     free_polymorphic_call_targets_hash ();
2086 }
2087
2088 /* Look up base of BINFO that has virtual table VTABLE with OFFSET.  */
2089
2090 tree
2091 subbinfo_with_vtable_at_offset (tree binfo, unsigned HOST_WIDE_INT offset,
2092                                 tree vtable)
2093 {
2094   tree v = BINFO_VTABLE (binfo);
2095   int i;
2096   tree base_binfo;
2097   unsigned HOST_WIDE_INT this_offset;
2098
2099   if (v)
2100     {
2101       if (!vtable_pointer_value_to_vtable (v, &v, &this_offset))
2102         gcc_unreachable ();
2103
2104       if (offset == this_offset
2105           && DECL_ASSEMBLER_NAME (v) == DECL_ASSEMBLER_NAME (vtable))
2106         return binfo;
2107     }
2108   
2109   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
2110     if (polymorphic_type_binfo_p (base_binfo))
2111       {
2112         base_binfo = subbinfo_with_vtable_at_offset (base_binfo, offset, vtable);
2113         if (base_binfo)
2114           return base_binfo;
2115       }
2116   return NULL;
2117 }
2118
2119 /* T is known constant value of virtual table pointer.
2120    Store virtual table to V and its offset to OFFSET. 
2121    Return false if T does not look like virtual table reference.  */
2122
2123 bool
2124 vtable_pointer_value_to_vtable (const_tree t, tree *v,
2125                                 unsigned HOST_WIDE_INT *offset)
2126 {
2127   /* We expect &MEM[(void *)&virtual_table + 16B].
2128      We obtain object's BINFO from the context of the virtual table. 
2129      This one contains pointer to virtual table represented via
2130      POINTER_PLUS_EXPR.  Verify that this pointer matches what
2131      we propagated through.
2132
2133      In the case of virtual inheritance, the virtual tables may
2134      be nested, i.e. the offset may be different from 16 and we may
2135      need to dive into the type representation.  */
2136   if (TREE_CODE (t) == ADDR_EXPR
2137       && TREE_CODE (TREE_OPERAND (t, 0)) == MEM_REF
2138       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 0)) == ADDR_EXPR
2139       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (t, 0), 1)) == INTEGER_CST
2140       && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0))
2141           == VAR_DECL)
2142       && DECL_VIRTUAL_P (TREE_OPERAND (TREE_OPERAND
2143                                          (TREE_OPERAND (t, 0), 0), 0)))
2144     {
2145       *v = TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (t, 0), 0), 0);
2146       *offset = tree_to_uhwi (TREE_OPERAND (TREE_OPERAND (t, 0), 1));
2147       return true;
2148     }
2149
2150   /* Alternative representation, used by C++ frontend is POINTER_PLUS_EXPR.
2151      We need to handle it when T comes from static variable initializer or
2152      BINFO. */
2153   if (TREE_CODE (t) == POINTER_PLUS_EXPR)
2154     {
2155       *offset = tree_to_uhwi (TREE_OPERAND (t, 1));
2156       t = TREE_OPERAND (t, 0);
2157     }
2158   else
2159     *offset = 0;
2160
2161   if (TREE_CODE (t) != ADDR_EXPR)
2162     return false;
2163   *v = TREE_OPERAND (t, 0);
2164   return true;
2165 }
2166
2167 /* T is known constant value of virtual table pointer.  Return BINFO of the
2168    instance type.  */
2169
2170 tree
2171 vtable_pointer_value_to_binfo (const_tree t)
2172 {
2173   tree vtable;
2174   unsigned HOST_WIDE_INT offset;
2175
2176   if (!vtable_pointer_value_to_vtable (t, &vtable, &offset))
2177     return NULL_TREE;
2178
2179   /* FIXME: for stores of construction vtables we return NULL,
2180      because we do not have BINFO for those. Eventually we should fix
2181      our representation to allow this case to be handled, too.
2182      In the case we see store of BINFO we however may assume
2183      that standard folding will be able to cope with it.  */
2184   return subbinfo_with_vtable_at_offset (TYPE_BINFO (DECL_CONTEXT (vtable)),
2185                                          offset, vtable);
2186 }
2187
2188 /* Walk bases of OUTER_TYPE that contain OTR_TYPE at OFFSET.
2189    Look up their respective virtual methods for OTR_TOKEN and OTR_TYPE
2190    and insert them in NODES.
2191
2192    MATCHED_VTABLES and INSERTED is used to avoid duplicated work.  */
2193
2194 static void
2195 record_targets_from_bases (tree otr_type,
2196                            HOST_WIDE_INT otr_token,
2197                            tree outer_type,
2198                            HOST_WIDE_INT offset,
2199                            vec <cgraph_node *> &nodes,
2200                            hash_set<tree> *inserted,
2201                            hash_set<tree> *matched_vtables,
2202                            bool *completep)
2203 {
2204   while (true)
2205     {
2206       HOST_WIDE_INT pos, size;
2207       tree base_binfo;
2208       tree fld;
2209
2210       if (types_same_for_odr (outer_type, otr_type))
2211         return;
2212
2213       for (fld = TYPE_FIELDS (outer_type); fld; fld = DECL_CHAIN (fld))
2214         {
2215           if (TREE_CODE (fld) != FIELD_DECL)
2216             continue;
2217
2218           pos = int_bit_position (fld);
2219           size = tree_to_shwi (DECL_SIZE (fld));
2220           if (pos <= offset && (pos + size) > offset
2221               /* Do not get confused by zero sized bases.  */
2222               && polymorphic_type_binfo_p (TYPE_BINFO (TREE_TYPE (fld))))
2223             break;
2224         }
2225       /* Within a class type we should always find corresponding fields.  */
2226       gcc_assert (fld && TREE_CODE (TREE_TYPE (fld)) == RECORD_TYPE);
2227
2228       /* Nonbase types should have been stripped by outer_class_type.  */
2229       gcc_assert (DECL_ARTIFICIAL (fld));
2230
2231       outer_type = TREE_TYPE (fld);
2232       offset -= pos;
2233
2234       base_binfo = get_binfo_at_offset (TYPE_BINFO (outer_type),
2235                                         offset, otr_type);
2236       if (!base_binfo)
2237         {
2238           gcc_assert (odr_violation_reported);
2239           return;
2240         }
2241       gcc_assert (base_binfo);
2242       if (!matched_vtables->add (BINFO_VTABLE (base_binfo)))
2243         {
2244           bool can_refer;
2245           tree target = gimple_get_virt_method_for_binfo (otr_token,
2246                                                           base_binfo,
2247                                                           &can_refer);
2248           if (!target || ! DECL_CXX_DESTRUCTOR_P (target))
2249             maybe_record_node (nodes, target, inserted, can_refer, completep);
2250           matched_vtables->add (BINFO_VTABLE (base_binfo));
2251         }
2252     }
2253 }
2254
2255 /* When virtual table is removed, we may need to flush the cache.  */
2256
2257 static void
2258 devirt_variable_node_removal_hook (varpool_node *n,
2259                                    void *d ATTRIBUTE_UNUSED)
2260 {
2261   if (cached_polymorphic_call_targets
2262       && DECL_VIRTUAL_P (n->decl)
2263       && type_in_anonymous_namespace_p (DECL_CONTEXT (n->decl)))
2264     free_polymorphic_call_targets_hash ();
2265 }
2266
2267 /* Record about how many calls would benefit from given type to be final.  */
2268
2269 struct odr_type_warn_count
2270 {
2271   tree type;
2272   int count;
2273   gcov_type dyn_count;
2274 };
2275
2276 /* Record about how many calls would benefit from given method to be final.  */
2277
2278 struct decl_warn_count
2279 {
2280   tree decl;
2281   int count;
2282   gcov_type dyn_count;
2283 };
2284
2285 /* Information about type and decl warnings.  */
2286
2287 struct final_warning_record
2288 {
2289   gcov_type dyn_count;
2290   vec<odr_type_warn_count> type_warnings;
2291   hash_map<tree, decl_warn_count> decl_warnings;
2292 };
2293 struct final_warning_record *final_warning_records;
2294
2295 /* Return vector containing possible targets of polymorphic call of type
2296    OTR_TYPE calling method OTR_TOKEN within type of OTR_OUTER_TYPE and OFFSET.
2297    If INCLUDE_BASES is true, walk also base types of OUTER_TYPES containing
2298    OTR_TYPE and include their virtual method.  This is useful for types
2299    possibly in construction or destruction where the virtual table may
2300    temporarily change to one of base types.  INCLUDE_DERIVER_TYPES make
2301    us to walk the inheritance graph for all derivations.
2302
2303    If COMPLETEP is non-NULL, store true if the list is complete. 
2304    CACHE_TOKEN (if non-NULL) will get stored to an unique ID of entry
2305    in the target cache.  If user needs to visit every target list
2306    just once, it can memoize them.
2307
2308    If SPECULATIVE is set, the list will not contain targets that
2309    are not speculatively taken.
2310
2311    Returned vector is placed into cache.  It is NOT caller's responsibility
2312    to free it.  The vector can be freed on cgraph_remove_node call if
2313    the particular node is a virtual function present in the cache.  */
2314
2315 vec <cgraph_node *>
2316 possible_polymorphic_call_targets (tree otr_type,
2317                                    HOST_WIDE_INT otr_token,
2318                                    ipa_polymorphic_call_context context,
2319                                    bool *completep,
2320                                    void **cache_token,
2321                                    bool speculative)
2322 {
2323   static struct cgraph_node_hook_list *node_removal_hook_holder;
2324   vec <cgraph_node *> nodes = vNULL;
2325   auto_vec <tree, 8> bases_to_consider;
2326   odr_type type, outer_type;
2327   polymorphic_call_target_d key;
2328   polymorphic_call_target_d **slot;
2329   unsigned int i;
2330   tree binfo, target;
2331   bool complete;
2332   bool can_refer = false;
2333   bool skipped = false;
2334
2335   otr_type = TYPE_MAIN_VARIANT (otr_type);
2336
2337   /* If ODR is not initialized or the context is invalid, return empty
2338      incomplete list.  */
2339   if (!odr_hash || context.invalid || !TYPE_BINFO (otr_type))
2340     {
2341       if (completep)
2342         *completep = context.invalid;
2343       if (cache_token)
2344         *cache_token = NULL;
2345       return nodes;
2346     }
2347
2348   /* Do not bother to compute speculative info when user do not asks for it.  */
2349   if (!speculative || !context.speculative_outer_type)
2350     context.clear_speculation ();
2351
2352   type = get_odr_type (otr_type, true);
2353
2354   /* Recording type variants would waste results cache.  */
2355   gcc_assert (!context.outer_type
2356               || TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
2357
2358   /* Look up the outer class type we want to walk.
2359      If we fail to do so, the context is invalid.  */
2360   if ((context.outer_type || context.speculative_outer_type)
2361       && !context.restrict_to_inner_class (otr_type))
2362     {
2363       if (completep)
2364         *completep = true;
2365       if (cache_token)
2366         *cache_token = NULL;
2367       return nodes;
2368     }
2369   gcc_assert (!context.invalid);
2370
2371   /* Check that restrict_to_inner_class kept the main variant.  */
2372   gcc_assert (!context.outer_type
2373               || TYPE_MAIN_VARIANT (context.outer_type) == context.outer_type);
2374
2375   /* We canonicalize our query, so we do not need extra hashtable entries.  */
2376
2377   /* Without outer type, we have no use for offset.  Just do the
2378      basic search from inner type.  */
2379   if (!context.outer_type)
2380     context.clear_outer_type (otr_type);
2381   /* We need to update our hierarchy if the type does not exist.  */
2382   outer_type = get_odr_type (context.outer_type, true);
2383   /* If the type is complete, there are no derivations.  */
2384   if (TYPE_FINAL_P (outer_type->type))
2385     context.maybe_derived_type = false;
2386
2387   /* Initialize query cache.  */
2388   if (!cached_polymorphic_call_targets)
2389     {
2390       cached_polymorphic_call_targets = new hash_set<cgraph_node *>;
2391       polymorphic_call_target_hash
2392         = new polymorphic_call_target_hash_type (23);
2393       if (!node_removal_hook_holder)
2394         {
2395           node_removal_hook_holder =
2396             symtab->add_cgraph_removal_hook (&devirt_node_removal_hook, NULL);
2397           symtab->add_varpool_removal_hook (&devirt_variable_node_removal_hook,
2398                                          NULL);
2399         }
2400     }
2401
2402   if (in_lto_p)
2403     {
2404       if (context.outer_type != otr_type)
2405         context.outer_type
2406           = get_odr_type (context.outer_type, true)->type;
2407       if (context.speculative_outer_type)
2408         context.speculative_outer_type
2409           = get_odr_type (context.speculative_outer_type, true)->type;
2410     }
2411
2412   /* Look up cached answer.  */
2413   key.type = type;
2414   key.otr_token = otr_token;
2415   key.speculative = speculative;
2416   key.context = context;
2417   slot = polymorphic_call_target_hash->find_slot (&key, INSERT);
2418   if (cache_token)
2419    *cache_token = (void *)*slot;
2420   if (*slot)
2421     {
2422       if (completep)
2423         *completep = (*slot)->complete;
2424       if ((*slot)->type_warning && final_warning_records)
2425         {
2426           final_warning_records->type_warnings[(*slot)->type_warning - 1].count++;
2427           final_warning_records->type_warnings[(*slot)->type_warning - 1].dyn_count
2428             += final_warning_records->dyn_count;
2429         }
2430       if (!speculative && (*slot)->decl_warning && final_warning_records)
2431         {
2432           struct decl_warn_count *c =
2433              final_warning_records->decl_warnings.get ((*slot)->decl_warning);
2434           c->count++;
2435           c->dyn_count += final_warning_records->dyn_count;
2436         }
2437       return (*slot)->targets;
2438     }
2439
2440   complete = true;
2441
2442   /* Do actual search.  */
2443   timevar_push (TV_IPA_VIRTUAL_CALL);
2444   *slot = XCNEW (polymorphic_call_target_d);
2445   if (cache_token)
2446     *cache_token = (void *)*slot;
2447   (*slot)->type = type;
2448   (*slot)->otr_token = otr_token;
2449   (*slot)->context = context;
2450   (*slot)->speculative = speculative;
2451
2452   hash_set<tree> inserted;
2453   hash_set<tree> matched_vtables;
2454
2455   /* First insert targets we speculatively identified as likely.  */
2456   if (context.speculative_outer_type)
2457     {
2458       odr_type speculative_outer_type;
2459       bool speculation_complete = true;
2460
2461       /* First insert target from type itself and check if it may have
2462          derived types.  */
2463       speculative_outer_type = get_odr_type (context.speculative_outer_type, true);
2464       if (TYPE_FINAL_P (speculative_outer_type->type))
2465         context.speculative_maybe_derived_type = false;
2466       binfo = get_binfo_at_offset (TYPE_BINFO (speculative_outer_type->type),
2467                                    context.speculative_offset, otr_type);
2468       if (binfo)
2469         target = gimple_get_virt_method_for_binfo (otr_token, binfo,
2470                                                    &can_refer);
2471       else
2472         target = NULL;
2473
2474       /* In the case we get complete method, we don't need 
2475          to walk derivations.  */
2476       if (target && DECL_FINAL_P (target))
2477         context.speculative_maybe_derived_type = false;
2478       if (type_possibly_instantiated_p (speculative_outer_type->type))
2479         maybe_record_node (nodes, target, &inserted, can_refer, &speculation_complete);
2480       if (binfo)
2481         matched_vtables.add (BINFO_VTABLE (binfo));
2482
2483
2484       /* Next walk recursively all derived types.  */
2485       if (context.speculative_maybe_derived_type)
2486         for (i = 0; i < speculative_outer_type->derived_types.length(); i++)
2487           possible_polymorphic_call_targets_1 (nodes, &inserted,
2488                                                &matched_vtables,
2489                                                otr_type,
2490                                                speculative_outer_type->derived_types[i],
2491                                                otr_token, speculative_outer_type->type,
2492                                                context.speculative_offset,
2493                                                &speculation_complete,
2494                                                bases_to_consider,
2495                                                false);
2496     }
2497
2498   if (!speculative || !nodes.length ())
2499     {
2500       /* First see virtual method of type itself.  */
2501       binfo = get_binfo_at_offset (TYPE_BINFO (outer_type->type),
2502                                    context.offset, otr_type);
2503       if (binfo)
2504         target = gimple_get_virt_method_for_binfo (otr_token, binfo,
2505                                                    &can_refer);
2506       else
2507         {
2508           gcc_assert (odr_violation_reported);
2509           target = NULL;
2510         }
2511
2512       /* Destructors are never called through construction virtual tables,
2513          because the type is always known.  */
2514       if (target && DECL_CXX_DESTRUCTOR_P (target))
2515         context.maybe_in_construction = false;
2516
2517       if (target)
2518         {
2519           /* In the case we get complete method, we don't need 
2520              to walk derivations.  */
2521           if (DECL_FINAL_P (target))
2522             context.maybe_derived_type = false;
2523         }
2524
2525       /* If OUTER_TYPE is abstract, we know we are not seeing its instance.  */
2526       if (type_possibly_instantiated_p (outer_type->type))
2527         maybe_record_node (nodes, target, &inserted, can_refer, &complete);
2528       else
2529         skipped = true;
2530
2531       if (binfo)
2532         matched_vtables.add (BINFO_VTABLE (binfo));
2533
2534       /* Next walk recursively all derived types.  */
2535       if (context.maybe_derived_type)
2536         {
2537           for (i = 0; i < outer_type->derived_types.length(); i++)
2538             possible_polymorphic_call_targets_1 (nodes, &inserted,
2539                                                  &matched_vtables,
2540                                                  otr_type,
2541                                                  outer_type->derived_types[i],
2542                                                  otr_token, outer_type->type,
2543                                                  context.offset, &complete,
2544                                                  bases_to_consider,
2545                                                  context.maybe_in_construction);
2546
2547           if (!outer_type->all_derivations_known)
2548             {
2549               if (!speculative && final_warning_records)
2550                 {
2551                   if (complete
2552                       && nodes.length () == 1
2553                       && warn_suggest_final_types
2554                       && !outer_type->derived_types.length ())
2555                     {
2556                       if (outer_type->id >= (int)final_warning_records->type_warnings.length ())
2557                         final_warning_records->type_warnings.safe_grow_cleared
2558                           (odr_types.length ());
2559                       final_warning_records->type_warnings[outer_type->id].count++;
2560                       final_warning_records->type_warnings[outer_type->id].dyn_count
2561                         += final_warning_records->dyn_count;
2562                       final_warning_records->type_warnings[outer_type->id].type
2563                         = outer_type->type;
2564                       (*slot)->type_warning = outer_type->id + 1;
2565                     }
2566                   if (complete
2567                       && warn_suggest_final_methods
2568                       && nodes.length () == 1
2569                       && types_same_for_odr (DECL_CONTEXT (nodes[0]->decl),
2570                                              outer_type->type))
2571                     {
2572                       bool existed;
2573                       struct decl_warn_count &c =
2574                          final_warning_records->decl_warnings.get_or_insert
2575                             (nodes[0]->decl, &existed);
2576
2577                       if (existed)
2578                         {
2579                           c.count++;
2580                           c.dyn_count += final_warning_records->dyn_count;
2581                         }
2582                       else
2583                         {
2584                           c.count = 1;
2585                           c.dyn_count = final_warning_records->dyn_count;
2586                           c.decl = nodes[0]->decl;
2587                         }
2588                       (*slot)->decl_warning = nodes[0]->decl;
2589                     }
2590                 }
2591               complete = false;
2592             }
2593         }
2594
2595       if (!speculative)
2596         {
2597           /* Destructors are never called through construction virtual tables,
2598              because the type is always known.  One of entries may be
2599              cxa_pure_virtual so look to at least two of them.  */
2600           if (context.maybe_in_construction)
2601             for (i =0 ; i < MIN (nodes.length (), 2); i++)
2602               if (DECL_CXX_DESTRUCTOR_P (nodes[i]->decl))
2603                 context.maybe_in_construction = false;
2604           if (context.maybe_in_construction)
2605             {
2606               if (type != outer_type
2607                   && (!skipped
2608                       || (context.maybe_derived_type
2609                           && !type_all_derivations_known_p (outer_type->type))))
2610                 record_targets_from_bases (otr_type, otr_token, outer_type->type,
2611                                            context.offset, nodes, &inserted,
2612                                            &matched_vtables, &complete);
2613               if (skipped)
2614                 maybe_record_node (nodes, target, &inserted, can_refer, &complete);
2615               for (i = 0; i < bases_to_consider.length(); i++)
2616                 maybe_record_node (nodes, bases_to_consider[i], &inserted, can_refer, &complete);
2617             }
2618         }
2619     }
2620
2621   (*slot)->targets = nodes;
2622   (*slot)->complete = complete;
2623   if (completep)
2624     *completep = complete;
2625
2626   timevar_pop (TV_IPA_VIRTUAL_CALL);
2627   return nodes;
2628 }
2629
2630 bool
2631 add_decl_warning (const tree &key ATTRIBUTE_UNUSED, const decl_warn_count &value,
2632                   vec<const decl_warn_count*> *vec)
2633 {
2634   vec->safe_push (&value);
2635   return true;
2636 }
2637
2638 /* Dump target list TARGETS into FILE.  */
2639
2640 static void
2641 dump_targets (FILE *f, vec <cgraph_node *> targets)
2642 {
2643   unsigned int i;
2644
2645   for (i = 0; i < targets.length (); i++)
2646     {
2647       char *name = NULL;
2648       if (in_lto_p)
2649         name = cplus_demangle_v3 (targets[i]->asm_name (), 0);
2650       fprintf (f, " %s/%i", name ? name : targets[i]->name (), targets[i]->order);
2651       if (in_lto_p)
2652         free (name);
2653       if (!targets[i]->definition)
2654         fprintf (f, " (no definition%s)",
2655                  DECL_DECLARED_INLINE_P (targets[i]->decl)
2656                  ? " inline" : "");
2657     }
2658   fprintf (f, "\n");
2659 }
2660
2661 /* Dump all possible targets of a polymorphic call.  */
2662
2663 void
2664 dump_possible_polymorphic_call_targets (FILE *f,
2665                                         tree otr_type,
2666                                         HOST_WIDE_INT otr_token,
2667                                         const ipa_polymorphic_call_context &ctx)
2668 {
2669   vec <cgraph_node *> targets;
2670   bool final;
2671   odr_type type = get_odr_type (TYPE_MAIN_VARIANT (otr_type), false);
2672   unsigned int len;
2673
2674   if (!type)
2675     return;
2676   targets = possible_polymorphic_call_targets (otr_type, otr_token,
2677                                                ctx,
2678                                                &final, NULL, false);
2679   fprintf (f, "  Targets of polymorphic call of type %i:", type->id);
2680   print_generic_expr (f, type->type, TDF_SLIM);
2681   fprintf (f, " token %i\n", (int)otr_token);
2682
2683   ctx.dump (f);
2684
2685   fprintf (f, "    %s%s%s%s\n      ",
2686            final ? "This is a complete list." :
2687            "This is partial list; extra targets may be defined in other units.",
2688            ctx.maybe_in_construction ? " (base types included)" : "",
2689            ctx.maybe_derived_type ? " (derived types included)" : "",
2690            ctx.speculative_maybe_derived_type ? " (speculative derived types included)" : "");
2691   len = targets.length ();
2692   dump_targets (f, targets);
2693
2694   targets = possible_polymorphic_call_targets (otr_type, otr_token,
2695                                                ctx,
2696                                                &final, NULL, true);
2697   gcc_assert (targets.length () <= len);
2698   if (targets.length () != len)
2699     {
2700       fprintf (f, "  Speculative targets:");
2701       dump_targets (f, targets);
2702     }
2703   fprintf (f, "\n");
2704 }
2705
2706
2707 /* Return true if N can be possibly target of a polymorphic call of
2708    OTR_TYPE/OTR_TOKEN.  */
2709
2710 bool
2711 possible_polymorphic_call_target_p (tree otr_type,
2712                                     HOST_WIDE_INT otr_token,
2713                                     const ipa_polymorphic_call_context &ctx,
2714                                     struct cgraph_node *n)
2715 {
2716   vec <cgraph_node *> targets;
2717   unsigned int i;
2718   enum built_in_function fcode;
2719   bool final;
2720
2721   if (TREE_CODE (TREE_TYPE (n->decl)) == FUNCTION_TYPE
2722       && ((fcode = DECL_FUNCTION_CODE (n->decl))
2723           == BUILT_IN_UNREACHABLE
2724           || fcode == BUILT_IN_TRAP))
2725     return true;
2726
2727   if (!odr_hash)
2728     return true;
2729   targets = possible_polymorphic_call_targets (otr_type, otr_token, ctx, &final);
2730   for (i = 0; i < targets.length (); i++)
2731     if (n->semantically_equivalent_p (targets[i]))
2732       return true;
2733
2734   /* At a moment we allow middle end to dig out new external declarations
2735      as a targets of polymorphic calls.  */
2736   if (!final && !n->definition)
2737     return true;
2738   return false;
2739 }
2740
2741
2742
2743 /* Return true if N can be possibly target of a polymorphic call of
2744    OBJ_TYPE_REF expression REF in STMT.  */
2745
2746 bool
2747 possible_polymorphic_call_target_p (tree ref,
2748                                     gimple stmt,
2749                                     struct cgraph_node *n)
2750 {
2751   ipa_polymorphic_call_context context (current_function_decl, ref, stmt);
2752   tree call_fn = gimple_call_fn (stmt);
2753
2754   return possible_polymorphic_call_target_p (obj_type_ref_class (call_fn),
2755                                              tree_to_uhwi
2756                                                (OBJ_TYPE_REF_TOKEN (call_fn)),
2757                                              context,
2758                                              n);
2759 }
2760
2761
2762 /* After callgraph construction new external nodes may appear.
2763    Add them into the graph.  */
2764
2765 void
2766 update_type_inheritance_graph (void)
2767 {
2768   struct cgraph_node *n;
2769
2770   if (!odr_hash)
2771     return;
2772   free_polymorphic_call_targets_hash ();
2773   timevar_push (TV_IPA_INHERITANCE);
2774   /* We reconstruct the graph starting from types of all methods seen in the
2775      the unit.  */
2776   FOR_EACH_FUNCTION (n)
2777     if (DECL_VIRTUAL_P (n->decl)
2778         && !n->definition
2779         && n->real_symbol_p ())
2780       get_odr_type (method_class_type (TYPE_MAIN_VARIANT (TREE_TYPE (n->decl))),
2781                                        true);
2782   timevar_pop (TV_IPA_INHERITANCE);
2783 }
2784
2785
2786 /* Return true if N looks like likely target of a polymorphic call.
2787    Rule out cxa_pure_virtual, noreturns, function declared cold and
2788    other obvious cases.  */
2789
2790 bool
2791 likely_target_p (struct cgraph_node *n)
2792 {
2793   int flags;
2794   /* cxa_pure_virtual and similar things are not likely.  */
2795   if (TREE_CODE (TREE_TYPE (n->decl)) != METHOD_TYPE)
2796     return false;
2797   flags = flags_from_decl_or_type (n->decl);
2798   if (flags & ECF_NORETURN)
2799     return false;
2800   if (lookup_attribute ("cold",
2801                         DECL_ATTRIBUTES (n->decl)))
2802     return false;
2803   if (n->frequency < NODE_FREQUENCY_NORMAL)
2804     return false;
2805   /* If there are no live virtual tables referring the target,
2806      the only way the target can be called is an instance coming from other
2807      compilation unit; speculative devirtualization is built around an
2808      assumption that won't happen.  */
2809   if (!referenced_from_vtable_p (n))
2810     return false;
2811   return true;
2812 }
2813
2814 /* Compare type warning records P1 and P2 and choose one with larger count;
2815    helper for qsort.  */
2816
2817 int
2818 type_warning_cmp (const void *p1, const void *p2)
2819 {
2820   const odr_type_warn_count *t1 = (const odr_type_warn_count *)p1;
2821   const odr_type_warn_count *t2 = (const odr_type_warn_count *)p2;
2822
2823   if (t1->dyn_count < t2->dyn_count)
2824    return 1;
2825   if (t1->dyn_count > t2->dyn_count)
2826    return -1;
2827   return t2->count - t1->count;
2828 }
2829
2830 /* Compare decl warning records P1 and P2 and choose one with larger count;
2831    helper for qsort.  */
2832
2833 int
2834 decl_warning_cmp (const void *p1, const void *p2)
2835 {
2836   const decl_warn_count *t1 = *(const decl_warn_count * const *)p1;
2837   const decl_warn_count *t2 = *(const decl_warn_count * const *)p2;
2838
2839   if (t1->dyn_count < t2->dyn_count)
2840    return 1;
2841   if (t1->dyn_count > t2->dyn_count)
2842    return -1;
2843   return t2->count - t1->count;
2844 }
2845
2846
2847 /* Try to speculatively devirtualize call to OTR_TYPE with OTR_TOKEN with
2848    context CTX.  */
2849
2850 struct cgraph_node *
2851 try_speculative_devirtualization (tree otr_type, HOST_WIDE_INT otr_token,
2852                                   ipa_polymorphic_call_context ctx)
2853 {
2854   vec <cgraph_node *>targets
2855      = possible_polymorphic_call_targets
2856           (otr_type, otr_token, ctx, NULL, NULL, true);
2857   unsigned int i;
2858   struct cgraph_node *likely_target = NULL;
2859
2860   for (i = 0; i < targets.length (); i++)
2861     if (likely_target_p (targets[i]))
2862       {
2863         if (likely_target)
2864           return NULL;
2865         likely_target = targets[i];
2866       }
2867   if (!likely_target
2868       ||!likely_target->definition
2869       || DECL_EXTERNAL (likely_target->decl))
2870     return NULL;
2871
2872   /* Don't use an implicitly-declared destructor (c++/58678).  */
2873   struct cgraph_node *non_thunk_target
2874     = likely_target->function_symbol ();
2875   if (DECL_ARTIFICIAL (non_thunk_target->decl))
2876     return NULL;
2877   if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
2878       && likely_target->can_be_discarded_p ())
2879     return NULL;
2880   return likely_target;
2881 }
2882
2883 /* The ipa-devirt pass.
2884    When polymorphic call has only one likely target in the unit,
2885    turn it into a speculative call.  */
2886
2887 static unsigned int
2888 ipa_devirt (void)
2889 {
2890   struct cgraph_node *n;
2891   hash_set<void *> bad_call_targets;
2892   struct cgraph_edge *e;
2893
2894   int npolymorphic = 0, nspeculated = 0, nconverted = 0, ncold = 0;
2895   int nmultiple = 0, noverwritable = 0, ndevirtualized = 0, nnotdefined = 0;
2896   int nwrong = 0, nok = 0, nexternal = 0, nartificial = 0;
2897   int ndropped = 0;
2898
2899   if (!odr_types_ptr)
2900     return 0;
2901
2902   /* We can output -Wsuggest-final-methods and -Wsuggest-final-types warnings.
2903      This is implemented by setting up final_warning_records that are updated
2904      by get_polymorphic_call_targets.
2905      We need to clear cache in this case to trigger recomputation of all
2906      entries.  */
2907   if (warn_suggest_final_methods || warn_suggest_final_types)
2908     {
2909       final_warning_records = new (final_warning_record);
2910       final_warning_records->type_warnings = vNULL;
2911       final_warning_records->type_warnings.safe_grow_cleared (odr_types.length ());
2912       free_polymorphic_call_targets_hash ();
2913     }
2914
2915   FOR_EACH_DEFINED_FUNCTION (n)
2916     {   
2917       bool update = false;
2918       if (!opt_for_fn (n->decl, flag_devirtualize))
2919         continue;
2920       if (dump_file && n->indirect_calls)
2921         fprintf (dump_file, "\n\nProcesing function %s/%i\n",
2922                  n->name (), n->order);
2923       for (e = n->indirect_calls; e; e = e->next_callee)
2924         if (e->indirect_info->polymorphic)
2925           {
2926             struct cgraph_node *likely_target = NULL;
2927             void *cache_token;
2928             bool final;
2929
2930             if (final_warning_records)
2931               final_warning_records->dyn_count = e->count;
2932
2933             vec <cgraph_node *>targets
2934                = possible_polymorphic_call_targets
2935                     (e, &final, &cache_token, true);
2936             unsigned int i;
2937
2938             /* Trigger warnings by calculating non-speculative targets.  */
2939             if (warn_suggest_final_methods || warn_suggest_final_types)
2940               possible_polymorphic_call_targets (e);
2941
2942             if (dump_file)
2943               dump_possible_polymorphic_call_targets 
2944                 (dump_file, e);
2945
2946             npolymorphic++;
2947
2948             /* See if the call can be devirtualized by means of ipa-prop's
2949                polymorphic call context propagation.  If not, we can just
2950                forget about this call being polymorphic and avoid some heavy
2951                lifting in remove_unreachable_nodes that will otherwise try to
2952                keep all possible targets alive until inlining and in the inliner
2953                itself.
2954
2955                This may need to be revisited once we add further ways to use
2956                the may edges, but it is a resonable thing to do right now.  */
2957
2958             if ((e->indirect_info->param_index == -1
2959                 || (!opt_for_fn (n->decl, flag_devirtualize_speculatively)
2960                     && e->indirect_info->vptr_changed))
2961                 && !flag_ltrans_devirtualize)
2962               {
2963                 e->indirect_info->polymorphic = false;
2964                 ndropped++;
2965                 if (dump_file)
2966                   fprintf (dump_file, "Dropping polymorphic call info;"
2967                            " it can not be used by ipa-prop\n");
2968               }
2969
2970             if (!opt_for_fn (n->decl, flag_devirtualize_speculatively))
2971               continue;
2972
2973             if (!e->maybe_hot_p ())
2974               {
2975                 if (dump_file)
2976                   fprintf (dump_file, "Call is cold\n\n");
2977                 ncold++;
2978                 continue;
2979               }
2980             if (e->speculative)
2981               {
2982                 if (dump_file)
2983                   fprintf (dump_file, "Call is already speculated\n\n");
2984                 nspeculated++;
2985
2986                 /* When dumping see if we agree with speculation.  */
2987                 if (!dump_file)
2988                   continue;
2989               }
2990             if (bad_call_targets.contains (cache_token))
2991               {
2992                 if (dump_file)
2993                   fprintf (dump_file, "Target list is known to be useless\n\n");
2994                 nmultiple++;
2995                 continue;
2996               }
2997             for (i = 0; i < targets.length (); i++)
2998               if (likely_target_p (targets[i]))
2999                 {
3000                   if (likely_target)
3001                     {
3002                       likely_target = NULL;
3003                       if (dump_file)
3004                         fprintf (dump_file, "More than one likely target\n\n");
3005                       nmultiple++;
3006                       break;
3007                     }
3008                   likely_target = targets[i];
3009                 }
3010             if (!likely_target)
3011               {
3012                 bad_call_targets.add (cache_token);
3013                 continue;
3014               }
3015             /* This is reached only when dumping; check if we agree or disagree
3016                with the speculation.  */
3017             if (e->speculative)
3018               {
3019                 struct cgraph_edge *e2;
3020                 struct ipa_ref *ref;
3021                 e->speculative_call_info (e2, e, ref);
3022                 if (e2->callee->ultimate_alias_target ()
3023                     == likely_target->ultimate_alias_target ())
3024                   {
3025                     fprintf (dump_file, "We agree with speculation\n\n");
3026                     nok++;
3027                   }
3028                 else
3029                   {
3030                     fprintf (dump_file, "We disagree with speculation\n\n");
3031                     nwrong++;
3032                   }
3033                 continue;
3034               }
3035             if (!likely_target->definition)
3036               {
3037                 if (dump_file)
3038                   fprintf (dump_file, "Target is not a definition\n\n");
3039                 nnotdefined++;
3040                 continue;
3041               }
3042             /* Do not introduce new references to external symbols.  While we
3043                can handle these just well, it is common for programs to
3044                incorrectly with headers defining methods they are linked
3045                with.  */
3046             if (DECL_EXTERNAL (likely_target->decl))
3047               {
3048                 if (dump_file)
3049                   fprintf (dump_file, "Target is external\n\n");
3050                 nexternal++;
3051                 continue;
3052               }
3053             /* Don't use an implicitly-declared destructor (c++/58678).  */
3054             struct cgraph_node *non_thunk_target
3055               = likely_target->function_symbol ();
3056             if (DECL_ARTIFICIAL (non_thunk_target->decl))
3057               {
3058                 if (dump_file)
3059                   fprintf (dump_file, "Target is artificial\n\n");
3060                 nartificial++;
3061                 continue;
3062               }
3063             if (likely_target->get_availability () <= AVAIL_INTERPOSABLE
3064                 && likely_target->can_be_discarded_p ())
3065               {
3066                 if (dump_file)
3067                   fprintf (dump_file, "Target is overwritable\n\n");
3068                 noverwritable++;
3069                 continue;
3070               }
3071             else if (dbg_cnt (devirt))
3072               {
3073                 if (dump_enabled_p ())
3074                   {
3075                     location_t locus = gimple_location_safe (e->call_stmt);
3076                     dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, locus,
3077                                      "speculatively devirtualizing call in %s/%i to %s/%i\n",
3078                                      n->name (), n->order,
3079                                      likely_target->name (),
3080                                      likely_target->order);
3081                   }
3082                 if (!likely_target->can_be_discarded_p ())
3083                   {
3084                     cgraph_node *alias;
3085                     alias = dyn_cast<cgraph_node *> (likely_target->noninterposable_alias ());
3086                     if (alias)
3087                       likely_target = alias;
3088                   }
3089                 nconverted++;
3090                 update = true;
3091                 e->make_speculative
3092                   (likely_target, e->count * 8 / 10, e->frequency * 8 / 10);
3093               }
3094           }
3095       if (update)
3096         inline_update_overall_summary (n);
3097     }
3098   if (warn_suggest_final_methods || warn_suggest_final_types)
3099     {
3100       if (warn_suggest_final_types)
3101         {
3102           final_warning_records->type_warnings.qsort (type_warning_cmp);
3103           for (unsigned int i = 0;
3104                i < final_warning_records->type_warnings.length (); i++)
3105             if (final_warning_records->type_warnings[i].count)
3106               {
3107                 tree type = final_warning_records->type_warnings[i].type;
3108                 int count = final_warning_records->type_warnings[i].count;
3109                 long long dyn_count
3110                   = final_warning_records->type_warnings[i].dyn_count;
3111
3112                 if (!dyn_count)
3113                   warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
3114                              OPT_Wsuggest_final_types, count,
3115                              "Declaring type %qD final "
3116                              "would enable devirtualization of %i call",
3117                              "Declaring type %qD final "
3118                              "would enable devirtualization of %i calls",
3119                              type,
3120                              count);
3121                 else
3122                   warning_n (DECL_SOURCE_LOCATION (TYPE_NAME (type)),
3123                              OPT_Wsuggest_final_types, count,
3124                              "Declaring type %qD final "
3125                              "would enable devirtualization of %i call "
3126                              "executed %lli times",
3127                              "Declaring type %qD final "
3128                              "would enable devirtualization of %i calls "
3129                              "executed %lli times",
3130                              type,
3131                              count,
3132                              dyn_count);
3133               }
3134         }
3135
3136       if (warn_suggest_final_methods)
3137         {
3138           vec<const decl_warn_count*> decl_warnings_vec = vNULL;
3139
3140           final_warning_records->decl_warnings.traverse
3141             <vec<const decl_warn_count *> *, add_decl_warning> (&decl_warnings_vec);
3142           decl_warnings_vec.qsort (decl_warning_cmp);
3143           for (unsigned int i = 0; i < decl_warnings_vec.length (); i++)
3144             {
3145               tree decl = decl_warnings_vec[i]->decl;
3146               int count = decl_warnings_vec[i]->count;
3147               long long dyn_count = decl_warnings_vec[i]->dyn_count;
3148
3149               if (!dyn_count)
3150                 if (DECL_CXX_DESTRUCTOR_P (decl))
3151                   warning_n (DECL_SOURCE_LOCATION (decl),
3152                               OPT_Wsuggest_final_methods, count,
3153                               "Declaring virtual destructor of %qD final "
3154                               "would enable devirtualization of %i call",
3155                               "Declaring virtual destructor of %qD final "
3156                               "would enable devirtualization of %i calls",
3157                               DECL_CONTEXT (decl), count);
3158                 else
3159                   warning_n (DECL_SOURCE_LOCATION (decl),
3160                               OPT_Wsuggest_final_methods, count,
3161                               "Declaring method %qD final "
3162                               "would enable devirtualization of %i call",
3163                               "Declaring method %qD final "
3164                               "would enable devirtualization of %i calls",
3165                               decl, count);
3166                else if (DECL_CXX_DESTRUCTOR_P (decl))
3167                   warning_n (DECL_SOURCE_LOCATION (decl),
3168                               OPT_Wsuggest_final_methods, count,
3169                               "Declaring virtual destructor of %qD final "
3170                               "would enable devirtualization of %i call "
3171                               "executed %lli times",
3172                               "Declaring virtual destructor of %qD final "
3173                               "would enable devirtualization of %i calls "
3174                               "executed %lli times",
3175                               DECL_CONTEXT (decl), count, dyn_count);
3176                 else
3177                   warning_n (DECL_SOURCE_LOCATION (decl),
3178                               OPT_Wsuggest_final_methods, count,
3179                               "Declaring method %qD final "
3180                               "would enable devirtualization of %i call "
3181                               "executed %lli times",
3182                               "Declaring method %qD final "
3183                               "would enable devirtualization of %i calls "
3184                               "executed %lli times",
3185                               decl, count, dyn_count);
3186             }
3187         }
3188         
3189       delete (final_warning_records);
3190       final_warning_records = 0;
3191     }
3192
3193   if (dump_file)
3194     fprintf (dump_file,
3195              "%i polymorphic calls, %i devirtualized,"
3196              " %i speculatively devirtualized, %i cold\n"
3197              "%i have multiple targets, %i overwritable,"
3198              " %i already speculated (%i agree, %i disagree),"
3199              " %i external, %i not defined, %i artificial, %i infos dropped\n",
3200              npolymorphic, ndevirtualized, nconverted, ncold,
3201              nmultiple, noverwritable, nspeculated, nok, nwrong,
3202              nexternal, nnotdefined, nartificial, ndropped);
3203   return ndevirtualized || ndropped ? TODO_remove_functions : 0;
3204 }
3205
3206 namespace {
3207
3208 const pass_data pass_data_ipa_devirt =
3209 {
3210   IPA_PASS, /* type */
3211   "devirt", /* name */
3212   OPTGROUP_NONE, /* optinfo_flags */
3213   TV_IPA_DEVIRT, /* tv_id */
3214   0, /* properties_required */
3215   0, /* properties_provided */
3216   0, /* properties_destroyed */
3217   0, /* todo_flags_start */
3218   ( TODO_dump_symtab ), /* todo_flags_finish */
3219 };
3220
3221 class pass_ipa_devirt : public ipa_opt_pass_d
3222 {
3223 public:
3224   pass_ipa_devirt (gcc::context *ctxt)
3225     : ipa_opt_pass_d (pass_data_ipa_devirt, ctxt,
3226                       NULL, /* generate_summary */
3227                       NULL, /* write_summary */
3228                       NULL, /* read_summary */
3229                       NULL, /* write_optimization_summary */
3230                       NULL, /* read_optimization_summary */
3231                       NULL, /* stmt_fixup */
3232                       0, /* function_transform_todo_flags_start */
3233                       NULL, /* function_transform */
3234                       NULL) /* variable_transform */
3235   {}
3236
3237   /* opt_pass methods: */
3238   virtual bool gate (function *)
3239     {
3240       /* In LTO, always run the IPA passes and decide on function basis if the
3241          pass is enabled.  */
3242       if (in_lto_p)
3243         return true;
3244       return (flag_devirtualize
3245               && (flag_devirtualize_speculatively
3246                   || (warn_suggest_final_methods
3247                       || warn_suggest_final_types))
3248               && optimize);
3249     }
3250
3251   virtual unsigned int execute (function *) { return ipa_devirt (); }
3252
3253 }; // class pass_ipa_devirt
3254
3255 } // anon namespace
3256
3257 ipa_opt_pass_d *
3258 make_pass_ipa_devirt (gcc::context *ctxt)
3259 {
3260   return new pass_ipa_devirt (ctxt);
3261 }
3262
3263 #include "gt-ipa-devirt.h"