OSDN Git Service

* cfgloopmanip.c (create_preheader): Do not use loop_preheader_edge.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005, 2006, 2007 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 2 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; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "flags.h"
30 #include "rtl.h"
31 #include "tm_p.h"
32 #include "hard-reg-set.h"
33 #include "basic-block.h"
34 #include "output.h"
35 #include "errors.h"
36 #include "diagnostic.h"
37 #include "tree.h"
38 #include "c-common.h"
39 #include "tree-flow.h"
40 #include "tree-inline.h"
41 #include "varray.h"
42 #include "c-tree.h"
43 #include "tree-gimple.h"
44 #include "hashtab.h"
45 #include "function.h"
46 #include "cgraph.h"
47 #include "tree-pass.h"
48 #include "timevar.h"
49 #include "alloc-pool.h"
50 #include "splay-tree.h"
51 #include "params.h"
52 #include "tree-ssa-structalias.h"
53 #include "cgraph.h"
54 #include "alias.h"
55 #include "pointer-set.h"
56
57 /* The idea behind this analyzer is to generate set constraints from the
58    program, then solve the resulting constraints in order to generate the
59    points-to sets.
60
61    Set constraints are a way of modeling program analysis problems that
62    involve sets.  They consist of an inclusion constraint language,
63    describing the variables (each variable is a set) and operations that
64    are involved on the variables, and a set of rules that derive facts
65    from these operations.  To solve a system of set constraints, you derive
66    all possible facts under the rules, which gives you the correct sets
67    as a consequence.
68
69    See  "Efficient Field-sensitive pointer analysis for C" by "David
70    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
71    http://citeseer.ist.psu.edu/pearce04efficient.html
72
73    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
74    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
75    http://citeseer.ist.psu.edu/heintze01ultrafast.html
76
77    There are three types of real constraint expressions, DEREF,
78    ADDRESSOF, and SCALAR.  Each constraint expression consists
79    of a constraint type, a variable, and an offset.
80
81    SCALAR is a constraint expression type used to represent x, whether
82    it appears on the LHS or the RHS of a statement.
83    DEREF is a constraint expression type used to represent *x, whether
84    it appears on the LHS or the RHS of a statement.
85    ADDRESSOF is a constraint expression used to represent &x, whether
86    it appears on the LHS or the RHS of a statement.
87
88    Each pointer variable in the program is assigned an integer id, and
89    each field of a structure variable is assigned an integer id as well.
90
91    Structure variables are linked to their list of fields through a "next
92    field" in each variable that points to the next field in offset
93    order.
94    Each variable for a structure field has
95
96    1. "size", that tells the size in bits of that field.
97    2. "fullsize, that tells the size in bits of the entire structure.
98    3. "offset", that tells the offset in bits from the beginning of the
99    structure to this field.
100
101    Thus,
102    struct f
103    {
104      int a;
105      int b;
106    } foo;
107    int *bar;
108
109    looks like
110
111    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
112    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
113    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
114
115
116   In order to solve the system of set constraints, the following is
117   done:
118
119   1. Each constraint variable x has a solution set associated with it,
120   Sol(x).
121
122   2. Constraints are separated into direct, copy, and complex.
123   Direct constraints are ADDRESSOF constraints that require no extra
124   processing, such as P = &Q
125   Copy constraints are those of the form P = Q.
126   Complex constraints are all the constraints involving dereferences
127   and offsets (including offsetted copies).
128
129   3. All direct constraints of the form P = &Q are processed, such
130   that Q is added to Sol(P)
131
132   4. All complex constraints for a given constraint variable are stored in a
133   linked list attached to that variable's node.
134
135   5. A directed graph is built out of the copy constraints. Each
136   constraint variable is a node in the graph, and an edge from
137   Q to P is added for each copy constraint of the form P = Q
138
139   6. The graph is then walked, and solution sets are
140   propagated along the copy edges, such that an edge from Q to P
141   causes Sol(P) <- Sol(P) union Sol(Q).
142
143   7.  As we visit each node, all complex constraints associated with
144   that node are processed by adding appropriate copy edges to the graph, or the
145   appropriate variables to the solution set.
146
147   8. The process of walking the graph is iterated until no solution
148   sets change.
149
150   Prior to walking the graph in steps 6 and 7, We perform static
151   cycle elimination on the constraint graph, as well
152   as off-line variable substitution.
153
154   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
155   on and turned into anything), but isn't.  You can just see what offset
156   inside the pointed-to struct it's going to access.
157
158   TODO: Constant bounded arrays can be handled as if they were structs of the
159   same number of elements.
160
161   TODO: Modeling heap and incoming pointers becomes much better if we
162   add fields to them as we discover them, which we could do.
163
164   TODO: We could handle unions, but to be honest, it's probably not
165   worth the pain or slowdown.  */
166
167 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
168 htab_t heapvar_for_stmt;
169
170 static bool use_field_sensitive = true;
171 static int in_ipa_mode = 0;
172
173 /* Used for predecessor bitmaps. */
174 static bitmap_obstack predbitmap_obstack;
175
176 /* Used for points-to sets.  */
177 static bitmap_obstack pta_obstack;
178
179 /* Used for oldsolution members of variables. */
180 static bitmap_obstack oldpta_obstack;
181
182 /* Used for per-solver-iteration bitmaps.  */
183 static bitmap_obstack iteration_obstack;
184
185 static unsigned int create_variable_info_for (tree, const char *);
186 typedef struct constraint_graph *constraint_graph_t;
187 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
188
189 DEF_VEC_P(constraint_t);
190 DEF_VEC_ALLOC_P(constraint_t,heap);
191
192 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d)        \
193   if (a)                                                \
194     EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
195
196 static struct constraint_stats
197 {
198   unsigned int total_vars;
199   unsigned int nonpointer_vars;
200   unsigned int unified_vars_static;
201   unsigned int unified_vars_dynamic;
202   unsigned int iterations;
203   unsigned int num_edges;
204   unsigned int num_implicit_edges;
205   unsigned int points_to_sets_created;
206 } stats;
207
208 struct variable_info
209 {
210   /* ID of this variable  */
211   unsigned int id;
212
213   /* Name of this variable */
214   const char *name;
215
216   /* Tree that this variable is associated with.  */
217   tree decl;
218
219   /* Offset of this variable, in bits, from the base variable  */
220   unsigned HOST_WIDE_INT offset;
221
222   /* Size of the variable, in bits.  */
223   unsigned HOST_WIDE_INT size;
224
225   /* Full size of the base variable, in bits.  */
226   unsigned HOST_WIDE_INT fullsize;
227
228   /* A link to the variable for the next field in this structure.  */
229   struct variable_info *next;
230
231   /* True if the variable is directly the target of a dereference.
232      This is used to track which variables are *actually* dereferenced
233      so we can prune their points to listed. */
234   unsigned int directly_dereferenced:1;
235
236   /* True if this is a variable created by the constraint analysis, such as
237      heap variables and constraints we had to break up.  */
238   unsigned int is_artificial_var:1;
239
240   /* True if this is a special variable whose solution set should not be
241      changed.  */
242   unsigned int is_special_var:1;
243
244   /* True for variables whose size is not known or variable.  */
245   unsigned int is_unknown_size_var:1;
246
247   /* True for variables that have unions somewhere in them.  */
248   unsigned int has_union:1;
249
250   /* True if this is a heap variable.  */
251   unsigned int is_heap_var:1;
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   /* Variable ids represented by this node.  */
260   bitmap variables;
261
262   /* Variable id this was collapsed to due to type unsafety.  This
263      should be unused completely after build_succ_graph, or something
264      is broken.  */
265   struct variable_info *collapsed_to;
266 };
267 typedef struct variable_info *varinfo_t;
268
269 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
270
271 /* Pool of variable info structures.  */
272 static alloc_pool variable_info_pool;
273
274 DEF_VEC_P(varinfo_t);
275
276 DEF_VEC_ALLOC_P(varinfo_t, heap);
277
278 /* Table of variable info structures for constraint variables.
279    Indexed directly by variable info id.  */
280 static VEC(varinfo_t,heap) *varmap;
281
282 /* Return the varmap element N */
283
284 static inline varinfo_t
285 get_varinfo (unsigned int n)
286 {
287   return VEC_index (varinfo_t, varmap, n);
288 }
289
290 /* Return the varmap element N, following the collapsed_to link.  */
291
292 static inline varinfo_t
293 get_varinfo_fc (unsigned int n)
294 {
295   varinfo_t v = VEC_index (varinfo_t, varmap, n);
296
297   if (v->collapsed_to)
298     return v->collapsed_to;
299   return v;
300 }
301
302 /* Variable that represents the unknown pointer.  */
303 static varinfo_t var_anything;
304 static tree anything_tree;
305 static unsigned int anything_id;
306
307 /* Variable that represents the NULL pointer.  */
308 static varinfo_t var_nothing;
309 static tree nothing_tree;
310 static unsigned int nothing_id;
311
312 /* Variable that represents read only memory.  */
313 static varinfo_t var_readonly;
314 static tree readonly_tree;
315 static unsigned int readonly_id;
316
317 /* Variable that represents integers.  This is used for when people do things
318    like &0->a.b.  */
319 static varinfo_t var_integer;
320 static tree integer_tree;
321 static unsigned int integer_id;
322
323 /* Lookup a heap var for FROM, and return it if we find one.  */
324
325 static tree
326 heapvar_lookup (tree from)
327 {
328   struct tree_map *h, in;
329   in.base.from = from;
330
331   h = htab_find_with_hash (heapvar_for_stmt, &in, htab_hash_pointer (from));
332   if (h)
333     return h->to;
334   return NULL_TREE;
335 }
336
337 /* Insert a mapping FROM->TO in the heap var for statement
338    hashtable.  */
339
340 static void
341 heapvar_insert (tree from, tree to)
342 {
343   struct tree_map *h;
344   void **loc;
345
346   h = ggc_alloc (sizeof (struct tree_map));
347   h->hash = htab_hash_pointer (from);
348   h->base.from = from;
349   h->to = to;
350   loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
351   *(struct tree_map **) loc = h;
352 }
353
354 /* Return a new variable info structure consisting for a variable
355    named NAME, and using constraint graph node NODE.  */
356
357 static varinfo_t
358 new_var_info (tree t, unsigned int id, const char *name)
359 {
360   varinfo_t ret = pool_alloc (variable_info_pool);
361
362   ret->id = id;
363   ret->name = name;
364   ret->decl = t;
365   ret->directly_dereferenced = false;
366   ret->is_artificial_var = false;
367   ret->is_heap_var = false;
368   ret->is_special_var = false;
369   ret->is_unknown_size_var = false;
370   ret->has_union = false;
371   ret->solution = BITMAP_ALLOC (&pta_obstack);
372   ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
373   ret->next = NULL;
374   ret->collapsed_to = NULL;
375   return ret;
376 }
377
378 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
379
380 /* An expression that appears in a constraint.  */
381
382 struct constraint_expr
383 {
384   /* Constraint type.  */
385   constraint_expr_type type;
386
387   /* Variable we are referring to in the constraint.  */
388   unsigned int var;
389
390   /* Offset, in bits, of this constraint from the beginning of
391      variables it ends up referring to.
392
393      IOW, in a deref constraint, we would deref, get the result set,
394      then add OFFSET to each member.   */
395   unsigned HOST_WIDE_INT offset;
396 };
397
398 typedef struct constraint_expr ce_s;
399 DEF_VEC_O(ce_s);
400 DEF_VEC_ALLOC_O(ce_s, heap);
401 static void get_constraint_for (tree, VEC(ce_s, heap) **);
402 static void do_deref (VEC (ce_s, heap) **);
403
404 /* Our set constraints are made up of two constraint expressions, one
405    LHS, and one RHS.
406
407    As described in the introduction, our set constraints each represent an
408    operation between set valued variables.
409 */
410 struct constraint
411 {
412   struct constraint_expr lhs;
413   struct constraint_expr rhs;
414 };
415
416 /* List of constraints that we use to build the constraint graph from.  */
417
418 static VEC(constraint_t,heap) *constraints;
419 static alloc_pool constraint_pool;
420
421
422 DEF_VEC_I(int);
423 DEF_VEC_ALLOC_I(int, heap);
424
425 /* The constraint graph is represented as an array of bitmaps
426    containing successor nodes.  */
427
428 struct constraint_graph
429 {
430   /* Size of this graph, which may be different than the number of
431      nodes in the variable map.  */
432   unsigned int size;
433
434   /* Explicit successors of each node. */
435   bitmap *succs;
436
437   /* Implicit predecessors of each node (Used for variable
438      substitution). */
439   bitmap *implicit_preds;
440
441   /* Explicit predecessors of each node (Used for variable substitution).  */
442   bitmap *preds;
443
444   /* Indirect cycle representatives, or -1 if the node has no indirect
445      cycles.  */
446   int *indirect_cycles;
447
448   /* Representative node for a node.  rep[a] == a unless the node has
449      been unified. */
450   unsigned int *rep;
451
452   /* Equivalence class representative for a node.  This is used for
453      variable substitution.  */
454   int *eq_rep;
455
456   /* Label for each node, used during variable substitution.  */
457   unsigned int *label;
458
459   /* Bitmap of nodes where the bit is set if the node is a direct
460      node.  Used for variable substitution.  */
461   sbitmap direct_nodes;
462
463   /* Vector of complex constraints for each graph node.  Complex
464      constraints are those involving dereferences or offsets that are
465      not 0.  */
466   VEC(constraint_t,heap) **complex;
467 };
468
469 static constraint_graph_t graph;
470
471 /* During variable substitution and the offline version of indirect
472    cycle finding, we create nodes to represent dereferences and
473    address taken constraints.  These represent where these start and
474    end.  */
475 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
476 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
477 #define FIRST_ADDR_NODE (LAST_REF_NODE + 1)
478
479 /* Return the representative node for NODE, if NODE has been unioned
480    with another NODE.
481    This function performs path compression along the way to finding
482    the representative.  */
483
484 static unsigned int
485 find (unsigned int node)
486 {
487   gcc_assert (node < graph->size);
488   if (graph->rep[node] != node)
489     return graph->rep[node] = find (graph->rep[node]);
490   return node;
491 }
492
493 /* Union the TO and FROM nodes to the TO nodes.
494    Note that at some point in the future, we may want to do
495    union-by-rank, in which case we are going to have to return the
496    node we unified to.  */
497
498 static bool
499 unite (unsigned int to, unsigned int from)
500 {
501   gcc_assert (to < graph->size && from < graph->size);
502   if (to != from && graph->rep[from] != to)
503     {
504       graph->rep[from] = to;
505       return true;
506     }
507   return false;
508 }
509
510 /* Create a new constraint consisting of LHS and RHS expressions.  */
511
512 static constraint_t
513 new_constraint (const struct constraint_expr lhs,
514                 const struct constraint_expr rhs)
515 {
516   constraint_t ret = pool_alloc (constraint_pool);
517   ret->lhs = lhs;
518   ret->rhs = rhs;
519   return ret;
520 }
521
522 /* Print out constraint C to FILE.  */
523
524 void
525 dump_constraint (FILE *file, constraint_t c)
526 {
527   if (c->lhs.type == ADDRESSOF)
528     fprintf (file, "&");
529   else if (c->lhs.type == DEREF)
530     fprintf (file, "*");
531   fprintf (file, "%s", get_varinfo_fc (c->lhs.var)->name);
532   if (c->lhs.offset != 0)
533     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
534   fprintf (file, " = ");
535   if (c->rhs.type == ADDRESSOF)
536     fprintf (file, "&");
537   else if (c->rhs.type == DEREF)
538     fprintf (file, "*");
539   fprintf (file, "%s", get_varinfo_fc (c->rhs.var)->name);
540   if (c->rhs.offset != 0)
541     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
542   fprintf (file, "\n");
543 }
544
545 /* Print out constraint C to stderr.  */
546
547 void
548 debug_constraint (constraint_t c)
549 {
550   dump_constraint (stderr, c);
551 }
552
553 /* Print out all constraints to FILE */
554
555 void
556 dump_constraints (FILE *file)
557 {
558   int i;
559   constraint_t c;
560   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
561     dump_constraint (file, c);
562 }
563
564 /* Print out all constraints to stderr.  */
565
566 void
567 debug_constraints (void)
568 {
569   dump_constraints (stderr);
570 }
571
572 /* SOLVER FUNCTIONS
573
574    The solver is a simple worklist solver, that works on the following
575    algorithm:
576
577    sbitmap changed_nodes = all zeroes;
578    changed_count = 0;
579    For each node that is not already collapsed:
580        changed_count++;
581        set bit in changed nodes
582
583    while (changed_count > 0)
584    {
585      compute topological ordering for constraint graph
586
587      find and collapse cycles in the constraint graph (updating
588      changed if necessary)
589
590      for each node (n) in the graph in topological order:
591        changed_count--;
592
593        Process each complex constraint associated with the node,
594        updating changed if necessary.
595
596        For each outgoing edge from n, propagate the solution from n to
597        the destination of the edge, updating changed as necessary.
598
599    }  */
600
601 /* Return true if two constraint expressions A and B are equal.  */
602
603 static bool
604 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
605 {
606   return a.type == b.type && a.var == b.var && a.offset == b.offset;
607 }
608
609 /* Return true if constraint expression A is less than constraint expression
610    B.  This is just arbitrary, but consistent, in order to give them an
611    ordering.  */
612
613 static bool
614 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
615 {
616   if (a.type == b.type)
617     {
618       if (a.var == b.var)
619         return a.offset < b.offset;
620       else
621         return a.var < b.var;
622     }
623   else
624     return a.type < b.type;
625 }
626
627 /* Return true if constraint A is less than constraint B.  This is just
628    arbitrary, but consistent, in order to give them an ordering.  */
629
630 static bool
631 constraint_less (const constraint_t a, const constraint_t b)
632 {
633   if (constraint_expr_less (a->lhs, b->lhs))
634     return true;
635   else if (constraint_expr_less (b->lhs, a->lhs))
636     return false;
637   else
638     return constraint_expr_less (a->rhs, b->rhs);
639 }
640
641 /* Return true if two constraints A and B are equal.  */
642
643 static bool
644 constraint_equal (struct constraint a, struct constraint b)
645 {
646   return constraint_expr_equal (a.lhs, b.lhs)
647     && constraint_expr_equal (a.rhs, b.rhs);
648 }
649
650
651 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
652
653 static constraint_t
654 constraint_vec_find (VEC(constraint_t,heap) *vec,
655                      struct constraint lookfor)
656 {
657   unsigned int place;
658   constraint_t found;
659
660   if (vec == NULL)
661     return NULL;
662
663   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
664   if (place >= VEC_length (constraint_t, vec))
665     return NULL;
666   found = VEC_index (constraint_t, vec, place);
667   if (!constraint_equal (*found, lookfor))
668     return NULL;
669   return found;
670 }
671
672 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
673
674 static void
675 constraint_set_union (VEC(constraint_t,heap) **to,
676                       VEC(constraint_t,heap) **from)
677 {
678   int i;
679   constraint_t c;
680
681   for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
682     {
683       if (constraint_vec_find (*to, *c) == NULL)
684         {
685           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
686                                                 constraint_less);
687           VEC_safe_insert (constraint_t, heap, *to, place, c);
688         }
689     }
690 }
691
692 /* Take a solution set SET, add OFFSET to each member of the set, and
693    overwrite SET with the result when done.  */
694
695 static void
696 solution_set_add (bitmap set, unsigned HOST_WIDE_INT offset)
697 {
698   bitmap result = BITMAP_ALLOC (&iteration_obstack);
699   unsigned int i;
700   bitmap_iterator bi;
701
702   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
703     {
704       /* If this is a properly sized variable, only add offset if it's
705          less than end.  Otherwise, it is globbed to a single
706          variable.  */
707
708       if ((get_varinfo (i)->offset + offset) < get_varinfo (i)->fullsize)
709         {
710           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (i)->offset + offset;
711           varinfo_t v = first_vi_for_offset (get_varinfo (i), fieldoffset);
712           if (!v)
713             continue;
714           bitmap_set_bit (result, v->id);
715         }
716       else if (get_varinfo (i)->is_artificial_var
717                || get_varinfo (i)->has_union
718                || get_varinfo (i)->is_unknown_size_var)
719         {
720           bitmap_set_bit (result, i);
721         }
722     }
723
724   bitmap_copy (set, result);
725   BITMAP_FREE (result);
726 }
727
728 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
729    process.  */
730
731 static bool
732 set_union_with_increment  (bitmap to, bitmap from, unsigned HOST_WIDE_INT inc)
733 {
734   if (inc == 0)
735     return bitmap_ior_into (to, from);
736   else
737     {
738       bitmap tmp;
739       bool res;
740
741       tmp = BITMAP_ALLOC (&iteration_obstack);
742       bitmap_copy (tmp, from);
743       solution_set_add (tmp, inc);
744       res = bitmap_ior_into (to, tmp);
745       BITMAP_FREE (tmp);
746       return res;
747     }
748 }
749
750 /* Insert constraint C into the list of complex constraints for graph
751    node VAR.  */
752
753 static void
754 insert_into_complex (constraint_graph_t graph,
755                      unsigned int var, constraint_t c)
756 {
757   VEC (constraint_t, heap) *complex = graph->complex[var];
758   unsigned int place = VEC_lower_bound (constraint_t, complex, c,
759                                         constraint_less);
760
761   /* Only insert constraints that do not already exist.  */
762   if (place >= VEC_length (constraint_t, complex)
763       || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
764     VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
765 }
766
767
768 /* Condense two variable nodes into a single variable node, by moving
769    all associated info from SRC to TO.  */
770
771 static void
772 merge_node_constraints (constraint_graph_t graph, unsigned int to,
773                         unsigned int from)
774 {
775   unsigned int i;
776   constraint_t c;
777
778   gcc_assert (find (from) == to);
779
780   /* Move all complex constraints from src node into to node  */
781   for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
782     {
783       /* In complex constraints for node src, we may have either
784          a = *src, and *src = a, or an offseted constraint which are
785          always added to the rhs node's constraints.  */
786
787       if (c->rhs.type == DEREF)
788         c->rhs.var = to;
789       else if (c->lhs.type == DEREF)
790         c->lhs.var = to;
791       else
792         c->rhs.var = to;
793     }
794   constraint_set_union (&graph->complex[to], &graph->complex[from]);
795   VEC_free (constraint_t, heap, graph->complex[from]);
796   graph->complex[from] = NULL;
797 }
798
799
800 /* Remove edges involving NODE from GRAPH.  */
801
802 static void
803 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
804 {
805   if (graph->succs[node])
806     BITMAP_FREE (graph->succs[node]);
807 }
808
809 /* Merge GRAPH nodes FROM and TO into node TO.  */
810
811 static void
812 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
813                    unsigned int from)
814 {
815   if (graph->indirect_cycles[from] != -1)
816     {
817       /* If we have indirect cycles with the from node, and we have
818          none on the to node, the to node has indirect cycles from the
819          from node now that they are unified.
820          If indirect cycles exist on both, unify the nodes that they
821          are in a cycle with, since we know they are in a cycle with
822          each other.  */
823       if (graph->indirect_cycles[to] == -1)
824         {
825           graph->indirect_cycles[to] = graph->indirect_cycles[from];
826         }
827       else
828         {
829           unsigned int tonode = find (graph->indirect_cycles[to]);
830           unsigned int fromnode = find (graph->indirect_cycles[from]);
831
832           if (unite (tonode, fromnode))
833             unify_nodes (graph, tonode, fromnode, true);
834         }
835     }
836
837   /* Merge all the successor edges.  */
838   if (graph->succs[from])
839     {
840       if (!graph->succs[to])
841         graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
842       bitmap_ior_into (graph->succs[to],
843                        graph->succs[from]);
844     }
845
846   clear_edges_for_node (graph, from);
847 }
848
849
850 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
851    it doesn't exist in the graph already.  */
852
853 static void
854 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
855                          unsigned int from)
856 {
857   if (to == from)
858     return;
859
860   if (!graph->implicit_preds[to])
861     graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
862
863   if (!bitmap_bit_p (graph->implicit_preds[to], from))
864     {
865       stats.num_implicit_edges++;
866       bitmap_set_bit (graph->implicit_preds[to], from);
867     }
868 }
869
870 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
871    it doesn't exist in the graph already.
872    Return false if the edge already existed, true otherwise.  */
873
874 static void
875 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
876                      unsigned int from)
877 {
878   if (!graph->preds[to])
879     graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
880   if (!bitmap_bit_p (graph->preds[to], from))
881     bitmap_set_bit (graph->preds[to], from);
882 }
883
884 /* Add a graph edge to GRAPH, going from FROM to TO if
885    it doesn't exist in the graph already.
886    Return false if the edge already existed, true otherwise.  */
887
888 static bool
889 add_graph_edge (constraint_graph_t graph, unsigned int to,
890                 unsigned int from)
891 {
892   if (to == from)
893     {
894       return false;
895     }
896   else
897     {
898       bool r = false;
899
900       if (!graph->succs[from])
901         graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
902       if (!bitmap_bit_p (graph->succs[from], to))
903         {
904           r = true;
905           if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
906             stats.num_edges++;
907           bitmap_set_bit (graph->succs[from], to);
908         }
909       return r;
910     }
911 }
912
913
914 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH.  */
915
916 static bool
917 valid_graph_edge (constraint_graph_t graph, unsigned int src,
918                   unsigned int dest)
919 {
920   return (graph->succs[dest]
921           && bitmap_bit_p (graph->succs[dest], src));
922 }
923
924 /* Build the constraint graph, adding only predecessor edges right now.  */
925
926 static void
927 build_pred_graph (void)
928 {
929   int i;
930   constraint_t c;
931   unsigned int j;
932
933   graph = XNEW (struct constraint_graph);
934   graph->size = (VEC_length (varinfo_t, varmap)) * 3;
935   graph->succs = XCNEWVEC (bitmap, graph->size);
936   graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
937   graph->preds = XCNEWVEC (bitmap, graph->size);
938   graph->indirect_cycles = XNEWVEC (int, VEC_length (varinfo_t, varmap));
939   graph->label = XCNEWVEC (unsigned int, graph->size);
940   graph->rep = XNEWVEC (unsigned int, graph->size);
941   graph->eq_rep = XNEWVEC (int, graph->size);
942   graph->complex = XCNEWVEC (VEC(constraint_t, heap) *,
943                              VEC_length (varinfo_t, varmap));
944   graph->direct_nodes = sbitmap_alloc (graph->size);
945   sbitmap_zero (graph->direct_nodes);
946
947   for (j = 0; j < FIRST_REF_NODE; j++)
948     {
949       if (!get_varinfo (j)->is_special_var)
950         SET_BIT (graph->direct_nodes, j);
951     }
952
953   for (j = 0; j < graph->size; j++)
954     {
955       graph->rep[j] = j;
956       graph->eq_rep[j] = -1;
957     }
958
959   for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
960     graph->indirect_cycles[j] = -1;
961
962   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
963     {
964       struct constraint_expr lhs = c->lhs;
965       struct constraint_expr rhs = c->rhs;
966       unsigned int lhsvar = get_varinfo_fc (lhs.var)->id;
967       unsigned int rhsvar = get_varinfo_fc (rhs.var)->id;
968
969       if (lhs.type == DEREF)
970         {
971           /* *x = y.  */
972           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
973             add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
974           if (rhs.type == ADDRESSOF)
975             RESET_BIT (graph->direct_nodes, rhsvar);
976         }
977       else if (rhs.type == DEREF)
978         {
979           /* x = *y */
980           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
981             add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
982           else
983             RESET_BIT (graph->direct_nodes, lhsvar);
984         }
985       else if (rhs.type == ADDRESSOF)
986         {
987           /* x = &y */
988           add_pred_graph_edge (graph, lhsvar, FIRST_ADDR_NODE + rhsvar);
989           /* Implicitly, *x = y */
990           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
991
992           RESET_BIT (graph->direct_nodes, rhsvar);
993         }
994       else if (lhsvar > anything_id
995                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
996         {
997           /* x = y */
998           add_pred_graph_edge (graph, lhsvar, rhsvar);
999           /* Implicitly, *x = *y */
1000           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1001                                    FIRST_REF_NODE + rhsvar);
1002         }
1003       else if (lhs.offset != 0 || rhs.offset != 0)
1004         {
1005           if (rhs.offset != 0)
1006             RESET_BIT (graph->direct_nodes, lhs.var);
1007           if (lhs.offset != 0)
1008             RESET_BIT (graph->direct_nodes, rhs.var);
1009         }
1010     }
1011 }
1012
1013 /* Build the constraint graph, adding successor edges.  */
1014
1015 static void
1016 build_succ_graph (void)
1017 {
1018   int i;
1019   constraint_t c;
1020
1021   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1022     {
1023       struct constraint_expr lhs;
1024       struct constraint_expr rhs;
1025       unsigned int lhsvar;
1026       unsigned int rhsvar;
1027
1028       if (!c)
1029         continue;
1030
1031       lhs = c->lhs;
1032       rhs = c->rhs;
1033       lhsvar = find (get_varinfo_fc (lhs.var)->id);
1034       rhsvar = find (get_varinfo_fc (rhs.var)->id);
1035
1036       if (lhs.type == DEREF)
1037         {
1038           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1039             add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1040         }
1041       else if (rhs.type == DEREF)
1042         {
1043           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1044             add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1045         }
1046       else if (rhs.type == ADDRESSOF)
1047         {
1048           /* x = &y */
1049           gcc_assert (find (get_varinfo_fc (rhs.var)->id)
1050                       == get_varinfo_fc (rhs.var)->id);
1051           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1052         }
1053       else if (lhsvar > anything_id
1054                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1055         {
1056           add_graph_edge (graph, lhsvar, rhsvar);
1057         }
1058     }
1059 }
1060
1061
1062 /* Changed variables on the last iteration.  */
1063 static unsigned int changed_count;
1064 static sbitmap changed;
1065
1066 DEF_VEC_I(unsigned);
1067 DEF_VEC_ALLOC_I(unsigned,heap);
1068
1069
1070 /* Strongly Connected Component visitation info.  */
1071
1072 struct scc_info
1073 {
1074   sbitmap visited;
1075   sbitmap roots;
1076   unsigned int *dfs;
1077   unsigned int *node_mapping;
1078   int current_index;
1079   VEC(unsigned,heap) *scc_stack;
1080 };
1081
1082
1083 /* Recursive routine to find strongly connected components in GRAPH.
1084    SI is the SCC info to store the information in, and N is the id of current
1085    graph node we are processing.
1086
1087    This is Tarjan's strongly connected component finding algorithm, as
1088    modified by Nuutila to keep only non-root nodes on the stack.
1089    The algorithm can be found in "On finding the strongly connected
1090    connected components in a directed graph" by Esko Nuutila and Eljas
1091    Soisalon-Soininen, in Information Processing Letters volume 49,
1092    number 1, pages 9-14.  */
1093
1094 static void
1095 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1096 {
1097   unsigned int i;
1098   bitmap_iterator bi;
1099   unsigned int my_dfs;
1100
1101   SET_BIT (si->visited, n);
1102   si->dfs[n] = si->current_index ++;
1103   my_dfs = si->dfs[n];
1104
1105   /* Visit all the successors.  */
1106   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1107     {
1108       unsigned int w;
1109
1110       if (i > LAST_REF_NODE)
1111         break;
1112
1113       w = find (i);
1114       if (TEST_BIT (si->roots, w))
1115         continue;
1116
1117       if (!TEST_BIT (si->visited, w))
1118         scc_visit (graph, si, w);
1119       {
1120         unsigned int t = find (w);
1121         unsigned int nnode = find (n);
1122         gcc_assert (nnode == n);
1123
1124         if (si->dfs[t] < si->dfs[nnode])
1125           si->dfs[n] = si->dfs[t];
1126       }
1127     }
1128
1129   /* See if any components have been identified.  */
1130   if (si->dfs[n] == my_dfs)
1131     {
1132       if (VEC_length (unsigned, si->scc_stack) > 0
1133           && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1134         {
1135           bitmap scc = BITMAP_ALLOC (NULL);
1136           bool have_ref_node = n >= FIRST_REF_NODE;
1137           unsigned int lowest_node;
1138           bitmap_iterator bi;
1139
1140           bitmap_set_bit (scc, n);
1141
1142           while (VEC_length (unsigned, si->scc_stack) != 0
1143                  && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1144             {
1145               unsigned int w = VEC_pop (unsigned, si->scc_stack);
1146
1147               bitmap_set_bit (scc, w);
1148               if (w >= FIRST_REF_NODE)
1149                 have_ref_node = true;
1150             }
1151
1152           lowest_node = bitmap_first_set_bit (scc);
1153           gcc_assert (lowest_node < FIRST_REF_NODE);
1154           EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1155             {
1156               if (i < FIRST_REF_NODE)
1157                 {
1158                   /* Mark this node for collapsing.  */
1159                   if (unite (lowest_node, i))
1160                     unify_nodes (graph, lowest_node, i, false);
1161                 }
1162               else
1163                 {
1164                   unite (lowest_node, i);
1165                   graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1166                 }
1167             }
1168         }
1169       SET_BIT (si->roots, n);
1170     }
1171   else
1172     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1173 }
1174
1175 /* Unify node FROM into node TO, updating the changed count if
1176    necessary when UPDATE_CHANGED is true.  */
1177
1178 static void
1179 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1180              bool update_changed)
1181 {
1182
1183   gcc_assert (to != from && find (to) == to);
1184   if (dump_file && (dump_flags & TDF_DETAILS))
1185     fprintf (dump_file, "Unifying %s to %s\n",
1186              get_varinfo (from)->name,
1187              get_varinfo (to)->name);
1188
1189   if (update_changed)
1190     stats.unified_vars_dynamic++;
1191   else
1192     stats.unified_vars_static++;
1193
1194   merge_graph_nodes (graph, to, from);
1195   merge_node_constraints (graph, to, from);
1196
1197   if (update_changed && TEST_BIT (changed, from))
1198     {
1199       RESET_BIT (changed, from);
1200       if (!TEST_BIT (changed, to))
1201         SET_BIT (changed, to);
1202       else
1203         {
1204           gcc_assert (changed_count > 0);
1205           changed_count--;
1206         }
1207     }
1208
1209   /* If the solution changes because of the merging, we need to mark
1210      the variable as changed.  */
1211   if (bitmap_ior_into (get_varinfo (to)->solution,
1212                        get_varinfo (from)->solution))
1213     {
1214       if (update_changed && !TEST_BIT (changed, to))
1215         {
1216           SET_BIT (changed, to);
1217           changed_count++;
1218         }
1219     }
1220
1221   BITMAP_FREE (get_varinfo (from)->solution);
1222   BITMAP_FREE (get_varinfo (from)->oldsolution);
1223
1224   if (stats.iterations > 0)
1225     {
1226       BITMAP_FREE (get_varinfo (to)->oldsolution);
1227       get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1228     }
1229
1230   if (valid_graph_edge (graph, to, to))
1231     {
1232       if (graph->succs[to])
1233         bitmap_clear_bit (graph->succs[to], to);
1234     }
1235 }
1236
1237 /* Information needed to compute the topological ordering of a graph.  */
1238
1239 struct topo_info
1240 {
1241   /* sbitmap of visited nodes.  */
1242   sbitmap visited;
1243   /* Array that stores the topological order of the graph, *in
1244      reverse*.  */
1245   VEC(unsigned,heap) *topo_order;
1246 };
1247
1248
1249 /* Initialize and return a topological info structure.  */
1250
1251 static struct topo_info *
1252 init_topo_info (void)
1253 {
1254   size_t size = VEC_length (varinfo_t, varmap);
1255   struct topo_info *ti = XNEW (struct topo_info);
1256   ti->visited = sbitmap_alloc (size);
1257   sbitmap_zero (ti->visited);
1258   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1259   return ti;
1260 }
1261
1262
1263 /* Free the topological sort info pointed to by TI.  */
1264
1265 static void
1266 free_topo_info (struct topo_info *ti)
1267 {
1268   sbitmap_free (ti->visited);
1269   VEC_free (unsigned, heap, ti->topo_order);
1270   free (ti);
1271 }
1272
1273 /* Visit the graph in topological order, and store the order in the
1274    topo_info structure.  */
1275
1276 static void
1277 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1278             unsigned int n)
1279 {
1280   bitmap_iterator bi;
1281   unsigned int j;
1282
1283   SET_BIT (ti->visited, n);
1284
1285   if (graph->succs[n])
1286     EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1287       {
1288         if (!TEST_BIT (ti->visited, j))
1289           topo_visit (graph, ti, j);
1290       }
1291
1292   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1293 }
1294
1295 /* Return true if variable N + OFFSET is a legal field of N.  */
1296
1297 static bool
1298 type_safe (unsigned int n, unsigned HOST_WIDE_INT *offset)
1299 {
1300   varinfo_t ninfo = get_varinfo (n);
1301
1302   /* For things we've globbed to single variables, any offset into the
1303      variable acts like the entire variable, so that it becomes offset
1304      0.  */
1305   if (ninfo->is_special_var
1306       || ninfo->is_artificial_var
1307       || ninfo->is_unknown_size_var)
1308     {
1309       *offset = 0;
1310       return true;
1311     }
1312   return (get_varinfo (n)->offset + *offset) < get_varinfo (n)->fullsize;
1313 }
1314
1315 /* Process a constraint C that represents *x = &y.  */
1316
1317 static void
1318 do_da_constraint (constraint_graph_t graph ATTRIBUTE_UNUSED,
1319                   constraint_t c, bitmap delta)
1320 {
1321   unsigned int rhs = c->rhs.var;
1322   unsigned int j;
1323   bitmap_iterator bi;
1324
1325   /* For each member j of Delta (Sol(x)), add x to Sol(j)  */
1326   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1327     {
1328       unsigned HOST_WIDE_INT offset = c->lhs.offset;
1329       if (type_safe (j, &offset) && !(get_varinfo (j)->is_special_var))
1330         {
1331         /* *x != NULL && *x != ANYTHING*/
1332           varinfo_t v;
1333           unsigned int t;
1334           bitmap sol;
1335           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + offset;
1336
1337           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1338           if (!v)
1339             continue;
1340           t = find (v->id);
1341           sol = get_varinfo (t)->solution;
1342           if (!bitmap_bit_p (sol, rhs))
1343             {
1344               bitmap_set_bit (sol, rhs);
1345               if (!TEST_BIT (changed, t))
1346                 {
1347                   SET_BIT (changed, t);
1348                   changed_count++;
1349                 }
1350             }
1351         }
1352       else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1353         fprintf (dump_file, "Untypesafe usage in do_da_constraint.\n");
1354
1355     }
1356 }
1357
1358 /* Process a constraint C that represents x = *y, using DELTA as the
1359    starting solution.  */
1360
1361 static void
1362 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1363                   bitmap delta)
1364 {
1365   unsigned int lhs = find (c->lhs.var);
1366   bool flag = false;
1367   bitmap sol = get_varinfo (lhs)->solution;
1368   unsigned int j;
1369   bitmap_iterator bi;
1370
1371  if (bitmap_bit_p (delta, anything_id))
1372    {
1373      flag = !bitmap_bit_p (sol, anything_id);
1374      if (flag)
1375        bitmap_set_bit (sol, anything_id);
1376      goto done;
1377    }
1378   /* For each variable j in delta (Sol(y)), add
1379      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1380   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1381     {
1382       unsigned HOST_WIDE_INT roffset = c->rhs.offset;
1383       if (type_safe (j, &roffset))
1384         {
1385           varinfo_t v;
1386           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + roffset;
1387           unsigned int t;
1388
1389           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1390           if (!v)
1391             continue;
1392           t = find (v->id);
1393
1394           /* Adding edges from the special vars is pointless.
1395              They don't have sets that can change.  */
1396           if (get_varinfo (t) ->is_special_var)
1397             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1398           else if (add_graph_edge (graph, lhs, t))
1399             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1400         }
1401       else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1402         fprintf (dump_file, "Untypesafe usage in do_sd_constraint\n");
1403
1404     }
1405
1406 done:
1407   /* If the LHS solution changed, mark the var as changed.  */
1408   if (flag)
1409     {
1410       get_varinfo (lhs)->solution = sol;
1411       if (!TEST_BIT (changed, lhs))
1412         {
1413           SET_BIT (changed, lhs);
1414           changed_count++;
1415         }
1416     }
1417 }
1418
1419 /* Process a constraint C that represents *x = y.  */
1420
1421 static void
1422 do_ds_constraint (constraint_t c, bitmap delta)
1423 {
1424   unsigned int rhs = find (c->rhs.var);
1425   unsigned HOST_WIDE_INT roff = c->rhs.offset;
1426   bitmap sol = get_varinfo (rhs)->solution;
1427   unsigned int j;
1428   bitmap_iterator bi;
1429
1430  if (bitmap_bit_p (sol, anything_id))
1431    {
1432      EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1433        {
1434          varinfo_t jvi = get_varinfo (j);
1435          unsigned int t;
1436          unsigned int loff = c->lhs.offset;
1437          unsigned HOST_WIDE_INT fieldoffset = jvi->offset + loff;
1438          varinfo_t v;
1439
1440          v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1441          if (!v)
1442            continue;
1443          t = find (v->id);
1444
1445          if (!bitmap_bit_p (get_varinfo (t)->solution, anything_id))
1446            {
1447              bitmap_set_bit (get_varinfo (t)->solution, anything_id);
1448              if (!TEST_BIT (changed, t))
1449                {
1450                  SET_BIT (changed, t);
1451                  changed_count++;
1452                }
1453            }
1454        }
1455      return;
1456    }
1457
1458   /* For each member j of delta (Sol(x)), add an edge from y to j and
1459      union Sol(y) into Sol(j) */
1460   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1461     {
1462       unsigned HOST_WIDE_INT loff = c->lhs.offset;
1463       if (type_safe (j, &loff) && !(get_varinfo (j)->is_special_var))
1464         {
1465           varinfo_t v;
1466           unsigned int t;
1467           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + loff;
1468           bitmap tmp;
1469
1470           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1471           if (!v)
1472             continue;
1473           t = find (v->id);
1474           tmp = get_varinfo (t)->solution;
1475
1476           if (set_union_with_increment (tmp, sol, roff))
1477             {
1478               get_varinfo (t)->solution = tmp;
1479               if (t == rhs)
1480                 sol = get_varinfo (rhs)->solution;
1481               if (!TEST_BIT (changed, t))
1482                 {
1483                   SET_BIT (changed, t);
1484                   changed_count++;
1485                 }
1486             }
1487         }
1488       else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1489         fprintf (dump_file, "Untypesafe usage in do_ds_constraint\n");
1490     }
1491 }
1492
1493 /* Handle a non-simple (simple meaning requires no iteration),
1494    constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved).  */
1495
1496 static void
1497 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1498 {
1499   if (c->lhs.type == DEREF)
1500     {
1501       if (c->rhs.type == ADDRESSOF)
1502         {
1503           /* *x = &y */
1504           do_da_constraint (graph, c, delta);
1505         }
1506       else
1507         {
1508           /* *x = y */
1509           do_ds_constraint (c, delta);
1510         }
1511     }
1512   else if (c->rhs.type == DEREF)
1513     {
1514       /* x = *y */
1515       if (!(get_varinfo (c->lhs.var)->is_special_var))
1516         do_sd_constraint (graph, c, delta);
1517     }
1518   else
1519     {
1520       bitmap tmp;
1521       bitmap solution;
1522       bool flag = false;
1523       unsigned int t;
1524
1525       gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1526       t = find (c->rhs.var);
1527       solution = get_varinfo (t)->solution;
1528       t = find (c->lhs.var);
1529       tmp = get_varinfo (t)->solution;
1530
1531       flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1532
1533       if (flag)
1534         {
1535           get_varinfo (t)->solution = tmp;
1536           if (!TEST_BIT (changed, t))
1537             {
1538               SET_BIT (changed, t);
1539               changed_count++;
1540             }
1541         }
1542     }
1543 }
1544
1545 /* Initialize and return a new SCC info structure.  */
1546
1547 static struct scc_info *
1548 init_scc_info (size_t size)
1549 {
1550   struct scc_info *si = XNEW (struct scc_info);
1551   size_t i;
1552
1553   si->current_index = 0;
1554   si->visited = sbitmap_alloc (size);
1555   sbitmap_zero (si->visited);
1556   si->roots = sbitmap_alloc (size);
1557   sbitmap_zero (si->roots);
1558   si->node_mapping = XNEWVEC (unsigned int, size);
1559   si->dfs = XCNEWVEC (unsigned int, size);
1560
1561   for (i = 0; i < size; i++)
1562     si->node_mapping[i] = i;
1563
1564   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1565   return si;
1566 }
1567
1568 /* Free an SCC info structure pointed to by SI */
1569
1570 static void
1571 free_scc_info (struct scc_info *si)
1572 {
1573   sbitmap_free (si->visited);
1574   sbitmap_free (si->roots);
1575   free (si->node_mapping);
1576   free (si->dfs);
1577   VEC_free (unsigned, heap, si->scc_stack);
1578   free (si);
1579 }
1580
1581
1582 /* Find indirect cycles in GRAPH that occur, using strongly connected
1583    components, and note them in the indirect cycles map.
1584
1585    This technique comes from Ben Hardekopf and Calvin Lin,
1586    "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1587    Lines of Code", submitted to PLDI 2007.  */
1588
1589 static void
1590 find_indirect_cycles (constraint_graph_t graph)
1591 {
1592   unsigned int i;
1593   unsigned int size = graph->size;
1594   struct scc_info *si = init_scc_info (size);
1595
1596   for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1597     if (!TEST_BIT (si->visited, i) && find (i) == i)
1598       scc_visit (graph, si, i);
1599
1600   free_scc_info (si);
1601 }
1602
1603 /* Compute a topological ordering for GRAPH, and store the result in the
1604    topo_info structure TI.  */
1605
1606 static void
1607 compute_topo_order (constraint_graph_t graph,
1608                     struct topo_info *ti)
1609 {
1610   unsigned int i;
1611   unsigned int size = VEC_length (varinfo_t, varmap);
1612
1613   for (i = 0; i != size; ++i)
1614     if (!TEST_BIT (ti->visited, i) && find (i) == i)
1615       topo_visit (graph, ti, i);
1616 }
1617
1618 /* Perform offline variable substitution.
1619
1620    This is a linear time way of identifying variables that must have
1621    equivalent points-to sets, including those caused by static cycles,
1622    and single entry subgraphs, in the constraint graph.
1623
1624    The technique is described in "Off-line variable substitution for
1625    scaling points-to analysis" by Atanas Rountev and Satish Chandra,
1626    in "ACM SIGPLAN Notices" volume 35, number 5, pages 47-56.
1627
1628    There is an optimal way to do this involving hash based value
1629    numbering, once the technique is published i will implement it
1630    here.  
1631
1632    The general method of finding equivalence classes is as follows:
1633    Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1634    Add fake nodes (ADDRESS nodes) and edges for a = &b constraints.
1635    Initialize all non-REF/ADDRESS nodes to be direct nodes
1636    For each SCC in the predecessor graph:
1637       for each member (x) of the SCC
1638          if x is not a direct node:
1639            set rootnode(SCC) to be not a direct node
1640          collapse node x into rootnode(SCC).
1641       if rootnode(SCC) is not a direct node:
1642         label rootnode(SCC) with a new equivalence class
1643       else:
1644         if all labeled predecessors of rootnode(SCC) have the same
1645         label:
1646           label rootnode(SCC) with this label
1647         else:
1648           label rootnode(SCC) with a new equivalence class
1649
1650    All direct nodes with the same equivalence class can be replaced
1651    with a single representative node.
1652    All unlabeled nodes (label == 0) are not pointers and all edges
1653    involving them can be eliminated.
1654    We perform these optimizations during move_complex_constraints.
1655 */
1656
1657 static int equivalence_class;
1658
1659 /* Recursive routine to find strongly connected components in GRAPH,
1660    and label it's nodes with equivalence classes.
1661    This is used during variable substitution to find cycles involving
1662    the regular or implicit predecessors, and label them as equivalent.
1663    The SCC finding algorithm used is the same as that for scc_visit.  */
1664
1665 static void
1666 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1667 {
1668   unsigned int i;
1669   bitmap_iterator bi;
1670   unsigned int my_dfs;
1671
1672   gcc_assert (si->node_mapping[n] == n);
1673   SET_BIT (si->visited, n);
1674   si->dfs[n] = si->current_index ++;
1675   my_dfs = si->dfs[n];
1676
1677   /* Visit all the successors.  */
1678   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1679     {
1680       unsigned int w = si->node_mapping[i];
1681
1682       if (TEST_BIT (si->roots, w))
1683         continue;
1684
1685       if (!TEST_BIT (si->visited, w))
1686         label_visit (graph, si, w);
1687       {
1688         unsigned int t = si->node_mapping[w];
1689         unsigned int nnode = si->node_mapping[n];
1690         gcc_assert (nnode == n);
1691
1692         if (si->dfs[t] < si->dfs[nnode])
1693           si->dfs[n] = si->dfs[t];
1694       }
1695     }
1696
1697   /* Visit all the implicit predecessors.  */
1698   EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
1699     {
1700       unsigned int w = si->node_mapping[i];
1701
1702       if (TEST_BIT (si->roots, w))
1703         continue;
1704
1705       if (!TEST_BIT (si->visited, w))
1706         label_visit (graph, si, w);
1707       {
1708         unsigned int t = si->node_mapping[w];
1709         unsigned int nnode = si->node_mapping[n];
1710         gcc_assert (nnode == n);
1711
1712         if (si->dfs[t] < si->dfs[nnode])
1713           si->dfs[n] = si->dfs[t];
1714       }
1715     }
1716
1717   /* See if any components have been identified.  */
1718   if (si->dfs[n] == my_dfs)
1719     {
1720       while (VEC_length (unsigned, si->scc_stack) != 0
1721              && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1722         {
1723           unsigned int w = VEC_pop (unsigned, si->scc_stack);
1724           si->node_mapping[w] = n;
1725
1726           if (!TEST_BIT (graph->direct_nodes, w))
1727             RESET_BIT (graph->direct_nodes, n);
1728         }
1729       SET_BIT (si->roots, n);
1730
1731       if (!TEST_BIT (graph->direct_nodes, n))
1732         {
1733           graph->label[n] = equivalence_class++;
1734         }
1735       else
1736         {
1737           unsigned int size = 0;
1738           unsigned int firstlabel = ~0;
1739
1740           EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1741             {
1742               unsigned int j = si->node_mapping[i];
1743
1744               if (j == n || graph->label[j] == 0)
1745                 continue;
1746
1747               if (firstlabel == (unsigned int)~0)
1748                 {
1749                   firstlabel = graph->label[j];
1750                   size++;
1751                 }
1752               else if (graph->label[j] != firstlabel)
1753                 size++;
1754             }
1755
1756           if (size == 0)
1757             graph->label[n] = 0;
1758           else if (size == 1)
1759             graph->label[n] = firstlabel;
1760           else
1761             graph->label[n] = equivalence_class++;
1762         }
1763     }
1764   else
1765     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1766 }
1767
1768 /* Perform offline variable substitution, discovering equivalence
1769    classes, and eliminating non-pointer variables.  */
1770
1771 static struct scc_info *
1772 perform_var_substitution (constraint_graph_t graph)
1773 {
1774   unsigned int i;
1775   unsigned int size = graph->size;
1776   struct scc_info *si = init_scc_info (size);
1777
1778   bitmap_obstack_initialize (&iteration_obstack);
1779   equivalence_class = 0;
1780
1781   /* We only need to visit the non-address nodes for labeling
1782      purposes, as the address nodes will never have any predecessors,
1783      because &x never appears on the LHS of a constraint.  */
1784   for (i = 0; i < LAST_REF_NODE; i++)
1785     if (!TEST_BIT (si->visited, si->node_mapping[i]))
1786       label_visit (graph, si, si->node_mapping[i]);
1787
1788   if (dump_file && (dump_flags & TDF_DETAILS))
1789     for (i = 0; i < FIRST_REF_NODE; i++)
1790       {
1791         bool direct_node = TEST_BIT (graph->direct_nodes, i);
1792         fprintf (dump_file,
1793                  "Equivalence class for %s node id %d:%s is %d\n",
1794                  direct_node ? "Direct node" : "Indirect node", i,
1795                  get_varinfo (i)->name,
1796                  graph->label[si->node_mapping[i]]);
1797       }
1798
1799   /* Quickly eliminate our non-pointer variables.  */
1800
1801   for (i = 0; i < FIRST_REF_NODE; i++)
1802     {
1803       unsigned int node = si->node_mapping[i];
1804
1805       if (graph->label[node] == 0 && TEST_BIT (graph->direct_nodes, node))
1806         {
1807           if (dump_file && (dump_flags & TDF_DETAILS))
1808             fprintf (dump_file,
1809                      "%s is a non-pointer variable, eliminating edges.\n",
1810                      get_varinfo (node)->name);
1811           stats.nonpointer_vars++;
1812           clear_edges_for_node (graph, node);
1813         }
1814     }
1815   return si;
1816 }
1817
1818 /* Free information that was only necessary for variable
1819    substitution.  */
1820
1821 static void
1822 free_var_substitution_info (struct scc_info *si)
1823 {
1824   free_scc_info (si);
1825   free (graph->label);
1826   free (graph->eq_rep);
1827   sbitmap_free (graph->direct_nodes);
1828   bitmap_obstack_release (&iteration_obstack);
1829 }
1830
1831 /* Return an existing node that is equivalent to NODE, which has
1832    equivalence class LABEL, if one exists.  Return NODE otherwise.  */
1833
1834 static unsigned int
1835 find_equivalent_node (constraint_graph_t graph,
1836                       unsigned int node, unsigned int label)
1837 {
1838   /* If the address version of this variable is unused, we can
1839      substitute it for anything else with the same label.
1840      Otherwise, we know the pointers are equivalent, but not the
1841      locations.  */
1842
1843   if (graph->label[FIRST_ADDR_NODE + node] == 0)
1844     {
1845       gcc_assert (label < graph->size);
1846
1847       if (graph->eq_rep[label] != -1)
1848         {
1849           /* Unify the two variables since we know they are equivalent.  */
1850           if (unite (graph->eq_rep[label], node))
1851             unify_nodes (graph, graph->eq_rep[label], node, false);
1852           return graph->eq_rep[label];
1853         }
1854       else
1855         {
1856           graph->eq_rep[label] = node;
1857         }
1858     }
1859   return node;
1860 }
1861
1862 /* Move complex constraints to the appropriate nodes, and collapse
1863    variables we've discovered are equivalent during variable
1864    substitution.  SI is the SCC_INFO that is the result of
1865    perform_variable_substitution.  */
1866
1867 static void
1868 move_complex_constraints (constraint_graph_t graph,
1869                           struct scc_info *si)
1870 {
1871   int i;
1872   unsigned int j;
1873   constraint_t c;
1874
1875   for (j = 0; j < graph->size; j++)
1876     gcc_assert (find (j) == j);
1877
1878   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1879     {
1880       struct constraint_expr lhs = c->lhs;
1881       struct constraint_expr rhs = c->rhs;
1882       unsigned int lhsvar = find (get_varinfo_fc (lhs.var)->id);
1883       unsigned int rhsvar = find (get_varinfo_fc (rhs.var)->id);
1884       unsigned int lhsnode, rhsnode;
1885       unsigned int lhslabel, rhslabel;
1886
1887       lhsnode = si->node_mapping[lhsvar];
1888       rhsnode = si->node_mapping[rhsvar];
1889       lhslabel = graph->label[lhsnode];
1890       rhslabel = graph->label[rhsnode];
1891
1892       /* See if it is really a non-pointer variable, and if so, ignore
1893          the constraint.  */
1894       if (lhslabel == 0)
1895         {
1896           if (!TEST_BIT (graph->direct_nodes, lhsnode))
1897             lhslabel = graph->label[lhsnode] = equivalence_class++;
1898           else
1899             {
1900               if (dump_file && (dump_flags & TDF_DETAILS))
1901                 {
1902
1903                   fprintf (dump_file, "%s is a non-pointer variable,"
1904                            "ignoring constraint:",
1905                            get_varinfo (lhs.var)->name);
1906                   dump_constraint (dump_file, c);
1907                 }
1908               VEC_replace (constraint_t, constraints, i, NULL);
1909               continue;
1910             }
1911         }
1912
1913       if (rhslabel == 0)
1914         {
1915           if (!TEST_BIT (graph->direct_nodes, rhsnode))
1916             rhslabel = graph->label[rhsnode] = equivalence_class++;
1917           else
1918             {
1919               if (dump_file && (dump_flags & TDF_DETAILS))
1920                 {
1921
1922                   fprintf (dump_file, "%s is a non-pointer variable,"
1923                            "ignoring constraint:",
1924                            get_varinfo (rhs.var)->name);
1925                   dump_constraint (dump_file, c);
1926                 }
1927               VEC_replace (constraint_t, constraints, i, NULL);
1928               continue;
1929             }
1930         }
1931
1932       lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
1933       rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
1934       c->lhs.var = lhsvar;
1935       c->rhs.var = rhsvar;
1936
1937       if (lhs.type == DEREF)
1938         {
1939           if (rhs.type == ADDRESSOF || rhsvar > anything_id)
1940             insert_into_complex (graph, lhsvar, c);
1941         }
1942       else if (rhs.type == DEREF)
1943         {
1944           if (!(get_varinfo (lhsvar)->is_special_var))
1945             insert_into_complex (graph, rhsvar, c);
1946         }
1947       else if (rhs.type != ADDRESSOF && lhsvar > anything_id
1948                && (lhs.offset != 0 || rhs.offset != 0))
1949         {
1950           insert_into_complex (graph, rhsvar, c);
1951         }
1952
1953     }
1954 }
1955
1956 /* Eliminate indirect cycles involving NODE.  Return true if NODE was
1957    part of an SCC, false otherwise.  */
1958
1959 static bool
1960 eliminate_indirect_cycles (unsigned int node)
1961 {
1962   if (graph->indirect_cycles[node] != -1
1963       && !bitmap_empty_p (get_varinfo (node)->solution))
1964     {
1965       unsigned int i;
1966       VEC(unsigned,heap) *queue = NULL;
1967       int queuepos;
1968       unsigned int to = find (graph->indirect_cycles[node]);
1969       bitmap_iterator bi;
1970
1971       /* We can't touch the solution set and call unify_nodes
1972          at the same time, because unify_nodes is going to do
1973          bitmap unions into it. */
1974
1975       EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
1976         {
1977           if (find (i) == i && i != to)
1978             {
1979               if (unite (to, i))
1980                 VEC_safe_push (unsigned, heap, queue, i);
1981             }
1982         }
1983
1984       for (queuepos = 0;
1985            VEC_iterate (unsigned, queue, queuepos, i);
1986            queuepos++)
1987         {
1988           unify_nodes (graph, to, i, true);
1989         }
1990       VEC_free (unsigned, heap, queue);
1991       return true;
1992     }
1993   return false;
1994 }
1995
1996 /* Solve the constraint graph GRAPH using our worklist solver.
1997    This is based on the PW* family of solvers from the "Efficient Field
1998    Sensitive Pointer Analysis for C" paper.
1999    It works by iterating over all the graph nodes, processing the complex
2000    constraints and propagating the copy constraints, until everything stops
2001    changed.  This corresponds to steps 6-8 in the solving list given above.  */
2002
2003 static void
2004 solve_graph (constraint_graph_t graph)
2005 {
2006   unsigned int size = VEC_length (varinfo_t, varmap);
2007   unsigned int i;
2008   bitmap pts;
2009
2010   changed_count = 0;
2011   changed = sbitmap_alloc (size);
2012   sbitmap_zero (changed);
2013
2014   /* Mark all initial non-collapsed nodes as changed.  */
2015   for (i = 0; i < size; i++)
2016     {
2017       varinfo_t ivi = get_varinfo (i);
2018       if (find (i) == i && !bitmap_empty_p (ivi->solution)
2019           && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2020               || VEC_length (constraint_t, graph->complex[i]) > 0))
2021         {
2022           SET_BIT (changed, i);
2023           changed_count++;
2024         }
2025     }
2026
2027   /* Allocate a bitmap to be used to store the changed bits.  */
2028   pts = BITMAP_ALLOC (&pta_obstack);
2029
2030   while (changed_count > 0)
2031     {
2032       unsigned int i;
2033       struct topo_info *ti = init_topo_info ();
2034       stats.iterations++;
2035
2036       bitmap_obstack_initialize (&iteration_obstack);
2037
2038       compute_topo_order (graph, ti);
2039
2040       while (VEC_length (unsigned, ti->topo_order) != 0)
2041         {
2042
2043           i = VEC_pop (unsigned, ti->topo_order);
2044
2045           /* If this variable is not a representative, skip it.  */
2046           if (find (i) != i)
2047             continue;
2048
2049           /* In certain indirect cycle cases, we may merge this
2050              variable to another.  */
2051           if (eliminate_indirect_cycles (i) && find (i) != i)
2052             continue;
2053
2054           /* If the node has changed, we need to process the
2055              complex constraints and outgoing edges again.  */
2056           if (TEST_BIT (changed, i))
2057             {
2058               unsigned int j;
2059               constraint_t c;
2060               bitmap solution;
2061               VEC(constraint_t,heap) *complex = graph->complex[i];
2062               bool solution_empty;
2063
2064               RESET_BIT (changed, i);
2065               changed_count--;
2066
2067               /* Compute the changed set of solution bits.  */
2068               bitmap_and_compl (pts, get_varinfo (i)->solution,
2069                                 get_varinfo (i)->oldsolution);
2070
2071               if (bitmap_empty_p (pts))
2072                 continue;
2073
2074               bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2075
2076               solution = get_varinfo (i)->solution;
2077               solution_empty = bitmap_empty_p (solution);
2078
2079               /* Process the complex constraints */
2080               for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2081                 {
2082                   /* The only complex constraint that can change our
2083                      solution to non-empty, given an empty solution,
2084                      is a constraint where the lhs side is receiving
2085                      some set from elsewhere.  */
2086                   if (!solution_empty || c->lhs.type != DEREF)
2087                     do_complex_constraint (graph, c, pts);
2088                 }
2089
2090               solution_empty = bitmap_empty_p (solution);
2091
2092               if (!solution_empty)
2093                 {
2094                   bitmap_iterator bi;
2095
2096                   /* Propagate solution to all successors.  */
2097                   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2098                                                 0, j, bi)
2099                     {
2100                       bitmap tmp;
2101                       bool flag;
2102
2103                       unsigned int to = find (j);
2104                       tmp = get_varinfo (to)->solution;
2105                       flag = false;
2106
2107                       /* Don't try to propagate to ourselves.  */
2108                       if (to == i)
2109                         continue;
2110
2111                       flag = set_union_with_increment (tmp, pts, 0);
2112
2113                       if (flag)
2114                         {
2115                           get_varinfo (to)->solution = tmp;
2116                           if (!TEST_BIT (changed, to))
2117                             {
2118                               SET_BIT (changed, to);
2119                               changed_count++;
2120                             }
2121                         }
2122                     }
2123                 }
2124             }
2125         }
2126       free_topo_info (ti);
2127       bitmap_obstack_release (&iteration_obstack);
2128     }
2129
2130   BITMAP_FREE (pts);
2131   sbitmap_free (changed);
2132   bitmap_obstack_release (&oldpta_obstack);
2133 }
2134
2135 /* Map from trees to variable infos.  */
2136 static struct pointer_map_t *vi_for_tree;
2137
2138
2139 /* Insert ID as the variable id for tree T in the vi_for_tree map.  */
2140
2141 static void
2142 insert_vi_for_tree (tree t, varinfo_t vi)
2143 {
2144   void **slot = pointer_map_insert (vi_for_tree, t);
2145   gcc_assert (vi);
2146   gcc_assert (*slot == NULL);
2147   *slot = vi;
2148 }
2149
2150 /* Find the variable info for tree T in VI_FOR_TREE.  If T does not
2151    exist in the map, return NULL, otherwise, return the varinfo we found.  */
2152
2153 static varinfo_t
2154 lookup_vi_for_tree (tree t)
2155 {
2156   void **slot = pointer_map_contains (vi_for_tree, t);
2157   if (slot == NULL)
2158     return NULL;
2159
2160   return (varinfo_t) *slot;
2161 }
2162
2163 /* Return a printable name for DECL  */
2164
2165 static const char *
2166 alias_get_name (tree decl)
2167 {
2168   const char *res = get_name (decl);
2169   char *temp;
2170   int num_printed = 0;
2171
2172   if (res != NULL)
2173     return res;
2174
2175   res = "NULL";
2176   if (!dump_file)
2177     return res;
2178
2179   if (TREE_CODE (decl) == SSA_NAME)
2180     {
2181       num_printed = asprintf (&temp, "%s_%u",
2182                               alias_get_name (SSA_NAME_VAR (decl)),
2183                               SSA_NAME_VERSION (decl));
2184     }
2185   else if (DECL_P (decl))
2186     {
2187       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2188     }
2189   if (num_printed > 0)
2190     {
2191       res = ggc_strdup (temp);
2192       free (temp);
2193     }
2194   return res;
2195 }
2196
2197 /* Find the variable id for tree T in the map.
2198    If T doesn't exist in the map, create an entry for it and return it.  */
2199
2200 static varinfo_t
2201 get_vi_for_tree (tree t)
2202 {
2203   void **slot = pointer_map_contains (vi_for_tree, t);
2204   if (slot == NULL)
2205     return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2206
2207   return (varinfo_t) *slot;
2208 }
2209
2210 /* Get a constraint expression from an SSA_VAR_P node.  */
2211
2212 static struct constraint_expr
2213 get_constraint_exp_from_ssa_var (tree t)
2214 {
2215   struct constraint_expr cexpr;
2216
2217   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2218
2219   /* For parameters, get at the points-to set for the actual parm
2220      decl.  */
2221   if (TREE_CODE (t) == SSA_NAME
2222       && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2223       && SSA_NAME_IS_DEFAULT_DEF (t))
2224     return get_constraint_exp_from_ssa_var (SSA_NAME_VAR (t));
2225
2226   cexpr.type = SCALAR;
2227
2228   cexpr.var = get_vi_for_tree (t)->id;
2229   /* If we determine the result is "anything", and we know this is readonly,
2230      say it points to readonly memory instead.  */
2231   if (cexpr.var == anything_id && TREE_READONLY (t))
2232     {
2233       cexpr.type = ADDRESSOF;
2234       cexpr.var = readonly_id;
2235     }
2236
2237   cexpr.offset = 0;
2238   return cexpr;
2239 }
2240
2241 /* Process a completed constraint T, and add it to the constraint
2242    list.  */
2243
2244 static void
2245 process_constraint (constraint_t t)
2246 {
2247   struct constraint_expr rhs = t->rhs;
2248   struct constraint_expr lhs = t->lhs;
2249
2250   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2251   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2252
2253   if (lhs.type == DEREF)
2254     get_varinfo (lhs.var)->directly_dereferenced = true;
2255   if (rhs.type == DEREF)
2256     get_varinfo (rhs.var)->directly_dereferenced = true;
2257
2258   if (!use_field_sensitive)
2259     {
2260       t->rhs.offset = 0;
2261       t->lhs.offset = 0;
2262     }
2263
2264   /* ANYTHING == ANYTHING is pointless.  */
2265   if (lhs.var == anything_id && rhs.var == anything_id)
2266     return;
2267
2268   /* If we have &ANYTHING = something, convert to SOMETHING = &ANYTHING) */
2269   else if (lhs.var == anything_id && lhs.type == ADDRESSOF)
2270     {
2271       rhs = t->lhs;
2272       t->lhs = t->rhs;
2273       t->rhs = rhs;
2274       process_constraint (t);
2275     }
2276   /* This can happen in our IR with things like n->a = *p */
2277   else if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2278     {
2279       /* Split into tmp = *rhs, *lhs = tmp */
2280       tree rhsdecl = get_varinfo (rhs.var)->decl;
2281       tree pointertype = TREE_TYPE (rhsdecl);
2282       tree pointedtotype = TREE_TYPE (pointertype);
2283       tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
2284       struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2285
2286       /* If this is an aggregate of known size, we should have passed
2287          this off to do_structure_copy, and it should have broken it
2288          up.  */
2289       gcc_assert (!AGGREGATE_TYPE_P (pointedtotype)
2290                   || get_varinfo (rhs.var)->is_unknown_size_var);
2291
2292       process_constraint (new_constraint (tmplhs, rhs));
2293       process_constraint (new_constraint (lhs, tmplhs));
2294     }
2295   else
2296     {
2297       gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2298       VEC_safe_push (constraint_t, heap, constraints, t);
2299     }
2300 }
2301
2302 /* Return true if T is a variable of a type that could contain
2303    pointers.  */
2304
2305 static bool
2306 could_have_pointers (tree t)
2307 {
2308   tree type = TREE_TYPE (t);
2309
2310   if (POINTER_TYPE_P (type)
2311       || AGGREGATE_TYPE_P (type)
2312       || TREE_CODE (type) == COMPLEX_TYPE)
2313     return true;
2314
2315   return false;
2316 }
2317
2318 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2319    structure.  */
2320
2321 static unsigned HOST_WIDE_INT
2322 bitpos_of_field (const tree fdecl)
2323 {
2324
2325   if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
2326       || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
2327     return -1;
2328
2329   return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8)
2330          + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
2331 }
2332
2333
2334 /* Return true if an access to [ACCESSPOS, ACCESSSIZE]
2335    overlaps with a field at [FIELDPOS, FIELDSIZE] */
2336
2337 static bool
2338 offset_overlaps_with_access (const unsigned HOST_WIDE_INT fieldpos,
2339                              const unsigned HOST_WIDE_INT fieldsize,
2340                              const unsigned HOST_WIDE_INT accesspos,
2341                              const unsigned HOST_WIDE_INT accesssize)
2342 {
2343   if (fieldpos == accesspos && fieldsize == accesssize)
2344     return true;
2345   if (accesspos >= fieldpos && accesspos < (fieldpos + fieldsize))
2346     return true;
2347   if (accesspos < fieldpos && (accesspos + accesssize > fieldpos))
2348     return true;
2349
2350   return false;
2351 }
2352
2353 /* Given a COMPONENT_REF T, return the constraint_expr for it.  */
2354
2355 static void
2356 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results)
2357 {
2358   tree orig_t = t;
2359   HOST_WIDE_INT bitsize = -1;
2360   HOST_WIDE_INT bitmaxsize = -1;
2361   HOST_WIDE_INT bitpos;
2362   tree forzero;
2363   struct constraint_expr *result;
2364   unsigned int beforelength = VEC_length (ce_s, *results);
2365
2366   /* Some people like to do cute things like take the address of
2367      &0->a.b */
2368   forzero = t;
2369   while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2370     forzero = TREE_OPERAND (forzero, 0);
2371
2372   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2373     {
2374       struct constraint_expr temp;
2375
2376       temp.offset = 0;
2377       temp.var = integer_id;
2378       temp.type = SCALAR;
2379       VEC_safe_push (ce_s, heap, *results, &temp);
2380       return;
2381     }
2382
2383   t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2384
2385   /* String constants are readonly, so there is nothing to really do
2386      here.  */
2387   if (TREE_CODE (t) == STRING_CST)
2388     return;
2389
2390   get_constraint_for (t, results);
2391   result = VEC_last (ce_s, *results);
2392   result->offset = bitpos;
2393
2394   gcc_assert (beforelength + 1 == VEC_length (ce_s, *results));
2395
2396   /* This can also happen due to weird offsetof type macros.  */
2397   if (TREE_CODE (t) != ADDR_EXPR && result->type == ADDRESSOF)
2398     result->type = SCALAR;
2399
2400   if (result->type == SCALAR)
2401     {
2402       /* In languages like C, you can access one past the end of an
2403          array.  You aren't allowed to dereference it, so we can
2404          ignore this constraint. When we handle pointer subtraction,
2405          we may have to do something cute here.  */
2406
2407       if (result->offset < get_varinfo (result->var)->fullsize
2408           && bitmaxsize != 0)
2409         {
2410           /* It's also not true that the constraint will actually start at the
2411              right offset, it may start in some padding.  We only care about
2412              setting the constraint to the first actual field it touches, so
2413              walk to find it.  */
2414           varinfo_t curr;
2415           for (curr = get_varinfo (result->var); curr; curr = curr->next)
2416             {
2417               if (offset_overlaps_with_access (curr->offset, curr->size,
2418                                                result->offset, bitmaxsize))
2419                 {
2420                   result->var = curr->id;
2421                   break;
2422                 }
2423             }
2424           /* assert that we found *some* field there. The user couldn't be
2425              accessing *only* padding.  */
2426           /* Still the user could access one past the end of an array
2427              embedded in a struct resulting in accessing *only* padding.  */
2428           gcc_assert (curr || ref_contains_array_ref (orig_t));
2429         }
2430       else if (bitmaxsize == 0)
2431         {
2432           if (dump_file && (dump_flags & TDF_DETAILS))
2433             fprintf (dump_file, "Access to zero-sized part of variable,"
2434                      "ignoring\n");
2435         }
2436       else
2437         if (dump_file && (dump_flags & TDF_DETAILS))
2438           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
2439
2440       result->offset = 0;
2441     }
2442 }
2443
2444
2445 /* Dereference the constraint expression CONS, and return the result.
2446    DEREF (ADDRESSOF) = SCALAR
2447    DEREF (SCALAR) = DEREF
2448    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
2449    This is needed so that we can handle dereferencing DEREF constraints.  */
2450
2451 static void
2452 do_deref (VEC (ce_s, heap) **constraints)
2453 {
2454   struct constraint_expr *c;
2455   unsigned int i = 0;
2456
2457   for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
2458     {
2459       if (c->type == SCALAR)
2460         c->type = DEREF;
2461       else if (c->type == ADDRESSOF)
2462         c->type = SCALAR;
2463       else if (c->type == DEREF)
2464         {
2465           tree tmpvar = create_tmp_var_raw (ptr_type_node, "dereftmp");
2466           struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2467           process_constraint (new_constraint (tmplhs, *c));
2468           c->var = tmplhs.var;
2469         }
2470       else
2471         gcc_unreachable ();
2472     }
2473 }
2474
2475 /* Given a tree T, return the constraint expression for it.  */
2476
2477 static void
2478 get_constraint_for (tree t, VEC (ce_s, heap) **results)
2479 {
2480   struct constraint_expr temp;
2481
2482   /* x = integer is all glommed to a single variable, which doesn't
2483      point to anything by itself.  That is, of course, unless it is an
2484      integer constant being treated as a pointer, in which case, we
2485      will return that this is really the addressof anything.  This
2486      happens below, since it will fall into the default case. The only
2487      case we know something about an integer treated like a pointer is
2488      when it is the NULL pointer, and then we just say it points to
2489      NULL.  */
2490   if (TREE_CODE (t) == INTEGER_CST
2491       && !POINTER_TYPE_P (TREE_TYPE (t)))
2492     {
2493       temp.var = integer_id;
2494       temp.type = SCALAR;
2495       temp.offset = 0;
2496       VEC_safe_push (ce_s, heap, *results, &temp);
2497       return;
2498     }
2499   else if (TREE_CODE (t) == INTEGER_CST
2500            && integer_zerop (t))
2501     {
2502       temp.var = nothing_id;
2503       temp.type = ADDRESSOF;
2504       temp.offset = 0;
2505       VEC_safe_push (ce_s, heap, *results, &temp);
2506       return;
2507     }
2508
2509   switch (TREE_CODE_CLASS (TREE_CODE (t)))
2510     {
2511     case tcc_expression:
2512     case tcc_vl_exp:
2513       {
2514         switch (TREE_CODE (t))
2515           {
2516           case ADDR_EXPR:
2517             {
2518               struct constraint_expr *c;
2519               unsigned int i;
2520               tree exp = TREE_OPERAND (t, 0);
2521               tree pttype = TREE_TYPE (TREE_TYPE (t));
2522
2523               get_constraint_for (exp, results);
2524
2525               /* Make sure we capture constraints to all elements
2526                  of an array.  */
2527               if ((handled_component_p (exp)
2528                    && ref_contains_array_ref (exp))
2529                   || TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
2530                 {
2531                   struct constraint_expr *origrhs;
2532                   varinfo_t origvar;
2533                   struct constraint_expr tmp;
2534
2535                   if (VEC_length (ce_s, *results) == 0)
2536                     return;
2537
2538                   gcc_assert (VEC_length (ce_s, *results) == 1);
2539                   origrhs = VEC_last (ce_s, *results);
2540                   tmp = *origrhs;
2541                   VEC_pop (ce_s, *results);
2542                   origvar = get_varinfo (origrhs->var);
2543                   for (; origvar; origvar = origvar->next)
2544                     {
2545                       tmp.var = origvar->id;
2546                       VEC_safe_push (ce_s, heap, *results, &tmp);
2547                     }
2548                 }
2549               else if (VEC_length (ce_s, *results) == 1
2550                        && (AGGREGATE_TYPE_P (pttype)
2551                            || TREE_CODE (pttype) == COMPLEX_TYPE))
2552                 {
2553                   struct constraint_expr *origrhs;
2554                   varinfo_t origvar;
2555                   struct constraint_expr tmp;
2556
2557                   gcc_assert (VEC_length (ce_s, *results) == 1);
2558                   origrhs = VEC_last (ce_s, *results);
2559                   tmp = *origrhs;
2560                   VEC_pop (ce_s, *results);
2561                   origvar = get_varinfo (origrhs->var);
2562                   for (; origvar; origvar = origvar->next)
2563                     {
2564                       tmp.var = origvar->id;
2565                       VEC_safe_push (ce_s, heap, *results, &tmp);
2566                     }
2567                 }
2568
2569               for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
2570                 {
2571                   if (c->type == DEREF)
2572                     c->type = SCALAR;
2573                   else
2574                     c->type = ADDRESSOF;
2575                 }
2576               return;
2577             }
2578             break;
2579           case CALL_EXPR:
2580             /* XXX: In interprocedural mode, if we didn't have the
2581                body, we would need to do *each pointer argument =
2582                &ANYTHING added.  */
2583             if (call_expr_flags (t) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA))
2584               {
2585                 varinfo_t vi;
2586                 tree heapvar = heapvar_lookup (t);
2587
2588                 if (heapvar == NULL)
2589                   {
2590                     heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
2591                     DECL_EXTERNAL (heapvar) = 1;
2592                     get_var_ann (heapvar)->is_heapvar = 1;
2593                     if (gimple_referenced_vars (cfun))
2594                       add_referenced_var (heapvar);
2595                     heapvar_insert (t, heapvar);
2596                   }
2597
2598                 temp.var = create_variable_info_for (heapvar,
2599                                                      alias_get_name (heapvar));
2600
2601                 vi = get_varinfo (temp.var);
2602                 vi->is_artificial_var = 1;
2603                 vi->is_heap_var = 1;
2604                 temp.type = ADDRESSOF;
2605                 temp.offset = 0;
2606                 VEC_safe_push (ce_s, heap, *results, &temp);
2607                 return;
2608               }
2609             else
2610               {
2611                 temp.var = anything_id;
2612                 temp.type = SCALAR;
2613                 temp.offset = 0;
2614                 VEC_safe_push (ce_s, heap, *results, &temp);
2615                 return;
2616               }
2617             break;
2618           default:
2619             {
2620               temp.type = ADDRESSOF;
2621               temp.var = anything_id;
2622               temp.offset = 0;
2623               VEC_safe_push (ce_s, heap, *results, &temp);
2624               return;
2625             }
2626           }
2627       }
2628     case tcc_reference:
2629       {
2630         switch (TREE_CODE (t))
2631           {
2632           case INDIRECT_REF:
2633             {
2634               get_constraint_for (TREE_OPERAND (t, 0), results);
2635               do_deref (results);
2636               return;
2637             }
2638           case ARRAY_REF:
2639           case ARRAY_RANGE_REF:
2640           case COMPONENT_REF:
2641             get_constraint_for_component_ref (t, results);
2642             return;
2643           default:
2644             {
2645               temp.type = ADDRESSOF;
2646               temp.var = anything_id;
2647               temp.offset = 0;
2648               VEC_safe_push (ce_s, heap, *results, &temp);
2649               return;
2650             }
2651           }
2652       }
2653     case tcc_unary:
2654       {
2655         switch (TREE_CODE (t))
2656           {
2657           case NOP_EXPR:
2658           case CONVERT_EXPR:
2659           case NON_LVALUE_EXPR:
2660             {
2661               tree op = TREE_OPERAND (t, 0);
2662
2663               /* Cast from non-pointer to pointers are bad news for us.
2664                  Anything else, we see through */
2665               if (!(POINTER_TYPE_P (TREE_TYPE (t))
2666                     && ! POINTER_TYPE_P (TREE_TYPE (op))))
2667                 {
2668                   get_constraint_for (op, results);
2669                   return;
2670                 }
2671
2672               /* FALLTHRU  */
2673             }
2674           default:
2675             {
2676               temp.type = ADDRESSOF;
2677               temp.var = anything_id;
2678               temp.offset = 0;
2679               VEC_safe_push (ce_s, heap, *results, &temp);
2680               return;
2681             }
2682           }
2683       }
2684     case tcc_exceptional:
2685       {
2686         switch (TREE_CODE (t))
2687           {
2688           case PHI_NODE:
2689             {
2690               get_constraint_for (PHI_RESULT (t), results);
2691               return;
2692             }
2693             break;
2694           case SSA_NAME:
2695             {
2696               struct constraint_expr temp;
2697               temp = get_constraint_exp_from_ssa_var (t);
2698               VEC_safe_push (ce_s, heap, *results, &temp);
2699               return;
2700             }
2701             break;
2702           default:
2703             {
2704               temp.type = ADDRESSOF;
2705               temp.var = anything_id;
2706               temp.offset = 0;
2707               VEC_safe_push (ce_s, heap, *results, &temp);
2708               return;
2709             }
2710           }
2711       }
2712     case tcc_declaration:
2713       {
2714         struct constraint_expr temp;
2715         temp = get_constraint_exp_from_ssa_var (t);
2716         VEC_safe_push (ce_s, heap, *results, &temp);
2717         return;
2718       }
2719     default:
2720       {
2721         temp.type = ADDRESSOF;
2722         temp.var = anything_id;
2723         temp.offset = 0;
2724         VEC_safe_push (ce_s, heap, *results, &temp);
2725         return;
2726       }
2727     }
2728 }
2729
2730
2731 /* Handle the structure copy case where we have a simple structure copy
2732    between LHS and RHS that is of SIZE (in bits)
2733
2734    For each field of the lhs variable (lhsfield)
2735      For each field of the rhs variable at lhsfield.offset (rhsfield)
2736        add the constraint lhsfield = rhsfield
2737
2738    If we fail due to some kind of type unsafety or other thing we
2739    can't handle, return false.  We expect the caller to collapse the
2740    variable in that case.  */
2741
2742 static bool
2743 do_simple_structure_copy (const struct constraint_expr lhs,
2744                           const struct constraint_expr rhs,
2745                           const unsigned HOST_WIDE_INT size)
2746 {
2747   varinfo_t p = get_varinfo (lhs.var);
2748   unsigned HOST_WIDE_INT pstart, last;
2749   pstart = p->offset;
2750   last = p->offset + size;
2751   for (; p && p->offset < last; p = p->next)
2752     {
2753       varinfo_t q;
2754       struct constraint_expr templhs = lhs;
2755       struct constraint_expr temprhs = rhs;
2756       unsigned HOST_WIDE_INT fieldoffset;
2757
2758       templhs.var = p->id;
2759       q = get_varinfo (temprhs.var);
2760       fieldoffset = p->offset - pstart;
2761       q = first_vi_for_offset (q, q->offset + fieldoffset);
2762       if (!q)
2763         return false;
2764       temprhs.var = q->id;
2765       process_constraint (new_constraint (templhs, temprhs));
2766     }
2767   return true;
2768 }
2769
2770
2771 /* Handle the structure copy case where we have a  structure copy between a
2772    aggregate on the LHS and a dereference of a pointer on the RHS
2773    that is of SIZE (in bits)
2774
2775    For each field of the lhs variable (lhsfield)
2776        rhs.offset = lhsfield->offset
2777        add the constraint lhsfield = rhs
2778 */
2779
2780 static void
2781 do_rhs_deref_structure_copy (const struct constraint_expr lhs,
2782                              const struct constraint_expr rhs,
2783                              const unsigned HOST_WIDE_INT size)
2784 {
2785   varinfo_t p = get_varinfo (lhs.var);
2786   unsigned HOST_WIDE_INT pstart,last;
2787   pstart = p->offset;
2788   last = p->offset + size;
2789
2790   for (; p && p->offset < last; p = p->next)
2791     {
2792       varinfo_t q;
2793       struct constraint_expr templhs = lhs;
2794       struct constraint_expr temprhs = rhs;
2795       unsigned HOST_WIDE_INT fieldoffset;
2796
2797
2798       if (templhs.type == SCALAR)
2799         templhs.var = p->id;
2800       else
2801         templhs.offset = p->offset;
2802
2803       q = get_varinfo (temprhs.var);
2804       fieldoffset = p->offset - pstart;
2805       temprhs.offset += fieldoffset;
2806       process_constraint (new_constraint (templhs, temprhs));
2807     }
2808 }
2809
2810 /* Handle the structure copy case where we have a structure copy
2811    between a aggregate on the RHS and a dereference of a pointer on
2812    the LHS that is of SIZE (in bits)
2813
2814    For each field of the rhs variable (rhsfield)
2815        lhs.offset = rhsfield->offset
2816        add the constraint lhs = rhsfield
2817 */
2818
2819 static void
2820 do_lhs_deref_structure_copy (const struct constraint_expr lhs,
2821                              const struct constraint_expr rhs,
2822                              const unsigned HOST_WIDE_INT size)
2823 {
2824   varinfo_t p = get_varinfo (rhs.var);
2825   unsigned HOST_WIDE_INT pstart,last;
2826   pstart = p->offset;
2827   last = p->offset + size;
2828
2829   for (; p && p->offset < last; p = p->next)
2830     {
2831       varinfo_t q;
2832       struct constraint_expr templhs = lhs;
2833       struct constraint_expr temprhs = rhs;
2834       unsigned HOST_WIDE_INT fieldoffset;
2835
2836
2837       if (temprhs.type == SCALAR)
2838         temprhs.var = p->id;
2839       else
2840         temprhs.offset = p->offset;
2841
2842       q = get_varinfo (templhs.var);
2843       fieldoffset = p->offset - pstart;
2844       templhs.offset += fieldoffset;
2845       process_constraint (new_constraint (templhs, temprhs));
2846     }
2847 }
2848
2849 /* Sometimes, frontends like to give us bad type information.  This
2850    function will collapse all the fields from VAR to the end of VAR,
2851    into VAR, so that we treat those fields as a single variable.
2852    We return the variable they were collapsed into.  */
2853
2854 static unsigned int
2855 collapse_rest_of_var (unsigned int var)
2856 {
2857   varinfo_t currvar = get_varinfo (var);
2858   varinfo_t field;
2859
2860   for (field = currvar->next; field; field = field->next)
2861     {
2862       if (dump_file)
2863         fprintf (dump_file, "Type safety: Collapsing var %s into %s\n",
2864                  field->name, currvar->name);
2865
2866       gcc_assert (!field->collapsed_to);
2867       field->collapsed_to = currvar;
2868     }
2869
2870   currvar->next = NULL;
2871   currvar->size = currvar->fullsize - currvar->offset;
2872
2873   return currvar->id;
2874 }
2875
2876 /* Handle aggregate copies by expanding into copies of the respective
2877    fields of the structures.  */
2878
2879 static void
2880 do_structure_copy (tree lhsop, tree rhsop)
2881 {
2882   struct constraint_expr lhs, rhs, tmp;
2883   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
2884   varinfo_t p;
2885   unsigned HOST_WIDE_INT lhssize;
2886   unsigned HOST_WIDE_INT rhssize;
2887
2888   get_constraint_for (lhsop, &lhsc);
2889   get_constraint_for (rhsop, &rhsc);
2890   gcc_assert (VEC_length (ce_s, lhsc) == 1);
2891   gcc_assert (VEC_length (ce_s, rhsc) == 1);
2892   lhs = *(VEC_last (ce_s, lhsc));
2893   rhs = *(VEC_last (ce_s, rhsc));
2894
2895   VEC_free (ce_s, heap, lhsc);
2896   VEC_free (ce_s, heap, rhsc);
2897
2898   /* If we have special var = x, swap it around.  */
2899   if (lhs.var <= integer_id && !(get_varinfo (rhs.var)->is_special_var))
2900     {
2901       tmp = lhs;
2902       lhs = rhs;
2903       rhs = tmp;
2904     }
2905
2906   /*  This is fairly conservative for the RHS == ADDRESSOF case, in that it's
2907       possible it's something we could handle.  However, most cases falling
2908       into this are dealing with transparent unions, which are slightly
2909       weird. */
2910   if (rhs.type == ADDRESSOF && !(get_varinfo (rhs.var)->is_special_var))
2911     {
2912       rhs.type = ADDRESSOF;
2913       rhs.var = anything_id;
2914     }
2915
2916   /* If the RHS is a special var, or an addressof, set all the LHS fields to
2917      that special var.  */
2918   if (rhs.var <= integer_id)
2919     {
2920       for (p = get_varinfo (lhs.var); p; p = p->next)
2921         {
2922           struct constraint_expr templhs = lhs;
2923           struct constraint_expr temprhs = rhs;
2924
2925           if (templhs.type == SCALAR )
2926             templhs.var = p->id;
2927           else
2928             templhs.offset += p->offset;
2929           process_constraint (new_constraint (templhs, temprhs));
2930         }
2931     }
2932   else
2933     {
2934       tree rhstype = TREE_TYPE (rhsop);
2935       tree lhstype = TREE_TYPE (lhsop);
2936       tree rhstypesize;
2937       tree lhstypesize;
2938
2939       lhstypesize = DECL_P (lhsop) ? DECL_SIZE (lhsop) : TYPE_SIZE (lhstype);
2940       rhstypesize = DECL_P (rhsop) ? DECL_SIZE (rhsop) : TYPE_SIZE (rhstype);
2941
2942       /* If we have a variably sized types on the rhs or lhs, and a deref
2943          constraint, add the constraint, lhsconstraint = &ANYTHING.
2944          This is conservatively correct because either the lhs is an unknown
2945          sized var (if the constraint is SCALAR), or the lhs is a DEREF
2946          constraint, and every variable it can point to must be unknown sized
2947          anyway, so we don't need to worry about fields at all.  */
2948       if ((rhs.type == DEREF && TREE_CODE (rhstypesize) != INTEGER_CST)
2949           || (lhs.type == DEREF && TREE_CODE (lhstypesize) != INTEGER_CST))
2950         {
2951           rhs.var = anything_id;
2952           rhs.type = ADDRESSOF;
2953           rhs.offset = 0;
2954           process_constraint (new_constraint (lhs, rhs));
2955           return;
2956         }
2957
2958       /* The size only really matters insofar as we don't set more or less of
2959          the variable.  If we hit an unknown size var, the size should be the
2960          whole darn thing.  */
2961       if (get_varinfo (rhs.var)->is_unknown_size_var)
2962         rhssize = ~0;
2963       else
2964         rhssize = TREE_INT_CST_LOW (rhstypesize);
2965
2966       if (get_varinfo (lhs.var)->is_unknown_size_var)
2967         lhssize = ~0;
2968       else
2969         lhssize = TREE_INT_CST_LOW (lhstypesize);
2970
2971
2972       if (rhs.type == SCALAR && lhs.type == SCALAR)
2973         {
2974           if (!do_simple_structure_copy (lhs, rhs, MIN (lhssize, rhssize)))
2975             {
2976               lhs.var = collapse_rest_of_var (lhs.var);
2977               rhs.var = collapse_rest_of_var (rhs.var);
2978               lhs.offset = 0;
2979               rhs.offset = 0;
2980               lhs.type = SCALAR;
2981               rhs.type = SCALAR;
2982               process_constraint (new_constraint (lhs, rhs));
2983             }
2984         }
2985       else if (lhs.type != DEREF && rhs.type == DEREF)
2986         do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2987       else if (lhs.type == DEREF && rhs.type != DEREF)
2988         do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2989       else
2990         {
2991           tree pointedtotype = lhstype;
2992           tree tmpvar;
2993
2994           gcc_assert (rhs.type == DEREF && lhs.type == DEREF);
2995           tmpvar = create_tmp_var_raw (pointedtotype, "structcopydereftmp");
2996           do_structure_copy (tmpvar, rhsop);
2997           do_structure_copy (lhsop, tmpvar);
2998         }
2999     }
3000 }
3001
3002
3003 /* Update related alias information kept in AI.  This is used when
3004    building name tags, alias sets and deciding grouping heuristics.
3005    STMT is the statement to process.  This function also updates
3006    ADDRESSABLE_VARS.  */
3007
3008 static void
3009 update_alias_info (tree stmt, struct alias_info *ai)
3010 {
3011   bitmap addr_taken;
3012   use_operand_p use_p;
3013   ssa_op_iter iter;
3014   enum escape_type stmt_escape_type = is_escape_site (stmt);
3015
3016   if (stmt_escape_type == ESCAPE_TO_CALL
3017       || stmt_escape_type == ESCAPE_TO_PURE_CONST)
3018     {
3019       ai->num_calls_found++;
3020       if (stmt_escape_type == ESCAPE_TO_PURE_CONST)
3021         ai->num_pure_const_calls_found++;
3022     }
3023
3024   /* Mark all the variables whose address are taken by the statement.  */
3025   addr_taken = addresses_taken (stmt);
3026   if (addr_taken)
3027     {
3028       bitmap_ior_into (gimple_addressable_vars (cfun), addr_taken);
3029
3030       /* If STMT is an escape point, all the addresses taken by it are
3031          call-clobbered.  */
3032       if (stmt_escape_type != NO_ESCAPE)
3033         {
3034           bitmap_iterator bi;
3035           unsigned i;
3036
3037           EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
3038             {
3039               tree rvar = referenced_var (i);
3040               if (!unmodifiable_var_p (rvar))
3041                 mark_call_clobbered (rvar, stmt_escape_type);
3042             }
3043         }
3044     }
3045
3046   /* Process each operand use.  If an operand may be aliased, keep
3047      track of how many times it's being used.  For pointers, determine
3048      whether they are dereferenced by the statement, or whether their
3049      value escapes, etc.  */
3050   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
3051     {
3052       tree op, var;
3053       var_ann_t v_ann;
3054       struct ptr_info_def *pi;
3055       bool is_store, is_potential_deref;
3056       unsigned num_uses, num_derefs;
3057
3058       op = USE_FROM_PTR (use_p);
3059
3060       /* If STMT is a PHI node, OP may be an ADDR_EXPR.  If so, add it
3061          to the set of addressable variables.  */
3062       if (TREE_CODE (op) == ADDR_EXPR)
3063         {
3064           bitmap addressable_vars = gimple_addressable_vars (cfun);
3065
3066           gcc_assert (TREE_CODE (stmt) == PHI_NODE);
3067           gcc_assert (addressable_vars);
3068
3069           /* PHI nodes don't have annotations for pinning the set
3070              of addresses taken, so we collect them here.
3071
3072              FIXME, should we allow PHI nodes to have annotations
3073              so that they can be treated like regular statements?
3074              Currently, they are treated as second-class
3075              statements.  */
3076           add_to_addressable_set (TREE_OPERAND (op, 0),
3077                                   &addressable_vars);
3078           continue;
3079         }
3080
3081       /* Ignore constants.  */
3082       if (TREE_CODE (op) != SSA_NAME)
3083         continue;
3084
3085       var = SSA_NAME_VAR (op);
3086       v_ann = var_ann (var);
3087
3088       /* The base variable of an SSA name must be a GIMPLE register, and thus
3089          it cannot be aliased.  */
3090       gcc_assert (!may_be_aliased (var));
3091
3092       /* We are only interested in pointers.  */
3093       if (!POINTER_TYPE_P (TREE_TYPE (op)))
3094         continue;
3095
3096       pi = get_ptr_info (op);
3097
3098       /* Add OP to AI->PROCESSED_PTRS, if it's not there already.  */
3099       if (!TEST_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op)))
3100         {
3101           SET_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op));
3102           VEC_safe_push (tree, heap, ai->processed_ptrs, op);
3103         }
3104
3105       /* If STMT is a PHI node, then it will not have pointer
3106          dereferences and it will not be an escape point.  */
3107       if (TREE_CODE (stmt) == PHI_NODE)
3108         continue;
3109
3110       /* Determine whether OP is a dereferenced pointer, and if STMT
3111          is an escape point, whether OP escapes.  */
3112       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
3113
3114       /* Handle a corner case involving address expressions of the
3115          form '&PTR->FLD'.  The problem with these expressions is that
3116          they do not represent a dereference of PTR.  However, if some
3117          other transformation propagates them into an INDIRECT_REF
3118          expression, we end up with '*(&PTR->FLD)' which is folded
3119          into 'PTR->FLD'.
3120
3121          So, if the original code had no other dereferences of PTR,
3122          the aliaser will not create memory tags for it, and when
3123          &PTR->FLD gets propagated to INDIRECT_REF expressions, the
3124          memory operations will receive no VDEF/VUSE operands.
3125
3126          One solution would be to have count_uses_and_derefs consider
3127          &PTR->FLD a dereference of PTR.  But that is wrong, since it
3128          is not really a dereference but an offset calculation.
3129
3130          What we do here is to recognize these special ADDR_EXPR
3131          nodes.  Since these expressions are never GIMPLE values (they
3132          are not GIMPLE invariants), they can only appear on the RHS
3133          of an assignment and their base address is always an
3134          INDIRECT_REF expression.  */
3135       is_potential_deref = false;
3136       if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3137           && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == ADDR_EXPR
3138           && !is_gimple_val (GIMPLE_STMT_OPERAND (stmt, 1)))
3139         {
3140           /* If the RHS if of the form &PTR->FLD and PTR == OP, then
3141              this represents a potential dereference of PTR.  */
3142           tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
3143           tree base = get_base_address (TREE_OPERAND (rhs, 0));
3144           if (TREE_CODE (base) == INDIRECT_REF
3145               && TREE_OPERAND (base, 0) == op)
3146             is_potential_deref = true;
3147         }
3148
3149       if (num_derefs > 0 || is_potential_deref)
3150         {
3151           /* Mark OP as dereferenced.  In a subsequent pass,
3152              dereferenced pointers that point to a set of
3153              variables will be assigned a name tag to alias
3154              all the variables OP points to.  */
3155           pi->is_dereferenced = 1;
3156
3157           /* If this is a store operation, mark OP as being
3158              dereferenced to store, otherwise mark it as being
3159              dereferenced to load.  */
3160           if (is_store)
3161             pointer_set_insert (ai->dereferenced_ptrs_store, var);
3162           else
3163             pointer_set_insert (ai->dereferenced_ptrs_load, var);
3164         }
3165
3166       if (stmt_escape_type != NO_ESCAPE && num_derefs < num_uses)
3167         {
3168           /* If STMT is an escape point and STMT contains at
3169              least one direct use of OP, then the value of OP
3170              escapes and so the pointed-to variables need to
3171              be marked call-clobbered.  */
3172           pi->value_escapes_p = 1;
3173           pi->escape_mask |= stmt_escape_type;
3174
3175           /* If the statement makes a function call, assume
3176              that pointer OP will be dereferenced in a store
3177              operation inside the called function.  */
3178           if (get_call_expr_in (stmt)
3179               || stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3180             {
3181               pointer_set_insert (ai->dereferenced_ptrs_store, var);
3182               pi->is_dereferenced = 1;
3183             }
3184         }
3185     }
3186
3187   if (TREE_CODE (stmt) == PHI_NODE)
3188     return;
3189
3190   /* Mark stored variables in STMT as being written to and update the
3191      reference counter for potentially aliased symbols in STMT.  */
3192   if (stmt_references_memory_p (stmt) && STORED_SYMS (stmt))
3193     {
3194       unsigned i;
3195       bitmap_iterator bi;
3196       EXECUTE_IF_SET_IN_BITMAP (STORED_SYMS (stmt), 0, i, bi)
3197         pointer_set_insert (ai->written_vars, referenced_var (i));
3198     }
3199 }
3200
3201
3202 /* Handle pointer arithmetic EXPR when creating aliasing constraints.
3203    Expressions of the type PTR + CST can be handled in two ways:
3204
3205    1- If the constraint for PTR is ADDRESSOF for a non-structure
3206       variable, then we can use it directly because adding or
3207       subtracting a constant may not alter the original ADDRESSOF
3208       constraint (i.e., pointer arithmetic may not legally go outside
3209       an object's boundaries).
3210
3211    2- If the constraint for PTR is ADDRESSOF for a structure variable,
3212       then if CST is a compile-time constant that can be used as an
3213       offset, we can determine which sub-variable will be pointed-to
3214       by the expression.
3215
3216    Return true if the expression is handled.  For any other kind of
3217    expression, return false so that each operand can be added as a
3218    separate constraint by the caller.  */
3219
3220 static bool
3221 handle_ptr_arith (VEC (ce_s, heap) *lhsc, tree expr)
3222 {
3223   tree op0, op1;
3224   struct constraint_expr *c, *c2;
3225   unsigned int i = 0;
3226   unsigned int j = 0;
3227   VEC (ce_s, heap) *temp = NULL;
3228   unsigned int rhsoffset = 0;
3229
3230   if (TREE_CODE (expr) != PLUS_EXPR
3231       && TREE_CODE (expr) != MINUS_EXPR)
3232     return false;
3233
3234   op0 = TREE_OPERAND (expr, 0);
3235   op1 = TREE_OPERAND (expr, 1);
3236
3237   get_constraint_for (op0, &temp);
3238   if (POINTER_TYPE_P (TREE_TYPE (op0))
3239       && TREE_CODE (op1) == INTEGER_CST
3240       && TREE_CODE (expr) == PLUS_EXPR)
3241     {
3242       rhsoffset = TREE_INT_CST_LOW (op1) * BITS_PER_UNIT;
3243     }
3244   else
3245     return false;
3246
3247
3248   for (i = 0; VEC_iterate (ce_s, lhsc, i, c); i++)
3249     for (j = 0; VEC_iterate (ce_s, temp, j, c2); j++)
3250       {
3251         if (c2->type == ADDRESSOF && rhsoffset != 0)
3252           {
3253             varinfo_t temp = get_varinfo (c2->var);
3254
3255             /* An access one after the end of an array is valid,
3256                so simply punt on accesses we cannot resolve.  */
3257             temp = first_vi_for_offset (temp, rhsoffset);
3258             if (temp == NULL)
3259               continue;
3260             c2->var = temp->id;
3261             c2->offset = 0;
3262           }
3263         else
3264           c2->offset = rhsoffset;
3265         process_constraint (new_constraint (*c, *c2));
3266       }
3267
3268   VEC_free (ce_s, heap, temp);
3269
3270   return true;
3271 }
3272
3273
3274 /* Walk statement T setting up aliasing constraints according to the
3275    references found in T.  This function is the main part of the
3276    constraint builder.  AI points to auxiliary alias information used
3277    when building alias sets and computing alias grouping heuristics.  */
3278
3279 static void
3280 find_func_aliases (tree origt)
3281 {
3282   tree t = origt;
3283   VEC(ce_s, heap) *lhsc = NULL;
3284   VEC(ce_s, heap) *rhsc = NULL;
3285   struct constraint_expr *c;
3286
3287   if (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0))
3288     t = TREE_OPERAND (t, 0);
3289
3290   /* Now build constraints expressions.  */
3291   if (TREE_CODE (t) == PHI_NODE)
3292     {
3293       gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (PHI_RESULT (t))));
3294
3295       /* Only care about pointers and structures containing
3296          pointers.  */
3297       if (could_have_pointers (PHI_RESULT (t)))
3298         {
3299           int i;
3300           unsigned int j;
3301
3302           /* For a phi node, assign all the arguments to
3303              the result.  */
3304           get_constraint_for (PHI_RESULT (t), &lhsc);
3305           for (i = 0; i < PHI_NUM_ARGS (t); i++)
3306             {
3307               tree rhstype;
3308               tree strippedrhs = PHI_ARG_DEF (t, i);
3309
3310               STRIP_NOPS (strippedrhs);
3311               rhstype = TREE_TYPE (strippedrhs);
3312               get_constraint_for (PHI_ARG_DEF (t, i), &rhsc);
3313
3314               for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3315                 {
3316                   struct constraint_expr *c2;
3317                   while (VEC_length (ce_s, rhsc) > 0)
3318                     {
3319                       c2 = VEC_last (ce_s, rhsc);
3320                       process_constraint (new_constraint (*c, *c2));
3321                       VEC_pop (ce_s, rhsc);
3322                     }
3323                 }
3324             }
3325         }
3326     }
3327   /* In IPA mode, we need to generate constraints to pass call
3328      arguments through their calls.   There are two cases, either a
3329      GIMPLE_MODIFY_STMT when we are returning a value, or just a plain
3330      CALL_EXPR when we are not.   */
3331   else if (in_ipa_mode
3332            && ((TREE_CODE (t) == GIMPLE_MODIFY_STMT
3333                 && TREE_CODE (GIMPLE_STMT_OPERAND (t, 1)) == CALL_EXPR
3334                && !(call_expr_flags (GIMPLE_STMT_OPERAND (t, 1))
3335                     & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))
3336                || (TREE_CODE (t) == CALL_EXPR
3337                    && !(call_expr_flags (t)
3338                         & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))))
3339     {
3340       tree lhsop;
3341       tree rhsop;
3342       tree arg;
3343       call_expr_arg_iterator iter;
3344       varinfo_t fi;
3345       int i = 1;
3346       tree decl;
3347       if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
3348         {
3349           lhsop = GIMPLE_STMT_OPERAND (t, 0);
3350           rhsop = GIMPLE_STMT_OPERAND (t, 1);
3351         }
3352       else
3353         {
3354           lhsop = NULL;
3355           rhsop = t;
3356         }
3357       decl = get_callee_fndecl (rhsop);
3358
3359       /* If we can directly resolve the function being called, do so.
3360          Otherwise, it must be some sort of indirect expression that
3361          we should still be able to handle.  */
3362       if (decl)
3363         {
3364           fi = get_vi_for_tree (decl);
3365         }
3366       else
3367         {
3368           decl = CALL_EXPR_FN (rhsop);
3369           fi = get_vi_for_tree (decl);
3370         }
3371
3372       /* Assign all the passed arguments to the appropriate incoming
3373          parameters of the function.  */
3374
3375       FOR_EACH_CALL_EXPR_ARG (arg, iter, rhsop)
3376         {
3377           struct constraint_expr lhs ;
3378           struct constraint_expr *rhsp;
3379
3380           get_constraint_for (arg, &rhsc);
3381           if (TREE_CODE (decl) != FUNCTION_DECL)
3382             {
3383               lhs.type = DEREF;
3384               lhs.var = fi->id;
3385               lhs.offset = i;
3386             }
3387           else
3388             {
3389               lhs.type = SCALAR;
3390               lhs.var = first_vi_for_offset (fi, i)->id;
3391               lhs.offset = 0;
3392             }
3393           while (VEC_length (ce_s, rhsc) != 0)
3394             {
3395               rhsp = VEC_last (ce_s, rhsc);
3396               process_constraint (new_constraint (lhs, *rhsp));
3397               VEC_pop (ce_s, rhsc);
3398             }
3399           i++;
3400         }
3401
3402       /* If we are returning a value, assign it to the result.  */
3403       if (lhsop)
3404         {
3405           struct constraint_expr rhs;
3406           struct constraint_expr *lhsp;
3407           unsigned int j = 0;
3408
3409           get_constraint_for (lhsop, &lhsc);
3410           if (TREE_CODE (decl) != FUNCTION_DECL)
3411             {
3412               rhs.type = DEREF;
3413               rhs.var = fi->id;
3414               rhs.offset = i;
3415             }
3416           else
3417             {
3418               rhs.type = SCALAR;
3419               rhs.var = first_vi_for_offset (fi, i)->id;
3420               rhs.offset = 0;
3421             }
3422           for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3423             process_constraint (new_constraint (*lhsp, rhs));
3424         }
3425     }
3426   /* Otherwise, just a regular assignment statement.  */
3427   else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
3428     {
3429       tree lhsop = GIMPLE_STMT_OPERAND (t, 0);
3430       tree rhsop = GIMPLE_STMT_OPERAND (t, 1);
3431       int i;
3432
3433       if ((AGGREGATE_TYPE_P (TREE_TYPE (lhsop))
3434            || TREE_CODE (TREE_TYPE (lhsop)) == COMPLEX_TYPE)
3435           && (AGGREGATE_TYPE_P (TREE_TYPE (rhsop))
3436               || TREE_CODE (TREE_TYPE (lhsop)) == COMPLEX_TYPE))
3437         {
3438           do_structure_copy (lhsop, rhsop);
3439         }
3440       else
3441         {
3442           /* Only care about operations with pointers, structures
3443              containing pointers, dereferences, and call expressions.  */
3444           if (could_have_pointers (lhsop)
3445               || TREE_CODE (rhsop) == CALL_EXPR)
3446             {
3447               get_constraint_for (lhsop, &lhsc);
3448               switch (TREE_CODE_CLASS (TREE_CODE (rhsop)))
3449                 {
3450                   /* RHS that consist of unary operations,
3451                      exceptional types, or bare decls/constants, get
3452                      handled directly by get_constraint_for.  */
3453                   case tcc_reference:
3454                   case tcc_declaration:
3455                   case tcc_constant:
3456                   case tcc_exceptional:
3457                   case tcc_expression:
3458                   case tcc_vl_exp:
3459                   case tcc_unary:
3460                       {
3461                         unsigned int j;
3462
3463                         get_constraint_for (rhsop, &rhsc);
3464                         for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3465                           {
3466                             struct constraint_expr *c2;
3467                             unsigned int k;
3468
3469                             for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3470                               process_constraint (new_constraint (*c, *c2));
3471                           }
3472
3473                       }
3474                     break;
3475
3476                   case tcc_binary:
3477                       {
3478                         /* For pointer arithmetic of the form
3479                            PTR + CST, we can simply use PTR's
3480                            constraint because pointer arithmetic is
3481                            not allowed to go out of bounds.  */
3482                         if (handle_ptr_arith (lhsc, rhsop))
3483                           break;
3484                       }
3485                     /* FALLTHRU  */
3486
3487                   /* Otherwise, walk each operand.  Notice that we
3488                      can't use the operand interface because we need
3489                      to process expressions other than simple operands
3490                      (e.g. INDIRECT_REF, ADDR_EXPR, CALL_EXPR).  */
3491                   default:
3492                     for (i = 0; i < TREE_OPERAND_LENGTH (rhsop); i++)
3493                       {
3494                         tree op = TREE_OPERAND (rhsop, i);
3495                         unsigned int j;
3496
3497                         gcc_assert (VEC_length (ce_s, rhsc) == 0);
3498                         get_constraint_for (op, &rhsc);
3499                         for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3500                           {
3501                             struct constraint_expr *c2;
3502                             while (VEC_length (ce_s, rhsc) > 0)
3503                               {
3504                                 c2 = VEC_last (ce_s, rhsc);
3505                                 process_constraint (new_constraint (*c, *c2));
3506                                 VEC_pop (ce_s, rhsc);
3507                               }
3508                           }
3509                       }
3510                 }
3511             }
3512         }
3513     }
3514
3515   /* After promoting variables and computing aliasing we will
3516      need to re-scan most statements.  FIXME: Try to minimize the
3517      number of statements re-scanned.  It's not really necessary to
3518      re-scan *all* statements.  */
3519   mark_stmt_modified (origt);
3520   VEC_free (ce_s, heap, rhsc);
3521   VEC_free (ce_s, heap, lhsc);
3522 }
3523
3524
3525 /* Find the first varinfo in the same variable as START that overlaps with
3526    OFFSET.
3527    Effectively, walk the chain of fields for the variable START to find the
3528    first field that overlaps with OFFSET.
3529    Return NULL if we can't find one.  */
3530
3531 static varinfo_t
3532 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3533 {
3534   varinfo_t curr = start;
3535   while (curr)
3536     {
3537       /* We may not find a variable in the field list with the actual
3538          offset when when we have glommed a structure to a variable.
3539          In that case, however, offset should still be within the size
3540          of the variable. */
3541       if (offset >= curr->offset && offset < (curr->offset +  curr->size))
3542         return curr;
3543       curr = curr->next;
3544     }
3545   return NULL;
3546 }
3547
3548
3549 /* Insert the varinfo FIELD into the field list for BASE, at the front
3550    of the list.  */
3551
3552 static void
3553 insert_into_field_list (varinfo_t base, varinfo_t field)
3554 {
3555   varinfo_t prev = base;
3556   varinfo_t curr = base->next;
3557
3558   field->next = curr;
3559   prev->next = field;
3560 }
3561
3562 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3563    offset.  */
3564
3565 static void
3566 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3567 {
3568   varinfo_t prev = base;
3569   varinfo_t curr = base->next;
3570
3571   if (curr == NULL)
3572     {
3573       prev->next = field;
3574       field->next = NULL;
3575     }
3576   else
3577     {
3578       while (curr)
3579         {
3580           if (field->offset <= curr->offset)
3581             break;
3582           prev = curr;
3583           curr = curr->next;
3584         }
3585       field->next = prev->next;
3586       prev->next = field;
3587     }
3588 }
3589
3590 /* qsort comparison function for two fieldoff's PA and PB */
3591
3592 static int
3593 fieldoff_compare (const void *pa, const void *pb)
3594 {
3595   const fieldoff_s *foa = (const fieldoff_s *)pa;
3596   const fieldoff_s *fob = (const fieldoff_s *)pb;
3597   HOST_WIDE_INT foasize, fobsize;
3598
3599   if (foa->offset != fob->offset)
3600     return foa->offset - fob->offset;
3601
3602   foasize = TREE_INT_CST_LOW (foa->size);
3603   fobsize = TREE_INT_CST_LOW (fob->size);
3604   return foasize - fobsize;
3605 }
3606
3607 /* Sort a fieldstack according to the field offset and sizes.  */
3608 void
3609 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3610 {
3611   qsort (VEC_address (fieldoff_s, fieldstack),
3612          VEC_length (fieldoff_s, fieldstack),
3613          sizeof (fieldoff_s),
3614          fieldoff_compare);
3615 }
3616
3617 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
3618    of TYPE onto fieldstack, recording their offsets along the way.
3619    OFFSET is used to keep track of the offset in this entire structure, rather
3620    than just the immediately containing structure.  Returns the number
3621    of fields pushed.
3622    HAS_UNION is set to true if we find a union type as a field of
3623    TYPE.  */
3624
3625 int
3626 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
3627                              HOST_WIDE_INT offset, bool *has_union)
3628 {
3629   tree field;
3630   int count = 0;
3631
3632   if (TREE_CODE (type) == COMPLEX_TYPE)
3633     {
3634       fieldoff_s *real_part, *img_part;
3635       real_part = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3636       real_part->type = TREE_TYPE (type);
3637       real_part->size = TYPE_SIZE (TREE_TYPE (type));
3638       real_part->offset = offset;
3639       real_part->decl = NULL_TREE;
3640
3641       img_part = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3642       img_part->type = TREE_TYPE (type);
3643       img_part->size = TYPE_SIZE (TREE_TYPE (type));
3644       img_part->offset = offset + TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (type)));
3645       img_part->decl = NULL_TREE;
3646
3647       return 2;
3648     }
3649
3650   if (TREE_CODE (type) == ARRAY_TYPE)
3651     {
3652       tree sz = TYPE_SIZE (type);
3653       tree elsz = TYPE_SIZE (TREE_TYPE (type));
3654       HOST_WIDE_INT nr;
3655       int i;
3656
3657       if (! sz
3658           || ! host_integerp (sz, 1)
3659           || TREE_INT_CST_LOW (sz) == 0
3660           || ! elsz
3661           || ! host_integerp (elsz, 1)
3662           || TREE_INT_CST_LOW (elsz) == 0)
3663         return 0;
3664
3665       nr = TREE_INT_CST_LOW (sz) / TREE_INT_CST_LOW (elsz);
3666       if (nr > SALIAS_MAX_ARRAY_ELEMENTS)
3667         return 0;
3668
3669       for (i = 0; i < nr; ++i)
3670         {
3671           bool push = false;
3672           int pushed = 0;
3673
3674           if (has_union
3675               && (TREE_CODE (TREE_TYPE (type)) == QUAL_UNION_TYPE
3676                   || TREE_CODE (TREE_TYPE (type)) == UNION_TYPE))
3677             *has_union = true;
3678
3679           if (!AGGREGATE_TYPE_P (TREE_TYPE (type))) /* var_can_have_subvars */
3680             push = true;
3681           else if (!(pushed = push_fields_onto_fieldstack
3682                      (TREE_TYPE (type), fieldstack,
3683                       offset + i * TREE_INT_CST_LOW (elsz), has_union)))
3684             /* Empty structures may have actual size, like in C++. So
3685                see if we didn't push any subfields and the size is
3686                nonzero, push the field onto the stack */
3687             push = true;
3688
3689           if (push)
3690             {
3691               fieldoff_s *pair;
3692
3693               pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3694               pair->type = TREE_TYPE (type);
3695               pair->size = elsz;
3696               pair->decl = NULL_TREE;
3697               pair->offset = offset + i * TREE_INT_CST_LOW (elsz);
3698               count++;
3699             }
3700           else
3701             count += pushed;
3702         }
3703
3704       return count;
3705     }
3706
3707   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3708     if (TREE_CODE (field) == FIELD_DECL)
3709       {
3710         bool push = false;
3711         int pushed = 0;
3712
3713         if (has_union
3714             && (TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
3715                 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE))
3716           *has_union = true;
3717
3718         if (!var_can_have_subvars (field))
3719           push = true;
3720         else if (!(pushed = push_fields_onto_fieldstack
3721                    (TREE_TYPE (field), fieldstack,
3722                     offset + bitpos_of_field (field), has_union))
3723                  && DECL_SIZE (field)
3724                  && !integer_zerop (DECL_SIZE (field)))
3725           /* Empty structures may have actual size, like in C++. So
3726              see if we didn't push any subfields and the size is
3727              nonzero, push the field onto the stack */
3728           push = true;
3729
3730         if (push)
3731           {
3732             fieldoff_s *pair;
3733
3734             pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3735             pair->type = TREE_TYPE (field);
3736             pair->size = DECL_SIZE (field);
3737             pair->decl = field;
3738             pair->offset = offset + bitpos_of_field (field);
3739             count++;
3740           }
3741         else
3742           count += pushed;
3743       }
3744
3745   return count;
3746 }
3747
3748 /* Create a constraint from ANYTHING variable to VI.  */
3749 static void
3750 make_constraint_from_anything (varinfo_t vi)
3751 {
3752   struct constraint_expr lhs, rhs;
3753
3754   lhs.var = vi->id;
3755   lhs.offset = 0;
3756   lhs.type = SCALAR;
3757
3758   rhs.var = anything_id;
3759   rhs.offset = 0;
3760   rhs.type = ADDRESSOF;
3761   process_constraint (new_constraint (lhs, rhs));
3762 }
3763
3764 /* Count the number of arguments DECL has, and set IS_VARARGS to true
3765    if it is a varargs function.  */
3766
3767 static unsigned int
3768 count_num_arguments (tree decl, bool *is_varargs)
3769 {
3770   unsigned int i = 0;
3771   tree t;
3772
3773   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
3774        t;
3775        t = TREE_CHAIN (t))
3776     {
3777       if (TREE_VALUE (t) == void_type_node)
3778         break;
3779       i++;
3780     }
3781
3782   if (!t)
3783     *is_varargs = true;
3784   return i;
3785 }
3786
3787 /* Creation function node for DECL, using NAME, and return the index
3788    of the variable we've created for the function.  */
3789
3790 static unsigned int
3791 create_function_info_for (tree decl, const char *name)
3792 {
3793   unsigned int index = VEC_length (varinfo_t, varmap);
3794   varinfo_t vi;
3795   tree arg;
3796   unsigned int i;
3797   bool is_varargs = false;
3798
3799   /* Create the variable info.  */
3800
3801   vi = new_var_info (decl, index, name);
3802   vi->decl = decl;
3803   vi->offset = 0;
3804   vi->has_union = 0;
3805   vi->size = 1;
3806   vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
3807   insert_vi_for_tree (vi->decl, vi);
3808   VEC_safe_push (varinfo_t, heap, varmap, vi);
3809
3810   stats.total_vars++;
3811
3812   /* If it's varargs, we don't know how many arguments it has, so we
3813      can't do much.
3814   */
3815   if (is_varargs)
3816     {
3817       vi->fullsize = ~0;
3818       vi->size = ~0;
3819       vi->is_unknown_size_var = true;
3820       return index;
3821     }
3822
3823
3824   arg = DECL_ARGUMENTS (decl);
3825
3826   /* Set up variables for each argument.  */
3827   for (i = 1; i < vi->fullsize; i++)
3828     {
3829       varinfo_t argvi;
3830       const char *newname;
3831       char *tempname;
3832       unsigned int newindex;
3833       tree argdecl = decl;
3834
3835       if (arg)
3836         argdecl = arg;
3837
3838       newindex = VEC_length (varinfo_t, varmap);
3839       asprintf (&tempname, "%s.arg%d", name, i-1);
3840       newname = ggc_strdup (tempname);
3841       free (tempname);
3842
3843       argvi = new_var_info (argdecl, newindex, newname);
3844       argvi->decl = argdecl;
3845       VEC_safe_push (varinfo_t, heap, varmap, argvi);
3846       argvi->offset = i;
3847       argvi->size = 1;
3848       argvi->fullsize = vi->fullsize;
3849       argvi->has_union = false;
3850       insert_into_field_list_sorted (vi, argvi);
3851       stats.total_vars ++;
3852       if (arg)
3853         {
3854           insert_vi_for_tree (arg, argvi);
3855           arg = TREE_CHAIN (arg);
3856         }
3857     }
3858
3859   /* Create a variable for the return var.  */
3860   if (DECL_RESULT (decl) != NULL
3861       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
3862     {
3863       varinfo_t resultvi;
3864       const char *newname;
3865       char *tempname;
3866       unsigned int newindex;
3867       tree resultdecl = decl;
3868
3869       vi->fullsize ++;
3870
3871       if (DECL_RESULT (decl))
3872         resultdecl = DECL_RESULT (decl);
3873
3874       newindex = VEC_length (varinfo_t, varmap);
3875       asprintf (&tempname, "%s.result", name);
3876       newname = ggc_strdup (tempname);
3877       free (tempname);
3878
3879       resultvi = new_var_info (resultdecl, newindex, newname);
3880       resultvi->decl = resultdecl;
3881       VEC_safe_push (varinfo_t, heap, varmap, resultvi);
3882       resultvi->offset = i;
3883       resultvi->size = 1;
3884       resultvi->fullsize = vi->fullsize;
3885       resultvi->has_union = false;
3886       insert_into_field_list_sorted (vi, resultvi);
3887       stats.total_vars ++;
3888       if (DECL_RESULT (decl))
3889         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
3890     }
3891   return index;
3892 }
3893
3894
3895 /* Return true if FIELDSTACK contains fields that overlap.
3896    FIELDSTACK is assumed to be sorted by offset.  */
3897
3898 static bool
3899 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
3900 {
3901   fieldoff_s *fo = NULL;
3902   unsigned int i;
3903   HOST_WIDE_INT lastoffset = -1;
3904
3905   for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3906     {
3907       if (fo->offset == lastoffset)
3908         return true;
3909       lastoffset = fo->offset;
3910     }
3911   return false;
3912 }
3913
3914 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
3915    This will also create any varinfo structures necessary for fields
3916    of DECL.  */
3917
3918 static unsigned int
3919 create_variable_info_for (tree decl, const char *name)
3920 {
3921   unsigned int index = VEC_length (varinfo_t, varmap);
3922   varinfo_t vi;
3923   tree decltype = TREE_TYPE (decl);
3924   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decltype);
3925   bool notokay = false;
3926   bool hasunion;
3927   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
3928   VEC (fieldoff_s,heap) *fieldstack = NULL;
3929
3930   if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
3931     return create_function_info_for (decl, name);
3932
3933   hasunion = TREE_CODE (decltype) == UNION_TYPE
3934              || TREE_CODE (decltype) == QUAL_UNION_TYPE;
3935   if (var_can_have_subvars (decl) && use_field_sensitive && !hasunion)
3936     {
3937       push_fields_onto_fieldstack (decltype, &fieldstack, 0, &hasunion);
3938       if (hasunion)
3939         {
3940           VEC_free (fieldoff_s, heap, fieldstack);
3941           notokay = true;
3942         }
3943     }
3944
3945
3946   /* If the variable doesn't have subvars, we may end up needing to
3947      sort the field list and create fake variables for all the
3948      fields.  */
3949   vi = new_var_info (decl, index, name);
3950   vi->decl = decl;
3951   vi->offset = 0;
3952   vi->has_union = hasunion;
3953   if (!declsize
3954       || TREE_CODE (declsize) != INTEGER_CST
3955       || TREE_CODE (decltype) == UNION_TYPE
3956       || TREE_CODE (decltype) == QUAL_UNION_TYPE)
3957     {
3958       vi->is_unknown_size_var = true;
3959       vi->fullsize = ~0;
3960       vi->size = ~0;
3961     }
3962   else
3963     {
3964       vi->fullsize = TREE_INT_CST_LOW (declsize);
3965       vi->size = vi->fullsize;
3966     }
3967
3968   insert_vi_for_tree (vi->decl, vi);
3969   VEC_safe_push (varinfo_t, heap, varmap, vi);
3970   if (is_global && (!flag_whole_program || !in_ipa_mode))
3971     make_constraint_from_anything (vi);
3972
3973   stats.total_vars++;
3974   if (use_field_sensitive
3975       && !notokay
3976       && !vi->is_unknown_size_var
3977       && var_can_have_subvars (decl)
3978       && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
3979     {
3980       unsigned int newindex = VEC_length (varinfo_t, varmap);
3981       fieldoff_s *fo = NULL;
3982       unsigned int i;
3983
3984       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3985         {
3986           if (! fo->size
3987               || TREE_CODE (fo->size) != INTEGER_CST
3988               || fo->offset < 0)
3989             {
3990               notokay = true;
3991               break;
3992             }
3993         }
3994
3995       /* We can't sort them if we have a field with a variable sized type,
3996          which will make notokay = true.  In that case, we are going to return
3997          without creating varinfos for the fields anyway, so sorting them is a
3998          waste to boot.  */
3999       if (!notokay)
4000         {
4001           sort_fieldstack (fieldstack);
4002           /* Due to some C++ FE issues, like PR 22488, we might end up
4003              what appear to be overlapping fields even though they,
4004              in reality, do not overlap.  Until the C++ FE is fixed,
4005              we will simply disable field-sensitivity for these cases.  */
4006           notokay = check_for_overlaps (fieldstack);
4007         }
4008
4009
4010       if (VEC_length (fieldoff_s, fieldstack) != 0)
4011         fo = VEC_index (fieldoff_s, fieldstack, 0);
4012
4013       if (fo == NULL || notokay)
4014         {
4015           vi->is_unknown_size_var = 1;
4016           vi->fullsize = ~0;
4017           vi->size = ~0;
4018           VEC_free (fieldoff_s, heap, fieldstack);
4019           return index;
4020         }
4021
4022       vi->size = TREE_INT_CST_LOW (fo->size);
4023       vi->offset = fo->offset;
4024       for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4025            i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4026            i--)
4027         {
4028           varinfo_t newvi;
4029           const char *newname = "NULL";
4030           char *tempname;
4031
4032           newindex = VEC_length (varinfo_t, varmap);
4033           if (dump_file)
4034             {
4035               if (fo->decl)
4036                 asprintf (&tempname, "%s.%s",
4037                           vi->name, alias_get_name (fo->decl));
4038               else
4039                 asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC,
4040                           vi->name, fo->offset);
4041               newname = ggc_strdup (tempname);
4042               free (tempname);
4043             }
4044           newvi = new_var_info (decl, newindex, newname);
4045           newvi->offset = fo->offset;
4046           newvi->size = TREE_INT_CST_LOW (fo->size);
4047           newvi->fullsize = vi->fullsize;
4048           insert_into_field_list (vi, newvi);
4049           VEC_safe_push (varinfo_t, heap, varmap, newvi);
4050           if (is_global && (!flag_whole_program || !in_ipa_mode))
4051               make_constraint_from_anything (newvi);
4052
4053           stats.total_vars++;
4054         }
4055       VEC_free (fieldoff_s, heap, fieldstack);
4056     }
4057   return index;
4058 }
4059
4060 /* Print out the points-to solution for VAR to FILE.  */
4061
4062 void
4063 dump_solution_for_var (FILE *file, unsigned int var)
4064 {
4065   varinfo_t vi = get_varinfo (var);
4066   unsigned int i;
4067   bitmap_iterator bi;
4068
4069   if (find (var) != var)
4070     {
4071       varinfo_t vipt = get_varinfo (find (var));
4072       fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4073     }
4074   else
4075     {
4076       fprintf (file, "%s = { ", vi->name);
4077       EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4078         {
4079           fprintf (file, "%s ", get_varinfo (i)->name);
4080         }
4081       fprintf (file, "}\n");
4082     }
4083 }
4084
4085 /* Print the points-to solution for VAR to stdout.  */
4086
4087 void
4088 debug_solution_for_var (unsigned int var)
4089 {
4090   dump_solution_for_var (stdout, var);
4091 }
4092
4093 /* Create varinfo structures for all of the variables in the
4094    function for intraprocedural mode.  */
4095
4096 static void
4097 intra_create_variable_infos (void)
4098 {
4099   tree t;
4100   struct constraint_expr lhs, rhs;
4101
4102   /* For each incoming pointer argument arg, create the constraint ARG
4103      = ANYTHING or a dummy variable if flag_argument_noalias is set.  */
4104   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4105     {
4106       varinfo_t p;
4107
4108       if (!could_have_pointers (t))
4109         continue;
4110
4111       /* With flag_argument_noalias greater than two means that the incoming
4112          argument cannot alias anything except for itself so create a HEAP
4113          variable.  */
4114       if (POINTER_TYPE_P (TREE_TYPE (t))
4115           && flag_argument_noalias > 2)
4116         {
4117           varinfo_t vi;
4118           tree heapvar = heapvar_lookup (t);
4119
4120           lhs.offset = 0;
4121           lhs.type = SCALAR;
4122           lhs.var  = get_vi_for_tree (t)->id;
4123
4124           if (heapvar == NULL_TREE)
4125             {
4126               heapvar = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (t)),
4127                                             "PARM_NOALIAS");
4128               get_var_ann (heapvar)->is_heapvar = 1;
4129               DECL_EXTERNAL (heapvar) = 1;
4130               if (gimple_referenced_vars (cfun))
4131                 add_referenced_var (heapvar);
4132               heapvar_insert (t, heapvar);
4133             }
4134           vi = get_vi_for_tree (heapvar);
4135           vi->is_artificial_var = 1;
4136           vi->is_heap_var = 1;
4137           rhs.var = vi->id;
4138           rhs.type = ADDRESSOF;
4139           rhs.offset = 0;
4140           for (p = get_varinfo (lhs.var); p; p = p->next)
4141             {
4142               struct constraint_expr temp = lhs;
4143               temp.var = p->id;
4144               process_constraint (new_constraint (temp, rhs));
4145             }
4146         }
4147       else
4148         {
4149           varinfo_t arg_vi = get_vi_for_tree (t);
4150
4151           for (p = arg_vi; p; p = p->next)
4152             make_constraint_from_anything (p);
4153         }
4154     }
4155 }
4156
4157 /* Structure used to put solution bitmaps in a hashtable so they can
4158    be shared among variables with the same points-to set.  */
4159
4160 typedef struct shared_bitmap_info
4161 {
4162   bitmap pt_vars;
4163   hashval_t hashcode;
4164 } *shared_bitmap_info_t;
4165
4166 static htab_t shared_bitmap_table;
4167
4168 /* Hash function for a shared_bitmap_info_t */
4169
4170 static hashval_t
4171 shared_bitmap_hash (const void *p)
4172 {
4173   const shared_bitmap_info_t bi = (shared_bitmap_info_t) p;
4174   return bi->hashcode;
4175 }
4176
4177 /* Equality function for two shared_bitmap_info_t's. */
4178
4179 static int
4180 shared_bitmap_eq (const void *p1, const void *p2)
4181 {
4182   const shared_bitmap_info_t sbi1 = (shared_bitmap_info_t) p1;
4183   const shared_bitmap_info_t sbi2 = (shared_bitmap_info_t) p2;
4184   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4185 }
4186
4187 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4188    existing instance if there is one, NULL otherwise.  */
4189
4190 static bitmap
4191 shared_bitmap_lookup (bitmap pt_vars)
4192 {
4193   void **slot;
4194   struct shared_bitmap_info sbi;
4195
4196   sbi.pt_vars = pt_vars;
4197   sbi.hashcode = bitmap_hash (pt_vars);
4198   
4199   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4200                                    sbi.hashcode, NO_INSERT);
4201   if (!slot)
4202     return NULL;
4203   else
4204     return ((shared_bitmap_info_t) *slot)->pt_vars;
4205 }
4206
4207
4208 /* Add a bitmap to the shared bitmap hashtable.  */
4209
4210 static void
4211 shared_bitmap_add (bitmap pt_vars)
4212 {
4213   void **slot;
4214   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4215   
4216   sbi->pt_vars = pt_vars;
4217   sbi->hashcode = bitmap_hash (pt_vars);
4218   
4219   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4220                                    sbi->hashcode, INSERT);
4221   gcc_assert (!*slot);
4222   *slot = (void *) sbi;
4223 }
4224
4225
4226 /* Set bits in INTO corresponding to the variable uids in solution set
4227    FROM, which came from variable PTR.
4228    For variables that are actually dereferenced, we also use type
4229    based alias analysis to prune the points-to sets.  */
4230
4231 static void
4232 set_uids_in_ptset (tree ptr, bitmap into, bitmap from)
4233 {
4234   unsigned int i;
4235   bitmap_iterator bi;
4236   subvar_t sv;
4237   HOST_WIDE_INT ptr_alias_set = get_alias_set (TREE_TYPE (ptr));
4238
4239   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4240     {
4241       varinfo_t vi = get_varinfo (i);
4242       unsigned HOST_WIDE_INT var_alias_set;
4243
4244       /* The only artificial variables that are allowed in a may-alias
4245          set are heap variables.  */
4246       if (vi->is_artificial_var && !vi->is_heap_var)
4247         continue;
4248
4249       if (vi->has_union && get_subvars_for_var (vi->decl) != NULL)
4250         {
4251           /* Variables containing unions may need to be converted to
4252              their SFT's, because SFT's can have unions and we cannot.  */
4253           for (sv = get_subvars_for_var (vi->decl); sv; sv = sv->next)
4254             bitmap_set_bit (into, DECL_UID (sv->var));
4255         }
4256       else if (TREE_CODE (vi->decl) == VAR_DECL
4257                || TREE_CODE (vi->decl) == PARM_DECL)
4258         {
4259           if (var_can_have_subvars (vi->decl)
4260               && get_subvars_for_var (vi->decl))
4261             {
4262               /* If VI->DECL is an aggregate for which we created
4263                  SFTs, add the SFT corresponding to VI->OFFSET.  */
4264               tree sft = get_subvar_at (vi->decl, vi->offset);
4265               if (sft)
4266                 {
4267                   var_alias_set = get_alias_set (sft);
4268                   if (!vi->directly_dereferenced
4269                       || alias_sets_conflict_p (ptr_alias_set, var_alias_set))
4270                     bitmap_set_bit (into, DECL_UID (sft));
4271                 }
4272             }
4273           else
4274             {
4275               /* Otherwise, just add VI->DECL to the alias set.
4276                  Don't type prune artificial vars.  */
4277               if (vi->is_artificial_var)
4278                 bitmap_set_bit (into, DECL_UID (vi->decl));
4279               else
4280                 {
4281                   var_alias_set = get_alias_set (vi->decl);
4282                   if (!vi->directly_dereferenced
4283                       || alias_sets_conflict_p (ptr_alias_set, var_alias_set))
4284                     bitmap_set_bit (into, DECL_UID (vi->decl));
4285                 }
4286             }
4287         }
4288     }
4289 }
4290
4291
4292 static bool have_alias_info = false;
4293
4294 /* The list of SMT's that are in use by our pointer variables.  This
4295    is the set of SMT's for all pointers that can point to anything.   */
4296 static bitmap used_smts;
4297
4298 /* Due to the ordering of points-to set calculation and SMT
4299    calculation being a bit co-dependent, we can't just calculate SMT
4300    used info whenever we want, we have to calculate it around the time
4301    that find_what_p_points_to is called.  */
4302
4303 /* Mark which SMT's are in use by points-to anything variables.  */
4304
4305 void
4306 set_used_smts (void)
4307 {
4308   int i;
4309   varinfo_t vi;
4310   used_smts = BITMAP_ALLOC (&pta_obstack);
4311
4312   for (i = 0; VEC_iterate (varinfo_t, varmap, i, vi); i++)
4313     {
4314       tree var = vi->decl;
4315       tree smt;
4316       var_ann_t va;
4317       struct ptr_info_def *pi = NULL;
4318
4319       /* For parm decls, the pointer info may be under the default
4320          def.  */
4321       if (TREE_CODE (vi->decl) == PARM_DECL
4322           && gimple_default_def (cfun, var))
4323         pi = SSA_NAME_PTR_INFO (gimple_default_def (cfun, var));
4324       else if (TREE_CODE (var) == SSA_NAME)
4325         pi = SSA_NAME_PTR_INFO (var);
4326
4327       /* Skip the special variables and those without their own
4328          solution set.  */
4329       if (vi->is_special_var || find (vi->id) != vi->id
4330           || !SSA_VAR_P (var)
4331           || (pi && !pi->is_dereferenced)
4332           || (TREE_CODE (var) == VAR_DECL && !may_be_aliased (var))
4333           || !POINTER_TYPE_P (TREE_TYPE (var)))
4334         continue;
4335
4336       if (TREE_CODE (var) == SSA_NAME)
4337         var = SSA_NAME_VAR (var);
4338
4339       va = var_ann (var);
4340       if (!va)
4341         continue;
4342
4343       smt = va->symbol_mem_tag;
4344       if (smt && bitmap_bit_p (vi->solution, anything_id))
4345         bitmap_set_bit (used_smts, DECL_UID (smt));
4346     }
4347 }
4348
4349 /* Merge the necessary SMT's into the bitmap INTO, which is
4350    P's varinfo.  This involves merging all SMT's that are a subset of
4351    the SMT necessary for P. */
4352
4353 static void
4354 merge_smts_into (tree p, bitmap solution)
4355 {
4356   unsigned int i;
4357   bitmap_iterator bi;
4358   tree smt;
4359   bitmap aliases;
4360   tree var = p;
4361
4362   if (TREE_CODE (p) == SSA_NAME)
4363     var = SSA_NAME_VAR (p);
4364
4365   smt = var_ann (var)->symbol_mem_tag;
4366   if (smt)
4367     {
4368       HOST_WIDE_INT smtset = get_alias_set (TREE_TYPE (smt));
4369
4370       /* Need to set the SMT subsets first before this
4371          will work properly.  */
4372       bitmap_set_bit (solution, DECL_UID (smt));
4373       EXECUTE_IF_SET_IN_BITMAP (used_smts, 0, i, bi)
4374         {
4375           tree newsmt = referenced_var (i);
4376           tree newsmttype = TREE_TYPE (newsmt);
4377
4378           if (alias_set_subset_of (get_alias_set (newsmttype),
4379                                    smtset))
4380             bitmap_set_bit (solution, i);
4381         }
4382
4383       aliases = MTAG_ALIASES (smt);
4384       if (aliases)
4385         bitmap_ior_into (solution, aliases);
4386     }
4387 }
4388
4389 /* Given a pointer variable P, fill in its points-to set, or return
4390    false if we can't.
4391    Rather than return false for variables that point-to anything, we
4392    instead find the corresponding SMT, and merge in it's aliases.  In
4393    addition to these aliases, we also set the bits for the SMT's
4394    themselves and their subsets, as SMT's are still in use by
4395    non-SSA_NAME's, and pruning may eliminate every one of their
4396    aliases.  In such a case, if we did not include the right set of
4397    SMT's in the points-to set of the variable, we'd end up with
4398    statements that do not conflict but should.  */
4399
4400 bool
4401 find_what_p_points_to (tree p)
4402 {
4403   tree lookup_p = p;
4404   varinfo_t vi;
4405
4406   if (!have_alias_info)
4407     return false;
4408
4409   /* For parameters, get at the points-to set for the actual parm
4410      decl.  */
4411   if (TREE_CODE (p) == SSA_NAME
4412       && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4413       && SSA_NAME_IS_DEFAULT_DEF (p))
4414     lookup_p = SSA_NAME_VAR (p);
4415
4416   vi = lookup_vi_for_tree (lookup_p);
4417   if (vi)
4418     {
4419       if (vi->is_artificial_var)
4420         return false;
4421
4422       /* See if this is a field or a structure.  */
4423       if (vi->size != vi->fullsize)
4424         {
4425           /* Nothing currently asks about structure fields directly,
4426              but when they do, we need code here to hand back the
4427              points-to set.  */
4428           if (!var_can_have_subvars (vi->decl)
4429               || get_subvars_for_var (vi->decl) == NULL)
4430             return false;
4431         }
4432       else
4433         {
4434           struct ptr_info_def *pi = get_ptr_info (p);
4435           unsigned int i;
4436           bitmap_iterator bi;
4437           bool was_pt_anything = false;
4438           bitmap finished_solution;
4439           bitmap result;
4440           
4441           if (!pi->is_dereferenced)
4442             return false;
4443
4444           /* This variable may have been collapsed, let's get the real
4445              variable.  */
4446           vi = get_varinfo (find (vi->id));
4447
4448           /* Translate artificial variables into SSA_NAME_PTR_INFO
4449              attributes.  */
4450           EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4451             {
4452               varinfo_t vi = get_varinfo (i);
4453
4454               if (vi->is_artificial_var)
4455                 {
4456                   /* FIXME.  READONLY should be handled better so that
4457                      flow insensitive aliasing can disregard writable
4458                      aliases.  */
4459                   if (vi->id == nothing_id)
4460                     pi->pt_null = 1;
4461                   else if (vi->id == anything_id)
4462                     was_pt_anything = 1;
4463                   else if (vi->id == readonly_id)
4464                     was_pt_anything = 1;
4465                   else if (vi->id == integer_id)
4466                     was_pt_anything = 1;
4467                   else if (vi->is_heap_var)
4468                     pi->pt_global_mem = 1;
4469                 }
4470             }
4471
4472           /* Share the final set of variables when possible.  */
4473           
4474           finished_solution = BITMAP_GGC_ALLOC ();
4475           stats.points_to_sets_created++;
4476           
4477           /* Instead of using pt_anything, we instead merge in the SMT
4478              aliases for the underlying SMT.  */
4479           if (was_pt_anything)
4480             {
4481               merge_smts_into (p, finished_solution);
4482               pi->pt_global_mem = 1;
4483             }
4484           
4485           set_uids_in_ptset (vi->decl, finished_solution, vi->solution);
4486           result = shared_bitmap_lookup (finished_solution);
4487
4488           if (!result)
4489             {
4490               shared_bitmap_add (finished_solution);
4491               pi->pt_vars = finished_solution;
4492             }
4493           else
4494             {
4495               pi->pt_vars = result;
4496               bitmap_clear (finished_solution);
4497             }
4498
4499           if (bitmap_empty_p (pi->pt_vars))
4500             pi->pt_vars = NULL;
4501
4502           return true;
4503         }
4504     }
4505
4506   return false;
4507 }
4508
4509
4510
4511 /* Dump points-to information to OUTFILE.  */
4512
4513 void
4514 dump_sa_points_to_info (FILE *outfile)
4515 {
4516   unsigned int i;
4517
4518   fprintf (outfile, "\nPoints-to sets\n\n");
4519
4520   if (dump_flags & TDF_STATS)
4521     {
4522       fprintf (outfile, "Stats:\n");
4523       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
4524       fprintf (outfile, "Non-pointer vars:          %d\n",
4525                stats.nonpointer_vars);
4526       fprintf (outfile, "Statically unified vars:  %d\n",
4527                stats.unified_vars_static);
4528       fprintf (outfile, "Dynamically unified vars: %d\n",
4529                stats.unified_vars_dynamic);
4530       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
4531       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
4532       fprintf (outfile, "Number of implicit edges: %d\n",
4533                stats.num_implicit_edges);
4534     }
4535
4536   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
4537     dump_solution_for_var (outfile, i);
4538 }
4539
4540
4541 /* Debug points-to information to stderr.  */
4542
4543 void
4544 debug_sa_points_to_info (void)
4545 {
4546   dump_sa_points_to_info (stderr);
4547 }
4548
4549
4550 /* Initialize the always-existing constraint variables for NULL
4551    ANYTHING, READONLY, and INTEGER */
4552
4553 static void
4554 init_base_vars (void)
4555 {
4556   struct constraint_expr lhs, rhs;
4557
4558   /* Create the NULL variable, used to represent that a variable points
4559      to NULL.  */
4560   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
4561   var_nothing = new_var_info (nothing_tree, 0, "NULL");
4562   insert_vi_for_tree (nothing_tree, var_nothing);
4563   var_nothing->is_artificial_var = 1;
4564   var_nothing->offset = 0;
4565   var_nothing->size = ~0;
4566   var_nothing->fullsize = ~0;
4567   var_nothing->is_special_var = 1;
4568   nothing_id = 0;
4569   VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
4570
4571   /* Create the ANYTHING variable, used to represent that a variable
4572      points to some unknown piece of memory.  */
4573   anything_tree = create_tmp_var_raw (void_type_node, "ANYTHING");
4574   var_anything = new_var_info (anything_tree, 1, "ANYTHING");
4575   insert_vi_for_tree (anything_tree, var_anything);
4576   var_anything->is_artificial_var = 1;
4577   var_anything->size = ~0;
4578   var_anything->offset = 0;
4579   var_anything->next = NULL;
4580   var_anything->fullsize = ~0;
4581   var_anything->is_special_var = 1;
4582   anything_id = 1;
4583
4584   /* Anything points to anything.  This makes deref constraints just
4585      work in the presence of linked list and other p = *p type loops,
4586      by saying that *ANYTHING = ANYTHING. */
4587   VEC_safe_push (varinfo_t, heap, varmap, var_anything);
4588   lhs.type = SCALAR;
4589   lhs.var = anything_id;
4590   lhs.offset = 0;
4591   rhs.type = ADDRESSOF;
4592   rhs.var = anything_id;
4593   rhs.offset = 0;
4594
4595   /* This specifically does not use process_constraint because
4596      process_constraint ignores all anything = anything constraints, since all
4597      but this one are redundant.  */
4598   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
4599
4600   /* Create the READONLY variable, used to represent that a variable
4601      points to readonly memory.  */
4602   readonly_tree = create_tmp_var_raw (void_type_node, "READONLY");
4603   var_readonly = new_var_info (readonly_tree, 2, "READONLY");
4604   var_readonly->is_artificial_var = 1;
4605   var_readonly->offset = 0;
4606   var_readonly->size = ~0;
4607   var_readonly->fullsize = ~0;
4608   var_readonly->next = NULL;
4609   var_readonly->is_special_var = 1;
4610   insert_vi_for_tree (readonly_tree, var_readonly);
4611   readonly_id = 2;
4612   VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
4613
4614   /* readonly memory points to anything, in order to make deref
4615      easier.  In reality, it points to anything the particular
4616      readonly variable can point to, but we don't track this
4617      separately. */
4618   lhs.type = SCALAR;
4619   lhs.var = readonly_id;
4620   lhs.offset = 0;
4621   rhs.type = ADDRESSOF;
4622   rhs.var = anything_id;
4623   rhs.offset = 0;
4624
4625   process_constraint (new_constraint (lhs, rhs));
4626
4627   /* Create the INTEGER variable, used to represent that a variable points
4628      to an INTEGER.  */
4629   integer_tree = create_tmp_var_raw (void_type_node, "INTEGER");
4630   var_integer = new_var_info (integer_tree, 3, "INTEGER");
4631   insert_vi_for_tree (integer_tree, var_integer);
4632   var_integer->is_artificial_var = 1;
4633   var_integer->size = ~0;
4634   var_integer->fullsize = ~0;
4635   var_integer->offset = 0;
4636   var_integer->next = NULL;
4637   var_integer->is_special_var = 1;
4638   integer_id = 3;
4639   VEC_safe_push (varinfo_t, heap, varmap, var_integer);
4640
4641   /* INTEGER = ANYTHING, because we don't know where a dereference of
4642      a random integer will point to.  */
4643   lhs.type = SCALAR;
4644   lhs.var = integer_id;
4645   lhs.offset = 0;
4646   rhs.type = ADDRESSOF;
4647   rhs.var = anything_id;
4648   rhs.offset = 0;
4649   process_constraint (new_constraint (lhs, rhs));
4650 }
4651
4652 /* Initialize things necessary to perform PTA */
4653
4654 static void
4655 init_alias_vars (void)
4656 {
4657   bitmap_obstack_initialize (&pta_obstack);
4658   bitmap_obstack_initialize (&oldpta_obstack);
4659   bitmap_obstack_initialize (&predbitmap_obstack);
4660
4661   constraint_pool = create_alloc_pool ("Constraint pool",
4662                                        sizeof (struct constraint), 30);
4663   variable_info_pool = create_alloc_pool ("Variable info pool",
4664                                           sizeof (struct variable_info), 30);
4665   constraints = VEC_alloc (constraint_t, heap, 8);
4666   varmap = VEC_alloc (varinfo_t, heap, 8);
4667   vi_for_tree = pointer_map_create ();
4668
4669   memset (&stats, 0, sizeof (stats));
4670   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
4671                                      shared_bitmap_eq, free);
4672   init_base_vars ();
4673 }
4674
4675 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
4676    predecessor edges.  */
4677
4678 static void
4679 remove_preds_and_fake_succs (constraint_graph_t graph)
4680 {
4681   unsigned int i;
4682
4683   /* Clear the implicit ref and address nodes from the successor
4684      lists.  */
4685   for (i = 0; i < FIRST_REF_NODE; i++)
4686     {
4687       if (graph->succs[i])
4688         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
4689                             FIRST_REF_NODE * 2);
4690     }
4691
4692   /* Free the successor list for the non-ref nodes.  */
4693   for (i = FIRST_REF_NODE; i < graph->size; i++)
4694     {
4695       if (graph->succs[i])
4696         BITMAP_FREE (graph->succs[i]);
4697     }
4698
4699   /* Now reallocate the size of the successor list as, and blow away
4700      the predecessor bitmaps.  */
4701   graph->size = VEC_length (varinfo_t, varmap);
4702   graph->succs = xrealloc (graph->succs, graph->size * sizeof (bitmap));
4703
4704   free (graph->implicit_preds);
4705   graph->implicit_preds = NULL;
4706   free (graph->preds);
4707   graph->preds = NULL;
4708   bitmap_obstack_release (&predbitmap_obstack);
4709 }
4710
4711 /* Create points-to sets for the current function.  See the comments
4712    at the start of the file for an algorithmic overview.  */
4713
4714 void
4715 compute_points_to_sets (struct alias_info *ai)
4716 {
4717   struct scc_info *si;
4718   basic_block bb;
4719
4720   timevar_push (TV_TREE_PTA);
4721
4722   init_alias_vars ();
4723   init_alias_heapvars ();
4724
4725   intra_create_variable_infos ();
4726
4727   /* Now walk all statements and derive aliases.  */
4728   FOR_EACH_BB (bb)
4729     {
4730       block_stmt_iterator bsi;
4731       tree phi;
4732
4733       for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
4734         {
4735           if (is_gimple_reg (PHI_RESULT (phi)))
4736             {
4737               find_func_aliases (phi);
4738
4739               /* Update various related attributes like escaped
4740                  addresses, pointer dereferences for loads and stores.
4741                  This is used when creating name tags and alias
4742                  sets.  */
4743               update_alias_info (phi, ai);
4744             }
4745         }
4746
4747       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4748         {
4749           tree stmt = bsi_stmt (bsi);
4750
4751           find_func_aliases (stmt);
4752
4753           /* Update various related attributes like escaped
4754              addresses, pointer dereferences for loads and stores.
4755              This is used when creating name tags and alias
4756              sets.  */
4757           update_alias_info (stmt, ai);
4758         }
4759     }
4760
4761
4762   if (dump_file)
4763     {
4764       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
4765       dump_constraints (dump_file);
4766     }
4767
4768   if (dump_file)
4769     fprintf (dump_file,
4770              "\nCollapsing static cycles and doing variable "
4771              "substitution:\n");
4772   build_pred_graph ();
4773   si = perform_var_substitution (graph);
4774   move_complex_constraints (graph, si);
4775   free_var_substitution_info (si);
4776
4777   build_succ_graph ();
4778   find_indirect_cycles (graph);
4779
4780   /* Implicit nodes and predecessors are no longer necessary at this
4781      point. */
4782   remove_preds_and_fake_succs (graph);
4783
4784   if (dump_file)
4785     fprintf (dump_file, "\nSolving graph:\n");
4786
4787   solve_graph (graph);
4788
4789   if (dump_file)
4790     dump_sa_points_to_info (dump_file);
4791
4792   have_alias_info = true;
4793
4794   timevar_pop (TV_TREE_PTA);
4795 }
4796
4797
4798 /* Delete created points-to sets.  */
4799
4800 void
4801 delete_points_to_sets (void)
4802 {
4803   varinfo_t v;
4804   int i;
4805
4806   htab_delete (shared_bitmap_table);
4807   if (dump_file && (dump_flags & TDF_STATS))
4808     fprintf (dump_file, "Points to sets created:%d\n",
4809              stats.points_to_sets_created);
4810
4811   pointer_map_destroy (vi_for_tree);
4812   bitmap_obstack_release (&pta_obstack);
4813   VEC_free (constraint_t, heap, constraints);
4814
4815   for (i = 0; VEC_iterate (varinfo_t, varmap, i, v); i++)
4816     VEC_free (constraint_t, heap, graph->complex[i]);
4817
4818   free (graph->rep);
4819   free (graph->succs);
4820   free (graph->indirect_cycles);
4821   free (graph);
4822
4823   VEC_free (varinfo_t, heap, varmap);
4824   free_alloc_pool (variable_info_pool);
4825   free_alloc_pool (constraint_pool);
4826   have_alias_info = false;
4827 }
4828
4829 /* Return true if we should execute IPA PTA.  */
4830 static bool
4831 gate_ipa_pta (void)
4832 {
4833   return (flag_unit_at_a_time != 0
4834           && flag_ipa_pta
4835           /* Don't bother doing anything if the program has errors.  */
4836           && !(errorcount || sorrycount));
4837 }
4838
4839 /* Execute the driver for IPA PTA.  */
4840 static unsigned int
4841 ipa_pta_execute (void)
4842 {
4843   struct cgraph_node *node;
4844   struct scc_info *si;
4845
4846   in_ipa_mode = 1;
4847   init_alias_heapvars ();
4848   init_alias_vars ();
4849
4850   for (node = cgraph_nodes; node; node = node->next)
4851     {
4852       if (!node->analyzed || cgraph_is_master_clone (node))
4853         {
4854           unsigned int varid;
4855
4856           varid = create_function_info_for (node->decl,
4857                                             cgraph_node_name (node));
4858           if (node->local.externally_visible)
4859             {
4860               varinfo_t fi = get_varinfo (varid);
4861               for (; fi; fi = fi->next)
4862                 make_constraint_from_anything (fi);
4863             }
4864         }
4865     }
4866   for (node = cgraph_nodes; node; node = node->next)
4867     {
4868       if (node->analyzed && cgraph_is_master_clone (node))
4869         {
4870           struct function *cfun = DECL_STRUCT_FUNCTION (node->decl);
4871           basic_block bb;
4872           tree old_func_decl = current_function_decl;
4873           if (dump_file)
4874             fprintf (dump_file,
4875                      "Generating constraints for %s\n",
4876                      cgraph_node_name (node));
4877           push_cfun (cfun);
4878           current_function_decl = node->decl;
4879
4880           FOR_EACH_BB_FN (bb, cfun)
4881             {
4882               block_stmt_iterator bsi;
4883               tree phi;
4884
4885               for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
4886                 {
4887                   if (is_gimple_reg (PHI_RESULT (phi)))
4888                     {
4889                       find_func_aliases (phi);
4890                     }
4891                 }
4892
4893               for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4894                 {
4895                   tree stmt = bsi_stmt (bsi);
4896                   find_func_aliases (stmt);
4897                 }
4898             }
4899           current_function_decl = old_func_decl;
4900           pop_cfun ();
4901         }
4902       else
4903         {
4904           /* Make point to anything.  */
4905         }
4906     }
4907
4908
4909
4910   if (dump_file)
4911     {
4912       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
4913       dump_constraints (dump_file);
4914     }
4915
4916   if (dump_file)
4917     fprintf (dump_file,
4918              "\nCollapsing static cycles and doing variable "
4919              "substitution:\n");
4920
4921   build_pred_graph ();
4922   si = perform_var_substitution (graph);
4923   move_complex_constraints (graph, si);
4924   free_var_substitution_info (si);
4925
4926   build_succ_graph ();
4927   find_indirect_cycles (graph);
4928
4929   /* Implicit nodes and predecessors are no longer necessary at this
4930      point. */
4931   remove_preds_and_fake_succs (graph);
4932
4933   if (dump_file)
4934     fprintf (dump_file, "\nSolving graph:\n");
4935
4936   solve_graph (graph);
4937
4938   if (dump_file)
4939     dump_sa_points_to_info (dump_file);
4940
4941   in_ipa_mode = 0;
4942   delete_alias_heapvars ();
4943   delete_points_to_sets ();
4944   return 0;
4945 }
4946
4947 struct tree_opt_pass pass_ipa_pta =
4948 {
4949   "pta",                                /* name */
4950   gate_ipa_pta,                 /* gate */
4951   ipa_pta_execute,                      /* execute */
4952   NULL,                                 /* sub */
4953   NULL,                                 /* next */
4954   0,                                    /* static_pass_number */
4955   TV_IPA_PTA,                   /* tv_id */
4956   0,                                    /* properties_required */
4957   0,                                    /* properties_provided */
4958   0,                                    /* properties_destroyed */
4959   0,                                    /* todo_flags_start */
4960   0,                                    /* todo_flags_finish */
4961   0                                     /* letter */
4962 };
4963
4964 /* Initialize the heapvar for statement mapping.  */
4965 void
4966 init_alias_heapvars (void)
4967 {
4968   if (!heapvar_for_stmt)
4969     heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
4970                                         NULL);
4971 }
4972
4973 void
4974 delete_alias_heapvars (void)
4975 {
4976   htab_delete (heapvar_for_stmt);
4977   heapvar_for_stmt = NULL;
4978 }
4979
4980
4981 #include "gt-tree-ssa-structalias.h"