OSDN Git Service

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