OSDN Git Service

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