OSDN Git Service

2008-05-27 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-alias.c
1 /* Alias analysis for trees.
2    Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License 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 "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "basic-block.h"
30 #include "timevar.h"
31 #include "expr.h"
32 #include "ggc.h"
33 #include "langhooks.h"
34 #include "flags.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "tree-dump.h"
38 #include "tree-gimple.h"
39 #include "tree-flow.h"
40 #include "tree-inline.h"
41 #include "tree-pass.h"
42 #include "tree-ssa-structalias.h"
43 #include "convert.h"
44 #include "params.h"
45 #include "ipa-type-escape.h"
46 #include "vec.h"
47 #include "bitmap.h"
48 #include "vecprim.h"
49 #include "pointer-set.h"
50 #include "alloc-pool.h"
51
52 /* Broad overview of how aliasing works:
53    
54    First we compute points-to sets, which is done in
55    tree-ssa-structalias.c
56       
57    During points-to set constraint finding, a bunch of little bits of
58    information is collected.
59    This is not done because it is necessary for points-to, but because
60    points-to has to walk every statement anyway.  The function performing
61    this collecting is update_alias_info.
62
63    Bits update_alias_info collects include:
64    1. Directly escaping variables and variables whose value escapes
65    (using is_escape_site).  This is the set of variables and values that
66    escape prior to transitive closure of the clobbers.
67    2.  The set of variables dereferenced on the LHS (into
68    dereferenced_ptr_stores) 
69    3. The set of variables dereferenced on the RHS (into
70    dereferenced_ptr_loads) 
71    4. The set of all pointers we saw.
72    5. The number of loads and stores for each variable
73    6. The number of statements touching memory
74    7. The set of address taken variables.
75    
76    
77    #1 is computed by a combination of is_escape_site, and counting the
78    number of uses/deref operators.  This function properly accounts for
79    situations like &ptr->field, which is *not* a dereference.
80    
81    After points-to sets are computed, the sets themselves still
82    contain points-to specific variables, such as a variable that says
83    the pointer points to anything, a variable that says the pointer
84    points to readonly memory, etc.
85
86    These are eliminated in a later phase, as we will see.
87
88    The rest of the phases are located in tree-ssa-alias.c
89
90    The next phase after points-to set computation is called
91    "setup_pointers_and_addressables"
92
93    This pass does 3 main things:
94    
95    1. All variables that can have TREE_ADDRESSABLE removed safely (IE
96    non-globals whose address is not taken), have TREE_ADDRESSABLE
97    removed.
98    2. All variables that may be aliased (which is the set of addressable
99    variables and globals) at all, are marked for renaming, and have
100    symbol memory tags created for them.
101    3. All variables which are stored into have their SMT's added to
102    written vars. 
103
104
105    After this function is run, all variables that will ever have an
106    SMT, have one, though its aliases are not filled in.
107
108    The next phase is to compute flow-insensitive aliasing, which in
109    our case, is a misnomer.  it is really computing aliasing that
110    requires no transitive closure to be correct.  In particular, it
111    uses stack vs non-stack, TBAA, etc, to determine whether two
112    symbols could *ever* alias .  This phase works by going through all
113    the pointers we collected during update_alias_info, and for every
114    addressable variable in the program, seeing if they alias.  If so,
115    the addressable variable is added to the symbol memory tag for the
116    pointer.
117
118    As part of this, we handle symbol memory tags that conflict but
119    have no aliases in common, by forcing them to have a symbol in
120    common (through unioning alias sets or adding one as an alias of
121    the other), or by adding one as an alias of another.  The case of
122    conflicts with no aliases in common occurs mainly due to aliasing
123    we cannot see.  In particular, it generally means we have a load
124    through a pointer whose value came from outside the function.
125    Without an addressable symbol to point to, they would get the wrong
126    answer.
127
128    After flow insensitive aliasing is computed, we compute name tags
129    (called compute_flow_sensitive_info).  We walk each pointer we
130    collected and see if it has a usable points-to set.  If so, we
131    generate a name tag using that pointer, and make an alias bitmap for
132    it.  Name tags are shared between all things with the same alias
133    bitmap.  The alias bitmap will be translated from what points-to
134    computed.  In particular, the "anything" variable in points-to will be
135    transformed into a pruned set of SMT's and their aliases that
136    compute_flow_insensitive_aliasing computed.
137    Note that since 4.3, every pointer that points-to computed a solution for
138    will get a name tag (whereas before 4.3, only those whose set did
139    *not* include the anything variable would).  At the point where name
140    tags are all assigned, symbol memory tags are dead, and could be
141    deleted, *except* on global variables.  Global variables still use
142    symbol memory tags as of right now.
143
144    After name tags are computed, the set of clobbered variables is
145    transitively closed.  In particular, we compute the set of clobbered
146    variables based on the initial set of clobbers, plus the aliases of
147    pointers which either escape, or have their value escape.
148
149    After this, maybe_create_global_var is run, which handles a corner
150    case where we have no call clobbered variables, but have pure and
151    non-pure functions.
152    
153    Staring at this function, I now remember it is a hack for the fact
154    that we do not mark all globals in the program as call clobbered for a
155    function unless they are actually used in that function.  Instead,  we
156    only mark the set that is actually clobbered.  As a result, you can
157    end up with situations where you have no call clobbered vars set.
158    
159    After maybe_create_global_var, we set pointers with the REF_ALL flag
160    to have alias sets that include all clobbered
161    memory tags and variables.
162    
163    After this, memory partitioning is computed (by the function
164    compute_memory_partitions) and alias sets are reworked accordingly.
165
166    Lastly, we delete partitions with no symbols, and clean up after
167    ourselves.  */
168
169 /* Structure to map a variable to its alias set.  */
170 struct alias_map_d
171 {
172   /* Variable and its alias set.  */
173   tree var;
174   alias_set_type set;
175 };
176
177
178 /* Counters used to display statistics on alias analysis.  */
179 struct alias_stats_d
180 {
181   unsigned int alias_queries;
182   unsigned int alias_mayalias;
183   unsigned int alias_noalias;
184   unsigned int simple_queries;
185   unsigned int simple_resolved;
186   unsigned int tbaa_queries;
187   unsigned int tbaa_resolved;
188   unsigned int structnoaddress_queries;
189   unsigned int structnoaddress_resolved;
190 };
191
192
193 /* Local variables.  */
194 static struct alias_stats_d alias_stats;
195 static bitmap_obstack alias_bitmap_obstack;
196
197 /* Local functions.  */
198 static void compute_flow_insensitive_aliasing (struct alias_info *);
199 static void dump_alias_stats (FILE *);
200 static bool may_alias_p (tree, alias_set_type, tree, alias_set_type, bool);
201 static tree create_memory_tag (tree type, bool is_type_tag);
202 static tree get_smt_for (tree, struct alias_info *);
203 static tree get_nmt_for (tree);
204 static void add_may_alias (tree, tree);
205 static struct alias_info *init_alias_info (void);
206 static void delete_alias_info (struct alias_info *);
207 static void compute_flow_sensitive_aliasing (struct alias_info *);
208 static void setup_pointers_and_addressables (struct alias_info *);
209 static void create_global_var (void);
210 static void maybe_create_global_var (void);
211 static void set_pt_anything (tree);
212
213 void debug_mp_info (VEC(mem_sym_stats_t,heap) *);
214
215 static alloc_pool mem_sym_stats_pool;
216
217 /* Return memory reference stats for symbol VAR.  Create a new slot in
218    cfun->gimple_df->mem_sym_stats if needed.  */
219
220 static struct mem_sym_stats_d *
221 get_mem_sym_stats_for (tree var)
222 {
223   void **slot;
224   struct mem_sym_stats_d *stats;
225   struct pointer_map_t *map = gimple_mem_ref_stats (cfun)->mem_sym_stats;
226   
227   gcc_assert (map);
228
229   slot = pointer_map_insert (map, var);
230   if (*slot == NULL)
231     {
232       stats = pool_alloc (mem_sym_stats_pool);
233       memset (stats, 0, sizeof (*stats));
234       stats->var = var;
235       *slot = (void *) stats;
236     }
237   else
238     stats = (struct mem_sym_stats_d *) *slot;
239
240   return stats;
241 }
242
243
244 /* Return memory reference statistics for variable VAR in function FN.
245    This is computed by alias analysis, but it is not kept
246    incrementally up-to-date.  So, these stats are only accurate if
247    pass_may_alias has been run recently.  If no alias information
248    exists, this function returns NULL.  */
249
250 static mem_sym_stats_t
251 mem_sym_stats (struct function *fn, tree var)
252 {
253   void **slot;
254   struct pointer_map_t *stats_map = gimple_mem_ref_stats (fn)->mem_sym_stats;
255
256   if (stats_map == NULL)
257     return NULL;
258
259   slot = pointer_map_contains (stats_map, var);
260   if (slot == NULL)
261     return NULL;
262
263   return (mem_sym_stats_t) *slot;
264 }
265
266
267 /* Set MPT to be the memory partition associated with symbol SYM.  */
268
269 static inline void
270 set_memory_partition (tree sym, tree mpt)
271 {
272 #if defined ENABLE_CHECKING
273   if (mpt)
274     gcc_assert (TREE_CODE (mpt) == MEMORY_PARTITION_TAG
275                 && !is_gimple_reg (sym));
276 #endif
277
278   var_ann (sym)->mpt = mpt;
279   if (mpt)
280     {
281       if (MPT_SYMBOLS (mpt) == NULL)
282         MPT_SYMBOLS (mpt) = BITMAP_ALLOC (&alias_bitmap_obstack);
283
284       bitmap_set_bit (MPT_SYMBOLS (mpt), DECL_UID (sym));
285
286       /* MPT inherits the call-clobbering attributes from SYM.  */
287       if (is_call_clobbered (sym))
288         {
289           MTAG_GLOBAL (mpt) = 1;
290           mark_call_clobbered (mpt, ESCAPE_IS_GLOBAL);
291         }
292     }
293 }
294
295
296 /* Mark variable VAR as being non-addressable.  */
297
298 static void
299 mark_non_addressable (tree var)
300 {
301   tree mpt;
302
303   if (!TREE_ADDRESSABLE (var))
304     return;
305
306   mpt = memory_partition (var);
307
308   if (!MTAG_P (var))
309     var_ann (var)->call_clobbered = false;
310
311   bitmap_clear_bit (gimple_call_clobbered_vars (cfun), DECL_UID (var));
312   TREE_ADDRESSABLE (var) = 0;
313
314   if (mpt)
315     {
316       /* Note that it's possible for a symbol to have an associated
317          MPT and the MPT have a NULL empty set.  During
318          init_alias_info, all MPTs get their sets cleared out, but the
319          symbols still point to the old MPTs that used to hold them.
320          This is done so that compute_memory_partitions can now which
321          symbols are losing or changing partitions and mark them for
322          renaming.  */
323       if (MPT_SYMBOLS (mpt))
324         bitmap_clear_bit (MPT_SYMBOLS (mpt), DECL_UID (var));
325       set_memory_partition (var, NULL_TREE);
326     }
327 }
328
329
330 /* qsort comparison function to sort type/name tags by DECL_UID.  */
331
332 static int
333 sort_tags_by_id (const void *pa, const void *pb)
334 {
335   const_tree const a = *(const_tree const *)pa;
336   const_tree const b = *(const_tree const *)pb;
337  
338   return DECL_UID (a) - DECL_UID (b);
339 }
340
341 /* Initialize WORKLIST to contain those memory tags that are marked call
342    clobbered.  Initialized WORKLIST2 to contain the reasons these
343    memory tags escaped.  */
344
345 static void
346 init_transitive_clobber_worklist (VEC (tree, heap) **worklist,
347                                   VEC (int, heap) **worklist2,
348                                   bitmap on_worklist)
349 {
350   referenced_var_iterator rvi;
351   tree curr;
352
353   FOR_EACH_REFERENCED_VAR (curr, rvi)
354     {
355       if (MTAG_P (curr) && is_call_clobbered (curr))
356         {
357           VEC_safe_push (tree, heap, *worklist, curr);
358           VEC_safe_push (int, heap, *worklist2,
359                          var_ann (curr)->escape_mask);
360           bitmap_set_bit (on_worklist, DECL_UID (curr));
361         }
362     }
363 }
364
365 /* Add ALIAS to WORKLIST (and the reason for escaping REASON to WORKLIST2) if
366    ALIAS is not already marked call clobbered, and is a memory
367    tag.  */
368
369 static void
370 add_to_worklist (tree alias, VEC (tree, heap) **worklist,
371                  VEC (int, heap) **worklist2, int reason,
372                  bitmap on_worklist)
373 {
374   if (MTAG_P (alias) && !is_call_clobbered (alias)
375       && !bitmap_bit_p (on_worklist, DECL_UID (alias)))
376     {
377       VEC_safe_push (tree, heap, *worklist, alias);
378       VEC_safe_push (int, heap, *worklist2, reason);
379       bitmap_set_bit (on_worklist, DECL_UID (alias));
380     }
381 }
382
383 /* Mark aliases of TAG as call clobbered, and place any tags on the
384    alias list that were not already call clobbered on WORKLIST.  */
385
386 static void
387 mark_aliases_call_clobbered (tree tag, VEC (tree, heap) **worklist,
388                              VEC (int, heap) **worklist2, bitmap on_worklist)
389 {
390   bitmap aliases;
391   bitmap_iterator bi;
392   unsigned int i;
393   tree entry;
394   var_ann_t ta = var_ann (tag);
395
396   if (!MTAG_P (tag))
397     return;
398   aliases = may_aliases (tag);
399   if (!aliases)
400     return;
401
402   EXECUTE_IF_SET_IN_BITMAP (aliases, 0, i, bi)
403     {
404       entry = referenced_var (i);
405       /* If you clobber one part of a structure, you
406          clobber the entire thing.  While this does not make
407          the world a particularly nice place, it is necessary
408          in order to allow C/C++ tricks that involve
409          pointer arithmetic to work.  */
410       if (!unmodifiable_var_p (entry))
411         {
412           add_to_worklist (entry, worklist, worklist2, ta->escape_mask,
413                            on_worklist);
414           mark_call_clobbered (entry, ta->escape_mask);
415         }
416     }
417 }
418
419 /* Tags containing global vars need to be marked as global.
420    Tags containing call clobbered vars need to be marked as call
421    clobbered. */
422
423 static void
424 compute_tag_properties (void)
425 {
426   referenced_var_iterator rvi;
427   tree tag;
428   bool changed = true;
429   VEC (tree, heap) *taglist = NULL;
430
431   FOR_EACH_REFERENCED_VAR (tag, rvi)
432     {
433       if (!MTAG_P (tag))
434         continue;
435       VEC_safe_push (tree, heap, taglist, tag);
436     }
437
438   /* We sort the taglist by DECL_UID, for two reasons.
439      1. To get a sequential ordering to make the bitmap accesses
440      faster.
441      2. Because of the way we compute aliases, it's more likely that
442      an earlier tag is included in a later tag, and this will reduce
443      the number of iterations.
444
445      If we had a real tag graph, we would just topo-order it and be
446      done with it.  */
447   qsort (VEC_address (tree, taglist),
448          VEC_length (tree, taglist),
449          sizeof (tree),
450          sort_tags_by_id);
451
452   /* Go through each tag not marked as global, and if it aliases
453      global vars, mark it global. 
454      
455      If the tag contains call clobbered vars, mark it call
456      clobbered.  
457
458      This loop iterates because tags may appear in the may-aliases
459      list of other tags when we group.  */
460
461   while (changed)
462     {
463       unsigned int k;
464
465       changed = false;      
466       for (k = 0; VEC_iterate (tree, taglist, k, tag); k++)
467         {
468           bitmap ma;
469           bitmap_iterator bi;
470           unsigned int i;
471           tree entry;
472           bool tagcc = is_call_clobbered (tag);
473           bool tagglobal = MTAG_GLOBAL (tag);
474           
475           if (tagcc && tagglobal)
476             continue;
477           
478           ma = may_aliases (tag);
479           if (!ma)
480             continue;
481
482           EXECUTE_IF_SET_IN_BITMAP (ma, 0, i, bi)
483             {
484               entry = referenced_var (i);
485               /* Call clobbered entries cause the tag to be marked
486                  call clobbered.  */
487               if (!tagcc && is_call_clobbered (entry))
488                 {
489                   mark_call_clobbered (tag, var_ann (entry)->escape_mask);
490                   tagcc = true;
491                   changed = true;
492                 }
493
494               /* Global vars cause the tag to be marked global.  */
495               if (!tagglobal && is_global_var (entry))
496                 {
497                   MTAG_GLOBAL (tag) = true;
498                   changed = true;
499                   tagglobal = true;
500                 }
501
502               /* Early exit once both global and cc are set, since the
503                  loop can't do any more than that.  */
504               if (tagcc && tagglobal)
505                 break;
506             }
507         }
508     }
509   VEC_free (tree, heap, taglist);
510 }
511
512 /* Set up the initial variable clobbers and globalness.
513    When this function completes, only tags whose aliases need to be
514    clobbered will be set clobbered.  Tags clobbered because they   
515    contain call clobbered vars are handled in compute_tag_properties.  */
516
517 static void
518 set_initial_properties (struct alias_info *ai)
519 {
520   unsigned int i;
521   referenced_var_iterator rvi;
522   tree var;
523   tree ptr;
524
525   FOR_EACH_REFERENCED_VAR (var, rvi)
526     {
527       if (is_global_var (var))
528         {
529           if (!unmodifiable_var_p (var))
530             mark_call_clobbered (var, ESCAPE_IS_GLOBAL);
531         }
532       else if (TREE_CODE (var) == PARM_DECL
533                && gimple_default_def (cfun, var)
534                && POINTER_TYPE_P (TREE_TYPE (var)))
535         {
536           tree def = gimple_default_def (cfun, var);
537           get_ptr_info (def)->value_escapes_p = 1;
538           get_ptr_info (def)->escape_mask |= ESCAPE_IS_PARM;      
539         }
540     }
541
542   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
543     {
544       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
545       tree tag = symbol_mem_tag (SSA_NAME_VAR (ptr));
546       
547       if (pi->value_escapes_p)
548         {
549           /* If PTR escapes then its associated memory tags and
550              pointed-to variables are call-clobbered.  */
551           if (pi->name_mem_tag)
552             mark_call_clobbered (pi->name_mem_tag, pi->escape_mask);
553
554           if (tag)
555             mark_call_clobbered (tag, pi->escape_mask);
556
557           if (pi->pt_vars)
558             {
559               bitmap_iterator bi;
560               unsigned int j;         
561               EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
562                 {
563                   tree alias = referenced_var (j);
564
565                   /* If you clobber one part of a structure, you
566                      clobber the entire thing.  While this does not make
567                      the world a particularly nice place, it is necessary
568                      in order to allow C/C++ tricks that involve
569                      pointer arithmetic to work.  */
570                   if (!unmodifiable_var_p (alias))
571                     mark_call_clobbered (alias, pi->escape_mask);
572                 }
573             }
574           else if (pi->pt_anything)
575             {
576               bitmap_iterator bi;
577               unsigned int j;
578
579               /* If we do not have the points-to set filled out we
580                  still need to honor that this escaped pointer points
581                  to anything.  */
582               EXECUTE_IF_SET_IN_BITMAP (gimple_addressable_vars (cfun),
583                                         0, j, bi)
584                 {
585                   tree var = referenced_var (j);
586                   if (!unmodifiable_var_p (var))
587                     mark_call_clobbered (var, pi->escape_mask);
588                 }
589             }
590         }
591
592       /* If the name tag is call clobbered, so is the symbol tag
593          associated with the base VAR_DECL.  */
594       if (pi->name_mem_tag
595           && tag
596           && is_call_clobbered (pi->name_mem_tag))
597         mark_call_clobbered (tag, pi->escape_mask);
598
599       /* Name tags and symbol tags that we don't know where they point
600          to, might point to global memory, and thus, are clobbered.
601
602          FIXME:  This is not quite right.  They should only be
603          clobbered if value_escapes_p is true, regardless of whether
604          they point to global memory or not.
605          So removing this code and fixing all the bugs would be nice.
606          It is the cause of a bunch of clobbering.  */
607       if ((pi->pt_global_mem || pi->pt_anything) 
608           && pi->is_dereferenced && pi->name_mem_tag)
609         {
610           mark_call_clobbered (pi->name_mem_tag, ESCAPE_IS_GLOBAL);
611           MTAG_GLOBAL (pi->name_mem_tag) = true;
612         }
613       
614       if ((pi->pt_global_mem || pi->pt_anything) 
615           && pi->is_dereferenced
616           && tag)
617         {
618           mark_call_clobbered (tag, ESCAPE_IS_GLOBAL);
619           MTAG_GLOBAL (tag) = true;
620         }
621     }
622 }
623
624 /* Compute which variables need to be marked call clobbered because
625    their tag is call clobbered, and which tags need to be marked
626    global because they contain global variables.  */
627
628 static void
629 compute_call_clobbered (struct alias_info *ai)
630 {
631   VEC (tree, heap) *worklist = NULL;
632   VEC (int,heap) *worklist2 = NULL;
633   bitmap on_worklist;
634
635   timevar_push (TV_CALL_CLOBBER);
636   on_worklist = BITMAP_ALLOC (NULL);
637     
638   set_initial_properties (ai);
639   init_transitive_clobber_worklist (&worklist, &worklist2, on_worklist);
640   while (VEC_length (tree, worklist) != 0)
641     {
642       tree curr = VEC_pop (tree, worklist);
643       int reason = VEC_pop (int, worklist2);
644
645       bitmap_clear_bit (on_worklist, DECL_UID (curr));
646       mark_call_clobbered (curr, reason);
647       mark_aliases_call_clobbered (curr, &worklist, &worklist2, on_worklist);
648     }
649   VEC_free (tree, heap, worklist);
650   VEC_free (int, heap, worklist2);
651   BITMAP_FREE (on_worklist);
652   compute_tag_properties ();
653   timevar_pop (TV_CALL_CLOBBER);
654 }
655
656
657 /* Dump memory partition information to FILE.  */
658
659 static void
660 dump_memory_partitions (FILE *file)
661 {
662   unsigned i, npart;
663   unsigned long nsyms;
664   tree mpt;
665
666   fprintf (file, "\nMemory partitions\n\n");
667   for (i = 0, npart = 0, nsyms = 0;
668        VEC_iterate (tree, gimple_ssa_operands (cfun)->mpt_table, i, mpt);
669        i++)
670     {
671       if (mpt)
672         {
673           bitmap syms = MPT_SYMBOLS (mpt);
674           unsigned long n = (syms) ? bitmap_count_bits (syms) : 0;
675
676           fprintf (file, "#%u: ", i);
677           print_generic_expr (file, mpt, 0);
678           fprintf (file, ": %lu elements: ", n);
679           dump_decl_set (file, syms);
680           npart++;
681           nsyms += n;
682         }
683     }
684
685   fprintf (file, "\n%u memory partitions holding %lu symbols\n", npart, nsyms);
686 }
687
688
689 /* Dump memory partition information to stderr.  */
690
691 void
692 debug_memory_partitions (void)
693 {
694   dump_memory_partitions (stderr);
695 }
696
697
698 /* Return true if memory partitioning is required given the memory
699    reference estimates in STATS.  */
700
701 static inline bool
702 need_to_partition_p (struct mem_ref_stats_d *stats)
703 {
704   long num_vops = stats->num_vuses + stats->num_vdefs;
705   long avg_vops = CEIL (num_vops, stats->num_mem_stmts);
706   return (num_vops > (long) MAX_ALIASED_VOPS
707           && avg_vops > (long) AVG_ALIASED_VOPS);
708 }
709
710
711 /* Count the actual number of virtual operators in CFUN.  Note that
712    this is only meaningful after virtual operands have been populated,
713    so it should be invoked at the end of compute_may_aliases.
714
715    The number of virtual operators are stored in *NUM_VDEFS_P and
716    *NUM_VUSES_P, the number of partitioned symbols in
717    *NUM_PARTITIONED_P and the number of unpartitioned symbols in
718    *NUM_UNPARTITIONED_P.
719
720    If any of these pointers is NULL the corresponding count is not
721    computed.  */
722
723 static void
724 count_mem_refs (long *num_vuses_p, long *num_vdefs_p,
725                 long *num_partitioned_p, long *num_unpartitioned_p)
726 {
727   block_stmt_iterator bsi;
728   basic_block bb;
729   long num_vdefs, num_vuses, num_partitioned, num_unpartitioned;
730   referenced_var_iterator rvi;
731   tree sym;
732
733   num_vuses = num_vdefs = num_partitioned = num_unpartitioned = 0;
734
735   if (num_vuses_p || num_vdefs_p)
736     FOR_EACH_BB (bb)
737       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
738         {
739           tree stmt = bsi_stmt (bsi);
740           if (stmt_references_memory_p (stmt))
741             {
742               num_vuses += NUM_SSA_OPERANDS (stmt, SSA_OP_VUSE);
743               num_vdefs += NUM_SSA_OPERANDS (stmt, SSA_OP_VDEF);
744             }
745         }
746
747   if (num_partitioned_p || num_unpartitioned_p)
748     FOR_EACH_REFERENCED_VAR (sym, rvi)
749       {
750         if (is_gimple_reg (sym))
751           continue;
752
753         if (memory_partition (sym))
754           num_partitioned++;
755         else
756           num_unpartitioned++;
757       }
758
759   if (num_vdefs_p)
760     *num_vdefs_p = num_vdefs;
761
762   if (num_vuses_p)
763     *num_vuses_p = num_vuses;
764
765   if (num_partitioned_p)
766     *num_partitioned_p = num_partitioned;
767
768   if (num_unpartitioned_p)
769     *num_unpartitioned_p = num_unpartitioned;
770 }
771
772
773 /* The list is sorted by increasing partitioning score (PSCORE).
774    This score is computed such that symbols with high scores are
775    those that are least likely to be partitioned.  Given a symbol
776    MP->VAR, PSCORE(S) is the result of the following weighted sum
777
778    PSCORE(S) =   FW * 64 + FR * 32
779                + DW * 16 + DR *  8 
780                + IW *  4 + IR *  2
781                + NO_ALIAS
782
783    where
784
785    FW           Execution frequency of writes to S
786    FR           Execution frequency of reads from S
787    DW           Number of direct writes to S
788    DR           Number of direct reads from S
789    IW           Number of indirect writes to S
790    IR           Number of indirect reads from S
791    NO_ALIAS     State of the NO_ALIAS* flags
792
793    The basic idea here is that symbols that are frequently
794    written-to in hot paths of the code are the last to be considered
795    for partitioning.  */
796
797 static inline long
798 mem_sym_score (mem_sym_stats_t mp)
799 {
800   return mp->frequency_writes * 64 + mp->frequency_reads * 32
801          + mp->num_direct_writes * 16 + mp->num_direct_reads * 8
802          + mp->num_indirect_writes * 4 + mp->num_indirect_reads * 2
803          + var_ann (mp->var)->noalias_state;
804 }
805
806
807 /* Dump memory reference stats for function CFUN to FILE.  */
808
809 void
810 dump_mem_ref_stats (FILE *file)
811 {
812   long actual_num_vuses, actual_num_vdefs;
813   long num_partitioned, num_unpartitioned;
814   struct mem_ref_stats_d *stats;
815   
816   stats = gimple_mem_ref_stats (cfun);
817
818   count_mem_refs (&actual_num_vuses, &actual_num_vdefs, &num_partitioned,
819                   &num_unpartitioned);
820
821   fprintf (file, "\nMemory reference statistics for %s\n\n", 
822            lang_hooks.decl_printable_name (current_function_decl, 2));
823
824   fprintf (file, "Number of memory statements:     %ld\n",
825            stats->num_mem_stmts);
826   fprintf (file, "Number of call sites:            %ld\n",
827            stats->num_call_sites);
828   fprintf (file, "Number of pure/const call sites: %ld\n",
829            stats->num_pure_const_call_sites);
830   fprintf (file, "Number of asm sites:             %ld\n",
831            stats->num_asm_sites);
832   fprintf (file, "Estimated number of loads:       %ld (%ld/stmt)\n",
833            stats->num_vuses,
834            (stats->num_mem_stmts)
835            ? CEIL (stats->num_vuses, stats->num_mem_stmts)
836            : 0);
837   fprintf (file, "Actual number of loads:          %ld (%ld/stmt)\n",
838            actual_num_vuses, 
839            (stats->num_mem_stmts)
840            ? CEIL (actual_num_vuses, stats->num_mem_stmts)
841            : 0);
842
843   if (actual_num_vuses > stats->num_vuses + (stats->num_vuses / 25))
844     fprintf (file, "\t(warning: estimation is lower by more than 25%%)\n");
845
846   fprintf (file, "Estimated number of stores:      %ld (%ld/stmt)\n",
847            stats->num_vdefs,
848            (stats->num_mem_stmts)
849            ? CEIL (stats->num_vdefs, stats->num_mem_stmts)
850            : 0);
851   fprintf (file, "Actual number of stores:         %ld (%ld/stmt)\n",
852            actual_num_vdefs, 
853            (stats->num_mem_stmts)
854            ? CEIL (actual_num_vdefs, stats->num_mem_stmts)
855            : 0);
856
857   if (actual_num_vdefs > stats->num_vdefs + (stats->num_vdefs / 25))
858     fprintf (file, "\t(warning: estimation is lower by more than 25%%)\n");
859
860   fprintf (file, "Partitioning thresholds:         MAX = %d   AVG = %d "
861            "(%sNEED TO PARTITION)\n", MAX_ALIASED_VOPS, AVG_ALIASED_VOPS,
862            stats->num_mem_stmts && need_to_partition_p (stats) ? "" : "NO ");
863   fprintf (file, "Number of partitioned symbols:   %ld\n", num_partitioned);
864   fprintf (file, "Number of unpartitioned symbols: %ld\n", num_unpartitioned);
865 }
866
867
868 /* Dump memory reference stats for function FN to stderr.  */
869
870 void
871 debug_mem_ref_stats (void)
872 {
873   dump_mem_ref_stats (stderr);
874 }
875
876
877 /* Dump memory reference stats for variable VAR to FILE.  */
878
879 static void
880 dump_mem_sym_stats (FILE *file, tree var)
881 {
882   mem_sym_stats_t stats = mem_sym_stats (cfun, var);
883
884   if (stats == NULL)
885     return;
886
887   fprintf (file, "read frequency: %6ld, write frequency: %6ld, "
888            "direct reads: %3ld, direct writes: %3ld, "
889            "indirect reads: %4ld, indirect writes: %4ld, symbol: ",
890            stats->frequency_reads, stats->frequency_writes,
891            stats->num_direct_reads, stats->num_direct_writes,
892            stats->num_indirect_reads, stats->num_indirect_writes);
893   print_generic_expr (file, stats->var, 0);
894   fprintf (file, ", tags: ");
895   dump_decl_set (file, stats->parent_tags);
896 }
897
898
899 /* Dump memory reference stats for variable VAR to stderr.  */
900
901 void
902 debug_mem_sym_stats (tree var)
903 {
904   dump_mem_sym_stats (stderr, var);
905 }
906
907 /* Dump memory reference stats for variable VAR to FILE.  For use
908    of tree-dfa.c:dump_variable.  */
909
910 void
911 dump_mem_sym_stats_for_var (FILE *file, tree var)
912 {
913   mem_sym_stats_t stats = mem_sym_stats (cfun, var);
914
915   if (stats == NULL)
916     return;
917
918   fprintf (file, ", score: %ld", mem_sym_score (stats));
919   fprintf (file, ", direct reads: %ld", stats->num_direct_reads);
920   fprintf (file, ", direct writes: %ld", stats->num_direct_writes);
921   fprintf (file, ", indirect reads: %ld", stats->num_indirect_reads);
922   fprintf (file, ", indirect writes: %ld", stats->num_indirect_writes);
923 }
924
925 /* Dump memory reference stats for all memory symbols to FILE.  */
926
927 static void
928 dump_all_mem_sym_stats (FILE *file)
929 {
930   referenced_var_iterator rvi;
931   tree sym;
932
933   FOR_EACH_REFERENCED_VAR (sym, rvi)
934     {
935       if (is_gimple_reg (sym))
936         continue;
937
938       dump_mem_sym_stats (file, sym);
939     }
940 }
941
942
943 /* Dump memory reference stats for all memory symbols to stderr.  */
944
945 void
946 debug_all_mem_sym_stats (void)
947 {
948   dump_all_mem_sym_stats (stderr);
949 }
950
951
952 /* Dump the MP_INFO array to FILE.  */
953
954 static void
955 dump_mp_info (FILE *file, VEC(mem_sym_stats_t,heap) *mp_info)
956 {
957   unsigned i;
958   mem_sym_stats_t mp_p;
959
960   for (i = 0; VEC_iterate (mem_sym_stats_t, mp_info, i, mp_p); i++)
961     if (!mp_p->partitioned_p)
962       dump_mem_sym_stats (file, mp_p->var);
963 }
964
965
966 /* Dump the MP_INFO array to stderr.  */
967
968 void
969 debug_mp_info (VEC(mem_sym_stats_t,heap) *mp_info)
970 {
971   dump_mp_info (stderr, mp_info);
972 }
973
974
975 /* Update memory reference stats for symbol VAR in statement STMT.
976    NUM_DIRECT_READS and NUM_DIRECT_WRITES specify the number of times
977    that VAR is read/written in STMT (indirect reads/writes are not
978    recorded by this function, see compute_memory_partitions).  */
979
980 void
981 update_mem_sym_stats_from_stmt (tree var, tree stmt, long num_direct_reads,
982                                 long num_direct_writes)
983 {
984   mem_sym_stats_t stats;
985
986   gcc_assert (num_direct_reads >= 0 && num_direct_writes >= 0);
987
988   stats = get_mem_sym_stats_for (var);
989
990   stats->num_direct_reads += num_direct_reads;
991   stats->frequency_reads += ((long) bb_for_stmt (stmt)->frequency
992                              * num_direct_reads);
993
994   stats->num_direct_writes += num_direct_writes;
995   stats->frequency_writes += ((long) bb_for_stmt (stmt)->frequency
996                               * num_direct_writes);
997 }
998
999
1000 /* Given two MP_INFO entries MP1 and MP2, return -1 if MP1->VAR should
1001    be partitioned before MP2->VAR, 0 if they are the same or 1 if
1002    MP1->VAR should be partitioned after MP2->VAR.  */
1003
1004 static inline int
1005 compare_mp_info_entries (mem_sym_stats_t mp1, mem_sym_stats_t mp2)
1006 {
1007   long pscore1 = mem_sym_score (mp1);
1008   long pscore2 = mem_sym_score (mp2);
1009
1010   if (pscore1 < pscore2)
1011     return -1;
1012   else if (pscore1 > pscore2)
1013     return 1;
1014   else
1015     return DECL_UID (mp1->var) - DECL_UID (mp2->var);
1016 }
1017
1018
1019 /* Comparison routine for qsort.  The list is sorted by increasing
1020    partitioning score (PSCORE).  This score is computed such that
1021    symbols with high scores are those that are least likely to be
1022    partitioned.  */
1023
1024 static int
1025 mp_info_cmp (const void *p, const void *q)
1026 {
1027   mem_sym_stats_t e1 = *((const mem_sym_stats_t *) p);
1028   mem_sym_stats_t e2 = *((const mem_sym_stats_t *) q);
1029   return compare_mp_info_entries (e1, e2);
1030 }
1031
1032
1033 /* Sort the array of reference counts used to compute memory partitions.
1034    Elements are sorted in ascending order of execution frequency and 
1035    descending order of virtual operators needed.  */
1036
1037 static inline void
1038 sort_mp_info (VEC(mem_sym_stats_t,heap) *list)
1039 {
1040   unsigned num = VEC_length (mem_sym_stats_t, list);
1041
1042   if (num < 2)
1043     return;
1044
1045   if (num == 2)
1046     {
1047       if (compare_mp_info_entries (VEC_index (mem_sym_stats_t, list, 0),
1048                                    VEC_index (mem_sym_stats_t, list, 1)) > 0)
1049         {  
1050           /* Swap elements if they are in the wrong order.  */
1051           mem_sym_stats_t tmp = VEC_index (mem_sym_stats_t, list, 0);
1052           VEC_replace (mem_sym_stats_t, list, 0,
1053                        VEC_index (mem_sym_stats_t, list, 1));
1054           VEC_replace (mem_sym_stats_t, list, 1, tmp);
1055         }
1056
1057       return;
1058     }
1059
1060   /* There are 3 or more elements, call qsort.  */
1061   qsort (VEC_address (mem_sym_stats_t, list),
1062          VEC_length (mem_sym_stats_t, list), 
1063          sizeof (mem_sym_stats_t),
1064          mp_info_cmp);
1065 }
1066
1067
1068 /* Return the memory partition tag (MPT) associated with memory
1069    symbol SYM.  */
1070
1071 static tree
1072 get_mpt_for (tree sym)
1073 {
1074   tree mpt;
1075
1076   /* Don't create a new tag unnecessarily.  */
1077   mpt = memory_partition (sym);
1078   if (mpt == NULL_TREE)
1079     {
1080       mpt = create_tag_raw (MEMORY_PARTITION_TAG, TREE_TYPE (sym), "MPT");
1081       TREE_ADDRESSABLE (mpt) = 0;
1082       add_referenced_var (mpt);
1083       VEC_safe_push (tree, heap, gimple_ssa_operands (cfun)->mpt_table, mpt);
1084       gcc_assert (MPT_SYMBOLS (mpt) == NULL);
1085       set_memory_partition (sym, mpt);
1086     }
1087
1088   return mpt;
1089 }
1090
1091
1092 /* Add MP_P->VAR to a memory partition and return the partition.  */
1093
1094 static tree
1095 find_partition_for (mem_sym_stats_t mp_p)
1096 {
1097   unsigned i;
1098   VEC(tree,heap) *mpt_table;
1099   tree mpt;
1100
1101   mpt_table = gimple_ssa_operands (cfun)->mpt_table;
1102   mpt = NULL_TREE;
1103
1104   /* Find an existing partition for MP_P->VAR.  */
1105   for (i = 0; VEC_iterate (tree, mpt_table, i, mpt); i++)
1106     {
1107       mem_sym_stats_t mpt_stats;
1108
1109       /* If MPT does not have any symbols yet, use it.  */
1110       if (MPT_SYMBOLS (mpt) == NULL)
1111         break;
1112
1113       /* Otherwise, see if MPT has common parent tags with MP_P->VAR,
1114          but avoid grouping clobbered variables with non-clobbered
1115          variables (otherwise, this tends to creates a single memory
1116          partition because other call-clobbered variables may have
1117          common parent tags with non-clobbered ones).  */
1118       mpt_stats = get_mem_sym_stats_for (mpt);
1119       if (mp_p->parent_tags
1120           && mpt_stats->parent_tags
1121           && is_call_clobbered (mpt) == is_call_clobbered (mp_p->var)
1122           && bitmap_intersect_p (mpt_stats->parent_tags, mp_p->parent_tags))
1123         break;
1124
1125       /* If no common parent tags are found, see if both MPT and
1126          MP_P->VAR are call-clobbered.  */
1127       if (is_call_clobbered (mpt) && is_call_clobbered (mp_p->var))
1128         break;
1129     }
1130
1131   if (mpt == NULL_TREE)
1132     mpt = get_mpt_for (mp_p->var);
1133   else
1134     set_memory_partition (mp_p->var, mpt);
1135
1136   mp_p->partitioned_p = true;
1137
1138   mark_sym_for_renaming (mp_p->var);
1139   mark_sym_for_renaming (mpt);
1140
1141   return mpt;
1142 }
1143
1144
1145 /* Rewrite the alias set for TAG to use the newly created partitions.
1146    If TAG is NULL, rewrite the set of call-clobbered variables.
1147    NEW_ALIASES is a scratch bitmap to build the new set of aliases for
1148    TAG.  */
1149
1150 static void
1151 rewrite_alias_set_for (tree tag, bitmap new_aliases)
1152 {
1153   bitmap_iterator bi;
1154   unsigned i;
1155   tree mpt, sym;
1156
1157   EXECUTE_IF_SET_IN_BITMAP (MTAG_ALIASES (tag), 0, i, bi)
1158     {
1159       sym = referenced_var (i);
1160       mpt = memory_partition (sym);
1161       if (mpt)
1162         bitmap_set_bit (new_aliases, DECL_UID (mpt));
1163       else
1164         bitmap_set_bit (new_aliases, DECL_UID (sym));
1165     }
1166
1167   /* Rebuild the may-alias array for TAG.  */
1168   bitmap_copy (MTAG_ALIASES (tag), new_aliases);
1169 }
1170
1171
1172 /* Determine how many virtual operands can be saved by partitioning
1173    MP_P->VAR into MPT.  When a symbol S is thrown inside a partition
1174    P, every virtual operand that used to reference S will now
1175    reference P.  Whether it reduces the number of virtual operands
1176    depends on:
1177
1178    1- Direct references to S are never saved.  Instead of the virtual
1179       operand to S, we will now have a virtual operand to P.
1180
1181    2- Indirect references to S are reduced only for those memory tags
1182       holding S that already had other symbols partitioned into P.
1183       For instance, if a memory tag T has the alias set { a b S c },
1184       the first time we partition S into P, the alias set will become
1185       { a b P c }, so no virtual operands will be saved. However, if
1186       we now partition symbol 'c' into P, then the alias set for T
1187       will become { a b P }, so we will be saving one virtual operand
1188       for every indirect reference to 'c'.
1189
1190    3- Is S is call-clobbered, we save as many virtual operands as
1191       call/asm sites exist in the code, but only if other
1192       call-clobbered symbols have been grouped into P.  The first
1193       call-clobbered symbol that we group does not produce any
1194       savings.
1195
1196    MEM_REF_STATS points to CFUN's memory reference information.  */
1197
1198 static void
1199 estimate_vop_reduction (struct mem_ref_stats_d *mem_ref_stats,
1200                         mem_sym_stats_t mp_p, tree mpt)
1201 {
1202   unsigned i;
1203   bitmap_iterator bi;
1204   mem_sym_stats_t mpt_stats;
1205
1206   /* We should only get symbols with indirect references here.  */
1207   gcc_assert (mp_p->num_indirect_reads > 0 || mp_p->num_indirect_writes > 0);
1208
1209   /* Note that the only statistics we keep for MPT is the set of
1210      parent tags to know which memory tags have had alias members
1211      partitioned, and the indicator has_call_clobbered_vars.
1212      Reference counts are not important for MPT.  */
1213   mpt_stats = get_mem_sym_stats_for (mpt);
1214
1215   /* Traverse all the parent tags for MP_P->VAR.  For every tag T, if
1216      partition P is already grouping aliases of T, then reduce the
1217      number of virtual operands by the number of direct references
1218      to T.  */
1219   if (mp_p->parent_tags)
1220     {
1221       if (mpt_stats->parent_tags == NULL)
1222         mpt_stats->parent_tags = BITMAP_ALLOC (&alias_bitmap_obstack);
1223
1224       EXECUTE_IF_SET_IN_BITMAP (mp_p->parent_tags, 0, i, bi)
1225         {
1226           if (bitmap_bit_p (mpt_stats->parent_tags, i))
1227             {
1228               /* Partition MPT is already partitioning symbols in the
1229                  alias set for TAG.  This means that we are now saving
1230                  1 virtual operand for every direct reference to TAG.  */
1231               tree tag = referenced_var (i);
1232               mem_sym_stats_t tag_stats = mem_sym_stats (cfun, tag);
1233               mem_ref_stats->num_vuses -= tag_stats->num_direct_reads;
1234               mem_ref_stats->num_vdefs -= tag_stats->num_direct_writes;
1235             }
1236           else
1237             {
1238               /* This is the first symbol in tag I's alias set that is
1239                  being grouped under MPT.  We will not save any
1240                  virtual operands this time, but record that MPT is
1241                  grouping a symbol from TAG's alias set so that the
1242                  next time we get the savings.  */
1243               bitmap_set_bit (mpt_stats->parent_tags, i);
1244             }
1245         }
1246     }
1247
1248   /* If MP_P->VAR is call-clobbered, and MPT is already grouping
1249      call-clobbered symbols, then we will save as many virtual
1250      operands as asm/call sites there are.  */
1251   if (is_call_clobbered (mp_p->var))
1252     {
1253       if (mpt_stats->has_call_clobbered_vars)
1254         mem_ref_stats->num_vdefs -= mem_ref_stats->num_call_sites
1255                                     + mem_ref_stats->num_asm_sites;
1256       else
1257         mpt_stats->has_call_clobbered_vars = true;
1258     }
1259 }
1260
1261
1262 /* Helper for compute_memory_partitions.  Transfer reference counts
1263    from pointers to their pointed-to sets.  Counters for pointers were
1264    computed by update_alias_info.  MEM_REF_STATS points to CFUN's
1265    memory reference information.  */
1266
1267 static void
1268 update_reference_counts (struct mem_ref_stats_d *mem_ref_stats)
1269 {
1270   unsigned i;
1271   bitmap_iterator bi;
1272   mem_sym_stats_t sym_stats;
1273
1274   for (i = 1; i < num_ssa_names; i++)
1275     {
1276       tree ptr;
1277       struct ptr_info_def *pi;
1278
1279       ptr = ssa_name (i);
1280       if (ptr
1281           && POINTER_TYPE_P (TREE_TYPE (ptr))
1282           && (pi = SSA_NAME_PTR_INFO (ptr)) != NULL
1283           && pi->is_dereferenced)
1284         {
1285           unsigned j;
1286           bitmap_iterator bj;
1287           tree tag;
1288           mem_sym_stats_t ptr_stats, tag_stats;
1289
1290           /* If PTR has flow-sensitive points-to information, use
1291              PTR's name tag, otherwise use the symbol tag associated
1292              with PTR's symbol.  */
1293           if (pi->name_mem_tag)
1294             tag = pi->name_mem_tag;
1295           else
1296             tag = symbol_mem_tag (SSA_NAME_VAR (ptr));
1297
1298           ptr_stats = get_mem_sym_stats_for (ptr);
1299           tag_stats = get_mem_sym_stats_for (tag);
1300
1301           /* TAG has as many direct references as dereferences we
1302              found for its parent pointer.  */
1303           tag_stats->num_direct_reads += ptr_stats->num_direct_reads;
1304           tag_stats->num_direct_writes += ptr_stats->num_direct_writes;
1305
1306           /* All the dereferences of pointer PTR are considered direct
1307              references to PTR's memory tag (TAG).  In turn,
1308              references to TAG will become virtual operands for every
1309              symbol in TAG's alias set.  So, for every symbol ALIAS in
1310              TAG's alias set, add as many indirect references to ALIAS
1311              as direct references there are for TAG.  */
1312           if (MTAG_ALIASES (tag))
1313             EXECUTE_IF_SET_IN_BITMAP (MTAG_ALIASES (tag), 0, j, bj)
1314               {
1315                 tree alias = referenced_var (j);
1316                 sym_stats = get_mem_sym_stats_for (alias);
1317
1318                 /* All the direct references to TAG are indirect references
1319                    to ALIAS.  */
1320                 sym_stats->num_indirect_reads += ptr_stats->num_direct_reads;
1321                 sym_stats->num_indirect_writes += ptr_stats->num_direct_writes;
1322                 sym_stats->frequency_reads += ptr_stats->frequency_reads;
1323                 sym_stats->frequency_writes += ptr_stats->frequency_writes;
1324
1325                 /* Indicate that TAG is one of ALIAS's parent tags.  */
1326                 if (sym_stats->parent_tags == NULL)
1327                   sym_stats->parent_tags = BITMAP_ALLOC (&alias_bitmap_obstack);
1328                 bitmap_set_bit (sym_stats->parent_tags, DECL_UID (tag));
1329               }
1330         }
1331     }
1332
1333   /* Call-clobbered symbols are indirectly written at every
1334      call/asm site.  */
1335   EXECUTE_IF_SET_IN_BITMAP (gimple_call_clobbered_vars (cfun), 0, i, bi)
1336     {
1337       tree sym = referenced_var (i);
1338       sym_stats = get_mem_sym_stats_for (sym);
1339       sym_stats->num_indirect_writes += mem_ref_stats->num_call_sites
1340                                         + mem_ref_stats->num_asm_sites;
1341     }
1342
1343   /* Addressable symbols are indirectly written at some ASM sites.
1344      Since only ASM sites that clobber memory actually affect
1345      addressable symbols, this is an over-estimation.  */
1346   EXECUTE_IF_SET_IN_BITMAP (gimple_addressable_vars (cfun), 0, i, bi)
1347     {
1348       tree sym = referenced_var (i);
1349       sym_stats = get_mem_sym_stats_for (sym);
1350       sym_stats->num_indirect_writes += mem_ref_stats->num_asm_sites;
1351     }
1352 }
1353
1354
1355 /* Helper for compute_memory_partitions.  Add all memory symbols to
1356    *MP_INFO_P and compute the initial estimate for the total number of
1357    virtual operands needed.  MEM_REF_STATS points to CFUN's memory
1358    reference information.  On exit, *TAGS_P will contain the list of
1359    memory tags whose alias set need to be rewritten after
1360    partitioning.  */
1361
1362 static void
1363 build_mp_info (struct mem_ref_stats_d *mem_ref_stats,
1364                VEC(mem_sym_stats_t,heap) **mp_info_p,
1365                VEC(tree,heap) **tags_p)
1366 {
1367   tree var;
1368   referenced_var_iterator rvi;
1369
1370   FOR_EACH_REFERENCED_VAR (var, rvi)
1371     {
1372       mem_sym_stats_t sym_stats;
1373       tree old_mpt;
1374
1375       /* We are only interested in memory symbols other than MPTs.  */
1376       if (is_gimple_reg (var) || TREE_CODE (var) == MEMORY_PARTITION_TAG)
1377         continue;
1378
1379       /* Collect memory tags into the TAGS array so that we can
1380          rewrite their alias sets after partitioning.  */
1381       if (MTAG_P (var) && MTAG_ALIASES (var))
1382         VEC_safe_push (tree, heap, *tags_p, var);
1383
1384       /* Since we are going to re-compute partitions, any symbols that
1385          used to belong to a partition must be detached from it and
1386          marked for renaming.  */
1387       if ((old_mpt = memory_partition (var)) != NULL)
1388         {
1389           mark_sym_for_renaming (old_mpt);
1390           set_memory_partition (var, NULL_TREE);
1391           mark_sym_for_renaming (var);
1392         }
1393
1394       sym_stats = get_mem_sym_stats_for (var);
1395
1396       /* Add VAR's reference info to MP_INFO.  Note that the only
1397          symbols that make sense to partition are those that have
1398          indirect references.  If a symbol S is always directly
1399          referenced, partitioning it will not reduce the number of
1400          virtual operators.  The only symbols that are profitable to
1401          partition are those that belong to alias sets and/or are
1402          call-clobbered.  */
1403       if (sym_stats->num_indirect_reads > 0
1404           || sym_stats->num_indirect_writes > 0)
1405         VEC_safe_push (mem_sym_stats_t, heap, *mp_info_p, sym_stats);
1406
1407       /* Update the number of estimated VOPS.  Note that direct
1408          references to memory tags are always counted as indirect
1409          references to their alias set members, so if a memory tag has
1410          aliases, do not count its direct references to avoid double
1411          accounting.  */
1412       if (!MTAG_P (var) || !MTAG_ALIASES (var))
1413         {
1414           mem_ref_stats->num_vuses += sym_stats->num_direct_reads;
1415           mem_ref_stats->num_vdefs += sym_stats->num_direct_writes;
1416         }
1417
1418       mem_ref_stats->num_vuses += sym_stats->num_indirect_reads;
1419       mem_ref_stats->num_vdefs += sym_stats->num_indirect_writes;
1420     }
1421 }
1422
1423
1424 /* Compute memory partitions.  A memory partition (MPT) is an
1425    arbitrary grouping of memory symbols, such that references to one
1426    member of the group is considered a reference to all the members of
1427    the group.
1428    
1429    As opposed to alias sets in memory tags, the grouping into
1430    partitions is completely arbitrary and only done to reduce the
1431    number of virtual operands.  The only rule that needs to be
1432    observed when creating memory partitions is that given two memory
1433    partitions MPT.i and MPT.j, they must not contain symbols in
1434    common.
1435
1436    Memory partitions are used when putting the program into Memory-SSA
1437    form.  In particular, in Memory-SSA PHI nodes are not computed for
1438    individual memory symbols.  They are computed for memory
1439    partitions.  This reduces the amount of PHI nodes in the SSA graph
1440    at the expense of precision (i.e., it makes unrelated stores affect
1441    each other).
1442    
1443    However, it is possible to increase precision by changing this
1444    partitioning scheme.  For instance, if the partitioning scheme is
1445    such that get_mpt_for is the identity function (that is,
1446    get_mpt_for (s) = s), this will result in ultimate precision at the
1447    expense of huge SSA webs.
1448
1449    At the other extreme, a partitioning scheme that groups all the
1450    symbols in the same set results in minimal SSA webs and almost
1451    total loss of precision.
1452
1453    There partitioning heuristic uses three parameters to decide the
1454    order in which symbols are processed.  The list of symbols is
1455    sorted so that symbols that are more likely to be partitioned are
1456    near the top of the list:
1457
1458    - Execution frequency.  If a memory references is in a frequently
1459      executed code path, grouping it into a partition may block useful
1460      transformations and cause sub-optimal code generation.  So, the
1461      partition heuristic tries to avoid grouping symbols with high
1462      execution frequency scores.  Execution frequency is taken
1463      directly from the basic blocks where every reference is made (see
1464      update_mem_sym_stats_from_stmt), which in turn uses the
1465      profile guided machinery, so if the program is compiled with PGO
1466      enabled, more accurate partitioning decisions will be made.
1467
1468    - Number of references.  Symbols with few references in the code,
1469      are partitioned before symbols with many references.
1470
1471    - NO_ALIAS attributes.  Symbols with any of the NO_ALIAS*
1472      attributes are partitioned after symbols marked MAY_ALIAS.
1473
1474    Once the list is sorted, the partitioning proceeds as follows:
1475
1476    1- For every symbol S in MP_INFO, create a new memory partition MP,
1477       if necessary.  To avoid memory partitions that contain symbols
1478       from non-conflicting alias sets, memory partitions are
1479       associated to the memory tag that holds S in its alias set.  So,
1480       when looking for a memory partition for S, the memory partition
1481       associated with one of the memory tags holding S is chosen.  If
1482       none exists, a new one is created.
1483
1484    2- Add S to memory partition MP.
1485
1486    3- Reduce by 1 the number of VOPS for every memory tag holding S.
1487
1488    4- If the total number of VOPS is less than MAX_ALIASED_VOPS or the
1489       average number of VOPS per statement is less than
1490       AVG_ALIASED_VOPS, stop.  Otherwise, go to the next symbol in the
1491       list.  */
1492
1493 static void
1494 compute_memory_partitions (void)
1495 {
1496   tree tag;
1497   unsigned i;
1498   mem_sym_stats_t mp_p;
1499   VEC(mem_sym_stats_t,heap) *mp_info;
1500   bitmap new_aliases;
1501   VEC(tree,heap) *tags;
1502   struct mem_ref_stats_d *mem_ref_stats;
1503   int prev_max_aliased_vops;
1504
1505   mem_ref_stats = gimple_mem_ref_stats (cfun);
1506   gcc_assert (mem_ref_stats->num_vuses == 0 && mem_ref_stats->num_vdefs == 0);
1507
1508   if (mem_ref_stats->num_mem_stmts == 0)
1509     return;
1510
1511   timevar_push (TV_MEMORY_PARTITIONING);
1512
1513   mp_info = NULL;
1514   tags = NULL;
1515   prev_max_aliased_vops = MAX_ALIASED_VOPS;
1516
1517   /* Since we clearly cannot lower the number of virtual operators
1518      below the total number of memory statements in the function, we
1519      may need to adjust MAX_ALIASED_VOPS beforehand.  */
1520   if (MAX_ALIASED_VOPS < mem_ref_stats->num_mem_stmts)
1521     MAX_ALIASED_VOPS = mem_ref_stats->num_mem_stmts;
1522
1523   /* Update reference stats for all the pointed-to variables and
1524      memory tags.  */
1525   update_reference_counts (mem_ref_stats);
1526
1527   /* Add all the memory symbols to MP_INFO.  */
1528   build_mp_info (mem_ref_stats, &mp_info, &tags);
1529
1530   /* No partitions required if we are below the threshold.  */
1531   if (!need_to_partition_p (mem_ref_stats))
1532     {
1533       if (dump_file)
1534         fprintf (dump_file, "\nMemory partitioning NOT NEEDED for %s\n",
1535                  get_name (current_function_decl));
1536       goto done;
1537     }
1538
1539   /* Sort the MP_INFO array so that symbols that should be partitioned
1540      first are near the top of the list.  */
1541   sort_mp_info (mp_info);
1542
1543   if (dump_file)
1544     {
1545       fprintf (dump_file, "\nMemory partitioning NEEDED for %s\n\n",
1546                get_name (current_function_decl));
1547       fprintf (dump_file, "Memory symbol references before partitioning:\n");
1548       dump_mp_info (dump_file, mp_info);
1549     }
1550
1551   /* Create partitions for variables in MP_INFO until we have enough
1552      to lower the total number of VOPS below MAX_ALIASED_VOPS or if
1553      the average number of VOPS per statement is below
1554      AVG_ALIASED_VOPS.  */
1555   for (i = 0; VEC_iterate (mem_sym_stats_t, mp_info, i, mp_p); i++)
1556     {
1557       tree mpt;
1558
1559       /* If we are below the threshold, stop.  */
1560       if (!need_to_partition_p (mem_ref_stats))
1561         break;
1562
1563       mpt = find_partition_for (mp_p);
1564       estimate_vop_reduction (mem_ref_stats, mp_p, mpt);
1565     }
1566
1567   /* After partitions have been created, rewrite alias sets to use
1568      them instead of the original symbols.  This way, if the alias set
1569      was computed as { a b c d e f }, and the subset { b e f } was
1570      grouped into partition MPT.3, then the new alias set for the tag
1571      will be  { a c d MPT.3 }.
1572      
1573      Note that this is not strictly necessary.  The operand scanner
1574      will always check if a symbol belongs to a partition when adding
1575      virtual operands.  However, by reducing the size of the alias
1576      sets to be scanned, the work needed inside the operand scanner is
1577      significantly reduced.  */
1578   new_aliases = BITMAP_ALLOC (&alias_bitmap_obstack);
1579
1580   for (i = 0; VEC_iterate (tree, tags, i, tag); i++)
1581     {
1582       rewrite_alias_set_for (tag, new_aliases);
1583       bitmap_clear (new_aliases);
1584     }
1585
1586   BITMAP_FREE (new_aliases);
1587
1588   if (dump_file)
1589     {
1590       fprintf (dump_file, "\nMemory symbol references after partitioning:\n");
1591       dump_mp_info (dump_file, mp_info);
1592     }
1593
1594 done:
1595   /* Free allocated memory.  */
1596   VEC_free (mem_sym_stats_t, heap, mp_info);
1597   VEC_free (tree, heap, tags);
1598
1599   MAX_ALIASED_VOPS = prev_max_aliased_vops;
1600
1601   timevar_pop (TV_MEMORY_PARTITIONING);
1602 }
1603
1604
1605 /* Compute may-alias information for every variable referenced in function
1606    FNDECL.
1607
1608    Alias analysis proceeds in 3 main phases:
1609
1610    1- Points-to and escape analysis.
1611
1612    This phase walks the use-def chains in the SSA web looking for three
1613    things:
1614
1615         * Assignments of the form P_i = &VAR
1616         * Assignments of the form P_i = malloc()
1617         * Pointers and ADDR_EXPR that escape the current function.
1618
1619    The concept of 'escaping' is the same one used in the Java world.  When
1620    a pointer or an ADDR_EXPR escapes, it means that it has been exposed
1621    outside of the current function.  So, assignment to global variables,
1622    function arguments and returning a pointer are all escape sites, as are
1623    conversions between pointers and integers.
1624
1625    This is where we are currently limited.  Since not everything is renamed
1626    into SSA, we lose track of escape properties when a pointer is stashed
1627    inside a field in a structure, for instance.  In those cases, we are
1628    assuming that the pointer does escape.
1629
1630    We use escape analysis to determine whether a variable is
1631    call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the variable
1632    is call-clobbered.  If a pointer P_i escapes, then all the variables
1633    pointed-to by P_i (and its memory tag) also escape.
1634
1635    2- Compute flow-sensitive aliases
1636
1637    We have two classes of memory tags.  Memory tags associated with the
1638    pointed-to data type of the pointers in the program.  These tags are
1639    called "symbol memory tag" (SMT).  The other class are those associated
1640    with SSA_NAMEs, called "name memory tag" (NMT). The basic idea is that
1641    when adding operands for an INDIRECT_REF *P_i, we will first check
1642    whether P_i has a name tag, if it does we use it, because that will have
1643    more precise aliasing information.  Otherwise, we use the standard symbol
1644    tag.
1645
1646    In this phase, we go through all the pointers we found in points-to
1647    analysis and create alias sets for the name memory tags associated with
1648    each pointer P_i.  If P_i escapes, we mark call-clobbered the variables
1649    it points to and its tag.
1650
1651
1652    3- Compute flow-insensitive aliases
1653
1654    This pass will compare the alias set of every symbol memory tag and
1655    every addressable variable found in the program.  Given a symbol
1656    memory tag SMT and an addressable variable V.  If the alias sets of
1657    SMT and V conflict (as computed by may_alias_p), then V is marked
1658    as an alias tag and added to the alias set of SMT.
1659
1660    For instance, consider the following function:
1661
1662             foo (int i)
1663             {
1664               int *p, a, b;
1665             
1666               if (i > 10)
1667                 p = &a;
1668               else
1669                 p = &b;
1670             
1671               *p = 3;
1672               a = b + 2;
1673               return *p;
1674             }
1675
1676    After aliasing analysis has finished, the symbol memory tag for pointer
1677    'p' will have two aliases, namely variables 'a' and 'b'.  Every time
1678    pointer 'p' is dereferenced, we want to mark the operation as a
1679    potential reference to 'a' and 'b'.
1680
1681             foo (int i)
1682             {
1683               int *p, a, b;
1684
1685               if (i_2 > 10)
1686                 p_4 = &a;
1687               else
1688                 p_6 = &b;
1689               # p_1 = PHI <p_4(1), p_6(2)>;
1690
1691               # a_7 = VDEF <a_3>;
1692               # b_8 = VDEF <b_5>;
1693               *p_1 = 3;
1694
1695               # a_9 = VDEF <a_7>
1696               # VUSE <b_8>
1697               a_9 = b_8 + 2;
1698
1699               # VUSE <a_9>;
1700               # VUSE <b_8>;
1701               return *p_1;
1702             }
1703
1704    In certain cases, the list of may aliases for a pointer may grow too
1705    large.  This may cause an explosion in the number of virtual operands
1706    inserted in the code.  Resulting in increased memory consumption and
1707    compilation time.
1708
1709    When the number of virtual operands needed to represent aliased
1710    loads and stores grows too large (configurable with option --param
1711    max-aliased-vops and --param avg-aliased-vops), alias sets are
1712    grouped to avoid severe compile-time slow downs and memory
1713    consumption. See compute_memory_partitions.  */
1714
1715 unsigned int
1716 compute_may_aliases (void)
1717 {
1718   struct alias_info *ai;
1719
1720   timevar_push (TV_TREE_MAY_ALIAS);
1721   
1722   memset (&alias_stats, 0, sizeof (alias_stats));
1723
1724   /* Initialize aliasing information.  */
1725   ai = init_alias_info ();
1726
1727   /* For each pointer P_i, determine the sets of variables that P_i may
1728      point-to.  For every addressable variable V, determine whether the
1729      address of V escapes the current function, making V call-clobbered
1730      (i.e., whether &V is stored in a global variable or if its passed as a
1731      function call argument).  */
1732   compute_points_to_sets (ai);
1733
1734   /* Collect all pointers and addressable variables, compute alias sets,
1735      create memory tags for pointers and promote variables whose address is
1736      not needed anymore.  */
1737   setup_pointers_and_addressables (ai);
1738
1739   /* Compute type-based flow-insensitive aliasing for all the type
1740      memory tags.  */
1741   compute_flow_insensitive_aliasing (ai);
1742
1743   /* Compute flow-sensitive, points-to based aliasing for all the name
1744      memory tags.  */
1745   compute_flow_sensitive_aliasing (ai);
1746   
1747   /* Compute call clobbering information.  */
1748   compute_call_clobbered (ai);
1749
1750   /* If the program makes no reference to global variables, but it
1751      contains a mixture of pure and non-pure functions, then we need
1752      to create use-def and def-def links between these functions to
1753      avoid invalid transformations on them.  */
1754   maybe_create_global_var ();
1755
1756   /* Compute memory partitions for every memory variable.  */
1757   compute_memory_partitions ();
1758
1759   /* Remove partitions with no symbols.  Partitions may end up with an
1760      empty MPT_SYMBOLS set if a previous round of alias analysis
1761      needed to partition more symbols.  Since we don't need those
1762      partitions anymore, remove them to free up the space.  */
1763   {
1764     tree mpt;
1765     unsigned i;
1766     VEC(tree,heap) *mpt_table;
1767
1768     mpt_table = gimple_ssa_operands (cfun)->mpt_table;
1769     i = 0;
1770     while (i < VEC_length (tree, mpt_table))
1771       {
1772         mpt = VEC_index (tree, mpt_table, i);
1773         if (MPT_SYMBOLS (mpt) == NULL)
1774           VEC_unordered_remove (tree, mpt_table, i);
1775         else
1776           i++;
1777       }
1778   }
1779
1780   /* Populate all virtual operands and newly promoted register operands.  */
1781   {
1782     block_stmt_iterator bsi;
1783     basic_block bb;
1784     FOR_EACH_BB (bb)
1785       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1786         update_stmt_if_modified (bsi_stmt (bsi));
1787   }
1788
1789   /* Debugging dumps.  */
1790   if (dump_file)
1791     {
1792       dump_mem_ref_stats (dump_file);
1793       dump_alias_info (dump_file);
1794       dump_points_to_info (dump_file);
1795
1796       if (dump_flags & TDF_STATS)
1797         dump_alias_stats (dump_file);
1798
1799       if (dump_flags & TDF_DETAILS)
1800         dump_referenced_vars (dump_file);
1801     }
1802
1803   /* Report strict aliasing violations.  */
1804   strict_aliasing_warning_backend ();
1805
1806   /* Deallocate memory used by aliasing data structures.  */
1807   delete_alias_info (ai);
1808
1809   if (need_ssa_update_p ())
1810     update_ssa (TODO_update_ssa);
1811
1812   timevar_pop (TV_TREE_MAY_ALIAS);
1813   
1814   return 0;
1815 }
1816
1817 /* Data structure used to count the number of dereferences to PTR
1818    inside an expression.  */
1819 struct count_ptr_d
1820 {
1821   tree ptr;
1822   unsigned count;
1823 };
1824
1825
1826 /* Helper for count_uses_and_derefs.  Called by walk_tree to look for
1827    (ALIGN/MISALIGNED_)INDIRECT_REF nodes for the pointer passed in DATA.  */
1828
1829 static tree
1830 count_ptr_derefs (tree *tp, int *walk_subtrees, void *data)
1831 {
1832   struct count_ptr_d *count_p = (struct count_ptr_d *) data;
1833
1834   /* Do not walk inside ADDR_EXPR nodes.  In the expression &ptr->fld,
1835      pointer 'ptr' is *not* dereferenced, it is simply used to compute
1836      the address of 'fld' as 'ptr + offsetof(fld)'.  */
1837   if (TREE_CODE (*tp) == ADDR_EXPR)
1838     {
1839       *walk_subtrees = 0;
1840       return NULL_TREE;
1841     }
1842
1843   if (INDIRECT_REF_P (*tp) && TREE_OPERAND (*tp, 0) == count_p->ptr)
1844     count_p->count++;
1845
1846   return NULL_TREE;
1847 }
1848
1849
1850 /* Count the number of direct and indirect uses for pointer PTR in
1851    statement STMT.  The number of direct uses is stored in
1852    *NUM_USES_P.  Indirect references are counted separately depending
1853    on whether they are store or load operations.  The counts are
1854    stored in *NUM_STORES_P and *NUM_LOADS_P.  */
1855
1856 void
1857 count_uses_and_derefs (tree ptr, tree stmt, unsigned *num_uses_p,
1858                        unsigned *num_loads_p, unsigned *num_stores_p)
1859 {
1860   ssa_op_iter i;
1861   tree use;
1862
1863   *num_uses_p = 0;
1864   *num_loads_p = 0;
1865   *num_stores_p = 0;
1866
1867   /* Find out the total number of uses of PTR in STMT.  */
1868   FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
1869     if (use == ptr)
1870       (*num_uses_p)++;
1871
1872   /* Now count the number of indirect references to PTR.  This is
1873      truly awful, but we don't have much choice.  There are no parent
1874      pointers inside INDIRECT_REFs, so an expression like
1875      '*x_1 = foo (x_1, *x_1)' needs to be traversed piece by piece to
1876      find all the indirect and direct uses of x_1 inside.  The only
1877      shortcut we can take is the fact that GIMPLE only allows
1878      INDIRECT_REFs inside the expressions below.  */
1879   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1880       || (TREE_CODE (stmt) == RETURN_EXPR
1881           && TREE_CODE (TREE_OPERAND (stmt, 0)) == GIMPLE_MODIFY_STMT)
1882       || TREE_CODE (stmt) == ASM_EXPR
1883       || TREE_CODE (stmt) == CALL_EXPR)
1884     {
1885       tree lhs, rhs;
1886
1887       if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1888         {
1889           lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1890           rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1891         }
1892       else if (TREE_CODE (stmt) == RETURN_EXPR)
1893         {
1894           tree e = TREE_OPERAND (stmt, 0);
1895           lhs = GIMPLE_STMT_OPERAND (e, 0);
1896           rhs = GIMPLE_STMT_OPERAND (e, 1);
1897         }
1898       else if (TREE_CODE (stmt) == ASM_EXPR)
1899         {
1900           lhs = ASM_OUTPUTS (stmt);
1901           rhs = ASM_INPUTS (stmt);
1902         }
1903       else
1904         {
1905           lhs = NULL_TREE;
1906           rhs = stmt;
1907         }
1908
1909       if (lhs
1910           && (TREE_CODE (lhs) == TREE_LIST
1911               || EXPR_P (lhs)
1912               || GIMPLE_STMT_P (lhs)))
1913         {
1914           struct count_ptr_d count;
1915           count.ptr = ptr;
1916           count.count = 0;
1917           walk_tree (&lhs, count_ptr_derefs, &count, NULL);
1918           *num_stores_p = count.count;
1919         }
1920
1921       if (rhs
1922           && (TREE_CODE (rhs) == TREE_LIST
1923               || EXPR_P (rhs)
1924               || GIMPLE_STMT_P (rhs)))
1925         {
1926           struct count_ptr_d count;
1927           count.ptr = ptr;
1928           count.count = 0;
1929           walk_tree (&rhs, count_ptr_derefs, &count, NULL);
1930           *num_loads_p = count.count;
1931         }
1932     }
1933
1934   gcc_assert (*num_uses_p >= *num_loads_p + *num_stores_p);
1935 }
1936
1937 /* Remove memory references stats for function FN.  */
1938
1939 void
1940 delete_mem_ref_stats (struct function *fn)
1941 {
1942   if (gimple_mem_ref_stats (fn)->mem_sym_stats)
1943     {
1944       free_alloc_pool (mem_sym_stats_pool);
1945       pointer_map_destroy (gimple_mem_ref_stats (fn)->mem_sym_stats);
1946     }
1947   gimple_mem_ref_stats (fn)->mem_sym_stats = NULL;
1948 }
1949
1950
1951 /* Initialize memory reference stats.  */
1952
1953 static void
1954 init_mem_ref_stats (void)
1955 {
1956   struct mem_ref_stats_d *mem_ref_stats = gimple_mem_ref_stats (cfun);
1957
1958   mem_sym_stats_pool = create_alloc_pool ("Mem sym stats",
1959                                           sizeof (struct mem_sym_stats_d),
1960                                           100);
1961   memset (mem_ref_stats, 0, sizeof (struct mem_ref_stats_d));
1962   mem_ref_stats->mem_sym_stats = pointer_map_create ();
1963 }
1964
1965
1966 /* Helper for init_alias_info.  Reset existing aliasing information.  */
1967
1968 static void
1969 reset_alias_info (void)
1970 {
1971   referenced_var_iterator rvi;
1972   tree var;
1973   unsigned i;
1974   bitmap active_nmts, all_nmts;
1975
1976   /* Clear the set of addressable variables.  We do not need to clear
1977      the TREE_ADDRESSABLE bit on every symbol because we are going to
1978      re-compute addressability here.  */
1979   bitmap_clear (gimple_addressable_vars (cfun));
1980
1981   active_nmts = BITMAP_ALLOC (&alias_bitmap_obstack);
1982   all_nmts = BITMAP_ALLOC (&alias_bitmap_obstack);
1983
1984   /* Clear flow-insensitive alias information from each symbol.  */
1985   FOR_EACH_REFERENCED_VAR (var, rvi)
1986     {
1987       if (is_gimple_reg (var))
1988         continue;
1989
1990       if (MTAG_P (var))
1991         MTAG_ALIASES (var) = NULL;
1992
1993       /* Memory partition information will be computed from scratch.  */
1994       if (TREE_CODE (var) == MEMORY_PARTITION_TAG)
1995         MPT_SYMBOLS (var) = NULL;
1996
1997       /* Collect all the name tags to determine if we have any
1998          orphaned that need to be removed from the IL.  A name tag
1999          will be orphaned if it is not associated with any active SSA
2000          name.  */
2001       if (TREE_CODE (var) == NAME_MEMORY_TAG)
2002         bitmap_set_bit (all_nmts, DECL_UID (var));
2003
2004       /* Since we are about to re-discover call-clobbered
2005          variables, clear the call-clobbered flag.  Variables that
2006          are intrinsically call-clobbered (globals, local statics,
2007          etc) will not be marked by the aliasing code, so we can't
2008          remove them from CALL_CLOBBERED_VARS.  
2009
2010          NB: STRUCT_FIELDS are still call clobbered if they are for a
2011          global variable, so we *don't* clear their call clobberedness
2012          just because they are tags, though we will clear it if they
2013          aren't for global variables.  */
2014       if (TREE_CODE (var) == NAME_MEMORY_TAG
2015           || TREE_CODE (var) == SYMBOL_MEMORY_TAG
2016           || TREE_CODE (var) == MEMORY_PARTITION_TAG
2017           || !is_global_var (var))
2018         clear_call_clobbered (var);
2019     }
2020
2021   /* Clear flow-sensitive points-to information from each SSA name.  */
2022   for (i = 1; i < num_ssa_names; i++)
2023     {
2024       tree name = ssa_name (i);
2025
2026       if (!name || !POINTER_TYPE_P (TREE_TYPE (name)))
2027         continue;
2028
2029       if (SSA_NAME_PTR_INFO (name))
2030         {
2031           struct ptr_info_def *pi = SSA_NAME_PTR_INFO (name);
2032
2033           /* Clear all the flags but keep the name tag to
2034              avoid creating new temporaries unnecessarily.  If
2035              this pointer is found to point to a subset or
2036              superset of its former points-to set, then a new
2037              tag will need to be created in create_name_tags.  */
2038           pi->pt_anything = 0;
2039           pi->pt_null = 0;
2040           pi->value_escapes_p = 0;
2041           pi->is_dereferenced = 0;
2042           if (pi->pt_vars)
2043             bitmap_clear (pi->pt_vars);
2044
2045           /* Add NAME's name tag to the set of active tags.  */
2046           if (pi->name_mem_tag)
2047             bitmap_set_bit (active_nmts, DECL_UID (pi->name_mem_tag));
2048         }
2049     }
2050
2051   /* Name memory tags that are no longer associated with an SSA name
2052      are considered stale and should be removed from the IL.  All the
2053      name tags that are in the set ALL_NMTS but not in ACTIVE_NMTS are
2054      considered stale and marked for renaming.  */
2055   bitmap_and_compl_into (all_nmts, active_nmts);
2056   mark_set_for_renaming (all_nmts);
2057
2058   BITMAP_FREE (all_nmts);
2059   BITMAP_FREE (active_nmts);
2060 }
2061
2062
2063 /* Initialize the data structures used for alias analysis.  */
2064
2065 static struct alias_info *
2066 init_alias_info (void)
2067 {
2068   struct alias_info *ai;
2069   referenced_var_iterator rvi;
2070   tree var;
2071
2072   ai = XCNEW (struct alias_info);
2073   ai->ssa_names_visited = sbitmap_alloc (num_ssa_names);
2074   sbitmap_zero (ai->ssa_names_visited);
2075   ai->processed_ptrs = VEC_alloc (tree, heap, 50);
2076   ai->written_vars = pointer_set_create ();
2077   ai->dereferenced_ptrs_store = pointer_set_create ();
2078   ai->dereferenced_ptrs_load = pointer_set_create ();
2079
2080   /* Clear out all memory reference stats.  */
2081   init_mem_ref_stats ();
2082
2083   /* If aliases have been computed before, clear existing information.  */
2084   if (gimple_aliases_computed_p (cfun))
2085     reset_alias_info ();
2086   else
2087     {
2088       /* If this is the first time we compute aliasing information,
2089          every non-register symbol will need to be put into SSA form
2090          (the initial SSA form only operates on GIMPLE registers).  */
2091       FOR_EACH_REFERENCED_VAR (var, rvi)
2092         if (!is_gimple_reg (var))
2093           mark_sym_for_renaming (var);
2094     }
2095
2096   /* Next time, we will need to reset alias information.  */
2097   cfun->gimple_df->aliases_computed_p = true;
2098   if (alias_bitmap_obstack.elements != NULL)
2099     bitmap_obstack_release (&alias_bitmap_obstack);    
2100   bitmap_obstack_initialize (&alias_bitmap_obstack);
2101
2102   return ai;
2103 }
2104
2105
2106 /* Deallocate memory used by alias analysis.  */
2107
2108 static void
2109 delete_alias_info (struct alias_info *ai)
2110 {
2111   size_t i;
2112
2113   sbitmap_free (ai->ssa_names_visited);
2114
2115   VEC_free (tree, heap, ai->processed_ptrs);
2116
2117   for (i = 0; i < ai->num_addressable_vars; i++)
2118     free (ai->addressable_vars[i]);
2119   free (ai->addressable_vars);
2120   
2121   for (i = 0; i < ai->num_pointers; i++)
2122     free (ai->pointers[i]);
2123   free (ai->pointers);
2124
2125   pointer_set_destroy (ai->written_vars);
2126   pointer_set_destroy (ai->dereferenced_ptrs_store);
2127   pointer_set_destroy (ai->dereferenced_ptrs_load);
2128   free (ai);
2129
2130   delete_mem_ref_stats (cfun);
2131   delete_points_to_sets ();
2132 }
2133
2134
2135 /* Used for hashing to identify pointer infos with identical
2136    pt_vars bitmaps.  */
2137
2138 static int
2139 eq_ptr_info (const void *p1, const void *p2)
2140 {
2141   const struct ptr_info_def *n1 = (const struct ptr_info_def *) p1;
2142   const struct ptr_info_def *n2 = (const struct ptr_info_def *) p2;
2143   return bitmap_equal_p (n1->pt_vars, n2->pt_vars);
2144 }
2145
2146 static hashval_t
2147 ptr_info_hash (const void *p)
2148 {
2149   const struct ptr_info_def *n = (const struct ptr_info_def *) p;
2150   return bitmap_hash (n->pt_vars);
2151 }
2152
2153
2154 /* Create name tags for all the pointers that have been dereferenced.
2155    We only create a name tag for a pointer P if P is found to point to
2156    a set of variables (so that we can alias them to *P) or if it is
2157    the result of a call to malloc (which means that P cannot point to
2158    anything else nor alias any other variable).
2159
2160    If two pointers P and Q point to the same set of variables, they
2161    are assigned the same name tag.  */
2162
2163 static void
2164 create_name_tags (void)
2165 {
2166   size_t i;
2167   VEC (tree, heap) *with_ptvars = NULL;
2168   tree ptr;
2169   htab_t ptr_hash;
2170
2171   /* Collect the list of pointers with a non-empty points to set.  */
2172   for (i = 1; i < num_ssa_names; i++)
2173     {
2174       tree ptr = ssa_name (i);
2175       struct ptr_info_def *pi;
2176
2177       if (!ptr
2178           || !POINTER_TYPE_P (TREE_TYPE (ptr))
2179           || !SSA_NAME_PTR_INFO (ptr))
2180         continue;
2181
2182       pi = SSA_NAME_PTR_INFO (ptr);
2183
2184       if (pi->pt_anything || !pi->is_dereferenced)
2185         {
2186           /* No name tags for pointers that have not been
2187              dereferenced or point to an arbitrary location.  */
2188           pi->name_mem_tag = NULL_TREE;
2189           continue;
2190         }
2191
2192       /* Set pt_anything on the pointers without pt_vars filled in so
2193          that they are assigned a symbol tag.  */
2194       if (pi->pt_vars && !bitmap_empty_p (pi->pt_vars)) 
2195         VEC_safe_push (tree, heap, with_ptvars, ptr);
2196       else
2197         set_pt_anything (ptr);
2198     }
2199   
2200   /* If we didn't find any pointers with pt_vars set, we're done.  */
2201   if (!with_ptvars)
2202     return;
2203
2204   ptr_hash = htab_create (10, ptr_info_hash, eq_ptr_info, NULL);
2205
2206   /* Now go through the pointers with pt_vars, and find a name tag
2207      with the same pt_vars as this pointer, or create one if one
2208      doesn't exist.  */
2209   for (i = 0; VEC_iterate (tree, with_ptvars, i, ptr); i++)
2210     {
2211       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2212       tree old_name_tag = pi->name_mem_tag;
2213       struct ptr_info_def **slot;
2214       
2215       /* If PTR points to a set of variables, check if we don't
2216          have another pointer Q with the same points-to set before
2217          creating a tag.  If so, use Q's tag instead of creating a
2218          new one.
2219          
2220          This is important for not creating unnecessary symbols
2221          and also for copy propagation.  If we ever need to
2222          propagate PTR into Q or vice-versa, we would run into
2223          problems if they both had different name tags because
2224          they would have different SSA version numbers (which
2225          would force us to take the name tags in and out of SSA).  */
2226       slot = (struct ptr_info_def **) htab_find_slot (ptr_hash, pi, INSERT);
2227       if (*slot)
2228         pi->name_mem_tag = (*slot)->name_mem_tag;
2229       else
2230         {
2231           *slot = pi;
2232
2233           /* If we didn't find a pointer with the same points-to set
2234              as PTR, create a new name tag if needed.  */
2235           if (pi->name_mem_tag == NULL_TREE)
2236             pi->name_mem_tag = get_nmt_for (ptr);
2237         }
2238       
2239       /* If the new name tag computed for PTR is different than
2240          the old name tag that it used to have, then the old tag
2241          needs to be removed from the IL, so we mark it for
2242          renaming.  */
2243       if (old_name_tag && old_name_tag != pi->name_mem_tag)
2244         mark_sym_for_renaming (old_name_tag);
2245
2246       /* Inherit volatility from the pointed-to type.  */
2247       TREE_THIS_VOLATILE (pi->name_mem_tag)
2248         |= TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (ptr)));
2249       
2250       /* Mark the new name tag for renaming.  */
2251       mark_sym_for_renaming (pi->name_mem_tag);
2252     }
2253
2254   htab_delete (ptr_hash);
2255
2256   VEC_free (tree, heap, with_ptvars);
2257 }
2258
2259
2260 /* Union the alias set SET into the may-aliases for TAG.  */
2261
2262 static void
2263 union_alias_set_into (tree tag, bitmap set)
2264 {
2265   bitmap ma = MTAG_ALIASES (tag);
2266   
2267   if (bitmap_empty_p (set))
2268     return;
2269   
2270   if (!ma)
2271     ma = MTAG_ALIASES (tag) = BITMAP_ALLOC (&alias_bitmap_obstack);
2272   bitmap_ior_into (ma, set);
2273 }
2274
2275
2276 /* For every pointer P_i in AI->PROCESSED_PTRS, create may-alias sets for
2277    the name memory tag (NMT) associated with P_i.  If P_i escapes, then its
2278    name tag and the variables it points-to are call-clobbered.  Finally, if
2279    P_i escapes and we could not determine where it points to, then all the
2280    variables in the same alias set as *P_i are marked call-clobbered.  This
2281    is necessary because we must assume that P_i may take the address of any
2282    variable in the same alias set.  */
2283
2284 static void
2285 compute_flow_sensitive_aliasing (struct alias_info *ai)
2286 {
2287   size_t i;
2288   tree ptr;
2289   
2290   timevar_push (TV_FLOW_SENSITIVE);
2291   set_used_smts ();
2292   
2293   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
2294     {
2295       if (!find_what_p_points_to (ptr))
2296         set_pt_anything (ptr);
2297     }
2298
2299   create_name_tags ();
2300
2301   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
2302     {
2303       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2304
2305       /* Set up aliasing information for PTR's name memory tag (if it has
2306          one).  Note that only pointers that have been dereferenced will
2307          have a name memory tag.  */
2308       if (pi->name_mem_tag && pi->pt_vars)
2309         {
2310           if (!bitmap_empty_p (pi->pt_vars))
2311             union_alias_set_into (pi->name_mem_tag, pi->pt_vars);
2312         }
2313     }
2314   timevar_pop (TV_FLOW_SENSITIVE);
2315 }
2316
2317
2318 /* Return TRUE if at least one symbol in TAG2's alias set is also
2319    present in TAG1's alias set.  */
2320
2321 static bool
2322 have_common_aliases_p (bitmap tag1aliases, bitmap tag2aliases)
2323 {
2324
2325   /* This is the old behavior of have_common_aliases_p, which is to
2326      return false if both sets are empty, or one set is and the other
2327      isn't.  */
2328   if (tag1aliases == NULL || tag2aliases == NULL)
2329     return false;
2330
2331   return bitmap_intersect_p (tag1aliases, tag2aliases);
2332 }
2333
2334 /* Compute type-based alias sets.  Traverse all the pointers and
2335    addressable variables found in setup_pointers_and_addressables.
2336    
2337    For every pointer P in AI->POINTERS and addressable variable V in
2338    AI->ADDRESSABLE_VARS, add V to the may-alias sets of P's symbol
2339    memory tag (SMT) if their alias sets conflict.  V is then marked as
2340    an aliased symbol so that the operand scanner knows that statements
2341    containing V have aliased operands.  */
2342
2343 static void
2344 compute_flow_insensitive_aliasing (struct alias_info *ai)
2345 {
2346   size_t i;
2347
2348   timevar_push (TV_FLOW_INSENSITIVE);
2349   /* For every pointer P, determine which addressable variables may alias
2350      with P's symbol memory tag.  */
2351   for (i = 0; i < ai->num_pointers; i++)
2352     {
2353       size_t j;
2354       struct alias_map_d *p_map = ai->pointers[i];
2355       tree tag = symbol_mem_tag (p_map->var);
2356       tree var;
2357
2358       for (j = 0; j < ai->num_addressable_vars; j++)
2359         {
2360           struct alias_map_d *v_map;
2361           var_ann_t v_ann;
2362           bool tag_stored_p, var_stored_p;
2363           
2364           v_map = ai->addressable_vars[j];
2365           var = v_map->var;
2366           v_ann = var_ann (var);
2367
2368           /* Skip memory tags and variables that have never been
2369              written to.  We also need to check if the variables are
2370              call-clobbered because they may be overwritten by
2371              function calls.  */
2372           tag_stored_p = pointer_set_contains (ai->written_vars, tag)
2373                          || is_call_clobbered (tag);
2374           var_stored_p = pointer_set_contains (ai->written_vars, var)
2375                          || is_call_clobbered (var);
2376           if (!tag_stored_p && !var_stored_p)
2377             continue;
2378              
2379           if (may_alias_p (p_map->var, p_map->set, var, v_map->set, false))
2380             {
2381               /* Add VAR to TAG's may-aliases set.  */
2382               add_may_alias (tag, var);
2383             }
2384         }
2385     }
2386
2387   /* Since this analysis is based exclusively on symbols, it fails to
2388      handle cases where two pointers P and Q have different memory
2389      tags with conflicting alias set numbers but no aliased symbols in
2390      common.
2391
2392      For example, suppose that we have two memory tags SMT.1 and SMT.2
2393      such that
2394      
2395                 may-aliases (SMT.1) = { a }
2396                 may-aliases (SMT.2) = { b }
2397
2398      and the alias set number of SMT.1 conflicts with that of SMT.2.
2399      Since they don't have symbols in common, loads and stores from
2400      SMT.1 and SMT.2 will seem independent of each other, which will
2401      lead to the optimizers making invalid transformations (see
2402      testsuite/gcc.c-torture/execute/pr15262-[12].c).
2403
2404      To avoid this problem, we do a final traversal of AI->POINTERS
2405      looking for pairs of pointers that have no aliased symbols in
2406      common and yet have conflicting alias set numbers.  */
2407   for (i = 0; i < ai->num_pointers; i++)
2408     {
2409       size_t j;
2410       struct alias_map_d *p_map1 = ai->pointers[i];
2411       tree tag1 = symbol_mem_tag (p_map1->var);
2412       bitmap may_aliases1 = MTAG_ALIASES (tag1);
2413
2414       for (j = 0; j < ai->num_pointers; j++)
2415         {
2416           struct alias_map_d *p_map2 = ai->pointers[j];
2417           tree tag2 = symbol_mem_tag (p_map2->var);
2418           bitmap may_aliases2 = may_aliases (tag2);
2419
2420           /* By convention tags don't alias themselves.  */
2421           if (tag1 == tag2)
2422             continue;
2423
2424           /* If the pointers may not point to each other, do nothing.  */
2425           if (!may_alias_p (p_map1->var, p_map1->set, tag2, p_map2->set, true))
2426             continue;
2427
2428           /* The two pointers may alias each other.  If they already have
2429              symbols in common, do nothing.  */
2430           if (have_common_aliases_p (may_aliases1, may_aliases2))
2431             continue;
2432
2433           add_may_alias (tag1, tag2);
2434         }
2435     }
2436   timevar_pop (TV_FLOW_INSENSITIVE);
2437 }
2438
2439
2440 /* Create a new alias set entry for VAR in AI->ADDRESSABLE_VARS.  */
2441
2442 static void
2443 create_alias_map_for (tree var, struct alias_info *ai)
2444 {
2445   struct alias_map_d *alias_map;
2446   alias_map = XCNEW (struct alias_map_d);
2447   alias_map->var = var;
2448   alias_map->set = get_alias_set (var);
2449   ai->addressable_vars[ai->num_addressable_vars++] = alias_map;
2450 }
2451
2452
2453 /* Create memory tags for all the dereferenced pointers and build the
2454    ADDRESSABLE_VARS and POINTERS arrays used for building the may-alias
2455    sets.  Based on the address escape and points-to information collected
2456    earlier, this pass will also clear the TREE_ADDRESSABLE flag from those
2457    variables whose address is not needed anymore.  */
2458
2459 static void
2460 setup_pointers_and_addressables (struct alias_info *ai)
2461 {
2462   size_t num_addressable_vars, num_pointers;
2463   referenced_var_iterator rvi;
2464   tree var;
2465   VEC (tree, heap) *varvec = NULL;
2466   safe_referenced_var_iterator srvi;
2467
2468   /* Size up the arrays ADDRESSABLE_VARS and POINTERS.  */
2469   num_addressable_vars = num_pointers = 0;
2470   
2471   FOR_EACH_REFERENCED_VAR (var, rvi)
2472     {
2473       if (may_be_aliased (var))
2474         num_addressable_vars++;
2475
2476       if (POINTER_TYPE_P (TREE_TYPE (var)))
2477         {
2478           /* Since we don't keep track of volatile variables, assume that
2479              these pointers are used in indirect store operations.  */
2480           if (TREE_THIS_VOLATILE (var))
2481             pointer_set_insert (ai->dereferenced_ptrs_store, var);
2482
2483           num_pointers++;
2484         }
2485     }
2486
2487   /* Create ADDRESSABLE_VARS and POINTERS.  Note that these arrays are
2488      always going to be slightly bigger than we actually need them
2489      because some TREE_ADDRESSABLE variables will be marked
2490      non-addressable below and only pointers with unique symbol tags are
2491      going to be added to POINTERS.  */
2492   ai->addressable_vars = XCNEWVEC (struct alias_map_d *, num_addressable_vars);
2493   ai->pointers = XCNEWVEC (struct alias_map_d *, num_pointers);
2494   ai->num_addressable_vars = 0;
2495   ai->num_pointers = 0;
2496
2497   FOR_EACH_REFERENCED_VAR_SAFE (var, varvec, srvi)
2498     {
2499       /* Name memory tags already have flow-sensitive aliasing
2500          information, so they need not be processed by
2501          compute_flow_insensitive_aliasing.  Similarly, symbol memory
2502          tags are already accounted for when we process their
2503          associated pointer. 
2504       
2505          Structure fields, on the other hand, have to have some of this
2506          information processed for them, but it's pointless to mark them
2507          non-addressable (since they are fake variables anyway).  */
2508       if (MTAG_P (var))
2509         continue;
2510
2511       /* Remove the ADDRESSABLE flag from every addressable variable whose
2512          address is not needed anymore.  This is caused by the propagation
2513          of ADDR_EXPR constants into INDIRECT_REF expressions and the
2514          removal of dead pointer assignments done by the early scalar
2515          cleanup passes.  */
2516       if (TREE_ADDRESSABLE (var))
2517         {
2518           if (!bitmap_bit_p (gimple_addressable_vars (cfun), DECL_UID (var))
2519               && TREE_CODE (var) != RESULT_DECL
2520               && !is_global_var (var))
2521             {
2522               bool okay_to_mark = true;
2523
2524               /* Since VAR is now a regular GIMPLE register, we will need
2525                  to rename VAR into SSA afterwards.  */
2526               mark_sym_for_renaming (var);
2527
2528               /* The address of VAR is not needed, remove the
2529                  addressable bit, so that it can be optimized as a
2530                  regular variable.  */
2531               if (okay_to_mark)
2532                 {
2533                   /* The memory partition holding VAR will no longer
2534                      contain VAR, and statements referencing it will need
2535                      to be updated.  */
2536                   if (memory_partition (var))
2537                     mark_sym_for_renaming (memory_partition (var));
2538
2539                   mark_non_addressable (var);
2540                 }
2541             }
2542         }
2543
2544       /* Global variables and addressable locals may be aliased.  Create an
2545          entry in ADDRESSABLE_VARS for VAR.  */
2546       if (may_be_aliased (var))
2547         {
2548           create_alias_map_for (var, ai);
2549           mark_sym_for_renaming (var);
2550         }
2551
2552       /* Add pointer variables that have been dereferenced to the POINTERS
2553          array and create a symbol memory tag for them.  */
2554       if (POINTER_TYPE_P (TREE_TYPE (var)))
2555         {
2556           if ((pointer_set_contains (ai->dereferenced_ptrs_store, var)
2557                || pointer_set_contains (ai->dereferenced_ptrs_load, var)))
2558             {
2559               tree tag, old_tag;
2560               var_ann_t t_ann;
2561
2562               /* If pointer VAR still doesn't have a memory tag
2563                  associated with it, create it now or re-use an
2564                  existing one.  */
2565               tag = get_smt_for (var, ai);
2566               t_ann = var_ann (tag);
2567
2568               /* The symbol tag will need to be renamed into SSA
2569                  afterwards. Note that we cannot do this inside
2570                  get_smt_for because aliasing may run multiple times
2571                  and we only create symbol tags the first time.  */
2572               mark_sym_for_renaming (tag);
2573
2574               /* Similarly, if pointer VAR used to have another type
2575                  tag, we will need to process it in the renamer to
2576                  remove the stale virtual operands.  */
2577               old_tag = symbol_mem_tag (var);
2578               if (old_tag)
2579                 mark_sym_for_renaming (old_tag);
2580
2581               /* Associate the tag with pointer VAR.  */
2582               set_symbol_mem_tag (var, tag);
2583
2584               /* If pointer VAR has been used in a store operation,
2585                  then its memory tag must be marked as written-to.  */
2586               if (pointer_set_contains (ai->dereferenced_ptrs_store, var))
2587                 pointer_set_insert (ai->written_vars, tag);
2588             }
2589           else
2590             {
2591               /* The pointer has not been dereferenced.  If it had a
2592                  symbol memory tag, remove it and mark the old tag for
2593                  renaming to remove it out of the IL.  */
2594               tree tag = symbol_mem_tag (var);
2595               if (tag)
2596                 {
2597                   mark_sym_for_renaming (tag);
2598                   set_symbol_mem_tag (var, NULL_TREE);
2599                 }
2600             }
2601         }
2602     }
2603
2604   VEC_free (tree, heap, varvec);
2605 }
2606
2607
2608 /* Determine whether to use .GLOBAL_VAR to model call clobbering
2609    semantics.  If the function makes no references to global
2610    variables and contains at least one call to a non-pure function,
2611    then we need to mark the side-effects of the call using .GLOBAL_VAR
2612    to represent all possible global memory referenced by the callee.  */
2613
2614 static void
2615 maybe_create_global_var (void)
2616 {
2617   /* No need to create it, if we have one already.  */
2618   if (gimple_global_var (cfun) == NULL_TREE)
2619     {
2620       struct mem_ref_stats_d *stats = gimple_mem_ref_stats (cfun);
2621
2622       /* Create .GLOBAL_VAR if there are no call-clobbered
2623          variables and the program contains a mixture of pure/const
2624          and regular function calls.  This is to avoid the problem
2625          described in PR 20115:
2626
2627               int X;
2628               int func_pure (void) { return X; }
2629               int func_non_pure (int a) { X += a; }
2630               int foo ()
2631               {
2632                 int a = func_pure ();
2633                 func_non_pure (a);
2634                 a = func_pure ();
2635                 return a;
2636               }
2637
2638          Since foo() has no call-clobbered variables, there is
2639          no relationship between the calls to func_pure and
2640          func_non_pure.  Since func_pure has no side-effects, value
2641          numbering optimizations elide the second call to func_pure.
2642          So, if we have some pure/const and some regular calls in the
2643          program we create .GLOBAL_VAR to avoid missing these
2644          relations.  */
2645       if (bitmap_empty_p (gimple_call_clobbered_vars (cfun))
2646           && stats->num_call_sites > 0
2647           && stats->num_pure_const_call_sites > 0
2648           && stats->num_call_sites > stats->num_pure_const_call_sites)
2649         create_global_var ();
2650     }
2651 }
2652
2653
2654 /* Return TRUE if pointer PTR may point to variable VAR.
2655    
2656    MEM_ALIAS_SET is the alias set for the memory location pointed-to by PTR
2657         This is needed because when checking for type conflicts we are
2658         interested in the alias set of the memory location pointed-to by
2659         PTR.  The alias set of PTR itself is irrelevant.
2660    
2661    VAR_ALIAS_SET is the alias set for VAR.  */
2662
2663 static bool
2664 may_alias_p (tree ptr, alias_set_type mem_alias_set,
2665              tree var, alias_set_type var_alias_set,
2666              bool alias_set_only)
2667 {
2668   tree mem;
2669
2670   alias_stats.alias_queries++;
2671   alias_stats.simple_queries++;
2672
2673   /* By convention, a variable cannot alias itself.  */
2674   mem = symbol_mem_tag (ptr);
2675   if (mem == var)
2676     {
2677       alias_stats.alias_noalias++;
2678       alias_stats.simple_resolved++;
2679       return false;
2680     }
2681
2682   /* If -fargument-noalias-global is > 2, pointer arguments may
2683      not point to anything else.  */
2684   if (flag_argument_noalias > 2 && TREE_CODE (ptr) == PARM_DECL)
2685     {
2686       alias_stats.alias_noalias++;
2687       alias_stats.simple_resolved++;
2688       return false;
2689     }
2690
2691   /* If -fargument-noalias-global is > 1, pointer arguments may
2692      not point to global variables.  */
2693   if (flag_argument_noalias > 1 && is_global_var (var)
2694       && TREE_CODE (ptr) == PARM_DECL)
2695     {
2696       alias_stats.alias_noalias++;
2697       alias_stats.simple_resolved++;
2698       return false;
2699     }
2700
2701   /* If either MEM or VAR is a read-only global and the other one
2702      isn't, then PTR cannot point to VAR.  */
2703   if ((unmodifiable_var_p (mem) && !unmodifiable_var_p (var))
2704       || (unmodifiable_var_p (var) && !unmodifiable_var_p (mem)))
2705     {
2706       alias_stats.alias_noalias++;
2707       alias_stats.simple_resolved++;
2708       return false;
2709     }
2710
2711   /* If the pointed to memory has alias set zero, or the pointer
2712      is ref-all, or the pointer decl is marked that no TBAA is to
2713      be applied, the MEM can alias VAR.  */
2714   if (mem_alias_set == 0
2715       || DECL_POINTER_ALIAS_SET (ptr) == 0
2716       || TYPE_REF_CAN_ALIAS_ALL (TREE_TYPE (ptr))
2717       || DECL_NO_TBAA_P (ptr))
2718     {
2719       alias_stats.alias_mayalias++;
2720       alias_stats.simple_resolved++;
2721       return true;
2722     }
2723
2724   gcc_assert (TREE_CODE (mem) == SYMBOL_MEMORY_TAG);
2725
2726   alias_stats.tbaa_queries++;
2727
2728   /* If the alias sets don't conflict then MEM cannot alias VAR.  */
2729   if (mem_alias_set != var_alias_set
2730       && !alias_set_subset_of (mem_alias_set, var_alias_set))
2731     {
2732       alias_stats.alias_noalias++;
2733       alias_stats.tbaa_resolved++;
2734       return false;
2735     }
2736
2737   /* If VAR is a record or union type, PTR cannot point into VAR
2738      unless there is some explicit address operation in the
2739      program that can reference a field of the type pointed-to by
2740      PTR.  This also assumes that the types of both VAR and PTR
2741      are contained within the compilation unit, and that there is
2742      no fancy addressing arithmetic associated with any of the
2743      types involved.  */
2744   if (mem_alias_set != 0 && var_alias_set != 0)
2745     {
2746       tree ptr_type = TREE_TYPE (ptr);
2747       tree var_type = TREE_TYPE (var);
2748       
2749       /* The star count is -1 if the type at the end of the
2750          pointer_to chain is not a record or union type. */ 
2751       if (!alias_set_only
2752           && ipa_type_escape_star_count_of_interesting_type (var_type) >= 0)
2753         {
2754           int ptr_star_count = 0;
2755           
2756           /* ipa_type_escape_star_count_of_interesting_type is a
2757              little too restrictive for the pointer type, need to
2758              allow pointers to primitive types as long as those
2759              types cannot be pointers to everything.  */
2760           while (POINTER_TYPE_P (ptr_type))
2761             {
2762               /* Strip the *s off.  */ 
2763               ptr_type = TREE_TYPE (ptr_type);
2764               ptr_star_count++;
2765             }
2766           
2767           /* There does not appear to be a better test to see if
2768              the pointer type was one of the pointer to everything
2769              types.  */
2770           if (ptr_star_count > 0)
2771             {
2772               alias_stats.structnoaddress_queries++;
2773               if (ipa_type_escape_field_does_not_clobber_p (var_type, 
2774                                                             TREE_TYPE (ptr)))
2775                 {
2776                   alias_stats.structnoaddress_resolved++;
2777                   alias_stats.alias_noalias++;
2778                   return false;
2779                 }
2780             }
2781           else if (ptr_star_count == 0)
2782             {
2783               /* If PTR_TYPE was not really a pointer to type, it cannot 
2784                  alias.  */ 
2785               alias_stats.structnoaddress_queries++;
2786               alias_stats.structnoaddress_resolved++;
2787               alias_stats.alias_noalias++;
2788               return false;
2789             }
2790         }
2791     }
2792
2793   alias_stats.alias_mayalias++;
2794   return true;
2795 }
2796
2797
2798 /* Add ALIAS to the set of variables that may alias VAR.  */
2799
2800 static void
2801 add_may_alias (tree var, tree alias)
2802 {
2803   /* Don't allow self-referential aliases.  */
2804   gcc_assert (var != alias);
2805
2806   /* ALIAS must be addressable if it's being added to an alias set.  */
2807 #if 1
2808   TREE_ADDRESSABLE (alias) = 1;
2809 #else
2810   gcc_assert (may_be_aliased (alias));
2811 #endif
2812
2813   /* VAR must be a symbol or a name tag.  */
2814   gcc_assert (TREE_CODE (var) == SYMBOL_MEMORY_TAG
2815               || TREE_CODE (var) == NAME_MEMORY_TAG);
2816
2817   if (MTAG_ALIASES (var) == NULL)
2818     MTAG_ALIASES (var) = BITMAP_ALLOC (&alias_bitmap_obstack);
2819   
2820   bitmap_set_bit (MTAG_ALIASES (var), DECL_UID (alias));
2821 }
2822
2823
2824 /* Mark pointer PTR as pointing to an arbitrary memory location.  */
2825
2826 static void
2827 set_pt_anything (tree ptr)
2828 {
2829   struct ptr_info_def *pi = get_ptr_info (ptr);
2830
2831   pi->pt_anything = 1;
2832   pi->pt_vars = NULL;
2833
2834   /* The pointer used to have a name tag, but we now found it pointing
2835      to an arbitrary location.  The name tag needs to be renamed and
2836      disassociated from PTR.  */
2837   if (pi->name_mem_tag)
2838     {
2839       mark_sym_for_renaming (pi->name_mem_tag);
2840       pi->name_mem_tag = NULL_TREE;
2841     }
2842 }
2843
2844
2845 /* Return true if STMT is an "escape" site from the current function.  Escape
2846    sites those statements which might expose the address of a variable
2847    outside the current function.  STMT is an escape site iff:
2848
2849         1- STMT is a function call, or
2850         2- STMT is an __asm__ expression, or
2851         3- STMT is an assignment to a non-local variable, or
2852         4- STMT is a return statement.
2853
2854    Return the type of escape site found, if we found one, or NO_ESCAPE
2855    if none.  */
2856
2857 enum escape_type
2858 is_escape_site (tree stmt)
2859 {
2860   tree call = get_call_expr_in (stmt);
2861   if (call != NULL_TREE)
2862     {
2863       if (!TREE_SIDE_EFFECTS (call))
2864         return ESCAPE_TO_PURE_CONST;
2865
2866       return ESCAPE_TO_CALL;
2867     }
2868   else if (TREE_CODE (stmt) == ASM_EXPR)
2869     return ESCAPE_TO_ASM;
2870   else if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
2871     {
2872       tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
2873
2874       /* Get to the base of _REF nodes.  */
2875       if (TREE_CODE (lhs) != SSA_NAME)
2876         lhs = get_base_address (lhs);
2877
2878       /* If we couldn't recognize the LHS of the assignment, assume that it
2879          is a non-local store.  */
2880       if (lhs == NULL_TREE)
2881         return ESCAPE_UNKNOWN;
2882
2883       if (CONVERT_EXPR_P (GIMPLE_STMT_OPERAND (stmt, 1))
2884           || TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == VIEW_CONVERT_EXPR)
2885         {
2886           tree from
2887             = TREE_TYPE (TREE_OPERAND (GIMPLE_STMT_OPERAND (stmt, 1), 0));
2888           tree to = TREE_TYPE (GIMPLE_STMT_OPERAND (stmt, 1));
2889
2890           /* If the RHS is a conversion between a pointer and an integer, the
2891              pointer escapes since we can't track the integer.  */
2892           if (POINTER_TYPE_P (from) && !POINTER_TYPE_P (to))
2893             return ESCAPE_BAD_CAST;
2894         }
2895
2896       /* If the LHS is an SSA name, it can't possibly represent a non-local
2897          memory store.  */
2898       if (TREE_CODE (lhs) == SSA_NAME)
2899         return NO_ESCAPE;
2900
2901       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
2902          local variables we cannot be sure if it will escape, because we
2903          don't have information about objects not in SSA form.  Need to
2904          implement something along the lines of
2905
2906          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2907          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2908          Conference on Object-Oriented Programming Systems, Languages, and
2909          Applications (OOPSLA), pp. 1-19, 1999.  */
2910       return ESCAPE_STORED_IN_GLOBAL;
2911     }
2912   else if (TREE_CODE (stmt) == RETURN_EXPR)
2913     return ESCAPE_TO_RETURN;
2914
2915   return NO_ESCAPE;
2916 }
2917
2918 /* Create a new memory tag of type TYPE.
2919    Does NOT push it into the current binding.  */
2920
2921 tree
2922 create_tag_raw (enum tree_code code, tree type, const char *prefix)
2923 {
2924   tree tmp_var;
2925
2926   tmp_var = build_decl (code, create_tmp_var_name (prefix), type);
2927
2928   /* Make the variable writable.  */
2929   TREE_READONLY (tmp_var) = 0;
2930
2931   /* It doesn't start out global.  */
2932   MTAG_GLOBAL (tmp_var) = 0;
2933   TREE_STATIC (tmp_var) = 0;
2934   TREE_USED (tmp_var) = 1;
2935
2936   return tmp_var;
2937 }
2938
2939 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2940    is considered to represent all the pointers whose pointed-to types are
2941    in the same alias set class.  Otherwise, the tag represents a single
2942    SSA_NAME pointer variable.  */
2943
2944 static tree
2945 create_memory_tag (tree type, bool is_type_tag)
2946 {
2947   tree tag = create_tag_raw (is_type_tag ? SYMBOL_MEMORY_TAG : NAME_MEMORY_TAG,
2948                              type, (is_type_tag) ? "SMT" : "NMT");
2949
2950   /* By default, memory tags are local variables.  Alias analysis will
2951      determine whether they should be considered globals.  */
2952   DECL_CONTEXT (tag) = current_function_decl;
2953
2954   /* Memory tags are by definition addressable.  */
2955   TREE_ADDRESSABLE (tag) = 1;
2956
2957   set_symbol_mem_tag (tag, NULL_TREE);
2958
2959   /* Add the tag to the symbol table.  */
2960   add_referenced_var (tag);
2961
2962   return tag;
2963 }
2964
2965
2966 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2967    This is used if P_i has been found to point to a specific set of
2968    variables or to a non-aliased memory location like the address returned
2969    by malloc functions.  */
2970
2971 static tree
2972 get_nmt_for (tree ptr)
2973 {
2974   struct ptr_info_def *pi = get_ptr_info (ptr);
2975   tree tag = pi->name_mem_tag;
2976
2977   if (tag == NULL_TREE)
2978     tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
2979   return tag;
2980 }
2981
2982
2983 /* Return the symbol memory tag associated to pointer PTR.  A memory
2984    tag is an artificial variable that represents the memory location
2985    pointed-to by PTR.  It is used to model the effects of pointer
2986    de-references on addressable variables.
2987    
2988    AI points to the data gathered during alias analysis.  This
2989    function populates the array AI->POINTERS.  */
2990
2991 static tree
2992 get_smt_for (tree ptr, struct alias_info *ai)
2993 {
2994   size_t i;
2995   tree tag;
2996   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
2997   alias_set_type tag_set = get_alias_set (tag_type);
2998
2999   /* To avoid creating unnecessary memory tags, only create one memory tag
3000      per alias set class.  Note that it may be tempting to group
3001      memory tags based on conflicting alias sets instead of
3002      equivalence.  That would be wrong because alias sets are not
3003      necessarily transitive (as demonstrated by the libstdc++ test
3004      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
3005      such that conflicts (A, B) == true and conflicts (A, C) == true,
3006      it does not necessarily follow that conflicts (B, C) == true.  */
3007   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
3008     {
3009       struct alias_map_d *curr = ai->pointers[i];
3010       tree curr_tag = symbol_mem_tag (curr->var);
3011       if (tag_set == curr->set)
3012         {
3013           tag = curr_tag;
3014           break;
3015         }
3016     }
3017
3018   /* If VAR cannot alias with any of the existing memory tags, create a new
3019      tag for PTR and add it to the POINTERS array.  */
3020   if (tag == NULL_TREE)
3021     {
3022       struct alias_map_d *alias_map;
3023
3024       /* If PTR did not have a symbol tag already, create a new SMT.*
3025          artificial variable representing the memory location
3026          pointed-to by PTR.  */
3027       tag = symbol_mem_tag (ptr);
3028       if (tag == NULL_TREE)
3029         tag = create_memory_tag (tag_type, true);
3030
3031       /* Add PTR to the POINTERS array.  Note that we are not interested in
3032          PTR's alias set.  Instead, we cache the alias set for the memory that
3033          PTR points to.  */
3034       alias_map = XCNEW (struct alias_map_d);
3035       alias_map->var = ptr;
3036       alias_map->set = tag_set;
3037       ai->pointers[ai->num_pointers++] = alias_map;
3038     }
3039
3040   /* If the pointed-to type is volatile, so is the tag.  */
3041   TREE_THIS_VOLATILE (tag) |= TREE_THIS_VOLATILE (tag_type);
3042
3043   /* Make sure that the symbol tag has the same alias set as the
3044      pointed-to type or at least accesses through the pointer will
3045      alias that set.  The latter can happen after the vectorizer
3046      created pointers of vector type.  */
3047   gcc_assert (tag_set == get_alias_set (tag)
3048               || alias_set_subset_of (tag_set, get_alias_set (tag)));
3049
3050   return tag;
3051 }
3052
3053
3054 /* Create GLOBAL_VAR, an artificial global variable to act as a
3055    representative of all the variables that may be clobbered by function
3056    calls.  */
3057
3058 static void
3059 create_global_var (void)
3060 {
3061   tree global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
3062                                 void_type_node);
3063   DECL_ARTIFICIAL (global_var) = 1;
3064   TREE_READONLY (global_var) = 0;
3065   DECL_EXTERNAL (global_var) = 1;
3066   TREE_STATIC (global_var) = 1;
3067   TREE_USED (global_var) = 1;
3068   DECL_CONTEXT (global_var) = NULL_TREE;
3069   TREE_THIS_VOLATILE (global_var) = 0;
3070   TREE_ADDRESSABLE (global_var) = 0;
3071
3072   create_var_ann (global_var);
3073   mark_call_clobbered (global_var, ESCAPE_UNKNOWN);
3074   add_referenced_var (global_var);
3075   mark_sym_for_renaming (global_var);
3076   cfun->gimple_df->global_var = global_var;
3077 }
3078
3079
3080 /* Dump alias statistics on FILE.  */
3081
3082 static void 
3083 dump_alias_stats (FILE *file)
3084 {
3085   const char *funcname
3086     = lang_hooks.decl_printable_name (current_function_decl, 2);
3087   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
3088   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
3089   fprintf (file, "Total alias mayalias results:\t%u\n", 
3090            alias_stats.alias_mayalias);
3091   fprintf (file, "Total alias noalias results:\t%u\n",
3092            alias_stats.alias_noalias);
3093   fprintf (file, "Total simple queries:\t%u\n",
3094            alias_stats.simple_queries);
3095   fprintf (file, "Total simple resolved:\t%u\n",
3096            alias_stats.simple_resolved);
3097   fprintf (file, "Total TBAA queries:\t%u\n",
3098            alias_stats.tbaa_queries);
3099   fprintf (file, "Total TBAA resolved:\t%u\n",
3100            alias_stats.tbaa_resolved);
3101   fprintf (file, "Total non-addressable structure type queries:\t%u\n",
3102            alias_stats.structnoaddress_queries);
3103   fprintf (file, "Total non-addressable structure type resolved:\t%u\n",
3104            alias_stats.structnoaddress_resolved);
3105 }
3106   
3107
3108 /* Dump alias information on FILE.  */
3109
3110 void
3111 dump_alias_info (FILE *file)
3112 {
3113   size_t i;
3114   const char *funcname
3115     = lang_hooks.decl_printable_name (current_function_decl, 2);
3116   referenced_var_iterator rvi;
3117   tree var;
3118
3119   fprintf (file, "\nAlias information for %s\n\n", funcname);
3120
3121   dump_memory_partitions (file);
3122
3123   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
3124
3125   fprintf (file, "Aliased symbols\n\n");
3126   
3127   FOR_EACH_REFERENCED_VAR (var, rvi)
3128     {
3129       if (may_be_aliased (var))
3130         dump_variable (file, var);
3131     }
3132
3133   fprintf (file, "\nDereferenced pointers\n\n");
3134
3135   FOR_EACH_REFERENCED_VAR (var, rvi)
3136     if (symbol_mem_tag (var))
3137       dump_variable (file, var);
3138
3139   fprintf (file, "\nSymbol memory tags\n\n");
3140   
3141   FOR_EACH_REFERENCED_VAR (var, rvi)
3142     {
3143       if (TREE_CODE (var) == SYMBOL_MEMORY_TAG)
3144         dump_variable (file, var);
3145     }
3146
3147   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
3148
3149   fprintf (file, "SSA_NAME pointers\n\n");
3150   for (i = 1; i < num_ssa_names; i++)
3151     {
3152       tree ptr = ssa_name (i);
3153       struct ptr_info_def *pi;
3154       
3155       if (ptr == NULL_TREE)
3156         continue;
3157
3158       pi = SSA_NAME_PTR_INFO (ptr);
3159       if (!SSA_NAME_IN_FREE_LIST (ptr)
3160           && pi
3161           && pi->name_mem_tag)
3162         dump_points_to_info_for (file, ptr);
3163     }
3164
3165   fprintf (file, "\nName memory tags\n\n");
3166   
3167   FOR_EACH_REFERENCED_VAR (var, rvi)
3168     {
3169       if (TREE_CODE (var) == NAME_MEMORY_TAG)
3170         dump_variable (file, var);
3171     }
3172
3173   fprintf (file, "\n");
3174 }
3175
3176
3177 /* Dump alias information on stderr.  */
3178
3179 void
3180 debug_alias_info (void)
3181 {
3182   dump_alias_info (stderr);
3183 }
3184
3185
3186 /* Return the alias information associated with pointer T.  It creates a
3187    new instance if none existed.  */
3188
3189 struct ptr_info_def *
3190 get_ptr_info (tree t)
3191 {
3192   struct ptr_info_def *pi;
3193
3194   gcc_assert (POINTER_TYPE_P (TREE_TYPE (t)));
3195
3196   pi = SSA_NAME_PTR_INFO (t);
3197   if (pi == NULL)
3198     {
3199       pi = GGC_CNEW (struct ptr_info_def);
3200       SSA_NAME_PTR_INFO (t) = pi;
3201     }
3202
3203   return pi;
3204 }
3205
3206
3207 /* Dump points-to information for SSA_NAME PTR into FILE.  */
3208
3209 void
3210 dump_points_to_info_for (FILE *file, tree ptr)
3211 {
3212   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
3213
3214   print_generic_expr (file, ptr, dump_flags);
3215
3216   if (pi)
3217     {
3218       if (pi->name_mem_tag)
3219         {
3220           fprintf (file, ", name memory tag: ");
3221           print_generic_expr (file, pi->name_mem_tag, dump_flags);
3222         }
3223
3224       if (pi->is_dereferenced)
3225         fprintf (file, ", is dereferenced");
3226
3227       if (pi->value_escapes_p)
3228         fprintf (file, ", its value escapes");
3229
3230       if (pi->pt_anything)
3231         fprintf (file, ", points-to anything");
3232
3233       if (pi->pt_null)
3234         fprintf (file, ", points-to NULL");
3235
3236       if (pi->pt_vars)
3237         {
3238           fprintf (file, ", points-to vars: ");
3239           dump_decl_set (file, pi->pt_vars);
3240         }
3241     }
3242
3243   fprintf (file, "\n");
3244 }
3245
3246
3247 /* Dump points-to information for VAR into stderr.  */
3248
3249 void
3250 debug_points_to_info_for (tree var)
3251 {
3252   dump_points_to_info_for (stderr, var);
3253 }
3254
3255
3256 /* Dump points-to information into FILE.  NOTE: This function is slow, as
3257    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
3258
3259 void
3260 dump_points_to_info (FILE *file)
3261 {
3262   basic_block bb;
3263   block_stmt_iterator si;
3264   ssa_op_iter iter;
3265   const char *fname =
3266     lang_hooks.decl_printable_name (current_function_decl, 2);
3267   referenced_var_iterator rvi;
3268   tree var;
3269
3270   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
3271
3272   /* First dump points-to information for the default definitions of
3273      pointer variables.  This is necessary because default definitions are
3274      not part of the code.  */
3275   FOR_EACH_REFERENCED_VAR (var, rvi)
3276     {
3277       if (POINTER_TYPE_P (TREE_TYPE (var)))
3278         {
3279           tree def = gimple_default_def (cfun, var);
3280           if (def)
3281             dump_points_to_info_for (file, def);
3282         }
3283     }
3284
3285   /* Dump points-to information for every pointer defined in the program.  */
3286   FOR_EACH_BB (bb)
3287     {
3288       tree phi;
3289
3290       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
3291         {
3292           tree ptr = PHI_RESULT (phi);
3293           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
3294             dump_points_to_info_for (file, ptr);
3295         }
3296
3297         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
3298           {
3299             tree stmt = bsi_stmt (si);
3300             tree def;
3301             FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3302               if (TREE_CODE (def) == SSA_NAME
3303                   && POINTER_TYPE_P (TREE_TYPE (def)))
3304                 dump_points_to_info_for (file, def);
3305           }
3306     }
3307
3308   fprintf (file, "\n");
3309 }
3310
3311
3312 /* Dump points-to info pointed to by PTO into STDERR.  */
3313
3314 void
3315 debug_points_to_info (void)
3316 {
3317   dump_points_to_info (stderr);
3318 }
3319
3320 /* Dump to FILE the list of variables that may be aliasing VAR.  */
3321
3322 void
3323 dump_may_aliases_for (FILE *file, tree var)
3324 {
3325   bitmap aliases;
3326   
3327   aliases = MTAG_ALIASES (var);
3328   if (aliases)
3329     {
3330       bitmap_iterator bi;
3331       unsigned int i;
3332       tree al;
3333
3334       fprintf (file, "{ ");
3335       EXECUTE_IF_SET_IN_BITMAP (aliases, 0, i, bi)
3336         {
3337           al = referenced_var (i);
3338           print_generic_expr (file, al, dump_flags);
3339           fprintf (file, " ");
3340         }
3341       fprintf (file, "}");
3342     }
3343 }
3344
3345
3346 /* Dump to stderr the list of variables that may be aliasing VAR.  */
3347
3348 void
3349 debug_may_aliases_for (tree var)
3350 {
3351   dump_may_aliases_for (stderr, var);
3352 }
3353
3354
3355 /* Return true if VAR may be aliased.  */
3356
3357 bool
3358 may_be_aliased (tree var)
3359 {
3360   /* Obviously.  */
3361   if (TREE_ADDRESSABLE (var))
3362     return true;
3363
3364   /* Globally visible variables can have their addresses taken by other
3365      translation units.  */
3366   if (MTAG_P (var)
3367       && (MTAG_GLOBAL (var) || TREE_PUBLIC (var)))
3368     return true;
3369   else if (!MTAG_P (var)
3370            && (DECL_EXTERNAL (var) || TREE_PUBLIC (var)))
3371     return true;
3372
3373   /* Automatic variables can't have their addresses escape any other
3374      way.  This must be after the check for global variables, as
3375      extern declarations do not have TREE_STATIC set.  */
3376   if (!TREE_STATIC (var))
3377     return false;
3378
3379   /* If we're in unit-at-a-time mode, then we must have seen all
3380      occurrences of address-of operators, and so we can trust
3381      TREE_ADDRESSABLE.  Otherwise we can only be sure the variable
3382      isn't addressable if it's local to the current function.  */
3383   if (flag_unit_at_a_time)
3384     return false;
3385
3386   if (decl_function_context (var) == current_function_decl)
3387     return false;
3388
3389   return true;
3390 }
3391
3392 /* The following is based on code in add_stmt_operand to ensure that the
3393    same defs/uses/vdefs/vuses will be found after replacing a reference
3394    to var (or ARRAY_REF to var) with an INDIRECT_REF to ptr whose value
3395    is the address of var.  Return a memtag for the ptr, after adding the 
3396    proper may_aliases to it (which are the aliases of var, if it has any,
3397    or var itself).  */
3398
3399 static tree
3400 add_may_alias_for_new_tag (tree tag, tree var)
3401 {
3402   bitmap aliases = NULL;
3403   
3404   if (MTAG_P (var))
3405     aliases = may_aliases (var);
3406
3407   /* Case 1: |aliases| == 1  */
3408   if (aliases
3409       && bitmap_single_bit_set_p (aliases))
3410     {
3411       tree ali = referenced_var (bitmap_first_set_bit (aliases));
3412       if (TREE_CODE (ali) == SYMBOL_MEMORY_TAG)
3413         return ali;
3414     }
3415
3416   /* Case 2: |aliases| == 0  */
3417   if (aliases == NULL)
3418     add_may_alias (tag, var);
3419   else
3420     {
3421       /* Case 3: |aliases| > 1  */
3422       union_alias_set_into (tag, aliases);
3423     }
3424   return tag;
3425 }
3426
3427 /* Create a new symbol tag for PTR.  Construct the may-alias list of
3428    this type tag so that it has the aliasing of VAR according to the
3429    location accessed by EXPR.
3430
3431    Note, the set of aliases represented by the new symbol tag are not
3432    marked for renaming.  */
3433
3434 void
3435 new_type_alias (tree ptr, tree var, tree expr)
3436 {
3437   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
3438   tree tag;
3439   tree ali = NULL_TREE;
3440   HOST_WIDE_INT offset, size, maxsize;
3441   tree ref;
3442
3443   gcc_assert (symbol_mem_tag (ptr) == NULL_TREE);
3444   gcc_assert (!MTAG_P (var));
3445
3446   ref = get_ref_base_and_extent (expr, &offset, &size, &maxsize);
3447   gcc_assert (ref);
3448
3449   tag = create_memory_tag (tag_type, true);
3450   set_symbol_mem_tag (ptr, tag);
3451
3452   ali = add_may_alias_for_new_tag (tag, var);
3453
3454   set_symbol_mem_tag (ptr, ali);
3455   MTAG_GLOBAL (tag) = is_global_var (var);
3456 }
3457
3458
3459 /* Reset the call_clobbered flags on our referenced vars.  In
3460    theory, this only needs to be done for globals.  */
3461
3462 static unsigned int
3463 reset_cc_flags (void)
3464 {
3465   tree var;
3466   referenced_var_iterator rvi;
3467
3468   FOR_EACH_REFERENCED_VAR (var, rvi)
3469     var_ann (var)->call_clobbered = false;
3470   return 0;
3471 }
3472
3473 struct gimple_opt_pass pass_reset_cc_flags =
3474 {
3475  {
3476   GIMPLE_PASS,
3477   NULL,          /* name */
3478   NULL,          /* gate */
3479   reset_cc_flags, /* execute */
3480   NULL,                  /* sub */
3481   NULL,                  /* next */
3482   0,                     /* static_pass_number */
3483   0,                     /* tv_id */
3484   PROP_referenced_vars |PROP_cfg, /* properties_required */
3485   0,                     /* properties_provided */
3486   0,                     /* properties_destroyed */
3487   0,                     /* todo_flags_start */
3488   0                      /* todo_flags_finish */
3489  }
3490 };
3491
3492
3493 /* A dummy pass to cause aliases to be computed via TODO_rebuild_alias.  */
3494
3495 struct gimple_opt_pass pass_build_alias =
3496 {
3497  {
3498   GIMPLE_PASS,
3499   "alias",                  /* name */
3500   NULL,                     /* gate */
3501   NULL,                     /* execute */
3502   NULL,                     /* sub */
3503   NULL,                     /* next */
3504   0,                        /* static_pass_number */
3505   0,                        /* tv_id */
3506   PROP_cfg | PROP_ssa,      /* properties_required */
3507   PROP_alias,               /* properties_provided */
3508   0,                        /* properties_destroyed */
3509   0,                        /* todo_flags_start */
3510   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
3511  }
3512 };