OSDN Git Service

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