OSDN Git Service

2009-04-15 Rafael Avila de Espindola <espindola@google.com>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dberlin@dberlin.org>
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    GCC is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING3.  If not see
19    <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "ggc.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "flags.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "tree.h"
35 #include "c-common.h"
36 #include "tree-flow.h"
37 #include "tree-inline.h"
38 #include "varray.h"
39 #include "c-tree.h"
40 #include "diagnostic.h"
41 #include "toplev.h"
42 #include "gimple.h"
43 #include "hashtab.h"
44 #include "function.h"
45 #include "cgraph.h"
46 #include "tree-pass.h"
47 #include "timevar.h"
48 #include "alloc-pool.h"
49 #include "splay-tree.h"
50 #include "params.h"
51 #include "cgraph.h"
52 #include "alias.h"
53 #include "pointer-set.h"
54
55 /* The idea behind this analyzer is to generate set constraints from the
56    program, then solve the resulting constraints in order to generate the
57    points-to sets.
58
59    Set constraints are a way of modeling program analysis problems that
60    involve sets.  They consist of an inclusion constraint language,
61    describing the variables (each variable is a set) and operations that
62    are involved on the variables, and a set of rules that derive facts
63    from these operations.  To solve a system of set constraints, you derive
64    all possible facts under the rules, which gives you the correct sets
65    as a consequence.
66
67    See  "Efficient Field-sensitive pointer analysis for C" by "David
68    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
69    http://citeseer.ist.psu.edu/pearce04efficient.html
70
71    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
72    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
73    http://citeseer.ist.psu.edu/heintze01ultrafast.html
74
75    There are three types of real constraint expressions, DEREF,
76    ADDRESSOF, and SCALAR.  Each constraint expression consists
77    of a constraint type, a variable, and an offset.
78
79    SCALAR is a constraint expression type used to represent x, whether
80    it appears on the LHS or the RHS of a statement.
81    DEREF is a constraint expression type used to represent *x, whether
82    it appears on the LHS or the RHS of a statement.
83    ADDRESSOF is a constraint expression used to represent &x, whether
84    it appears on the LHS or the RHS of a statement.
85
86    Each pointer variable in the program is assigned an integer id, and
87    each field of a structure variable is assigned an integer id as well.
88
89    Structure variables are linked to their list of fields through a "next
90    field" in each variable that points to the next field in offset
91    order.
92    Each variable for a structure field has
93
94    1. "size", that tells the size in bits of that field.
95    2. "fullsize, that tells the size in bits of the entire structure.
96    3. "offset", that tells the offset in bits from the beginning of the
97    structure to this field.
98
99    Thus,
100    struct f
101    {
102      int a;
103      int b;
104    } foo;
105    int *bar;
106
107    looks like
108
109    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
110    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
111    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
112
113
114   In order to solve the system of set constraints, the following is
115   done:
116
117   1. Each constraint variable x has a solution set associated with it,
118   Sol(x).
119
120   2. Constraints are separated into direct, copy, and complex.
121   Direct constraints are ADDRESSOF constraints that require no extra
122   processing, such as P = &Q
123   Copy constraints are those of the form P = Q.
124   Complex constraints are all the constraints involving dereferences
125   and offsets (including offsetted copies).
126
127   3. All direct constraints of the form P = &Q are processed, such
128   that Q is added to Sol(P)
129
130   4. All complex constraints for a given constraint variable are stored in a
131   linked list attached to that variable's node.
132
133   5. A directed graph is built out of the copy constraints. Each
134   constraint variable is a node in the graph, and an edge from
135   Q to P is added for each copy constraint of the form P = Q
136
137   6. The graph is then walked, and solution sets are
138   propagated along the copy edges, such that an edge from Q to P
139   causes Sol(P) <- Sol(P) union Sol(Q).
140
141   7.  As we visit each node, all complex constraints associated with
142   that node are processed by adding appropriate copy edges to the graph, or the
143   appropriate variables to the solution set.
144
145   8. The process of walking the graph is iterated until no solution
146   sets change.
147
148   Prior to walking the graph in steps 6 and 7, We perform static
149   cycle elimination on the constraint graph, as well
150   as off-line variable substitution.
151
152   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
153   on and turned into anything), but isn't.  You can just see what offset
154   inside the pointed-to struct it's going to access.
155
156   TODO: Constant bounded arrays can be handled as if they were structs of the
157   same number of elements.
158
159   TODO: Modeling heap and incoming pointers becomes much better if we
160   add fields to them as we discover them, which we could do.
161
162   TODO: We could handle unions, but to be honest, it's probably not
163   worth the pain or slowdown.  */
164
165 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
166 htab_t heapvar_for_stmt;
167
168 static bool use_field_sensitive = true;
169 static int in_ipa_mode = 0;
170
171 /* Used for predecessor bitmaps. */
172 static bitmap_obstack predbitmap_obstack;
173
174 /* Used for points-to sets.  */
175 static bitmap_obstack pta_obstack;
176
177 /* Used for oldsolution members of variables. */
178 static bitmap_obstack oldpta_obstack;
179
180 /* Used for per-solver-iteration bitmaps.  */
181 static bitmap_obstack iteration_obstack;
182
183 static unsigned int create_variable_info_for (tree, const char *);
184 typedef struct constraint_graph *constraint_graph_t;
185 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
186
187 struct constraint;
188 typedef struct constraint *constraint_t;
189
190 DEF_VEC_P(constraint_t);
191 DEF_VEC_ALLOC_P(constraint_t,heap);
192
193 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d)        \
194   if (a)                                                \
195     EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
196
197 static struct constraint_stats
198 {
199   unsigned int total_vars;
200   unsigned int nonpointer_vars;
201   unsigned int unified_vars_static;
202   unsigned int unified_vars_dynamic;
203   unsigned int iterations;
204   unsigned int num_edges;
205   unsigned int num_implicit_edges;
206   unsigned int points_to_sets_created;
207 } stats;
208
209 struct variable_info
210 {
211   /* ID of this variable  */
212   unsigned int id;
213
214   /* True if this is a variable created by the constraint analysis, such as
215      heap variables and constraints we had to break up.  */
216   unsigned int is_artificial_var:1;
217
218   /* True if this is a special variable whose solution set should not be
219      changed.  */
220   unsigned int is_special_var:1;
221
222   /* True for variables whose size is not known or variable.  */
223   unsigned int is_unknown_size_var:1;
224
225   /* True for (sub-)fields that represent a whole variable.  */
226   unsigned int is_full_var : 1;
227
228   /* True if this is a heap variable.  */
229   unsigned int is_heap_var:1;
230
231   /* True if we may not use TBAA to prune references to this
232      variable.  This is used for C++ placement new.  */
233   unsigned int no_tbaa_pruning : 1;
234
235   /* True if this field may contain pointers.  */
236   unsigned int may_have_pointers : 1;
237
238   /* A link to the variable for the next field in this structure.  */
239   struct variable_info *next;
240
241   /* Offset of this variable, in bits, from the base variable  */
242   unsigned HOST_WIDE_INT offset;
243
244   /* Size of the variable, in bits.  */
245   unsigned HOST_WIDE_INT size;
246
247   /* Full size of the base variable, in bits.  */
248   unsigned HOST_WIDE_INT fullsize;
249
250   /* Name of this variable */
251   const char *name;
252
253   /* Tree that this variable is associated with.  */
254   tree decl;
255
256   /* Points-to set for this variable.  */
257   bitmap solution;
258
259   /* Old points-to set for this variable.  */
260   bitmap oldsolution;
261 };
262 typedef struct variable_info *varinfo_t;
263
264 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
265 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
266                                                    unsigned HOST_WIDE_INT);
267 static varinfo_t lookup_vi_for_tree (tree);
268
269 /* Pool of variable info structures.  */
270 static alloc_pool variable_info_pool;
271
272 DEF_VEC_P(varinfo_t);
273
274 DEF_VEC_ALLOC_P(varinfo_t, heap);
275
276 /* Table of variable info structures for constraint variables.
277    Indexed directly by variable info id.  */
278 static VEC(varinfo_t,heap) *varmap;
279
280 /* Return the varmap element N */
281
282 static inline varinfo_t
283 get_varinfo (unsigned int n)
284 {
285   return VEC_index (varinfo_t, varmap, n);
286 }
287
288 /* Static IDs for the special variables.  */
289 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
290        escaped_id = 3, nonlocal_id = 4, callused_id = 5,
291        storedanything_id = 6, integer_id = 7 };
292
293 /* Variable that represents the unknown pointer.  */
294 static varinfo_t var_anything;
295 static tree anything_tree;
296
297 /* Variable that represents the NULL pointer.  */
298 static varinfo_t var_nothing;
299 static tree nothing_tree;
300
301 /* Variable that represents read only memory.  */
302 static varinfo_t var_readonly;
303 static tree readonly_tree;
304
305 /* Variable that represents escaped memory.  */
306 static varinfo_t var_escaped;
307 static tree escaped_tree;
308
309 /* Variable that represents nonlocal memory.  */
310 static varinfo_t var_nonlocal;
311 static tree nonlocal_tree;
312
313 /* Variable that represents call-used memory.  */
314 static varinfo_t var_callused;
315 static tree callused_tree;
316
317 /* Variable that represents variables that are stored to anything.  */
318 static varinfo_t var_storedanything;
319 static tree storedanything_tree;
320
321 /* Variable that represents integers.  This is used for when people do things
322    like &0->a.b.  */
323 static varinfo_t var_integer;
324 static tree integer_tree;
325
326 /* Lookup a heap var for FROM, and return it if we find one.  */
327
328 static tree
329 heapvar_lookup (tree from)
330 {
331   struct tree_map *h, in;
332   in.base.from = from;
333
334   h = (struct tree_map *) htab_find_with_hash (heapvar_for_stmt, &in,
335                                                htab_hash_pointer (from));
336   if (h)
337     return h->to;
338   return NULL_TREE;
339 }
340
341 /* Insert a mapping FROM->TO in the heap var for statement
342    hashtable.  */
343
344 static void
345 heapvar_insert (tree from, tree to)
346 {
347   struct tree_map *h;
348   void **loc;
349
350   h = GGC_NEW (struct tree_map);
351   h->hash = htab_hash_pointer (from);
352   h->base.from = from;
353   h->to = to;
354   loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
355   *(struct tree_map **) loc = h;
356 }
357
358 /* Return a new variable info structure consisting for a variable
359    named NAME, and using constraint graph node NODE.  */
360
361 static varinfo_t
362 new_var_info (tree t, unsigned int id, const char *name)
363 {
364   varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
365   tree var;
366
367   ret->id = id;
368   ret->name = name;
369   ret->decl = t;
370   ret->is_artificial_var = false;
371   ret->is_heap_var = false;
372   ret->is_special_var = false;
373   ret->is_unknown_size_var = false;
374   ret->is_full_var = false;
375   ret->may_have_pointers = true;
376   var = t;
377   if (TREE_CODE (var) == SSA_NAME)
378     var = SSA_NAME_VAR (var);
379   ret->no_tbaa_pruning = (DECL_P (var)
380                           && POINTER_TYPE_P (TREE_TYPE (var))
381                           && DECL_NO_TBAA_P (var));
382   ret->solution = BITMAP_ALLOC (&pta_obstack);
383   ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
384   ret->next = NULL;
385   return ret;
386 }
387
388 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
389
390 /* An expression that appears in a constraint.  */
391
392 struct constraint_expr
393 {
394   /* Constraint type.  */
395   constraint_expr_type type;
396
397   /* Variable we are referring to in the constraint.  */
398   unsigned int var;
399
400   /* Offset, in bits, of this constraint from the beginning of
401      variables it ends up referring to.
402
403      IOW, in a deref constraint, we would deref, get the result set,
404      then add OFFSET to each member.   */
405   HOST_WIDE_INT offset;
406 };
407
408 /* Use 0x8000... as special unknown offset.  */
409 #define UNKNOWN_OFFSET ((HOST_WIDE_INT)-1 << (HOST_BITS_PER_WIDE_INT-1))
410
411 typedef struct constraint_expr ce_s;
412 DEF_VEC_O(ce_s);
413 DEF_VEC_ALLOC_O(ce_s, heap);
414 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool);
415 static void get_constraint_for (tree, VEC(ce_s, heap) **);
416 static void do_deref (VEC (ce_s, heap) **);
417
418 /* Our set constraints are made up of two constraint expressions, one
419    LHS, and one RHS.
420
421    As described in the introduction, our set constraints each represent an
422    operation between set valued variables.
423 */
424 struct constraint
425 {
426   struct constraint_expr lhs;
427   struct constraint_expr rhs;
428 };
429
430 /* List of constraints that we use to build the constraint graph from.  */
431
432 static VEC(constraint_t,heap) *constraints;
433 static alloc_pool constraint_pool;
434
435
436 DEF_VEC_I(int);
437 DEF_VEC_ALLOC_I(int, heap);
438
439 /* The constraint graph is represented as an array of bitmaps
440    containing successor nodes.  */
441
442 struct constraint_graph
443 {
444   /* Size of this graph, which may be different than the number of
445      nodes in the variable map.  */
446   unsigned int size;
447
448   /* Explicit successors of each node. */
449   bitmap *succs;
450
451   /* Implicit predecessors of each node (Used for variable
452      substitution). */
453   bitmap *implicit_preds;
454
455   /* Explicit predecessors of each node (Used for variable substitution).  */
456   bitmap *preds;
457
458   /* Indirect cycle representatives, or -1 if the node has no indirect
459      cycles.  */
460   int *indirect_cycles;
461
462   /* Representative node for a node.  rep[a] == a unless the node has
463      been unified. */
464   unsigned int *rep;
465
466   /* Equivalence class representative for a label.  This is used for
467      variable substitution.  */
468   int *eq_rep;
469
470   /* Pointer equivalence label for a node.  All nodes with the same
471      pointer equivalence label can be unified together at some point
472      (either during constraint optimization or after the constraint
473      graph is built).  */
474   unsigned int *pe;
475
476   /* Pointer equivalence representative for a label.  This is used to
477      handle nodes that are pointer equivalent but not location
478      equivalent.  We can unite these once the addressof constraints
479      are transformed into initial points-to sets.  */
480   int *pe_rep;
481
482   /* Pointer equivalence label for each node, used during variable
483      substitution.  */
484   unsigned int *pointer_label;
485
486   /* Location equivalence label for each node, used during location
487      equivalence finding.  */
488   unsigned int *loc_label;
489
490   /* Pointed-by set for each node, used during location equivalence
491      finding.  This is pointed-by rather than pointed-to, because it
492      is constructed using the predecessor graph.  */
493   bitmap *pointed_by;
494
495   /* Points to sets for pointer equivalence.  This is *not* the actual
496      points-to sets for nodes.  */
497   bitmap *points_to;
498
499   /* Bitmap of nodes where the bit is set if the node is a direct
500      node.  Used for variable substitution.  */
501   sbitmap direct_nodes;
502
503   /* Bitmap of nodes where the bit is set if the node is address
504      taken.  Used for variable substitution.  */
505   bitmap address_taken;
506
507   /* Vector of complex constraints for each graph node.  Complex
508      constraints are those involving dereferences or offsets that are
509      not 0.  */
510   VEC(constraint_t,heap) **complex;
511 };
512
513 static constraint_graph_t graph;
514
515 /* During variable substitution and the offline version of indirect
516    cycle finding, we create nodes to represent dereferences and
517    address taken constraints.  These represent where these start and
518    end.  */
519 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
520 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
521
522 /* Return the representative node for NODE, if NODE has been unioned
523    with another NODE.
524    This function performs path compression along the way to finding
525    the representative.  */
526
527 static unsigned int
528 find (unsigned int node)
529 {
530   gcc_assert (node < graph->size);
531   if (graph->rep[node] != node)
532     return graph->rep[node] = find (graph->rep[node]);
533   return node;
534 }
535
536 /* Union the TO and FROM nodes to the TO nodes.
537    Note that at some point in the future, we may want to do
538    union-by-rank, in which case we are going to have to return the
539    node we unified to.  */
540
541 static bool
542 unite (unsigned int to, unsigned int from)
543 {
544   gcc_assert (to < graph->size && from < graph->size);
545   if (to != from && graph->rep[from] != to)
546     {
547       graph->rep[from] = to;
548       return true;
549     }
550   return false;
551 }
552
553 /* Create a new constraint consisting of LHS and RHS expressions.  */
554
555 static constraint_t
556 new_constraint (const struct constraint_expr lhs,
557                 const struct constraint_expr rhs)
558 {
559   constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
560   ret->lhs = lhs;
561   ret->rhs = rhs;
562   return ret;
563 }
564
565 /* Print out constraint C to FILE.  */
566
567 static void
568 dump_constraint (FILE *file, constraint_t c)
569 {
570   if (c->lhs.type == ADDRESSOF)
571     fprintf (file, "&");
572   else if (c->lhs.type == DEREF)
573     fprintf (file, "*");
574   fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
575   if (c->lhs.offset == UNKNOWN_OFFSET)
576     fprintf (file, " + UNKNOWN");
577   else if (c->lhs.offset != 0)
578     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
579   fprintf (file, " = ");
580   if (c->rhs.type == ADDRESSOF)
581     fprintf (file, "&");
582   else if (c->rhs.type == DEREF)
583     fprintf (file, "*");
584   fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
585   if (c->rhs.offset == UNKNOWN_OFFSET)
586     fprintf (file, " + UNKNOWN");
587   else if (c->rhs.offset != 0)
588     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
589   fprintf (file, "\n");
590 }
591
592
593 void debug_constraint (constraint_t);
594 void debug_constraints (void);
595 void debug_constraint_graph (void);
596 void debug_solution_for_var (unsigned int);
597 void debug_sa_points_to_info (void);
598
599 /* Print out constraint C to stderr.  */
600
601 void
602 debug_constraint (constraint_t c)
603 {
604   dump_constraint (stderr, c);
605 }
606
607 /* Print out all constraints to FILE */
608
609 static void
610 dump_constraints (FILE *file)
611 {
612   int i;
613   constraint_t c;
614   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
615     dump_constraint (file, c);
616 }
617
618 /* Print out all constraints to stderr.  */
619
620 void
621 debug_constraints (void)
622 {
623   dump_constraints (stderr);
624 }
625
626 /* Print out to FILE the edge in the constraint graph that is created by
627    constraint c. The edge may have a label, depending on the type of
628    constraint that it represents. If complex1, e.g: a = *b, then the label
629    is "=*", if complex2, e.g: *a = b, then the label is "*=", if
630    complex with an offset, e.g: a = b + 8, then the label is "+".
631    Otherwise the edge has no label.  */
632
633 static void
634 dump_constraint_edge (FILE *file, constraint_t c)
635 {
636   if (c->rhs.type != ADDRESSOF)
637     {
638       const char *src = get_varinfo (c->rhs.var)->name;
639       const char *dst = get_varinfo (c->lhs.var)->name;
640       fprintf (file, "  \"%s\" -> \"%s\" ", src, dst);
641       /* Due to preprocessing of constraints, instructions like *a = *b are
642          illegal; thus, we do not have to handle such cases.  */
643       if (c->lhs.type == DEREF)
644         fprintf (file, " [ label=\"*=\" ] ;\n");
645       else if (c->rhs.type == DEREF)
646         fprintf (file, " [ label=\"=*\" ] ;\n");
647       else
648         {
649           /* We must check the case where the constraint is an offset.
650              In this case, it is treated as a complex constraint.  */
651           if (c->rhs.offset != c->lhs.offset)
652             fprintf (file, " [ label=\"+\" ] ;\n");
653           else
654             fprintf (file, " ;\n");
655         }
656     }
657 }
658
659 /* Print the constraint graph in dot format.  */
660
661 static void
662 dump_constraint_graph (FILE *file)
663 {
664   unsigned int i=0, size;
665   constraint_t c;
666
667   /* Only print the graph if it has already been initialized:  */
668   if (!graph)
669     return;
670
671   /* Print the constraints used to produce the constraint graph. The
672      constraints will be printed as comments in the dot file:  */
673   fprintf (file, "\n\n/* Constraints used in the constraint graph:\n");
674   dump_constraints (file);
675   fprintf (file, "*/\n");
676
677   /* Prints the header of the dot file:  */
678   fprintf (file, "\n\n// The constraint graph in dot format:\n");
679   fprintf (file, "strict digraph {\n");
680   fprintf (file, "  node [\n    shape = box\n  ]\n");
681   fprintf (file, "  edge [\n    fontsize = \"12\"\n  ]\n");
682   fprintf (file, "\n  // List of nodes in the constraint graph:\n");
683
684   /* The next lines print the nodes in the graph. In order to get the
685      number of nodes in the graph, we must choose the minimum between the
686      vector VEC (varinfo_t, varmap) and graph->size. If the graph has not
687      yet been initialized, then graph->size == 0, otherwise we must only
688      read nodes that have an entry in VEC (varinfo_t, varmap).  */
689   size = VEC_length (varinfo_t, varmap);
690   size = size < graph->size ? size : graph->size;
691   for (i = 0; i < size; i++)
692     {
693       const char *name = get_varinfo (graph->rep[i])->name;
694       fprintf (file, "  \"%s\" ;\n", name);
695     }
696
697   /* Go over the list of constraints printing the edges in the constraint
698      graph.  */
699   fprintf (file, "\n  // The constraint edges:\n");
700   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
701     if (c)
702       dump_constraint_edge (file, c);
703
704   /* Prints the tail of the dot file. By now, only the closing bracket.  */
705   fprintf (file, "}\n\n\n");
706 }
707
708 /* Print out the constraint graph to stderr.  */
709
710 void
711 debug_constraint_graph (void)
712 {
713   dump_constraint_graph (stderr);
714 }
715
716 /* SOLVER FUNCTIONS
717
718    The solver is a simple worklist solver, that works on the following
719    algorithm:
720
721    sbitmap changed_nodes = all zeroes;
722    changed_count = 0;
723    For each node that is not already collapsed:
724        changed_count++;
725        set bit in changed nodes
726
727    while (changed_count > 0)
728    {
729      compute topological ordering for constraint graph
730
731      find and collapse cycles in the constraint graph (updating
732      changed if necessary)
733
734      for each node (n) in the graph in topological order:
735        changed_count--;
736
737        Process each complex constraint associated with the node,
738        updating changed if necessary.
739
740        For each outgoing edge from n, propagate the solution from n to
741        the destination of the edge, updating changed as necessary.
742
743    }  */
744
745 /* Return true if two constraint expressions A and B are equal.  */
746
747 static bool
748 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
749 {
750   return a.type == b.type && a.var == b.var && a.offset == b.offset;
751 }
752
753 /* Return true if constraint expression A is less than constraint expression
754    B.  This is just arbitrary, but consistent, in order to give them an
755    ordering.  */
756
757 static bool
758 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
759 {
760   if (a.type == b.type)
761     {
762       if (a.var == b.var)
763         return a.offset < b.offset;
764       else
765         return a.var < b.var;
766     }
767   else
768     return a.type < b.type;
769 }
770
771 /* Return true if constraint A is less than constraint B.  This is just
772    arbitrary, but consistent, in order to give them an ordering.  */
773
774 static bool
775 constraint_less (const constraint_t a, const constraint_t b)
776 {
777   if (constraint_expr_less (a->lhs, b->lhs))
778     return true;
779   else if (constraint_expr_less (b->lhs, a->lhs))
780     return false;
781   else
782     return constraint_expr_less (a->rhs, b->rhs);
783 }
784
785 /* Return true if two constraints A and B are equal.  */
786
787 static bool
788 constraint_equal (struct constraint a, struct constraint b)
789 {
790   return constraint_expr_equal (a.lhs, b.lhs)
791     && constraint_expr_equal (a.rhs, b.rhs);
792 }
793
794
795 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
796
797 static constraint_t
798 constraint_vec_find (VEC(constraint_t,heap) *vec,
799                      struct constraint lookfor)
800 {
801   unsigned int place;
802   constraint_t found;
803
804   if (vec == NULL)
805     return NULL;
806
807   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
808   if (place >= VEC_length (constraint_t, vec))
809     return NULL;
810   found = VEC_index (constraint_t, vec, place);
811   if (!constraint_equal (*found, lookfor))
812     return NULL;
813   return found;
814 }
815
816 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
817
818 static void
819 constraint_set_union (VEC(constraint_t,heap) **to,
820                       VEC(constraint_t,heap) **from)
821 {
822   int i;
823   constraint_t c;
824
825   for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
826     {
827       if (constraint_vec_find (*to, *c) == NULL)
828         {
829           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
830                                                 constraint_less);
831           VEC_safe_insert (constraint_t, heap, *to, place, c);
832         }
833     }
834 }
835
836 /* Expands the solution in SET to all sub-fields of variables included.
837    Union the expanded result into RESULT.  */
838
839 static void
840 solution_set_expand (bitmap result, bitmap set)
841 {
842   bitmap_iterator bi;
843   bitmap vars = NULL;
844   unsigned j;
845
846   /* In a first pass record all variables we need to add all
847      sub-fields off.  This avoids quadratic behavior.  */
848   EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
849     {
850       varinfo_t v = get_varinfo (j);
851       if (v->is_artificial_var
852           || v->is_full_var)
853         continue;
854       v = lookup_vi_for_tree (v->decl);
855       if (vars == NULL)
856         vars = BITMAP_ALLOC (NULL);
857       bitmap_set_bit (vars, v->id);
858     }
859
860   /* In the second pass now do the addition to the solution and
861      to speed up solving add it to the delta as well.  */
862   if (vars != NULL)
863     {
864       EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
865         {
866           varinfo_t v = get_varinfo (j);
867           for (; v != NULL; v = v->next)
868             bitmap_set_bit (result, v->id);
869         }
870       BITMAP_FREE (vars);
871     }
872 }
873
874 /* Take a solution set SET, add OFFSET to each member of the set, and
875    overwrite SET with the result when done.  */
876
877 static void
878 solution_set_add (bitmap set, HOST_WIDE_INT offset)
879 {
880   bitmap result = BITMAP_ALLOC (&iteration_obstack);
881   unsigned int i;
882   bitmap_iterator bi;
883
884   /* If the offset is unknown we have to expand the solution to
885      all subfields.  */
886   if (offset == UNKNOWN_OFFSET)
887     {
888       solution_set_expand (set, set);
889       return;
890     }
891
892   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
893     {
894       varinfo_t vi = get_varinfo (i);
895
896       /* If this is a variable with just one field just set its bit
897          in the result.  */
898       if (vi->is_artificial_var
899           || vi->is_unknown_size_var
900           || vi->is_full_var)
901         bitmap_set_bit (result, i);
902       else
903         {
904           unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
905
906           /* If the offset makes the pointer point to before the
907              variable use offset zero for the field lookup.  */
908           if (offset < 0
909               && fieldoffset > vi->offset)
910             fieldoffset = 0;
911
912           if (offset != 0)
913             vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
914
915           bitmap_set_bit (result, vi->id);
916           /* If the result is not exactly at fieldoffset include the next
917              field as well.  See get_constraint_for_ptr_offset for more
918              rationale.  */
919           if (vi->offset != fieldoffset
920               && vi->next != NULL)
921             bitmap_set_bit (result, vi->next->id);
922         }
923     }
924
925   bitmap_copy (set, result);
926   BITMAP_FREE (result);
927 }
928
929 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
930    process.  */
931
932 static bool
933 set_union_with_increment  (bitmap to, bitmap from, HOST_WIDE_INT inc)
934 {
935   if (inc == 0)
936     return bitmap_ior_into (to, from);
937   else
938     {
939       bitmap tmp;
940       bool res;
941
942       tmp = BITMAP_ALLOC (&iteration_obstack);
943       bitmap_copy (tmp, from);
944       solution_set_add (tmp, inc);
945       res = bitmap_ior_into (to, tmp);
946       BITMAP_FREE (tmp);
947       return res;
948     }
949 }
950
951 /* Insert constraint C into the list of complex constraints for graph
952    node VAR.  */
953
954 static void
955 insert_into_complex (constraint_graph_t graph,
956                      unsigned int var, constraint_t c)
957 {
958   VEC (constraint_t, heap) *complex = graph->complex[var];
959   unsigned int place = VEC_lower_bound (constraint_t, complex, c,
960                                         constraint_less);
961
962   /* Only insert constraints that do not already exist.  */
963   if (place >= VEC_length (constraint_t, complex)
964       || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
965     VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
966 }
967
968
969 /* Condense two variable nodes into a single variable node, by moving
970    all associated info from SRC to TO.  */
971
972 static void
973 merge_node_constraints (constraint_graph_t graph, unsigned int to,
974                         unsigned int from)
975 {
976   unsigned int i;
977   constraint_t c;
978
979   gcc_assert (find (from) == to);
980
981   /* Move all complex constraints from src node into to node  */
982   for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
983     {
984       /* In complex constraints for node src, we may have either
985          a = *src, and *src = a, or an offseted constraint which are
986          always added to the rhs node's constraints.  */
987
988       if (c->rhs.type == DEREF)
989         c->rhs.var = to;
990       else if (c->lhs.type == DEREF)
991         c->lhs.var = to;
992       else
993         c->rhs.var = to;
994     }
995   constraint_set_union (&graph->complex[to], &graph->complex[from]);
996   VEC_free (constraint_t, heap, graph->complex[from]);
997   graph->complex[from] = NULL;
998 }
999
1000
1001 /* Remove edges involving NODE from GRAPH.  */
1002
1003 static void
1004 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1005 {
1006   if (graph->succs[node])
1007     BITMAP_FREE (graph->succs[node]);
1008 }
1009
1010 /* Merge GRAPH nodes FROM and TO into node TO.  */
1011
1012 static void
1013 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1014                    unsigned int from)
1015 {
1016   if (graph->indirect_cycles[from] != -1)
1017     {
1018       /* If we have indirect cycles with the from node, and we have
1019          none on the to node, the to node has indirect cycles from the
1020          from node now that they are unified.
1021          If indirect cycles exist on both, unify the nodes that they
1022          are in a cycle with, since we know they are in a cycle with
1023          each other.  */
1024       if (graph->indirect_cycles[to] == -1)
1025         graph->indirect_cycles[to] = graph->indirect_cycles[from];
1026     }
1027
1028   /* Merge all the successor edges.  */
1029   if (graph->succs[from])
1030     {
1031       if (!graph->succs[to])
1032         graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1033       bitmap_ior_into (graph->succs[to],
1034                        graph->succs[from]);
1035     }
1036
1037   clear_edges_for_node (graph, from);
1038 }
1039
1040
1041 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1042    it doesn't exist in the graph already.  */
1043
1044 static void
1045 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1046                          unsigned int from)
1047 {
1048   if (to == from)
1049     return;
1050
1051   if (!graph->implicit_preds[to])
1052     graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1053
1054   if (bitmap_set_bit (graph->implicit_preds[to], from))
1055     stats.num_implicit_edges++;
1056 }
1057
1058 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1059    it doesn't exist in the graph already.
1060    Return false if the edge already existed, true otherwise.  */
1061
1062 static void
1063 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1064                      unsigned int from)
1065 {
1066   if (!graph->preds[to])
1067     graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1068   bitmap_set_bit (graph->preds[to], from);
1069 }
1070
1071 /* Add a graph edge to GRAPH, going from FROM to TO if
1072    it doesn't exist in the graph already.
1073    Return false if the edge already existed, true otherwise.  */
1074
1075 static bool
1076 add_graph_edge (constraint_graph_t graph, unsigned int to,
1077                 unsigned int from)
1078 {
1079   if (to == from)
1080     {
1081       return false;
1082     }
1083   else
1084     {
1085       bool r = false;
1086
1087       if (!graph->succs[from])
1088         graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1089       if (bitmap_set_bit (graph->succs[from], to))
1090         {
1091           r = true;
1092           if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1093             stats.num_edges++;
1094         }
1095       return r;
1096     }
1097 }
1098
1099
1100 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH.  */
1101
1102 static bool
1103 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1104                   unsigned int dest)
1105 {
1106   return (graph->succs[dest]
1107           && bitmap_bit_p (graph->succs[dest], src));
1108 }
1109
1110 /* Initialize the constraint graph structure to contain SIZE nodes.  */
1111
1112 static void
1113 init_graph (unsigned int size)
1114 {
1115   unsigned int j;
1116
1117   graph = XCNEW (struct constraint_graph);
1118   graph->size = size;
1119   graph->succs = XCNEWVEC (bitmap, graph->size);
1120   graph->indirect_cycles = XNEWVEC (int, graph->size);
1121   graph->rep = XNEWVEC (unsigned int, graph->size);
1122   graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1123   graph->pe = XCNEWVEC (unsigned int, graph->size);
1124   graph->pe_rep = XNEWVEC (int, graph->size);
1125
1126   for (j = 0; j < graph->size; j++)
1127     {
1128       graph->rep[j] = j;
1129       graph->pe_rep[j] = -1;
1130       graph->indirect_cycles[j] = -1;
1131     }
1132 }
1133
1134 /* Build the constraint graph, adding only predecessor edges right now.  */
1135
1136 static void
1137 build_pred_graph (void)
1138 {
1139   int i;
1140   constraint_t c;
1141   unsigned int j;
1142
1143   graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1144   graph->preds = XCNEWVEC (bitmap, graph->size);
1145   graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1146   graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1147   graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1148   graph->points_to = XCNEWVEC (bitmap, graph->size);
1149   graph->eq_rep = XNEWVEC (int, graph->size);
1150   graph->direct_nodes = sbitmap_alloc (graph->size);
1151   graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1152   sbitmap_zero (graph->direct_nodes);
1153
1154   for (j = 0; j < FIRST_REF_NODE; j++)
1155     {
1156       if (!get_varinfo (j)->is_special_var)
1157         SET_BIT (graph->direct_nodes, j);
1158     }
1159
1160   for (j = 0; j < graph->size; j++)
1161     graph->eq_rep[j] = -1;
1162
1163   for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1164     graph->indirect_cycles[j] = -1;
1165
1166   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1167     {
1168       struct constraint_expr lhs = c->lhs;
1169       struct constraint_expr rhs = c->rhs;
1170       unsigned int lhsvar = lhs.var;
1171       unsigned int rhsvar = rhs.var;
1172
1173       if (lhs.type == DEREF)
1174         {
1175           /* *x = y.  */
1176           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1177             add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1178         }
1179       else if (rhs.type == DEREF)
1180         {
1181           /* x = *y */
1182           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1183             add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1184           else
1185             RESET_BIT (graph->direct_nodes, lhsvar);
1186         }
1187       else if (rhs.type == ADDRESSOF)
1188         {
1189           varinfo_t v;
1190
1191           /* x = &y */
1192           if (graph->points_to[lhsvar] == NULL)
1193             graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1194           bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1195
1196           if (graph->pointed_by[rhsvar] == NULL)
1197             graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1198           bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1199
1200           /* Implicitly, *x = y */
1201           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1202
1203           /* All related variables are no longer direct nodes.  */
1204           RESET_BIT (graph->direct_nodes, rhsvar);
1205           v = get_varinfo (rhsvar);
1206           if (!v->is_full_var)
1207             {
1208               v = lookup_vi_for_tree (v->decl);
1209               do
1210                 {
1211                   RESET_BIT (graph->direct_nodes, v->id);
1212                   v = v->next;
1213                 }
1214               while (v != NULL);
1215             }
1216           bitmap_set_bit (graph->address_taken, rhsvar);
1217         }
1218       else if (lhsvar > anything_id
1219                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1220         {
1221           /* x = y */
1222           add_pred_graph_edge (graph, lhsvar, rhsvar);
1223           /* Implicitly, *x = *y */
1224           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1225                                    FIRST_REF_NODE + rhsvar);
1226         }
1227       else if (lhs.offset != 0 || rhs.offset != 0)
1228         {
1229           if (rhs.offset != 0)
1230             RESET_BIT (graph->direct_nodes, lhs.var);
1231           else if (lhs.offset != 0)
1232             RESET_BIT (graph->direct_nodes, rhs.var);
1233         }
1234     }
1235 }
1236
1237 /* Build the constraint graph, adding successor edges.  */
1238
1239 static void
1240 build_succ_graph (void)
1241 {
1242   unsigned i, t;
1243   constraint_t c;
1244
1245   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1246     {
1247       struct constraint_expr lhs;
1248       struct constraint_expr rhs;
1249       unsigned int lhsvar;
1250       unsigned int rhsvar;
1251
1252       if (!c)
1253         continue;
1254
1255       lhs = c->lhs;
1256       rhs = c->rhs;
1257       lhsvar = find (lhs.var);
1258       rhsvar = find (rhs.var);
1259
1260       if (lhs.type == DEREF)
1261         {
1262           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1263             add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1264         }
1265       else if (rhs.type == DEREF)
1266         {
1267           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1268             add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1269         }
1270       else if (rhs.type == ADDRESSOF)
1271         {
1272           /* x = &y */
1273           gcc_assert (find (rhs.var) == rhs.var);
1274           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1275         }
1276       else if (lhsvar > anything_id
1277                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1278         {
1279           add_graph_edge (graph, lhsvar, rhsvar);
1280         }
1281     }
1282
1283   /* Add edges from STOREDANYTHING to all non-direct nodes.  */
1284   t = find (storedanything_id);
1285   for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1286     {
1287       if (!TEST_BIT (graph->direct_nodes, i))
1288         add_graph_edge (graph, find (i), t);
1289     }
1290 }
1291
1292
1293 /* Changed variables on the last iteration.  */
1294 static unsigned int changed_count;
1295 static sbitmap changed;
1296
1297 DEF_VEC_I(unsigned);
1298 DEF_VEC_ALLOC_I(unsigned,heap);
1299
1300
1301 /* Strongly Connected Component visitation info.  */
1302
1303 struct scc_info
1304 {
1305   sbitmap visited;
1306   sbitmap deleted;
1307   unsigned int *dfs;
1308   unsigned int *node_mapping;
1309   int current_index;
1310   VEC(unsigned,heap) *scc_stack;
1311 };
1312
1313
1314 /* Recursive routine to find strongly connected components in GRAPH.
1315    SI is the SCC info to store the information in, and N is the id of current
1316    graph node we are processing.
1317
1318    This is Tarjan's strongly connected component finding algorithm, as
1319    modified by Nuutila to keep only non-root nodes on the stack.
1320    The algorithm can be found in "On finding the strongly connected
1321    connected components in a directed graph" by Esko Nuutila and Eljas
1322    Soisalon-Soininen, in Information Processing Letters volume 49,
1323    number 1, pages 9-14.  */
1324
1325 static void
1326 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1327 {
1328   unsigned int i;
1329   bitmap_iterator bi;
1330   unsigned int my_dfs;
1331
1332   SET_BIT (si->visited, n);
1333   si->dfs[n] = si->current_index ++;
1334   my_dfs = si->dfs[n];
1335
1336   /* Visit all the successors.  */
1337   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1338     {
1339       unsigned int w;
1340
1341       if (i > LAST_REF_NODE)
1342         break;
1343
1344       w = find (i);
1345       if (TEST_BIT (si->deleted, w))
1346         continue;
1347
1348       if (!TEST_BIT (si->visited, w))
1349         scc_visit (graph, si, w);
1350       {
1351         unsigned int t = find (w);
1352         unsigned int nnode = find (n);
1353         gcc_assert (nnode == n);
1354
1355         if (si->dfs[t] < si->dfs[nnode])
1356           si->dfs[n] = si->dfs[t];
1357       }
1358     }
1359
1360   /* See if any components have been identified.  */
1361   if (si->dfs[n] == my_dfs)
1362     {
1363       if (VEC_length (unsigned, si->scc_stack) > 0
1364           && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1365         {
1366           bitmap scc = BITMAP_ALLOC (NULL);
1367           bool have_ref_node = n >= FIRST_REF_NODE;
1368           unsigned int lowest_node;
1369           bitmap_iterator bi;
1370
1371           bitmap_set_bit (scc, n);
1372
1373           while (VEC_length (unsigned, si->scc_stack) != 0
1374                  && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1375             {
1376               unsigned int w = VEC_pop (unsigned, si->scc_stack);
1377
1378               bitmap_set_bit (scc, w);
1379               if (w >= FIRST_REF_NODE)
1380                 have_ref_node = true;
1381             }
1382
1383           lowest_node = bitmap_first_set_bit (scc);
1384           gcc_assert (lowest_node < FIRST_REF_NODE);
1385
1386           /* Collapse the SCC nodes into a single node, and mark the
1387              indirect cycles.  */
1388           EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1389             {
1390               if (i < FIRST_REF_NODE)
1391                 {
1392                   if (unite (lowest_node, i))
1393                     unify_nodes (graph, lowest_node, i, false);
1394                 }
1395               else
1396                 {
1397                   unite (lowest_node, i);
1398                   graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1399                 }
1400             }
1401         }
1402       SET_BIT (si->deleted, n);
1403     }
1404   else
1405     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1406 }
1407
1408 /* Unify node FROM into node TO, updating the changed count if
1409    necessary when UPDATE_CHANGED is true.  */
1410
1411 static void
1412 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1413              bool update_changed)
1414 {
1415
1416   gcc_assert (to != from && find (to) == to);
1417   if (dump_file && (dump_flags & TDF_DETAILS))
1418     fprintf (dump_file, "Unifying %s to %s\n",
1419              get_varinfo (from)->name,
1420              get_varinfo (to)->name);
1421
1422   if (update_changed)
1423     stats.unified_vars_dynamic++;
1424   else
1425     stats.unified_vars_static++;
1426
1427   merge_graph_nodes (graph, to, from);
1428   merge_node_constraints (graph, to, from);
1429
1430   if (get_varinfo (from)->no_tbaa_pruning)
1431     get_varinfo (to)->no_tbaa_pruning = true;
1432
1433   /* Mark TO as changed if FROM was changed. If TO was already marked
1434      as changed, decrease the changed count.  */
1435
1436   if (update_changed && TEST_BIT (changed, from))
1437     {
1438       RESET_BIT (changed, from);
1439       if (!TEST_BIT (changed, to))
1440         SET_BIT (changed, to);
1441       else
1442         {
1443           gcc_assert (changed_count > 0);
1444           changed_count--;
1445         }
1446     }
1447   if (get_varinfo (from)->solution)
1448     {
1449       /* If the solution changes because of the merging, we need to mark
1450          the variable as changed.  */
1451       if (bitmap_ior_into (get_varinfo (to)->solution,
1452                            get_varinfo (from)->solution))
1453         {
1454           if (update_changed && !TEST_BIT (changed, to))
1455             {
1456               SET_BIT (changed, to);
1457               changed_count++;
1458             }
1459         }
1460       
1461       BITMAP_FREE (get_varinfo (from)->solution);
1462       BITMAP_FREE (get_varinfo (from)->oldsolution);
1463       
1464       if (stats.iterations > 0)
1465         {
1466           BITMAP_FREE (get_varinfo (to)->oldsolution);
1467           get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1468         }
1469     }
1470   if (valid_graph_edge (graph, to, to))
1471     {
1472       if (graph->succs[to])
1473         bitmap_clear_bit (graph->succs[to], to);
1474     }
1475 }
1476
1477 /* Information needed to compute the topological ordering of a graph.  */
1478
1479 struct topo_info
1480 {
1481   /* sbitmap of visited nodes.  */
1482   sbitmap visited;
1483   /* Array that stores the topological order of the graph, *in
1484      reverse*.  */
1485   VEC(unsigned,heap) *topo_order;
1486 };
1487
1488
1489 /* Initialize and return a topological info structure.  */
1490
1491 static struct topo_info *
1492 init_topo_info (void)
1493 {
1494   size_t size = graph->size;
1495   struct topo_info *ti = XNEW (struct topo_info);
1496   ti->visited = sbitmap_alloc (size);
1497   sbitmap_zero (ti->visited);
1498   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1499   return ti;
1500 }
1501
1502
1503 /* Free the topological sort info pointed to by TI.  */
1504
1505 static void
1506 free_topo_info (struct topo_info *ti)
1507 {
1508   sbitmap_free (ti->visited);
1509   VEC_free (unsigned, heap, ti->topo_order);
1510   free (ti);
1511 }
1512
1513 /* Visit the graph in topological order, and store the order in the
1514    topo_info structure.  */
1515
1516 static void
1517 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1518             unsigned int n)
1519 {
1520   bitmap_iterator bi;
1521   unsigned int j;
1522
1523   SET_BIT (ti->visited, n);
1524
1525   if (graph->succs[n])
1526     EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1527       {
1528         if (!TEST_BIT (ti->visited, j))
1529           topo_visit (graph, ti, j);
1530       }
1531
1532   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1533 }
1534
1535 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1536    starting solution for y.  */
1537
1538 static void
1539 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1540                   bitmap delta)
1541 {
1542   unsigned int lhs = c->lhs.var;
1543   bool flag = false;
1544   bitmap sol = get_varinfo (lhs)->solution;
1545   unsigned int j;
1546   bitmap_iterator bi;
1547   HOST_WIDE_INT roffset = c->rhs.offset;
1548
1549   /* Our IL does not allow this.  */
1550   gcc_assert (c->lhs.offset == 0);
1551
1552   /* If the solution of Y contains anything it is good enough to transfer
1553      this to the LHS.  */
1554   if (bitmap_bit_p (delta, anything_id))
1555     {
1556       flag |= bitmap_set_bit (sol, anything_id);
1557       goto done;
1558     }
1559
1560   /* If we do not know at with offset the rhs is dereferenced compute
1561      the reachability set of DELTA, conservatively assuming it is
1562      dereferenced at all valid offsets.  */
1563   if (roffset == UNKNOWN_OFFSET)
1564     {
1565       solution_set_expand (delta, delta);
1566       /* No further offset processing is necessary.  */
1567       roffset = 0;
1568     }
1569
1570   /* For each variable j in delta (Sol(y)), add
1571      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1572   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1573     {
1574       varinfo_t v = get_varinfo (j);
1575       HOST_WIDE_INT fieldoffset = v->offset + roffset;
1576       unsigned int t;
1577
1578       if (v->is_full_var)
1579         fieldoffset = v->offset;
1580       else if (roffset != 0)
1581         v = first_vi_for_offset (v, fieldoffset);
1582       /* If the access is outside of the variable we can ignore it.  */
1583       if (!v)
1584         continue;
1585
1586       do
1587         {
1588           t = find (v->id);
1589
1590           /* Adding edges from the special vars is pointless.
1591              They don't have sets that can change.  */
1592           if (get_varinfo (t)->is_special_var)
1593             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1594           /* Merging the solution from ESCAPED needlessly increases
1595              the set.  Use ESCAPED as representative instead.  */
1596           else if (v->id == escaped_id)
1597             flag |= bitmap_set_bit (sol, escaped_id);
1598           else if (add_graph_edge (graph, lhs, t))
1599             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1600
1601           /* If the variable is not exactly at the requested offset
1602              we have to include the next one.  */
1603           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1604               || v->next == NULL)
1605             break;
1606
1607           v = v->next;
1608           fieldoffset = v->offset;
1609         }
1610       while (1);
1611     }
1612
1613 done:
1614   /* If the LHS solution changed, mark the var as changed.  */
1615   if (flag)
1616     {
1617       get_varinfo (lhs)->solution = sol;
1618       if (!TEST_BIT (changed, lhs))
1619         {
1620           SET_BIT (changed, lhs);
1621           changed_count++;
1622         }
1623     }
1624 }
1625
1626 /* Process a constraint C that represents *(x + off) = y using DELTA
1627    as the starting solution for x.  */
1628
1629 static void
1630 do_ds_constraint (constraint_t c, bitmap delta)
1631 {
1632   unsigned int rhs = c->rhs.var;
1633   bitmap sol = get_varinfo (rhs)->solution;
1634   unsigned int j;
1635   bitmap_iterator bi;
1636   HOST_WIDE_INT loff = c->lhs.offset;
1637
1638   /* Our IL does not allow this.  */
1639   gcc_assert (c->rhs.offset == 0);
1640
1641   /* If the solution of y contains ANYTHING simply use the ANYTHING
1642      solution.  This avoids needlessly increasing the points-to sets.  */
1643   if (bitmap_bit_p (sol, anything_id))
1644     sol = get_varinfo (find (anything_id))->solution;
1645
1646   /* If the solution for x contains ANYTHING we have to merge the
1647      solution of y into all pointer variables which we do via
1648      STOREDANYTHING.  */
1649   if (bitmap_bit_p (delta, anything_id))
1650     {
1651       unsigned t = find (storedanything_id);
1652       if (add_graph_edge (graph, t, rhs))
1653         {
1654           if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1655             {
1656               if (!TEST_BIT (changed, t))
1657                 {
1658                   SET_BIT (changed, t);
1659                   changed_count++;
1660                 }
1661             }
1662         }
1663       return;
1664     }
1665
1666   /* If we do not know at with offset the rhs is dereferenced compute
1667      the reachability set of DELTA, conservatively assuming it is
1668      dereferenced at all valid offsets.  */
1669   if (loff == UNKNOWN_OFFSET)
1670     {
1671       solution_set_expand (delta, delta);
1672       loff = 0;
1673     }
1674
1675   /* For each member j of delta (Sol(x)), add an edge from y to j and
1676      union Sol(y) into Sol(j) */
1677   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1678     {
1679       varinfo_t v = get_varinfo (j);
1680       unsigned int t;
1681       HOST_WIDE_INT fieldoffset = v->offset + loff;
1682
1683       if (v->is_special_var)
1684         continue;
1685
1686       if (v->is_full_var)
1687         fieldoffset = v->offset;
1688       else if (loff != 0)
1689         v = first_vi_for_offset (v, fieldoffset);
1690       /* If the access is outside of the variable we can ignore it.  */
1691       if (!v)
1692         continue;
1693
1694       do
1695         {
1696           if (v->may_have_pointers)
1697             {
1698               t = find (v->id);
1699               if (add_graph_edge (graph, t, rhs))
1700                 {
1701                   if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1702                     {
1703                       if (t == rhs)
1704                         sol = get_varinfo (rhs)->solution;
1705                       if (!TEST_BIT (changed, t))
1706                         {
1707                           SET_BIT (changed, t);
1708                           changed_count++;
1709                         }
1710                     }
1711                 }
1712             }
1713
1714           /* If the variable is not exactly at the requested offset
1715              we have to include the next one.  */
1716           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1717               || v->next == NULL)
1718             break;
1719
1720           v = v->next;
1721           fieldoffset = v->offset;
1722         }
1723       while (1);
1724     }
1725 }
1726
1727 /* Handle a non-simple (simple meaning requires no iteration),
1728    constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved).  */
1729
1730 static void
1731 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1732 {
1733   if (c->lhs.type == DEREF)
1734     {
1735       if (c->rhs.type == ADDRESSOF)
1736         {
1737           gcc_unreachable();
1738         }
1739       else
1740         {
1741           /* *x = y */
1742           do_ds_constraint (c, delta);
1743         }
1744     }
1745   else if (c->rhs.type == DEREF)
1746     {
1747       /* x = *y */
1748       if (!(get_varinfo (c->lhs.var)->is_special_var))
1749         do_sd_constraint (graph, c, delta);
1750     }
1751   else
1752     {
1753       bitmap tmp;
1754       bitmap solution;
1755       bool flag = false;
1756
1757       gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1758       solution = get_varinfo (c->rhs.var)->solution;
1759       tmp = get_varinfo (c->lhs.var)->solution;
1760
1761       flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1762
1763       if (flag)
1764         {
1765           get_varinfo (c->lhs.var)->solution = tmp;
1766           if (!TEST_BIT (changed, c->lhs.var))
1767             {
1768               SET_BIT (changed, c->lhs.var);
1769               changed_count++;
1770             }
1771         }
1772     }
1773 }
1774
1775 /* Initialize and return a new SCC info structure.  */
1776
1777 static struct scc_info *
1778 init_scc_info (size_t size)
1779 {
1780   struct scc_info *si = XNEW (struct scc_info);
1781   size_t i;
1782
1783   si->current_index = 0;
1784   si->visited = sbitmap_alloc (size);
1785   sbitmap_zero (si->visited);
1786   si->deleted = sbitmap_alloc (size);
1787   sbitmap_zero (si->deleted);
1788   si->node_mapping = XNEWVEC (unsigned int, size);
1789   si->dfs = XCNEWVEC (unsigned int, size);
1790
1791   for (i = 0; i < size; i++)
1792     si->node_mapping[i] = i;
1793
1794   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1795   return si;
1796 }
1797
1798 /* Free an SCC info structure pointed to by SI */
1799
1800 static void
1801 free_scc_info (struct scc_info *si)
1802 {
1803   sbitmap_free (si->visited);
1804   sbitmap_free (si->deleted);
1805   free (si->node_mapping);
1806   free (si->dfs);
1807   VEC_free (unsigned, heap, si->scc_stack);
1808   free (si);
1809 }
1810
1811
1812 /* Find indirect cycles in GRAPH that occur, using strongly connected
1813    components, and note them in the indirect cycles map.
1814
1815    This technique comes from Ben Hardekopf and Calvin Lin,
1816    "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1817    Lines of Code", submitted to PLDI 2007.  */
1818
1819 static void
1820 find_indirect_cycles (constraint_graph_t graph)
1821 {
1822   unsigned int i;
1823   unsigned int size = graph->size;
1824   struct scc_info *si = init_scc_info (size);
1825
1826   for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1827     if (!TEST_BIT (si->visited, i) && find (i) == i)
1828       scc_visit (graph, si, i);
1829
1830   free_scc_info (si);
1831 }
1832
1833 /* Compute a topological ordering for GRAPH, and store the result in the
1834    topo_info structure TI.  */
1835
1836 static void
1837 compute_topo_order (constraint_graph_t graph,
1838                     struct topo_info *ti)
1839 {
1840   unsigned int i;
1841   unsigned int size = graph->size;
1842
1843   for (i = 0; i != size; ++i)
1844     if (!TEST_BIT (ti->visited, i) && find (i) == i)
1845       topo_visit (graph, ti, i);
1846 }
1847
1848 /* Structure used to for hash value numbering of pointer equivalence
1849    classes.  */
1850
1851 typedef struct equiv_class_label
1852 {
1853   hashval_t hashcode;
1854   unsigned int equivalence_class;
1855   bitmap labels;
1856 } *equiv_class_label_t;
1857 typedef const struct equiv_class_label *const_equiv_class_label_t;
1858
1859 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1860    classes.  */
1861 static htab_t pointer_equiv_class_table;
1862
1863 /* A hashtable for mapping a bitmap of labels->location equivalence
1864    classes.  */
1865 static htab_t location_equiv_class_table;
1866
1867 /* Hash function for a equiv_class_label_t */
1868
1869 static hashval_t
1870 equiv_class_label_hash (const void *p)
1871 {
1872   const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
1873   return ecl->hashcode;
1874 }
1875
1876 /* Equality function for two equiv_class_label_t's.  */
1877
1878 static int
1879 equiv_class_label_eq (const void *p1, const void *p2)
1880 {
1881   const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
1882   const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
1883   return bitmap_equal_p (eql1->labels, eql2->labels);
1884 }
1885
1886 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
1887    contains.  */
1888
1889 static unsigned int
1890 equiv_class_lookup (htab_t table, bitmap labels)
1891 {
1892   void **slot;
1893   struct equiv_class_label ecl;
1894
1895   ecl.labels = labels;
1896   ecl.hashcode = bitmap_hash (labels);
1897
1898   slot = htab_find_slot_with_hash (table, &ecl,
1899                                    ecl.hashcode, NO_INSERT);
1900   if (!slot)
1901     return 0;
1902   else
1903     return ((equiv_class_label_t) *slot)->equivalence_class;
1904 }
1905
1906
1907 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
1908    to TABLE.  */
1909
1910 static void
1911 equiv_class_add (htab_t table, unsigned int equivalence_class,
1912                  bitmap labels)
1913 {
1914   void **slot;
1915   equiv_class_label_t ecl = XNEW (struct equiv_class_label);
1916
1917   ecl->labels = labels;
1918   ecl->equivalence_class = equivalence_class;
1919   ecl->hashcode = bitmap_hash (labels);
1920
1921   slot = htab_find_slot_with_hash (table, ecl,
1922                                    ecl->hashcode, INSERT);
1923   gcc_assert (!*slot);
1924   *slot = (void *) ecl;
1925 }
1926
1927 /* Perform offline variable substitution.
1928
1929    This is a worst case quadratic time way of identifying variables
1930    that must have equivalent points-to sets, including those caused by
1931    static cycles, and single entry subgraphs, in the constraint graph.
1932
1933    The technique is described in "Exploiting Pointer and Location
1934    Equivalence to Optimize Pointer Analysis. In the 14th International
1935    Static Analysis Symposium (SAS), August 2007."  It is known as the
1936    "HU" algorithm, and is equivalent to value numbering the collapsed
1937    constraint graph including evaluating unions.
1938
1939    The general method of finding equivalence classes is as follows:
1940    Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1941    Initialize all non-REF nodes to be direct nodes.
1942    For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1943    variable}
1944    For each constraint containing the dereference, we also do the same
1945    thing.
1946
1947    We then compute SCC's in the graph and unify nodes in the same SCC,
1948    including pts sets.
1949
1950    For each non-collapsed node x:
1951     Visit all unvisited explicit incoming edges.
1952     Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1953     where y->x.
1954     Lookup the equivalence class for pts(x).
1955      If we found one, equivalence_class(x) = found class.
1956      Otherwise, equivalence_class(x) = new class, and new_class is
1957     added to the lookup table.
1958
1959    All direct nodes with the same equivalence class can be replaced
1960    with a single representative node.
1961    All unlabeled nodes (label == 0) are not pointers and all edges
1962    involving them can be eliminated.
1963    We perform these optimizations during rewrite_constraints
1964
1965    In addition to pointer equivalence class finding, we also perform
1966    location equivalence class finding.  This is the set of variables
1967    that always appear together in points-to sets.  We use this to
1968    compress the size of the points-to sets.  */
1969
1970 /* Current maximum pointer equivalence class id.  */
1971 static int pointer_equiv_class;
1972
1973 /* Current maximum location equivalence class id.  */
1974 static int location_equiv_class;
1975
1976 /* Recursive routine to find strongly connected components in GRAPH,
1977    and label it's nodes with DFS numbers.  */
1978
1979 static void
1980 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1981 {
1982   unsigned int i;
1983   bitmap_iterator bi;
1984   unsigned int my_dfs;
1985
1986   gcc_assert (si->node_mapping[n] == n);
1987   SET_BIT (si->visited, n);
1988   si->dfs[n] = si->current_index ++;
1989   my_dfs = si->dfs[n];
1990
1991   /* Visit all the successors.  */
1992   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1993     {
1994       unsigned int w = si->node_mapping[i];
1995
1996       if (TEST_BIT (si->deleted, w))
1997         continue;
1998
1999       if (!TEST_BIT (si->visited, w))
2000         condense_visit (graph, si, w);
2001       {
2002         unsigned int t = si->node_mapping[w];
2003         unsigned int nnode = si->node_mapping[n];
2004         gcc_assert (nnode == n);
2005
2006         if (si->dfs[t] < si->dfs[nnode])
2007           si->dfs[n] = si->dfs[t];
2008       }
2009     }
2010
2011   /* Visit all the implicit predecessors.  */
2012   EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2013     {
2014       unsigned int w = si->node_mapping[i];
2015
2016       if (TEST_BIT (si->deleted, w))
2017         continue;
2018
2019       if (!TEST_BIT (si->visited, w))
2020         condense_visit (graph, si, w);
2021       {
2022         unsigned int t = si->node_mapping[w];
2023         unsigned int nnode = si->node_mapping[n];
2024         gcc_assert (nnode == n);
2025
2026         if (si->dfs[t] < si->dfs[nnode])
2027           si->dfs[n] = si->dfs[t];
2028       }
2029     }
2030
2031   /* See if any components have been identified.  */
2032   if (si->dfs[n] == my_dfs)
2033     {
2034       while (VEC_length (unsigned, si->scc_stack) != 0
2035              && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2036         {
2037           unsigned int w = VEC_pop (unsigned, si->scc_stack);
2038           si->node_mapping[w] = n;
2039
2040           if (!TEST_BIT (graph->direct_nodes, w))
2041             RESET_BIT (graph->direct_nodes, n);
2042
2043           /* Unify our nodes.  */
2044           if (graph->preds[w])
2045             {
2046               if (!graph->preds[n])
2047                 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2048               bitmap_ior_into (graph->preds[n], graph->preds[w]);
2049             }
2050           if (graph->implicit_preds[w])
2051             {
2052               if (!graph->implicit_preds[n])
2053                 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2054               bitmap_ior_into (graph->implicit_preds[n],
2055                                graph->implicit_preds[w]);
2056             }
2057           if (graph->points_to[w])
2058             {
2059               if (!graph->points_to[n])
2060                 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2061               bitmap_ior_into (graph->points_to[n],
2062                                graph->points_to[w]);
2063             }
2064         }
2065       SET_BIT (si->deleted, n);
2066     }
2067   else
2068     VEC_safe_push (unsigned, heap, si->scc_stack, n);
2069 }
2070
2071 /* Label pointer equivalences.  */
2072
2073 static void
2074 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2075 {
2076   unsigned int i;
2077   bitmap_iterator bi;
2078   SET_BIT (si->visited, n);
2079
2080   if (!graph->points_to[n])
2081     graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2082
2083   /* Label and union our incoming edges's points to sets.  */
2084   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2085     {
2086       unsigned int w = si->node_mapping[i];
2087       if (!TEST_BIT (si->visited, w))
2088         label_visit (graph, si, w);
2089
2090       /* Skip unused edges  */
2091       if (w == n || graph->pointer_label[w] == 0)
2092         continue;
2093
2094       if (graph->points_to[w])
2095         bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2096     }
2097   /* Indirect nodes get fresh variables.  */
2098   if (!TEST_BIT (graph->direct_nodes, n))
2099     bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2100
2101   if (!bitmap_empty_p (graph->points_to[n]))
2102     {
2103       unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2104                                                graph->points_to[n]);
2105       if (!label)
2106         {
2107           label = pointer_equiv_class++;
2108           equiv_class_add (pointer_equiv_class_table,
2109                            label, graph->points_to[n]);
2110         }
2111       graph->pointer_label[n] = label;
2112     }
2113 }
2114
2115 /* Perform offline variable substitution, discovering equivalence
2116    classes, and eliminating non-pointer variables.  */
2117
2118 static struct scc_info *
2119 perform_var_substitution (constraint_graph_t graph)
2120 {
2121   unsigned int i;
2122   unsigned int size = graph->size;
2123   struct scc_info *si = init_scc_info (size);
2124
2125   bitmap_obstack_initialize (&iteration_obstack);
2126   pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2127                                            equiv_class_label_eq, free);
2128   location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2129                                             equiv_class_label_eq, free);
2130   pointer_equiv_class = 1;
2131   location_equiv_class = 1;
2132
2133   /* Condense the nodes, which means to find SCC's, count incoming
2134      predecessors, and unite nodes in SCC's.  */
2135   for (i = 0; i < FIRST_REF_NODE; i++)
2136     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2137       condense_visit (graph, si, si->node_mapping[i]);
2138
2139   sbitmap_zero (si->visited);
2140   /* Actually the label the nodes for pointer equivalences  */
2141   for (i = 0; i < FIRST_REF_NODE; i++)
2142     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2143       label_visit (graph, si, si->node_mapping[i]);
2144
2145   /* Calculate location equivalence labels.  */
2146   for (i = 0; i < FIRST_REF_NODE; i++)
2147     {
2148       bitmap pointed_by;
2149       bitmap_iterator bi;
2150       unsigned int j;
2151       unsigned int label;
2152
2153       if (!graph->pointed_by[i])
2154         continue;
2155       pointed_by = BITMAP_ALLOC (&iteration_obstack);
2156
2157       /* Translate the pointed-by mapping for pointer equivalence
2158          labels.  */
2159       EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2160         {
2161           bitmap_set_bit (pointed_by,
2162                           graph->pointer_label[si->node_mapping[j]]);
2163         }
2164       /* The original pointed_by is now dead.  */
2165       BITMAP_FREE (graph->pointed_by[i]);
2166
2167       /* Look up the location equivalence label if one exists, or make
2168          one otherwise.  */
2169       label = equiv_class_lookup (location_equiv_class_table,
2170                                   pointed_by);
2171       if (label == 0)
2172         {
2173           label = location_equiv_class++;
2174           equiv_class_add (location_equiv_class_table,
2175                            label, pointed_by);
2176         }
2177       else
2178         {
2179           if (dump_file && (dump_flags & TDF_DETAILS))
2180             fprintf (dump_file, "Found location equivalence for node %s\n",
2181                      get_varinfo (i)->name);
2182           BITMAP_FREE (pointed_by);
2183         }
2184       graph->loc_label[i] = label;
2185
2186     }
2187
2188   if (dump_file && (dump_flags & TDF_DETAILS))
2189     for (i = 0; i < FIRST_REF_NODE; i++)
2190       {
2191         bool direct_node = TEST_BIT (graph->direct_nodes, i);
2192         fprintf (dump_file,
2193                  "Equivalence classes for %s node id %d:%s are pointer: %d"
2194                  ", location:%d\n",
2195                  direct_node ? "Direct node" : "Indirect node", i,
2196                  get_varinfo (i)->name,
2197                  graph->pointer_label[si->node_mapping[i]],
2198                  graph->loc_label[si->node_mapping[i]]);
2199       }
2200
2201   /* Quickly eliminate our non-pointer variables.  */
2202
2203   for (i = 0; i < FIRST_REF_NODE; i++)
2204     {
2205       unsigned int node = si->node_mapping[i];
2206
2207       if (graph->pointer_label[node] == 0)
2208         {
2209           if (dump_file && (dump_flags & TDF_DETAILS))
2210             fprintf (dump_file,
2211                      "%s is a non-pointer variable, eliminating edges.\n",
2212                      get_varinfo (node)->name);
2213           stats.nonpointer_vars++;
2214           clear_edges_for_node (graph, node);
2215         }
2216     }
2217
2218   return si;
2219 }
2220
2221 /* Free information that was only necessary for variable
2222    substitution.  */
2223
2224 static void
2225 free_var_substitution_info (struct scc_info *si)
2226 {
2227   free_scc_info (si);
2228   free (graph->pointer_label);
2229   free (graph->loc_label);
2230   free (graph->pointed_by);
2231   free (graph->points_to);
2232   free (graph->eq_rep);
2233   sbitmap_free (graph->direct_nodes);
2234   htab_delete (pointer_equiv_class_table);
2235   htab_delete (location_equiv_class_table);
2236   bitmap_obstack_release (&iteration_obstack);
2237 }
2238
2239 /* Return an existing node that is equivalent to NODE, which has
2240    equivalence class LABEL, if one exists.  Return NODE otherwise.  */
2241
2242 static unsigned int
2243 find_equivalent_node (constraint_graph_t graph,
2244                       unsigned int node, unsigned int label)
2245 {
2246   /* If the address version of this variable is unused, we can
2247      substitute it for anything else with the same label.
2248      Otherwise, we know the pointers are equivalent, but not the
2249      locations, and we can unite them later.  */
2250
2251   if (!bitmap_bit_p (graph->address_taken, node))
2252     {
2253       gcc_assert (label < graph->size);
2254
2255       if (graph->eq_rep[label] != -1)
2256         {
2257           /* Unify the two variables since we know they are equivalent.  */
2258           if (unite (graph->eq_rep[label], node))
2259             unify_nodes (graph, graph->eq_rep[label], node, false);
2260           return graph->eq_rep[label];
2261         }
2262       else
2263         {
2264           graph->eq_rep[label] = node;
2265           graph->pe_rep[label] = node;
2266         }
2267     }
2268   else
2269     {
2270       gcc_assert (label < graph->size);
2271       graph->pe[node] = label;
2272       if (graph->pe_rep[label] == -1)
2273         graph->pe_rep[label] = node;
2274     }
2275
2276   return node;
2277 }
2278
2279 /* Unite pointer equivalent but not location equivalent nodes in
2280    GRAPH.  This may only be performed once variable substitution is
2281    finished.  */
2282
2283 static void
2284 unite_pointer_equivalences (constraint_graph_t graph)
2285 {
2286   unsigned int i;
2287
2288   /* Go through the pointer equivalences and unite them to their
2289      representative, if they aren't already.  */
2290   for (i = 0; i < FIRST_REF_NODE; i++)
2291     {
2292       unsigned int label = graph->pe[i];
2293       if (label)
2294         {
2295           int label_rep = graph->pe_rep[label];
2296           
2297           if (label_rep == -1)
2298             continue;
2299           
2300           label_rep = find (label_rep);
2301           if (label_rep >= 0 && unite (label_rep, find (i)))
2302             unify_nodes (graph, label_rep, i, false);
2303         }
2304     }
2305 }
2306
2307 /* Move complex constraints to the GRAPH nodes they belong to.  */
2308
2309 static void
2310 move_complex_constraints (constraint_graph_t graph)
2311 {
2312   int i;
2313   constraint_t c;
2314
2315   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2316     {
2317       if (c)
2318         {
2319           struct constraint_expr lhs = c->lhs;
2320           struct constraint_expr rhs = c->rhs;
2321
2322           if (lhs.type == DEREF)
2323             {
2324               insert_into_complex (graph, lhs.var, c);
2325             }
2326           else if (rhs.type == DEREF)
2327             {
2328               if (!(get_varinfo (lhs.var)->is_special_var))
2329                 insert_into_complex (graph, rhs.var, c);
2330             }
2331           else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2332                    && (lhs.offset != 0 || rhs.offset != 0))
2333             {
2334               insert_into_complex (graph, rhs.var, c);
2335             }
2336         }
2337     }
2338 }
2339
2340
2341 /* Optimize and rewrite complex constraints while performing
2342    collapsing of equivalent nodes.  SI is the SCC_INFO that is the
2343    result of perform_variable_substitution.  */
2344
2345 static void
2346 rewrite_constraints (constraint_graph_t graph,
2347                      struct scc_info *si)
2348 {
2349   int i;
2350   unsigned int j;
2351   constraint_t c;
2352
2353   for (j = 0; j < graph->size; j++)
2354     gcc_assert (find (j) == j);
2355
2356   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2357     {
2358       struct constraint_expr lhs = c->lhs;
2359       struct constraint_expr rhs = c->rhs;
2360       unsigned int lhsvar = find (lhs.var);
2361       unsigned int rhsvar = find (rhs.var);
2362       unsigned int lhsnode, rhsnode;
2363       unsigned int lhslabel, rhslabel;
2364
2365       lhsnode = si->node_mapping[lhsvar];
2366       rhsnode = si->node_mapping[rhsvar];
2367       lhslabel = graph->pointer_label[lhsnode];
2368       rhslabel = graph->pointer_label[rhsnode];
2369
2370       /* See if it is really a non-pointer variable, and if so, ignore
2371          the constraint.  */
2372       if (lhslabel == 0)
2373         {
2374           if (dump_file && (dump_flags & TDF_DETAILS))
2375             {
2376               
2377               fprintf (dump_file, "%s is a non-pointer variable,"
2378                        "ignoring constraint:",
2379                        get_varinfo (lhs.var)->name);
2380               dump_constraint (dump_file, c);
2381             }
2382           VEC_replace (constraint_t, constraints, i, NULL);
2383           continue;
2384         }
2385
2386       if (rhslabel == 0)
2387         {
2388           if (dump_file && (dump_flags & TDF_DETAILS))
2389             {
2390               
2391               fprintf (dump_file, "%s is a non-pointer variable,"
2392                        "ignoring constraint:",
2393                        get_varinfo (rhs.var)->name);
2394               dump_constraint (dump_file, c);
2395             }
2396           VEC_replace (constraint_t, constraints, i, NULL);
2397           continue;
2398         }
2399
2400       lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2401       rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2402       c->lhs.var = lhsvar;
2403       c->rhs.var = rhsvar;
2404
2405     }
2406 }
2407
2408 /* Eliminate indirect cycles involving NODE.  Return true if NODE was
2409    part of an SCC, false otherwise.  */
2410
2411 static bool
2412 eliminate_indirect_cycles (unsigned int node)
2413 {
2414   if (graph->indirect_cycles[node] != -1
2415       && !bitmap_empty_p (get_varinfo (node)->solution))
2416     {
2417       unsigned int i;
2418       VEC(unsigned,heap) *queue = NULL;
2419       int queuepos;
2420       unsigned int to = find (graph->indirect_cycles[node]);
2421       bitmap_iterator bi;
2422
2423       /* We can't touch the solution set and call unify_nodes
2424          at the same time, because unify_nodes is going to do
2425          bitmap unions into it. */
2426
2427       EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2428         {
2429           if (find (i) == i && i != to)
2430             {
2431               if (unite (to, i))
2432                 VEC_safe_push (unsigned, heap, queue, i);
2433             }
2434         }
2435
2436       for (queuepos = 0;
2437            VEC_iterate (unsigned, queue, queuepos, i);
2438            queuepos++)
2439         {
2440           unify_nodes (graph, to, i, true);
2441         }
2442       VEC_free (unsigned, heap, queue);
2443       return true;
2444     }
2445   return false;
2446 }
2447
2448 /* Solve the constraint graph GRAPH using our worklist solver.
2449    This is based on the PW* family of solvers from the "Efficient Field
2450    Sensitive Pointer Analysis for C" paper.
2451    It works by iterating over all the graph nodes, processing the complex
2452    constraints and propagating the copy constraints, until everything stops
2453    changed.  This corresponds to steps 6-8 in the solving list given above.  */
2454
2455 static void
2456 solve_graph (constraint_graph_t graph)
2457 {
2458   unsigned int size = graph->size;
2459   unsigned int i;
2460   bitmap pts;
2461
2462   changed_count = 0;
2463   changed = sbitmap_alloc (size);
2464   sbitmap_zero (changed);
2465
2466   /* Mark all initial non-collapsed nodes as changed.  */
2467   for (i = 0; i < size; i++)
2468     {
2469       varinfo_t ivi = get_varinfo (i);
2470       if (find (i) == i && !bitmap_empty_p (ivi->solution)
2471           && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2472               || VEC_length (constraint_t, graph->complex[i]) > 0))
2473         {
2474           SET_BIT (changed, i);
2475           changed_count++;
2476         }
2477     }
2478
2479   /* Allocate a bitmap to be used to store the changed bits.  */
2480   pts = BITMAP_ALLOC (&pta_obstack);
2481
2482   while (changed_count > 0)
2483     {
2484       unsigned int i;
2485       struct topo_info *ti = init_topo_info ();
2486       stats.iterations++;
2487
2488       bitmap_obstack_initialize (&iteration_obstack);
2489
2490       compute_topo_order (graph, ti);
2491
2492       while (VEC_length (unsigned, ti->topo_order) != 0)
2493         {
2494
2495           i = VEC_pop (unsigned, ti->topo_order);
2496
2497           /* If this variable is not a representative, skip it.  */
2498           if (find (i) != i)
2499             continue;
2500
2501           /* In certain indirect cycle cases, we may merge this
2502              variable to another.  */
2503           if (eliminate_indirect_cycles (i) && find (i) != i)
2504             continue;
2505
2506           /* If the node has changed, we need to process the
2507              complex constraints and outgoing edges again.  */
2508           if (TEST_BIT (changed, i))
2509             {
2510               unsigned int j;
2511               constraint_t c;
2512               bitmap solution;
2513               VEC(constraint_t,heap) *complex = graph->complex[i];
2514               bool solution_empty;
2515
2516               RESET_BIT (changed, i);
2517               changed_count--;
2518
2519               /* Compute the changed set of solution bits.  */
2520               bitmap_and_compl (pts, get_varinfo (i)->solution,
2521                                 get_varinfo (i)->oldsolution);
2522
2523               if (bitmap_empty_p (pts))
2524                 continue;
2525
2526               bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2527
2528               solution = get_varinfo (i)->solution;
2529               solution_empty = bitmap_empty_p (solution);
2530
2531               /* Process the complex constraints */
2532               for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2533                 {
2534                   /* XXX: This is going to unsort the constraints in
2535                      some cases, which will occasionally add duplicate
2536                      constraints during unification.  This does not
2537                      affect correctness.  */
2538                   c->lhs.var = find (c->lhs.var);
2539                   c->rhs.var = find (c->rhs.var);
2540
2541                   /* The only complex constraint that can change our
2542                      solution to non-empty, given an empty solution,
2543                      is a constraint where the lhs side is receiving
2544                      some set from elsewhere.  */
2545                   if (!solution_empty || c->lhs.type != DEREF)
2546                     do_complex_constraint (graph, c, pts);
2547                 }
2548
2549               solution_empty = bitmap_empty_p (solution);
2550
2551               if (!solution_empty)
2552                 {
2553                   bitmap_iterator bi;
2554                   unsigned eff_escaped_id = find (escaped_id);
2555
2556                   /* Propagate solution to all successors.  */
2557                   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2558                                                 0, j, bi)
2559                     {
2560                       bitmap tmp;
2561                       bool flag;
2562
2563                       unsigned int to = find (j);
2564                       tmp = get_varinfo (to)->solution;
2565                       flag = false;
2566
2567                       /* Don't try to propagate to ourselves.  */
2568                       if (to == i)
2569                         continue;
2570
2571                       /* If we propagate from ESCAPED use ESCAPED as
2572                          placeholder.  */
2573                       if (i == eff_escaped_id)
2574                         flag = bitmap_set_bit (tmp, escaped_id);
2575                       else
2576                         flag = set_union_with_increment (tmp, pts, 0);
2577
2578                       if (flag)
2579                         {
2580                           get_varinfo (to)->solution = tmp;
2581                           if (!TEST_BIT (changed, to))
2582                             {
2583                               SET_BIT (changed, to);
2584                               changed_count++;
2585                             }
2586                         }
2587                     }
2588                 }
2589             }
2590         }
2591       free_topo_info (ti);
2592       bitmap_obstack_release (&iteration_obstack);
2593     }
2594
2595   BITMAP_FREE (pts);
2596   sbitmap_free (changed);
2597   bitmap_obstack_release (&oldpta_obstack);
2598 }
2599
2600 /* Map from trees to variable infos.  */
2601 static struct pointer_map_t *vi_for_tree;
2602
2603
2604 /* Insert ID as the variable id for tree T in the vi_for_tree map.  */
2605
2606 static void
2607 insert_vi_for_tree (tree t, varinfo_t vi)
2608 {
2609   void **slot = pointer_map_insert (vi_for_tree, t);
2610   gcc_assert (vi);
2611   gcc_assert (*slot == NULL);
2612   *slot = vi;
2613 }
2614
2615 /* Find the variable info for tree T in VI_FOR_TREE.  If T does not
2616    exist in the map, return NULL, otherwise, return the varinfo we found.  */
2617
2618 static varinfo_t
2619 lookup_vi_for_tree (tree t)
2620 {
2621   void **slot = pointer_map_contains (vi_for_tree, t);
2622   if (slot == NULL)
2623     return NULL;
2624
2625   return (varinfo_t) *slot;
2626 }
2627
2628 /* Return a printable name for DECL  */
2629
2630 static const char *
2631 alias_get_name (tree decl)
2632 {
2633   const char *res = get_name (decl);
2634   char *temp;
2635   int num_printed = 0;
2636
2637   if (res != NULL)
2638     return res;
2639
2640   res = "NULL";
2641   if (!dump_file)
2642     return res;
2643
2644   if (TREE_CODE (decl) == SSA_NAME)
2645     {
2646       num_printed = asprintf (&temp, "%s_%u",
2647                               alias_get_name (SSA_NAME_VAR (decl)),
2648                               SSA_NAME_VERSION (decl));
2649     }
2650   else if (DECL_P (decl))
2651     {
2652       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2653     }
2654   if (num_printed > 0)
2655     {
2656       res = ggc_strdup (temp);
2657       free (temp);
2658     }
2659   return res;
2660 }
2661
2662 /* Find the variable id for tree T in the map.
2663    If T doesn't exist in the map, create an entry for it and return it.  */
2664
2665 static varinfo_t
2666 get_vi_for_tree (tree t)
2667 {
2668   void **slot = pointer_map_contains (vi_for_tree, t);
2669   if (slot == NULL)
2670     return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2671
2672   return (varinfo_t) *slot;
2673 }
2674
2675 /* Get a constraint expression for a new temporary variable.  */
2676
2677 static struct constraint_expr
2678 get_constraint_exp_for_temp (tree t)
2679 {
2680   struct constraint_expr cexpr;
2681
2682   gcc_assert (SSA_VAR_P (t));
2683
2684   cexpr.type = SCALAR;
2685   cexpr.var = get_vi_for_tree (t)->id;
2686   cexpr.offset = 0;
2687
2688   return cexpr;
2689 }
2690
2691 /* Get a constraint expression vector from an SSA_VAR_P node.
2692    If address_p is true, the result will be taken its address of.  */
2693
2694 static void
2695 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2696 {
2697   struct constraint_expr cexpr;
2698   varinfo_t vi;
2699
2700   /* We allow FUNCTION_DECLs here even though it doesn't make much sense.  */
2701   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2702
2703   /* For parameters, get at the points-to set for the actual parm
2704      decl.  */
2705   if (TREE_CODE (t) == SSA_NAME
2706       && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2707       && SSA_NAME_IS_DEFAULT_DEF (t))
2708     {
2709       get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2710       return;
2711     }
2712
2713   vi = get_vi_for_tree (t);
2714   cexpr.var = vi->id;
2715   cexpr.type = SCALAR;
2716   cexpr.offset = 0;
2717   /* If we determine the result is "anything", and we know this is readonly,
2718      say it points to readonly memory instead.  */
2719   if (cexpr.var == anything_id && TREE_READONLY (t))
2720     {
2721       gcc_unreachable ();
2722       cexpr.type = ADDRESSOF;
2723       cexpr.var = readonly_id;
2724     }
2725
2726   /* If we are not taking the address of the constraint expr, add all
2727      sub-fiels of the variable as well.  */
2728   if (!address_p)
2729     {
2730       for (; vi; vi = vi->next)
2731         {
2732           cexpr.var = vi->id;
2733           VEC_safe_push (ce_s, heap, *results, &cexpr);
2734         }
2735       return;
2736     }
2737
2738   VEC_safe_push (ce_s, heap, *results, &cexpr);
2739 }
2740
2741 /* Process constraint T, performing various simplifications and then
2742    adding it to our list of overall constraints.  */
2743
2744 static void
2745 process_constraint (constraint_t t)
2746 {
2747   struct constraint_expr rhs = t->rhs;
2748   struct constraint_expr lhs = t->lhs;
2749
2750   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2751   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2752
2753   /* If we didn't get any useful constraint from the lhs we get
2754      &ANYTHING as fallback from get_constraint_for.  Deal with
2755      it here by turning it into *ANYTHING.  */
2756   if (lhs.type == ADDRESSOF
2757       && lhs.var == anything_id)
2758     lhs.type = DEREF;
2759
2760   /* ADDRESSOF on the lhs is invalid.  */
2761   gcc_assert (lhs.type != ADDRESSOF);
2762
2763   /* This can happen in our IR with things like n->a = *p */
2764   if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2765     {
2766       /* Split into tmp = *rhs, *lhs = tmp */
2767       tree rhsdecl = get_varinfo (rhs.var)->decl;
2768       tree pointertype = TREE_TYPE (rhsdecl);
2769       tree pointedtotype = TREE_TYPE (pointertype);
2770       tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
2771       struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2772
2773       process_constraint (new_constraint (tmplhs, rhs));
2774       process_constraint (new_constraint (lhs, tmplhs));
2775     }
2776   else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2777     {
2778       /* Split into tmp = &rhs, *lhs = tmp */
2779       tree rhsdecl = get_varinfo (rhs.var)->decl;
2780       tree pointertype = TREE_TYPE (rhsdecl);
2781       tree tmpvar = create_tmp_var_raw (pointertype, "derefaddrtmp");
2782       struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2783
2784       process_constraint (new_constraint (tmplhs, rhs));
2785       process_constraint (new_constraint (lhs, tmplhs));
2786     }
2787   else
2788     {
2789       gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2790       VEC_safe_push (constraint_t, heap, constraints, t);
2791     }
2792 }
2793
2794 /* Return true if T is a type that could contain pointers.  */
2795
2796 static bool
2797 type_could_have_pointers (tree type)
2798 {
2799   if (POINTER_TYPE_P (type))
2800     return true;
2801
2802   if (TREE_CODE (type) == ARRAY_TYPE)
2803     return type_could_have_pointers (TREE_TYPE (type));
2804
2805   return AGGREGATE_TYPE_P (type);
2806 }
2807
2808 /* Return true if T is a variable of a type that could contain
2809    pointers.  */
2810
2811 static bool
2812 could_have_pointers (tree t)
2813 {
2814   return type_could_have_pointers (TREE_TYPE (t));
2815 }
2816
2817 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2818    structure.  */
2819
2820 static HOST_WIDE_INT
2821 bitpos_of_field (const tree fdecl)
2822 {
2823
2824   if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2825       || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2826     return -1;
2827
2828   return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * 8
2829           + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2830 }
2831
2832
2833 /* Get constraint expressions for offsetting PTR by OFFSET.  Stores the
2834    resulting constraint expressions in *RESULTS.  */
2835
2836 static void
2837 get_constraint_for_ptr_offset (tree ptr, tree offset,
2838                                VEC (ce_s, heap) **results)
2839 {
2840   struct constraint_expr *c;
2841   unsigned int j, n;
2842   HOST_WIDE_INT rhsunitoffset, rhsoffset;
2843
2844   /* If we do not do field-sensitive PTA adding offsets to pointers
2845      does not change the points-to solution.  */
2846   if (!use_field_sensitive)
2847     {
2848       get_constraint_for (ptr, results);
2849       return;
2850     }
2851
2852   /* If the offset is not a non-negative integer constant that fits
2853      in a HOST_WIDE_INT, we have to fall back to a conservative
2854      solution which includes all sub-fields of all pointed-to
2855      variables of ptr.  */
2856   if (!host_integerp (offset, 0))
2857     rhsoffset = UNKNOWN_OFFSET;
2858   else
2859     {
2860       /* Make sure the bit-offset also fits.  */
2861       rhsunitoffset = TREE_INT_CST_LOW (offset);
2862       rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2863       if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2864         rhsoffset = UNKNOWN_OFFSET;
2865     }
2866
2867   get_constraint_for (ptr, results);
2868   if (rhsoffset == 0)
2869     return;
2870
2871   /* As we are eventually appending to the solution do not use
2872      VEC_iterate here.  */
2873   n = VEC_length (ce_s, *results);
2874   for (j = 0; j < n; j++)
2875     {
2876       varinfo_t curr;
2877       c = VEC_index (ce_s, *results, j);
2878       curr = get_varinfo (c->var);
2879
2880       if (c->type == ADDRESSOF
2881           /* If this varinfo represents a full variable just use it.  */
2882           && curr->is_full_var)
2883         c->offset = 0;
2884       else if (c->type == ADDRESSOF
2885                /* If we do not know the offset add all subfields.  */
2886                && rhsoffset == UNKNOWN_OFFSET)
2887         {
2888           varinfo_t temp = lookup_vi_for_tree (curr->decl);
2889           do
2890             {
2891               struct constraint_expr c2;
2892               c2.var = temp->id;
2893               c2.type = ADDRESSOF;
2894               c2.offset = 0;
2895               VEC_safe_push (ce_s, heap, *results, &c2);
2896               temp = temp->next;
2897             }
2898           while (temp);
2899         }
2900       else if (c->type == ADDRESSOF)
2901         {
2902           varinfo_t temp;
2903           unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
2904
2905           /* Search the sub-field which overlaps with the
2906              pointed-to offset.  If the result is outside of the variable
2907              we have to provide a conservative result, as the variable is
2908              still reachable from the resulting pointer (even though it
2909              technically cannot point to anything).  The last and first
2910              sub-fields are such conservative results.
2911              ???  If we always had a sub-field for &object + 1 then
2912              we could represent this in a more precise way.  */
2913           if (rhsoffset < 0
2914               && curr->offset < offset)
2915             offset = 0;
2916           temp = first_or_preceding_vi_for_offset (curr, offset);
2917
2918           /* If the found variable is not exactly at the pointed to
2919              result, we have to include the next variable in the
2920              solution as well.  Otherwise two increments by offset / 2
2921              do not result in the same or a conservative superset
2922              solution.  */
2923           if (temp->offset != offset
2924               && temp->next != NULL)
2925             {
2926               struct constraint_expr c2;
2927               c2.var = temp->next->id;
2928               c2.type = ADDRESSOF;
2929               c2.offset = 0;
2930               VEC_safe_push (ce_s, heap, *results, &c2);
2931             }
2932           c->var = temp->id;
2933           c->offset = 0;
2934         }
2935       else
2936         c->offset = rhsoffset;
2937     }
2938 }
2939
2940
2941 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
2942    If address_p is true the result will be taken its address of.  */
2943
2944 static void
2945 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
2946                                   bool address_p)
2947 {
2948   tree orig_t = t;
2949   HOST_WIDE_INT bitsize = -1;
2950   HOST_WIDE_INT bitmaxsize = -1;
2951   HOST_WIDE_INT bitpos;
2952   tree forzero;
2953   struct constraint_expr *result;
2954
2955   /* Some people like to do cute things like take the address of
2956      &0->a.b */
2957   forzero = t;
2958   while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2959     forzero = TREE_OPERAND (forzero, 0);
2960
2961   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2962     {
2963       struct constraint_expr temp;
2964
2965       temp.offset = 0;
2966       temp.var = integer_id;
2967       temp.type = SCALAR;
2968       VEC_safe_push (ce_s, heap, *results, &temp);
2969       return;
2970     }
2971
2972   t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2973
2974   /* Pretend to take the address of the base, we'll take care of
2975      adding the required subset of sub-fields below.  */
2976   get_constraint_for_1 (t, results, true);
2977   gcc_assert (VEC_length (ce_s, *results) == 1);
2978   result = VEC_last (ce_s, *results);
2979
2980   if (result->type == SCALAR
2981       && get_varinfo (result->var)->is_full_var)
2982     /* For single-field vars do not bother about the offset.  */
2983     result->offset = 0;
2984   else if (result->type == SCALAR)
2985     {
2986       /* In languages like C, you can access one past the end of an
2987          array.  You aren't allowed to dereference it, so we can
2988          ignore this constraint. When we handle pointer subtraction,
2989          we may have to do something cute here.  */
2990
2991       if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
2992           && bitmaxsize != 0)
2993         {
2994           /* It's also not true that the constraint will actually start at the
2995              right offset, it may start in some padding.  We only care about
2996              setting the constraint to the first actual field it touches, so
2997              walk to find it.  */
2998           struct constraint_expr cexpr = *result;
2999           varinfo_t curr;
3000           VEC_pop (ce_s, *results);
3001           cexpr.offset = 0;
3002           for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
3003             {
3004               if (ranges_overlap_p (curr->offset, curr->size,
3005                                     bitpos, bitmaxsize))
3006                 {
3007                   cexpr.var = curr->id;
3008                   VEC_safe_push (ce_s, heap, *results, &cexpr);
3009                   if (address_p)
3010                     break;
3011                 }
3012             }
3013           /* If we are going to take the address of this field then
3014              to be able to compute reachability correctly add at least
3015              the last field of the variable.  */
3016           if (address_p
3017               && VEC_length (ce_s, *results) == 0)
3018             {
3019               curr = get_varinfo (cexpr.var);
3020               while (curr->next != NULL)
3021                 curr = curr->next;
3022               cexpr.var = curr->id;
3023               VEC_safe_push (ce_s, heap, *results, &cexpr);
3024             }
3025           else
3026             /* Assert that we found *some* field there. The user couldn't be
3027                accessing *only* padding.  */
3028             /* Still the user could access one past the end of an array
3029                embedded in a struct resulting in accessing *only* padding.  */
3030             gcc_assert (VEC_length (ce_s, *results) >= 1
3031                         || ref_contains_array_ref (orig_t));
3032         }
3033       else if (bitmaxsize == 0)
3034         {
3035           if (dump_file && (dump_flags & TDF_DETAILS))
3036             fprintf (dump_file, "Access to zero-sized part of variable,"
3037                      "ignoring\n");
3038         }
3039       else
3040         if (dump_file && (dump_flags & TDF_DETAILS))
3041           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3042     }
3043   else if (result->type == DEREF)
3044     {
3045       /* If we do not know exactly where the access goes say so.  Note
3046          that only for non-structure accesses we know that we access
3047          at most one subfiled of any variable.  */
3048       if (bitpos == -1
3049           || bitsize != bitmaxsize
3050           || AGGREGATE_TYPE_P (TREE_TYPE (orig_t)))
3051         result->offset = UNKNOWN_OFFSET;
3052       else
3053         result->offset = bitpos;
3054     }
3055   else
3056     gcc_unreachable ();
3057 }
3058
3059
3060 /* Dereference the constraint expression CONS, and return the result.
3061    DEREF (ADDRESSOF) = SCALAR
3062    DEREF (SCALAR) = DEREF
3063    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3064    This is needed so that we can handle dereferencing DEREF constraints.  */
3065
3066 static void
3067 do_deref (VEC (ce_s, heap) **constraints)
3068 {
3069   struct constraint_expr *c;
3070   unsigned int i = 0;
3071
3072   for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
3073     {
3074       if (c->type == SCALAR)
3075         c->type = DEREF;
3076       else if (c->type == ADDRESSOF)
3077         c->type = SCALAR;
3078       else if (c->type == DEREF)
3079         {
3080           tree tmpvar = create_tmp_var_raw (ptr_type_node, "dereftmp");
3081           struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
3082           process_constraint (new_constraint (tmplhs, *c));
3083           c->var = tmplhs.var;
3084         }
3085       else
3086         gcc_unreachable ();
3087     }
3088 }
3089
3090 /* Given a tree T, return the constraint expression for it.  */
3091
3092 static void
3093 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p)
3094 {
3095   struct constraint_expr temp;
3096
3097   /* x = integer is all glommed to a single variable, which doesn't
3098      point to anything by itself.  That is, of course, unless it is an
3099      integer constant being treated as a pointer, in which case, we
3100      will return that this is really the addressof anything.  This
3101      happens below, since it will fall into the default case. The only
3102      case we know something about an integer treated like a pointer is
3103      when it is the NULL pointer, and then we just say it points to
3104      NULL.
3105
3106      Do not do that if -fno-delete-null-pointer-checks though, because
3107      in that case *NULL does not fail, so it _should_ alias *anything.
3108      It is not worth adding a new option or renaming the existing one,
3109      since this case is relatively obscure.  */
3110   if (flag_delete_null_pointer_checks
3111       && ((TREE_CODE (t) == INTEGER_CST
3112            && integer_zerop (t))
3113           /* The only valid CONSTRUCTORs in gimple with pointer typed
3114              elements are zero-initializer.  */
3115           || TREE_CODE (t) == CONSTRUCTOR))
3116     {
3117       temp.var = nothing_id;
3118       temp.type = ADDRESSOF;
3119       temp.offset = 0;
3120       VEC_safe_push (ce_s, heap, *results, &temp);
3121       return;
3122     }
3123
3124   /* String constants are read-only.  */
3125   if (TREE_CODE (t) == STRING_CST)
3126     {
3127       temp.var = readonly_id;
3128       temp.type = SCALAR;
3129       temp.offset = 0;
3130       VEC_safe_push (ce_s, heap, *results, &temp);
3131       return;
3132     }
3133
3134   switch (TREE_CODE_CLASS (TREE_CODE (t)))
3135     {
3136     case tcc_expression:
3137       {
3138         switch (TREE_CODE (t))
3139           {
3140           case ADDR_EXPR:
3141             {
3142               struct constraint_expr *c;
3143               unsigned int i;
3144               tree exp = TREE_OPERAND (t, 0);
3145
3146               get_constraint_for_1 (exp, results, true);
3147
3148               for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
3149                 {
3150                   if (c->type == DEREF)
3151                     c->type = SCALAR;
3152                   else
3153                     c->type = ADDRESSOF;
3154                 }
3155               return;
3156             }
3157             break;
3158           default:;
3159           }
3160         break;
3161       }
3162     case tcc_reference:
3163       {
3164         switch (TREE_CODE (t))
3165           {
3166           case INDIRECT_REF:
3167             {
3168               get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3169               do_deref (results);
3170               return;
3171             }
3172           case ARRAY_REF:
3173           case ARRAY_RANGE_REF:
3174           case COMPONENT_REF:
3175             get_constraint_for_component_ref (t, results, address_p);
3176             return;
3177           case VIEW_CONVERT_EXPR:
3178             get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3179             return;
3180           /* We are missing handling for TARGET_MEM_REF here.  */
3181           default:;
3182           }
3183         break;
3184       }
3185     case tcc_exceptional:
3186       {
3187         switch (TREE_CODE (t))
3188           {
3189           case SSA_NAME:
3190             {
3191               get_constraint_for_ssa_var (t, results, address_p);
3192               return;
3193             }
3194           default:;
3195           }
3196         break;
3197       }
3198     case tcc_declaration:
3199       {
3200         get_constraint_for_ssa_var (t, results, address_p);
3201         return;
3202       }
3203     default:;
3204     }
3205
3206   /* The default fallback is a constraint from anything.  */
3207   temp.type = ADDRESSOF;
3208   temp.var = anything_id;
3209   temp.offset = 0;
3210   VEC_safe_push (ce_s, heap, *results, &temp);
3211 }
3212
3213 /* Given a gimple tree T, return the constraint expression vector for it.  */
3214
3215 static void
3216 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3217 {
3218   gcc_assert (VEC_length (ce_s, *results) == 0);
3219
3220   get_constraint_for_1 (t, results, false);
3221 }
3222
3223 /* Handle aggregate copies by expanding into copies of the respective
3224    fields of the structures.  */
3225
3226 static void
3227 do_structure_copy (tree lhsop, tree rhsop)
3228 {
3229   struct constraint_expr *lhsp, *rhsp;
3230   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3231   unsigned j;
3232
3233   get_constraint_for (lhsop, &lhsc);
3234   get_constraint_for (rhsop, &rhsc);
3235   lhsp = VEC_index (ce_s, lhsc, 0);
3236   rhsp = VEC_index (ce_s, rhsc, 0);
3237   if (lhsp->type == DEREF
3238       || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3239       || rhsp->type == DEREF)
3240     {
3241       struct constraint_expr tmp;
3242       tree tmpvar = create_tmp_var_raw (ptr_type_node,
3243                                         "structcopydereftmp");
3244       tmp.var = get_vi_for_tree (tmpvar)->id;
3245       tmp.type = SCALAR;
3246       tmp.offset = 0;
3247       for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3248         process_constraint (new_constraint (tmp, *rhsp));
3249       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); ++j)
3250         process_constraint (new_constraint (*lhsp, tmp));
3251     }
3252   else if (lhsp->type == SCALAR
3253            && (rhsp->type == SCALAR
3254                || rhsp->type == ADDRESSOF))
3255     {
3256       tree lhsbase, rhsbase;
3257       HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3258       HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3259       unsigned k = 0;
3260       lhsbase = get_ref_base_and_extent (lhsop, &lhsoffset,
3261                                          &lhssize, &lhsmaxsize);
3262       rhsbase = get_ref_base_and_extent (rhsop, &rhsoffset,
3263                                          &rhssize, &rhsmaxsize);
3264       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3265         {
3266           varinfo_t lhsv, rhsv;
3267           rhsp = VEC_index (ce_s, rhsc, k);
3268           lhsv = get_varinfo (lhsp->var);
3269           rhsv = get_varinfo (rhsp->var);
3270           if (lhsv->may_have_pointers
3271               && ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3272                                    rhsv->offset + lhsoffset, rhsv->size))
3273             process_constraint (new_constraint (*lhsp, *rhsp));
3274           if (lhsv->offset + rhsoffset + lhsv->size
3275               > rhsv->offset + lhsoffset + rhsv->size)
3276             {
3277               ++k;
3278               if (k >= VEC_length (ce_s, rhsc))
3279                 break;
3280             }
3281           else
3282             ++j;
3283         }
3284     }
3285   else
3286     gcc_unreachable ();
3287
3288   VEC_free (ce_s, heap, lhsc);
3289   VEC_free (ce_s, heap, rhsc);
3290 }
3291
3292 /* Create a constraint ID = OP.  */
3293
3294 static void
3295 make_constraint_to (unsigned id, tree op)
3296 {
3297   VEC(ce_s, heap) *rhsc = NULL;
3298   struct constraint_expr *c;
3299   struct constraint_expr includes;
3300   unsigned int j;
3301
3302   includes.var = id;
3303   includes.offset = 0;
3304   includes.type = SCALAR;
3305
3306   get_constraint_for (op, &rhsc);
3307   for (j = 0; VEC_iterate (ce_s, rhsc, j, c); j++)
3308     process_constraint (new_constraint (includes, *c));
3309   VEC_free (ce_s, heap, rhsc);
3310 }
3311
3312 /* Make constraints necessary to make OP escape.  */
3313
3314 static void
3315 make_escape_constraint (tree op)
3316 {
3317   make_constraint_to (escaped_id, op);
3318 }
3319
3320 /* For non-IPA mode, generate constraints necessary for a call on the
3321    RHS.  */
3322
3323 static void
3324 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3325 {
3326   struct constraint_expr rhsc;
3327   unsigned i;
3328
3329   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3330     {
3331       tree arg = gimple_call_arg (stmt, i);
3332
3333       /* Find those pointers being passed, and make sure they end up
3334          pointing to anything.  */
3335       if (could_have_pointers (arg))
3336         make_escape_constraint (arg);
3337     }
3338
3339   /* The static chain escapes as well.  */
3340   if (gimple_call_chain (stmt))
3341     make_escape_constraint (gimple_call_chain (stmt));
3342
3343   /* Regular functions return nonlocal memory.  */
3344   rhsc.var = nonlocal_id;
3345   rhsc.offset = 0;
3346   rhsc.type = SCALAR;
3347   VEC_safe_push (ce_s, heap, *results, &rhsc);
3348 }
3349
3350 /* For non-IPA mode, generate constraints necessary for a call
3351    that returns a pointer and assigns it to LHS.  This simply makes
3352    the LHS point to global and escaped variables.  */
3353
3354 static void
3355 handle_lhs_call (tree lhs, int flags, VEC(ce_s, heap) *rhsc)
3356 {
3357   VEC(ce_s, heap) *lhsc = NULL;
3358   unsigned int j;
3359   struct constraint_expr *lhsp;
3360
3361   get_constraint_for (lhs, &lhsc);
3362
3363   if (flags & ECF_MALLOC)
3364     {
3365       struct constraint_expr rhsc;
3366       tree heapvar = heapvar_lookup (lhs);
3367       varinfo_t vi;
3368
3369       if (heapvar == NULL)
3370         {
3371           heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
3372           DECL_EXTERNAL (heapvar) = 1;
3373           get_var_ann (heapvar)->is_heapvar = 1;
3374           if (gimple_referenced_vars (cfun))
3375             add_referenced_var (heapvar);
3376           heapvar_insert (lhs, heapvar);
3377         }
3378
3379       rhsc.var = create_variable_info_for (heapvar,
3380                                            alias_get_name (heapvar));
3381       vi = get_varinfo (rhsc.var);
3382       vi->is_artificial_var = 1;
3383       vi->is_heap_var = 1;
3384       vi->is_unknown_size_var = true;
3385       vi->fullsize = ~0;
3386       vi->size = ~0;
3387       rhsc.type = ADDRESSOF;
3388       rhsc.offset = 0;
3389       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3390         process_constraint (new_constraint (*lhsp, rhsc));
3391     }
3392   else if (VEC_length (ce_s, rhsc) > 0)
3393     {
3394       struct constraint_expr *lhsp, *rhsp;
3395       unsigned int i, j;
3396       /* If the store is to a global decl make sure to
3397          add proper escape constraints.  */
3398       lhs = get_base_address (lhs);
3399       if (lhs
3400           && DECL_P (lhs)
3401           && is_global_var (lhs))
3402         {
3403           struct constraint_expr tmpc;
3404           tmpc.var = escaped_id;
3405           tmpc.offset = 0;
3406           tmpc.type = SCALAR;
3407           VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3408         }
3409       for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3410         for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3411           process_constraint (new_constraint (*lhsp, *rhsp));
3412     }
3413   VEC_free (ce_s, heap, lhsc);
3414 }
3415
3416 /* For non-IPA mode, generate constraints necessary for a call of a
3417    const function that returns a pointer in the statement STMT.  */
3418
3419 static void
3420 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3421 {
3422   struct constraint_expr rhsc, tmpc;
3423   tree tmpvar = NULL_TREE;
3424   unsigned int k;
3425
3426   /* Treat nested const functions the same as pure functions as far
3427      as the static chain is concerned.  */
3428   if (gimple_call_chain (stmt))
3429     {
3430       make_constraint_to (callused_id, gimple_call_chain (stmt));
3431       rhsc.var = callused_id;
3432       rhsc.offset = 0;
3433       rhsc.type = SCALAR;
3434       VEC_safe_push (ce_s, heap, *results, &rhsc);
3435     }
3436
3437   /* May return arguments.  */
3438   for (k = 0; k < gimple_call_num_args (stmt); ++k)
3439     {
3440       tree arg = gimple_call_arg (stmt, k);
3441
3442       if (could_have_pointers (arg))
3443         {
3444           VEC(ce_s, heap) *argc = NULL;
3445           struct constraint_expr *argp;
3446           int i;
3447
3448           /* We always use a temporary here, otherwise we end up with
3449              a quadratic amount of constraints for
3450                large_struct = const_call (large_struct);
3451              with field-sensitive PTA.  */
3452           if (tmpvar == NULL_TREE)
3453             {
3454               tmpvar = create_tmp_var_raw (ptr_type_node, "consttmp");
3455               tmpc = get_constraint_exp_for_temp (tmpvar);
3456             }
3457
3458           get_constraint_for (arg, &argc);
3459           for (i = 0; VEC_iterate (ce_s, argc, i, argp); i++)
3460             process_constraint (new_constraint (tmpc, *argp));
3461           VEC_free (ce_s, heap, argc);
3462         }
3463     }
3464   if (tmpvar != NULL_TREE)
3465     VEC_safe_push (ce_s, heap, *results, &tmpc);
3466
3467   /* May return addresses of globals.  */
3468   rhsc.var = nonlocal_id;
3469   rhsc.offset = 0;
3470   rhsc.type = ADDRESSOF;
3471   VEC_safe_push (ce_s, heap, *results, &rhsc);
3472 }
3473
3474 /* For non-IPA mode, generate constraints necessary for a call to a
3475    pure function in statement STMT.  */
3476
3477 static void
3478 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3479 {
3480   struct constraint_expr rhsc;
3481   unsigned i;
3482   bool need_callused = false;
3483
3484   /* Memory reached from pointer arguments is call-used.  */
3485   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3486     {
3487       tree arg = gimple_call_arg (stmt, i);
3488
3489       if (could_have_pointers (arg))
3490         {
3491           make_constraint_to (callused_id, arg);
3492           need_callused = true;
3493         }
3494     }
3495
3496   /* The static chain is used as well.  */
3497   if (gimple_call_chain (stmt))
3498     {
3499       make_constraint_to (callused_id, gimple_call_chain (stmt));
3500       need_callused = true;
3501     }
3502
3503   /* Pure functions may return callused and nonlocal memory.  */
3504   if (need_callused)
3505     {
3506       rhsc.var = callused_id;
3507       rhsc.offset = 0;
3508       rhsc.type = SCALAR;
3509       VEC_safe_push (ce_s, heap, *results, &rhsc);
3510     }
3511   rhsc.var = nonlocal_id;
3512   rhsc.offset = 0;
3513   rhsc.type = SCALAR;
3514   VEC_safe_push (ce_s, heap, *results, &rhsc);
3515 }
3516
3517 /* Walk statement T setting up aliasing constraints according to the
3518    references found in T.  This function is the main part of the
3519    constraint builder.  AI points to auxiliary alias information used
3520    when building alias sets and computing alias grouping heuristics.  */
3521
3522 static void
3523 find_func_aliases (gimple origt)
3524 {
3525   gimple t = origt;
3526   VEC(ce_s, heap) *lhsc = NULL;
3527   VEC(ce_s, heap) *rhsc = NULL;
3528   struct constraint_expr *c;
3529   enum escape_type stmt_escape_type;
3530
3531   /* Now build constraints expressions.  */
3532   if (gimple_code (t) == GIMPLE_PHI)
3533     {
3534       gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (gimple_phi_result (t))));
3535
3536       /* Only care about pointers and structures containing
3537          pointers.  */
3538       if (could_have_pointers (gimple_phi_result (t)))
3539         {
3540           size_t i;
3541           unsigned int j;
3542
3543           /* For a phi node, assign all the arguments to
3544              the result.  */
3545           get_constraint_for (gimple_phi_result (t), &lhsc);
3546           for (i = 0; i < gimple_phi_num_args (t); i++)
3547             {
3548               tree rhstype;
3549               tree strippedrhs = PHI_ARG_DEF (t, i);
3550
3551               STRIP_NOPS (strippedrhs);
3552               rhstype = TREE_TYPE (strippedrhs);
3553               get_constraint_for (gimple_phi_arg_def (t, i), &rhsc);
3554
3555               for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3556                 {
3557                   struct constraint_expr *c2;
3558                   while (VEC_length (ce_s, rhsc) > 0)
3559                     {
3560                       c2 = VEC_last (ce_s, rhsc);
3561                       process_constraint (new_constraint (*c, *c2));
3562                       VEC_pop (ce_s, rhsc);
3563                     }
3564                 }
3565             }
3566         }
3567     }
3568   /* In IPA mode, we need to generate constraints to pass call
3569      arguments through their calls.   There are two cases,
3570      either a GIMPLE_CALL returning a value, or just a plain
3571      GIMPLE_CALL when we are not.
3572
3573      In non-ipa mode, we need to generate constraints for each
3574      pointer passed by address.  */
3575   else if (is_gimple_call (t))
3576     {
3577       if (!in_ipa_mode)
3578         {
3579           VEC(ce_s, heap) *rhsc = NULL;
3580           int flags = gimple_call_flags (t);
3581
3582           /* Const functions can return their arguments and addresses
3583              of global memory but not of escaped memory.  */
3584           if (flags & (ECF_CONST|ECF_NOVOPS))
3585             {
3586               if (gimple_call_lhs (t)
3587                   && could_have_pointers (gimple_call_lhs (t)))
3588                 handle_const_call (t, &rhsc);
3589             }
3590           /* Pure functions can return addresses in and of memory
3591              reachable from their arguments, but they are not an escape
3592              point for reachable memory of their arguments.  */
3593           else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
3594             handle_pure_call (t, &rhsc);
3595           else
3596             handle_rhs_call (t, &rhsc);
3597           if (gimple_call_lhs (t)
3598               && could_have_pointers (gimple_call_lhs (t)))
3599             handle_lhs_call (gimple_call_lhs (t), flags, rhsc);
3600           VEC_free (ce_s, heap, rhsc);
3601         }
3602       else
3603         {
3604           tree lhsop;
3605           varinfo_t fi;
3606           int i = 1;
3607           size_t j;
3608           tree decl;
3609
3610           lhsop = gimple_call_lhs (t);
3611           decl = gimple_call_fndecl (t);
3612
3613           /* If we can directly resolve the function being called, do so.
3614              Otherwise, it must be some sort of indirect expression that
3615              we should still be able to handle.  */
3616           if (decl)
3617             fi = get_vi_for_tree (decl);
3618           else
3619             {
3620               decl = gimple_call_fn (t);
3621               fi = get_vi_for_tree (decl);
3622             }
3623
3624           /* Assign all the passed arguments to the appropriate incoming
3625              parameters of the function.  */
3626           for (j = 0; j < gimple_call_num_args (t); j++)
3627             {
3628               struct constraint_expr lhs ;
3629               struct constraint_expr *rhsp;
3630               tree arg = gimple_call_arg (t, j);
3631
3632               get_constraint_for (arg, &rhsc);
3633               if (TREE_CODE (decl) != FUNCTION_DECL)
3634                 {
3635                   lhs.type = DEREF;
3636                   lhs.var = fi->id;
3637                   lhs.offset = i;
3638                 }
3639               else
3640                 {
3641                   lhs.type = SCALAR;
3642                   lhs.var = first_vi_for_offset (fi, i)->id;
3643                   lhs.offset = 0;
3644                 }
3645               while (VEC_length (ce_s, rhsc) != 0)
3646                 {
3647                   rhsp = VEC_last (ce_s, rhsc);
3648                   process_constraint (new_constraint (lhs, *rhsp));
3649                   VEC_pop (ce_s, rhsc);
3650                 }
3651               i++;
3652             }
3653
3654           /* If we are returning a value, assign it to the result.  */
3655           if (lhsop)
3656             {
3657               struct constraint_expr rhs;
3658               struct constraint_expr *lhsp;
3659               unsigned int j = 0;
3660
3661               get_constraint_for (lhsop, &lhsc);
3662               if (TREE_CODE (decl) != FUNCTION_DECL)
3663                 {
3664                   rhs.type = DEREF;
3665                   rhs.var = fi->id;
3666                   rhs.offset = i;
3667                 }
3668               else
3669                 {
3670                   rhs.type = SCALAR;
3671                   rhs.var = first_vi_for_offset (fi, i)->id;
3672                   rhs.offset = 0;
3673                 }
3674               for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3675                 process_constraint (new_constraint (*lhsp, rhs));
3676             }
3677         }
3678     }
3679   /* Otherwise, just a regular assignment statement.  Only care about
3680      operations with pointer result, others are dealt with as escape
3681      points if they have pointer operands.  */
3682   else if (is_gimple_assign (t)
3683            && could_have_pointers (gimple_assign_lhs (t)))
3684     {
3685       /* Otherwise, just a regular assignment statement.  */
3686       tree lhsop = gimple_assign_lhs (t);
3687       tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
3688
3689       if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
3690         do_structure_copy (lhsop, rhsop);
3691       else
3692         {
3693           unsigned int j;
3694           struct constraint_expr temp;
3695           get_constraint_for (lhsop, &lhsc);
3696
3697           if (gimple_assign_rhs_code (t) == POINTER_PLUS_EXPR)
3698             get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
3699                                            gimple_assign_rhs2 (t), &rhsc);
3700           else if ((CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3701                     && !(POINTER_TYPE_P (gimple_expr_type (t))
3702                          && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
3703                    || gimple_assign_single_p (t))
3704             get_constraint_for (rhsop, &rhsc);
3705           else
3706             {
3707               temp.type = ADDRESSOF;
3708               temp.var = anything_id;
3709               temp.offset = 0;
3710               VEC_safe_push (ce_s, heap, rhsc, &temp);
3711             }
3712           for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3713             {
3714               struct constraint_expr *c2;
3715               unsigned int k;
3716
3717               for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3718                 process_constraint (new_constraint (*c, *c2));
3719             }
3720         }
3721     }
3722   else if (gimple_code (t) == GIMPLE_CHANGE_DYNAMIC_TYPE)
3723     {
3724       unsigned int j;
3725
3726       get_constraint_for (gimple_cdt_location (t), &lhsc);
3727       for (j = 0; VEC_iterate (ce_s, lhsc, j, c); ++j)
3728         get_varinfo (c->var)->no_tbaa_pruning = true;
3729     }
3730
3731   stmt_escape_type = is_escape_site (t);
3732   if (stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3733     {
3734       gcc_assert (is_gimple_assign (t));
3735       if (gimple_assign_rhs_code (t) == ADDR_EXPR)
3736         {
3737           tree rhs = gimple_assign_rhs1 (t);
3738           tree base = get_base_address (TREE_OPERAND (rhs, 0));
3739           if (base
3740               && (!DECL_P (base)
3741                   || !is_global_var (base)))
3742             make_escape_constraint (rhs);
3743         }
3744       else if (get_gimple_rhs_class (gimple_assign_rhs_code (t))
3745                == GIMPLE_SINGLE_RHS)
3746         {
3747           if (could_have_pointers (gimple_assign_rhs1 (t)))
3748             make_escape_constraint (gimple_assign_rhs1 (t));
3749         }
3750       else
3751         gcc_unreachable ();
3752     }
3753   else if (stmt_escape_type == ESCAPE_BAD_CAST)
3754     {
3755       gcc_assert (is_gimple_assign (t));
3756       gcc_assert (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3757                   || gimple_assign_rhs_code (t) == VIEW_CONVERT_EXPR);
3758       make_escape_constraint (gimple_assign_rhs1 (t));
3759     }
3760   else if (stmt_escape_type == ESCAPE_TO_ASM)
3761     {
3762       unsigned i, noutputs;
3763       const char **oconstraints;
3764       const char *constraint;
3765       bool allows_mem, allows_reg, is_inout;
3766
3767       noutputs = gimple_asm_noutputs (t);
3768       oconstraints = XALLOCAVEC (const char *, noutputs);
3769
3770       for (i = 0; i < noutputs; ++i)
3771         {
3772           tree link = gimple_asm_output_op (t, i);
3773           tree op = TREE_VALUE (link);
3774
3775           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3776           oconstraints[i] = constraint;
3777           parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
3778                                    &allows_reg, &is_inout);
3779
3780           /* A memory constraint makes the address of the operand escape.  */
3781           if (!allows_reg && allows_mem)
3782             make_escape_constraint (build_fold_addr_expr (op));
3783
3784           /* The asm may read global memory, so outputs may point to
3785              any global memory.  */
3786           if (op && could_have_pointers (op))
3787             {
3788               VEC(ce_s, heap) *lhsc = NULL;
3789               struct constraint_expr rhsc, *lhsp;
3790               unsigned j;
3791               get_constraint_for (op, &lhsc);
3792               rhsc.var = nonlocal_id;
3793               rhsc.offset = 0;
3794               rhsc.type = SCALAR;
3795               for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3796                 process_constraint (new_constraint (*lhsp, rhsc));
3797               VEC_free (ce_s, heap, lhsc);
3798             }
3799         }
3800       for (i = 0; i < gimple_asm_ninputs (t); ++i)
3801         {
3802           tree link = gimple_asm_input_op (t, i);
3803           tree op = TREE_VALUE (link);
3804
3805           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3806
3807           parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
3808                                   &allows_mem, &allows_reg);
3809
3810           /* A memory constraint makes the address of the operand escape.  */
3811           if (!allows_reg && allows_mem)
3812             make_escape_constraint (build_fold_addr_expr (op));
3813           /* Strictly we'd only need the constraint to ESCAPED if
3814              the asm clobbers memory, otherwise using CALLUSED
3815              would be enough.  */
3816           else if (op && could_have_pointers (op))
3817             make_escape_constraint (op);
3818         }
3819     }
3820
3821   VEC_free (ce_s, heap, rhsc);
3822   VEC_free (ce_s, heap, lhsc);
3823 }
3824
3825
3826 /* Find the first varinfo in the same variable as START that overlaps with
3827    OFFSET.  Return NULL if we can't find one.  */
3828
3829 static varinfo_t
3830 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3831 {
3832   /* If the offset is outside of the variable, bail out.  */
3833   if (offset >= start->fullsize)
3834     return NULL;
3835
3836   /* If we cannot reach offset from start, lookup the first field
3837      and start from there.  */
3838   if (start->offset > offset)
3839     start = lookup_vi_for_tree (start->decl);
3840
3841   while (start)
3842     {
3843       /* We may not find a variable in the field list with the actual
3844          offset when when we have glommed a structure to a variable.
3845          In that case, however, offset should still be within the size
3846          of the variable. */
3847       if (offset >= start->offset
3848           && offset < (start->offset + start->size))
3849         return start;
3850
3851       start= start->next;
3852     }
3853
3854   return NULL;
3855 }
3856
3857 /* Find the first varinfo in the same variable as START that overlaps with
3858    OFFSET.  If there is no such varinfo the varinfo directly preceding
3859    OFFSET is returned.  */
3860
3861 static varinfo_t
3862 first_or_preceding_vi_for_offset (varinfo_t start,
3863                                   unsigned HOST_WIDE_INT offset)
3864 {
3865   /* If we cannot reach offset from start, lookup the first field
3866      and start from there.  */
3867   if (start->offset > offset)
3868     start = lookup_vi_for_tree (start->decl);
3869
3870   /* We may not find a variable in the field list with the actual
3871      offset when when we have glommed a structure to a variable.
3872      In that case, however, offset should still be within the size
3873      of the variable.
3874      If we got beyond the offset we look for return the field
3875      directly preceding offset which may be the last field.  */
3876   while (start->next
3877          && offset >= start->offset
3878          && !(offset < (start->offset + start->size)))
3879     start = start->next;
3880
3881   return start;
3882 }
3883
3884
3885 /* Insert the varinfo FIELD into the field list for BASE, at the front
3886    of the list.  */
3887
3888 static void
3889 insert_into_field_list (varinfo_t base, varinfo_t field)
3890 {
3891   varinfo_t prev = base;
3892   varinfo_t curr = base->next;
3893
3894   field->next = curr;
3895   prev->next = field;
3896 }
3897
3898 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3899    offset.  */
3900
3901 static void
3902 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3903 {
3904   varinfo_t prev = base;
3905   varinfo_t curr = base->next;
3906
3907   if (curr == NULL)
3908     {
3909       prev->next = field;
3910       field->next = NULL;
3911     }
3912   else
3913     {
3914       while (curr)
3915         {
3916           if (field->offset <= curr->offset)
3917             break;
3918           prev = curr;
3919           curr = curr->next;
3920         }
3921       field->next = prev->next;
3922       prev->next = field;
3923     }
3924 }
3925
3926 /* This structure is used during pushing fields onto the fieldstack
3927    to track the offset of the field, since bitpos_of_field gives it
3928    relative to its immediate containing type, and we want it relative
3929    to the ultimate containing object.  */
3930
3931 struct fieldoff
3932 {
3933   /* Offset from the base of the base containing object to this field.  */
3934   HOST_WIDE_INT offset;
3935
3936   /* Size, in bits, of the field.  */
3937   unsigned HOST_WIDE_INT size;
3938
3939   unsigned has_unknown_size : 1;
3940
3941   unsigned may_have_pointers : 1;
3942 };
3943 typedef struct fieldoff fieldoff_s;
3944
3945 DEF_VEC_O(fieldoff_s);
3946 DEF_VEC_ALLOC_O(fieldoff_s,heap);
3947
3948 /* qsort comparison function for two fieldoff's PA and PB */
3949
3950 static int
3951 fieldoff_compare (const void *pa, const void *pb)
3952 {
3953   const fieldoff_s *foa = (const fieldoff_s *)pa;
3954   const fieldoff_s *fob = (const fieldoff_s *)pb;
3955   unsigned HOST_WIDE_INT foasize, fobsize;
3956
3957   if (foa->offset < fob->offset)
3958     return -1;
3959   else if (foa->offset > fob->offset)
3960     return 1;
3961
3962   foasize = foa->size;
3963   fobsize = fob->size;
3964   if (foasize < fobsize)
3965     return -1;
3966   else if (foasize > fobsize)
3967     return 1;
3968   return 0;
3969 }
3970
3971 /* Sort a fieldstack according to the field offset and sizes.  */
3972 static void
3973 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3974 {
3975   qsort (VEC_address (fieldoff_s, fieldstack),
3976          VEC_length (fieldoff_s, fieldstack),
3977          sizeof (fieldoff_s),
3978          fieldoff_compare);
3979 }
3980
3981 /* Return true if V is a tree that we can have subvars for.
3982    Normally, this is any aggregate type.  Also complex
3983    types which are not gimple registers can have subvars.  */
3984
3985 static inline bool
3986 var_can_have_subvars (const_tree v)
3987 {
3988   /* Volatile variables should never have subvars.  */
3989   if (TREE_THIS_VOLATILE (v))
3990     return false;
3991
3992   /* Non decls or memory tags can never have subvars.  */
3993   if (!DECL_P (v))
3994     return false;
3995
3996   /* Aggregates without overlapping fields can have subvars.  */
3997   if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
3998     return true;
3999
4000   return false;
4001 }
4002
4003 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
4004    the fields of TYPE onto fieldstack, recording their offsets along
4005    the way.
4006
4007    OFFSET is used to keep track of the offset in this entire
4008    structure, rather than just the immediately containing structure.
4009    Returns the number of fields pushed.  */
4010
4011 static int
4012 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
4013                              HOST_WIDE_INT offset)
4014 {
4015   tree field;
4016   int count = 0;
4017
4018   if (TREE_CODE (type) != RECORD_TYPE)
4019     return 0;
4020
4021   /* If the vector of fields is growing too big, bail out early.
4022      Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
4023      sure this fails.  */
4024   if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
4025     return 0;
4026
4027   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4028     if (TREE_CODE (field) == FIELD_DECL)
4029       {
4030         bool push = false;
4031         int pushed = 0;
4032         HOST_WIDE_INT foff = bitpos_of_field (field);
4033
4034         if (!var_can_have_subvars (field)
4035             || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
4036             || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
4037           push = true;
4038         else if (!(pushed = push_fields_onto_fieldstack
4039                    (TREE_TYPE (field), fieldstack, offset + foff))
4040                  && (DECL_SIZE (field)
4041                      && !integer_zerop (DECL_SIZE (field))))
4042           /* Empty structures may have actual size, like in C++.  So
4043              see if we didn't push any subfields and the size is
4044              nonzero, push the field onto the stack.  */
4045           push = true;
4046
4047         if (push)
4048           {
4049             fieldoff_s *pair = NULL;
4050             bool has_unknown_size = false;
4051
4052             if (!VEC_empty (fieldoff_s, *fieldstack))
4053               pair = VEC_last (fieldoff_s, *fieldstack);
4054
4055             if (!DECL_SIZE (field)
4056                 || !host_integerp (DECL_SIZE (field), 1))
4057               has_unknown_size = true;
4058
4059             /* If adjacent fields do not contain pointers merge them.  */
4060             if (pair
4061                 && !pair->may_have_pointers
4062                 && !could_have_pointers (field)
4063                 && !pair->has_unknown_size
4064                 && !has_unknown_size
4065                 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
4066               {
4067                 pair = VEC_last (fieldoff_s, *fieldstack);
4068                 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
4069               }
4070             else
4071               {
4072                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
4073                 pair->offset = offset + foff;
4074                 pair->has_unknown_size = has_unknown_size;
4075                 if (!has_unknown_size)
4076                   pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
4077                 else
4078                   pair->size = -1;
4079                 pair->may_have_pointers = could_have_pointers (field);
4080                 count++;
4081               }
4082           }
4083         else
4084           count += pushed;
4085       }
4086
4087   return count;
4088 }
4089
4090 /* Create a constraint ID = &FROM.  */
4091
4092 static void
4093 make_constraint_from (varinfo_t vi, int from)
4094 {
4095   struct constraint_expr lhs, rhs;
4096
4097   lhs.var = vi->id;
4098   lhs.offset = 0;
4099   lhs.type = SCALAR;
4100
4101   rhs.var = from;
4102   rhs.offset = 0;
4103   rhs.type = ADDRESSOF;
4104   process_constraint (new_constraint (lhs, rhs));
4105 }
4106
4107 /* Create a constraint ID = FROM.  */
4108
4109 static void
4110 make_copy_constraint (varinfo_t vi, int from)
4111 {
4112   struct constraint_expr lhs, rhs;
4113
4114   lhs.var = vi->id;
4115   lhs.offset = 0;
4116   lhs.type = SCALAR;
4117
4118   rhs.var = from;
4119   rhs.offset = 0;
4120   rhs.type = SCALAR;
4121   process_constraint (new_constraint (lhs, rhs));
4122 }
4123
4124 /* Count the number of arguments DECL has, and set IS_VARARGS to true
4125    if it is a varargs function.  */
4126
4127 static unsigned int
4128 count_num_arguments (tree decl, bool *is_varargs)
4129 {
4130   unsigned int i = 0;
4131   tree t;
4132
4133   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
4134        t;
4135        t = TREE_CHAIN (t))
4136     {
4137       if (TREE_VALUE (t) == void_type_node)
4138         break;
4139       i++;
4140     }
4141
4142   if (!t)
4143     *is_varargs = true;
4144   return i;
4145 }
4146
4147 /* Creation function node for DECL, using NAME, and return the index
4148    of the variable we've created for the function.  */
4149
4150 static unsigned int
4151 create_function_info_for (tree decl, const char *name)
4152 {
4153   unsigned int index = VEC_length (varinfo_t, varmap);
4154   varinfo_t vi;
4155   tree arg;
4156   unsigned int i;
4157   bool is_varargs = false;
4158
4159   /* Create the variable info.  */
4160
4161   vi = new_var_info (decl, index, name);
4162   vi->decl = decl;
4163   vi->offset = 0;
4164   vi->size = 1;
4165   vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
4166   insert_vi_for_tree (vi->decl, vi);
4167   VEC_safe_push (varinfo_t, heap, varmap, vi);
4168
4169   stats.total_vars++;
4170
4171   /* If it's varargs, we don't know how many arguments it has, so we
4172      can't do much.  */
4173   if (is_varargs)
4174     {
4175       vi->fullsize = ~0;
4176       vi->size = ~0;
4177       vi->is_unknown_size_var = true;
4178       return index;
4179     }
4180
4181
4182   arg = DECL_ARGUMENTS (decl);
4183
4184   /* Set up variables for each argument.  */
4185   for (i = 1; i < vi->fullsize; i++)
4186     {
4187       varinfo_t argvi;
4188       const char *newname;
4189       char *tempname;
4190       unsigned int newindex;
4191       tree argdecl = decl;
4192
4193       if (arg)
4194         argdecl = arg;
4195
4196       newindex = VEC_length (varinfo_t, varmap);
4197       asprintf (&tempname, "%s.arg%d", name, i-1);
4198       newname = ggc_strdup (tempname);
4199       free (tempname);
4200
4201       argvi = new_var_info (argdecl, newindex, newname);
4202       argvi->decl = argdecl;
4203       VEC_safe_push (varinfo_t, heap, varmap, argvi);
4204       argvi->offset = i;
4205       argvi->size = 1;
4206       argvi->is_full_var = true;
4207       argvi->fullsize = vi->fullsize;
4208       insert_into_field_list_sorted (vi, argvi);
4209       stats.total_vars ++;
4210       if (arg)
4211         {
4212           insert_vi_for_tree (arg, argvi);
4213           arg = TREE_CHAIN (arg);
4214         }
4215     }
4216
4217   /* Create a variable for the return var.  */
4218   if (DECL_RESULT (decl) != NULL
4219       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
4220     {
4221       varinfo_t resultvi;
4222       const char *newname;
4223       char *tempname;
4224       unsigned int newindex;
4225       tree resultdecl = decl;
4226
4227       vi->fullsize ++;
4228
4229       if (DECL_RESULT (decl))
4230         resultdecl = DECL_RESULT (decl);
4231
4232       newindex = VEC_length (varinfo_t, varmap);
4233       asprintf (&tempname, "%s.result", name);
4234       newname = ggc_strdup (tempname);
4235       free (tempname);
4236
4237       resultvi = new_var_info (resultdecl, newindex, newname);
4238       resultvi->decl = resultdecl;
4239       VEC_safe_push (varinfo_t, heap, varmap, resultvi);
4240       resultvi->offset = i;
4241       resultvi->size = 1;
4242       resultvi->fullsize = vi->fullsize;
4243       resultvi->is_full_var = true;
4244       insert_into_field_list_sorted (vi, resultvi);
4245       stats.total_vars ++;
4246       if (DECL_RESULT (decl))
4247         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
4248     }
4249   return index;
4250 }
4251
4252
4253 /* Return true if FIELDSTACK contains fields that overlap.
4254    FIELDSTACK is assumed to be sorted by offset.  */
4255
4256 static bool
4257 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
4258 {
4259   fieldoff_s *fo = NULL;
4260   unsigned int i;
4261   HOST_WIDE_INT lastoffset = -1;
4262
4263   for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4264     {
4265       if (fo->offset == lastoffset)
4266         return true;
4267       lastoffset = fo->offset;
4268     }
4269   return false;
4270 }
4271
4272 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
4273    This will also create any varinfo structures necessary for fields
4274    of DECL.  */
4275
4276 static unsigned int
4277 create_variable_info_for (tree decl, const char *name)
4278 {
4279   unsigned int index = VEC_length (varinfo_t, varmap);
4280   varinfo_t vi;
4281   tree decl_type = TREE_TYPE (decl);
4282   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
4283   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
4284   VEC (fieldoff_s,heap) *fieldstack = NULL;
4285
4286   if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
4287     return create_function_info_for (decl, name);
4288
4289   if (var_can_have_subvars (decl) && use_field_sensitive
4290       && (!var_ann (decl)
4291           || var_ann (decl)->noalias_state == 0)
4292       && (!var_ann (decl)
4293           || !var_ann (decl)->is_heapvar))
4294     push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
4295
4296   /* If the variable doesn't have subvars, we may end up needing to
4297      sort the field list and create fake variables for all the
4298      fields.  */
4299   vi = new_var_info (decl, index, name);
4300   vi->decl = decl;
4301   vi->offset = 0;
4302   vi->may_have_pointers = could_have_pointers (decl);
4303   if (!declsize
4304       || !host_integerp (declsize, 1))
4305     {
4306       vi->is_unknown_size_var = true;
4307       vi->fullsize = ~0;
4308       vi->size = ~0;
4309     }
4310   else
4311     {
4312       vi->fullsize = TREE_INT_CST_LOW (declsize);
4313       vi->size = vi->fullsize;
4314     }
4315
4316   insert_vi_for_tree (vi->decl, vi);
4317   VEC_safe_push (varinfo_t, heap, varmap, vi);
4318   if (is_global && (!flag_whole_program || !in_ipa_mode)
4319       && vi->may_have_pointers)
4320     {
4321       if (var_ann (decl)
4322           && var_ann (decl)->noalias_state == NO_ALIAS_ANYTHING)
4323         make_constraint_from (vi, vi->id);
4324       else
4325         make_copy_constraint (vi, nonlocal_id);
4326     }
4327
4328   stats.total_vars++;
4329   if (use_field_sensitive
4330       && !vi->is_unknown_size_var
4331       && var_can_have_subvars (decl)
4332       && VEC_length (fieldoff_s, fieldstack) > 1
4333       && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4334     {
4335       unsigned int newindex = VEC_length (varinfo_t, varmap);
4336       fieldoff_s *fo = NULL;
4337       bool notokay = false;
4338       unsigned int i;
4339
4340       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4341         {
4342           if (fo->has_unknown_size
4343               || fo->offset < 0)
4344             {
4345               notokay = true;
4346               break;
4347             }
4348         }
4349
4350       /* We can't sort them if we have a field with a variable sized type,
4351          which will make notokay = true.  In that case, we are going to return
4352          without creating varinfos for the fields anyway, so sorting them is a
4353          waste to boot.  */
4354       if (!notokay)
4355         {
4356           sort_fieldstack (fieldstack);
4357           /* Due to some C++ FE issues, like PR 22488, we might end up
4358              what appear to be overlapping fields even though they,
4359              in reality, do not overlap.  Until the C++ FE is fixed,
4360              we will simply disable field-sensitivity for these cases.  */
4361           notokay = check_for_overlaps (fieldstack);
4362         }
4363
4364
4365       if (VEC_length (fieldoff_s, fieldstack) != 0)
4366         fo = VEC_index (fieldoff_s, fieldstack, 0);
4367
4368       if (fo == NULL || notokay)
4369         {
4370           vi->is_unknown_size_var = 1;
4371           vi->fullsize = ~0;
4372           vi->size = ~0;
4373           vi->is_full_var = true;
4374           VEC_free (fieldoff_s, heap, fieldstack);
4375           return index;
4376         }
4377
4378       vi->size = fo->size;
4379       vi->offset = fo->offset;
4380       vi->may_have_pointers = fo->may_have_pointers;
4381       for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4382            i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4383            i--)
4384         {
4385           varinfo_t newvi;
4386           const char *newname = "NULL";
4387           char *tempname;
4388
4389           newindex = VEC_length (varinfo_t, varmap);
4390           if (dump_file)
4391             {
4392               asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
4393                         "+" HOST_WIDE_INT_PRINT_DEC,
4394                         vi->name, fo->offset, fo->size);
4395               newname = ggc_strdup (tempname);
4396               free (tempname);
4397             }
4398           newvi = new_var_info (decl, newindex, newname);
4399           newvi->offset = fo->offset;
4400           newvi->size = fo->size;
4401           newvi->fullsize = vi->fullsize;
4402           newvi->may_have_pointers = fo->may_have_pointers;
4403           insert_into_field_list (vi, newvi);
4404           VEC_safe_push (varinfo_t, heap, varmap, newvi);
4405           if (is_global && (!flag_whole_program || !in_ipa_mode)
4406               && newvi->may_have_pointers)
4407             make_copy_constraint (newvi, nonlocal_id);
4408
4409           stats.total_vars++;
4410         }
4411     }
4412   else
4413     vi->is_full_var = true;
4414
4415   VEC_free (fieldoff_s, heap, fieldstack);
4416
4417   return index;
4418 }
4419
4420 /* Print out the points-to solution for VAR to FILE.  */
4421
4422 static void
4423 dump_solution_for_var (FILE *file, unsigned int var)
4424 {
4425   varinfo_t vi = get_varinfo (var);
4426   unsigned int i;
4427   bitmap_iterator bi;
4428
4429   if (find (var) != var)
4430     {
4431       varinfo_t vipt = get_varinfo (find (var));
4432       fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4433     }
4434   else
4435     {
4436       fprintf (file, "%s = { ", vi->name);
4437       EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4438         {
4439           fprintf (file, "%s ", get_varinfo (i)->name);
4440         }
4441       fprintf (file, "}");
4442       if (vi->no_tbaa_pruning)
4443         fprintf (file, " no-tbaa-pruning");
4444       fprintf (file, "\n");
4445     }
4446 }
4447
4448 /* Print the points-to solution for VAR to stdout.  */
4449
4450 void
4451 debug_solution_for_var (unsigned int var)
4452 {
4453   dump_solution_for_var (stdout, var);
4454 }
4455
4456 /* Create varinfo structures for all of the variables in the
4457    function for intraprocedural mode.  */
4458
4459 static void
4460 intra_create_variable_infos (void)
4461 {
4462   tree t;
4463   struct constraint_expr lhs, rhs;
4464
4465   /* For each incoming pointer argument arg, create the constraint ARG
4466      = NONLOCAL or a dummy variable if flag_argument_noalias is set.  */
4467   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4468     {
4469       varinfo_t p;
4470
4471       if (!could_have_pointers (t))
4472         continue;
4473
4474       /* If flag_argument_noalias is set, then function pointer
4475          arguments are guaranteed not to point to each other.  In that
4476          case, create an artificial variable PARM_NOALIAS and the
4477          constraint ARG = &PARM_NOALIAS.  */
4478       if (POINTER_TYPE_P (TREE_TYPE (t)) && flag_argument_noalias > 0)
4479         {
4480           varinfo_t vi;
4481           tree heapvar = heapvar_lookup (t);
4482
4483           lhs.offset = 0;
4484           lhs.type = SCALAR;
4485           lhs.var  = get_vi_for_tree (t)->id;
4486
4487           if (heapvar == NULL_TREE)
4488             {
4489               var_ann_t ann;
4490               heapvar = create_tmp_var_raw (ptr_type_node,
4491                                             "PARM_NOALIAS");
4492               DECL_EXTERNAL (heapvar) = 1;
4493               if (gimple_referenced_vars (cfun))
4494                 add_referenced_var (heapvar);
4495
4496               heapvar_insert (t, heapvar);
4497
4498               ann = get_var_ann (heapvar);
4499               ann->is_heapvar = 1;
4500               if (flag_argument_noalias == 1)
4501                 ann->noalias_state = NO_ALIAS;
4502               else if (flag_argument_noalias == 2)
4503                 ann->noalias_state = NO_ALIAS_GLOBAL;
4504               else if (flag_argument_noalias == 3)
4505                 ann->noalias_state = NO_ALIAS_ANYTHING;
4506               else
4507                 gcc_unreachable ();
4508             }
4509
4510           vi = get_vi_for_tree (heapvar);
4511           vi->is_artificial_var = 1;
4512           vi->is_heap_var = 1;
4513           vi->is_unknown_size_var = true;
4514           vi->fullsize = ~0;
4515           vi->size = ~0;
4516           rhs.var = vi->id;
4517           rhs.type = ADDRESSOF;
4518           rhs.offset = 0;
4519           for (p = get_varinfo (lhs.var); p; p = p->next)
4520             {
4521               struct constraint_expr temp = lhs;
4522               temp.var = p->id;
4523               process_constraint (new_constraint (temp, rhs));
4524             }
4525         }
4526       else
4527         {
4528           varinfo_t arg_vi = get_vi_for_tree (t);
4529
4530           for (p = arg_vi; p; p = p->next)
4531             make_constraint_from (p, nonlocal_id);
4532         }
4533     }
4534
4535   /* Add a constraint for a result decl that is passed by reference.  */
4536   if (DECL_RESULT (cfun->decl)
4537       && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
4538     {
4539       varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
4540
4541       for (p = result_vi; p; p = p->next)
4542         make_constraint_from (p, nonlocal_id);
4543     }
4544
4545   /* Add a constraint for the incoming static chain parameter.  */
4546   if (cfun->static_chain_decl != NULL_TREE)
4547     {
4548       varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
4549
4550       for (p = chain_vi; p; p = p->next)
4551         make_constraint_from (p, nonlocal_id);
4552     }
4553 }
4554
4555 /* Structure used to put solution bitmaps in a hashtable so they can
4556    be shared among variables with the same points-to set.  */
4557
4558 typedef struct shared_bitmap_info
4559 {
4560   bitmap pt_vars;
4561   hashval_t hashcode;
4562 } *shared_bitmap_info_t;
4563 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
4564
4565 static htab_t shared_bitmap_table;
4566
4567 /* Hash function for a shared_bitmap_info_t */
4568
4569 static hashval_t
4570 shared_bitmap_hash (const void *p)
4571 {
4572   const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
4573   return bi->hashcode;
4574 }
4575
4576 /* Equality function for two shared_bitmap_info_t's. */
4577
4578 static int
4579 shared_bitmap_eq (const void *p1, const void *p2)
4580 {
4581   const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
4582   const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
4583   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4584 }
4585
4586 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4587    existing instance if there is one, NULL otherwise.  */
4588
4589 static bitmap
4590 shared_bitmap_lookup (bitmap pt_vars)
4591 {
4592   void **slot;
4593   struct shared_bitmap_info sbi;
4594
4595   sbi.pt_vars = pt_vars;
4596   sbi.hashcode = bitmap_hash (pt_vars);
4597
4598   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4599                                    sbi.hashcode, NO_INSERT);
4600   if (!slot)
4601     return NULL;
4602   else
4603     return ((shared_bitmap_info_t) *slot)->pt_vars;
4604 }
4605
4606
4607 /* Add a bitmap to the shared bitmap hashtable.  */
4608
4609 static void
4610 shared_bitmap_add (bitmap pt_vars)
4611 {
4612   void **slot;
4613   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4614
4615   sbi->pt_vars = pt_vars;
4616   sbi->hashcode = bitmap_hash (pt_vars);
4617
4618   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4619                                    sbi->hashcode, INSERT);
4620   gcc_assert (!*slot);
4621   *slot = (void *) sbi;
4622 }
4623
4624
4625 /* Set bits in INTO corresponding to the variable uids in solution set FROM.
4626    If MEM_ALIAS_SET is not zero, we also use type based alias analysis to
4627    prune the points-to sets with this alias-set.
4628    Returns the number of pruned variables and updates the vars_contains_global
4629    member of *PT .  */
4630
4631 static unsigned
4632 set_uids_in_ptset (bitmap into, bitmap from,
4633                    alias_set_type mem_alias_set, struct pt_solution *pt)
4634 {
4635   unsigned int i;
4636   bitmap_iterator bi;
4637   unsigned pruned = 0;
4638
4639   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4640     {
4641       varinfo_t vi = get_varinfo (i);
4642
4643       /* The only artificial variables that are allowed in a may-alias
4644          set are heap variables.  */
4645       if (vi->is_artificial_var && !vi->is_heap_var)
4646         continue;
4647
4648       if (TREE_CODE (vi->decl) == VAR_DECL
4649           || TREE_CODE (vi->decl) == PARM_DECL
4650           || TREE_CODE (vi->decl) == RESULT_DECL)
4651         {
4652           /* Don't type prune artificial vars or points-to sets
4653              for pointers that have not been dereferenced or with
4654              type-based pruning disabled.  */
4655           if (!vi->is_artificial_var
4656               && !vi->no_tbaa_pruning
4657               && mem_alias_set != 0)
4658             {
4659               alias_set_type var_alias_set = get_alias_set (vi->decl);
4660               if (mem_alias_set != var_alias_set
4661                   && !alias_set_subset_of (mem_alias_set, var_alias_set))
4662                 {
4663                   ++pruned;
4664                   continue;
4665                 }
4666             }
4667
4668           /* Add the decl to the points-to set.  Note that the points-to
4669              set contains global variables.  */
4670           bitmap_set_bit (into, DECL_UID (vi->decl));
4671           if (is_global_var (vi->decl))
4672             pt->vars_contains_global = true;
4673         }
4674     }
4675
4676   return pruned;
4677 }
4678
4679
4680 static bool have_alias_info = false;
4681
4682 /* Emit a note for the pointer initialization point DEF.  */
4683
4684 static void
4685 emit_pointer_definition (tree ptr, bitmap visited)
4686 {
4687   gimple def = SSA_NAME_DEF_STMT (ptr);
4688   if (gimple_code (def) == GIMPLE_PHI)
4689     {
4690       use_operand_p argp;
4691       ssa_op_iter oi;
4692
4693       FOR_EACH_PHI_ARG (argp, def, oi, SSA_OP_USE)
4694         {
4695           tree arg = USE_FROM_PTR (argp);
4696           if (TREE_CODE (arg) == SSA_NAME)
4697             {
4698               if (bitmap_set_bit (visited, SSA_NAME_VERSION (arg)))
4699                 emit_pointer_definition (arg, visited);
4700             }
4701           else
4702             inform (0, "initialized from %qE", arg);
4703         }
4704     }
4705   else if (!gimple_nop_p (def))
4706     inform (gimple_location (def), "initialized from here");
4707 }
4708
4709 /* Emit a strict aliasing warning for dereferencing the pointer PTR.  */
4710
4711 static void
4712 emit_alias_warning (tree ptr)
4713 {
4714   gimple use;
4715   imm_use_iterator ui;
4716   bool warned = false;
4717
4718   FOR_EACH_IMM_USE_STMT (use, ui, ptr)
4719     {
4720       tree deref = NULL_TREE;
4721
4722       if (gimple_has_lhs (use))
4723         {
4724           tree lhs = get_base_address (gimple_get_lhs (use));
4725           if (lhs
4726               && INDIRECT_REF_P (lhs)
4727               && TREE_OPERAND (lhs, 0) == ptr)
4728             deref = lhs;
4729         }
4730       if (gimple_assign_single_p (use))
4731         {
4732           tree rhs = get_base_address (gimple_assign_rhs1 (use));
4733           if (rhs
4734               && INDIRECT_REF_P (rhs)
4735               && TREE_OPERAND (rhs, 0) == ptr)
4736             deref = rhs;
4737         }
4738       else if (is_gimple_call (use))
4739         {
4740           unsigned i;
4741           for (i = 0; i < gimple_call_num_args (use); ++i)
4742             {
4743               tree op = get_base_address (gimple_call_arg (use, i));
4744               if (op
4745                   && INDIRECT_REF_P (op)
4746                   && TREE_OPERAND (op, 0) == ptr)
4747                 deref = op;
4748             }
4749         }
4750       if (deref
4751           && !TREE_NO_WARNING (deref))
4752         {
4753           TREE_NO_WARNING (deref) = 1;
4754           warned |= warning_at (gimple_location (use), OPT_Wstrict_aliasing,
4755                                 "dereferencing pointer %qD does break "
4756                                 "strict-aliasing rules", SSA_NAME_VAR (ptr));
4757         }
4758     }
4759   if (warned)
4760     {
4761       bitmap visited = BITMAP_ALLOC (NULL);
4762       emit_pointer_definition (ptr, visited);
4763       BITMAP_FREE (visited);
4764     }
4765 }
4766
4767 /* Compute the points-to solution *PT for the variable VI.
4768    Prunes the points-to set based on TBAA rules if DO_TBAA_PRUNING
4769    is true.  Returns the number of TBAA pruned variables from the
4770    points-to set.  */
4771
4772 static unsigned int
4773 find_what_var_points_to (varinfo_t vi, struct pt_solution *pt,
4774                          bool do_tbaa_pruning)
4775 {
4776   unsigned int i, pruned;
4777   bitmap_iterator bi;
4778   bitmap finished_solution;
4779   bitmap result;
4780   tree ptr = vi->decl;
4781   alias_set_type mem_alias_set;
4782
4783   memset (pt, 0, sizeof (struct pt_solution));
4784
4785   /* This variable may have been collapsed, let's get the real
4786      variable.  */
4787   vi = get_varinfo (find (vi->id));
4788
4789   /* Translate artificial variables into SSA_NAME_PTR_INFO
4790      attributes.  */
4791   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4792     {
4793       varinfo_t vi = get_varinfo (i);
4794
4795       if (vi->is_artificial_var)
4796         {
4797           if (vi->id == nothing_id)
4798             pt->null = 1;
4799           else if (vi->id == escaped_id)
4800             pt->escaped = 1;
4801           else if (vi->id == callused_id)
4802             gcc_unreachable ();
4803           else if (vi->id == nonlocal_id)
4804             pt->nonlocal = 1;
4805           else if (vi->is_heap_var)
4806             /* We represent heapvars in the points-to set properly.  */
4807             ;
4808           else if (vi->id == anything_id
4809                    || vi->id == readonly_id
4810                    || vi->id == integer_id)
4811             pt->anything = 1;
4812         }
4813     }
4814
4815   /* Instead of doing extra work, simply do not create
4816      elaborate points-to information for pt_anything pointers.  */
4817   if (pt->anything)
4818     return 0;
4819
4820   /* Share the final set of variables when possible.  */
4821   finished_solution = BITMAP_GGC_ALLOC ();
4822   stats.points_to_sets_created++;
4823
4824   if (TREE_CODE (ptr) == SSA_NAME)
4825     ptr = SSA_NAME_VAR (ptr);
4826
4827   /* If the pointer decl is marked that no TBAA is to be applied,
4828      do not do tbaa pruning.  */
4829   if (!do_tbaa_pruning
4830       || DECL_NO_TBAA_P (ptr))
4831     mem_alias_set = 0;
4832   else
4833     mem_alias_set = get_deref_alias_set (ptr);
4834   pruned = set_uids_in_ptset (finished_solution, vi->solution,
4835                               mem_alias_set, pt);
4836   result = shared_bitmap_lookup (finished_solution);
4837   if (!result)
4838     {
4839       shared_bitmap_add (finished_solution);
4840       pt->vars = finished_solution;
4841     }
4842   else
4843     {
4844       pt->vars = result;
4845       bitmap_clear (finished_solution);
4846     }
4847
4848   return pruned;
4849 }
4850
4851 /* Given a pointer variable P, fill in its points-to set.  Apply
4852    type-based pruning if IS_DEREFERENCED is true.  */
4853
4854 static void
4855 find_what_p_points_to (tree p, bool is_dereferenced)
4856 {
4857   struct ptr_info_def *pi;
4858   unsigned int pruned;
4859   tree lookup_p = p;
4860   varinfo_t vi;
4861
4862   /* For parameters, get at the points-to set for the actual parm
4863      decl.  */
4864   if (TREE_CODE (p) == SSA_NAME
4865       && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4866       && SSA_NAME_IS_DEFAULT_DEF (p))
4867     lookup_p = SSA_NAME_VAR (p);
4868
4869   vi = lookup_vi_for_tree (lookup_p);
4870   if (!vi)
4871     return;
4872
4873   pi = get_ptr_info (p);
4874   pruned = find_what_var_points_to (vi, &pi->pt, is_dereferenced);
4875
4876   if (!(pi->pt.anything || pi->pt.nonlocal || pi->pt.escaped)
4877       && bitmap_empty_p (pi->pt.vars)
4878       && pruned > 0
4879       && is_dereferenced
4880       && warn_strict_aliasing > 0
4881       && !SSA_NAME_IS_DEFAULT_DEF (p))
4882     {
4883       if (dump_file && dump_flags & TDF_DETAILS)
4884         {
4885           fprintf (dump_file, "alias warning for ");
4886           print_generic_expr (dump_file, p, 0);
4887           fprintf (dump_file, "\n");
4888         }
4889       emit_alias_warning (p);
4890     }
4891 }
4892
4893
4894 /* Query statistics for points-to solutions.  */
4895
4896 static struct {
4897   unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
4898   unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
4899   unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
4900   unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
4901 } pta_stats;
4902
4903 void
4904 dump_pta_stats (FILE *s)
4905 {
4906   fprintf (s, "\nPTA query stats:\n");
4907   fprintf (s, "  pt_solution_includes: "
4908            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4909            HOST_WIDE_INT_PRINT_DEC" queries\n",
4910            pta_stats.pt_solution_includes_no_alias,
4911            pta_stats.pt_solution_includes_no_alias
4912            + pta_stats.pt_solution_includes_may_alias);
4913   fprintf (s, "  pt_solutions_intersect: "
4914            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4915            HOST_WIDE_INT_PRINT_DEC" queries\n",
4916            pta_stats.pt_solutions_intersect_no_alias,
4917            pta_stats.pt_solutions_intersect_no_alias
4918            + pta_stats.pt_solutions_intersect_may_alias);
4919 }
4920
4921
4922 /* Reset the points-to solution *PT to a conservative default
4923    (point to anything).  */
4924
4925 void
4926 pt_solution_reset (struct pt_solution *pt)
4927 {
4928   memset (pt, 0, sizeof (struct pt_solution));
4929   pt->anything = true;
4930 }
4931
4932 /* Return true if the points-to solution *PT is empty.  */
4933
4934 static bool
4935 pt_solution_empty_p (struct pt_solution *pt)
4936 {
4937   if (pt->anything
4938       || pt->nonlocal)
4939     return false;
4940
4941   if (pt->vars
4942       && !bitmap_empty_p (pt->vars))
4943     return false;
4944
4945   /* If the solution includes ESCAPED, check if that is empty.  */
4946   if (pt->escaped
4947       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
4948     return false;
4949
4950   return true;
4951 }
4952
4953 /* Return true if the points-to solution *PT includes global memory.  */
4954
4955 bool
4956 pt_solution_includes_global (struct pt_solution *pt)
4957 {
4958   if (pt->anything
4959       || pt->nonlocal
4960       || pt->vars_contains_global)
4961     return true;
4962
4963   if (pt->escaped)
4964     return pt_solution_includes_global (&cfun->gimple_df->escaped);
4965
4966   return false;
4967 }
4968
4969 /* Return true if the points-to solution *PT includes the variable
4970    declaration DECL.  */
4971
4972 static bool
4973 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
4974 {
4975   if (pt->anything)
4976     return true;
4977
4978   if (pt->nonlocal
4979       && is_global_var (decl))
4980     return true;
4981
4982   if (pt->vars
4983       && bitmap_bit_p (pt->vars, DECL_UID (decl)))
4984     return true;
4985
4986   /* If the solution includes ESCAPED, check it.  */
4987   if (pt->escaped
4988       && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
4989     return true;
4990
4991   return false;
4992 }
4993
4994 bool
4995 pt_solution_includes (struct pt_solution *pt, const_tree decl)
4996 {
4997   bool res = pt_solution_includes_1 (pt, decl);
4998   if (res)
4999     ++pta_stats.pt_solution_includes_may_alias;
5000   else
5001     ++pta_stats.pt_solution_includes_no_alias;
5002   return res;
5003 }
5004
5005 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
5006    intersection.  */
5007
5008 static bool
5009 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
5010 {
5011   if (pt1->anything || pt2->anything)
5012     return true;
5013
5014   /* If either points to unknown global memory and the other points to
5015      any global memory they alias.  */
5016   if ((pt1->nonlocal
5017        && (pt2->nonlocal
5018            || pt2->vars_contains_global))
5019       || (pt2->nonlocal
5020           && pt1->vars_contains_global))
5021     return true;
5022
5023   /* Check the escaped solution if required.  */
5024   if ((pt1->escaped || pt2->escaped)
5025       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
5026     {
5027       /* If both point to escaped memory and that solution
5028          is not empty they alias.  */
5029       if (pt1->escaped && pt2->escaped)
5030         return true;
5031
5032       /* If either points to escaped memory see if the escaped solution
5033          intersects with the other.  */
5034       if ((pt1->escaped
5035            && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt2))
5036           || (pt2->escaped
5037               && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt1)))
5038         return true;
5039     }
5040
5041   /* Now both pointers alias if their points-to solution intersects.  */
5042   return (pt1->vars
5043           && pt2->vars
5044           && bitmap_intersect_p (pt1->vars, pt2->vars));
5045 }
5046
5047 bool
5048 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
5049 {
5050   bool res = pt_solutions_intersect_1 (pt1, pt2);
5051   if (res)
5052     ++pta_stats.pt_solutions_intersect_may_alias;
5053   else
5054     ++pta_stats.pt_solutions_intersect_no_alias;
5055   return res;
5056 }
5057
5058
5059 /* Dump points-to information to OUTFILE.  */
5060
5061 static void
5062 dump_sa_points_to_info (FILE *outfile)
5063 {
5064   unsigned int i;
5065
5066   fprintf (outfile, "\nPoints-to sets\n\n");
5067
5068   if (dump_flags & TDF_STATS)
5069     {
5070       fprintf (outfile, "Stats:\n");
5071       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
5072       fprintf (outfile, "Non-pointer vars:          %d\n",
5073                stats.nonpointer_vars);
5074       fprintf (outfile, "Statically unified vars:  %d\n",
5075                stats.unified_vars_static);
5076       fprintf (outfile, "Dynamically unified vars: %d\n",
5077                stats.unified_vars_dynamic);
5078       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
5079       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
5080       fprintf (outfile, "Number of implicit edges: %d\n",
5081                stats.num_implicit_edges);
5082     }
5083
5084   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
5085     dump_solution_for_var (outfile, i);
5086 }
5087
5088
5089 /* Debug points-to information to stderr.  */
5090
5091 void
5092 debug_sa_points_to_info (void)
5093 {
5094   dump_sa_points_to_info (stderr);
5095 }
5096
5097
5098 /* Initialize the always-existing constraint variables for NULL
5099    ANYTHING, READONLY, and INTEGER */
5100
5101 static void
5102 init_base_vars (void)
5103 {
5104   struct constraint_expr lhs, rhs;
5105
5106   /* Create the NULL variable, used to represent that a variable points
5107      to NULL.  */
5108   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
5109   var_nothing = new_var_info (nothing_tree, nothing_id, "NULL");
5110   insert_vi_for_tree (nothing_tree, var_nothing);
5111   var_nothing->is_artificial_var = 1;
5112   var_nothing->offset = 0;
5113   var_nothing->size = ~0;
5114   var_nothing->fullsize = ~0;
5115   var_nothing->is_special_var = 1;
5116   VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
5117
5118   /* Create the ANYTHING variable, used to represent that a variable
5119      points to some unknown piece of memory.  */
5120   anything_tree = create_tmp_var_raw (ptr_type_node, "ANYTHING");
5121   var_anything = new_var_info (anything_tree, anything_id, "ANYTHING");
5122   insert_vi_for_tree (anything_tree, var_anything);
5123   var_anything->is_artificial_var = 1;
5124   var_anything->size = ~0;
5125   var_anything->offset = 0;
5126   var_anything->next = NULL;
5127   var_anything->fullsize = ~0;
5128   var_anything->is_special_var = 1;
5129
5130   /* Anything points to anything.  This makes deref constraints just
5131      work in the presence of linked list and other p = *p type loops,
5132      by saying that *ANYTHING = ANYTHING. */
5133   VEC_safe_push (varinfo_t, heap, varmap, var_anything);
5134   lhs.type = SCALAR;
5135   lhs.var = anything_id;
5136   lhs.offset = 0;
5137   rhs.type = ADDRESSOF;
5138   rhs.var = anything_id;
5139   rhs.offset = 0;
5140
5141   /* This specifically does not use process_constraint because
5142      process_constraint ignores all anything = anything constraints, since all
5143      but this one are redundant.  */
5144   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
5145
5146   /* Create the READONLY variable, used to represent that a variable
5147      points to readonly memory.  */
5148   readonly_tree = create_tmp_var_raw (ptr_type_node, "READONLY");
5149   var_readonly = new_var_info (readonly_tree, readonly_id, "READONLY");
5150   var_readonly->is_artificial_var = 1;
5151   var_readonly->offset = 0;
5152   var_readonly->size = ~0;
5153   var_readonly->fullsize = ~0;
5154   var_readonly->next = NULL;
5155   var_readonly->is_special_var = 1;
5156   insert_vi_for_tree (readonly_tree, var_readonly);
5157   VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
5158
5159   /* readonly memory points to anything, in order to make deref
5160      easier.  In reality, it points to anything the particular
5161      readonly variable can point to, but we don't track this
5162      separately. */
5163   lhs.type = SCALAR;
5164   lhs.var = readonly_id;
5165   lhs.offset = 0;
5166   rhs.type = ADDRESSOF;
5167   rhs.var = readonly_id;  /* FIXME */
5168   rhs.offset = 0;
5169   process_constraint (new_constraint (lhs, rhs));
5170
5171   /* Create the ESCAPED variable, used to represent the set of escaped
5172      memory.  */
5173   escaped_tree = create_tmp_var_raw (ptr_type_node, "ESCAPED");
5174   var_escaped = new_var_info (escaped_tree, escaped_id, "ESCAPED");
5175   insert_vi_for_tree (escaped_tree, var_escaped);
5176   var_escaped->is_artificial_var = 1;
5177   var_escaped->offset = 0;
5178   var_escaped->size = ~0;
5179   var_escaped->fullsize = ~0;
5180   var_escaped->is_special_var = 0;
5181   VEC_safe_push (varinfo_t, heap, varmap, var_escaped);
5182   gcc_assert (VEC_index (varinfo_t, varmap, 3) == var_escaped);
5183
5184   /* Create the NONLOCAL variable, used to represent the set of nonlocal
5185      memory.  */
5186   nonlocal_tree = create_tmp_var_raw (ptr_type_node, "NONLOCAL");
5187   var_nonlocal = new_var_info (nonlocal_tree, nonlocal_id, "NONLOCAL");
5188   insert_vi_for_tree (nonlocal_tree, var_nonlocal);
5189   var_nonlocal->is_artificial_var = 1;
5190   var_nonlocal->offset = 0;
5191   var_nonlocal->size = ~0;
5192   var_nonlocal->fullsize = ~0;
5193   var_nonlocal->is_special_var = 1;
5194   VEC_safe_push (varinfo_t, heap, varmap, var_nonlocal);
5195
5196   /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc.  */
5197   lhs.type = SCALAR;
5198   lhs.var = escaped_id;
5199   lhs.offset = 0;
5200   rhs.type = DEREF;
5201   rhs.var = escaped_id;
5202   rhs.offset = 0;
5203   process_constraint (new_constraint (lhs, rhs));
5204
5205   /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
5206      whole variable escapes.  */
5207   lhs.type = SCALAR;
5208   lhs.var = escaped_id;
5209   lhs.offset = 0;
5210   rhs.type = SCALAR;
5211   rhs.var = escaped_id;
5212   rhs.offset = UNKNOWN_OFFSET;
5213   process_constraint (new_constraint (lhs, rhs));
5214
5215   /* *ESCAPED = NONLOCAL.  This is true because we have to assume
5216      everything pointed to by escaped points to what global memory can
5217      point to.  */
5218   lhs.type = DEREF;
5219   lhs.var = escaped_id;
5220   lhs.offset = 0;
5221   rhs.type = SCALAR;
5222   rhs.var = nonlocal_id;
5223   rhs.offset = 0;
5224   process_constraint (new_constraint (lhs, rhs));
5225
5226   /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED.  This is true because
5227      global memory may point to global memory and escaped memory.  */
5228   lhs.type = SCALAR;
5229   lhs.var = nonlocal_id;
5230   lhs.offset = 0;
5231   rhs.type = ADDRESSOF;
5232   rhs.var = nonlocal_id;
5233   rhs.offset = 0;
5234   process_constraint (new_constraint (lhs, rhs));
5235   rhs.type = ADDRESSOF;
5236   rhs.var = escaped_id;
5237   rhs.offset = 0;
5238   process_constraint (new_constraint (lhs, rhs));
5239
5240   /* Create the CALLUSED variable, used to represent the set of call-used
5241      memory.  */
5242   callused_tree = create_tmp_var_raw (ptr_type_node, "CALLUSED");
5243   var_callused = new_var_info (callused_tree, callused_id, "CALLUSED");
5244   insert_vi_for_tree (callused_tree, var_callused);
5245   var_callused->is_artificial_var = 1;
5246   var_callused->offset = 0;
5247   var_callused->size = ~0;
5248   var_callused->fullsize = ~0;
5249   var_callused->is_special_var = 0;
5250   VEC_safe_push (varinfo_t, heap, varmap, var_callused);
5251
5252   /* CALLUSED = *CALLUSED, because call-used is may-deref'd at calls, etc.  */
5253   lhs.type = SCALAR;
5254   lhs.var = callused_id;
5255   lhs.offset = 0;
5256   rhs.type = DEREF;
5257   rhs.var = callused_id;
5258   rhs.offset = 0;
5259   process_constraint (new_constraint (lhs, rhs));
5260
5261   /* CALLUSED = CALLUSED + UNKNOWN, because if a sub-field is call-used the
5262      whole variable is call-used.  */
5263   lhs.type = SCALAR;
5264   lhs.var = callused_id;
5265   lhs.offset = 0;
5266   rhs.type = SCALAR;
5267   rhs.var = callused_id;
5268   rhs.offset = UNKNOWN_OFFSET;
5269   process_constraint (new_constraint (lhs, rhs));
5270
5271   /* Create the STOREDANYTHING variable, used to represent the set of
5272      variables stored to *ANYTHING.  */
5273   storedanything_tree = create_tmp_var_raw (ptr_type_node, "STOREDANYTHING");
5274   var_storedanything = new_var_info (storedanything_tree, storedanything_id,
5275                                      "STOREDANYTHING");
5276   insert_vi_for_tree (storedanything_tree, var_storedanything);
5277   var_storedanything->is_artificial_var = 1;
5278   var_storedanything->offset = 0;
5279   var_storedanything->size = ~0;
5280   var_storedanything->fullsize = ~0;
5281   var_storedanything->is_special_var = 0;
5282   VEC_safe_push (varinfo_t, heap, varmap, var_storedanything);
5283
5284   /* Create the INTEGER variable, used to represent that a variable points
5285      to what an INTEGER "points to".  */
5286   integer_tree = create_tmp_var_raw (ptr_type_node, "INTEGER");
5287   var_integer = new_var_info (integer_tree, integer_id, "INTEGER");
5288   insert_vi_for_tree (integer_tree, var_integer);
5289   var_integer->is_artificial_var = 1;
5290   var_integer->size = ~0;
5291   var_integer->fullsize = ~0;
5292   var_integer->offset = 0;
5293   var_integer->next = NULL;
5294   var_integer->is_special_var = 1;
5295   VEC_safe_push (varinfo_t, heap, varmap, var_integer);
5296
5297   /* INTEGER = ANYTHING, because we don't know where a dereference of
5298      a random integer will point to.  */
5299   lhs.type = SCALAR;
5300   lhs.var = integer_id;
5301   lhs.offset = 0;
5302   rhs.type = ADDRESSOF;
5303   rhs.var = anything_id;
5304   rhs.offset = 0;
5305   process_constraint (new_constraint (lhs, rhs));
5306 }
5307
5308 /* Initialize things necessary to perform PTA */
5309
5310 static void
5311 init_alias_vars (void)
5312 {
5313   use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
5314
5315   bitmap_obstack_initialize (&pta_obstack);
5316   bitmap_obstack_initialize (&oldpta_obstack);
5317   bitmap_obstack_initialize (&predbitmap_obstack);
5318
5319   constraint_pool = create_alloc_pool ("Constraint pool",
5320                                        sizeof (struct constraint), 30);
5321   variable_info_pool = create_alloc_pool ("Variable info pool",
5322                                           sizeof (struct variable_info), 30);
5323   constraints = VEC_alloc (constraint_t, heap, 8);
5324   varmap = VEC_alloc (varinfo_t, heap, 8);
5325   vi_for_tree = pointer_map_create ();
5326
5327   memset (&stats, 0, sizeof (stats));
5328   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
5329                                      shared_bitmap_eq, free);
5330   init_base_vars ();
5331 }
5332
5333 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
5334    predecessor edges.  */
5335
5336 static void
5337 remove_preds_and_fake_succs (constraint_graph_t graph)
5338 {
5339   unsigned int i;
5340
5341   /* Clear the implicit ref and address nodes from the successor
5342      lists.  */
5343   for (i = 0; i < FIRST_REF_NODE; i++)
5344     {
5345       if (graph->succs[i])
5346         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
5347                             FIRST_REF_NODE * 2);
5348     }
5349
5350   /* Free the successor list for the non-ref nodes.  */
5351   for (i = FIRST_REF_NODE; i < graph->size; i++)
5352     {
5353       if (graph->succs[i])
5354         BITMAP_FREE (graph->succs[i]);
5355     }
5356
5357   /* Now reallocate the size of the successor list as, and blow away
5358      the predecessor bitmaps.  */
5359   graph->size = VEC_length (varinfo_t, varmap);
5360   graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
5361
5362   free (graph->implicit_preds);
5363   graph->implicit_preds = NULL;
5364   free (graph->preds);
5365   graph->preds = NULL;
5366   bitmap_obstack_release (&predbitmap_obstack);
5367 }
5368
5369 /* Compute the set of variables we can't TBAA prune.  */
5370
5371 static void
5372 compute_tbaa_pruning (void)
5373 {
5374   unsigned int size = VEC_length (varinfo_t, varmap);
5375   unsigned int i;
5376   bool any;
5377
5378   changed_count = 0;
5379   changed = sbitmap_alloc (size);
5380   sbitmap_zero (changed);
5381
5382   /* Mark all initial no_tbaa_pruning nodes as changed.  */
5383   any = false;
5384   for (i = 0; i < size; ++i)
5385     {
5386       varinfo_t ivi = get_varinfo (i);
5387
5388       if (find (i) == i && ivi->no_tbaa_pruning)
5389         {
5390           any = true;
5391           if ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
5392               || VEC_length (constraint_t, graph->complex[i]) > 0)
5393             {
5394               SET_BIT (changed, i);
5395               ++changed_count;
5396             }
5397         }
5398     }
5399
5400   while (changed_count > 0)
5401     {
5402       struct topo_info *ti = init_topo_info ();
5403       ++stats.iterations;
5404
5405       compute_topo_order (graph, ti);
5406
5407       while (VEC_length (unsigned, ti->topo_order) != 0)
5408         {
5409           bitmap_iterator bi;
5410
5411           i = VEC_pop (unsigned, ti->topo_order);
5412
5413           /* If this variable is not a representative, skip it.  */
5414           if (find (i) != i)
5415             continue;
5416
5417           /* If the node has changed, we need to process the complex
5418              constraints and outgoing edges again.  */
5419           if (TEST_BIT (changed, i))
5420             {
5421               unsigned int j;
5422               constraint_t c;
5423               VEC(constraint_t,heap) *complex = graph->complex[i];
5424
5425               RESET_BIT (changed, i);
5426               --changed_count;
5427
5428               /* Process the complex copy constraints.  */
5429               for (j = 0; VEC_iterate (constraint_t, complex, j, c); ++j)
5430                 {
5431                   if (c->lhs.type == SCALAR && c->rhs.type == SCALAR)
5432                     {
5433                       varinfo_t lhsvi = get_varinfo (find (c->lhs.var));
5434
5435                       if (!lhsvi->no_tbaa_pruning)
5436                         {
5437                           lhsvi->no_tbaa_pruning = true;
5438                           if (!TEST_BIT (changed, lhsvi->id))
5439                             {
5440                               SET_BIT (changed, lhsvi->id);
5441                               ++changed_count;
5442                             }
5443                         }
5444                     }
5445                 }
5446
5447               /* Propagate to all successors.  */
5448               EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
5449                 {
5450                   unsigned int to = find (j);
5451                   varinfo_t tovi = get_varinfo (to);
5452
5453                   /* Don't propagate to ourselves.  */
5454                   if (to == i)
5455                     continue;
5456
5457                   if (!tovi->no_tbaa_pruning)
5458                     {
5459                       tovi->no_tbaa_pruning = true;
5460                       if (!TEST_BIT (changed, to))
5461                         {
5462                           SET_BIT (changed, to);
5463                           ++changed_count;
5464                         }
5465                     }
5466                 }
5467             }
5468         }
5469
5470       free_topo_info (ti);
5471     }
5472
5473   sbitmap_free (changed);
5474
5475   if (any)
5476     {
5477       for (i = 0; i < size; ++i)
5478         {
5479           varinfo_t ivi = get_varinfo (i);
5480           varinfo_t ivip = get_varinfo (find (i));
5481
5482           if (ivip->no_tbaa_pruning)
5483             {
5484               tree var = ivi->decl;
5485
5486               if (TREE_CODE (var) == SSA_NAME)
5487                 var = SSA_NAME_VAR (var);
5488
5489               if (POINTER_TYPE_P (TREE_TYPE (var)))
5490                 {
5491                   DECL_NO_TBAA_P (var) = 1;
5492
5493                   /* Tell the RTL layer that this pointer can alias
5494                      anything.  */
5495                   DECL_POINTER_ALIAS_SET (var) = 0;
5496                 }
5497             }
5498         }
5499     }
5500 }
5501
5502 /* Initialize the heapvar for statement mapping.  */
5503
5504 static void
5505 init_alias_heapvars (void)
5506 {
5507   if (!heapvar_for_stmt)
5508     heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
5509                                         NULL);
5510 }
5511
5512 /* Delete the heapvar for statement mapping.  */
5513
5514 void
5515 delete_alias_heapvars (void)
5516 {
5517   if (heapvar_for_stmt)
5518     htab_delete (heapvar_for_stmt);
5519   heapvar_for_stmt = NULL;
5520 }
5521
5522 /* Create points-to sets for the current function.  See the comments
5523    at the start of the file for an algorithmic overview.  */
5524
5525 static void
5526 compute_points_to_sets (void)
5527 {
5528   struct scc_info *si;
5529   basic_block bb;
5530   unsigned i;
5531   sbitmap dereferenced_ptrs;
5532
5533   timevar_push (TV_TREE_PTA);
5534
5535   init_alias_vars ();
5536   init_alias_heapvars ();
5537
5538   intra_create_variable_infos ();
5539
5540   /* A bitmap of SSA_NAME pointers that are dereferenced.  This is
5541      used to track which points-to sets may be TBAA pruned.  */
5542   dereferenced_ptrs = sbitmap_alloc (num_ssa_names);
5543   sbitmap_zero (dereferenced_ptrs);
5544
5545   /* Now walk all statements and derive aliases.  */
5546   FOR_EACH_BB (bb)
5547     {
5548       gimple_stmt_iterator gsi;
5549
5550       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5551         {
5552           gimple phi = gsi_stmt (gsi);
5553
5554           if (is_gimple_reg (gimple_phi_result (phi)))
5555             find_func_aliases (phi);
5556         }
5557
5558       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5559         {
5560           gimple stmt = gsi_stmt (gsi);
5561           use_operand_p use_p;
5562           ssa_op_iter iter;
5563
5564           /* Mark dereferenced pointers.  This is used by TBAA pruning
5565              of the points-to sets and the alias warning machinery.  */
5566           FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
5567             {
5568               unsigned num_uses, num_loads, num_stores;
5569               tree op = USE_FROM_PTR (use_p);
5570
5571               if (!POINTER_TYPE_P (TREE_TYPE (op)))
5572                 continue;
5573
5574               /* Determine whether OP is a dereferenced pointer.  */
5575               count_uses_and_derefs (op, stmt,
5576                                      &num_uses, &num_loads, &num_stores);
5577               if (num_loads + num_stores > 0)
5578                 SET_BIT (dereferenced_ptrs, SSA_NAME_VERSION (op));
5579             }
5580
5581           find_func_aliases (stmt);
5582         }
5583     }
5584
5585
5586   if (dump_file)
5587     {
5588       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5589       dump_constraints (dump_file);
5590     }
5591
5592   if (dump_file)
5593     fprintf (dump_file,
5594              "\nCollapsing static cycles and doing variable "
5595              "substitution\n");
5596
5597   init_graph (VEC_length (varinfo_t, varmap) * 2);
5598   
5599   if (dump_file)
5600     fprintf (dump_file, "Building predecessor graph\n");
5601   build_pred_graph ();
5602   
5603   if (dump_file)
5604     fprintf (dump_file, "Detecting pointer and location "
5605              "equivalences\n");
5606   si = perform_var_substitution (graph);
5607   
5608   if (dump_file)
5609     fprintf (dump_file, "Rewriting constraints and unifying "
5610              "variables\n");
5611   rewrite_constraints (graph, si);
5612
5613   build_succ_graph ();
5614   free_var_substitution_info (si);
5615
5616   if (dump_file && (dump_flags & TDF_GRAPH))
5617     dump_constraint_graph (dump_file);
5618
5619   move_complex_constraints (graph);
5620
5621   if (dump_file)
5622     fprintf (dump_file, "Uniting pointer but not location equivalent "
5623              "variables\n");
5624   unite_pointer_equivalences (graph);
5625
5626   if (dump_file)
5627     fprintf (dump_file, "Finding indirect cycles\n");
5628   find_indirect_cycles (graph);
5629
5630   /* Implicit nodes and predecessors are no longer necessary at this
5631      point. */
5632   remove_preds_and_fake_succs (graph);
5633
5634   if (dump_file)
5635     fprintf (dump_file, "Solving graph\n");
5636
5637   solve_graph (graph);
5638
5639   compute_tbaa_pruning ();
5640
5641   if (dump_file)
5642     dump_sa_points_to_info (dump_file);
5643
5644   /* Compute the points-to sets for ESCAPED and CALLUSED used for
5645      call-clobber analysis.  */
5646   find_what_var_points_to (var_escaped, &cfun->gimple_df->escaped, false);
5647   find_what_var_points_to (var_callused, &cfun->gimple_df->callused, false);
5648
5649   /* Make sure the ESCAPED solution (which is used as placeholder in
5650      other solutions) does not reference itself.  This simplifies
5651      points-to solution queries.  */
5652   cfun->gimple_df->escaped.escaped = 0;
5653
5654   /* Compute the points-to sets for pointer SSA_NAMEs.  */
5655   for (i = 0; i < num_ssa_names; ++i)
5656     {
5657       tree ptr = ssa_name (i);
5658       if (ptr
5659           && POINTER_TYPE_P (TREE_TYPE (ptr)))
5660         find_what_p_points_to (ptr, TEST_BIT (dereferenced_ptrs, i));
5661     }
5662   sbitmap_free (dereferenced_ptrs);
5663
5664   timevar_pop (TV_TREE_PTA);
5665
5666   have_alias_info = true;
5667 }
5668
5669
5670 /* Delete created points-to sets.  */
5671
5672 static void
5673 delete_points_to_sets (void)
5674 {
5675   unsigned int i;
5676
5677   htab_delete (shared_bitmap_table);
5678   if (dump_file && (dump_flags & TDF_STATS))
5679     fprintf (dump_file, "Points to sets created:%d\n",
5680              stats.points_to_sets_created);
5681
5682   pointer_map_destroy (vi_for_tree);
5683   bitmap_obstack_release (&pta_obstack);
5684   VEC_free (constraint_t, heap, constraints);
5685
5686   for (i = 0; i < graph->size; i++)
5687     VEC_free (constraint_t, heap, graph->complex[i]);
5688   free (graph->complex);
5689
5690   free (graph->rep);
5691   free (graph->succs);
5692   free (graph->pe);
5693   free (graph->pe_rep);
5694   free (graph->indirect_cycles);
5695   free (graph);
5696
5697   VEC_free (varinfo_t, heap, varmap);
5698   free_alloc_pool (variable_info_pool);
5699   free_alloc_pool (constraint_pool);
5700   have_alias_info = false;
5701 }
5702
5703
5704 /* Compute points-to information for every SSA_NAME pointer in the
5705    current function and compute the transitive closure of escaped
5706    variables to re-initialize the call-clobber states of local variables.  */
5707
5708 unsigned int
5709 compute_may_aliases (void)
5710 {
5711   /* For each pointer P_i, determine the sets of variables that P_i may
5712      point-to.  Compute the reachability set of escaped and call-used
5713      variables.  */
5714   compute_points_to_sets ();
5715
5716   /* Debugging dumps.  */
5717   if (dump_file)
5718     {
5719       dump_alias_info (dump_file);
5720
5721       if (dump_flags & TDF_DETAILS)
5722         dump_referenced_vars (dump_file);
5723     }
5724
5725   /* Deallocate memory used by aliasing data structures and the internal
5726      points-to solution.  */
5727   delete_points_to_sets ();
5728
5729   gcc_assert (!need_ssa_update_p (cfun));
5730
5731   return 0;
5732 }
5733
5734
5735 /* A dummy pass to cause points-to information to be computed via
5736    TODO_rebuild_alias.  */
5737
5738 struct gimple_opt_pass pass_build_alias =
5739 {
5740  {
5741   GIMPLE_PASS,
5742   "alias",                  /* name */
5743   NULL,                     /* gate */
5744   NULL,                     /* execute */
5745   NULL,                     /* sub */
5746   NULL,                     /* next */
5747   0,                        /* static_pass_number */
5748   0,                        /* tv_id */
5749   PROP_cfg | PROP_ssa,      /* properties_required */
5750   PROP_alias,               /* properties_provided */
5751   0,                        /* properties_destroyed */
5752   0,                        /* todo_flags_start */
5753   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
5754  }
5755 };
5756
5757
5758 /* Return true if we should execute IPA PTA.  */
5759 static bool
5760 gate_ipa_pta (void)
5761 {
5762   return (flag_ipa_pta
5763           /* Don't bother doing anything if the program has errors.  */
5764           && !(errorcount || sorrycount));
5765 }
5766
5767 /* Execute the driver for IPA PTA.  */
5768 static unsigned int
5769 ipa_pta_execute (void)
5770 {
5771   struct cgraph_node *node;
5772   struct scc_info *si;
5773
5774   in_ipa_mode = 1;
5775   init_alias_heapvars ();
5776   init_alias_vars ();
5777
5778   for (node = cgraph_nodes; node; node = node->next)
5779     {
5780       unsigned int varid;
5781
5782       varid = create_function_info_for (node->decl,
5783                                         cgraph_node_name (node));
5784       if (node->local.externally_visible)
5785         {
5786           varinfo_t fi = get_varinfo (varid);
5787           for (; fi; fi = fi->next)
5788             make_constraint_from (fi, anything_id);
5789         }
5790     }
5791   for (node = cgraph_nodes; node; node = node->next)
5792     {
5793       if (node->analyzed)
5794         {
5795           struct function *func = DECL_STRUCT_FUNCTION (node->decl);
5796           basic_block bb;
5797           tree old_func_decl = current_function_decl;
5798           if (dump_file)
5799             fprintf (dump_file,
5800                      "Generating constraints for %s\n",
5801                      cgraph_node_name (node));
5802           push_cfun (func);
5803           current_function_decl = node->decl;
5804
5805           FOR_EACH_BB_FN (bb, func)
5806             {
5807               gimple_stmt_iterator gsi;
5808
5809               for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5810                    gsi_next (&gsi))
5811                 {
5812                   gimple phi = gsi_stmt (gsi);
5813
5814                   if (is_gimple_reg (gimple_phi_result (phi)))
5815                     find_func_aliases (phi);
5816                 }
5817
5818               for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5819                 find_func_aliases (gsi_stmt (gsi));
5820             }
5821           current_function_decl = old_func_decl;
5822           pop_cfun ();
5823         }
5824       else
5825         {
5826           /* Make point to anything.  */
5827         }
5828     }
5829
5830   if (dump_file)
5831     {
5832       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5833       dump_constraints (dump_file);
5834     }
5835
5836   if (dump_file)
5837     fprintf (dump_file,
5838              "\nCollapsing static cycles and doing variable "
5839              "substitution:\n");
5840
5841   init_graph (VEC_length (varinfo_t, varmap) * 2);
5842   build_pred_graph ();
5843   si = perform_var_substitution (graph);
5844   rewrite_constraints (graph, si);
5845
5846   build_succ_graph ();
5847   free_var_substitution_info (si);
5848   move_complex_constraints (graph);
5849   unite_pointer_equivalences (graph);
5850   find_indirect_cycles (graph);
5851
5852   /* Implicit nodes and predecessors are no longer necessary at this
5853      point. */
5854   remove_preds_and_fake_succs (graph);
5855
5856   if (dump_file)
5857     fprintf (dump_file, "\nSolving graph\n");
5858
5859   solve_graph (graph);
5860
5861   if (dump_file)
5862     dump_sa_points_to_info (dump_file);
5863
5864   in_ipa_mode = 0;
5865   delete_alias_heapvars ();
5866   delete_points_to_sets ();
5867   return 0;
5868 }
5869
5870 struct simple_ipa_opt_pass pass_ipa_pta =
5871 {
5872  {
5873   SIMPLE_IPA_PASS,
5874   "pta",                                /* name */
5875   gate_ipa_pta,                 /* gate */
5876   ipa_pta_execute,                      /* execute */
5877   NULL,                                 /* sub */
5878   NULL,                                 /* next */
5879   0,                                    /* static_pass_number */
5880   TV_IPA_PTA,                   /* tv_id */
5881   0,                                    /* properties_required */
5882   0,                                    /* properties_provided */
5883   0,                                    /* properties_destroyed */
5884   0,                                    /* todo_flags_start */
5885   TODO_update_ssa                       /* todo_flags_finish */
5886  }
5887 };
5888
5889
5890 #include "gt-tree-ssa-structalias.h"