OSDN Git Service

* c-decl.c (pushdecl): When an extern declaration at block scope
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-alias.c
1 /* Alias analysis for trees.
2    Copyright (C) 2004 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, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, 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 "convert.h"
44 #include "params.h"
45
46
47 /* Structure to map a variable to its alias set and keep track of the
48    virtual operands that will be needed to represent it.  */
49 struct alias_map_d
50 {
51   /* Variable and its alias set.  */
52   tree var;
53   HOST_WIDE_INT set;
54
55   /* Total number of virtual operands that will be needed to represent
56      all the aliases of VAR.  */
57   long total_alias_vops;
58
59   /* Nonzero if the aliases for this memory tag have been grouped
60      already.  Used in group_aliases.  */
61   unsigned int grouped_p : 1;
62
63   /* Set of variables aliased with VAR.  This is the exact same
64      information contained in VAR_ANN (VAR)->MAY_ALIASES, but in
65      bitmap form to speed up alias grouping.  */
66   sbitmap may_aliases;
67 };
68
69
70 /* Alias information used by compute_may_aliases and its helpers.  */
71 struct alias_info
72 {
73   /* SSA names visited while collecting points-to information.  If bit I
74      is set, it means that SSA variable with version I has already been
75      visited.  */
76   bitmap ssa_names_visited;
77
78   /* Array of SSA_NAME pointers processed by the points-to collector.  */
79   varray_type processed_ptrs;
80
81   /* Variables whose address is still needed.  */
82   bitmap addresses_needed;
83
84   /* ADDRESSABLE_VARS contains all the global variables and locals that
85      have had their address taken.  */
86   struct alias_map_d **addressable_vars;
87   size_t num_addressable_vars;
88
89   /* POINTERS contains all the _DECL pointers with unique memory tags
90      that have been referenced in the program.  */
91   struct alias_map_d **pointers;
92   size_t num_pointers;
93
94   /* Number of function calls found in the program.  */
95   size_t num_calls_found;
96
97   /* Array of counters to keep track of how many times each pointer has
98      been dereferenced in the program.  This is used by the alias grouping
99      heuristic in compute_flow_insensitive_aliasing.  */
100   varray_type num_references;
101
102   /* Total number of virtual operands that will be needed to represent
103      all the aliases of all the pointers found in the program.  */
104   long total_alias_vops;
105
106   /* Variables that have been written to.  */
107   bitmap written_vars;
108
109   /* Pointers that have been used in an indirect store operation.  */
110   bitmap dereferenced_ptrs_store;
111
112   /* Pointers that have been used in an indirect load operation.  */
113   bitmap dereferenced_ptrs_load;
114 };
115
116
117 /* Counters used to display statistics on alias analysis.  */
118 struct alias_stats_d
119 {
120   unsigned int alias_queries;
121   unsigned int alias_mayalias;
122   unsigned int alias_noalias;
123   unsigned int simple_queries;
124   unsigned int simple_resolved;
125   unsigned int tbaa_queries;
126   unsigned int tbaa_resolved;
127 };
128
129
130 /* Local variables.  */
131 static struct alias_stats_d alias_stats;
132
133 /* Local functions.  */
134 static void compute_flow_insensitive_aliasing (struct alias_info *);
135 static void dump_alias_stats (FILE *);
136 static bool may_alias_p (tree, HOST_WIDE_INT, tree, HOST_WIDE_INT);
137 static tree create_memory_tag (tree type, bool is_type_tag);
138 static tree get_tmt_for (tree, struct alias_info *);
139 static tree get_nmt_for (tree);
140 static void add_may_alias (tree, tree);
141 static void replace_may_alias (tree, size_t, tree);
142 static struct alias_info *init_alias_info (void);
143 static void delete_alias_info (struct alias_info *);
144 static void compute_points_to_and_addr_escape (struct alias_info *);
145 static void compute_flow_sensitive_aliasing (struct alias_info *);
146 static void setup_pointers_and_addressables (struct alias_info *);
147 static bool collect_points_to_info_r (tree, tree, void *);
148 static bool is_escape_site (tree, size_t *);
149 static void add_pointed_to_var (struct alias_info *, tree, tree);
150 static void create_global_var (void);
151 static void collect_points_to_info_for (struct alias_info *, tree);
152 static bool ptr_is_dereferenced_by (tree, tree, bool *);
153 static void maybe_create_global_var (struct alias_info *ai);
154 static void group_aliases (struct alias_info *);
155 static struct ptr_info_def *get_ptr_info (tree t);
156 static void set_pt_anything (tree ptr);
157 static void set_pt_malloc (tree ptr);
158
159 /* Global declarations.  */
160
161 /* Call clobbered variables in the function.  If bit I is set, then
162    REFERENCED_VARS (I) is call-clobbered.  */
163 bitmap call_clobbered_vars;
164
165 /* Addressable variables in the function.  If bit I is set, then
166    REFERENCED_VARS (I) has had its address taken.  Note that
167    CALL_CLOBBERED_VARS and ADDRESSABLE_VARS are not related.  An
168    addressable variable is not necessarily call-clobbered (e.g., a
169    local addressable whose address does not escape) and not all
170    call-clobbered variables are addressable (e.g., a local static
171    variable).  */
172 bitmap addressable_vars;
173
174 /* When the program has too many call-clobbered variables and call-sites,
175    this variable is used to represent the clobbering effects of function
176    calls.  In these cases, all the call clobbered variables in the program
177    are forced to alias this variable.  This reduces compile times by not
178    having to keep track of too many V_MAY_DEF expressions at call sites.  */
179 tree global_var;
180
181
182 /* Compute may-alias information for every variable referenced in function
183    FNDECL.
184
185    Alias analysis proceeds in 3 main phases:
186
187    1- Points-to and escape analysis.
188
189    This phase walks the use-def chains in the SSA web looking for three
190    things:
191
192         * Assignments of the form P_i = &VAR
193         * Assignments of the form P_i = malloc()
194         * Pointers and ADDR_EXPR that escape the current function.
195
196    The concept of 'escaping' is the same one used in the Java world.  When
197    a pointer or an ADDR_EXPR escapes, it means that it has been exposed
198    outside of the current function.  So, assignment to global variables,
199    function arguments and returning a pointer are all escape sites.
200
201    This is where we are currently limited.  Since not everything is renamed
202    into SSA, we lose track of escape properties when a pointer is stashed
203    inside a field in a structure, for instance.  In those cases, we are
204    assuming that the pointer does escape.
205
206    We use escape analysis to determine whether a variable is
207    call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the variable
208    is call-clobbered.  If a pointer P_i escapes, then all the variables
209    pointed-to by P_i (and its memory tag) also escape.
210
211    2- Compute flow-sensitive aliases
212
213    We have two classes of memory tags.  Memory tags associated with the
214    pointed-to data type of the pointers in the program.  These tags are
215    called "type memory tag" (TMT).  The other class are those associated
216    with SSA_NAMEs, called "name memory tag" (NMT). The basic idea is that
217    when adding operands for an INDIRECT_REF *P_i, we will first check
218    whether P_i has a name tag, if it does we use it, because that will have
219    more precise aliasing information.  Otherwise, we use the standard type
220    tag.
221
222    In this phase, we go through all the pointers we found in points-to
223    analysis and create alias sets for the name memory tags associated with
224    each pointer P_i.  If P_i escapes, we mark call-clobbered the variables
225    it points to and its tag.
226
227
228    3- Compute flow-insensitive aliases
229
230    This pass will compare the alias set of every type memory tag and every
231    addressable variable found in the program.  Given a type memory tag TMT
232    and an addressable variable V.  If the alias sets of TMT and V conflict
233    (as computed by may_alias_p), then V is marked as an alias tag and added
234    to the alias set of TMT.
235
236    For instance, consider the following function:
237
238             foo (int i)
239             {
240               int *p, *q, a, b;
241             
242               if (i > 10)
243                 p = &a;
244               else
245                 q = &b;
246             
247               *p = 3;
248               *q = 5;
249               a = b + 2;
250               return *p;
251             }
252
253    After aliasing analysis has finished, the type memory tag for pointer
254    'p' will have two aliases, namely variables 'a' and 'b'.  Every time
255    pointer 'p' is dereferenced, we want to mark the operation as a
256    potential reference to 'a' and 'b'.
257
258             foo (int i)
259             {
260               int *p, a, b;
261
262               if (i_2 > 10)
263                 p_4 = &a;
264               else
265                 p_6 = &b;
266               # p_1 = PHI <p_4(1), p_6(2)>;
267
268               # a_7 = V_MAY_DEF <a_3>;
269               # b_8 = V_MAY_DEF <b_5>;
270               *p_1 = 3;
271
272               # a_9 = V_MAY_DEF <a_7>
273               # VUSE <b_8>
274               a_9 = b_8 + 2;
275
276               # VUSE <a_9>;
277               # VUSE <b_8>;
278               return *p_1;
279             }
280
281    In certain cases, the list of may aliases for a pointer may grow too
282    large.  This may cause an explosion in the number of virtual operands
283    inserted in the code.  Resulting in increased memory consumption and
284    compilation time.
285
286    When the number of virtual operands needed to represent aliased
287    loads and stores grows too large (configurable with @option{--param
288    max-aliased-vops}), alias sets are grouped to avoid severe
289    compile-time slow downs and memory consumption.  See group_aliases.  */
290
291 static void
292 compute_may_aliases (void)
293 {
294   struct alias_info *ai;
295   
296   memset (&alias_stats, 0, sizeof (alias_stats));
297
298   /* Initialize aliasing information.  */
299   ai = init_alias_info ();
300
301   /* For each pointer P_i, determine the sets of variables that P_i may
302      point-to.  For every addressable variable V, determine whether the
303      address of V escapes the current function, making V call-clobbered
304      (i.e., whether &V is stored in a global variable or if its passed as a
305      function call argument).  */
306   compute_points_to_and_addr_escape (ai);
307
308   /* Collect all pointers and addressable variables, compute alias sets,
309      create memory tags for pointers and promote variables whose address is
310      not needed anymore.  */
311   setup_pointers_and_addressables (ai);
312
313   /* Compute flow-sensitive, points-to based aliasing for all the name
314      memory tags.  Note that this pass needs to be done before flow
315      insensitive analysis because it uses the points-to information
316      gathered before to mark call-clobbered type tags.  */
317   compute_flow_sensitive_aliasing (ai);
318
319   /* Compute type-based flow-insensitive aliasing for all the type
320      memory tags.  */
321   compute_flow_insensitive_aliasing (ai);
322
323   /* If the program has too many call-clobbered variables and/or function
324      calls, create .GLOBAL_VAR and use it to model call-clobbering
325      semantics at call sites.  This reduces the number of virtual operands
326      considerably, improving compile times at the expense of lost
327      aliasing precision.  */
328   maybe_create_global_var (ai);
329
330   /* Debugging dumps.  */
331   if (dump_file)
332     {
333       dump_referenced_vars (dump_file);
334       if (dump_flags & TDF_STATS)
335         dump_alias_stats (dump_file);
336       dump_points_to_info (dump_file);
337       dump_alias_info (dump_file);
338     }
339
340   /* Deallocate memory used by aliasing data structures.  */
341   delete_alias_info (ai);
342 }
343
344 struct tree_opt_pass pass_may_alias = 
345 {
346   "alias",                              /* name */
347   NULL,                                 /* gate */
348   compute_may_aliases,                  /* execute */
349   NULL,                                 /* sub */
350   NULL,                                 /* next */
351   0,                                    /* static_pass_number */
352   TV_TREE_MAY_ALIAS,                    /* tv_id */
353   PROP_cfg | PROP_ssa,                  /* properties_required */
354   PROP_alias,                           /* properties_provided */
355   0,                                    /* properties_destroyed */
356   0,                                    /* todo_flags_start */
357   TODO_dump_func | TODO_rename_vars
358     | TODO_ggc_collect | TODO_verify_ssa,  /* todo_flags_finish */
359   0                                     /* letter */
360 };
361
362
363 /* Initialize the data structures used for alias analysis.  */
364
365 static struct alias_info *
366 init_alias_info (void)
367 {
368   struct alias_info *ai;
369   static bool aliases_computed_p = false;
370
371   ai = xcalloc (1, sizeof (struct alias_info));
372   ai->ssa_names_visited = BITMAP_XMALLOC ();
373   VARRAY_TREE_INIT (ai->processed_ptrs, 50, "processed_ptrs");
374   ai->addresses_needed = BITMAP_XMALLOC ();
375   VARRAY_UINT_INIT (ai->num_references, num_referenced_vars, "num_references");
376   ai->written_vars = BITMAP_XMALLOC ();
377   ai->dereferenced_ptrs_store = BITMAP_XMALLOC ();
378   ai->dereferenced_ptrs_load = BITMAP_XMALLOC ();
379
380   /* If aliases have been computed before, clear existing information.  */
381   if (aliases_computed_p)
382     {
383       size_t i;
384       bitmap_iterator bi;
385
386       /* Clear the call-clobbered set.  We are going to re-discover
387           call-clobbered variables.  */
388       EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, bi)
389         {
390           tree var = referenced_var (i);
391
392           /* Variables that are intrinsically call-clobbered (globals,
393              local statics, etc) will not be marked by the aliasing
394              code, so we can't remove them from CALL_CLOBBERED_VARS.  */
395           if (!is_call_clobbered (var))
396             bitmap_clear_bit (call_clobbered_vars, var_ann (var)->uid);
397         }
398
399       /* Similarly, clear the set of addressable variables.  In this
400          case, we can just clear the set because addressability is
401          only computed here.  */
402       bitmap_clear (addressable_vars);
403
404       /* Clear flow-insensitive alias information from each symbol.  */
405       for (i = 0; i < num_referenced_vars; i++)
406         {
407           var_ann_t ann = var_ann (referenced_var (i));
408           ann->is_alias_tag = 0;
409           ann->may_aliases = NULL;
410         }
411
412       /* Clear flow-sensitive points-to information from each SSA name.  */
413       for (i = 1; i < num_ssa_names; i++)
414         {
415           tree name = ssa_name (i);
416
417           if (!name || !POINTER_TYPE_P (TREE_TYPE (name)))
418             continue;
419
420           if (SSA_NAME_PTR_INFO (name))
421             {
422               struct ptr_info_def *pi = SSA_NAME_PTR_INFO (name);
423
424               /* Clear all the flags but keep the name tag to
425                  avoid creating new temporaries unnecessarily.  If
426                  this pointer is found to point to a subset or
427                  superset of its former points-to set, then a new
428                  tag will need to be created in create_name_tags.  */
429               pi->pt_anything = 0;
430               pi->pt_malloc = 0;
431               pi->value_escapes_p = 0;
432               pi->is_dereferenced = 0;
433               if (pi->pt_vars)
434                 bitmap_clear (pi->pt_vars);
435             }
436         }
437     }
438
439   /* Next time, we will need to reset alias information.  */
440   aliases_computed_p = true;
441
442   return ai;
443 }
444
445
446 /* Deallocate memory used by alias analysis.  */
447
448 static void
449 delete_alias_info (struct alias_info *ai)
450 {
451   size_t i;
452
453   BITMAP_XFREE (ai->ssa_names_visited);
454   ai->processed_ptrs = NULL;
455   BITMAP_XFREE (ai->addresses_needed);
456
457   for (i = 0; i < ai->num_addressable_vars; i++)
458     {
459       sbitmap_free (ai->addressable_vars[i]->may_aliases);
460       free (ai->addressable_vars[i]);
461     }
462   free (ai->addressable_vars);
463
464   for (i = 0; i < ai->num_pointers; i++)
465     {
466       sbitmap_free (ai->pointers[i]->may_aliases);
467       free (ai->pointers[i]);
468     }
469   free (ai->pointers);
470
471   ai->num_references = NULL;
472   BITMAP_XFREE (ai->written_vars);
473   BITMAP_XFREE (ai->dereferenced_ptrs_store);
474   BITMAP_XFREE (ai->dereferenced_ptrs_load);
475
476   free (ai);
477 }
478
479
480 /* Walk use-def chains for pointer PTR to determine what variables is PTR
481    pointing to.  */
482
483 static void
484 collect_points_to_info_for (struct alias_info *ai, tree ptr)
485 {
486   gcc_assert (POINTER_TYPE_P (TREE_TYPE (ptr)));
487
488   if (!bitmap_bit_p (ai->ssa_names_visited, SSA_NAME_VERSION (ptr)))
489     {
490       bitmap_set_bit (ai->ssa_names_visited, SSA_NAME_VERSION (ptr));
491       walk_use_def_chains (ptr, collect_points_to_info_r, ai, true);
492       VARRAY_PUSH_TREE (ai->processed_ptrs, ptr);
493     }
494 }
495
496
497 /* Helper for ptr_is_dereferenced_by.  Called by walk_tree to look for
498    (ALIGN/MISALIGNED_)INDIRECT_REF nodes for the pointer passed in DATA.  */
499
500 static tree
501 find_ptr_dereference (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
502 {
503   tree ptr = (tree) data;
504
505   if (INDIRECT_REF_P (*tp)
506       && TREE_OPERAND (*tp, 0) == ptr)
507     return *tp;
508
509   return NULL_TREE;
510 }
511
512
513 /* Return true if STMT contains (ALIGN/MISALIGNED_)INDIRECT_REF <PTR>.  
514    *IS_STORE is set to 'true' if the dereference is on the LHS of an 
515    assignment.  */
516
517 static bool
518 ptr_is_dereferenced_by (tree ptr, tree stmt, bool *is_store)
519 {
520   *is_store = false;
521
522   if (TREE_CODE (stmt) == MODIFY_EXPR
523       || (TREE_CODE (stmt) == RETURN_EXPR
524           && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR))
525     {
526       tree e, lhs, rhs;
527
528       e = (TREE_CODE (stmt) == RETURN_EXPR) ? TREE_OPERAND (stmt, 0) : stmt;
529       lhs = TREE_OPERAND (e, 0);
530       rhs = TREE_OPERAND (e, 1);
531
532       if (EXPR_P (lhs)
533           && walk_tree (&lhs, find_ptr_dereference, ptr, NULL))
534         {
535           *is_store = true;
536           return true;
537         }
538       else if (EXPR_P (rhs)
539                && walk_tree (&rhs, find_ptr_dereference, ptr, NULL))
540         {
541           return true;
542         }
543     }
544   else if (TREE_CODE (stmt) == ASM_EXPR)
545     {
546       if (walk_tree (&ASM_OUTPUTS (stmt), find_ptr_dereference, ptr, NULL)
547           || walk_tree (&ASM_CLOBBERS (stmt), find_ptr_dereference, ptr, NULL))
548         {
549           *is_store = true;
550           return true;
551         }
552       else if (walk_tree (&ASM_INPUTS (stmt), find_ptr_dereference, ptr, NULL))
553         {
554           return true;
555         }
556     }
557
558   return false;
559 }
560
561
562 /* Traverse use-def links for all the pointers in the program to collect
563    address escape and points-to information.
564    
565    This is loosely based on the same idea described in R. Hasti and S.
566    Horwitz, ``Using static single assignment form to improve
567    flow-insensitive pointer analysis,'' in SIGPLAN Conference on
568    Programming Language Design and Implementation, pp. 97-105, 1998.  */
569
570 static void
571 compute_points_to_and_addr_escape (struct alias_info *ai)
572 {
573   basic_block bb;
574   size_t i;
575   tree op;
576   ssa_op_iter iter;
577
578   timevar_push (TV_TREE_PTA);
579
580   FOR_EACH_BB (bb)
581     {
582       bb_ann_t block_ann = bb_ann (bb);
583       block_stmt_iterator si;
584
585       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
586         {
587           bitmap addr_taken;
588           tree stmt = bsi_stmt (si);
589           bool stmt_escapes_p = is_escape_site (stmt, &ai->num_calls_found);
590           bitmap_iterator bi;
591
592           /* Mark all the variables whose address are taken by the
593              statement.  Note that this will miss all the addresses taken
594              in PHI nodes (those are discovered while following the use-def
595              chains).  */
596           get_stmt_operands (stmt);
597           addr_taken = addresses_taken (stmt);
598           if (addr_taken)
599             EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
600               {
601                 tree var = referenced_var (i);
602                 bitmap_set_bit (ai->addresses_needed, var_ann (var)->uid);
603                 if (stmt_escapes_p)
604                   mark_call_clobbered (var);
605               }
606
607           if (stmt_escapes_p)
608             block_ann->has_escape_site = 1;
609
610           /* Special case for silly ADDR_EXPR tricks
611              (gcc.c-torture/unsorted/pass.c).  If this statement is an
612              assignment to a non-pointer variable and the RHS takes the
613              address of a variable, assume that the variable on the RHS is
614              call-clobbered.  We could add the LHS to the list of
615              "pointers" and follow it to see if it really escapes, but it's
616              not worth the pain.  */
617           if (addr_taken
618               && TREE_CODE (stmt) == MODIFY_EXPR
619               && !POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 0))))
620             EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
621               {
622                 tree var = referenced_var (i);
623                 mark_call_clobbered (var);
624               }
625
626           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
627             {
628               var_ann_t v_ann = var_ann (SSA_NAME_VAR (op));
629               struct ptr_info_def *pi;
630               bool is_store;
631
632               /* If the operand's variable may be aliased, keep track
633                  of how many times we've referenced it.  This is used
634                  for alias grouping in compute_flow_sensitive_aliasing.
635                  Note that we don't need to grow AI->NUM_REFERENCES
636                  because we are processing regular variables, not
637                  memory tags (the array's initial size is set to
638                  NUM_REFERENCED_VARS).  */
639               if (may_be_aliased (SSA_NAME_VAR (op)))
640                 (VARRAY_UINT (ai->num_references, v_ann->uid))++;
641
642               if (!POINTER_TYPE_P (TREE_TYPE (op)))
643                 continue;
644
645               collect_points_to_info_for (ai, op);
646
647               pi = SSA_NAME_PTR_INFO (op);
648               if (ptr_is_dereferenced_by (op, stmt, &is_store))
649                 {
650                   /* Mark OP as dereferenced.  In a subsequent pass,
651                      dereferenced pointers that point to a set of
652                      variables will be assigned a name tag to alias
653                      all the variables OP points to.  */
654                   pi->is_dereferenced = 1;
655
656                   /* Keep track of how many time we've dereferenced each
657                      pointer.  Again, we don't need to grow
658                      AI->NUM_REFERENCES because we're processing
659                      existing program variables.  */
660                   (VARRAY_UINT (ai->num_references, v_ann->uid))++;
661
662                   /* If this is a store operation, mark OP as being
663                      dereferenced to store, otherwise mark it as being
664                      dereferenced to load.  */
665                   if (is_store)
666                     bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
667                   else
668                     bitmap_set_bit (ai->dereferenced_ptrs_load, v_ann->uid);
669                 }
670               else if (stmt_escapes_p)
671                 {
672                   /* Note that even if STMT is an escape point, pointer OP
673                      will not escape if it is being dereferenced.  That's
674                      why we only check for escape points if OP is not
675                      dereferenced by STMT.  */
676                   pi->value_escapes_p = 1;
677
678                   /* If the statement makes a function call, assume
679                      that pointer OP will be dereferenced in a store
680                      operation inside the called function.  */
681                   if (get_call_expr_in (stmt))
682                     {
683                       bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
684                       pi->is_dereferenced = 1;
685                     }
686                 }
687             }
688
689           /* Update reference counter for definitions to any
690              potentially aliased variable.  This is used in the alias
691              grouping heuristics.  */
692           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
693             {
694               tree var = SSA_NAME_VAR (op);
695               var_ann_t ann = var_ann (var);
696               bitmap_set_bit (ai->written_vars, ann->uid);
697               if (may_be_aliased (var))
698                 (VARRAY_UINT (ai->num_references, ann->uid))++;
699
700               if (POINTER_TYPE_P (TREE_TYPE (op)))
701                 collect_points_to_info_for (ai, op);
702             }
703
704           /* Mark variables in V_MAY_DEF operands as being written to.  */
705           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_VIRTUAL_DEFS)
706             {
707               tree var = SSA_NAME_VAR (op);
708               var_ann_t ann = var_ann (var);
709               bitmap_set_bit (ai->written_vars, ann->uid);
710             }
711             
712           /* After promoting variables and computing aliasing we will
713              need to re-scan most statements.  FIXME: Try to minimize the
714              number of statements re-scanned.  It's not really necessary to
715              re-scan *all* statements.  */
716           modify_stmt (stmt);
717         }
718     }
719
720   timevar_pop (TV_TREE_PTA);
721 }
722
723
724 /* Create name tags for all the pointers that have been dereferenced.
725    We only create a name tag for a pointer P if P is found to point to
726    a set of variables (so that we can alias them to *P) or if it is
727    the result of a call to malloc (which means that P cannot point to
728    anything else nor alias any other variable).
729
730    If two pointers P and Q point to the same set of variables, they
731    are assigned the same name tag.  */
732
733 static void
734 create_name_tags (struct alias_info *ai)
735 {
736   size_t i;
737
738   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
739     {
740       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
741       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
742
743       if (pi->pt_anything || !pi->is_dereferenced)
744         {
745           /* No name tags for pointers that have not been
746              dereferenced or point to an arbitrary location.  */
747           pi->name_mem_tag = NULL_TREE;
748           continue;
749         }
750
751       if (pi->pt_vars
752           && bitmap_first_set_bit (pi->pt_vars) >= 0)
753         {
754           size_t j;
755           tree old_name_tag = pi->name_mem_tag;
756
757           /* If PTR points to a set of variables, check if we don't
758              have another pointer Q with the same points-to set before
759              creating a tag.  If so, use Q's tag instead of creating a
760              new one.
761
762              This is important for not creating unnecessary symbols
763              and also for copy propagation.  If we ever need to
764              propagate PTR into Q or vice-versa, we would run into
765              problems if they both had different name tags because
766              they would have different SSA version numbers (which
767              would force us to take the name tags in and out of SSA).  */
768           for (j = 0; j < i; j++)
769             {
770               tree q = VARRAY_TREE (ai->processed_ptrs, j);
771               struct ptr_info_def *qi = SSA_NAME_PTR_INFO (q);
772
773               if (qi
774                   && qi->pt_vars
775                   && qi->name_mem_tag
776                   && bitmap_equal_p (pi->pt_vars, qi->pt_vars))
777                 {
778                   pi->name_mem_tag = qi->name_mem_tag;
779                   break;
780                 }
781             }
782
783           /* If we didn't find a pointer with the same points-to set
784              as PTR, create a new name tag if needed.  */
785           if (pi->name_mem_tag == NULL_TREE)
786             pi->name_mem_tag = get_nmt_for (ptr);
787
788           /* If the new name tag computed for PTR is different than
789              the old name tag that it used to have, then the old tag
790              needs to be removed from the IL, so we mark it for
791              renaming.  */
792           if (old_name_tag && old_name_tag != pi->name_mem_tag)
793             bitmap_set_bit (vars_to_rename, var_ann (old_name_tag)->uid);
794         }
795       else if (pi->pt_malloc)
796         {
797           /* Otherwise, create a unique name tag for this pointer.  */
798           pi->name_mem_tag = get_nmt_for (ptr);
799         }
800       else
801         {
802           /* Only pointers that may point to malloc or other variables
803              may receive a name tag.  If the pointer does not point to
804              a known spot, we should use type tags.  */
805           set_pt_anything (ptr);
806           continue;
807         }
808
809       TREE_THIS_VOLATILE (pi->name_mem_tag)
810           |= TREE_THIS_VOLATILE (TREE_TYPE (TREE_TYPE (ptr)));
811
812       /* Mark the new name tag for renaming.  */
813       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
814     }
815 }
816
817
818
819 /* For every pointer P_i in AI->PROCESSED_PTRS, create may-alias sets for
820    the name memory tag (NMT) associated with P_i.  If P_i escapes, then its
821    name tag and the variables it points-to are call-clobbered.  Finally, if
822    P_i escapes and we could not determine where it points to, then all the
823    variables in the same alias set as *P_i are marked call-clobbered.  This
824    is necessary because we must assume that P_i may take the address of any
825    variable in the same alias set.  */
826
827 static void
828 compute_flow_sensitive_aliasing (struct alias_info *ai)
829 {
830   size_t i;
831
832   create_name_tags (ai);
833
834   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
835     {
836       size_t j;
837       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
838       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
839       var_ann_t v_ann = var_ann (SSA_NAME_VAR (ptr));
840       bitmap_iterator bi;
841
842       if (pi->value_escapes_p || pi->pt_anything)
843         {
844           /* If PTR escapes or may point to anything, then its associated
845              memory tags and pointed-to variables are call-clobbered.  */
846           if (pi->name_mem_tag)
847             mark_call_clobbered (pi->name_mem_tag);
848
849           if (v_ann->type_mem_tag)
850             mark_call_clobbered (v_ann->type_mem_tag);
851
852           if (pi->pt_vars)
853             EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
854               {
855                 mark_call_clobbered (referenced_var (j));
856               }
857         }
858
859       /* Set up aliasing information for PTR's name memory tag (if it has
860          one).  Note that only pointers that have been dereferenced will
861          have a name memory tag.  */
862       if (pi->name_mem_tag && pi->pt_vars)
863         EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
864           {
865             add_may_alias (pi->name_mem_tag, referenced_var (j));
866           }
867
868       /* If the name tag is call clobbered, so is the type tag
869          associated with the base VAR_DECL.  */
870       if (pi->name_mem_tag
871           && v_ann->type_mem_tag
872           && is_call_clobbered (pi->name_mem_tag))
873         mark_call_clobbered (v_ann->type_mem_tag);
874     }
875 }
876
877
878 /* Compute type-based alias sets.  Traverse all the pointers and
879    addressable variables found in setup_pointers_and_addressables.
880    
881    For every pointer P in AI->POINTERS and addressable variable V in
882    AI->ADDRESSABLE_VARS, add V to the may-alias sets of P's type
883    memory tag (TMT) if their alias sets conflict.  V is then marked as
884    an alias tag so that the operand scanner knows that statements
885    containing V have aliased operands.  */
886
887 static void
888 compute_flow_insensitive_aliasing (struct alias_info *ai)
889 {
890   size_t i;
891   sbitmap res;
892
893   /* Initialize counter for the total number of virtual operands that
894      aliasing will introduce.  When AI->TOTAL_ALIAS_VOPS goes beyond the
895      threshold set by --params max-alias-vops, we enable alias
896      grouping.  */
897   ai->total_alias_vops = 0;
898
899   /* For every pointer P, determine which addressable variables may alias
900      with P's type memory tag.  */
901   for (i = 0; i < ai->num_pointers; i++)
902     {
903       size_t j;
904       struct alias_map_d *p_map = ai->pointers[i];
905       tree tag = var_ann (p_map->var)->type_mem_tag;
906       var_ann_t tag_ann = var_ann (tag);
907
908       p_map->total_alias_vops = 0;
909       p_map->may_aliases = sbitmap_alloc (num_referenced_vars);
910       sbitmap_zero (p_map->may_aliases);
911
912       for (j = 0; j < ai->num_addressable_vars; j++)
913         {
914           struct alias_map_d *v_map;
915           var_ann_t v_ann;
916           tree var;
917           bool tag_stored_p, var_stored_p;
918           
919           v_map = ai->addressable_vars[j];
920           var = v_map->var;
921           v_ann = var_ann (var);
922
923           /* Skip memory tags and variables that have never been
924              written to.  We also need to check if the variables are
925              call-clobbered because they may be overwritten by
926              function calls.  */
927           tag_stored_p = bitmap_bit_p (ai->written_vars, tag_ann->uid)
928                          || is_call_clobbered (tag);
929           var_stored_p = bitmap_bit_p (ai->written_vars, v_ann->uid)
930                          || is_call_clobbered (var);
931           if (!tag_stored_p && !var_stored_p)
932             continue;
933              
934           if (may_alias_p (p_map->var, p_map->set, var, v_map->set))
935             {
936               size_t num_tag_refs, num_var_refs;
937
938               num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
939               num_var_refs = VARRAY_UINT (ai->num_references, v_ann->uid);
940
941               /* Add VAR to TAG's may-aliases set.  */
942               add_may_alias (tag, var);
943
944               /* Update the total number of virtual operands due to
945                  aliasing.  Since we are adding one more alias to TAG's
946                  may-aliases set, the total number of virtual operands due
947                  to aliasing will be increased by the number of references
948                  made to VAR and TAG (every reference to TAG will also
949                  count as a reference to VAR).  */
950               ai->total_alias_vops += (num_var_refs + num_tag_refs);
951               p_map->total_alias_vops += (num_var_refs + num_tag_refs);
952
953               /* Update the bitmap used to represent TAG's alias set
954                  in case we need to group aliases.  */
955               SET_BIT (p_map->may_aliases, var_ann (var)->uid);
956             }
957         }
958     }
959
960   /* Since this analysis is based exclusively on symbols, it fails to
961      handle cases where two pointers P and Q have different memory
962      tags with conflicting alias set numbers but no aliased symbols in
963      common.
964
965      For example, suppose that we have two memory tags TMT.1 and TMT.2
966      such that
967      
968                 may-aliases (TMT.1) = { a }
969                 may-aliases (TMT.2) = { b }
970
971      and the alias set number of TMT.1 conflicts with that of TMT.2.
972      Since they don't have symbols in common, loads and stores from
973      TMT.1 and TMT.2 will seem independent of each other, which will
974      lead to the optimizers making invalid transformations (see
975      testsuite/gcc.c-torture/execute/pr15262-[12].c).
976
977      To avoid this problem, we do a final traversal of AI->POINTERS
978      looking for pairs of pointers that have no aliased symbols in
979      common and yet have conflicting alias set numbers.  */
980   res = sbitmap_alloc (num_referenced_vars);
981
982   for (i = 0; i < ai->num_pointers; i++)
983     {
984       size_t j;
985       struct alias_map_d *p_map1 = ai->pointers[i];
986       tree tag1 = var_ann (p_map1->var)->type_mem_tag;
987       sbitmap may_aliases1 = p_map1->may_aliases;
988
989       for (j = i + 1; j < ai->num_pointers; j++)
990         {
991           struct alias_map_d *p_map2 = ai->pointers[j];
992           tree tag2 = var_ann (p_map2->var)->type_mem_tag;
993           sbitmap may_aliases2 = p_map2->may_aliases;
994
995           /* If the pointers may not point to each other, do nothing.  */
996           if (!may_alias_p (p_map1->var, p_map1->set, p_map2->var, p_map2->set))
997             continue;
998
999           /* The two pointers may alias each other.  If they already have
1000              symbols in common, do nothing.  */
1001           sbitmap_a_and_b (res, may_aliases1, may_aliases2);
1002           if (sbitmap_first_set_bit (res) >= 0)
1003             continue;
1004
1005           if (sbitmap_first_set_bit (may_aliases2) >= 0)
1006             {
1007               size_t k;
1008
1009               /* Add all the aliases for TAG2 into TAG1's alias set.
1010                  FIXME, update grouping heuristic counters.  */
1011               EXECUTE_IF_SET_IN_SBITMAP (may_aliases2, 0, k,
1012                   add_may_alias (tag1, referenced_var (k)));
1013               sbitmap_a_or_b (may_aliases1, may_aliases1, may_aliases2);
1014             }
1015           else
1016             {
1017               /* Since TAG2 does not have any aliases of its own, add
1018                  TAG2 itself to the alias set of TAG1.  */
1019               add_may_alias (tag1, tag2);
1020             }
1021         }
1022     }
1023
1024   sbitmap_free (res);
1025
1026   if (dump_file)
1027     fprintf (dump_file, "%s: Total number of aliased vops: %ld\n",
1028              get_name (current_function_decl),
1029              ai->total_alias_vops);
1030
1031   /* Determine if we need to enable alias grouping.  */
1032   if (ai->total_alias_vops >= MAX_ALIASED_VOPS)
1033     group_aliases (ai);
1034 }
1035
1036
1037 /* Comparison function for qsort used in group_aliases.  */
1038
1039 static int
1040 total_alias_vops_cmp (const void *p, const void *q)
1041 {
1042   const struct alias_map_d **p1 = (const struct alias_map_d **)p;
1043   const struct alias_map_d **p2 = (const struct alias_map_d **)q;
1044   long n1 = (*p1)->total_alias_vops;
1045   long n2 = (*p2)->total_alias_vops;
1046
1047   /* We want to sort in descending order.  */
1048   return (n1 > n2 ? -1 : (n1 == n2) ? 0 : 1);
1049 }
1050
1051 /* Group all the aliases for TAG to make TAG represent all the
1052    variables in its alias set.  Update the total number
1053    of virtual operands due to aliasing (AI->TOTAL_ALIAS_VOPS).  This
1054    function will make TAG be the unique alias tag for all the
1055    variables in its may-aliases.  So, given:
1056
1057         may-aliases(TAG) = { V1, V2, V3 }
1058
1059    This function will group the variables into:
1060
1061         may-aliases(V1) = { TAG }
1062         may-aliases(V2) = { TAG }
1063         may-aliases(V2) = { TAG }  */
1064
1065 static void
1066 group_aliases_into (tree tag, sbitmap tag_aliases, struct alias_info *ai)
1067 {
1068   size_t i;
1069   var_ann_t tag_ann = var_ann (tag);
1070   size_t num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
1071
1072   EXECUTE_IF_SET_IN_SBITMAP (tag_aliases, 0, i,
1073     {
1074       tree var = referenced_var (i);
1075       var_ann_t ann = var_ann (var);
1076
1077       /* Make TAG the unique alias of VAR.  */
1078       ann->is_alias_tag = 0;
1079       ann->may_aliases = NULL;
1080
1081       /* Note that VAR and TAG may be the same if the function has no
1082          addressable variables (see the discussion at the end of
1083          setup_pointers_and_addressables).  */
1084       if (var != tag)
1085         add_may_alias (var, tag);
1086
1087       /* Reduce total number of virtual operands contributed
1088          by TAG on behalf of VAR.  Notice that the references to VAR
1089          itself won't be removed.  We will merely replace them with
1090          references to TAG.  */
1091       ai->total_alias_vops -= num_tag_refs;
1092     });
1093
1094   /* We have reduced the number of virtual operands that TAG makes on
1095      behalf of all the variables formerly aliased with it.  However,
1096      we have also "removed" all the virtual operands for TAG itself,
1097      so we add them back.  */
1098   ai->total_alias_vops += num_tag_refs;
1099
1100   /* TAG no longer has any aliases.  */
1101   tag_ann->may_aliases = NULL;
1102 }
1103
1104
1105 /* Group may-aliases sets to reduce the number of virtual operands due
1106    to aliasing.
1107
1108      1- Sort the list of pointers in decreasing number of contributed
1109         virtual operands.
1110
1111      2- Take the first entry in AI->POINTERS and revert the role of
1112         the memory tag and its aliases.  Usually, whenever an aliased
1113         variable Vi is found to alias with a memory tag T, we add Vi
1114         to the may-aliases set for T.  Meaning that after alias
1115         analysis, we will have:
1116
1117                 may-aliases(T) = { V1, V2, V3, ..., Vn }
1118
1119         This means that every statement that references T, will get 'n'
1120         virtual operands for each of the Vi tags.  But, when alias
1121         grouping is enabled, we make T an alias tag and add it to the
1122         alias set of all the Vi variables:
1123
1124                 may-aliases(V1) = { T }
1125                 may-aliases(V2) = { T }
1126                 ...
1127                 may-aliases(Vn) = { T }
1128
1129         This has two effects: (a) statements referencing T will only get
1130         a single virtual operand, and, (b) all the variables Vi will now
1131         appear to alias each other.  So, we lose alias precision to
1132         improve compile time.  But, in theory, a program with such a high
1133         level of aliasing should not be very optimizable in the first
1134         place.
1135
1136      3- Since variables may be in the alias set of more than one
1137         memory tag, the grouping done in step (2) needs to be extended
1138         to all the memory tags that have a non-empty intersection with
1139         the may-aliases set of tag T.  For instance, if we originally
1140         had these may-aliases sets:
1141
1142                 may-aliases(T) = { V1, V2, V3 }
1143                 may-aliases(R) = { V2, V4 }
1144
1145         In step (2) we would have reverted the aliases for T as:
1146
1147                 may-aliases(V1) = { T }
1148                 may-aliases(V2) = { T }
1149                 may-aliases(V3) = { T }
1150
1151         But note that now V2 is no longer aliased with R.  We could
1152         add R to may-aliases(V2), but we are in the process of
1153         grouping aliases to reduce virtual operands so what we do is
1154         add V4 to the grouping to obtain:
1155
1156                 may-aliases(V1) = { T }
1157                 may-aliases(V2) = { T }
1158                 may-aliases(V3) = { T }
1159                 may-aliases(V4) = { T }
1160
1161      4- If the total number of virtual operands due to aliasing is
1162         still above the threshold set by max-alias-vops, go back to (2).  */
1163
1164 static void
1165 group_aliases (struct alias_info *ai)
1166 {
1167   size_t i;
1168   sbitmap res;
1169
1170   /* Sort the POINTERS array in descending order of contributed
1171      virtual operands.  */
1172   qsort (ai->pointers, ai->num_pointers, sizeof (struct alias_map_d *),
1173          total_alias_vops_cmp);
1174
1175   res = sbitmap_alloc (num_referenced_vars);
1176
1177   /* For every pointer in AI->POINTERS, reverse the roles of its tag
1178      and the tag's may-aliases set.  */
1179   for (i = 0; i < ai->num_pointers; i++)
1180     {
1181       size_t j;
1182       tree tag1 = var_ann (ai->pointers[i]->var)->type_mem_tag;
1183       sbitmap tag1_aliases = ai->pointers[i]->may_aliases;
1184
1185       /* Skip tags that have been grouped already.  */
1186       if (ai->pointers[i]->grouped_p)
1187         continue;
1188
1189       /* See if TAG1 had any aliases in common with other type tags.
1190          If we find a TAG2 with common aliases with TAG1, add TAG2's
1191          aliases into TAG1.  */
1192       for (j = i + 1; j < ai->num_pointers; j++)
1193         {
1194           sbitmap tag2_aliases = ai->pointers[j]->may_aliases;
1195
1196           sbitmap_a_and_b (res, tag1_aliases, tag2_aliases);
1197           if (sbitmap_first_set_bit (res) >= 0)
1198             {
1199               tree tag2 = var_ann (ai->pointers[j]->var)->type_mem_tag;
1200
1201               sbitmap_a_or_b (tag1_aliases, tag1_aliases, tag2_aliases);
1202
1203               /* TAG2 does not need its aliases anymore.  */
1204               sbitmap_zero (tag2_aliases);
1205               var_ann (tag2)->may_aliases = NULL;
1206
1207               /* TAG1 is the unique alias of TAG2.  */
1208               add_may_alias (tag2, tag1);
1209
1210               ai->pointers[j]->grouped_p = true;
1211             }
1212         }
1213
1214       /* Now group all the aliases we collected into TAG1.  */
1215       group_aliases_into (tag1, tag1_aliases, ai);
1216
1217       /* If we've reduced total number of virtual operands below the
1218          threshold, stop.  */
1219       if (ai->total_alias_vops < MAX_ALIASED_VOPS)
1220         break;
1221     }
1222
1223   /* Finally, all the variables that have been grouped cannot be in
1224      the may-alias set of name memory tags.  Suppose that we have
1225      grouped the aliases in this code so that may-aliases(a) = TMT.20
1226
1227         p_5 = &a;
1228         ...
1229         # a_9 = V_MAY_DEF <a_8>
1230         p_5->field = 0
1231         ... Several modifications to TMT.20 ... 
1232         # VUSE <a_9>
1233         x_30 = p_5->field
1234
1235      Since p_5 points to 'a', the optimizers will try to propagate 0
1236      into p_5->field, but that is wrong because there have been
1237      modifications to 'TMT.20' in between.  To prevent this we have to
1238      replace 'a' with 'TMT.20' in the name tag of p_5.  */
1239   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
1240     {
1241       size_t j;
1242       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
1243       tree name_tag = SSA_NAME_PTR_INFO (ptr)->name_mem_tag;
1244       varray_type aliases;
1245       
1246       if (name_tag == NULL_TREE)
1247         continue;
1248
1249       aliases = var_ann (name_tag)->may_aliases;
1250       for (j = 0; aliases && j < VARRAY_ACTIVE_SIZE (aliases); j++)
1251         {
1252           tree alias = VARRAY_TREE (aliases, j);
1253           var_ann_t ann = var_ann (alias);
1254
1255           if (ann->mem_tag_kind == NOT_A_TAG && ann->may_aliases)
1256             {
1257               tree new_alias;
1258
1259               gcc_assert (VARRAY_ACTIVE_SIZE (ann->may_aliases) == 1);
1260
1261               new_alias = VARRAY_TREE (ann->may_aliases, 0);
1262               replace_may_alias (name_tag, j, new_alias);
1263             }
1264         }
1265     }
1266
1267   sbitmap_free (res);
1268
1269   if (dump_file)
1270     fprintf (dump_file,
1271              "%s: Total number of aliased vops after grouping: %ld%s\n",
1272              get_name (current_function_decl),
1273              ai->total_alias_vops,
1274              (ai->total_alias_vops < 0) ? " (negative values are OK)" : "");
1275 }
1276
1277
1278 /* Create a new alias set entry for VAR in AI->ADDRESSABLE_VARS.  */
1279
1280 static void
1281 create_alias_map_for (tree var, struct alias_info *ai)
1282 {
1283   struct alias_map_d *alias_map;
1284   alias_map = xcalloc (1, sizeof (*alias_map));
1285   alias_map->var = var;
1286   alias_map->set = get_alias_set (var);
1287   ai->addressable_vars[ai->num_addressable_vars++] = alias_map;
1288 }
1289
1290
1291 /* Create memory tags for all the dereferenced pointers and build the
1292    ADDRESSABLE_VARS and POINTERS arrays used for building the may-alias
1293    sets.  Based on the address escape and points-to information collected
1294    earlier, this pass will also clear the TREE_ADDRESSABLE flag from those
1295    variables whose address is not needed anymore.  */
1296
1297 static void
1298 setup_pointers_and_addressables (struct alias_info *ai)
1299 {
1300   size_t i, n_vars, num_addressable_vars, num_pointers;
1301
1302   /* Size up the arrays ADDRESSABLE_VARS and POINTERS.  */
1303   num_addressable_vars = num_pointers = 0;
1304   for (i = 0; i < num_referenced_vars; i++)
1305     {
1306       tree var = referenced_var (i);
1307
1308       if (may_be_aliased (var))
1309         num_addressable_vars++;
1310
1311       if (POINTER_TYPE_P (TREE_TYPE (var)))
1312         {
1313           /* Since we don't keep track of volatile variables, assume that
1314              these pointers are used in indirect store operations.  */
1315           if (TREE_THIS_VOLATILE (var))
1316             bitmap_set_bit (ai->dereferenced_ptrs_store, var_ann (var)->uid);
1317
1318           num_pointers++;
1319         }
1320     }
1321
1322   /* Create ADDRESSABLE_VARS and POINTERS.  Note that these arrays are
1323      always going to be slightly bigger than we actually need them
1324      because some TREE_ADDRESSABLE variables will be marked
1325      non-addressable below and only pointers with unique type tags are
1326      going to be added to POINTERS.  */
1327   ai->addressable_vars = xcalloc (num_addressable_vars,
1328                                   sizeof (struct alias_map_d *));
1329   ai->pointers = xcalloc (num_pointers, sizeof (struct alias_map_d *));
1330   ai->num_addressable_vars = 0;
1331   ai->num_pointers = 0;
1332
1333   /* Since we will be creating type memory tags within this loop, cache the
1334      value of NUM_REFERENCED_VARS to avoid processing the additional tags
1335      unnecessarily.  */
1336   n_vars = num_referenced_vars;
1337
1338   for (i = 0; i < n_vars; i++)
1339     {
1340       tree var = referenced_var (i);
1341       var_ann_t v_ann = var_ann (var);
1342
1343       /* Name memory tags already have flow-sensitive aliasing
1344          information, so they need not be processed by
1345          compute_flow_insensitive_aliasing.  Similarly, type memory
1346          tags are already accounted for when we process their
1347          associated pointer.  */
1348       if (v_ann->mem_tag_kind != NOT_A_TAG)
1349         continue;
1350
1351       /* Remove the ADDRESSABLE flag from every addressable variable whose
1352          address is not needed anymore.  This is caused by the propagation
1353          of ADDR_EXPR constants into INDIRECT_REF expressions and the
1354          removal of dead pointer assignments done by the early scalar
1355          cleanup passes.  */
1356       if (TREE_ADDRESSABLE (var))
1357         {
1358           if (!bitmap_bit_p (ai->addresses_needed, v_ann->uid)
1359               && v_ann->mem_tag_kind == NOT_A_TAG
1360               && TREE_CODE (var) != RESULT_DECL
1361               && !is_global_var (var))
1362             {
1363               /* The address of VAR is not needed, remove the
1364                  addressable bit, so that it can be optimized as a
1365                  regular variable.  */
1366               mark_non_addressable (var);
1367
1368               /* Since VAR is now a regular GIMPLE register, we will need
1369                  to rename VAR into SSA afterwards.  */
1370               bitmap_set_bit (vars_to_rename, v_ann->uid);
1371             }
1372           else
1373             {
1374               /* Add the variable to the set of addressables.  Mostly
1375                  used when scanning operands for ASM_EXPRs that
1376                  clobber memory.  In those cases, we need to clobber
1377                  all call-clobbered variables and all addressables.  */
1378               bitmap_set_bit (addressable_vars, v_ann->uid);
1379             }
1380         }
1381
1382       /* Global variables and addressable locals may be aliased.  Create an
1383          entry in ADDRESSABLE_VARS for VAR.  */
1384       if (may_be_aliased (var))
1385         {
1386           create_alias_map_for (var, ai);
1387           bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1388         }
1389
1390       /* Add pointer variables that have been dereferenced to the POINTERS
1391          array and create a type memory tag for them.  */
1392       if (POINTER_TYPE_P (TREE_TYPE (var)))
1393         {
1394           if ((bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid)
1395                 || bitmap_bit_p (ai->dereferenced_ptrs_load, v_ann->uid)))
1396             {
1397               tree tag;
1398               var_ann_t t_ann;
1399
1400               /* If pointer VAR still doesn't have a memory tag
1401                  associated with it, create it now or re-use an
1402                  existing one.  */
1403               tag = get_tmt_for (var, ai);
1404               t_ann = var_ann (tag);
1405
1406               /* The type tag will need to be renamed into SSA
1407                  afterwards. Note that we cannot do this inside
1408                  get_tmt_for because aliasing may run multiple times
1409                  and we only create type tags the first time.  */
1410               bitmap_set_bit (vars_to_rename, t_ann->uid);
1411
1412               /* Associate the tag with pointer VAR.  */
1413               v_ann->type_mem_tag = tag;
1414
1415               /* If pointer VAR has been used in a store operation,
1416                  then its memory tag must be marked as written-to.  */
1417               if (bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid))
1418                 bitmap_set_bit (ai->written_vars, t_ann->uid);
1419
1420               /* If pointer VAR is a global variable or a PARM_DECL,
1421                  then its memory tag should be considered a global
1422                  variable.  */
1423               if (TREE_CODE (var) == PARM_DECL || is_global_var (var))
1424                 mark_call_clobbered (tag);
1425
1426               /* All the dereferences of pointer VAR count as
1427                  references of TAG.  Since TAG can be associated with
1428                  several pointers, add the dereferences of VAR to the
1429                  TAG.  We may need to grow AI->NUM_REFERENCES because
1430                  we have been adding name and type tags.  */
1431               if (t_ann->uid >= VARRAY_SIZE (ai->num_references))
1432                 VARRAY_GROW (ai->num_references, t_ann->uid + 10);
1433
1434               VARRAY_UINT (ai->num_references, t_ann->uid)
1435                 += VARRAY_UINT (ai->num_references, v_ann->uid);
1436             }
1437           else
1438             {
1439               /* The pointer has not been dereferenced.  If it had a
1440                  type memory tag, remove it and mark the old tag for
1441                  renaming to remove it out of the IL.  */
1442               var_ann_t ann = var_ann (var);
1443               tree tag = ann->type_mem_tag;
1444               if (tag)
1445                 {
1446                   bitmap_set_bit (vars_to_rename, var_ann (tag)->uid);
1447                   ann->type_mem_tag = NULL_TREE;
1448                 }
1449             }
1450         }
1451     }
1452 }
1453
1454
1455 /* Determine whether to use .GLOBAL_VAR to model call clobbering semantics. At
1456    every call site, we need to emit V_MAY_DEF expressions to represent the
1457    clobbering effects of the call for variables whose address escapes the
1458    current function.
1459
1460    One approach is to group all call-clobbered variables into a single
1461    representative that is used as an alias of every call-clobbered variable
1462    (.GLOBAL_VAR).  This works well, but it ties the optimizer hands because
1463    references to any call clobbered variable is a reference to .GLOBAL_VAR.
1464
1465    The second approach is to emit a clobbering V_MAY_DEF for every 
1466    call-clobbered variable at call sites.  This is the preferred way in terms 
1467    of optimization opportunities but it may create too many V_MAY_DEF operands
1468    if there are many call clobbered variables and function calls in the 
1469    function.
1470
1471    To decide whether or not to use .GLOBAL_VAR we multiply the number of
1472    function calls found by the number of call-clobbered variables.  If that
1473    product is beyond a certain threshold, as determined by the parameterized
1474    values shown below, we use .GLOBAL_VAR.
1475
1476    FIXME.  This heuristic should be improved.  One idea is to use several
1477    .GLOBAL_VARs of different types instead of a single one.  The thresholds
1478    have been derived from a typical bootstrap cycle, including all target
1479    libraries. Compile times were found increase by ~1% compared to using
1480    .GLOBAL_VAR.  */
1481
1482 static void
1483 maybe_create_global_var (struct alias_info *ai)
1484 {
1485   size_t i, n_clobbered;
1486   bitmap_iterator bi;
1487   
1488   /* No need to create it, if we have one already.  */
1489   if (global_var == NULL_TREE)
1490     {
1491       /* Count all the call-clobbered variables.  */
1492       n_clobbered = 0;
1493       EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, bi)
1494         {
1495           n_clobbered++;
1496         }
1497
1498       /* Create .GLOBAL_VAR if we have too many call-clobbered
1499          variables.  We also create .GLOBAL_VAR when there no
1500          call-clobbered variables to prevent code motion
1501          transformations from re-arranging function calls that may
1502          have side effects.  For instance,
1503
1504                 foo ()
1505                 {
1506                   int a = f ();
1507                   g ();
1508                   h (a);
1509                 }
1510
1511          There are no call-clobbered variables in foo(), so it would
1512          be entirely possible for a pass to want to move the call to
1513          f() after the call to g().  If f() has side effects, that
1514          would be wrong.  Creating .GLOBAL_VAR in this case will
1515          insert VDEFs for it and prevent such transformations.  */
1516       if (n_clobbered == 0
1517           || ai->num_calls_found * n_clobbered >= (size_t) GLOBAL_VAR_THRESHOLD)
1518         create_global_var ();
1519     }
1520
1521   /* If the function has calls to clobbering functions and .GLOBAL_VAR has
1522      been created, make it an alias for all call-clobbered variables.  */
1523   if (global_var)
1524     EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, bi)
1525       {
1526         tree var = referenced_var (i);
1527         if (var != global_var)
1528           {
1529              add_may_alias (var, global_var);
1530              bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1531           }
1532       }
1533 }
1534
1535
1536 /* Return TRUE if pointer PTR may point to variable VAR.
1537    
1538    MEM_ALIAS_SET is the alias set for the memory location pointed-to by PTR
1539         This is needed because when checking for type conflicts we are
1540         interested in the alias set of the memory location pointed-to by
1541         PTR.  The alias set of PTR itself is irrelevant.
1542    
1543    VAR_ALIAS_SET is the alias set for VAR.  */
1544
1545 static bool
1546 may_alias_p (tree ptr, HOST_WIDE_INT mem_alias_set,
1547              tree var, HOST_WIDE_INT var_alias_set)
1548 {
1549   tree mem;
1550   var_ann_t v_ann, m_ann;
1551
1552   alias_stats.alias_queries++;
1553   alias_stats.simple_queries++;
1554
1555   /* By convention, a variable cannot alias itself.  */
1556   mem = var_ann (ptr)->type_mem_tag;
1557   if (mem == var)
1558     {
1559       alias_stats.alias_noalias++;
1560       alias_stats.simple_resolved++;
1561       return false;
1562     }
1563
1564   v_ann = var_ann (var);
1565   m_ann = var_ann (mem);
1566
1567   gcc_assert (m_ann->mem_tag_kind == TYPE_TAG);
1568
1569   alias_stats.tbaa_queries++;
1570
1571   /* If VAR is a pointer with the same alias set as PTR, then dereferencing
1572      PTR can't possibly affect VAR.  Note, that we are specifically testing
1573      for PTR's alias set here, not its pointed-to type.  We also can't
1574      do this check with relaxed aliasing enabled.  */
1575   if (POINTER_TYPE_P (TREE_TYPE (var))
1576       && var_alias_set != 0
1577       && mem_alias_set != 0)
1578     {
1579       HOST_WIDE_INT ptr_alias_set = get_alias_set (ptr);
1580       if (ptr_alias_set == var_alias_set)
1581         {
1582           alias_stats.alias_noalias++;
1583           alias_stats.tbaa_resolved++;
1584           return false;
1585         }
1586     }
1587
1588   /* If the alias sets don't conflict then MEM cannot alias VAR.  */
1589   if (!alias_sets_conflict_p (mem_alias_set, var_alias_set))
1590     {
1591       alias_stats.alias_noalias++;
1592       alias_stats.tbaa_resolved++;
1593       return false;
1594     }
1595
1596   alias_stats.alias_mayalias++;
1597   return true;
1598 }
1599
1600
1601 /* Add ALIAS to the set of variables that may alias VAR.  */
1602
1603 static void
1604 add_may_alias (tree var, tree alias)
1605 {
1606   size_t i;
1607   var_ann_t v_ann = get_var_ann (var);
1608   var_ann_t a_ann = get_var_ann (alias);
1609
1610   gcc_assert (var != alias);
1611
1612   if (v_ann->may_aliases == NULL)
1613     VARRAY_TREE_INIT (v_ann->may_aliases, 2, "aliases");
1614
1615   /* Avoid adding duplicates.  */
1616   for (i = 0; i < VARRAY_ACTIVE_SIZE (v_ann->may_aliases); i++)
1617     if (alias == VARRAY_TREE (v_ann->may_aliases, i))
1618       return;
1619
1620   /* If VAR is a call-clobbered variable, so is its new ALIAS.
1621      FIXME, call-clobbering should only depend on whether an address
1622      escapes.  It should be independent of aliasing.  */
1623   if (is_call_clobbered (var))
1624     mark_call_clobbered (alias);
1625
1626   /* Likewise.  If ALIAS is call-clobbered, so is VAR.  */
1627   else if (is_call_clobbered (alias))
1628     mark_call_clobbered (var);
1629
1630   VARRAY_PUSH_TREE (v_ann->may_aliases, alias);
1631   a_ann->is_alias_tag = 1;
1632 }
1633
1634
1635 /* Replace alias I in the alias sets of VAR with NEW_ALIAS.  */
1636
1637 static void
1638 replace_may_alias (tree var, size_t i, tree new_alias)
1639 {
1640   var_ann_t v_ann = var_ann (var);
1641   VARRAY_TREE (v_ann->may_aliases, i) = new_alias;
1642
1643   /* If VAR is a call-clobbered variable, so is NEW_ALIAS.
1644      FIXME, call-clobbering should only depend on whether an address
1645      escapes.  It should be independent of aliasing.  */
1646   if (is_call_clobbered (var))
1647     mark_call_clobbered (new_alias);
1648
1649   /* Likewise.  If NEW_ALIAS is call-clobbered, so is VAR.  */
1650   else if (is_call_clobbered (new_alias))
1651     mark_call_clobbered (var);
1652 }
1653
1654
1655 /* Mark pointer PTR as pointing to an arbitrary memory location.  */
1656
1657 static void
1658 set_pt_anything (tree ptr)
1659 {
1660   struct ptr_info_def *pi = get_ptr_info (ptr);
1661
1662   pi->pt_anything = 1;
1663   pi->pt_malloc = 0;
1664
1665   /* The pointer used to have a name tag, but we now found it pointing
1666      to an arbitrary location.  The name tag needs to be renamed and
1667      disassociated from PTR.  */
1668   if (pi->name_mem_tag)
1669     {
1670       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
1671       pi->name_mem_tag = NULL_TREE;
1672     }
1673 }
1674
1675
1676 /* Mark pointer PTR as pointing to a malloc'd memory area.  */
1677
1678 static void
1679 set_pt_malloc (tree ptr)
1680 {
1681   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
1682
1683   /* If the pointer has already been found to point to arbitrary
1684      memory locations, it is unsafe to mark it as pointing to malloc.  */
1685   if (pi->pt_anything)
1686     return;
1687
1688   pi->pt_malloc = 1;
1689 }
1690
1691
1692 /* Given two pointers DEST and ORIG.  Merge the points-to information in
1693    ORIG into DEST.  AI is as in collect_points_to_info.  */
1694
1695 static void
1696 merge_pointed_to_info (struct alias_info *ai, tree dest, tree orig)
1697 {
1698   struct ptr_info_def *dest_pi, *orig_pi;
1699
1700   /* Make sure we have points-to information for ORIG.  */
1701   collect_points_to_info_for (ai, orig);
1702
1703   dest_pi = get_ptr_info (dest);
1704   orig_pi = SSA_NAME_PTR_INFO (orig);
1705
1706   if (orig_pi)
1707     {
1708       /* Notice that we never merge PT_MALLOC.  This attribute is only
1709          true if the pointer is the result of a malloc() call.
1710          Otherwise, we can end up in this situation:
1711
1712          P_i = malloc ();
1713          ...
1714          P_j = P_i + X;
1715
1716          P_j would be marked as PT_MALLOC, which is wrong because
1717          PT_MALLOC implies that the pointer may not point to another
1718          variable.
1719
1720          FIXME 1: Subsequent analysis may determine that P_j
1721          cannot alias anything else, but we are being conservative
1722          here.
1723
1724          FIXME 2: If the merging comes from a copy assignment, we
1725          ought to merge PT_MALLOC, but then both pointers would end up
1726          getting different name tags because create_name_tags is not
1727          smart enough to determine that the two come from the same
1728          malloc call.  Copy propagation before aliasing should cure
1729          this.  */
1730       dest_pi->pt_malloc = 0;
1731
1732       if (orig_pi->pt_malloc || orig_pi->pt_anything)
1733         set_pt_anything (dest);
1734
1735       if (!dest_pi->pt_anything
1736           && orig_pi->pt_vars
1737           && bitmap_first_set_bit (orig_pi->pt_vars) >= 0)
1738         {
1739           if (dest_pi->pt_vars == NULL)
1740             {
1741               dest_pi->pt_vars = BITMAP_GGC_ALLOC ();
1742               bitmap_copy (dest_pi->pt_vars, orig_pi->pt_vars);
1743             }
1744           else
1745             bitmap_a_or_b (dest_pi->pt_vars,
1746                            dest_pi->pt_vars,
1747                            orig_pi->pt_vars);
1748         }
1749     }
1750   else
1751     set_pt_anything (dest);
1752 }
1753
1754
1755 /* Add EXPR to the list of expressions pointed-to by PTR.  */
1756
1757 static void
1758 add_pointed_to_expr (struct alias_info *ai, tree ptr, tree expr)
1759 {
1760   if (TREE_CODE (expr) == WITH_SIZE_EXPR)
1761     expr = TREE_OPERAND (expr, 0);
1762
1763   get_ptr_info (ptr);
1764
1765   if (TREE_CODE (expr) == CALL_EXPR
1766       && (call_expr_flags (expr) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))
1767     {
1768       /* If EXPR is a malloc-like call, then the area pointed to PTR
1769          is guaranteed to not alias with anything else.  */
1770       set_pt_malloc (ptr);
1771     }
1772   else if (TREE_CODE (expr) == ADDR_EXPR)
1773     {
1774       /* Found P_i = ADDR_EXPR  */
1775       add_pointed_to_var (ai, ptr, expr);
1776     }
1777   else if (TREE_CODE (expr) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (expr)))
1778     {
1779       /* Found P_i = Q_j.  */
1780       merge_pointed_to_info (ai, ptr, expr);
1781     }
1782   else if (TREE_CODE (expr) == PLUS_EXPR || TREE_CODE (expr) == MINUS_EXPR)
1783     {
1784       /* Found P_i = PLUS_EXPR or P_i = MINUS_EXPR  */
1785       tree op0 = TREE_OPERAND (expr, 0);
1786       tree op1 = TREE_OPERAND (expr, 1);
1787
1788       /* Both operands may be of pointer type.  FIXME: Shouldn't
1789          we just expect PTR + OFFSET always?  */
1790       if (POINTER_TYPE_P (TREE_TYPE (op0))
1791           && TREE_CODE (op0) != INTEGER_CST)
1792         {
1793           if (TREE_CODE (op0) == SSA_NAME)
1794             merge_pointed_to_info (ai, ptr, op0);
1795           else if (TREE_CODE (op0) == ADDR_EXPR)
1796             add_pointed_to_var (ai, ptr, op0);
1797           else
1798             set_pt_anything (ptr);
1799         }
1800
1801       if (POINTER_TYPE_P (TREE_TYPE (op1))
1802           && TREE_CODE (op1) != INTEGER_CST)
1803         {
1804           if (TREE_CODE (op1) == SSA_NAME)
1805             merge_pointed_to_info (ai, ptr, op1);
1806           else if (TREE_CODE (op1) == ADDR_EXPR)
1807             add_pointed_to_var (ai, ptr, op1);
1808           else
1809             set_pt_anything (ptr);
1810         }
1811
1812       /* Neither operand is a pointer?  VAR can be pointing anywhere.
1813          FIXME: Shouldn't we abort here?  If we get here, we found
1814          PTR = INT_CST + INT_CST, which should not be a valid pointer
1815          expression.  */
1816       if (!(POINTER_TYPE_P (TREE_TYPE (op0))
1817             && TREE_CODE (op0) != INTEGER_CST)
1818           && !(POINTER_TYPE_P (TREE_TYPE (op1))
1819                && TREE_CODE (op1) != INTEGER_CST))
1820         set_pt_anything (ptr);
1821     }
1822   else
1823     {
1824       /* If we can't recognize the expression, assume that PTR may
1825          point anywhere.  */
1826       set_pt_anything (ptr);
1827     }
1828 }
1829
1830
1831 /* If VALUE is of the form &DECL, add DECL to the set of variables
1832    pointed-to by PTR.  Otherwise, add VALUE as a pointed-to expression by
1833    PTR.  AI is as in collect_points_to_info.  */
1834
1835 static void
1836 add_pointed_to_var (struct alias_info *ai, tree ptr, tree value)
1837 {
1838   struct ptr_info_def *pi = get_ptr_info (ptr);
1839   tree pt_var;
1840   size_t uid;
1841
1842   gcc_assert (TREE_CODE (value) == ADDR_EXPR);
1843
1844   pt_var = TREE_OPERAND (value, 0);
1845   if (REFERENCE_CLASS_P (pt_var))
1846     pt_var = get_base_address (pt_var);
1847
1848   if (pt_var && SSA_VAR_P (pt_var))
1849     {
1850       uid = var_ann (pt_var)->uid;
1851       bitmap_set_bit (ai->addresses_needed, uid);
1852
1853       if (pi->pt_vars == NULL)
1854         pi->pt_vars = BITMAP_GGC_ALLOC ();
1855       bitmap_set_bit (pi->pt_vars, uid);
1856
1857       /* If the variable is a global, mark the pointer as pointing to
1858          global memory (which will make its tag a global variable).  */
1859       if (is_global_var (pt_var))
1860         pi->pt_global_mem = 1;
1861     }
1862 }
1863
1864
1865 /* Callback for walk_use_def_chains to gather points-to information from the
1866    SSA web.
1867    
1868    VAR is an SSA variable or a GIMPLE expression.
1869    
1870    STMT is the statement that generates the SSA variable or, if STMT is a
1871       PHI_NODE, VAR is one of the PHI arguments.
1872
1873    DATA is a pointer to a structure of type ALIAS_INFO.  */
1874
1875 static bool
1876 collect_points_to_info_r (tree var, tree stmt, void *data)
1877 {
1878   struct alias_info *ai = (struct alias_info *) data;
1879
1880   if (dump_file && (dump_flags & TDF_DETAILS))
1881     {
1882       fprintf (dump_file, "Visiting use-def links for ");
1883       print_generic_expr (dump_file, var, dump_flags);
1884       fprintf (dump_file, "\n");
1885     }
1886
1887   switch (TREE_CODE (stmt))
1888     {
1889     case RETURN_EXPR:
1890       if (TREE_CODE (TREE_OPERAND (stmt, 0)) != MODIFY_EXPR)
1891         abort ();
1892       stmt = TREE_OPERAND (stmt, 0);
1893       /* FALLTHRU  */
1894
1895     case MODIFY_EXPR:
1896       {
1897         tree rhs = TREE_OPERAND (stmt, 1);
1898         STRIP_NOPS (rhs);
1899         add_pointed_to_expr (ai, var, rhs);
1900         break;
1901       }
1902
1903     case ASM_EXPR:
1904       /* Pointers defined by __asm__ statements can point anywhere.  */
1905       set_pt_anything (var);
1906       break;
1907
1908     case NOP_EXPR:
1909       if (IS_EMPTY_STMT (stmt))
1910         {
1911           tree decl = SSA_NAME_VAR (var);
1912           
1913           if (TREE_CODE (decl) == PARM_DECL)
1914             add_pointed_to_expr (ai, var, decl);
1915           else if (DECL_INITIAL (decl))
1916             add_pointed_to_expr (ai, var, DECL_INITIAL (decl));
1917           else
1918             add_pointed_to_expr (ai, var, decl);
1919         }
1920       break;
1921
1922     case PHI_NODE:
1923       {
1924         /* It STMT is a PHI node, then VAR is one of its arguments.  The
1925            variable that we are analyzing is the LHS of the PHI node.  */
1926         tree lhs = PHI_RESULT (stmt);
1927
1928         switch (TREE_CODE (var))
1929           {
1930           case ADDR_EXPR:
1931             add_pointed_to_var (ai, lhs, var);
1932             break;
1933             
1934           case SSA_NAME:
1935             merge_pointed_to_info (ai, lhs, var);
1936             break;
1937             
1938           default:
1939             gcc_assert (is_gimple_min_invariant (var));
1940             add_pointed_to_expr (ai, lhs, var);
1941             break;
1942           }
1943         break;
1944       }
1945
1946     default:
1947       gcc_unreachable ();
1948     }
1949   
1950   return false;
1951 }
1952
1953
1954 /* Return true if STMT is an "escape" site from the current function.  Escape
1955    sites those statements which might expose the address of a variable
1956    outside the current function.  STMT is an escape site iff:
1957
1958         1- STMT is a function call, or
1959         2- STMT is an __asm__ expression, or
1960         3- STMT is an assignment to a non-local variable, or
1961         4- STMT is a return statement.
1962
1963    If NUM_CALLS_P is not NULL, the counter is incremented if STMT contains
1964    a function call.  */
1965
1966 static bool
1967 is_escape_site (tree stmt, size_t *num_calls_p)
1968 {
1969   if (get_call_expr_in (stmt) != NULL_TREE)
1970     {
1971       if (num_calls_p)
1972         (*num_calls_p)++;
1973
1974       return true;
1975     }
1976   else if (TREE_CODE (stmt) == ASM_EXPR)
1977     return true;
1978   else if (TREE_CODE (stmt) == MODIFY_EXPR)
1979     {
1980       tree lhs = TREE_OPERAND (stmt, 0);
1981
1982       /* Get to the base of _REF nodes.  */
1983       if (TREE_CODE (lhs) != SSA_NAME)
1984         lhs = get_base_address (lhs);
1985
1986       /* If we couldn't recognize the LHS of the assignment, assume that it
1987          is a non-local store.  */
1988       if (lhs == NULL_TREE)
1989         return true;
1990
1991       /* If the LHS is an SSA name, it can't possibly represent a non-local
1992          memory store.  */
1993       if (TREE_CODE (lhs) == SSA_NAME)
1994         return false;
1995
1996       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
1997          local variables we cannot be sure if it will escape, because we
1998          don't have information about objects not in SSA form.  Need to
1999          implement something along the lines of
2000
2001          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2002          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2003          Conference on Object-Oriented Programming Systems, Languages, and
2004          Applications (OOPSLA), pp. 1-19, 1999.  */
2005       return true;
2006     }
2007   else if (TREE_CODE (stmt) == RETURN_EXPR)
2008     return true;
2009
2010   return false;
2011 }
2012
2013
2014 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2015    is considered to represent all the pointers whose pointed-to types are
2016    in the same alias set class.  Otherwise, the tag represents a single
2017    SSA_NAME pointer variable.  */
2018
2019 static tree
2020 create_memory_tag (tree type, bool is_type_tag)
2021 {
2022   var_ann_t ann;
2023   tree tag = create_tmp_var_raw (type, (is_type_tag) ? "TMT" : "NMT");
2024
2025   /* By default, memory tags are local variables.  Alias analysis will
2026      determine whether they should be considered globals.  */
2027   DECL_CONTEXT (tag) = current_function_decl;
2028
2029   /* Memory tags are by definition addressable.  This also prevents
2030      is_gimple_ref frome confusing memory tags with optimizable
2031      variables.  */
2032   TREE_ADDRESSABLE (tag) = 1;
2033
2034   ann = get_var_ann (tag);
2035   ann->mem_tag_kind = (is_type_tag) ? TYPE_TAG : NAME_TAG;
2036   ann->type_mem_tag = NULL_TREE;
2037
2038   /* Add the tag to the symbol table.  */
2039   add_referenced_tmp_var (tag);
2040
2041   return tag;
2042 }
2043
2044
2045 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2046    This is used if P_i has been found to point to a specific set of
2047    variables or to a non-aliased memory location like the address returned
2048    by malloc functions.  */
2049
2050 static tree
2051 get_nmt_for (tree ptr)
2052 {
2053   struct ptr_info_def *pi = get_ptr_info (ptr);
2054   tree tag = pi->name_mem_tag;
2055
2056   if (tag == NULL_TREE)
2057     tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
2058
2059   /* If PTR is a PARM_DECL, it points to a global variable or malloc,
2060      then its name tag should be considered a global variable.  */
2061   if (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
2062       || pi->pt_malloc
2063       || pi->pt_global_mem)
2064     mark_call_clobbered (tag);
2065
2066   return tag;
2067 }
2068
2069
2070 /* Return the type memory tag associated to pointer PTR.  A memory tag is an
2071    artificial variable that represents the memory location pointed-to by
2072    PTR.  It is used to model the effects of pointer de-references on
2073    addressable variables.
2074    
2075    AI points to the data gathered during alias analysis.  This function
2076    populates the array AI->POINTERS.  */
2077
2078 static tree
2079 get_tmt_for (tree ptr, struct alias_info *ai)
2080 {
2081   size_t i;
2082   tree tag;
2083   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
2084   HOST_WIDE_INT tag_set = get_alias_set (tag_type);
2085
2086   /* To avoid creating unnecessary memory tags, only create one memory tag
2087      per alias set class.  Note that it may be tempting to group
2088      memory tags based on conflicting alias sets instead of
2089      equivalence.  That would be wrong because alias sets are not
2090      necessarily transitive (as demonstrated by the libstdc++ test
2091      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
2092      such that conflicts (A, B) == true and conflicts (A, C) == true,
2093      it does not necessarily follow that conflicts (B, C) == true.  */
2094   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
2095     {
2096       struct alias_map_d *curr = ai->pointers[i];
2097       if (tag_set == curr->set)
2098         {
2099           tag = var_ann (curr->var)->type_mem_tag;
2100           break;
2101         }
2102     }
2103
2104   /* If VAR cannot alias with any of the existing memory tags, create a new
2105      tag for PTR and add it to the POINTERS array.  */
2106   if (tag == NULL_TREE)
2107     {
2108       struct alias_map_d *alias_map;
2109
2110       /* If PTR did not have a type tag already, create a new TMT.*
2111          artificial variable representing the memory location
2112          pointed-to by PTR.  */
2113       if (var_ann (ptr)->type_mem_tag == NULL_TREE)
2114         tag = create_memory_tag (tag_type, true);
2115       else
2116         tag = var_ann (ptr)->type_mem_tag;
2117
2118       /* Add PTR to the POINTERS array.  Note that we are not interested in
2119          PTR's alias set.  Instead, we cache the alias set for the memory that
2120          PTR points to.  */
2121       alias_map = xcalloc (1, sizeof (*alias_map));
2122       alias_map->var = ptr;
2123       alias_map->set = tag_set;
2124       ai->pointers[ai->num_pointers++] = alias_map;
2125     }
2126
2127   /* If the pointed-to type is volatile, so is the tag.  */
2128   TREE_THIS_VOLATILE (tag) |= TREE_THIS_VOLATILE (tag_type);
2129
2130   /* Make sure that the type tag has the same alias set as the
2131      pointed-to type.  */
2132   gcc_assert (tag_set == get_alias_set (tag));
2133
2134   return tag;
2135 }
2136
2137
2138 /* Create GLOBAL_VAR, an artificial global variable to act as a
2139    representative of all the variables that may be clobbered by function
2140    calls.  */
2141
2142 static void
2143 create_global_var (void)
2144 {
2145   global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
2146                            size_type_node);
2147   DECL_ARTIFICIAL (global_var) = 1;
2148   TREE_READONLY (global_var) = 0;
2149   DECL_EXTERNAL (global_var) = 1;
2150   TREE_STATIC (global_var) = 1;
2151   TREE_USED (global_var) = 1;
2152   DECL_CONTEXT (global_var) = NULL_TREE;
2153   TREE_THIS_VOLATILE (global_var) = 0;
2154   TREE_ADDRESSABLE (global_var) = 0;
2155
2156   add_referenced_tmp_var (global_var);
2157   bitmap_set_bit (vars_to_rename, var_ann (global_var)->uid);
2158 }
2159
2160
2161 /* Dump alias statistics on FILE.  */
2162
2163 static void 
2164 dump_alias_stats (FILE *file)
2165 {
2166   const char *funcname
2167     = lang_hooks.decl_printable_name (current_function_decl, 2);
2168   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
2169   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
2170   fprintf (file, "Total alias mayalias results:\t%u\n", 
2171            alias_stats.alias_mayalias);
2172   fprintf (file, "Total alias noalias results:\t%u\n",
2173            alias_stats.alias_noalias);
2174   fprintf (file, "Total simple queries:\t%u\n",
2175            alias_stats.simple_queries);
2176   fprintf (file, "Total simple resolved:\t%u\n",
2177            alias_stats.simple_resolved);
2178   fprintf (file, "Total TBAA queries:\t%u\n",
2179            alias_stats.tbaa_queries);
2180   fprintf (file, "Total TBAA resolved:\t%u\n",
2181            alias_stats.tbaa_resolved);
2182 }
2183   
2184
2185 /* Dump alias information on FILE.  */
2186
2187 void
2188 dump_alias_info (FILE *file)
2189 {
2190   size_t i;
2191   const char *funcname
2192     = lang_hooks.decl_printable_name (current_function_decl, 2);
2193
2194   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
2195
2196   fprintf (file, "Aliased symbols\n\n");
2197   for (i = 0; i < num_referenced_vars; i++)
2198     {
2199       tree var = referenced_var (i);
2200       if (may_be_aliased (var))
2201         dump_variable (file, var);
2202     }
2203
2204   fprintf (file, "\nDereferenced pointers\n\n");
2205   for (i = 0; i < num_referenced_vars; i++)
2206     {
2207       tree var = referenced_var (i);
2208       var_ann_t ann = var_ann (var);
2209       if (ann->type_mem_tag)
2210         dump_variable (file, var);
2211     }
2212
2213   fprintf (file, "\nType memory tags\n\n");
2214   for (i = 0; i < num_referenced_vars; i++)
2215     {
2216       tree var = referenced_var (i);
2217       var_ann_t ann = var_ann (var);
2218       if (ann->mem_tag_kind == TYPE_TAG)
2219         dump_variable (file, var);
2220     }
2221
2222   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
2223
2224   fprintf (file, "SSA_NAME pointers\n\n");
2225   for (i = 1; i < num_ssa_names; i++)
2226     {
2227       tree ptr = ssa_name (i);
2228       struct ptr_info_def *pi;
2229       
2230       if (ptr == NULL_TREE)
2231         continue;
2232
2233       pi = SSA_NAME_PTR_INFO (ptr);
2234       if (!SSA_NAME_IN_FREE_LIST (ptr)
2235           && pi
2236           && pi->name_mem_tag)
2237         dump_points_to_info_for (file, ptr);
2238     }
2239
2240   fprintf (file, "\nName memory tags\n\n");
2241   for (i = 0; i < num_referenced_vars; i++)
2242     {
2243       tree var = referenced_var (i);
2244       var_ann_t ann = var_ann (var);
2245       if (ann->mem_tag_kind == NAME_TAG)
2246         dump_variable (file, var);
2247     }
2248
2249   fprintf (file, "\n");
2250 }
2251
2252
2253 /* Dump alias information on stderr.  */
2254
2255 void
2256 debug_alias_info (void)
2257 {
2258   dump_alias_info (stderr);
2259 }
2260
2261
2262 /* Return the alias information associated with pointer T.  It creates a
2263    new instance if none existed.  */
2264
2265 static struct ptr_info_def *
2266 get_ptr_info (tree t)
2267 {
2268   struct ptr_info_def *pi;
2269
2270   gcc_assert (POINTER_TYPE_P (TREE_TYPE (t)));
2271
2272   pi = SSA_NAME_PTR_INFO (t);
2273   if (pi == NULL)
2274     {
2275       pi = ggc_alloc (sizeof (*pi));
2276       memset ((void *)pi, 0, sizeof (*pi));
2277       SSA_NAME_PTR_INFO (t) = pi;
2278     }
2279
2280   return pi;
2281 }
2282
2283
2284 /* Dump points-to information for SSA_NAME PTR into FILE.  */
2285
2286 void
2287 dump_points_to_info_for (FILE *file, tree ptr)
2288 {
2289   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2290
2291   print_generic_expr (file, ptr, dump_flags);
2292
2293   if (pi)
2294     {
2295       if (pi->name_mem_tag)
2296         {
2297           fprintf (file, ", name memory tag: ");
2298           print_generic_expr (file, pi->name_mem_tag, dump_flags);
2299         }
2300
2301       if (pi->is_dereferenced)
2302         fprintf (file, ", is dereferenced");
2303
2304       if (pi->value_escapes_p)
2305         fprintf (file, ", its value escapes");
2306
2307       if (pi->pt_anything)
2308         fprintf (file, ", points-to anything");
2309
2310       if (pi->pt_malloc)
2311         fprintf (file, ", points-to malloc");
2312
2313       if (pi->pt_vars)
2314         {
2315           unsigned ix;
2316           bitmap_iterator bi;
2317
2318           fprintf (file, ", points-to vars: { ");
2319           EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, ix, bi)
2320             {
2321               print_generic_expr (file, referenced_var (ix), dump_flags);
2322               fprintf (file, " ");
2323             }
2324           fprintf (file, "}");
2325         }
2326     }
2327
2328   fprintf (file, "\n");
2329 }
2330
2331
2332 /* Dump points-to information for VAR into stderr.  */
2333
2334 void
2335 debug_points_to_info_for (tree var)
2336 {
2337   dump_points_to_info_for (stderr, var);
2338 }
2339
2340
2341 /* Dump points-to information into FILE.  NOTE: This function is slow, as
2342    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
2343
2344 void
2345 dump_points_to_info (FILE *file)
2346 {
2347   basic_block bb;
2348   block_stmt_iterator si;
2349   size_t i;
2350   ssa_op_iter iter;
2351   const char *fname =
2352     lang_hooks.decl_printable_name (current_function_decl, 2);
2353
2354   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
2355
2356   /* First dump points-to information for the default definitions of
2357      pointer variables.  This is necessary because default definitions are
2358      not part of the code.  */
2359   for (i = 0; i < num_referenced_vars; i++)
2360     {
2361       tree var = referenced_var (i);
2362       if (POINTER_TYPE_P (TREE_TYPE (var)))
2363         {
2364           var_ann_t ann = var_ann (var);
2365           if (ann->default_def)
2366             dump_points_to_info_for (file, ann->default_def);
2367         }
2368     }
2369
2370   /* Dump points-to information for every pointer defined in the program.  */
2371   FOR_EACH_BB (bb)
2372     {
2373       tree phi;
2374
2375       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2376         {
2377           tree ptr = PHI_RESULT (phi);
2378           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
2379             dump_points_to_info_for (file, ptr);
2380         }
2381
2382         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2383           {
2384             tree stmt = bsi_stmt (si);
2385             tree def;
2386             FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
2387               if (POINTER_TYPE_P (TREE_TYPE (def)))
2388                 dump_points_to_info_for (file, def);
2389           }
2390     }
2391
2392   fprintf (file, "\n");
2393 }
2394
2395
2396 /* Dump points-to info pointed by PTO into STDERR.  */
2397
2398 void
2399 debug_points_to_info (void)
2400 {
2401   dump_points_to_info (stderr);
2402 }
2403
2404 /* Dump to FILE the list of variables that may be aliasing VAR.  */
2405
2406 void
2407 dump_may_aliases_for (FILE *file, tree var)
2408 {
2409   varray_type aliases;
2410   
2411   if (TREE_CODE (var) == SSA_NAME)
2412     var = SSA_NAME_VAR (var);
2413
2414   aliases = var_ann (var)->may_aliases;
2415   if (aliases)
2416     {
2417       size_t i;
2418       fprintf (file, "{ ");
2419       for (i = 0; i < VARRAY_ACTIVE_SIZE (aliases); i++)
2420         {
2421           print_generic_expr (file, VARRAY_TREE (aliases, i), dump_flags);
2422           fprintf (file, " ");
2423         }
2424       fprintf (file, "}");
2425     }
2426 }
2427
2428
2429 /* Dump to stderr the list of variables that may be aliasing VAR.  */
2430
2431 void
2432 debug_may_aliases_for (tree var)
2433 {
2434   dump_may_aliases_for (stderr, var);
2435 }
2436
2437 /* Return true if VAR may be aliased.  */
2438
2439 bool
2440 may_be_aliased (tree var)
2441 {
2442   /* Obviously.  */
2443   if (TREE_ADDRESSABLE (var))
2444     return true;
2445
2446   /* Globally visible variables can have their addresses taken by other
2447      translation units.  */
2448   if (DECL_EXTERNAL (var) || TREE_PUBLIC (var))
2449     return true;
2450
2451   /* Automatic variables can't have their addresses escape any other way.
2452      This must be after the check for global variables, as extern declarations
2453      do not have TREE_STATIC set.  */
2454   if (!TREE_STATIC (var))
2455     return false;
2456
2457   /* If we're in unit-at-a-time mode, then we must have seen all occurrences
2458      of address-of operators, and so we can trust TREE_ADDRESSABLE.  Otherwise
2459      we can only be sure the variable isn't addressable if it's local to the
2460      current function.  */
2461   if (flag_unit_at_a_time)
2462     return false;
2463   if (decl_function_context (var) == current_function_decl)
2464     return false;
2465
2466   return true;
2467 }
2468