Update gcc-50 to SVN version 221572
[dragonfly.git] / contrib / gcc-5.0 / gcc / ipa-polymorphic-call.c
1 /* Analysis of polymorphic call context.
2    Copyright (C) 2013-2015 Free Software Foundation, Inc.
3    Contributed by Jan Hubicka
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "hash-set.h"
26 #include "machmode.h"
27 #include "vec.h"
28 #include "double-int.h"
29 #include "input.h"
30 #include "alias.h"
31 #include "symtab.h"
32 #include "wide-int.h"
33 #include "inchash.h"
34 #include "tree.h"
35 #include "fold-const.h"
36 #include "print-tree.h"
37 #include "calls.h"
38 #include "hashtab.h"
39 #include "hard-reg-set.h"
40 #include "function.h"
41 #include "rtl.h"
42 #include "flags.h"
43 #include "statistics.h"
44 #include "real.h"
45 #include "fixed-value.h"
46 #include "insn-config.h"
47 #include "expmed.h"
48 #include "dojump.h"
49 #include "explow.h"
50 #include "emit-rtl.h"
51 #include "varasm.h"
52 #include "stmt.h"
53 #include "expr.h"
54 #include "tree-pass.h"
55 #include "target.h"
56 #include "tree-pretty-print.h"
57 #include "predict.h"
58 #include "basic-block.h"
59 #include "hash-map.h"
60 #include "is-a.h"
61 #include "plugin-api.h"
62 #include "ipa-ref.h"
63 #include "cgraph.h"
64 #include "ipa-utils.h"
65 #include "tree-ssa-alias.h"
66 #include "internal-fn.h"
67 #include "gimple-fold.h"
68 #include "gimple-expr.h"
69 #include "gimple.h"
70 #include "alloc-pool.h"
71 #include "symbol-summary.h"
72 #include "ipa-prop.h"
73 #include "ipa-inline.h"
74 #include "diagnostic.h"
75 #include "tree-dfa.h"
76 #include "demangle.h"
77 #include "dbgcnt.h"
78 #include "gimple-pretty-print.h"
79 #include "stor-layout.h"
80 #include "intl.h"
81 #include "data-streamer.h"
82 #include "lto-streamer.h"
83 #include "streamer-hooks.h"
84 #include "tree-ssa-operands.h"
85 #include "tree-into-ssa.h"
86
87 /* Return true when TYPE contains an polymorphic type and thus is interesting
88    for devirtualization machinery.  */
89
90 static bool contains_type_p (tree, HOST_WIDE_INT, tree,
91                              bool consider_placement_new = true,
92                              bool consider_bases = true);
93
94 bool
95 contains_polymorphic_type_p (const_tree type)
96 {
97   type = TYPE_MAIN_VARIANT (type);
98
99   if (RECORD_OR_UNION_TYPE_P (type))
100     {
101       if (TYPE_BINFO (type)
102           && polymorphic_type_binfo_p (TYPE_BINFO (type)))
103         return true;
104       for (tree fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
105         if (TREE_CODE (fld) == FIELD_DECL
106             && !DECL_ARTIFICIAL (fld)
107             && contains_polymorphic_type_p (TREE_TYPE (fld)))
108           return true;
109       return false;
110     }
111   if (TREE_CODE (type) == ARRAY_TYPE)
112     return contains_polymorphic_type_p (TREE_TYPE (type));
113   return false;
114 }
115
116 /* Return true if it seems valid to use placement new to build EXPECTED_TYPE
117    at possition CUR_OFFSET within TYPE.  
118
119    POD can be changed to an instance of a polymorphic type by
120    placement new.  Here we play safe and assume that any
121    non-polymorphic type is POD.  */
122 bool
123 possible_placement_new (tree type, tree expected_type,
124                         HOST_WIDE_INT cur_offset)
125 {
126   return ((TREE_CODE (type) != RECORD_TYPE
127            || !TYPE_BINFO (type)
128            || cur_offset >= POINTER_SIZE
129            || !polymorphic_type_binfo_p (TYPE_BINFO (type)))
130           && (!TYPE_SIZE (type)
131               || !tree_fits_shwi_p (TYPE_SIZE (type))
132               || (cur_offset
133                   + (expected_type ? tree_to_uhwi (TYPE_SIZE (expected_type))
134                      : POINTER_SIZE)
135                   <= tree_to_uhwi (TYPE_SIZE (type)))));
136 }
137
138 /* THIS->OUTER_TYPE is a type of memory object where object of OTR_TYPE
139    is contained at THIS->OFFSET.  Walk the memory representation of
140    THIS->OUTER_TYPE and find the outermost class type that match
141    OTR_TYPE or contain OTR_TYPE as a base.  Update THIS
142    to represent it.
143
144    If OTR_TYPE is NULL, just find outermost polymorphic type with
145    virtual table present at possition OFFSET.
146
147    For example when THIS represents type
148    class A
149      {
150        int a;
151        class B b;
152      }
153    and we look for type at offset sizeof(int), we end up with B and offset 0.
154    If the same is produced by multiple inheritance, we end up with A and offset
155    sizeof(int). 
156
157    If we can not find corresponding class, give up by setting
158    THIS->OUTER_TYPE to OTR_TYPE and THIS->OFFSET to NULL. 
159    Return true when lookup was sucesful.
160
161    When CONSIDER_PLACEMENT_NEW is false, reject contexts that may be made
162    valid only via alocation of new polymorphic type inside by means
163    of placement new.
164
165    When CONSIDER_BASES is false, only look for actual fields, not base types
166    of TYPE.  */
167
168 bool
169 ipa_polymorphic_call_context::restrict_to_inner_class (tree otr_type,
170                                                        bool consider_placement_new,
171                                                        bool consider_bases)
172 {
173   tree type = outer_type;
174   HOST_WIDE_INT cur_offset = offset;
175   bool speculative = false;
176   bool size_unknown = false;
177   unsigned HOST_WIDE_INT otr_type_size = POINTER_SIZE;
178
179   /* Update OUTER_TYPE to match EXPECTED_TYPE if it is not set.  */
180   if (!outer_type)
181     {
182       clear_outer_type (otr_type);
183       type = otr_type;
184       cur_offset = 0;
185     }
186  /* See if OFFSET points inside OUTER_TYPE.  If it does not, we know
187     that the context is either invalid, or the instance type must be
188     derived from OUTER_TYPE.
189
190     Because the instance type may contain field whose type is of OUTER_TYPE,
191     we can not derive any effective information about it.
192
193     TODO: In the case we know all derrived types, we can definitely do better
194     here.  */
195   else if (TYPE_SIZE (outer_type)
196            && tree_fits_shwi_p (TYPE_SIZE (outer_type))
197            && tree_to_shwi (TYPE_SIZE (outer_type)) >= 0
198            && tree_to_shwi (TYPE_SIZE (outer_type)) <= offset)
199    {
200      clear_outer_type (otr_type);
201      type = otr_type;
202      cur_offset = 0;
203
204      /* If derived type is not allowed, we know that the context is invalid.
205         For dynamic types, we really do not have information about
206         size of the memory location.  It is possible that completely
207         different type is stored after outer_type.  */
208      if (!maybe_derived_type && !dynamic)
209        {
210          clear_speculation ();
211          invalid = true;
212          return false;
213        }
214    }
215
216   if (otr_type && TYPE_SIZE (otr_type)
217       && tree_fits_shwi_p (TYPE_SIZE (otr_type)))
218     otr_type_size = tree_to_uhwi (TYPE_SIZE (otr_type));
219
220   if (!type || offset < 0)
221     goto no_useful_type_info;
222
223   /* Find the sub-object the constant actually refers to and mark whether it is
224      an artificial one (as opposed to a user-defined one).
225
226      This loop is performed twice; first time for outer_type and second time
227      for speculative_outer_type.  The second run has SPECULATIVE set.  */
228   while (true)
229     {
230       unsigned HOST_WIDE_INT pos, size;
231       tree fld;
232
233       /* If we do not know size of TYPE, we need to be more conservative
234          about accepting cases where we can not find EXPECTED_TYPE.
235          Generally the types that do matter here are of constant size.
236          Size_unknown case should be very rare.  */
237       if (TYPE_SIZE (type)
238           && tree_fits_shwi_p (TYPE_SIZE (type))
239           && tree_to_shwi (TYPE_SIZE (type)) >= 0)
240         size_unknown = false;
241       else
242         size_unknown = true;
243
244       /* On a match, just return what we found.  */
245       if ((otr_type
246            && types_odr_comparable (type, otr_type)
247            && types_same_for_odr (type, otr_type))
248           || (!otr_type
249               && TREE_CODE (type) == RECORD_TYPE
250               && TYPE_BINFO (type)
251               && polymorphic_type_binfo_p (TYPE_BINFO (type))))
252         {
253           if (speculative)
254             {
255               /* If we did not match the offset, just give up on speculation.  */
256               if (cur_offset != 0
257                   /* Also check if speculation did not end up being same as
258                      non-speculation.  */
259                   || (types_must_be_same_for_odr (speculative_outer_type,
260                                                   outer_type)
261                       && (maybe_derived_type
262                           == speculative_maybe_derived_type)))
263                 clear_speculation ();
264               return true;
265             }
266           else
267             {
268               /* If type is known to be final, do not worry about derived
269                  types.  Testing it here may help us to avoid speculation.  */
270               if (otr_type && TREE_CODE (outer_type) == RECORD_TYPE
271                   && (!in_lto_p || odr_type_p (outer_type))
272                   && type_known_to_have_no_deriavations_p (outer_type))
273                 maybe_derived_type = false;
274
275               /* Type can not contain itself on an non-zero offset.  In that case
276                  just give up.  Still accept the case where size is now known.
277                  Either the second copy may appear past the end of type or within
278                  the non-POD buffer located inside the variably sized type
279                  itself.  */
280               if (cur_offset != 0)
281                 goto no_useful_type_info;
282               /* If we determined type precisely or we have no clue on
283                  speuclation, we are done.  */
284               if (!maybe_derived_type || !speculative_outer_type
285                   || !speculation_consistent_p (speculative_outer_type,
286                                                 speculative_offset,
287                                                 speculative_maybe_derived_type,
288                                                 otr_type))
289                 {
290                   clear_speculation ();
291                   return true;
292                 }
293               /* Otherwise look into speculation now.  */
294               else
295                 {
296                   speculative = true;
297                   type = speculative_outer_type;
298                   cur_offset = speculative_offset;
299                   continue;
300                 }
301             }
302         }
303
304       /* Walk fields and find corresponding on at OFFSET.  */
305       if (TREE_CODE (type) == RECORD_TYPE)
306         {
307           for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
308             {
309               if (TREE_CODE (fld) != FIELD_DECL)
310                 continue;
311
312               pos = int_bit_position (fld);
313               if (pos > (unsigned HOST_WIDE_INT)cur_offset)
314                 continue;
315
316               /* Do not consider vptr itself.  Not even for placement new.  */
317               if (!pos && DECL_ARTIFICIAL (fld)
318                   && POINTER_TYPE_P (TREE_TYPE (fld))
319                   && TYPE_BINFO (type)
320                   && polymorphic_type_binfo_p (TYPE_BINFO (type)))
321                 continue;
322
323               if (!DECL_SIZE (fld) || !tree_fits_uhwi_p (DECL_SIZE (fld)))
324                 goto no_useful_type_info;
325               size = tree_to_uhwi (DECL_SIZE (fld));
326
327               /* We can always skip types smaller than pointer size:
328                  those can not contain a virtual table pointer.
329
330                  Disqualifying fields that are too small to fit OTR_TYPE
331                  saves work needed to walk them for no benefit.
332                  Because of the way the bases are packed into a class, the
333                  field's size may be smaller than type size, so it needs
334                  to be done with a care.  */
335                 
336               if (pos <= (unsigned HOST_WIDE_INT)cur_offset
337                   && (pos + size) >= (unsigned HOST_WIDE_INT)cur_offset
338                                      + POINTER_SIZE
339                   && (!otr_type
340                       || !TYPE_SIZE (TREE_TYPE (fld))
341                       || !tree_fits_shwi_p (TYPE_SIZE (TREE_TYPE (fld)))
342                       || (pos + tree_to_uhwi (TYPE_SIZE (TREE_TYPE (fld))))
343                           >= cur_offset + otr_type_size))
344                 break;
345             }
346
347           if (!fld)
348             goto no_useful_type_info;
349
350           type = TYPE_MAIN_VARIANT (TREE_TYPE (fld));
351           cur_offset -= pos;
352           /* DECL_ARTIFICIAL represents a basetype.  */
353           if (!DECL_ARTIFICIAL (fld))
354             {
355               if (!speculative)
356                 {
357                   outer_type = type;
358                   offset = cur_offset;
359                   /* As soon as we se an field containing the type,
360                      we know we are not looking for derivations.  */
361                   maybe_derived_type = false;
362                 }
363               else
364                 {
365                   speculative_outer_type = type;
366                   speculative_offset = cur_offset;
367                   speculative_maybe_derived_type = false;
368                 }
369             }
370           else if (!consider_bases)
371             goto no_useful_type_info;
372         }
373       else if (TREE_CODE (type) == ARRAY_TYPE)
374         {
375           tree subtype = TYPE_MAIN_VARIANT (TREE_TYPE (type));
376
377           /* Give up if we don't know array field size.
378              Also give up on non-polymorphic types as they are used
379              as buffers for placement new.  */
380           if (!TYPE_SIZE (subtype)
381               || !tree_fits_shwi_p (TYPE_SIZE (subtype))
382               || tree_to_shwi (TYPE_SIZE (subtype)) <= 0
383               || !contains_polymorphic_type_p (subtype))
384             goto no_useful_type_info;
385
386           HOST_WIDE_INT new_offset = cur_offset % tree_to_shwi (TYPE_SIZE (subtype));
387
388           /* We may see buffer for placement new.  In this case the expected type
389              can be bigger than the subtype.  */
390           if (TYPE_SIZE (subtype)
391               && (cur_offset + otr_type_size
392                   > tree_to_uhwi (TYPE_SIZE (subtype))))
393             goto no_useful_type_info;
394
395           cur_offset = new_offset;
396           type = subtype;
397           if (!speculative)
398             {
399               outer_type = type;
400               offset = cur_offset;
401               maybe_derived_type = false;
402             }
403           else
404             {
405               speculative_outer_type = type;
406               speculative_offset = cur_offset;
407               speculative_maybe_derived_type = false;
408             }
409         }
410       /* Give up on anything else.  */
411       else
412         {
413 no_useful_type_info:
414           if (maybe_derived_type && !speculative
415               && TREE_CODE (outer_type) == RECORD_TYPE
416               && TREE_CODE (otr_type) == RECORD_TYPE
417               && TYPE_BINFO (otr_type)
418               && !offset
419               && get_binfo_at_offset (TYPE_BINFO (otr_type), 0, outer_type))
420             {
421               clear_outer_type (otr_type);
422               if (!speculative_outer_type
423                   || !speculation_consistent_p (speculative_outer_type,
424                                                 speculative_offset,
425                                                 speculative_maybe_derived_type,
426                                                 otr_type))
427                 clear_speculation ();
428               if (speculative_outer_type)
429                 {
430                   speculative = true;
431                   type = speculative_outer_type;
432                   cur_offset = speculative_offset;
433                 }
434               else
435                 return true;
436             }
437           /* We found no way to embedd EXPECTED_TYPE in TYPE.
438              We still permit two special cases - placement new and
439              the case of variadic types containing themselves.  */
440           if (!speculative
441               && consider_placement_new
442               && (size_unknown || !type || maybe_derived_type
443                   || possible_placement_new (type, otr_type, cur_offset)))
444             {
445               /* In these weird cases we want to accept the context.
446                  In non-speculative run we have no useful outer_type info
447                  (TODO: we may eventually want to record upper bound on the
448                   type size that can be used to prune the walk),
449                  but we still want to consider speculation that may
450                  give useful info.  */
451               if (!speculative)
452                 {
453                   clear_outer_type (otr_type);
454                   if (!speculative_outer_type
455                       || !speculation_consistent_p (speculative_outer_type,
456                                                     speculative_offset,
457                                                     speculative_maybe_derived_type,
458                                                     otr_type))
459                     clear_speculation ();
460                   if (speculative_outer_type)
461                     {
462                       speculative = true;
463                       type = speculative_outer_type;
464                       cur_offset = speculative_offset;
465                     }
466                   else
467                     return true;
468                 }
469               else
470                 clear_speculation ();
471               return true;
472             }
473           else
474             {
475               clear_speculation ();
476               if (speculative)
477                 return true;
478               clear_outer_type (otr_type);
479               invalid = true; 
480               return false;
481             }
482         }
483     }
484 }
485
486 /* Return true if OUTER_TYPE contains OTR_TYPE at OFFSET.
487    CONSIDER_PLACEMENT_NEW makes function to accept cases where OTR_TYPE can
488    be built within OUTER_TYPE by means of placement new.  CONSIDER_BASES makes
489    function to accept cases where OTR_TYPE appears as base of OUTER_TYPE or as
490    base of one of fields of OUTER_TYPE.  */
491
492 static bool
493 contains_type_p (tree outer_type, HOST_WIDE_INT offset,
494                  tree otr_type,
495                  bool consider_placement_new,
496                  bool consider_bases)
497 {
498   ipa_polymorphic_call_context context;
499
500   /* Check that type is within range.  */
501   if (offset < 0)
502     return false;
503   if (TYPE_SIZE (outer_type) && TYPE_SIZE (otr_type)
504       && TREE_CODE (outer_type) == INTEGER_CST
505       && TREE_CODE (otr_type) == INTEGER_CST
506       && wi::ltu_p (wi::to_offset (outer_type), (wi::to_offset (otr_type) + offset)))
507     return false;
508
509   context.offset = offset;
510   context.outer_type = TYPE_MAIN_VARIANT (outer_type);
511   context.maybe_derived_type = false;
512   return context.restrict_to_inner_class (otr_type, consider_placement_new, consider_bases);
513 }
514
515
516 /* We know that the instance is stored in variable or parameter
517    (not dynamically allocated) and we want to disprove the fact
518    that it may be in construction at invocation of CALL.
519
520    BASE represents memory location where instance is stored.
521    If BASE is NULL, it is assumed to be global memory.
522    OUTER_TYPE is known type of the instance or NULL if not
523    known.
524
525    For the variable to be in construction we actually need to
526    be in constructor of corresponding global variable or
527    the inline stack of CALL must contain the constructor.
528    Check this condition.  This check works safely only before
529    IPA passes, because inline stacks may become out of date
530    later.  */
531
532 bool
533 decl_maybe_in_construction_p (tree base, tree outer_type,
534                               gimple call, tree function)
535 {
536   if (outer_type)
537     outer_type = TYPE_MAIN_VARIANT (outer_type);
538   gcc_assert (!base || DECL_P (base));
539
540   /* After inlining the code unification optimizations may invalidate
541      inline stacks.  Also we need to give up on global variables after
542      IPA, because addresses of these may have been propagated to their
543      constructors.  */
544   if (DECL_STRUCT_FUNCTION (function)->after_inlining)
545     return true;
546
547   /* Pure functions can not do any changes on the dynamic type;
548      that require writting to memory.  */
549   if ((!base || !auto_var_in_fn_p (base, function))
550       && flags_from_decl_or_type (function) & (ECF_PURE | ECF_CONST))
551     return false;
552
553   for (tree block = gimple_block (call); block && TREE_CODE (block) == BLOCK;
554        block = BLOCK_SUPERCONTEXT (block))
555     if (BLOCK_ABSTRACT_ORIGIN (block)
556         && TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block)) == FUNCTION_DECL)
557       {
558         tree fn = BLOCK_ABSTRACT_ORIGIN (block);
559
560         if (TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
561             || (!DECL_CXX_CONSTRUCTOR_P (fn)
562                 && !DECL_CXX_DESTRUCTOR_P (fn)))
563           {
564             /* Watch for clones where we constant propagated the first
565                argument (pointer to the instance).  */
566             fn = DECL_ABSTRACT_ORIGIN (fn);
567             if (!fn
568                 || (base && !is_global_var (base))
569                 || TREE_CODE (TREE_TYPE (fn)) != METHOD_TYPE
570                 || (!DECL_CXX_CONSTRUCTOR_P (fn)
571                     && !DECL_CXX_DESTRUCTOR_P (fn)))
572               continue;
573           }
574         if (flags_from_decl_or_type (fn) & (ECF_PURE | ECF_CONST))
575           continue;
576
577         tree type = TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (fn)));
578
579         if (!outer_type || !types_odr_comparable (type, outer_type))
580           {
581             if (TREE_CODE (type) == RECORD_TYPE
582                 && TYPE_BINFO (type)
583                 && polymorphic_type_binfo_p (TYPE_BINFO (type)))
584               return true;
585           }
586         else if (types_same_for_odr (type, outer_type))
587           return true;
588       }
589
590   if (!base || (TREE_CODE (base) == VAR_DECL && is_global_var (base)))
591     {
592       if (TREE_CODE (TREE_TYPE (function)) != METHOD_TYPE
593           || (!DECL_CXX_CONSTRUCTOR_P (function)
594               && !DECL_CXX_DESTRUCTOR_P (function)))
595         {
596           if (!DECL_ABSTRACT_ORIGIN (function))
597             return false;
598           /* Watch for clones where we constant propagated the first
599              argument (pointer to the instance).  */
600           function = DECL_ABSTRACT_ORIGIN (function);
601           if (!function
602               || TREE_CODE (TREE_TYPE (function)) != METHOD_TYPE
603               || (!DECL_CXX_CONSTRUCTOR_P (function)
604                   && !DECL_CXX_DESTRUCTOR_P (function)))
605             return false;
606         }
607       tree type = TYPE_MAIN_VARIANT (method_class_type (TREE_TYPE (function)));
608       if (!outer_type || !types_odr_comparable (type, outer_type))
609         {
610           if (TREE_CODE (type) == RECORD_TYPE
611               && TYPE_BINFO (type)
612               && polymorphic_type_binfo_p (TYPE_BINFO (type)))
613             return true;
614         }
615       else if (types_same_for_odr (type, outer_type))
616         return true;
617     }
618   return false;
619 }
620
621 /* Dump human readable context to F.  If NEWLINE is true, it will be terminated
622    by a newline.  */
623
624 void
625 ipa_polymorphic_call_context::dump (FILE *f, bool newline) const
626 {
627   fprintf (f, "    ");
628   if (invalid)
629     fprintf (f, "Call is known to be undefined");
630   else
631     {
632       if (useless_p ())
633         fprintf (f, "nothing known");
634       if (outer_type || offset)
635         {
636           fprintf (f, "Outer type%s:", dynamic ? " (dynamic)":"");
637           print_generic_expr (f, outer_type, TDF_SLIM);
638           if (maybe_derived_type)
639             fprintf (f, " (or a derived type)");
640           if (maybe_in_construction)
641             fprintf (f, " (maybe in construction)");
642           fprintf (f, " offset "HOST_WIDE_INT_PRINT_DEC,
643                    offset);
644         }
645       if (speculative_outer_type)
646         {
647           if (outer_type || offset)
648             fprintf (f, " ");
649           fprintf (f, "Speculative outer type:");
650           print_generic_expr (f, speculative_outer_type, TDF_SLIM);
651           if (speculative_maybe_derived_type)
652             fprintf (f, " (or a derived type)");
653           fprintf (f, " at offset "HOST_WIDE_INT_PRINT_DEC,
654                    speculative_offset);
655         }
656     }
657   if (newline)
658     fprintf(f, "\n");
659 }
660
661 /* Print context to stderr.  */
662
663 void
664 ipa_polymorphic_call_context::debug () const
665 {
666   dump (stderr);
667 }
668
669 /* Stream out the context to OB.  */
670
671 void
672 ipa_polymorphic_call_context::stream_out (struct output_block *ob) const
673 {
674   struct bitpack_d bp = bitpack_create (ob->main_stream);
675
676   bp_pack_value (&bp, invalid, 1);
677   bp_pack_value (&bp, maybe_in_construction, 1);
678   bp_pack_value (&bp, maybe_derived_type, 1);
679   bp_pack_value (&bp, speculative_maybe_derived_type, 1);
680   bp_pack_value (&bp, dynamic, 1);
681   bp_pack_value (&bp, outer_type != NULL, 1);
682   bp_pack_value (&bp, offset != 0, 1);
683   bp_pack_value (&bp, speculative_outer_type != NULL, 1);
684   streamer_write_bitpack (&bp);
685
686   if (outer_type != NULL)
687     stream_write_tree (ob, outer_type, true);
688   if (offset)
689     streamer_write_hwi (ob, offset);
690   if (speculative_outer_type != NULL)
691     {
692       stream_write_tree (ob, speculative_outer_type, true);
693       streamer_write_hwi (ob, speculative_offset);
694     }
695   else
696     gcc_assert (!speculative_offset);
697 }
698
699 /* Stream in the context from IB and DATA_IN.  */
700
701 void
702 ipa_polymorphic_call_context::stream_in (struct lto_input_block *ib,
703                                          struct data_in *data_in)
704 {
705   struct bitpack_d bp = streamer_read_bitpack (ib);
706
707   invalid = bp_unpack_value (&bp, 1);
708   maybe_in_construction = bp_unpack_value (&bp, 1);
709   maybe_derived_type = bp_unpack_value (&bp, 1);
710   speculative_maybe_derived_type = bp_unpack_value (&bp, 1);
711   dynamic = bp_unpack_value (&bp, 1);
712   bool outer_type_p = bp_unpack_value (&bp, 1);
713   bool offset_p = bp_unpack_value (&bp, 1);
714   bool speculative_outer_type_p = bp_unpack_value (&bp, 1);
715
716   if (outer_type_p)
717     outer_type = stream_read_tree (ib, data_in);
718   else
719     outer_type = NULL;
720   if (offset_p)
721     offset = (HOST_WIDE_INT) streamer_read_hwi (ib);
722   else
723     offset = 0;
724   if (speculative_outer_type_p)
725     {
726       speculative_outer_type = stream_read_tree (ib, data_in);
727       speculative_offset = (HOST_WIDE_INT) streamer_read_hwi (ib);
728     }
729   else
730     {
731       speculative_outer_type = NULL;
732       speculative_offset = 0;
733     }
734 }
735
736 /* Proudce polymorphic call context for call method of instance
737    that is located within BASE (that is assumed to be a decl) at offset OFF. */
738
739 void
740 ipa_polymorphic_call_context::set_by_decl (tree base, HOST_WIDE_INT off)
741 {
742   gcc_assert (DECL_P (base));
743   clear_speculation ();
744
745   if (!contains_polymorphic_type_p (TREE_TYPE (base)))
746     {
747       clear_outer_type ();
748       offset = off;
749       return;
750     }
751   outer_type = TYPE_MAIN_VARIANT (TREE_TYPE (base));
752   offset = off;
753   /* Make very conservative assumption that all objects
754      may be in construction. 
755  
756      It is up to caller to revisit this via
757      get_dynamic_type or decl_maybe_in_construction_p.  */
758   maybe_in_construction = true;
759   maybe_derived_type = false;
760   dynamic = false;
761 }
762
763 /* CST is an invariant (address of decl), try to get meaningful
764    polymorphic call context for polymorphic call of method 
765    if instance of OTR_TYPE that is located at offset OFF of this invariant.
766    Return FALSE if nothing meaningful can be found.  */
767
768 bool
769 ipa_polymorphic_call_context::set_by_invariant (tree cst,
770                                                 tree otr_type,
771                                                 HOST_WIDE_INT off)
772 {
773   HOST_WIDE_INT offset2, size, max_size;
774   tree base;
775
776   invalid = false;
777   off = 0;
778   clear_outer_type (otr_type);
779
780   if (TREE_CODE (cst) != ADDR_EXPR)
781     return false;
782
783   cst = TREE_OPERAND (cst, 0);
784   base = get_ref_base_and_extent (cst, &offset2, &size, &max_size);
785   if (!DECL_P (base) || max_size == -1 || max_size != size)
786     return false;
787
788   /* Only type inconsistent programs can have otr_type that is
789      not part of outer type.  */
790   if (otr_type && !contains_type_p (TREE_TYPE (base), off, otr_type))
791     return false;
792
793   set_by_decl (base, off);
794   return true;
795 }
796
797 /* See if OP is SSA name initialized as a copy or by single assignment.
798    If so, walk the SSA graph up.  Because simple PHI conditional is considered
799    copy, GLOBAL_VISITED may be used to avoid infinite loop walking the SSA
800    graph.  */
801
802 static tree
803 walk_ssa_copies (tree op, hash_set<tree> **global_visited = NULL)
804 {
805   hash_set <tree> *visited = NULL;
806   STRIP_NOPS (op);
807   while (TREE_CODE (op) == SSA_NAME
808          && !SSA_NAME_IS_DEFAULT_DEF (op)
809          /* We might be called via fold_stmt during cfgcleanup where
810             SSA form need not be up-to-date.  */
811          && !name_registered_for_update_p (op) 
812          && (gimple_assign_single_p (SSA_NAME_DEF_STMT (op))
813              || gimple_code (SSA_NAME_DEF_STMT (op)) == GIMPLE_PHI))
814     {
815       if (global_visited)
816         {
817           if (!*global_visited)
818             *global_visited = new hash_set<tree>;
819           if ((*global_visited)->add (op))
820             goto done;
821         }       
822       else
823         {
824           if (!visited)
825             visited = new hash_set<tree>;
826           if (visited->add (op))
827             goto done;
828         }
829       /* Special case
830          if (ptr == 0)
831            ptr = 0;
832          else
833            ptr = ptr.foo;
834          This pattern is implicitly produced for casts to non-primary
835          bases.  When doing context analysis, we do not really care
836          about the case pointer is NULL, becuase the call will be
837          undefined anyway.  */
838       if (gimple_code (SSA_NAME_DEF_STMT (op)) == GIMPLE_PHI)
839         {
840           gimple phi = SSA_NAME_DEF_STMT (op);
841
842           if (gimple_phi_num_args (phi) > 2)
843             goto done;
844           if (gimple_phi_num_args (phi) == 1)
845             op = gimple_phi_arg_def (phi, 0);
846           else if (integer_zerop (gimple_phi_arg_def (phi, 0)))
847             op = gimple_phi_arg_def (phi, 1);
848           else if (integer_zerop (gimple_phi_arg_def (phi, 1)))
849             op = gimple_phi_arg_def (phi, 0);
850           else
851             goto done;
852         }
853       else
854         {
855           if (gimple_assign_load_p (SSA_NAME_DEF_STMT (op)))
856             goto done;
857           op = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (op));
858         }
859       STRIP_NOPS (op);
860     }
861 done:
862   if (visited)
863     delete (visited);
864   return op;
865 }
866
867 /* Create polymorphic call context from IP invariant CST.
868    This is typically &global_var.
869    OTR_TYPE specify type of polymorphic call or NULL if unknown, OFF
870    is offset of call.  */
871
872 ipa_polymorphic_call_context::ipa_polymorphic_call_context (tree cst,
873                                                             tree otr_type,
874                                                             HOST_WIDE_INT off)
875 {
876   clear_speculation ();
877   set_by_invariant (cst, otr_type, off);
878 }
879
880 /* Build context for pointer REF contained in FNDECL at statement STMT.
881    if INSTANCE is non-NULL, return pointer to the object described by
882    the context or DECL where context is contained in.  */
883
884 ipa_polymorphic_call_context::ipa_polymorphic_call_context (tree fndecl,
885                                                             tree ref,
886                                                             gimple stmt,
887                                                             tree *instance)
888 {
889   tree otr_type = NULL;
890   tree base_pointer;
891   hash_set <tree> *visited = NULL;
892
893   if (TREE_CODE (ref) == OBJ_TYPE_REF)
894     {
895       otr_type = obj_type_ref_class (ref);
896       base_pointer = OBJ_TYPE_REF_OBJECT (ref);
897     }
898   else
899     base_pointer = ref;
900
901   /* Set up basic info in case we find nothing interesting in the analysis.  */
902   clear_speculation ();
903   clear_outer_type (otr_type);
904   invalid = false;
905
906   /* Walk SSA for outer object.  */
907   while (true)
908     {
909       base_pointer = walk_ssa_copies (base_pointer, &visited);
910       if (TREE_CODE (base_pointer) == ADDR_EXPR)
911         {
912           HOST_WIDE_INT size, max_size;
913           HOST_WIDE_INT offset2;
914           tree base = get_ref_base_and_extent (TREE_OPERAND (base_pointer, 0),
915                                                &offset2, &size, &max_size);
916
917           if (max_size != -1 && max_size == size)
918             combine_speculation_with (TYPE_MAIN_VARIANT (TREE_TYPE (base)),
919                                       offset + offset2,
920                                       true,
921                                       NULL /* Do not change outer type.  */);
922
923           /* If this is a varying address, punt.  */
924           if ((TREE_CODE (base) == MEM_REF || DECL_P (base))
925               && max_size != -1
926               && max_size == size)
927             {
928               /* We found dereference of a pointer.  Type of the pointer
929                  and MEM_REF is meaningless, but we can look futher.  */
930               if (TREE_CODE (base) == MEM_REF)
931                 {
932                   base_pointer = TREE_OPERAND (base, 0);
933                   offset
934                     += offset2 + mem_ref_offset (base).to_short_addr () * BITS_PER_UNIT;
935                   outer_type = NULL;
936                 }
937               /* We found base object.  In this case the outer_type
938                  is known.  */
939               else if (DECL_P (base))
940                 {
941                   if (visited)
942                     delete (visited);
943                   /* Only type inconsistent programs can have otr_type that is
944                      not part of outer type.  */
945                   if (otr_type
946                       && !contains_type_p (TREE_TYPE (base),
947                                            offset + offset2, otr_type))
948                     {
949                       invalid = true;
950                       if (instance)
951                         *instance = base_pointer;
952                       return;
953                     }
954                   set_by_decl (base, offset + offset2);
955                   if (outer_type && maybe_in_construction && stmt)
956                     maybe_in_construction
957                      = decl_maybe_in_construction_p (base,
958                                                      outer_type,
959                                                      stmt,
960                                                      fndecl);
961                   if (instance)
962                     *instance = base;
963                   return;
964                 }
965               else
966                 break;
967             }
968           else
969             break;
970         }
971       else if (TREE_CODE (base_pointer) == POINTER_PLUS_EXPR
972                && tree_fits_uhwi_p (TREE_OPERAND (base_pointer, 1)))
973         {
974           offset += tree_to_shwi (TREE_OPERAND (base_pointer, 1))
975                     * BITS_PER_UNIT;
976           base_pointer = TREE_OPERAND (base_pointer, 0);
977         }
978       else
979         break;
980     }
981
982   if (visited)
983     delete (visited);
984
985   /* Try to determine type of the outer object.  */
986   if (TREE_CODE (base_pointer) == SSA_NAME
987       && SSA_NAME_IS_DEFAULT_DEF (base_pointer)
988       && TREE_CODE (SSA_NAME_VAR (base_pointer)) == PARM_DECL)
989     {
990       /* See if parameter is THIS pointer of a method.  */
991       if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE
992           && SSA_NAME_VAR (base_pointer) == DECL_ARGUMENTS (fndecl))
993         {
994           outer_type
995              = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (base_pointer)));
996           gcc_assert (TREE_CODE (outer_type) == RECORD_TYPE
997                       || TREE_CODE (outer_type) == UNION_TYPE);
998
999           /* Dynamic casting has possibly upcasted the type
1000              in the hiearchy.  In this case outer type is less
1001              informative than inner type and we should forget
1002              about it.  */
1003           if ((otr_type
1004                && !contains_type_p (outer_type, offset,
1005                                     otr_type))
1006               || !contains_polymorphic_type_p (outer_type))
1007             {
1008               outer_type = NULL;
1009               if (instance)
1010                 *instance = base_pointer;
1011               return;
1012             }
1013
1014           dynamic = true;
1015
1016           /* If the function is constructor or destructor, then
1017              the type is possibly in construction, but we know
1018              it is not derived type.  */
1019           if (DECL_CXX_CONSTRUCTOR_P (fndecl)
1020               || DECL_CXX_DESTRUCTOR_P (fndecl))
1021             {
1022               maybe_in_construction = true;
1023               maybe_derived_type = false;
1024             }
1025           else
1026             {
1027               maybe_derived_type = true;
1028               maybe_in_construction = false;
1029             }
1030           if (instance)
1031             *instance = base_pointer;
1032           return;
1033         }
1034       /* Non-PODs passed by value are really passed by invisible
1035          reference.  In this case we also know the type of the
1036          object.  */
1037       if (DECL_BY_REFERENCE (SSA_NAME_VAR (base_pointer)))
1038         {
1039           outer_type
1040              = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (base_pointer)));
1041           /* Only type inconsistent programs can have otr_type that is
1042              not part of outer type.  */
1043           if (otr_type && !contains_type_p (outer_type, offset,
1044                                             otr_type))
1045             { 
1046               invalid = true;
1047               if (instance)
1048                 *instance = base_pointer;
1049               return;
1050             }
1051           /* Non-polymorphic types have no interest for us.  */
1052           else if (!otr_type && !contains_polymorphic_type_p (outer_type))
1053             {
1054               outer_type = NULL;
1055               if (instance)
1056                 *instance = base_pointer;
1057               return;
1058             }
1059           maybe_derived_type = false;
1060           maybe_in_construction = false;
1061           if (instance)
1062             *instance = base_pointer;
1063           return;
1064         }
1065     }
1066
1067   tree base_type = TREE_TYPE (base_pointer);
1068
1069   if (TREE_CODE (base_pointer) == SSA_NAME
1070       && SSA_NAME_IS_DEFAULT_DEF (base_pointer)
1071       && !(TREE_CODE (SSA_NAME_VAR (base_pointer)) == PARM_DECL
1072            || TREE_CODE (SSA_NAME_VAR (base_pointer)) == RESULT_DECL))
1073     {
1074       invalid = true;
1075       if (instance)
1076         *instance = base_pointer;
1077       return;
1078     }
1079   if (TREE_CODE (base_pointer) == SSA_NAME
1080       && SSA_NAME_DEF_STMT (base_pointer)
1081       && gimple_assign_single_p (SSA_NAME_DEF_STMT (base_pointer)))
1082     base_type = TREE_TYPE (gimple_assign_rhs1
1083                             (SSA_NAME_DEF_STMT (base_pointer)));
1084  
1085   if (base_type && POINTER_TYPE_P (base_type))
1086     combine_speculation_with (TYPE_MAIN_VARIANT (TREE_TYPE (base_type)),
1087                               offset,
1088                               true, NULL /* Do not change type here */);
1089   /* TODO: There are multiple ways to derive a type.  For instance
1090      if BASE_POINTER is passed to an constructor call prior our refernece.
1091      We do not make this type of flow sensitive analysis yet.  */
1092   if (instance)
1093     *instance = base_pointer;
1094   return;
1095 }
1096
1097 /* Structure to be passed in between detect_type_change and
1098    check_stmt_for_type_change.  */
1099
1100 struct type_change_info
1101 {
1102   /* Offset into the object where there is the virtual method pointer we are
1103      looking for.  */
1104   HOST_WIDE_INT offset;
1105   /* The declaration or SSA_NAME pointer of the base that we are checking for
1106      type change.  */
1107   tree instance;
1108   /* The reference to virtual table pointer used.  */
1109   tree vtbl_ptr_ref;
1110   tree otr_type;
1111   /* If we actually can tell the type that the object has changed to, it is
1112      stored in this field.  Otherwise it remains NULL_TREE.  */
1113   tree known_current_type;
1114   HOST_WIDE_INT known_current_offset;
1115
1116   /* Set to true if dynamic type change has been detected.  */
1117   bool type_maybe_changed;
1118   /* Set to true if multiple types have been encountered.  known_current_type
1119      must be disregarded in that case.  */
1120   bool multiple_types_encountered;
1121   /* Set to true if we possibly missed some dynamic type changes and we should
1122      consider the set to be speculative.  */
1123   bool speculative;
1124   bool seen_unanalyzed_store;
1125 };
1126
1127 /* Return true if STMT is not call and can modify a virtual method table pointer.
1128    We take advantage of fact that vtable stores must appear within constructor
1129    and destructor functions.  */
1130
1131 static bool
1132 noncall_stmt_may_be_vtbl_ptr_store (gimple stmt)
1133 {
1134   if (is_gimple_assign (stmt))
1135     {
1136       tree lhs = gimple_assign_lhs (stmt);
1137
1138       if (gimple_clobber_p (stmt))
1139         return false;
1140       if (!AGGREGATE_TYPE_P (TREE_TYPE (lhs)))
1141         {
1142           if (flag_strict_aliasing
1143               && !POINTER_TYPE_P (TREE_TYPE (lhs)))
1144             return false;
1145
1146           if (TREE_CODE (lhs) == COMPONENT_REF
1147               && !DECL_VIRTUAL_P (TREE_OPERAND (lhs, 1)))
1148             return false;
1149           /* In the future we might want to use get_base_ref_and_offset to find
1150              if there is a field corresponding to the offset and if so, proceed
1151              almost like if it was a component ref.  */
1152         }
1153     }
1154
1155   /* Code unification may mess with inline stacks.  */
1156   if (cfun->after_inlining)
1157     return true;
1158
1159   /* Walk the inline stack and watch out for ctors/dtors.
1160      TODO: Maybe we can require the store to appear in toplevel
1161      block of CTOR/DTOR.  */
1162   for (tree block = gimple_block (stmt); block && TREE_CODE (block) == BLOCK;
1163        block = BLOCK_SUPERCONTEXT (block))
1164     if (BLOCK_ABSTRACT_ORIGIN (block)
1165         && TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block)) == FUNCTION_DECL)
1166       {
1167         tree fn = BLOCK_ABSTRACT_ORIGIN (block);
1168
1169         if (flags_from_decl_or_type (fn) & (ECF_PURE | ECF_CONST))
1170           return false;
1171         return (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
1172                 && (DECL_CXX_CONSTRUCTOR_P (fn)
1173                     || DECL_CXX_DESTRUCTOR_P (fn)));
1174       }
1175   return (TREE_CODE (TREE_TYPE (current_function_decl)) == METHOD_TYPE
1176           && (DECL_CXX_CONSTRUCTOR_P (current_function_decl)
1177               || DECL_CXX_DESTRUCTOR_P (current_function_decl)));
1178 }
1179
1180 /* If STMT can be proved to be an assignment to the virtual method table
1181    pointer of ANALYZED_OBJ and the type associated with the new table
1182    identified, return the type.  Otherwise return NULL_TREE if type changes
1183    in unknown way or ERROR_MARK_NODE if type is unchanged.  */
1184
1185 static tree
1186 extr_type_from_vtbl_ptr_store (gimple stmt, struct type_change_info *tci,
1187                                HOST_WIDE_INT *type_offset)
1188 {
1189   HOST_WIDE_INT offset, size, max_size;
1190   tree lhs, rhs, base;
1191
1192   if (!gimple_assign_single_p (stmt))
1193     return NULL_TREE;
1194
1195   lhs = gimple_assign_lhs (stmt);
1196   rhs = gimple_assign_rhs1 (stmt);
1197   if (TREE_CODE (lhs) != COMPONENT_REF
1198       || !DECL_VIRTUAL_P (TREE_OPERAND (lhs, 1)))
1199      {
1200         if (dump_file)
1201           fprintf (dump_file, "  LHS is not virtual table.\n");
1202         return NULL_TREE;
1203      }
1204
1205   if (tci->vtbl_ptr_ref && operand_equal_p (lhs, tci->vtbl_ptr_ref, 0))
1206     ;
1207   else
1208     {
1209       base = get_ref_base_and_extent (lhs, &offset, &size, &max_size);
1210       if (DECL_P (tci->instance))
1211         {
1212           if (base != tci->instance)
1213             {
1214               if (dump_file)
1215                 {
1216                   fprintf (dump_file, "    base:");
1217                   print_generic_expr (dump_file, base, TDF_SLIM);
1218                   fprintf (dump_file, " does not match instance:");
1219                   print_generic_expr (dump_file, tci->instance, TDF_SLIM);
1220                   fprintf (dump_file, "\n");
1221                 }
1222               return NULL_TREE;
1223             }
1224         }
1225       else if (TREE_CODE (base) == MEM_REF)
1226         {
1227           if (!operand_equal_p (tci->instance, TREE_OPERAND (base, 0), 0))
1228             {
1229               if (dump_file)
1230                 {
1231                   fprintf (dump_file, "    base mem ref:");
1232                   print_generic_expr (dump_file, base, TDF_SLIM);
1233                   fprintf (dump_file, " does not match instance:");
1234                   print_generic_expr (dump_file, tci->instance, TDF_SLIM);
1235                   fprintf (dump_file, "\n");
1236                 }
1237               return NULL_TREE;
1238             }
1239           if (!integer_zerop (TREE_OPERAND (base, 1)))
1240             {
1241               if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
1242                 {
1243                   if (dump_file)
1244                     {
1245                       fprintf (dump_file, "    base mem ref:");
1246                       print_generic_expr (dump_file, base, TDF_SLIM);
1247                       fprintf (dump_file, " has non-representable offset:");
1248                       print_generic_expr (dump_file, tci->instance, TDF_SLIM);
1249                       fprintf (dump_file, "\n");
1250                     }
1251                   return NULL_TREE;
1252                 }
1253               else
1254                 offset += tree_to_shwi (TREE_OPERAND (base, 1)) * BITS_PER_UNIT;
1255             }
1256         }
1257       else if (!operand_equal_p (tci->instance, base, 0)
1258                || tci->offset)
1259         {
1260           if (dump_file)
1261             {
1262               fprintf (dump_file, "    base:");
1263               print_generic_expr (dump_file, base, TDF_SLIM);
1264               fprintf (dump_file, " does not match instance:");
1265               print_generic_expr (dump_file, tci->instance, TDF_SLIM);
1266               fprintf (dump_file, " with offset %i\n", (int)tci->offset);
1267             }
1268           return tci->offset > POINTER_SIZE ? error_mark_node : NULL_TREE;
1269         }
1270       if (offset != tci->offset
1271           || size != POINTER_SIZE
1272           || max_size != POINTER_SIZE)
1273         {
1274           if (dump_file)
1275             fprintf (dump_file, "    wrong offset %i!=%i or size %i\n",
1276                      (int)offset, (int)tci->offset, (int)size);
1277           return offset + POINTER_SIZE <= tci->offset
1278                  || (max_size != -1
1279                      && tci->offset + POINTER_SIZE > offset + max_size)
1280                  ? error_mark_node : NULL;
1281         }
1282     }
1283
1284   tree vtable;
1285   unsigned HOST_WIDE_INT offset2;
1286
1287   if (!vtable_pointer_value_to_vtable (rhs, &vtable, &offset2))
1288     {
1289       if (dump_file)
1290         fprintf (dump_file, "    Failed to lookup binfo\n");
1291       return NULL;
1292     }
1293
1294   tree binfo = subbinfo_with_vtable_at_offset (TYPE_BINFO (DECL_CONTEXT (vtable)),
1295                                                offset2, vtable);
1296   if (!binfo)
1297     {
1298       if (dump_file)
1299         fprintf (dump_file, "    Construction vtable used\n");
1300       /* FIXME: We should suport construction contexts.  */
1301       return NULL;
1302     }
1303  
1304   *type_offset = tree_to_shwi (BINFO_OFFSET (binfo)) * BITS_PER_UNIT;
1305   return DECL_CONTEXT (vtable);
1306 }
1307
1308 /* Record dynamic type change of TCI to TYPE.  */
1309
1310 static void
1311 record_known_type (struct type_change_info *tci, tree type, HOST_WIDE_INT offset)
1312 {
1313   if (dump_file)
1314     {
1315       if (type)
1316         {
1317           fprintf (dump_file, "  Recording type: ");
1318           print_generic_expr (dump_file, type, TDF_SLIM);
1319           fprintf (dump_file, " at offset %i\n", (int)offset);
1320         }
1321      else
1322        fprintf (dump_file, "  Recording unknown type\n");
1323     }
1324
1325   /* If we found a constructor of type that is not polymorphic or
1326      that may contain the type in question as a field (not as base),
1327      restrict to the inner class first to make type matching bellow
1328      happier.  */
1329   if (type
1330       && (offset
1331           || (TREE_CODE (type) != RECORD_TYPE
1332               || !TYPE_BINFO (type)
1333               || !polymorphic_type_binfo_p (TYPE_BINFO (type)))))
1334     {
1335       ipa_polymorphic_call_context context;
1336
1337       context.offset = offset;
1338       context.outer_type = type;
1339       context.maybe_in_construction = false;
1340       context.maybe_derived_type = false;
1341       context.dynamic = true;
1342       /* If we failed to find the inner type, we know that the call
1343          would be undefined for type produced here.  */
1344       if (!context.restrict_to_inner_class (tci->otr_type))
1345         {
1346           if (dump_file)
1347             fprintf (dump_file, "  Ignoring; does not contain otr_type\n");
1348           return;
1349         }
1350       /* Watch for case we reached an POD type and anticipate placement
1351          new.  */
1352       if (!context.maybe_derived_type)
1353         {
1354           type = context.outer_type;
1355           offset = context.offset;
1356         }
1357     }
1358   if (tci->type_maybe_changed
1359       && (!types_same_for_odr (type, tci->known_current_type)
1360           || offset != tci->known_current_offset))
1361     tci->multiple_types_encountered = true;
1362   tci->known_current_type = TYPE_MAIN_VARIANT (type);
1363   tci->known_current_offset = offset;
1364   tci->type_maybe_changed = true;
1365 }
1366
1367 /* Callback of walk_aliased_vdefs and a helper function for
1368    detect_type_change to check whether a particular statement may modify
1369    the virtual table pointer, and if possible also determine the new type of
1370    the (sub-)object.  It stores its result into DATA, which points to a
1371    type_change_info structure.  */
1372
1373 static bool
1374 check_stmt_for_type_change (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef, void *data)
1375 {
1376   gimple stmt = SSA_NAME_DEF_STMT (vdef);
1377   struct type_change_info *tci = (struct type_change_info *) data;
1378   tree fn;
1379
1380   /* If we already gave up, just terminate the rest of walk.  */
1381   if (tci->multiple_types_encountered)
1382     return true;
1383
1384   if (is_gimple_call (stmt))
1385     {
1386       if (gimple_call_flags (stmt) & (ECF_CONST | ECF_PURE))
1387         return false;
1388
1389       /* Check for a constructor call.  */
1390       if ((fn = gimple_call_fndecl (stmt)) != NULL_TREE
1391           && DECL_CXX_CONSTRUCTOR_P (fn)
1392           && TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE
1393           && gimple_call_num_args (stmt))
1394       {
1395         tree op = walk_ssa_copies (gimple_call_arg (stmt, 0));
1396         tree type = method_class_type (TREE_TYPE (fn));
1397         HOST_WIDE_INT offset = 0, size, max_size;
1398
1399         if (dump_file)
1400           {
1401             fprintf (dump_file, "  Checking constructor call: ");
1402             print_gimple_stmt (dump_file, stmt, 0, 0);
1403           }
1404
1405         /* See if THIS parameter seems like instance pointer.  */
1406         if (TREE_CODE (op) == ADDR_EXPR)
1407           {
1408             op = get_ref_base_and_extent (TREE_OPERAND (op, 0),
1409                                           &offset, &size, &max_size);
1410             if (size != max_size || max_size == -1)
1411               {
1412                 tci->speculative = true;
1413                 return false;
1414               }
1415             if (op && TREE_CODE (op) == MEM_REF)
1416               {
1417                 if (!tree_fits_shwi_p (TREE_OPERAND (op, 1)))
1418                   {
1419                     tci->speculative = true;
1420                     return false;
1421                   }
1422                 offset += tree_to_shwi (TREE_OPERAND (op, 1))
1423                           * BITS_PER_UNIT;
1424                 op = TREE_OPERAND (op, 0);
1425               }
1426             else if (DECL_P (op))
1427               ;
1428             else
1429               {
1430                 tci->speculative = true;
1431                 return false;
1432               }
1433             op = walk_ssa_copies (op);
1434           }
1435         if (operand_equal_p (op, tci->instance, 0)
1436             && TYPE_SIZE (type)
1437             && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
1438             && tree_fits_shwi_p (TYPE_SIZE (type))
1439             && tree_to_shwi (TYPE_SIZE (type)) + offset > tci->offset)
1440           {
1441             record_known_type (tci, type, tci->offset - offset);
1442             return true;
1443           }
1444       }
1445      /* Calls may possibly change dynamic type by placement new. Assume
1446         it will not happen, but make result speculative only.  */
1447      if (dump_file)
1448         {
1449           fprintf (dump_file, "  Function call may change dynamic type:");
1450           print_gimple_stmt (dump_file, stmt, 0, 0);
1451         }
1452      tci->speculative = true;
1453      return false;
1454    }
1455   /* Check for inlined virtual table store.  */
1456   else if (noncall_stmt_may_be_vtbl_ptr_store (stmt))
1457     {
1458       tree type;
1459       HOST_WIDE_INT offset = 0;
1460       if (dump_file)
1461         {
1462           fprintf (dump_file, "  Checking vtbl store: ");
1463           print_gimple_stmt (dump_file, stmt, 0, 0);
1464         }
1465
1466       type = extr_type_from_vtbl_ptr_store (stmt, tci, &offset);
1467       if (type == error_mark_node)
1468         return false;
1469       gcc_assert (!type || TYPE_MAIN_VARIANT (type) == type);
1470       if (!type)
1471         {
1472           if (dump_file)
1473             fprintf (dump_file, "  Unanalyzed store may change type.\n");
1474           tci->seen_unanalyzed_store = true;
1475           tci->speculative = true;
1476         }
1477       else
1478         record_known_type (tci, type, offset);
1479       return true;
1480     }
1481   else
1482     return false;
1483 }
1484
1485 /* THIS is polymorphic call context obtained from get_polymorphic_context.
1486    OTR_OBJECT is pointer to the instance returned by OBJ_TYPE_REF_OBJECT.
1487    INSTANCE is pointer to the outer instance as returned by
1488    get_polymorphic_context.  To avoid creation of temporary expressions,
1489    INSTANCE may also be an declaration of get_polymorphic_context found the
1490    value to be in static storage.
1491
1492    If the type of instance is not fully determined
1493    (either OUTER_TYPE is unknown or MAYBE_IN_CONSTRUCTION/INCLUDE_DERIVED_TYPES
1494    is set), try to walk memory writes and find the actual construction of the
1495    instance.
1496
1497    Return true if memory is unchanged from function entry.
1498
1499    We do not include this analysis in the context analysis itself, because
1500    it needs memory SSA to be fully built and the walk may be expensive.
1501    So it is not suitable for use withing fold_stmt and similar uses.  */
1502
1503 bool
1504 ipa_polymorphic_call_context::get_dynamic_type (tree instance,
1505                                                 tree otr_object,
1506                                                 tree otr_type,
1507                                                 gimple call)
1508 {
1509   struct type_change_info tci;
1510   ao_ref ao;
1511   bool function_entry_reached = false;
1512   tree instance_ref = NULL;
1513   gimple stmt = call;
1514   /* Remember OFFSET before it is modified by restrict_to_inner_class.
1515      This is because we do not update INSTANCE when walking inwards.  */
1516   HOST_WIDE_INT instance_offset = offset;
1517
1518   if (otr_type)
1519     otr_type = TYPE_MAIN_VARIANT (otr_type);
1520
1521   /* Walk into inner type. This may clear maybe_derived_type and save us
1522      from useless work.  It also makes later comparsions with static type
1523      easier.  */
1524   if (outer_type && otr_type)
1525     {
1526       if (!restrict_to_inner_class (otr_type))
1527         return false;
1528     }
1529
1530   if (!maybe_in_construction && !maybe_derived_type)
1531     return false;
1532
1533   /* We need to obtain refernce to virtual table pointer.  It is better
1534      to look it up in the code rather than build our own.  This require bit
1535      of pattern matching, but we end up verifying that what we found is
1536      correct. 
1537
1538      What we pattern match is:
1539
1540        tmp = instance->_vptr.A;   // vtbl ptr load
1541        tmp2 = tmp[otr_token];     // vtable lookup
1542        OBJ_TYPE_REF(tmp2;instance->0) (instance);
1543  
1544      We want to start alias oracle walk from vtbl pointer load,
1545      but we may not be able to identify it, for example, when PRE moved the
1546      load around.  */
1547
1548   if (gimple_code (call) == GIMPLE_CALL)
1549     {
1550       tree ref = gimple_call_fn (call);
1551       HOST_WIDE_INT offset2, size, max_size;
1552
1553       if (TREE_CODE (ref) == OBJ_TYPE_REF)
1554         {
1555           ref = OBJ_TYPE_REF_EXPR (ref);
1556           ref = walk_ssa_copies (ref);
1557
1558           /* Check if definition looks like vtable lookup.  */
1559           if (TREE_CODE (ref) == SSA_NAME
1560               && !SSA_NAME_IS_DEFAULT_DEF (ref)
1561               && gimple_assign_load_p (SSA_NAME_DEF_STMT (ref))
1562               && TREE_CODE (gimple_assign_rhs1
1563                              (SSA_NAME_DEF_STMT (ref))) == MEM_REF)
1564             {
1565               ref = get_base_address
1566                      (TREE_OPERAND (gimple_assign_rhs1
1567                                      (SSA_NAME_DEF_STMT (ref)), 0));
1568               ref = walk_ssa_copies (ref);
1569               /* Find base address of the lookup and see if it looks like
1570                  vptr load.  */
1571               if (TREE_CODE (ref) == SSA_NAME
1572                   && !SSA_NAME_IS_DEFAULT_DEF (ref)
1573                   && gimple_assign_load_p (SSA_NAME_DEF_STMT (ref)))
1574                 {
1575                   tree ref_exp = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (ref));
1576                   tree base_ref = get_ref_base_and_extent
1577                                    (ref_exp, &offset2, &size, &max_size);
1578
1579                   /* Finally verify that what we found looks like read from OTR_OBJECT
1580                      or from INSTANCE with offset OFFSET.  */
1581                   if (base_ref
1582                       && ((TREE_CODE (base_ref) == MEM_REF
1583                            && ((offset2 == instance_offset
1584                                 && TREE_OPERAND (base_ref, 0) == instance)
1585                                || (!offset2 && TREE_OPERAND (base_ref, 0) == otr_object)))
1586                           || (DECL_P (instance) && base_ref == instance
1587                               && offset2 == instance_offset)))
1588                     {
1589                       stmt = SSA_NAME_DEF_STMT (ref);
1590                       instance_ref = ref_exp;
1591                     }
1592                 }
1593             }
1594         }
1595     }
1596  
1597   /* If we failed to look up the refernece in code, build our own.  */
1598   if (!instance_ref)
1599     {
1600       /* If the statement in question does not use memory, we can't tell
1601          anything.  */
1602       if (!gimple_vuse (stmt))
1603         return false;
1604       ao_ref_init_from_ptr_and_size (&ao, otr_object, NULL);
1605     }
1606   else
1607   /* Otherwise use the real reference.  */
1608     ao_ref_init (&ao, instance_ref);
1609
1610   /* We look for vtbl pointer read.  */
1611   ao.size = POINTER_SIZE;
1612   ao.max_size = ao.size;
1613   if (otr_type)
1614     ao.ref_alias_set
1615       = get_deref_alias_set (TREE_TYPE (BINFO_VTABLE (TYPE_BINFO (otr_type))));
1616
1617   if (dump_file)
1618     {
1619       fprintf (dump_file, "Determining dynamic type for call: ");
1620       print_gimple_stmt (dump_file, call, 0, 0);
1621       fprintf (dump_file, "  Starting walk at: ");
1622       print_gimple_stmt (dump_file, stmt, 0, 0);
1623       fprintf (dump_file, "  instance pointer: ");
1624       print_generic_expr (dump_file, otr_object, TDF_SLIM);
1625       fprintf (dump_file, "  Outer instance pointer: ");
1626       print_generic_expr (dump_file, instance, TDF_SLIM);
1627       fprintf (dump_file, " offset: %i (bits)", (int)offset);
1628       fprintf (dump_file, " vtbl reference: ");
1629       print_generic_expr (dump_file, instance_ref, TDF_SLIM);
1630       fprintf (dump_file, "\n");
1631     }
1632
1633   tci.offset = offset;
1634   tci.instance = instance;
1635   tci.vtbl_ptr_ref = instance_ref;
1636   gcc_assert (TREE_CODE (instance) != MEM_REF);
1637   tci.known_current_type = NULL_TREE;
1638   tci.known_current_offset = 0;
1639   tci.otr_type = otr_type;
1640   tci.type_maybe_changed = false;
1641   tci.multiple_types_encountered = false;
1642   tci.speculative = false;
1643   tci.seen_unanalyzed_store = false;
1644
1645   walk_aliased_vdefs (&ao, gimple_vuse (stmt), check_stmt_for_type_change,
1646                       &tci, NULL, &function_entry_reached);
1647
1648   /* If we did not find any type changing statements, we may still drop
1649      maybe_in_construction flag if the context already have outer type. 
1650
1651      Here we make special assumptions about both constructors and
1652      destructors which are all the functions that are allowed to alter the
1653      VMT pointers.  It assumes that destructors begin with assignment into
1654      all VMT pointers and that constructors essentially look in the
1655      following way:
1656
1657      1) The very first thing they do is that they call constructors of
1658      ancestor sub-objects that have them.
1659
1660      2) Then VMT pointers of this and all its ancestors is set to new
1661      values corresponding to the type corresponding to the constructor.
1662
1663      3) Only afterwards, other stuff such as constructor of member
1664      sub-objects and the code written by the user is run.  Only this may
1665      include calling virtual functions, directly or indirectly.
1666
1667      4) placement new can not be used to change type of non-POD statically
1668      allocated variables.
1669
1670      There is no way to call a constructor of an ancestor sub-object in any
1671      other way.
1672
1673      This means that we do not have to care whether constructors get the
1674      correct type information because they will always change it (in fact,
1675      if we define the type to be given by the VMT pointer, it is undefined).
1676
1677      The most important fact to derive from the above is that if, for some
1678      statement in the section 3, we try to detect whether the dynamic type
1679      has changed, we can safely ignore all calls as we examine the function
1680      body backwards until we reach statements in section 2 because these
1681      calls cannot be ancestor constructors or destructors (if the input is
1682      not bogus) and so do not change the dynamic type (this holds true only
1683      for automatically allocated objects but at the moment we devirtualize
1684      only these).  We then must detect that statements in section 2 change
1685      the dynamic type and can try to derive the new type.  That is enough
1686      and we can stop, we will never see the calls into constructors of
1687      sub-objects in this code. 
1688
1689      Therefore if the static outer type was found (outer_type)
1690      we can safely ignore tci.speculative that is set on calls and give up
1691      only if there was dyanmic type store that may affect given variable
1692      (seen_unanalyzed_store)  */
1693
1694   if (!tci.type_maybe_changed
1695       || (outer_type
1696           && !dynamic
1697           && !tci.seen_unanalyzed_store
1698           && !tci.multiple_types_encountered
1699           && offset == tci.offset
1700           && types_same_for_odr (tci.known_current_type,
1701                                  outer_type)))
1702     {
1703       if (!outer_type || tci.seen_unanalyzed_store)
1704         return false;
1705       if (maybe_in_construction)
1706         maybe_in_construction = false;
1707       if (dump_file)
1708         fprintf (dump_file, "  No dynamic type change found.\n");
1709       return true;
1710     }
1711
1712   if (tci.known_current_type
1713       && !function_entry_reached
1714       && !tci.multiple_types_encountered)
1715     {
1716       if (!tci.speculative)
1717         {
1718           outer_type = TYPE_MAIN_VARIANT (tci.known_current_type);
1719           offset = tci.known_current_offset;
1720           dynamic = true;
1721           maybe_in_construction = false;
1722           maybe_derived_type = false;
1723           if (dump_file)
1724             fprintf (dump_file, "  Determined dynamic type.\n");
1725         }
1726       else if (!speculative_outer_type
1727                || speculative_maybe_derived_type)
1728         {
1729           speculative_outer_type = TYPE_MAIN_VARIANT (tci.known_current_type);
1730           speculative_offset = tci.known_current_offset;
1731           speculative_maybe_derived_type = false;
1732           if (dump_file)
1733             fprintf (dump_file, "  Determined speculative dynamic type.\n");
1734         }
1735     }
1736   else if (dump_file)
1737     {
1738       fprintf (dump_file, "  Found multiple types%s%s\n",
1739                function_entry_reached ? " (function entry reached)" : "",
1740                function_entry_reached ? " (multiple types encountered)" : "");
1741     }
1742
1743   return false;
1744 }
1745
1746 /* See if speculation given by SPEC_OUTER_TYPE, SPEC_OFFSET and SPEC_MAYBE_DERIVED_TYPE
1747    seems consistent (and useful) with what we already have in the non-speculative context.  */
1748
1749 bool
1750 ipa_polymorphic_call_context::speculation_consistent_p (tree spec_outer_type,
1751                                                         HOST_WIDE_INT spec_offset,
1752                                                         bool spec_maybe_derived_type,
1753                                                         tree otr_type) const
1754 {
1755   if (!flag_devirtualize_speculatively)
1756     return false;
1757
1758   /* Non-polymorphic types are useless for deriving likely polymorphic
1759      call targets.  */
1760   if (!spec_outer_type || !contains_polymorphic_type_p (spec_outer_type))
1761     return false;
1762
1763   /* If we know nothing, speculation is always good.  */
1764   if (!outer_type)
1765     return true;
1766
1767   /* Speculation is only useful to avoid derived types.
1768      This is not 100% true for placement new, where the outer context may
1769      turn out to be useless, but ignore these for now.  */
1770   if (!maybe_derived_type)
1771     return false;
1772
1773   /* If types agrees, speculation is consistent, but it makes sense only
1774      when it says something new.  */
1775   if (types_must_be_same_for_odr (spec_outer_type, outer_type))
1776     return maybe_derived_type && !spec_maybe_derived_type;
1777
1778   /* If speculation does not contain the type in question, ignore it.  */
1779   if (otr_type
1780       && !contains_type_p (spec_outer_type, spec_offset, otr_type, false, true))
1781     return false;
1782
1783   /* If outer type already contains speculation as a filed,
1784      it is useless.  We already know from OUTER_TYPE 
1785      SPEC_TYPE and that it is not in the construction.  */
1786   if (contains_type_p (outer_type, offset - spec_offset,
1787                        spec_outer_type, false, false))
1788     return false;
1789
1790   /* If speculative outer type is not more specified than outer
1791      type, just give up. 
1792      We can only decide this safely if we can compare types with OUTER_TYPE.
1793    */
1794   if ((!in_lto_p || odr_type_p (outer_type))
1795       && !contains_type_p (spec_outer_type,
1796                            spec_offset - offset,
1797                            outer_type, false))
1798     return false;
1799   return true;
1800 }
1801
1802 /* Improve THIS with speculation described by NEW_OUTER_TYPE, NEW_OFFSET,
1803    NEW_MAYBE_DERIVED_TYPE 
1804    If OTR_TYPE is set, assume the context is used with OTR_TYPE.  */
1805
1806 bool
1807 ipa_polymorphic_call_context::combine_speculation_with
1808    (tree new_outer_type, HOST_WIDE_INT new_offset, bool new_maybe_derived_type,
1809     tree otr_type)
1810 {
1811   if (!new_outer_type)
1812     return false;
1813
1814   /* restrict_to_inner_class may eliminate wrong speculation making our job
1815      easeier.  */
1816   if (otr_type)
1817     restrict_to_inner_class (otr_type);
1818
1819   if (!speculation_consistent_p (new_outer_type, new_offset,
1820                                  new_maybe_derived_type, otr_type))
1821     return false;
1822
1823   /* New speculation is a win in case we have no speculation or new
1824      speculation does not consider derivations.  */
1825   if (!speculative_outer_type
1826       || (speculative_maybe_derived_type
1827           && !new_maybe_derived_type))
1828     {
1829       speculative_outer_type = new_outer_type;
1830       speculative_offset = new_offset;
1831       speculative_maybe_derived_type = new_maybe_derived_type;
1832       return true;
1833     }
1834   else if (types_must_be_same_for_odr (speculative_outer_type,
1835                                        new_outer_type))
1836     {
1837       if (speculative_offset != new_offset)
1838         {
1839           /* OK we have two contexts that seems valid but they disagree,
1840              just give up.
1841
1842              This is not a lattice operation, so we may want to drop it later.  */
1843           if (dump_file && (dump_flags & TDF_DETAILS))
1844             fprintf (dump_file,
1845                      "Speculative outer types match, "
1846                      "offset mismatch -> invalid speculation\n");
1847           clear_speculation ();
1848           return true;
1849         }
1850       else
1851         {
1852           if (speculative_maybe_derived_type && !new_maybe_derived_type)
1853             {
1854               speculative_maybe_derived_type = false;
1855               return true;
1856             }
1857           else
1858             return false;
1859         }
1860     }
1861   /* Choose type that contains the other.  This one either contains the outer
1862      as a field (thus giving exactly one target) or is deeper in the type
1863      hiearchy.  */
1864   else if (speculative_outer_type
1865            && speculative_maybe_derived_type
1866            && (new_offset > speculative_offset
1867                || (new_offset == speculative_offset
1868                    && contains_type_p (new_outer_type,
1869                                        0, speculative_outer_type, false))))
1870     {
1871       tree old_outer_type = speculative_outer_type;
1872       HOST_WIDE_INT old_offset = speculative_offset;
1873       bool old_maybe_derived_type = speculative_maybe_derived_type;
1874
1875       speculative_outer_type = new_outer_type;
1876       speculative_offset = new_offset;
1877       speculative_maybe_derived_type = new_maybe_derived_type;
1878
1879       if (otr_type)
1880         restrict_to_inner_class (otr_type);
1881
1882       /* If the speculation turned out to make no sense, revert to sensible
1883          one.  */
1884       if (!speculative_outer_type)
1885         {
1886           speculative_outer_type = old_outer_type;
1887           speculative_offset = old_offset;
1888           speculative_maybe_derived_type = old_maybe_derived_type;
1889           return false;
1890         }
1891       return (old_offset != speculative_offset
1892               || old_maybe_derived_type != speculative_maybe_derived_type
1893               || types_must_be_same_for_odr (speculative_outer_type,
1894                                              new_outer_type));
1895     }
1896   return false;
1897 }
1898
1899 /* Make speculation less specific so
1900    NEW_OUTER_TYPE, NEW_OFFSET, NEW_MAYBE_DERIVED_TYPE is also included.
1901    If OTR_TYPE is set, assume the context is used with OTR_TYPE.  */
1902
1903 bool
1904 ipa_polymorphic_call_context::meet_speculation_with
1905    (tree new_outer_type, HOST_WIDE_INT new_offset, bool new_maybe_derived_type,
1906     tree otr_type)
1907 {
1908   if (!new_outer_type && speculative_outer_type)
1909     {
1910       clear_speculation ();
1911       return true;
1912     }
1913
1914   /* restrict_to_inner_class may eliminate wrong speculation making our job
1915      easeier.  */
1916   if (otr_type)
1917     restrict_to_inner_class (otr_type);
1918
1919   if (!speculative_outer_type
1920       || !speculation_consistent_p (speculative_outer_type,
1921                                     speculative_offset,
1922                                     speculative_maybe_derived_type,
1923                                     otr_type))
1924     return false;
1925
1926   if (!speculation_consistent_p (new_outer_type, new_offset,
1927                                  new_maybe_derived_type, otr_type))
1928     {
1929       clear_speculation ();
1930       return true;
1931     }
1932
1933   else if (types_must_be_same_for_odr (speculative_outer_type,
1934                                        new_outer_type))
1935     {
1936       if (speculative_offset != new_offset)
1937         {
1938           clear_speculation ();
1939           return true;
1940         }
1941       else
1942         {
1943           if (!speculative_maybe_derived_type && new_maybe_derived_type)
1944             {
1945               speculative_maybe_derived_type = true;
1946               return true;
1947             }
1948           else
1949             return false;
1950         }
1951     }
1952   /* See if one type contains the other as a field (not base).  */
1953   else if (contains_type_p (new_outer_type, new_offset - speculative_offset,
1954                             speculative_outer_type, false, false))
1955     return false;
1956   else if (contains_type_p (speculative_outer_type,
1957                             speculative_offset - new_offset,
1958                             new_outer_type, false, false))
1959     {
1960       speculative_outer_type = new_outer_type;
1961       speculative_offset = new_offset;
1962       speculative_maybe_derived_type = new_maybe_derived_type;
1963       return true;
1964     }
1965   /* See if OUTER_TYPE is base of CTX.OUTER_TYPE.  */
1966   else if (contains_type_p (new_outer_type,
1967                             new_offset - speculative_offset,
1968                             speculative_outer_type, false, true))
1969     {
1970       if (!speculative_maybe_derived_type)
1971         {
1972           speculative_maybe_derived_type = true;
1973           return true;
1974         }
1975       return false;
1976     }
1977   /* See if CTX.OUTER_TYPE is base of OUTER_TYPE.  */
1978   else if (contains_type_p (speculative_outer_type,
1979                             speculative_offset - new_offset, new_outer_type, false, true))
1980     {
1981       speculative_outer_type = new_outer_type;
1982       speculative_offset = new_offset;
1983       speculative_maybe_derived_type = true;
1984       return true;
1985     }
1986   else
1987     {
1988       if (dump_file && (dump_flags & TDF_DETAILS))
1989         fprintf (dump_file, "Giving up on speculative meet\n");
1990       clear_speculation ();
1991       return true;
1992     }
1993 }
1994
1995 /* Assume that both THIS and a given context is valid and strenghten THIS
1996    if possible.  Return true if any strenghtening was made.
1997    If actual type the context is being used in is known, OTR_TYPE should be
1998    set accordingly. This improves quality of combined result.  */
1999
2000 bool
2001 ipa_polymorphic_call_context::combine_with (ipa_polymorphic_call_context ctx,
2002                                             tree otr_type)
2003 {
2004   bool updated = false;
2005
2006   if (ctx.useless_p () || invalid)
2007     return false;
2008
2009   /* Restricting context to inner type makes merging easier, however do not
2010      do that unless we know how the context is used (OTR_TYPE is non-NULL)  */
2011   if (otr_type && !invalid && !ctx.invalid)
2012     {
2013       restrict_to_inner_class (otr_type);
2014       ctx.restrict_to_inner_class (otr_type);
2015       if(invalid)
2016         return false;
2017     }
2018
2019   if (dump_file && (dump_flags & TDF_DETAILS))
2020     {
2021       fprintf (dump_file, "Polymorphic call context combine:");
2022       dump (dump_file);
2023       fprintf (dump_file, "With context:                    ");
2024       ctx.dump (dump_file);
2025       if (otr_type)
2026         {
2027           fprintf (dump_file, "To be used with type:            ");
2028           print_generic_expr (dump_file, otr_type, TDF_SLIM);
2029           fprintf (dump_file, "\n");
2030         }
2031     }
2032
2033   /* If call is known to be invalid, we are done.  */
2034   if (ctx.invalid)
2035     {
2036       if (dump_file && (dump_flags & TDF_DETAILS))
2037         fprintf (dump_file, "-> Invalid context\n");
2038       goto invalidate;
2039     }
2040
2041   if (!ctx.outer_type)
2042     ;
2043   else if (!outer_type)
2044     {
2045       outer_type = ctx.outer_type;
2046       offset = ctx.offset;
2047       dynamic = ctx.dynamic;
2048       maybe_in_construction = ctx.maybe_in_construction;
2049       maybe_derived_type = ctx.maybe_derived_type;
2050       updated = true;
2051     }
2052   /* If types are known to be same, merging is quite easy.  */
2053   else if (types_must_be_same_for_odr (outer_type, ctx.outer_type))
2054     {
2055       if (offset != ctx.offset
2056           && TYPE_SIZE (outer_type)
2057           && TREE_CODE (TYPE_SIZE (outer_type)) == INTEGER_CST)
2058         {
2059           if (dump_file && (dump_flags & TDF_DETAILS))
2060             fprintf (dump_file, "Outer types match, offset mismatch -> invalid\n");
2061           clear_speculation ();
2062           clear_outer_type ();
2063           invalid = true;
2064           return true;
2065         }
2066       if (dump_file && (dump_flags & TDF_DETAILS))
2067         fprintf (dump_file, "Outer types match, merging flags\n");
2068       if (maybe_in_construction && !ctx.maybe_in_construction)
2069         {
2070           updated = true;
2071           maybe_in_construction = false;
2072         }
2073       if (maybe_derived_type && !ctx.maybe_derived_type)
2074         {
2075           updated = true;
2076           maybe_derived_type = false;
2077         }
2078       if (dynamic && !ctx.dynamic)
2079         {
2080           updated = true;
2081           dynamic = false;
2082         }
2083     }
2084   /* If we know the type precisely, there is not much to improve.  */
2085   else if (!maybe_derived_type && !maybe_in_construction
2086            && !ctx.maybe_derived_type && !ctx.maybe_in_construction)
2087     {
2088       /* It may be easy to check if second context permits the first
2089          and set INVALID otherwise.  This is not easy to do in general;
2090          contains_type_p may return false negatives for non-comparable
2091          types.  
2092
2093          If OTR_TYPE is known, we however can expect that
2094          restrict_to_inner_class should have discovered the same base
2095          type.  */
2096       if (otr_type && !ctx.maybe_in_construction && !ctx.maybe_derived_type)
2097         {
2098           if (dump_file && (dump_flags & TDF_DETAILS))
2099             fprintf (dump_file, "Contextes disagree -> invalid\n");
2100           goto invalidate;
2101         }
2102     }
2103   /* See if one type contains the other as a field (not base).
2104      In this case we want to choose the wider type, because it contains
2105      more information.  */
2106   else if (contains_type_p (ctx.outer_type, ctx.offset - offset,
2107                             outer_type, false, false))
2108     {
2109       if (dump_file && (dump_flags & TDF_DETAILS))
2110         fprintf (dump_file, "Second type contain the first as a field\n");
2111
2112       if (maybe_derived_type)
2113         {
2114           outer_type = ctx.outer_type;
2115           maybe_derived_type = ctx.maybe_derived_type;
2116           offset = ctx.offset;
2117           dynamic = ctx.dynamic;
2118           updated = true;
2119         }
2120
2121       /* If we do not know how the context is being used, we can
2122          not clear MAYBE_IN_CONSTRUCTION because it may be offseted
2123          to other component of OUTER_TYPE later and we know nothing
2124          about it.  */
2125       if (otr_type && maybe_in_construction
2126           && !ctx.maybe_in_construction)
2127         {
2128           maybe_in_construction = false;
2129           updated = true;
2130         }
2131     }
2132   else if (contains_type_p (outer_type, offset - ctx.offset,
2133                             ctx.outer_type, false, false))
2134     {
2135       if (dump_file && (dump_flags & TDF_DETAILS))
2136         fprintf (dump_file, "First type contain the second as a field\n");
2137
2138       if (otr_type && maybe_in_construction
2139           && !ctx.maybe_in_construction)
2140         {
2141           maybe_in_construction = false;
2142           updated = true;
2143         }
2144     }
2145   /* See if OUTER_TYPE is base of CTX.OUTER_TYPE.  */
2146   else if (contains_type_p (ctx.outer_type,
2147                             ctx.offset - offset, outer_type, false, true))
2148     {
2149       if (dump_file && (dump_flags & TDF_DETAILS))
2150         fprintf (dump_file, "First type is base of second\n");
2151       if (!maybe_derived_type)
2152         {
2153           if (!ctx.maybe_in_construction
2154               && types_odr_comparable (outer_type, ctx.outer_type))
2155             {
2156               if (dump_file && (dump_flags & TDF_DETAILS))
2157                 fprintf (dump_file, "Second context does not permit base -> invalid\n");
2158               goto invalidate;
2159             }
2160         }
2161       /* Pick variant deeper in the hiearchy.  */
2162       else
2163         {
2164           outer_type = ctx.outer_type;
2165           maybe_in_construction = ctx.maybe_in_construction;
2166           maybe_derived_type = ctx.maybe_derived_type;
2167           offset = ctx.offset;
2168           dynamic = ctx.dynamic;
2169           updated = true;
2170         }
2171     }
2172   /* See if CTX.OUTER_TYPE is base of OUTER_TYPE.  */
2173   else if (contains_type_p (outer_type,
2174                             offset - ctx.offset, ctx.outer_type, false, true))
2175     {
2176       if (dump_file && (dump_flags & TDF_DETAILS))
2177         fprintf (dump_file, "Second type is base of first\n");
2178       if (!ctx.maybe_derived_type)
2179         {
2180           if (!maybe_in_construction
2181               && types_odr_comparable (outer_type, ctx.outer_type))
2182             {
2183               if (dump_file && (dump_flags & TDF_DETAILS))
2184                 fprintf (dump_file, "First context does not permit base -> invalid\n");
2185               goto invalidate;
2186             }
2187           /* Pick the base type.  */
2188           else if (maybe_in_construction)
2189             {
2190               outer_type = ctx.outer_type;
2191               maybe_in_construction = ctx.maybe_in_construction;
2192               maybe_derived_type = ctx.maybe_derived_type;
2193               offset = ctx.offset;
2194               dynamic = ctx.dynamic;
2195               updated = true;
2196             }
2197         }
2198     }
2199   /* TODO handle merging using hiearchy. */
2200   else if (dump_file && (dump_flags & TDF_DETAILS))
2201     fprintf (dump_file, "Giving up on merge\n");
2202
2203   updated |= combine_speculation_with (ctx.speculative_outer_type,
2204                                        ctx.speculative_offset,
2205                                        ctx.speculative_maybe_derived_type,
2206                                        otr_type);
2207
2208   if (updated && dump_file && (dump_flags & TDF_DETAILS))
2209     {
2210       fprintf (dump_file, "Updated as:                      ");
2211       dump (dump_file);
2212       fprintf (dump_file, "\n");
2213     }
2214   return updated;
2215
2216 invalidate:
2217   invalid = true;
2218   clear_speculation ();
2219   clear_outer_type ();
2220   return true;
2221 }
2222
2223 /* Take non-speculative info, merge it with speculative and clear speculation.
2224    Used when we no longer manage to keep track of actual outer type, but we
2225    think it is still there.
2226
2227    If OTR_TYPE is set, the transformation can be done more effectively assuming
2228    that context is going to be used only that way.  */
2229
2230 void
2231 ipa_polymorphic_call_context::make_speculative (tree otr_type)
2232 {
2233   tree spec_outer_type = outer_type;
2234   HOST_WIDE_INT spec_offset = offset;
2235   bool spec_maybe_derived_type = maybe_derived_type;
2236
2237   if (invalid)
2238     {
2239       invalid = false;
2240       clear_outer_type ();
2241       clear_speculation ();
2242       return;
2243     }
2244   if (!outer_type)
2245     return;
2246   clear_outer_type ();
2247   combine_speculation_with (spec_outer_type, spec_offset,
2248                             spec_maybe_derived_type,
2249                             otr_type);
2250 }
2251
2252 /* Use when we can not track dynamic type change.  This speculatively assume
2253    type change is not happening.  */
2254
2255 void
2256 ipa_polymorphic_call_context::possible_dynamic_type_change (bool in_poly_cdtor,
2257                                                             tree otr_type)
2258 {
2259   if (dynamic)
2260     make_speculative (otr_type);
2261   else if (in_poly_cdtor)
2262     maybe_in_construction = true;
2263 }
2264
2265 /* Return TRUE if this context conveys the same information as OTHER.  */
2266
2267 bool
2268 ipa_polymorphic_call_context::equal_to
2269     (const ipa_polymorphic_call_context &x) const
2270 {
2271   if (useless_p ())
2272     return x.useless_p ();
2273   if (invalid)
2274     return x.invalid;
2275   if (x.useless_p () || x.invalid)
2276     return false;
2277
2278   if (outer_type)
2279     {
2280       if (!x.outer_type
2281           || !types_odr_comparable (outer_type, x.outer_type)
2282           || !types_same_for_odr (outer_type, x.outer_type)
2283           || offset != x.offset
2284           || maybe_in_construction != x.maybe_in_construction
2285           || maybe_derived_type != x.maybe_derived_type
2286           || dynamic != x.dynamic)
2287         return false;
2288     }
2289   else if (x.outer_type)
2290     return false;
2291
2292
2293   if (speculative_outer_type
2294       && speculation_consistent_p (speculative_outer_type, speculative_offset,
2295                                    speculative_maybe_derived_type, NULL_TREE))
2296     {
2297       if (!x.speculative_outer_type)
2298         return false;
2299
2300       if (!types_odr_comparable (speculative_outer_type,
2301                                  x.speculative_outer_type)
2302           || !types_same_for_odr  (speculative_outer_type,
2303                                    x.speculative_outer_type)
2304           || speculative_offset != x.speculative_offset
2305           || speculative_maybe_derived_type != x.speculative_maybe_derived_type)
2306         return false;
2307     }
2308   else if (x.speculative_outer_type
2309            && x.speculation_consistent_p (x.speculative_outer_type,
2310                                           x.speculative_offset,
2311                                           x.speculative_maybe_derived_type,
2312                                           NULL))
2313     return false;
2314
2315   return true;
2316 }
2317
2318 /* Modify context to be strictly less restrictive than CTX.  */
2319
2320 bool
2321 ipa_polymorphic_call_context::meet_with (ipa_polymorphic_call_context ctx,
2322                                          tree otr_type)
2323 {
2324   bool updated = false;
2325
2326   if (useless_p () || ctx.invalid)
2327     return false;
2328
2329   /* Restricting context to inner type makes merging easier, however do not
2330      do that unless we know how the context is used (OTR_TYPE is non-NULL)  */
2331   if (otr_type && !useless_p () && !ctx.useless_p ())
2332     {
2333       restrict_to_inner_class (otr_type);
2334       ctx.restrict_to_inner_class (otr_type);
2335       if(invalid)
2336         return false;
2337     }
2338
2339   if (equal_to (ctx))
2340     return false;
2341
2342   if (ctx.useless_p () || invalid)
2343     {
2344       *this = ctx;
2345       return true;
2346     }
2347
2348   if (dump_file && (dump_flags & TDF_DETAILS))
2349     {
2350       fprintf (dump_file, "Polymorphic call context meet:");
2351       dump (dump_file);
2352       fprintf (dump_file, "With context:                    ");
2353       ctx.dump (dump_file);
2354       if (otr_type)
2355         {
2356           fprintf (dump_file, "To be used with type:            ");
2357           print_generic_expr (dump_file, otr_type, TDF_SLIM);
2358           fprintf (dump_file, "\n");
2359         }
2360     }
2361
2362   if (!dynamic && ctx.dynamic)
2363     {
2364       dynamic = true;
2365       updated = true;
2366     }
2367
2368   /* If call is known to be invalid, we are done.  */
2369   if (!outer_type)
2370     ;
2371   else if (!ctx.outer_type)
2372     {
2373       clear_outer_type ();
2374       updated = true;
2375     }
2376   /* If types are known to be same, merging is quite easy.  */
2377   else if (types_must_be_same_for_odr (outer_type, ctx.outer_type))
2378     {
2379       if (offset != ctx.offset
2380           && TYPE_SIZE (outer_type)
2381           && TREE_CODE (TYPE_SIZE (outer_type)) == INTEGER_CST)
2382         {
2383           if (dump_file && (dump_flags & TDF_DETAILS))
2384             fprintf (dump_file, "Outer types match, offset mismatch -> clearing\n");
2385           clear_outer_type ();
2386           return true;
2387         }
2388       if (dump_file && (dump_flags & TDF_DETAILS))
2389         fprintf (dump_file, "Outer types match, merging flags\n");
2390       if (!maybe_in_construction && ctx.maybe_in_construction)
2391         {
2392           updated = true;
2393           maybe_in_construction = true;
2394         }
2395       if (!maybe_derived_type && ctx.maybe_derived_type)
2396         {
2397           updated = true;
2398           maybe_derived_type = true;
2399         }
2400       if (!dynamic && ctx.dynamic)
2401         {
2402           updated = true;
2403           dynamic = true;
2404         }
2405     }
2406   /* See if one type contains the other as a field (not base).  */
2407   else if (contains_type_p (ctx.outer_type, ctx.offset - offset,
2408                             outer_type, false, false))
2409     {
2410       if (dump_file && (dump_flags & TDF_DETAILS))
2411         fprintf (dump_file, "Second type contain the first as a field\n");
2412
2413       /* The second type is more specified, so we keep the first.
2414          We need to set DYNAMIC flag to avoid declaring context INVALID
2415          of OFFSET ends up being out of range.  */
2416       if (!dynamic
2417           && (ctx.dynamic
2418               || (!otr_type
2419                   && (!TYPE_SIZE (ctx.outer_type)
2420                       || !TYPE_SIZE (outer_type)
2421                       || !operand_equal_p (TYPE_SIZE (ctx.outer_type),
2422                                            TYPE_SIZE (outer_type), 0)))))
2423         {
2424           dynamic = true;
2425           updated = true;
2426         }
2427     }
2428   else if (contains_type_p (outer_type, offset - ctx.offset,
2429                             ctx.outer_type, false, false))
2430     {
2431       if (dump_file && (dump_flags & TDF_DETAILS))
2432         fprintf (dump_file, "First type contain the second as a field\n");
2433
2434       if (!dynamic
2435           && (ctx.dynamic
2436               || (!otr_type
2437                   && (!TYPE_SIZE (ctx.outer_type)
2438                       || !TYPE_SIZE (outer_type)
2439                       || !operand_equal_p (TYPE_SIZE (ctx.outer_type),
2440                                            TYPE_SIZE (outer_type), 0)))))
2441         dynamic = true;
2442       outer_type = ctx.outer_type;
2443       offset = ctx.offset;
2444       dynamic = ctx.dynamic;
2445       maybe_in_construction = ctx.maybe_in_construction;
2446       maybe_derived_type = ctx.maybe_derived_type;
2447       updated = true;
2448     }
2449   /* See if OUTER_TYPE is base of CTX.OUTER_TYPE.  */
2450   else if (contains_type_p (ctx.outer_type,
2451                             ctx.offset - offset, outer_type, false, true))
2452     {
2453       if (dump_file && (dump_flags & TDF_DETAILS))
2454         fprintf (dump_file, "First type is base of second\n");
2455       if (!maybe_derived_type)
2456         {
2457           maybe_derived_type = true;
2458           updated = true;
2459         }
2460       if (!maybe_in_construction && ctx.maybe_in_construction)
2461         {
2462           maybe_in_construction = true;
2463           updated = true;
2464         }
2465       if (!dynamic && ctx.dynamic)
2466         {
2467           dynamic = true;
2468           updated = true;
2469         }
2470     }
2471   /* See if CTX.OUTER_TYPE is base of OUTER_TYPE.  */
2472   else if (contains_type_p (outer_type,
2473                             offset - ctx.offset, ctx.outer_type, false, true))
2474     {
2475       if (dump_file && (dump_flags & TDF_DETAILS))
2476         fprintf (dump_file, "Second type is base of first\n");
2477       outer_type = ctx.outer_type;
2478       offset = ctx.offset;
2479       updated = true;
2480       if (!maybe_derived_type)
2481         maybe_derived_type = true;
2482       if (!maybe_in_construction && ctx.maybe_in_construction)
2483         maybe_in_construction = true;
2484       if (!dynamic && ctx.dynamic)
2485         dynamic = true;
2486     }
2487   /* TODO handle merging using hiearchy. */
2488   else
2489     {
2490       if (dump_file && (dump_flags & TDF_DETAILS))
2491         fprintf (dump_file, "Giving up on meet\n");
2492       clear_outer_type ();
2493       updated = true;
2494     }
2495
2496   updated |= meet_speculation_with (ctx.speculative_outer_type,
2497                                     ctx.speculative_offset,
2498                                     ctx.speculative_maybe_derived_type,
2499                                     otr_type);
2500
2501   if (updated && dump_file && (dump_flags & TDF_DETAILS))
2502     {
2503       fprintf (dump_file, "Updated as:                      ");
2504       dump (dump_file);
2505       fprintf (dump_file, "\n");
2506     }
2507   return updated;
2508 }