OSDN Git Service

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