OSDN Git Service

Fix typo
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005 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 "tree-ssa-structalias.h"
52
53 /* The idea behind this analyzer is to generate set constraints from the
54    program, then solve the resulting constraints in order to generate the
55    points-to sets. 
56
57    Set constraints are a way of modeling program analysis problems that
58    involve sets.  They consist of an inclusion constraint language,
59    describing the variables (each variable is a set) and operations that
60    are involved on the variables, and a set of rules that derive facts
61    from these operations.  To solve a system of set constraints, you derive
62    all possible facts under the rules, which gives you the correct sets
63    as a consequence.
64
65    See  "Efficient Field-sensitive pointer analysis for C" by "David
66    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
67    http://citeseer.ist.psu.edu/pearce04efficient.html
68
69    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
70    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
71    http://citeseer.ist.psu.edu/heintze01ultrafast.html 
72
73    There are three types of constraint expressions, DEREF, ADDRESSOF, and
74    SCALAR.  Each constraint expression consists of a constraint type,
75    a variable, and an offset.  
76    
77    SCALAR is a constraint expression type used to represent x, whether
78    it appears on the LHS or the RHS of a statement.
79    DEREF is a constraint expression type used to represent *x, whether
80    it appears on the LHS or the RHS of a statement. 
81    ADDRESSOF is a constraint expression used to represent &x, whether
82    it appears on the LHS or the RHS of a statement.
83    
84    Each pointer variable in the program is assigned an integer id, and
85    each field of a structure variable is assigned an integer id as well.
86    
87    Structure variables are linked to their list of fields through a "next
88    field" in each variable that points to the next field in offset
89    order.  
90    Each variable for a structure field has 
91
92    1. "size", that tells the size in bits of that field.
93    2. "fullsize, that tells the size in bits of the entire structure.
94    3. "offset", that tells the offset in bits from the beginning of the
95    structure to this field.
96
97    Thus, 
98    struct f
99    {
100      int a;
101      int b;
102    } foo;
103    int *bar;
104
105    looks like
106
107    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
108    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
109    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
110
111    
112   In order to solve the system of set constraints, the following is
113   done:
114
115   1. Each constraint variable x has a solution set associated with it,
116   Sol(x).
117   
118   2. Constraints are separated into direct, copy, and complex.
119   Direct constraints are ADDRESSOF constraints that require no extra
120   processing, such as P = &Q
121   Copy constraints are those of the form P = Q.
122   Complex constraints are all the constraints involving dereferences.
123   
124   3. All direct constraints of the form P = &Q are processed, such
125   that Q is added to Sol(P) 
126
127   4. All complex constraints for a given constraint variable are stored in a
128   linked list attached to that variable's node.  
129
130   5. A directed graph is built out of the copy constraints. Each
131   constraint variable is a node in the graph, and an edge from 
132   Q to P is added for each copy constraint of the form P = Q
133   
134   6. The graph is then walked, and solution sets are
135   propagated along the copy edges, such that an edge from Q to P
136   causes Sol(P) <- Sol(P) union Sol(Q).
137   
138   7.  As we visit each node, all complex constraints associated with
139   that node are processed by adding appropriate copy edges to the graph, or the
140   appropriate variables to the solution set.  
141
142   8. The process of walking the graph is iterated until no solution
143   sets change.
144
145   Prior to walking the graph in steps 6 and 7, We perform static
146   cycle elimination on the constraint graph, as well 
147   as off-line variable substitution.
148   
149   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
150   on and turned into anything), but isn't.  You can just see what offset
151   inside the pointed-to struct it's going to access.
152   
153   TODO: Constant bounded arrays can be handled as if they were structs of the
154   same number of elements. 
155
156   TODO: Modeling heap and incoming pointers becomes much better if we
157   add fields to them as we discover them, which we could do.
158
159   TODO: We could handle unions, but to be honest, it's probably not
160   worth the pain or slowdown.  */
161
162 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map))) 
163   htab_t heapvar_for_stmt;
164 static bool use_field_sensitive = true;
165 static unsigned int create_variable_info_for (tree, const char *);
166 static struct constraint_expr get_constraint_for (tree, bool *);
167 static void build_constraint_graph (void);
168
169 static bitmap_obstack ptabitmap_obstack;
170 static bitmap_obstack iteration_obstack;
171 DEF_VEC_P(constraint_t);
172 DEF_VEC_ALLOC_P(constraint_t,heap);
173
174 static struct constraint_stats
175 {
176   unsigned int total_vars;
177   unsigned int collapsed_vars;
178   unsigned int unified_vars_static;
179   unsigned int unified_vars_dynamic;
180   unsigned int iterations;
181 } stats;
182
183 struct variable_info
184 {
185   /* ID of this variable  */
186   unsigned int id;
187
188   /* Name of this variable */
189   const char *name;
190
191   /* Tree that this variable is associated with.  */
192   tree decl;
193
194   /* Offset of this variable, in bits, from the base variable  */
195   unsigned HOST_WIDE_INT offset;  
196
197   /* Size of the variable, in bits.  */
198   unsigned HOST_WIDE_INT size;
199
200   /* Full size of the base variable, in bits.  */
201   unsigned HOST_WIDE_INT fullsize;
202
203   /* A link to the variable for the next field in this structure.  */
204   struct variable_info *next;
205
206   /* Node in the graph that represents the constraints and points-to
207      solution for the variable.  */
208   unsigned int node;
209
210   /* True if the address of this variable is taken.  Needed for
211      variable substitution.  */
212   unsigned int address_taken:1;
213
214   /* True if this variable is the target of a dereference.  Needed for
215      variable substitution.  */
216   unsigned int indirect_target:1;
217
218   /* True if this is a variable created by the constraint analysis, such as
219      heap variables and constraints we had to break up.  */
220   unsigned int is_artificial_var:1;
221   
222   /* True if this is a special variable whose solution set should not be
223      changed.  */
224   unsigned int is_special_var:1;
225
226   /* True for variables whose size is not known or variable.  */
227   unsigned int is_unknown_size_var:1;  
228
229   /* True for variables that have unions somewhere in them.  */
230   unsigned int has_union:1;
231
232   /* True if this is a heap variable.  */
233   unsigned int is_heap_var:1;
234
235   /* Points-to set for this variable.  */
236   bitmap solution;
237
238   /* Variable ids represented by this node.  */
239   bitmap variables;
240
241   /* Vector of complex constraints for this node.  Complex
242      constraints are those involving dereferences.  */
243   VEC(constraint_t,heap) *complex;
244   
245   /* Variable id this was collapsed to due to type unsafety.
246      This should be unused completely after build_constraint_graph, or
247      something is broken.  */
248   struct variable_info *collapsed_to;
249 };
250 typedef struct variable_info *varinfo_t;
251
252 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
253
254 /* Pool of variable info structures.  */
255 static alloc_pool variable_info_pool;
256
257 DEF_VEC_P(varinfo_t);
258
259 DEF_VEC_ALLOC_P(varinfo_t, heap);
260
261 /* Table of variable info structures for constraint variables.  Indexed directly
262    by variable info id.  */
263 static VEC(varinfo_t,heap) *varmap;
264
265 /* Return the varmap element N */
266
267 static inline varinfo_t
268 get_varinfo (unsigned int n)
269 {
270   return VEC_index(varinfo_t, varmap, n);
271 }
272
273 /* Return the varmap element N, following the collapsed_to link.  */
274
275 static inline varinfo_t
276 get_varinfo_fc (unsigned int n)
277 {
278   varinfo_t v = VEC_index(varinfo_t, varmap, n);
279
280   if (v->collapsed_to)
281     return v->collapsed_to;
282   return v;
283 }
284
285 /* Variable that represents the unknown pointer.  */
286 static varinfo_t var_anything;
287 static tree anything_tree;
288 static unsigned int anything_id;
289
290 /* Variable that represents the NULL pointer.  */
291 static varinfo_t var_nothing;
292 static tree nothing_tree;
293 static unsigned int nothing_id;
294
295 /* Variable that represents read only memory.  */
296 static varinfo_t var_readonly;
297 static tree readonly_tree;
298 static unsigned int readonly_id;
299
300 /* Variable that represents integers.  This is used for when people do things
301    like &0->a.b.  */
302 static varinfo_t var_integer;
303 static tree integer_tree;
304 static unsigned int integer_id;
305
306 /* Variable that represents arbitrary offsets into an object.  Used to
307    represent pointer arithmetic, which may not legally escape the
308    bounds of an object.  */
309 static varinfo_t var_anyoffset;
310 static tree anyoffset_tree;
311 static unsigned int anyoffset_id;
312
313
314 /* Lookup a heap var for FROM, and return it if we find one.  */
315
316 static tree 
317 heapvar_lookup (tree from)
318 {
319   struct tree_map *h, in;
320   in.from = from;
321
322   h = htab_find_with_hash (heapvar_for_stmt, &in, htab_hash_pointer (from));
323   if (h)
324     return h->to;
325   return NULL_TREE;
326 }
327
328 /* Insert a mapping FROM->TO in the heap var for statement
329    hashtable.  */
330
331 static void
332 heapvar_insert (tree from, tree to)
333 {
334   struct tree_map *h;
335   void **loc;
336
337   h = ggc_alloc (sizeof (struct tree_map));
338   h->hash = htab_hash_pointer (from);
339   h->from = from;
340   h->to = to;
341   loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
342   *(struct tree_map **) loc = h;
343 }  
344
345 /* Return a new variable info structure consisting for a variable
346    named NAME, and using constraint graph node NODE.  */
347
348 static varinfo_t
349 new_var_info (tree t, unsigned int id, const char *name, unsigned int node)
350 {
351   varinfo_t ret = pool_alloc (variable_info_pool);
352
353   ret->id = id;
354   ret->name = name;
355   ret->decl = t;
356   ret->node = node;
357   ret->address_taken = false;
358   ret->indirect_target = false;
359   ret->is_artificial_var = false;
360   ret->is_heap_var = false;
361   ret->is_special_var = false;
362   ret->is_unknown_size_var = false;
363   ret->has_union = false;
364   ret->solution = BITMAP_ALLOC (&ptabitmap_obstack);
365   bitmap_clear (ret->solution);
366   ret->variables = BITMAP_ALLOC (&ptabitmap_obstack);
367   bitmap_clear (ret->variables);
368   ret->complex = NULL;
369   ret->next = NULL;
370   ret->collapsed_to = NULL;
371   return ret;
372 }
373
374 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
375
376 /* An expression that appears in a constraint.  */
377
378 struct constraint_expr 
379 {
380   /* Constraint type.  */
381   constraint_expr_type type;
382
383   /* Variable we are referring to in the constraint.  */
384   unsigned int var;
385
386   /* Offset, in bits, of this constraint from the beginning of
387      variables it ends up referring to.
388
389      IOW, in a deref constraint, we would deref, get the result set,
390      then add OFFSET to each member.   */
391   unsigned HOST_WIDE_INT offset;
392 };
393
394 static struct constraint_expr do_deref (struct constraint_expr);
395
396 /* Our set constraints are made up of two constraint expressions, one
397    LHS, and one RHS.  
398
399    As described in the introduction, our set constraints each represent an
400    operation between set valued variables.
401 */
402 struct constraint
403 {
404   struct constraint_expr lhs;
405   struct constraint_expr rhs;
406 };
407
408 /* List of constraints that we use to build the constraint graph from.  */
409
410 static VEC(constraint_t,heap) *constraints;
411 static alloc_pool constraint_pool;
412
413 /* An edge in the constraint graph.  We technically have no use for
414    the src, since it will always be the same node that we are indexing
415    into the pred/succ arrays with, but it's nice for checking
416    purposes.  The edges are weighted, with a bit set in weights for
417    each edge from src to dest with that weight.  */
418
419 struct constraint_edge
420 {
421   unsigned int src;
422   unsigned int dest;
423   bitmap weights;
424 };
425
426 typedef struct constraint_edge *constraint_edge_t;
427 static alloc_pool constraint_edge_pool;
428
429 /* Return a new constraint edge from SRC to DEST.  */
430
431 static constraint_edge_t
432 new_constraint_edge (unsigned int src, unsigned int dest)
433 {
434   constraint_edge_t ret = pool_alloc (constraint_edge_pool);
435   ret->src = src;
436   ret->dest = dest;
437   ret->weights = NULL;
438   return ret;
439 }
440
441 DEF_VEC_P(constraint_edge_t);
442 DEF_VEC_ALLOC_P(constraint_edge_t,heap);
443
444
445 /* The constraint graph is simply a set of adjacency vectors, one per
446    variable. succs[x] is the vector of successors for variable x, and preds[x]
447    is the vector of predecessors for variable x. 
448    IOW, all edges are "forward" edges, which is not like our CFG.  
449    So remember that
450    preds[x]->src == x, and
451    succs[x]->src == x.  */
452
453 struct constraint_graph
454 {
455   VEC(constraint_edge_t,heap) **succs;
456   VEC(constraint_edge_t,heap) **preds;
457 };
458
459 typedef struct constraint_graph *constraint_graph_t;
460
461 static constraint_graph_t graph;
462
463 /* Create a new constraint consisting of LHS and RHS expressions.  */
464
465 static constraint_t 
466 new_constraint (const struct constraint_expr lhs,
467                 const struct constraint_expr rhs)
468 {
469   constraint_t ret = pool_alloc (constraint_pool);
470   ret->lhs = lhs;
471   ret->rhs = rhs;
472   return ret;
473 }
474
475 /* Print out constraint C to FILE.  */
476
477 void
478 dump_constraint (FILE *file, constraint_t c)
479 {
480   if (c->lhs.type == ADDRESSOF)
481     fprintf (file, "&");
482   else if (c->lhs.type == DEREF)
483     fprintf (file, "*");  
484   fprintf (file, "%s", get_varinfo_fc (c->lhs.var)->name);
485   if (c->lhs.offset != 0)
486     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
487   fprintf (file, " = ");
488   if (c->rhs.type == ADDRESSOF)
489     fprintf (file, "&");
490   else if (c->rhs.type == DEREF)
491     fprintf (file, "*");
492   fprintf (file, "%s", get_varinfo_fc (c->rhs.var)->name);
493   if (c->rhs.offset != 0)
494     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
495   fprintf (file, "\n");
496 }
497
498 /* Print out constraint C to stderr.  */
499
500 void
501 debug_constraint (constraint_t c)
502 {
503   dump_constraint (stderr, c);
504 }
505
506 /* Print out all constraints to FILE */
507
508 void
509 dump_constraints (FILE *file)
510 {
511   int i;
512   constraint_t c;
513   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
514     dump_constraint (file, c);
515 }
516
517 /* Print out all constraints to stderr.  */
518
519 void
520 debug_constraints (void)
521 {
522   dump_constraints (stderr);
523 }
524
525 /* SOLVER FUNCTIONS 
526
527    The solver is a simple worklist solver, that works on the following
528    algorithm:
529    
530    sbitmap changed_nodes = all ones;
531    changed_count = number of nodes;
532    For each node that was already collapsed:
533        changed_count--;
534
535
536    while (changed_count > 0)
537    {
538      compute topological ordering for constraint graph
539   
540      find and collapse cycles in the constraint graph (updating
541      changed if necessary)
542      
543      for each node (n) in the graph in topological order:
544        changed_count--;
545
546        Process each complex constraint associated with the node,
547        updating changed if necessary.
548
549        For each outgoing edge from n, propagate the solution from n to
550        the destination of the edge, updating changed as necessary.
551
552    }  */
553
554 /* Return true if two constraint expressions A and B are equal.  */
555
556 static bool
557 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
558 {
559   return a.type == b.type
560     && a.var == b.var
561     && a.offset == b.offset;
562 }
563
564 /* Return true if constraint expression A is less than constraint expression
565    B.  This is just arbitrary, but consistent, in order to give them an
566    ordering.  */
567
568 static bool
569 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
570 {
571   if (a.type == b.type)
572     {
573       if (a.var == b.var)
574         return a.offset < b.offset;
575       else
576         return a.var < b.var;
577     }
578   else
579     return a.type < b.type;
580 }
581
582 /* Return true if constraint A is less than constraint B.  This is just
583    arbitrary, but consistent, in order to give them an ordering.  */
584
585 static bool
586 constraint_less (const constraint_t a, const constraint_t b)
587 {
588   if (constraint_expr_less (a->lhs, b->lhs))
589     return true;
590   else if (constraint_expr_less (b->lhs, a->lhs))
591     return false;
592   else
593     return constraint_expr_less (a->rhs, b->rhs);
594 }
595
596 /* Return true if two constraints A and B are equal.  */
597   
598 static bool
599 constraint_equal (struct constraint a, struct constraint b)
600 {
601   return constraint_expr_equal (a.lhs, b.lhs) 
602     && constraint_expr_equal (a.rhs, b.rhs);
603 }
604
605
606 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
607
608 static constraint_t
609 constraint_vec_find (VEC(constraint_t,heap) *vec,
610                      struct constraint lookfor)
611 {
612   unsigned int place;  
613   constraint_t found;
614
615   if (vec == NULL)
616     return NULL;
617
618   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
619   if (place >= VEC_length (constraint_t, vec))
620     return NULL;
621   found = VEC_index (constraint_t, vec, place);
622   if (!constraint_equal (*found, lookfor))
623     return NULL;
624   return found;
625 }
626
627 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
628
629 static void
630 constraint_set_union (VEC(constraint_t,heap) **to,
631                       VEC(constraint_t,heap) **from)
632 {
633   int i;
634   constraint_t c;
635
636   for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
637     {
638       if (constraint_vec_find (*to, *c) == NULL)
639         {
640           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
641                                                 constraint_less);
642           VEC_safe_insert (constraint_t, heap, *to, place, c);
643         }
644     }
645 }
646
647 /* Take a solution set SET, add OFFSET to each member of the set, and
648    overwrite SET with the result when done.  */
649
650 static void
651 solution_set_add (bitmap set, unsigned HOST_WIDE_INT offset)
652 {
653   bitmap result = BITMAP_ALLOC (&iteration_obstack);
654   unsigned int i;
655   bitmap_iterator bi;
656
657   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
658     {
659       /* If this is a properly sized variable, only add offset if it's
660          less than end.  Otherwise, it is globbed to a single
661          variable.  */
662       
663       if ((get_varinfo (i)->offset + offset) < get_varinfo (i)->fullsize)
664         {
665           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (i)->offset + offset;
666           varinfo_t v = first_vi_for_offset (get_varinfo (i), fieldoffset);
667           if (!v)
668             continue;
669           bitmap_set_bit (result, v->id);
670         }
671       else if (get_varinfo (i)->is_artificial_var 
672                || get_varinfo (i)->has_union
673                || get_varinfo (i)->is_unknown_size_var)
674         {
675           bitmap_set_bit (result, i);
676         }
677     }
678   
679   bitmap_copy (set, result);  
680   BITMAP_FREE (result);
681 }
682
683 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
684    process.  */
685
686 static bool
687 set_union_with_increment  (bitmap to, bitmap from, unsigned HOST_WIDE_INT inc)
688 {
689   if (inc == 0)
690     return bitmap_ior_into (to, from);
691   else
692     {
693       bitmap tmp;
694       bool res;
695
696       tmp = BITMAP_ALLOC (&iteration_obstack);
697       bitmap_copy (tmp, from);
698       solution_set_add (tmp, inc);
699       res = bitmap_ior_into (to, tmp);
700       BITMAP_FREE (tmp);
701       return res;
702     }
703 }
704
705 /* Insert constraint C into the list of complex constraints for VAR.  */
706
707 static void
708 insert_into_complex (unsigned int var, constraint_t c)
709 {
710   varinfo_t vi = get_varinfo (var);
711   unsigned int place = VEC_lower_bound (constraint_t, vi->complex, c,
712                                         constraint_less);
713   VEC_safe_insert (constraint_t, heap, vi->complex, place, c);
714 }
715
716
717 /* Compare two constraint edges A and B, return true if they are equal.  */
718
719 static bool
720 constraint_edge_equal (struct constraint_edge a, struct constraint_edge b)
721 {
722   return a.src == b.src && a.dest == b.dest;
723 }
724
725 /* Compare two constraint edges, return true if A is less than B */
726
727 static bool
728 constraint_edge_less (const constraint_edge_t a, const constraint_edge_t b)
729 {
730   if (a->dest < b->dest)
731     return true;
732   else if (a->dest == b->dest)
733     return a->src < b->src;
734   else
735     return false;
736 }
737
738 /* Find the constraint edge that matches LOOKFOR, in VEC.
739    Return the edge, if found, NULL otherwise.  */
740
741 static constraint_edge_t 
742 constraint_edge_vec_find (VEC(constraint_edge_t,heap) *vec, 
743                           struct constraint_edge lookfor)
744 {
745   unsigned int place;  
746   constraint_edge_t edge;
747
748   place = VEC_lower_bound (constraint_edge_t, vec, &lookfor, 
749                            constraint_edge_less);
750   edge = VEC_index (constraint_edge_t, vec, place);
751   if (!constraint_edge_equal (*edge, lookfor))
752     return NULL;
753   return edge;
754 }
755
756 /* Condense two variable nodes into a single variable node, by moving
757    all associated info from SRC to TO.  */
758
759 static void 
760 condense_varmap_nodes (unsigned int to, unsigned int src)
761 {
762   varinfo_t tovi = get_varinfo (to);
763   varinfo_t srcvi = get_varinfo (src);
764   unsigned int i;
765   constraint_t c;
766   bitmap_iterator bi;
767   
768   /* the src node, and all its variables, are now the to node.  */
769   srcvi->node = to;
770   EXECUTE_IF_SET_IN_BITMAP (srcvi->variables, 0, i, bi)
771     get_varinfo (i)->node = to;
772   
773   /* Merge the src node variables and the to node variables.  */
774   bitmap_set_bit (tovi->variables, src);
775   bitmap_ior_into (tovi->variables, srcvi->variables);
776   bitmap_clear (srcvi->variables);
777   
778   /* Move all complex constraints from src node into to node  */
779   for (i = 0; VEC_iterate (constraint_t, srcvi->complex, i, c); i++)
780     {
781       /* In complex constraints for node src, we may have either
782          a = *src, and *src = a.  */
783       
784       if (c->rhs.type == DEREF)
785         c->rhs.var = to;
786       else
787         c->lhs.var = to;
788     }
789   constraint_set_union (&tovi->complex, &srcvi->complex);
790   VEC_free (constraint_t, heap, srcvi->complex);
791   srcvi->complex = NULL;
792 }
793
794 /* Erase EDGE from GRAPH.  This routine only handles self-edges
795    (e.g. an edge from a to a).  */
796
797 static void
798 erase_graph_self_edge (constraint_graph_t graph, struct constraint_edge edge)
799 {
800   VEC(constraint_edge_t,heap) *predvec = graph->preds[edge.src];
801   VEC(constraint_edge_t,heap) *succvec = graph->succs[edge.dest];
802   unsigned int place;
803   gcc_assert (edge.src == edge.dest);
804
805   /* Remove from the successors.  */
806   place = VEC_lower_bound (constraint_edge_t, succvec, &edge, 
807                            constraint_edge_less);
808   
809   /* Make sure we found the edge.  */
810 #ifdef ENABLE_CHECKING
811   {
812     constraint_edge_t tmp = VEC_index (constraint_edge_t, succvec, place);
813     gcc_assert (constraint_edge_equal (*tmp, edge));
814   }
815 #endif
816   VEC_ordered_remove (constraint_edge_t, succvec, place);
817
818   /* Remove from the predecessors.  */
819   place = VEC_lower_bound (constraint_edge_t, predvec, &edge,
820                            constraint_edge_less);
821
822   /* Make sure we found the edge.  */
823 #ifdef ENABLE_CHECKING
824   {
825     constraint_edge_t tmp = VEC_index (constraint_edge_t, predvec, place);
826     gcc_assert (constraint_edge_equal (*tmp, edge));
827   }
828 #endif
829   VEC_ordered_remove (constraint_edge_t, predvec, place);
830 }
831
832 /* Remove edges involving NODE from GRAPH.  */
833
834 static void
835 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
836 {
837   VEC(constraint_edge_t,heap) *succvec = graph->succs[node];
838   VEC(constraint_edge_t,heap) *predvec = graph->preds[node];
839   constraint_edge_t c;
840   int i;
841   
842   /* Walk the successors, erase the associated preds.  */
843   for (i = 0; VEC_iterate (constraint_edge_t, succvec, i, c); i++)
844     if (c->dest != node)
845       {
846         unsigned int place;
847         struct constraint_edge lookfor;
848         lookfor.src = c->dest;
849         lookfor.dest = node;
850         place = VEC_lower_bound (constraint_edge_t, graph->preds[c->dest], 
851                                  &lookfor, constraint_edge_less);
852         VEC_ordered_remove (constraint_edge_t, graph->preds[c->dest], place);
853       }
854   /* Walk the preds, erase the associated succs.  */
855   for (i =0; VEC_iterate (constraint_edge_t, predvec, i, c); i++)
856     if (c->dest != node)
857       {
858         unsigned int place;
859         struct constraint_edge lookfor;
860         lookfor.src = c->dest;
861         lookfor.dest = node;
862         place = VEC_lower_bound (constraint_edge_t, graph->succs[c->dest],
863                                  &lookfor, constraint_edge_less);
864         VEC_ordered_remove (constraint_edge_t, graph->succs[c->dest], place);
865       }    
866   
867   VEC_free (constraint_edge_t, heap, graph->preds[node]);
868   VEC_free (constraint_edge_t, heap, graph->succs[node]);
869   graph->preds[node] = NULL;
870   graph->succs[node] = NULL;
871 }
872
873 static bool edge_added = false;
874   
875 /* Add edge NEWE to the graph.  */
876
877 static bool
878 add_graph_edge (constraint_graph_t graph, struct constraint_edge newe)
879 {
880   unsigned int place;
881   unsigned int src = newe.src;
882   unsigned int dest = newe.dest;
883   VEC(constraint_edge_t,heap) *vec;
884
885   vec = graph->preds[src];
886   place = VEC_lower_bound (constraint_edge_t, vec, &newe, 
887                            constraint_edge_less);
888   if (place == VEC_length (constraint_edge_t, vec)
889       || VEC_index (constraint_edge_t, vec, place)->dest != dest)
890     {
891       constraint_edge_t edge = new_constraint_edge (src, dest);
892       bitmap weightbitmap;
893
894       weightbitmap = BITMAP_ALLOC (&ptabitmap_obstack);
895       edge->weights = weightbitmap;
896       VEC_safe_insert (constraint_edge_t, heap, graph->preds[edge->src], 
897                        place, edge);
898       edge = new_constraint_edge (dest, src);
899       edge->weights = weightbitmap;
900       place = VEC_lower_bound (constraint_edge_t, graph->succs[edge->src],
901                                edge, constraint_edge_less);
902       VEC_safe_insert (constraint_edge_t, heap, graph->succs[edge->src], 
903                        place, edge);
904       edge_added = true;
905       return true;
906     }
907   else
908     return false;
909 }
910
911
912 /* Return the bitmap representing the weights of edge LOOKFOR */
913
914 static bitmap
915 get_graph_weights (constraint_graph_t graph, struct constraint_edge lookfor)
916 {
917   constraint_edge_t edge;
918   unsigned int src = lookfor.src;
919   VEC(constraint_edge_t,heap) *vec;
920   vec = graph->preds[src];
921   edge = constraint_edge_vec_find (vec, lookfor);
922   gcc_assert (edge != NULL);
923   return edge->weights;
924 }
925
926
927 /* Merge GRAPH nodes FROM and TO into node TO.  */
928
929 static void
930 merge_graph_nodes (constraint_graph_t graph, unsigned int to, 
931                    unsigned int from)
932 {
933   VEC(constraint_edge_t,heap) *succvec = graph->succs[from];
934   VEC(constraint_edge_t,heap) *predvec = graph->preds[from];
935   int i;
936   constraint_edge_t c;
937   
938   /* Merge all the predecessor edges.  */
939
940   for (i = 0; VEC_iterate (constraint_edge_t, predvec, i, c); i++)
941     {
942       unsigned int d = c->dest;
943       struct constraint_edge olde;
944       struct constraint_edge newe;
945       bitmap temp;
946       bitmap weights;
947       if (c->dest == from)
948         d = to;
949       newe.src = to;
950       newe.dest = d;
951       add_graph_edge (graph, newe);
952       olde.src = from;
953       olde.dest = c->dest;
954       olde.weights = NULL;
955       temp = get_graph_weights (graph, olde);
956       weights = get_graph_weights (graph, newe);
957       bitmap_ior_into (weights, temp);
958     }
959   
960   /* Merge all the successor edges.  */
961   for (i = 0; VEC_iterate (constraint_edge_t, succvec, i, c); i++)
962     {
963       unsigned int d = c->dest;
964       struct constraint_edge olde;
965       struct constraint_edge newe;
966       bitmap temp;
967       bitmap weights;
968       if (c->dest == from)
969         d = to;
970       newe.src = d;
971       newe.dest = to;
972       add_graph_edge (graph, newe);
973       olde.src = c->dest;
974       olde.dest = from;
975       olde.weights = NULL;
976       temp = get_graph_weights (graph, olde);
977       weights = get_graph_weights (graph, newe);
978       bitmap_ior_into (weights, temp);
979     }
980   clear_edges_for_node (graph, from);
981 }
982
983 /* Add a graph edge to GRAPH, going from TO to FROM, with WEIGHT, if
984    it doesn't exist in the graph already.
985    Return false if the edge already existed, true otherwise.  */
986
987 static bool
988 int_add_graph_edge (constraint_graph_t graph, unsigned int to, 
989                     unsigned int from, unsigned HOST_WIDE_INT weight)
990 {
991   if (to == from && weight == 0)
992     {
993       return false;
994     }
995   else
996     {
997       bool r;
998       struct constraint_edge edge;
999       edge.src = to;
1000       edge.dest = from;
1001       edge.weights = NULL;
1002       r = add_graph_edge (graph, edge);
1003       r |= !bitmap_bit_p (get_graph_weights (graph, edge), weight);
1004       bitmap_set_bit (get_graph_weights (graph, edge), weight);
1005       return r;
1006     }
1007 }
1008
1009
1010 /* Return true if LOOKFOR is an existing graph edge.  */
1011
1012 static bool
1013 valid_graph_edge (constraint_graph_t graph, struct constraint_edge lookfor)
1014 {
1015   return constraint_edge_vec_find (graph->preds[lookfor.src], lookfor) != NULL;
1016 }
1017
1018
1019 /* Build the constraint graph.  */
1020
1021 static void
1022 build_constraint_graph (void)
1023 {
1024   int i = 0;
1025   constraint_t c;
1026
1027   graph = xmalloc (sizeof (struct constraint_graph));
1028   graph->succs = xcalloc (VEC_length (varinfo_t, varmap),
1029                           sizeof (*graph->succs));
1030   graph->preds = xcalloc (VEC_length (varinfo_t, varmap),
1031                           sizeof (*graph->preds));
1032
1033   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1034     {
1035       struct constraint_expr lhs = c->lhs;
1036       struct constraint_expr rhs = c->rhs;
1037       unsigned int lhsvar = get_varinfo_fc (lhs.var)->id;
1038       unsigned int rhsvar = get_varinfo_fc (rhs.var)->id;
1039
1040       if (lhs.type == DEREF)
1041         {
1042           /* *x = y or *x = &y (complex) */
1043           if (rhs.type == ADDRESSOF || rhsvar > anything_id)
1044             insert_into_complex (lhsvar, c);
1045         }
1046       else if (rhs.type == DEREF)
1047         {
1048           /* !special var= *y */
1049           if (!(get_varinfo (lhsvar)->is_special_var))
1050             insert_into_complex (rhsvar, c);
1051         }
1052       else if (rhs.type == ADDRESSOF)
1053         {
1054           /* x = &y */
1055           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1056         }
1057       else if (lhsvar > anything_id)
1058         {
1059           /* Ignore 0 weighted self edges, as they can't possibly contribute
1060              anything */
1061           if (lhsvar != rhsvar || rhs.offset != 0 || lhs.offset != 0)
1062             {
1063               
1064               struct constraint_edge edge;
1065               edge.src = lhsvar;
1066               edge.dest = rhsvar;
1067               /* x = y (simple) */
1068               add_graph_edge (graph, edge);
1069               bitmap_set_bit (get_graph_weights (graph, edge),
1070                               rhs.offset);
1071             }
1072           
1073         }
1074     }
1075 }
1076
1077
1078 /* Changed variables on the last iteration.  */
1079 static unsigned int changed_count;
1080 static sbitmap changed;
1081
1082 DEF_VEC_I(unsigned);
1083 DEF_VEC_ALLOC_I(unsigned,heap);
1084
1085
1086 /* Strongly Connected Component visitation info.  */
1087
1088 struct scc_info
1089 {
1090   sbitmap visited;
1091   sbitmap in_component;
1092   int current_index;
1093   unsigned int *visited_index;
1094   VEC(unsigned,heap) *scc_stack;
1095   VEC(unsigned,heap) *unification_queue;
1096 };
1097
1098
1099 /* Recursive routine to find strongly connected components in GRAPH.
1100    SI is the SCC info to store the information in, and N is the id of current
1101    graph node we are processing.
1102    
1103    This is Tarjan's strongly connected component finding algorithm, as
1104    modified by Nuutila to keep only non-root nodes on the stack.  
1105    The algorithm can be found in "On finding the strongly connected
1106    connected components in a directed graph" by Esko Nuutila and Eljas
1107    Soisalon-Soininen, in Information Processing Letters volume 49,
1108    number 1, pages 9-14.  */
1109
1110 static void
1111 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1112 {
1113   constraint_edge_t c;
1114   int i;
1115
1116   gcc_assert (get_varinfo (n)->node == n);
1117   SET_BIT (si->visited, n);
1118   RESET_BIT (si->in_component, n);
1119   si->visited_index[n] = si->current_index ++;
1120   
1121   /* Visit all the successors.  */
1122   for (i = 0; VEC_iterate (constraint_edge_t, graph->succs[n], i, c); i++)
1123     {
1124       /* We only want to find and collapse the zero weight edges. */
1125       if (bitmap_bit_p (c->weights, 0))
1126         {
1127           unsigned int w = c->dest;
1128           if (!TEST_BIT (si->visited, w))
1129             scc_visit (graph, si, w);
1130           if (!TEST_BIT (si->in_component, w))
1131             {
1132               unsigned int t = get_varinfo (w)->node;
1133               unsigned int nnode = get_varinfo (n)->node;
1134               if (si->visited_index[t] < si->visited_index[nnode])
1135                 get_varinfo (n)->node = t;
1136             }
1137         }
1138     }
1139   
1140   /* See if any components have been identified.  */
1141   if (get_varinfo (n)->node == n)
1142     {
1143       unsigned int t = si->visited_index[n];
1144       SET_BIT (si->in_component, n);
1145       while (VEC_length (unsigned, si->scc_stack) != 0 
1146              && t < si->visited_index[VEC_last (unsigned, si->scc_stack)])
1147         {
1148           unsigned int w = VEC_pop (unsigned, si->scc_stack);
1149           get_varinfo (w)->node = n;
1150           SET_BIT (si->in_component, w);
1151           /* Mark this node for collapsing.  */
1152           VEC_safe_push (unsigned, heap, si->unification_queue, w);
1153         } 
1154     }
1155   else
1156     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1157 }
1158
1159
1160 /* Collapse two variables into one variable.  */
1161
1162 static void
1163 collapse_nodes (constraint_graph_t graph, unsigned int to, unsigned int from)
1164 {
1165   bitmap tosol, fromsol;
1166   struct constraint_edge edge;
1167
1168
1169   condense_varmap_nodes (to, from);
1170   tosol = get_varinfo (to)->solution;
1171   fromsol = get_varinfo (from)->solution;
1172   bitmap_ior_into (tosol, fromsol);
1173   merge_graph_nodes (graph, to, from);
1174   edge.src = to;
1175   edge.dest = to;
1176   edge.weights = NULL;
1177   if (valid_graph_edge (graph, edge))
1178     {
1179       bitmap weights = get_graph_weights (graph, edge);
1180       bitmap_clear_bit (weights, 0);
1181       if (bitmap_empty_p (weights))
1182         erase_graph_self_edge (graph, edge);
1183     }
1184   bitmap_clear (fromsol);
1185   get_varinfo (to)->address_taken |= get_varinfo (from)->address_taken;
1186   get_varinfo (to)->indirect_target |= get_varinfo (from)->indirect_target;
1187 }
1188
1189
1190 /* Unify nodes in GRAPH that we have found to be part of a cycle.
1191    SI is the Strongly Connected Components information structure that tells us
1192    what components to unify.
1193    UPDATE_CHANGED should be set to true if the changed sbitmap and changed
1194    count should be updated to reflect the unification.  */
1195
1196 static void
1197 process_unification_queue (constraint_graph_t graph, struct scc_info *si,
1198                            bool update_changed)
1199 {
1200   size_t i = 0;
1201   bitmap tmp = BITMAP_ALLOC (update_changed ? &iteration_obstack : NULL);
1202   bitmap_clear (tmp);
1203
1204   /* We proceed as follows:
1205
1206      For each component in the queue (components are delineated by
1207      when current_queue_element->node != next_queue_element->node):
1208
1209         rep = representative node for component
1210
1211         For each node (tounify) to be unified in the component,
1212            merge the solution for tounify into tmp bitmap
1213
1214            clear solution for tounify
1215
1216            merge edges from tounify into rep
1217
1218            merge complex constraints from tounify into rep
1219
1220            update changed count to note that tounify will never change
1221            again
1222
1223         Merge tmp into solution for rep, marking rep changed if this
1224         changed rep's solution.
1225         
1226         Delete any 0 weighted self-edges we now have for rep.  */
1227   while (i != VEC_length (unsigned, si->unification_queue))
1228     {
1229       unsigned int tounify = VEC_index (unsigned, si->unification_queue, i);
1230       unsigned int n = get_varinfo (tounify)->node;
1231
1232       if (dump_file && (dump_flags & TDF_DETAILS))
1233         fprintf (dump_file, "Unifying %s to %s\n", 
1234                  get_varinfo (tounify)->name,
1235                  get_varinfo (n)->name);
1236       if (update_changed)
1237         stats.unified_vars_dynamic++;
1238       else
1239         stats.unified_vars_static++;
1240       bitmap_ior_into (tmp, get_varinfo (tounify)->solution);
1241       merge_graph_nodes (graph, n, tounify);
1242       condense_varmap_nodes (n, tounify);
1243       
1244       if (update_changed && TEST_BIT (changed, tounify))
1245         {
1246           RESET_BIT (changed, tounify);
1247           if (!TEST_BIT (changed, n))
1248             SET_BIT (changed, n);
1249           else
1250             {
1251               gcc_assert (changed_count > 0);
1252               changed_count--;
1253             }
1254         }
1255
1256       bitmap_clear (get_varinfo (tounify)->solution);
1257       ++i;
1258
1259       /* If we've either finished processing the entire queue, or
1260          finished processing all nodes for component n, update the solution for
1261          n.  */
1262       if (i == VEC_length (unsigned, si->unification_queue)
1263           || get_varinfo (VEC_index (unsigned, si->unification_queue, i))->node != n)
1264         {
1265           struct constraint_edge edge;
1266
1267           /* If the solution changes because of the merging, we need to mark
1268              the variable as changed.  */
1269           if (bitmap_ior_into (get_varinfo (n)->solution, tmp))
1270             {
1271               if (update_changed && !TEST_BIT (changed, n))
1272                 {
1273                   SET_BIT (changed, n);
1274                   changed_count++;
1275                 }
1276             }
1277           bitmap_clear (tmp);
1278           edge.src = n;
1279           edge.dest = n;
1280           edge.weights = NULL;
1281           if (valid_graph_edge (graph, edge))
1282             {
1283               bitmap weights = get_graph_weights (graph, edge);
1284               bitmap_clear_bit (weights, 0);
1285               if (bitmap_empty_p (weights))
1286                 erase_graph_self_edge (graph, edge);
1287             }
1288         }
1289     }
1290   BITMAP_FREE (tmp);
1291 }
1292
1293
1294 /* Information needed to compute the topological ordering of a graph.  */
1295
1296 struct topo_info
1297 {
1298   /* sbitmap of visited nodes.  */
1299   sbitmap visited;
1300   /* Array that stores the topological order of the graph, *in
1301      reverse*.  */
1302   VEC(unsigned,heap) *topo_order;
1303 };
1304
1305
1306 /* Initialize and return a topological info structure.  */
1307
1308 static struct topo_info *
1309 init_topo_info (void)
1310 {
1311   size_t size = VEC_length (varinfo_t, varmap);
1312   struct topo_info *ti = xmalloc (sizeof (struct topo_info));
1313   ti->visited = sbitmap_alloc (size);
1314   sbitmap_zero (ti->visited);
1315   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1316   return ti;
1317 }
1318
1319
1320 /* Free the topological sort info pointed to by TI.  */
1321
1322 static void
1323 free_topo_info (struct topo_info *ti)
1324 {
1325   sbitmap_free (ti->visited);
1326   VEC_free (unsigned, heap, ti->topo_order);
1327   free (ti);
1328 }
1329
1330 /* Visit the graph in topological order, and store the order in the
1331    topo_info structure.  */
1332
1333 static void
1334 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1335             unsigned int n)
1336 {
1337   VEC(constraint_edge_t,heap) *succs = graph->succs[n];
1338   constraint_edge_t c;
1339   int i;
1340   SET_BIT (ti->visited, n);
1341   for (i = 0; VEC_iterate (constraint_edge_t, succs, i, c); i++)
1342     {
1343       if (!TEST_BIT (ti->visited, c->dest))
1344         topo_visit (graph, ti, c->dest);
1345     }
1346   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1347 }
1348
1349 /* Return true if variable N + OFFSET is a legal field of N.  */
1350
1351 static bool 
1352 type_safe (unsigned int n, unsigned HOST_WIDE_INT *offset)
1353 {
1354   varinfo_t ninfo = get_varinfo (n);
1355
1356   /* For things we've globbed to single variables, any offset into the
1357      variable acts like the entire variable, so that it becomes offset
1358      0.  */
1359   if (ninfo->is_special_var
1360       || ninfo->is_artificial_var
1361       || ninfo->is_unknown_size_var)
1362     {
1363       *offset = 0;
1364       return true;
1365     }
1366   return (get_varinfo (n)->offset + *offset) < get_varinfo (n)->fullsize;
1367 }
1368
1369 /* Process a constraint C that represents *x = &y.  */
1370
1371 static void
1372 do_da_constraint (constraint_graph_t graph ATTRIBUTE_UNUSED,
1373                   constraint_t c, bitmap delta)
1374 {
1375   unsigned int rhs = c->rhs.var;
1376   unsigned int j;
1377   bitmap_iterator bi;
1378
1379   /* For each member j of Delta (Sol(x)), add x to Sol(j)  */
1380   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1381     {
1382       unsigned HOST_WIDE_INT offset = c->lhs.offset;
1383       if (type_safe (j, &offset) && !(get_varinfo (j)->is_special_var))
1384         {
1385         /* *x != NULL && *x != ANYTHING*/
1386           varinfo_t v;
1387           unsigned int t;
1388           bitmap sol;
1389           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + offset;
1390
1391           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1392           if (!v)
1393             continue;
1394           t = v->node;
1395           sol = get_varinfo (t)->solution;
1396           if (!bitmap_bit_p (sol, rhs))
1397             {             
1398               bitmap_set_bit (sol, rhs);
1399               if (!TEST_BIT (changed, t))
1400                 {
1401                   SET_BIT (changed, t);
1402                   changed_count++;
1403                 }
1404             }
1405         }
1406       else if (dump_file && !(get_varinfo (j)->is_special_var))
1407         fprintf (dump_file, "Untypesafe usage in do_da_constraint.\n");
1408       
1409     }
1410 }
1411
1412 /* Process a constraint C that represents x = *y, using DELTA as the
1413    starting solution.  */
1414
1415 static void
1416 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1417                   bitmap delta)
1418 {
1419   unsigned int lhs = get_varinfo (c->lhs.var)->node;
1420   bool flag = false;
1421   bitmap sol = get_varinfo (lhs)->solution;
1422   unsigned int j;
1423   bitmap_iterator bi;
1424   
1425   /* For each variable j in delta (Sol(y)), add    
1426      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1427   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1428     {
1429       unsigned HOST_WIDE_INT roffset = c->rhs.offset;
1430       if (type_safe (j, &roffset))
1431         {
1432           varinfo_t v;
1433           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + roffset;
1434           unsigned int t;
1435
1436           v = first_vi_for_offset (get_varinfo (j), fieldoffset);         
1437           if (!v)
1438             continue;
1439           t = v->node;
1440           if (int_add_graph_edge (graph, lhs, t, 0))
1441             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);     
1442         }
1443       else if (dump_file && !(get_varinfo (j)->is_special_var))
1444         fprintf (dump_file, "Untypesafe usage in do_sd_constraint\n");
1445       
1446     }
1447
1448   /* If the LHS solution changed, mark the var as changed.  */
1449   if (flag)
1450     {
1451       get_varinfo (lhs)->solution = sol;
1452       if (!TEST_BIT (changed, lhs))
1453         {
1454           SET_BIT (changed, lhs);
1455           changed_count++;
1456         }
1457     }    
1458 }
1459
1460 /* Process a constraint C that represents *x = y.  */
1461
1462 static void
1463 do_ds_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1464 {
1465   unsigned int rhs = get_varinfo (c->rhs.var)->node;
1466   unsigned HOST_WIDE_INT roff = c->rhs.offset;
1467   bitmap sol = get_varinfo (rhs)->solution;
1468   unsigned int j;
1469   bitmap_iterator bi;
1470
1471   /* For each member j of delta (Sol(x)), add an edge from y to j and
1472      union Sol(y) into Sol(j) */
1473   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1474     {
1475       unsigned HOST_WIDE_INT loff = c->lhs.offset;
1476       if (type_safe (j, &loff) && !(get_varinfo(j)->is_special_var))
1477         {
1478           varinfo_t v;
1479           unsigned int t;
1480           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + loff;
1481
1482           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1483           if (!v)
1484             continue;
1485           t = v->node;
1486           if (int_add_graph_edge (graph, t, rhs, roff))
1487             {
1488               bitmap tmp = get_varinfo (t)->solution;
1489               if (set_union_with_increment (tmp, sol, roff))
1490                 {
1491                   get_varinfo (t)->solution = tmp;
1492                   if (t == rhs)
1493                     {
1494                       sol = get_varinfo (rhs)->solution;
1495                     }
1496                   if (!TEST_BIT (changed, t))
1497                     {
1498                       SET_BIT (changed, t);
1499                       changed_count++;
1500                     }
1501                 }
1502             }
1503         }    
1504       else if (dump_file && !(get_varinfo (j)->is_special_var))
1505         fprintf (dump_file, "Untypesafe usage in do_ds_constraint\n");
1506     }
1507 }
1508
1509 /* Handle a non-simple (simple meaning requires no iteration), non-copy
1510    constraint (IE *x = &y, x = *y, and *x = y).  */
1511    
1512 static void
1513 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1514 {
1515   if (c->lhs.type == DEREF)
1516     {
1517       if (c->rhs.type == ADDRESSOF)
1518         {
1519           /* *x = &y */
1520           do_da_constraint (graph, c, delta);
1521         }
1522       else
1523         {
1524           /* *x = y */
1525           do_ds_constraint (graph, c, delta);
1526         }
1527     }
1528   else
1529     {
1530       /* x = *y */
1531       if (!(get_varinfo (c->lhs.var)->is_special_var))
1532         do_sd_constraint (graph, c, delta);
1533     }
1534 }
1535
1536 /* Initialize and return a new SCC info structure.  */
1537
1538 static struct scc_info *
1539 init_scc_info (void)
1540 {
1541   struct scc_info *si = xmalloc (sizeof (struct scc_info));
1542   size_t size = VEC_length (varinfo_t, varmap);
1543
1544   si->current_index = 0;
1545   si->visited = sbitmap_alloc (size);
1546   sbitmap_zero (si->visited);
1547   si->in_component = sbitmap_alloc (size);
1548   sbitmap_ones (si->in_component);
1549   si->visited_index = xcalloc (sizeof (unsigned int), size + 1);
1550   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1551   si->unification_queue = VEC_alloc (unsigned, heap, 1);
1552   return si;
1553 }
1554
1555 /* Free an SCC info structure pointed to by SI */
1556
1557 static void
1558 free_scc_info (struct scc_info *si)
1559 {  
1560   sbitmap_free (si->visited);
1561   sbitmap_free (si->in_component);
1562   free (si->visited_index);
1563   VEC_free (unsigned, heap, si->scc_stack);
1564   VEC_free (unsigned, heap, si->unification_queue);
1565   free(si); 
1566 }
1567
1568
1569 /* Find cycles in GRAPH that occur, using strongly connected components, and
1570    collapse the cycles into a single representative node.  if UPDATE_CHANGED
1571    is true, then update the changed sbitmap to note those nodes whose
1572    solutions have changed as a result of collapsing.  */
1573
1574 static void
1575 find_and_collapse_graph_cycles (constraint_graph_t graph, bool update_changed)
1576 {
1577   unsigned int i;
1578   unsigned int size = VEC_length (varinfo_t, varmap);
1579   struct scc_info *si = init_scc_info ();
1580
1581   for (i = 0; i != size; ++i)
1582     if (!TEST_BIT (si->visited, i) && get_varinfo (i)->node == i)
1583       scc_visit (graph, si, i);
1584   process_unification_queue (graph, si, update_changed);
1585   free_scc_info (si);
1586 }
1587
1588 /* Compute a topological ordering for GRAPH, and store the result in the
1589    topo_info structure TI.  */
1590
1591 static void 
1592 compute_topo_order (constraint_graph_t graph,
1593                     struct topo_info *ti)
1594 {
1595   unsigned int i;
1596   unsigned int size = VEC_length (varinfo_t, varmap);
1597   
1598   for (i = 0; i != size; ++i)
1599     if (!TEST_BIT (ti->visited, i) && get_varinfo (i)->node == i)
1600       topo_visit (graph, ti, i);
1601 }
1602
1603 /* Return true if bitmap B is empty, or a bitmap other than bit 0 is set. */
1604
1605 static bool
1606 bitmap_other_than_zero_bit_set (bitmap b)
1607 {
1608   unsigned int i;
1609   bitmap_iterator bi;
1610
1611   if (bitmap_empty_p (b))
1612     return false;
1613   EXECUTE_IF_SET_IN_BITMAP (b, 1, i, bi)
1614     return true;
1615   return false;
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 static void
1629 perform_var_substitution (constraint_graph_t graph)
1630 {
1631   struct topo_info *ti = init_topo_info ();
1632  
1633   /* Compute the topological ordering of the graph, then visit each
1634      node in topological order.  */
1635   compute_topo_order (graph, ti);
1636  
1637   while (VEC_length (unsigned, ti->topo_order) != 0)
1638     {
1639       unsigned int i = VEC_pop (unsigned, ti->topo_order);
1640       unsigned int pred;
1641       varinfo_t vi = get_varinfo (i);
1642       bool okay_to_elim = false;
1643       unsigned int root = VEC_length (varinfo_t, varmap);
1644       VEC(constraint_edge_t,heap) *predvec = graph->preds[i];
1645       constraint_edge_t ce;
1646       bitmap tmp;
1647
1648       /* We can't eliminate things whose address is taken, or which is
1649          the target of a dereference.  */
1650       if (vi->address_taken || vi->indirect_target)
1651         continue;
1652
1653       /* See if all predecessors of I are ripe for elimination */
1654       for (pred = 0; VEC_iterate (constraint_edge_t, predvec, pred, ce); pred++)
1655         {
1656           bitmap weight;
1657           unsigned int w;
1658           weight = get_graph_weights (graph, *ce);
1659         
1660           /* We can't eliminate variables that have nonzero weighted
1661              edges between them.  */
1662           if (bitmap_other_than_zero_bit_set (weight))
1663             {
1664               okay_to_elim = false;
1665               break;
1666             }
1667           w = get_varinfo (ce->dest)->node;
1668
1669           /* We can't eliminate the node if one of the predecessors is
1670              part of a different strongly connected component.  */
1671           if (!okay_to_elim)
1672             {
1673               root = w;
1674               okay_to_elim = true;
1675             }
1676           else if (w != root)
1677             {
1678               okay_to_elim = false;
1679               break;
1680             }
1681
1682           /* Theorem 4 in Rountev and Chandra: If i is a direct node,
1683              then Solution(i) is a subset of Solution (w), where w is a
1684              predecessor in the graph.  
1685              Corollary: If all predecessors of i have the same
1686              points-to set, then i has that same points-to set as
1687              those predecessors.  */
1688           tmp = BITMAP_ALLOC (NULL);
1689           bitmap_and_compl (tmp, get_varinfo (i)->solution,
1690                             get_varinfo (w)->solution);
1691           if (!bitmap_empty_p (tmp))
1692             {
1693               okay_to_elim = false;
1694               BITMAP_FREE (tmp);
1695               break;
1696             }
1697           BITMAP_FREE (tmp);
1698         }
1699
1700       /* See if the root is different than the original node. 
1701          If so, we've found an equivalence.  */
1702       if (root != get_varinfo (i)->node && okay_to_elim)
1703         {
1704           /* Found an equivalence */
1705           get_varinfo (i)->node = root;
1706           collapse_nodes (graph, root, i);
1707           if (dump_file && (dump_flags & TDF_DETAILS))
1708             fprintf (dump_file, "Collapsing %s into %s\n",
1709                      get_varinfo (i)->name,
1710                      get_varinfo (root)->name);
1711           stats.collapsed_vars++;
1712         }
1713     }
1714
1715   free_topo_info (ti);
1716 }
1717
1718
1719 /* Solve the constraint graph GRAPH using our worklist solver.
1720    This is based on the PW* family of solvers from the "Efficient Field
1721    Sensitive Pointer Analysis for C" paper.
1722    It works by iterating over all the graph nodes, processing the complex
1723    constraints and propagating the copy constraints, until everything stops
1724    changed.  This corresponds to steps 6-8 in the solving list given above.  */
1725
1726 static void
1727 solve_graph (constraint_graph_t graph)
1728 {
1729   unsigned int size = VEC_length (varinfo_t, varmap);
1730   unsigned int i;
1731
1732   changed_count = size;
1733   changed = sbitmap_alloc (size);
1734   sbitmap_ones (changed);
1735   
1736   /* The already collapsed/unreachable nodes will never change, so we
1737      need to  account for them in changed_count.  */
1738   for (i = 0; i < size; i++)
1739     if (get_varinfo (i)->node != i)
1740       changed_count--;
1741   
1742   while (changed_count > 0)
1743     {
1744       unsigned int i;
1745       struct topo_info *ti = init_topo_info ();
1746       stats.iterations++;
1747       
1748       bitmap_obstack_initialize (&iteration_obstack);
1749       
1750       if (edge_added)
1751         {
1752           /* We already did cycle elimination once, when we did
1753              variable substitution, so we don't need it again for the
1754              first iteration.  */
1755           if (stats.iterations > 1)
1756             find_and_collapse_graph_cycles (graph, true);
1757           
1758           edge_added = false;
1759         }
1760
1761       compute_topo_order (graph, ti);
1762
1763       while (VEC_length (unsigned, ti->topo_order) != 0)
1764         {
1765           i = VEC_pop (unsigned, ti->topo_order);
1766           gcc_assert (get_varinfo (i)->node == i);
1767
1768           /* If the node has changed, we need to process the
1769              complex constraints and outgoing edges again.  */
1770           if (TEST_BIT (changed, i))
1771             {
1772               unsigned int j;
1773               constraint_t c;
1774               constraint_edge_t e;
1775               bitmap solution;
1776               VEC(constraint_t,heap) *complex = get_varinfo (i)->complex;
1777               VEC(constraint_edge_t,heap) *succs;
1778
1779               RESET_BIT (changed, i);
1780               changed_count--;
1781
1782               /* Process the complex constraints */
1783               solution = get_varinfo (i)->solution;
1784               for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
1785                 do_complex_constraint (graph, c, solution);
1786
1787               /* Propagate solution to all successors.  */
1788               succs = graph->succs[i];
1789               for (j = 0; VEC_iterate (constraint_edge_t, succs, j, e); j++)
1790                 {
1791                   bitmap tmp = get_varinfo (e->dest)->solution;
1792                   bool flag = false;
1793                   unsigned int k;
1794                   bitmap weights = e->weights;
1795                   bitmap_iterator bi;
1796
1797                   gcc_assert (!bitmap_empty_p (weights));
1798                   EXECUTE_IF_SET_IN_BITMAP (weights, 0, k, bi)
1799                     flag |= set_union_with_increment (tmp, solution, k);
1800
1801                   if (flag)
1802                     {
1803                       get_varinfo (e->dest)->solution = tmp;                
1804                       if (!TEST_BIT (changed, e->dest))
1805                         {
1806                           SET_BIT (changed, e->dest);
1807                           changed_count++;
1808                         }
1809                     }
1810                 }
1811             }
1812         }
1813       free_topo_info (ti);
1814       bitmap_obstack_release (&iteration_obstack);
1815     }
1816
1817   sbitmap_free (changed);
1818 }
1819
1820
1821 /* CONSTRAINT AND VARIABLE GENERATION FUNCTIONS */
1822
1823 /* Map from trees to variable ids.  */    
1824 static htab_t id_for_tree;
1825
1826 typedef struct tree_id
1827 {
1828   tree t;
1829   unsigned int id;
1830 } *tree_id_t;
1831
1832 /* Hash a tree id structure.  */
1833
1834 static hashval_t 
1835 tree_id_hash (const void *p)
1836 {
1837   const tree_id_t ta = (tree_id_t) p;
1838   return htab_hash_pointer (ta->t);
1839 }
1840
1841 /* Return true if the tree in P1 and the tree in P2 are the same.  */
1842
1843 static int
1844 tree_id_eq (const void *p1, const void *p2)
1845 {
1846   const tree_id_t ta1 = (tree_id_t) p1;
1847   const tree_id_t ta2 = (tree_id_t) p2;
1848   return ta1->t == ta2->t;
1849 }
1850
1851 /* Insert ID as the variable id for tree T in the hashtable.  */
1852
1853 static void 
1854 insert_id_for_tree (tree t, int id)
1855 {
1856   void **slot;
1857   struct tree_id finder;
1858   tree_id_t new_pair;
1859   
1860   finder.t = t;
1861   slot = htab_find_slot (id_for_tree, &finder, INSERT);
1862   gcc_assert (*slot == NULL);
1863   new_pair = xmalloc (sizeof (struct tree_id));
1864   new_pair->t = t;
1865   new_pair->id = id;
1866   *slot = (void *)new_pair;
1867 }
1868
1869 /* Find the variable id for tree T in ID_FOR_TREE.  If T does not
1870    exist in the hash table, return false, otherwise, return true and
1871    set *ID to the id we found.  */
1872
1873 static bool
1874 lookup_id_for_tree (tree t, unsigned int *id)
1875 {
1876   tree_id_t pair;
1877   struct tree_id finder;
1878
1879   finder.t = t;
1880   pair = htab_find (id_for_tree,  &finder);
1881   if (pair == NULL)
1882     return false;
1883   *id = pair->id;
1884   return true;
1885 }
1886
1887 /* Return a printable name for DECL  */
1888
1889 static const char *
1890 alias_get_name (tree decl)
1891 {
1892   const char *res = get_name (decl);
1893   char *temp;
1894   int num_printed = 0;
1895
1896   if (res != NULL)
1897     return res;
1898
1899   res = "NULL";
1900   if (TREE_CODE (decl) == SSA_NAME)
1901     {
1902       num_printed = asprintf (&temp, "%s_%u", 
1903                               alias_get_name (SSA_NAME_VAR (decl)),
1904                               SSA_NAME_VERSION (decl));
1905     }
1906   else if (DECL_P (decl))
1907     {
1908       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
1909     }
1910   if (num_printed > 0)
1911     {
1912       res = ggc_strdup (temp);
1913       free (temp);
1914     }
1915   return res;
1916 }
1917
1918 /* Find the variable id for tree T in the hashtable.
1919    If T doesn't exist in the hash table, create an entry for it.  */
1920
1921 static unsigned int
1922 get_id_for_tree (tree t)
1923 {
1924   tree_id_t pair;
1925   struct tree_id finder;
1926
1927   finder.t = t;
1928   pair = htab_find (id_for_tree,  &finder);
1929   if (pair == NULL)
1930     return create_variable_info_for (t, alias_get_name (t));
1931   
1932   return pair->id;
1933 }
1934
1935 /* Get a constraint expression from an SSA_VAR_P node.  */
1936
1937 static struct constraint_expr
1938 get_constraint_exp_from_ssa_var (tree t)
1939 {
1940   struct constraint_expr cexpr;
1941
1942   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
1943
1944   /* For parameters, get at the points-to set for the actual parm
1945      decl.  */
1946   if (TREE_CODE (t) == SSA_NAME 
1947       && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL 
1948       && default_def (SSA_NAME_VAR (t)) == t)
1949     return get_constraint_exp_from_ssa_var (SSA_NAME_VAR (t));
1950
1951   cexpr.type = SCALAR;
1952   
1953   cexpr.var = get_id_for_tree (t);
1954   /* If we determine the result is "anything", and we know this is readonly,
1955      say it points to readonly memory instead.  */
1956   if (cexpr.var == anything_id && TREE_READONLY (t))
1957     {
1958       cexpr.type = ADDRESSOF;
1959       cexpr.var = readonly_id;
1960     }
1961     
1962   cexpr.offset = 0;
1963   return cexpr;
1964 }
1965
1966 /* Process a completed constraint T, and add it to the constraint
1967    list.  */
1968
1969 static void
1970 process_constraint (constraint_t t)
1971 {
1972   struct constraint_expr rhs = t->rhs;
1973   struct constraint_expr lhs = t->lhs;
1974   
1975   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
1976   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
1977
1978   /* ANYTHING == ANYTHING is pointless.  */
1979   if (lhs.var == anything_id && rhs.var == anything_id)
1980     return;
1981
1982   /* If we have &ANYTHING = something, convert to SOMETHING = &ANYTHING) */
1983   else if (lhs.var == anything_id && lhs.type == ADDRESSOF)
1984     {
1985       rhs = t->lhs;
1986       t->lhs = t->rhs;
1987       t->rhs = rhs;
1988       process_constraint (t);
1989     }   
1990   /* This can happen in our IR with things like n->a = *p */
1991   else if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
1992     {
1993       /* Split into tmp = *rhs, *lhs = tmp */
1994       tree rhsdecl = get_varinfo (rhs.var)->decl;
1995       tree pointertype = TREE_TYPE (rhsdecl);
1996       tree pointedtotype = TREE_TYPE (pointertype);
1997       tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
1998       struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
1999       
2000       /* If this is an aggregate of known size, we should have passed
2001          this off to do_structure_copy, and it should have broken it
2002          up.  */
2003       gcc_assert (!AGGREGATE_TYPE_P (pointedtotype) 
2004                   || get_varinfo (rhs.var)->is_unknown_size_var);
2005       
2006       process_constraint (new_constraint (tmplhs, rhs));
2007       process_constraint (new_constraint (lhs, tmplhs));
2008     }
2009   else if (rhs.type == ADDRESSOF)
2010     {
2011       varinfo_t vi;
2012       gcc_assert (rhs.offset == 0);
2013       
2014       for (vi = get_varinfo (rhs.var); vi != NULL; vi = vi->next)
2015         vi->address_taken = true;
2016
2017       VEC_safe_push (constraint_t, heap, constraints, t);
2018     }
2019   else
2020     {
2021       if (lhs.type != DEREF && rhs.type == DEREF)
2022         get_varinfo (lhs.var)->indirect_target = true;
2023       VEC_safe_push (constraint_t, heap, constraints, t);
2024     }
2025 }
2026
2027
2028 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2029    structure.  */
2030
2031 static unsigned HOST_WIDE_INT
2032 bitpos_of_field (const tree fdecl)
2033 {
2034
2035   if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
2036       || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
2037     return -1;
2038   
2039   return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8) 
2040          + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
2041 }
2042
2043
2044 /* Return true if an access to [ACCESSPOS, ACCESSSIZE]
2045    overlaps with a field at [FIELDPOS, FIELDSIZE] */
2046
2047 static bool
2048 offset_overlaps_with_access (const unsigned HOST_WIDE_INT fieldpos,
2049                              const unsigned HOST_WIDE_INT fieldsize,
2050                              const unsigned HOST_WIDE_INT accesspos,
2051                              const unsigned HOST_WIDE_INT accesssize)
2052 {
2053   if (fieldpos == accesspos && fieldsize == accesssize)
2054     return true;
2055   if (accesspos >= fieldpos && accesspos < (fieldpos + fieldsize))
2056     return true;
2057   if (accesspos < fieldpos && (accesspos + accesssize > fieldpos))
2058     return true;
2059   
2060   return false;
2061 }
2062
2063 /* Given a COMPONENT_REF T, return the constraint_expr for it.  */
2064
2065 static struct constraint_expr
2066 get_constraint_for_component_ref (tree t, bool *need_anyoffset)
2067 {
2068   struct constraint_expr result;
2069   HOST_WIDE_INT bitsize = -1;
2070   HOST_WIDE_INT bitpos;
2071   tree offset = NULL_TREE;
2072   enum machine_mode mode;
2073   int unsignedp;
2074   int volatilep;
2075   tree forzero;
2076   
2077   result.offset = 0;
2078   result.type = SCALAR;
2079   result.var = 0;
2080
2081   /* Some people like to do cute things like take the address of
2082      &0->a.b */
2083   forzero = t;
2084   while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2085       forzero = TREE_OPERAND (forzero, 0);
2086
2087   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero)) 
2088     {
2089       result.offset = 0;
2090       result.var = integer_id;
2091       result.type = SCALAR;
2092       return result;
2093     }
2094  
2095   t = get_inner_reference (t, &bitsize, &bitpos, &offset, &mode,
2096                            &unsignedp, &volatilep, false);
2097   result = get_constraint_for (t, need_anyoffset);
2098
2099   /* This can also happen due to weird offsetof type macros.  */
2100   if (TREE_CODE (t) != ADDR_EXPR && result.type == ADDRESSOF)
2101     result.type = SCALAR;
2102   
2103   /* If we know where this goes, then yay. Otherwise, booo. */
2104
2105   if (offset == NULL && bitsize != -1)
2106     {
2107       result.offset = bitpos;
2108     }   
2109   else if (need_anyoffset)
2110     {
2111       result.offset = 0;
2112       *need_anyoffset = true; 
2113     }
2114   else
2115     {
2116       result.var = anything_id;
2117       result.offset = 0;      
2118     }
2119
2120   if (result.type == SCALAR)
2121     {
2122       /* In languages like C, you can access one past the end of an
2123          array.  You aren't allowed to dereference it, so we can
2124          ignore this constraint. When we handle pointer subtraction,
2125          we may have to do something cute here.  */
2126       
2127       if (result.offset < get_varinfo (result.var)->fullsize)   
2128         {
2129           /* It's also not true that the constraint will actually start at the
2130              right offset, it may start in some padding.  We only care about
2131              setting the constraint to the first actual field it touches, so
2132              walk to find it.  */ 
2133           varinfo_t curr;
2134           for (curr = get_varinfo (result.var); curr; curr = curr->next)
2135             {
2136               if (offset_overlaps_with_access (curr->offset, curr->size,
2137                                                result.offset, bitsize))
2138                 {
2139                   result.var = curr->id;
2140                   break;
2141
2142                 }
2143             }
2144           /* assert that we found *some* field there. The user couldn't be
2145              accessing *only* padding.  */
2146              
2147           gcc_assert (curr);
2148         }
2149       else
2150         if (dump_file && (dump_flags & TDF_DETAILS))
2151           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
2152
2153       result.offset = 0;
2154     }
2155   
2156   return result;
2157 }
2158
2159
2160 /* Dereference the constraint expression CONS, and return the result.
2161    DEREF (ADDRESSOF) = SCALAR
2162    DEREF (SCALAR) = DEREF
2163    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
2164    This is needed so that we can handle dereferencing DEREF constraints.  */
2165
2166 static struct constraint_expr
2167 do_deref (struct constraint_expr cons)
2168 {
2169   if (cons.type == SCALAR)
2170     {
2171       cons.type = DEREF;
2172       return cons;
2173     }
2174   else if (cons.type == ADDRESSOF)
2175     {
2176       cons.type = SCALAR;
2177       return cons;
2178     }
2179   else if (cons.type == DEREF)
2180     {
2181       tree tmpvar = create_tmp_var_raw (ptr_type_node, "derefmp");
2182       struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2183       process_constraint (new_constraint (tmplhs, cons));
2184       cons.var = tmplhs.var;
2185       return cons;
2186     }
2187   gcc_unreachable ();
2188 }
2189
2190
2191 /* Given a tree T, return the constraint expression for it.  */
2192
2193 static struct constraint_expr
2194 get_constraint_for (tree t, bool *need_anyoffset)
2195 {
2196   struct constraint_expr temp;
2197
2198   /* x = integer is all glommed to a single variable, which doesn't
2199      point to anything by itself.  That is, of course, unless it is an
2200      integer constant being treated as a pointer, in which case, we
2201      will return that this is really the addressof anything.  This
2202      happens below, since it will fall into the default case. The only
2203      case we know something about an integer treated like a pointer is
2204      when it is the NULL pointer, and then we just say it points to
2205      NULL.  */
2206   if (TREE_CODE (t) == INTEGER_CST
2207       && !POINTER_TYPE_P (TREE_TYPE (t)))
2208     {
2209       temp.var = integer_id;
2210       temp.type = SCALAR;
2211       temp.offset = 0;
2212       return temp;
2213     }
2214   else if (TREE_CODE (t) == INTEGER_CST
2215            && integer_zerop (t))
2216     {
2217       temp.var = nothing_id;
2218       temp.type = ADDRESSOF;
2219       temp.offset = 0;
2220       return temp;
2221     }
2222
2223   switch (TREE_CODE_CLASS (TREE_CODE (t)))
2224     {
2225     case tcc_expression:
2226       {
2227         switch (TREE_CODE (t))
2228           {
2229           case ADDR_EXPR:
2230             {
2231               temp = get_constraint_for (TREE_OPERAND (t, 0), need_anyoffset);
2232                if (temp.type == DEREF)
2233                  temp.type = SCALAR;
2234                else
2235                  temp.type = ADDRESSOF;
2236               return temp;
2237             }
2238             break;
2239           case CALL_EXPR:
2240             
2241             /* XXX: In interprocedural mode, if we didn't have the
2242                body, we would need to do *each pointer argument =
2243                &ANYTHING added.  */
2244             if (call_expr_flags (t) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA))
2245               {
2246                 varinfo_t vi;
2247                 tree heapvar = heapvar_lookup (t);
2248                 
2249                 if (heapvar == NULL)
2250                   {                 
2251                     heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
2252                     DECL_EXTERNAL (heapvar) = 1;
2253                     add_referenced_tmp_var (heapvar);
2254                     heapvar_insert (t, heapvar);
2255                   }
2256
2257                 temp.var = create_variable_info_for (heapvar,
2258                                                      alias_get_name (heapvar));
2259                 
2260                 vi = get_varinfo (temp.var);
2261                 vi->is_artificial_var = 1;
2262                 vi->is_heap_var = 1;
2263                 temp.type = ADDRESSOF;
2264                 temp.offset = 0;
2265                 return temp;
2266               }
2267             /* FALLTHRU */
2268           default:
2269             {
2270               temp.type = ADDRESSOF;
2271               temp.var = anything_id;
2272               temp.offset = 0;
2273               return temp;
2274             }
2275           }
2276       }
2277     case tcc_reference:
2278       {
2279         switch (TREE_CODE (t))
2280           {
2281           case INDIRECT_REF:
2282             {
2283               temp = get_constraint_for (TREE_OPERAND (t, 0), need_anyoffset);
2284               temp = do_deref (temp);
2285               return temp;
2286             }
2287           case ARRAY_REF:
2288           case COMPONENT_REF:
2289             temp = get_constraint_for_component_ref (t, need_anyoffset);
2290             return temp;
2291           default:
2292             {
2293               temp.type = ADDRESSOF;
2294               temp.var = anything_id;
2295               temp.offset = 0;
2296               return temp;
2297             }
2298           }
2299       }
2300     case tcc_unary:
2301       {
2302         switch (TREE_CODE (t))
2303           {
2304           case NOP_EXPR:
2305           case CONVERT_EXPR:
2306           case NON_LVALUE_EXPR:
2307             {
2308               tree op = TREE_OPERAND (t, 0);
2309               
2310               /* Cast from non-pointer to pointers are bad news for us.
2311                  Anything else, we see through */
2312               if (!(POINTER_TYPE_P (TREE_TYPE (t))
2313                     && ! POINTER_TYPE_P (TREE_TYPE (op))))
2314                 return get_constraint_for (op, need_anyoffset);
2315
2316               /* FALLTHRU  */
2317             }
2318           default:
2319             {
2320               temp.type = ADDRESSOF;
2321               temp.var = anything_id;
2322               temp.offset = 0;
2323               return temp;
2324             }
2325           }
2326       }
2327     case tcc_exceptional:
2328       {
2329         switch (TREE_CODE (t))
2330           {
2331           case PHI_NODE:           
2332             return get_constraint_for (PHI_RESULT (t), need_anyoffset);
2333           case SSA_NAME:
2334             return get_constraint_exp_from_ssa_var (t);
2335           default:
2336             {
2337               temp.type = ADDRESSOF;
2338               temp.var = anything_id;
2339               temp.offset = 0;
2340               return temp;
2341             }
2342           }
2343       }
2344     case tcc_declaration:
2345       return get_constraint_exp_from_ssa_var (t);
2346     default:
2347       {
2348         temp.type = ADDRESSOF;
2349         temp.var = anything_id;
2350         temp.offset = 0;
2351         return temp;
2352       }
2353     }
2354 }
2355
2356
2357 /* Handle the structure copy case where we have a simple structure copy
2358    between LHS and RHS that is of SIZE (in bits) 
2359   
2360    For each field of the lhs variable (lhsfield)
2361      For each field of the rhs variable at lhsfield.offset (rhsfield)
2362        add the constraint lhsfield = rhsfield
2363
2364    If we fail due to some kind of type unsafety or other thing we
2365    can't handle, return false.  We expect the caller to collapse the
2366    variable in that case.  */
2367
2368 static bool
2369 do_simple_structure_copy (const struct constraint_expr lhs,
2370                           const struct constraint_expr rhs,
2371                           const unsigned HOST_WIDE_INT size)
2372 {
2373   varinfo_t p = get_varinfo (lhs.var);
2374   unsigned HOST_WIDE_INT pstart, last;
2375   pstart = p->offset;
2376   last = p->offset + size;
2377   for (; p && p->offset < last; p = p->next)
2378     {
2379       varinfo_t q;
2380       struct constraint_expr templhs = lhs;
2381       struct constraint_expr temprhs = rhs;
2382       unsigned HOST_WIDE_INT fieldoffset;
2383
2384       templhs.var = p->id;            
2385       q = get_varinfo (temprhs.var);
2386       fieldoffset = p->offset - pstart;
2387       q = first_vi_for_offset (q, q->offset + fieldoffset);
2388       if (!q)
2389         return false;
2390       temprhs.var = q->id;
2391       process_constraint (new_constraint (templhs, temprhs));
2392     }
2393   return true;
2394 }
2395
2396
2397 /* Handle the structure copy case where we have a  structure copy between a
2398    aggregate on the LHS and a dereference of a pointer on the RHS
2399    that is of SIZE (in bits) 
2400   
2401    For each field of the lhs variable (lhsfield)
2402        rhs.offset = lhsfield->offset
2403        add the constraint lhsfield = rhs
2404 */
2405
2406 static void
2407 do_rhs_deref_structure_copy (const struct constraint_expr lhs,
2408                              const struct constraint_expr rhs,
2409                              const unsigned HOST_WIDE_INT size)
2410 {
2411   varinfo_t p = get_varinfo (lhs.var);
2412   unsigned HOST_WIDE_INT pstart,last;
2413   pstart = p->offset;
2414   last = p->offset + size;
2415
2416   for (; p && p->offset < last; p = p->next)
2417     {
2418       varinfo_t q;
2419       struct constraint_expr templhs = lhs;
2420       struct constraint_expr temprhs = rhs;
2421       unsigned HOST_WIDE_INT fieldoffset;
2422
2423
2424       if (templhs.type == SCALAR)
2425         templhs.var = p->id;      
2426       else
2427         templhs.offset = p->offset;
2428       
2429       q = get_varinfo (temprhs.var);
2430       fieldoffset = p->offset - pstart;      
2431       temprhs.offset += fieldoffset;
2432       process_constraint (new_constraint (templhs, temprhs));
2433     }
2434 }
2435
2436 /* Handle the structure copy case where we have a structure copy
2437    between a aggregate on the RHS and a dereference of a pointer on
2438    the LHS that is of SIZE (in bits) 
2439
2440    For each field of the rhs variable (rhsfield)
2441        lhs.offset = rhsfield->offset
2442        add the constraint lhs = rhsfield
2443 */
2444
2445 static void
2446 do_lhs_deref_structure_copy (const struct constraint_expr lhs,
2447                              const struct constraint_expr rhs,
2448                              const unsigned HOST_WIDE_INT size)
2449 {
2450   varinfo_t p = get_varinfo (rhs.var);
2451   unsigned HOST_WIDE_INT pstart,last;
2452   pstart = p->offset;
2453   last = p->offset + size;
2454
2455   for (; p && p->offset < last; p = p->next)
2456     {
2457       varinfo_t q;
2458       struct constraint_expr templhs = lhs;
2459       struct constraint_expr temprhs = rhs;
2460       unsigned HOST_WIDE_INT fieldoffset;
2461
2462
2463       if (temprhs.type == SCALAR)
2464         temprhs.var = p->id;      
2465       else
2466         temprhs.offset = p->offset;
2467       
2468       q = get_varinfo (templhs.var);
2469       fieldoffset = p->offset - pstart;      
2470       templhs.offset += fieldoffset;
2471       process_constraint (new_constraint (templhs, temprhs));
2472     }
2473 }
2474
2475 /* Sometimes, frontends like to give us bad type information.  This
2476    function will collapse all the fields from VAR to the end of VAR,
2477    into VAR, so that we treat those fields as a single variable. 
2478    We return the variable they were collapsed into.  */
2479
2480 static unsigned int
2481 collapse_rest_of_var (unsigned int var)
2482 {
2483   varinfo_t currvar = get_varinfo (var);
2484   varinfo_t field;
2485
2486   for (field = currvar->next; field; field = field->next)
2487     {
2488       if (dump_file)
2489         fprintf (dump_file, "Type safety: Collapsing var %s into %s\n", 
2490                  field->name, currvar->name);
2491       
2492       gcc_assert (!field->collapsed_to);
2493       field->collapsed_to = currvar;
2494     }
2495
2496   currvar->next = NULL;
2497   currvar->size = currvar->fullsize - currvar->offset;
2498   
2499   return currvar->id;
2500 }
2501
2502 /* Handle aggregate copies by expanding into copies of the respective
2503    fields of the structures.  */
2504
2505 static void
2506 do_structure_copy (tree lhsop, tree rhsop)
2507 {
2508   struct constraint_expr lhs, rhs, tmp;
2509   varinfo_t p;
2510   unsigned HOST_WIDE_INT lhssize;
2511   unsigned HOST_WIDE_INT rhssize;
2512
2513   lhs = get_constraint_for (lhsop, NULL);  
2514   rhs = get_constraint_for (rhsop, NULL);
2515   
2516   /* If we have special var = x, swap it around.  */
2517   if (lhs.var <= integer_id && !(get_varinfo (rhs.var)->is_special_var))
2518     {
2519       tmp = lhs;
2520       lhs = rhs;
2521       rhs = tmp;
2522     }
2523   
2524   /*  This is fairly conservative for the RHS == ADDRESSOF case, in that it's
2525       possible it's something we could handle.  However, most cases falling
2526       into this are dealing with transparent unions, which are slightly
2527       weird. */
2528   if (rhs.type == ADDRESSOF && !(get_varinfo (rhs.var)->is_special_var))
2529     {
2530       rhs.type = ADDRESSOF;
2531       rhs.var = anything_id;
2532     }
2533
2534   /* If the RHS is a special var, or an addressof, set all the LHS fields to
2535      that special var.  */
2536   if (rhs.var <= integer_id)
2537     {
2538       for (p = get_varinfo (lhs.var); p; p = p->next)
2539         {
2540           struct constraint_expr templhs = lhs;
2541           struct constraint_expr temprhs = rhs;
2542           if (templhs.type == SCALAR )
2543             templhs.var = p->id;
2544           else
2545             templhs.offset += p->offset;
2546           process_constraint (new_constraint (templhs, temprhs));
2547         }
2548     }
2549   else
2550     {
2551       tree rhstype = TREE_TYPE (rhsop);
2552       tree lhstype = TREE_TYPE (lhsop);
2553       tree rhstypesize = TYPE_SIZE (rhstype);
2554       tree lhstypesize = TYPE_SIZE (lhstype);
2555
2556       /* If we have a variably sized types on the rhs or lhs, and a deref
2557          constraint, add the constraint, lhsconstraint = &ANYTHING.
2558          This is conservatively correct because either the lhs is an unknown
2559          sized var (if the constraint is SCALAR), or the lhs is a DEREF
2560          constraint, and every variable it can point to must be unknown sized
2561          anyway, so we don't need to worry about fields at all.  */
2562       if ((rhs.type == DEREF && TREE_CODE (rhstypesize) != INTEGER_CST)
2563           || (lhs.type == DEREF && TREE_CODE (lhstypesize) != INTEGER_CST))
2564         {
2565           rhs.var = anything_id;
2566           rhs.type = ADDRESSOF;
2567           rhs.offset = 0;
2568           process_constraint (new_constraint (lhs, rhs));
2569           return;
2570         }
2571
2572       /* The size only really matters insofar as we don't set more or less of
2573          the variable.  If we hit an unknown size var, the size should be the
2574          whole darn thing.  */
2575       if (get_varinfo (rhs.var)->is_unknown_size_var)
2576         rhssize = ~0;
2577       else
2578         rhssize = TREE_INT_CST_LOW (rhstypesize);
2579
2580       if (get_varinfo (lhs.var)->is_unknown_size_var)
2581         lhssize = ~0;
2582       else
2583         lhssize = TREE_INT_CST_LOW (lhstypesize);
2584
2585   
2586       if (rhs.type == SCALAR && lhs.type == SCALAR)  
2587         {
2588           if (!do_simple_structure_copy (lhs, rhs, MIN (lhssize, rhssize)))
2589             {         
2590               lhs.var = collapse_rest_of_var (lhs.var);
2591               rhs.var = collapse_rest_of_var (rhs.var);
2592               lhs.offset = 0;
2593               rhs.offset = 0;
2594               lhs.type = SCALAR;
2595               rhs.type = SCALAR;
2596               process_constraint (new_constraint (lhs, rhs));
2597             }
2598         }
2599       else if (lhs.type != DEREF && rhs.type == DEREF)
2600         do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2601       else if (lhs.type == DEREF && rhs.type != DEREF)
2602         do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2603       else
2604         {
2605           tree pointedtotype = lhstype;
2606           tree tmpvar;  
2607
2608           gcc_assert (rhs.type == DEREF && lhs.type == DEREF);
2609           tmpvar = create_tmp_var_raw (pointedtotype, "structcopydereftmp");
2610           do_structure_copy (tmpvar, rhsop);
2611           do_structure_copy (lhsop, tmpvar);
2612         }
2613     }
2614 }
2615
2616 /* Update related alias information kept in AI.  This is used when
2617    building name tags, alias sets and deciding grouping heuristics.
2618    STMT is the statement to process.  This function also updates
2619    ADDRESSABLE_VARS.  */
2620
2621 static void
2622 update_alias_info (tree stmt, struct alias_info *ai)
2623 {
2624   bitmap addr_taken;
2625   use_operand_p use_p;
2626   ssa_op_iter iter;
2627   bool stmt_escapes_p = is_escape_site (stmt, ai);
2628   tree op;
2629
2630   /* Mark all the variables whose address are taken by the statement.  */
2631   addr_taken = addresses_taken (stmt);
2632   if (addr_taken)
2633     {
2634       bitmap_ior_into (addressable_vars, addr_taken);
2635
2636       /* If STMT is an escape point, all the addresses taken by it are
2637          call-clobbered.  */
2638       if (stmt_escapes_p)
2639         {
2640           bitmap_iterator bi;
2641           unsigned i;
2642
2643           EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
2644             mark_call_clobbered (referenced_var (i));
2645         }
2646     }
2647
2648   /* Process each operand use.  If an operand may be aliased, keep
2649      track of how many times it's being used.  For pointers, determine
2650      whether they are dereferenced by the statement, or whether their
2651      value escapes, etc.  */
2652   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2653     {
2654       tree op, var;
2655       var_ann_t v_ann;
2656       struct ptr_info_def *pi;
2657       bool is_store, is_potential_deref;
2658       unsigned num_uses, num_derefs;
2659
2660       op = USE_FROM_PTR (use_p);
2661
2662       /* If STMT is a PHI node, OP may be an ADDR_EXPR.  If so, add it
2663          to the set of addressable variables.  */
2664       if (TREE_CODE (op) == ADDR_EXPR)
2665         {
2666           gcc_assert (TREE_CODE (stmt) == PHI_NODE);
2667
2668           /* PHI nodes don't have annotations for pinning the set
2669              of addresses taken, so we collect them here.
2670
2671              FIXME, should we allow PHI nodes to have annotations
2672              so that they can be treated like regular statements?
2673              Currently, they are treated as second-class
2674              statements.  */
2675           add_to_addressable_set (TREE_OPERAND (op, 0), &addressable_vars);
2676           continue;
2677         }
2678
2679       /* Ignore constants.  */
2680       if (TREE_CODE (op) != SSA_NAME)
2681         continue;
2682
2683       var = SSA_NAME_VAR (op);
2684       v_ann = var_ann (var);
2685
2686       /* If the operand's variable may be aliased, keep track of how
2687          many times we've referenced it.  This is used for alias
2688          grouping in compute_flow_insensitive_aliasing.  */
2689       if (may_be_aliased (var))
2690         NUM_REFERENCES_INC (v_ann);
2691
2692       /* We are only interested in pointers.  */
2693       if (!POINTER_TYPE_P (TREE_TYPE (op)))
2694         continue;
2695
2696       pi = get_ptr_info (op);
2697
2698       /* Add OP to AI->PROCESSED_PTRS, if it's not there already.  */
2699       if (!TEST_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op)))
2700         {
2701           SET_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op));
2702           VARRAY_PUSH_TREE (ai->processed_ptrs, op);
2703         }
2704
2705       /* If STMT is a PHI node, then it will not have pointer
2706          dereferences and it will not be an escape point.  */
2707       if (TREE_CODE (stmt) == PHI_NODE)
2708         continue;
2709
2710       /* Determine whether OP is a dereferenced pointer, and if STMT
2711          is an escape point, whether OP escapes.  */
2712       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
2713
2714       /* Handle a corner case involving address expressions of the
2715          form '&PTR->FLD'.  The problem with these expressions is that
2716          they do not represent a dereference of PTR.  However, if some
2717          other transformation propagates them into an INDIRECT_REF
2718          expression, we end up with '*(&PTR->FLD)' which is folded
2719          into 'PTR->FLD'.
2720
2721          So, if the original code had no other dereferences of PTR,
2722          the aliaser will not create memory tags for it, and when
2723          &PTR->FLD gets propagated to INDIRECT_REF expressions, the
2724          memory operations will receive no V_MAY_DEF/VUSE operands.
2725
2726          One solution would be to have count_uses_and_derefs consider
2727          &PTR->FLD a dereference of PTR.  But that is wrong, since it
2728          is not really a dereference but an offset calculation.
2729
2730          What we do here is to recognize these special ADDR_EXPR
2731          nodes.  Since these expressions are never GIMPLE values (they
2732          are not GIMPLE invariants), they can only appear on the RHS
2733          of an assignment and their base address is always an
2734          INDIRECT_REF expression.  */
2735       is_potential_deref = false;
2736       if (TREE_CODE (stmt) == MODIFY_EXPR
2737           && TREE_CODE (TREE_OPERAND (stmt, 1)) == ADDR_EXPR
2738           && !is_gimple_val (TREE_OPERAND (stmt, 1)))
2739         {
2740           /* If the RHS if of the form &PTR->FLD and PTR == OP, then
2741              this represents a potential dereference of PTR.  */
2742           tree rhs = TREE_OPERAND (stmt, 1);
2743           tree base = get_base_address (TREE_OPERAND (rhs, 0));
2744           if (TREE_CODE (base) == INDIRECT_REF
2745               && TREE_OPERAND (base, 0) == op)
2746             is_potential_deref = true;
2747         }
2748
2749       if (num_derefs > 0 || is_potential_deref)
2750         {
2751           /* Mark OP as dereferenced.  In a subsequent pass,
2752              dereferenced pointers that point to a set of
2753              variables will be assigned a name tag to alias
2754              all the variables OP points to.  */
2755           pi->is_dereferenced = 1;
2756
2757           /* Keep track of how many time we've dereferenced each
2758              pointer.  */
2759           NUM_REFERENCES_INC (v_ann);
2760
2761           /* If this is a store operation, mark OP as being
2762              dereferenced to store, otherwise mark it as being
2763              dereferenced to load.  */
2764           if (is_store)
2765             bitmap_set_bit (ai->dereferenced_ptrs_store, DECL_UID (var));
2766           else
2767             bitmap_set_bit (ai->dereferenced_ptrs_load, DECL_UID (var));
2768         }
2769
2770       if (stmt_escapes_p && num_derefs < num_uses)
2771         {
2772           /* If STMT is an escape point and STMT contains at
2773              least one direct use of OP, then the value of OP
2774              escapes and so the pointed-to variables need to
2775              be marked call-clobbered.  */
2776           pi->value_escapes_p = 1;
2777
2778           /* If the statement makes a function call, assume
2779              that pointer OP will be dereferenced in a store
2780              operation inside the called function.  */
2781           if (get_call_expr_in (stmt))
2782             {
2783               bitmap_set_bit (ai->dereferenced_ptrs_store, DECL_UID (var));
2784               pi->is_dereferenced = 1;
2785             }
2786         }
2787     }
2788
2789   if (TREE_CODE (stmt) == PHI_NODE)
2790     return;
2791
2792   /* Update reference counter for definitions to any
2793      potentially aliased variable.  This is used in the alias
2794      grouping heuristics.  */
2795   FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
2796     {
2797       tree var = SSA_NAME_VAR (op);
2798       var_ann_t ann = var_ann (var);
2799       bitmap_set_bit (ai->written_vars, DECL_UID (var));
2800       if (may_be_aliased (var))
2801         NUM_REFERENCES_INC (ann);
2802       
2803     }
2804   
2805   /* Mark variables in V_MAY_DEF operands as being written to.  */
2806   FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_VIRTUAL_DEFS)
2807     {
2808       tree var = DECL_P (op) ? op : SSA_NAME_VAR (op);
2809       bitmap_set_bit (ai->written_vars, DECL_UID (var));
2810     }
2811 }
2812
2813
2814 /* Handle pointer arithmetic EXPR when creating aliasing constraints.
2815    Expressions of the type PTR + CST can be handled in two ways:
2816
2817    1- If the constraint for PTR is ADDRESSOF for a non-structure
2818       variable, then we can use it directly because adding or
2819       subtracting a constant may not alter the original ADDRESSOF
2820       constraint (i.e., pointer arithmetic may not legally go outside
2821       an object's boundaries).
2822
2823    2- If the constraint for PTR is ADDRESSOF for a structure variable,
2824       then if CST is a compile-time constant that can be used as an
2825       offset, we can determine which sub-variable will be pointed-to
2826       by the expression.
2827
2828    Return true if the expression is handled.  For any other kind of
2829    expression, return false so that each operand can be added as a
2830    separate constraint by the caller.  */
2831
2832 static bool
2833 handle_ptr_arith (struct constraint_expr lhs, tree expr)
2834 {
2835   tree op0, op1;
2836   struct constraint_expr base, offset;
2837
2838   if (TREE_CODE (expr) != PLUS_EXPR)
2839     return false;
2840
2841   op0 = TREE_OPERAND (expr, 0);
2842   op1 = TREE_OPERAND (expr, 1);
2843
2844   base = get_constraint_for (op0, NULL);
2845
2846   offset.var = anyoffset_id;
2847   offset.type = ADDRESSOF;
2848   offset.offset = 0;
2849
2850   process_constraint (new_constraint (lhs, base));
2851   process_constraint (new_constraint (lhs, offset));
2852
2853   return true;
2854 }
2855
2856
2857 /* Walk statement T setting up aliasing constraints according to the
2858    references found in T.  This function is the main part of the
2859    constraint builder.  AI points to auxiliary alias information used
2860    when building alias sets and computing alias grouping heuristics.  */
2861
2862 static void
2863 find_func_aliases (tree t, struct alias_info *ai)
2864 {
2865   struct constraint_expr lhs, rhs;
2866
2867   /* Update various related attributes like escaped addresses, pointer
2868      dereferences for loads and stores.  This is used when creating
2869      name tags and alias sets.  */
2870   update_alias_info (t, ai);
2871
2872   /* Now build constraints expressions.  */
2873   if (TREE_CODE (t) == PHI_NODE)
2874     {
2875       /* Only care about pointers and structures containing
2876          pointers.  */
2877       if (POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (t)))
2878           || AGGREGATE_TYPE_P (TREE_TYPE (PHI_RESULT (t))))
2879         {
2880           int i;
2881
2882           lhs = get_constraint_for (PHI_RESULT (t), NULL);
2883           for (i = 0; i < PHI_NUM_ARGS (t); i++)
2884             {
2885               rhs = get_constraint_for (PHI_ARG_DEF (t, i), NULL);
2886               process_constraint (new_constraint (lhs, rhs));
2887             }
2888         }
2889     }
2890   else if (TREE_CODE (t) == MODIFY_EXPR)
2891     {
2892       tree lhsop = TREE_OPERAND (t, 0);
2893       tree rhsop = TREE_OPERAND (t, 1);
2894       int i;    
2895
2896       if (AGGREGATE_TYPE_P (TREE_TYPE (lhsop)) 
2897           && AGGREGATE_TYPE_P (TREE_TYPE (rhsop)))
2898         {
2899           do_structure_copy (lhsop, rhsop);
2900         }
2901       else
2902         {
2903           /* Only care about operations with pointers, structures
2904              containing pointers, dereferences, and call expressions.  */
2905           if (POINTER_TYPE_P (TREE_TYPE (lhsop))
2906               || AGGREGATE_TYPE_P (TREE_TYPE (lhsop))
2907               || TREE_CODE (rhsop) == CALL_EXPR)
2908             {
2909               lhs = get_constraint_for (lhsop, NULL);
2910               switch (TREE_CODE_CLASS (TREE_CODE (rhsop)))
2911                 {
2912                   /* RHS that consist of unary operations,
2913                      exceptional types, or bare decls/constants, get
2914                      handled directly by get_constraint_for.  */ 
2915                   case tcc_reference:
2916                   case tcc_declaration:
2917                   case tcc_constant:
2918                   case tcc_exceptional:
2919                   case tcc_expression:
2920                   case tcc_unary:
2921                       {
2922                         tree anyoffsetrhs = rhsop;
2923                         bool need_anyoffset = false;
2924                         rhs = get_constraint_for (rhsop, &need_anyoffset);
2925                         process_constraint (new_constraint (lhs, rhs));
2926                         
2927                         STRIP_NOPS (anyoffsetrhs);
2928                         /* When taking the address of an aggregate
2929                            type, from the LHS we can access any field
2930                            of the RHS.  */
2931                         if (need_anyoffset || (rhs.type == ADDRESSOF
2932                             && !(get_varinfo (rhs.var)->is_special_var)
2933                             && AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (anyoffsetrhs)))))
2934                           {
2935                             rhs.var = anyoffset_id;
2936                             rhs.type = ADDRESSOF;
2937                             rhs.offset = 0;
2938                             process_constraint (new_constraint (lhs, rhs));
2939                           }
2940                       }
2941                     break;
2942
2943                   case tcc_binary:
2944                       {
2945                         /* For pointer arithmetic of the form
2946                            PTR + CST, we can simply use PTR's
2947                            constraint because pointer arithmetic is
2948                            not allowed to go out of bounds.  */
2949                         if (handle_ptr_arith (lhs, rhsop))
2950                           break;
2951                       }
2952                     /* FALLTHRU  */
2953
2954                   /* Otherwise, walk each operand.  Notice that we
2955                      can't use the operand interface because we need
2956                      to process expressions other than simple operands
2957                      (e.g. INDIRECT_REF, ADDR_EXPR, CALL_EXPR).  */
2958                   default:
2959                     for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (rhsop)); i++)
2960                       {
2961                         tree op = TREE_OPERAND (rhsop, i);
2962                         rhs = get_constraint_for (op, NULL);
2963                         process_constraint (new_constraint (lhs, rhs));
2964                       }
2965                 }      
2966             }
2967         }
2968     }
2969
2970   /* After promoting variables and computing aliasing we will
2971      need to re-scan most statements.  FIXME: Try to minimize the
2972      number of statements re-scanned.  It's not really necessary to
2973      re-scan *all* statements.  */
2974   mark_stmt_modified (t);
2975 }
2976
2977
2978 /* Find the first varinfo in the same variable as START that overlaps with
2979    OFFSET.
2980    Effectively, walk the chain of fields for the variable START to find the
2981    first field that overlaps with OFFSET.
2982    Return NULL if we can't find one.  */
2983
2984 static varinfo_t 
2985 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
2986 {
2987   varinfo_t curr = start;
2988   while (curr)
2989     {
2990       /* We may not find a variable in the field list with the actual
2991          offset when when we have glommed a structure to a variable.
2992          In that case, however, offset should still be within the size
2993          of the variable. */
2994       if (offset >= curr->offset && offset < (curr->offset +  curr->size))
2995         return curr;
2996       curr = curr->next;
2997     }
2998   return NULL;
2999 }
3000
3001
3002 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3003    offset.  */
3004
3005 static void
3006 insert_into_field_list (varinfo_t base, varinfo_t field)
3007 {
3008   varinfo_t prev = base;
3009   varinfo_t curr = base->next;
3010   
3011   if (curr == NULL)
3012     {
3013       prev->next = field;
3014       field->next = NULL;
3015     }
3016   else
3017     {
3018       while (curr)
3019         {
3020           if (field->offset <= curr->offset)
3021             break;
3022           prev = curr;
3023           curr = curr->next;
3024         }
3025       field->next = prev->next;
3026       prev->next = field;
3027     }
3028 }
3029
3030 /* qsort comparison function for two fieldoff's PA and PB */
3031
3032 static int 
3033 fieldoff_compare (const void *pa, const void *pb)
3034 {
3035   const fieldoff_s *foa = (const fieldoff_s *)pa;
3036   const fieldoff_s *fob = (const fieldoff_s *)pb;
3037   HOST_WIDE_INT foasize, fobsize;
3038   
3039   if (foa->offset != fob->offset)
3040     return foa->offset - fob->offset;
3041
3042   foasize = TREE_INT_CST_LOW (DECL_SIZE (foa->field));
3043   fobsize = TREE_INT_CST_LOW (DECL_SIZE (fob->field));
3044   return foasize - fobsize;
3045 }
3046
3047 /* Sort a fieldstack according to the field offset and sizes.  */
3048 void sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3049 {
3050   qsort (VEC_address (fieldoff_s, fieldstack), 
3051          VEC_length (fieldoff_s, fieldstack), 
3052          sizeof (fieldoff_s),
3053          fieldoff_compare);
3054 }
3055
3056 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
3057    of TYPE onto fieldstack, recording their offsets along the way.
3058    OFFSET is used to keep track of the offset in this entire structure, rather
3059    than just the immediately containing structure.  Returns the number
3060    of fields pushed.
3061    HAS_UNION is set to true if we find a union type as a field of
3062    TYPE.  */
3063
3064 int
3065 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack, 
3066                              HOST_WIDE_INT offset, bool *has_union)
3067 {
3068   tree field;
3069   int count = 0;
3070
3071   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3072     if (TREE_CODE (field) == FIELD_DECL)
3073       {
3074         bool push = false;
3075         int pushed = 0;
3076         
3077         if (has_union 
3078             && (TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
3079                 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE))
3080           *has_union = true;
3081         
3082         if (!var_can_have_subvars (field))
3083           push = true;
3084         else if (!(pushed = push_fields_onto_fieldstack
3085                    (TREE_TYPE (field), fieldstack,
3086                     offset + bitpos_of_field (field), has_union))
3087                  && DECL_SIZE (field)
3088                  && !integer_zerop (DECL_SIZE (field)))
3089           /* Empty structures may have actual size, like in C++. So
3090              see if we didn't push any subfields and the size is
3091              nonzero, push the field onto the stack */
3092           push = true;
3093         
3094         if (push)
3095           {
3096             fieldoff_s *pair;
3097
3098             pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3099             pair->field = field;
3100             pair->offset = offset + bitpos_of_field (field);
3101             count++;
3102           }
3103         else
3104           count += pushed;
3105       }
3106
3107   return count;
3108 }
3109
3110 static void
3111 make_constraint_to_anything (varinfo_t vi)
3112 {
3113   struct constraint_expr lhs, rhs;
3114   
3115   lhs.var = vi->id;
3116   lhs.offset = 0;
3117   lhs.type = SCALAR;
3118   
3119   rhs.var = anything_id;
3120   rhs.offset =0 ;
3121   rhs.type = ADDRESSOF;
3122   process_constraint (new_constraint (lhs, rhs));
3123 }
3124
3125
3126 /* Return true if FIELDSTACK contains fields that overlap. 
3127    FIELDSTACK is assumed to be sorted by offset.  */
3128
3129 static bool
3130 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
3131 {
3132   fieldoff_s *fo = NULL;
3133   unsigned int i;
3134   HOST_WIDE_INT lastoffset = -1;
3135
3136   for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3137     {
3138       if (fo->offset == lastoffset)
3139         return true;
3140       lastoffset = fo->offset;
3141     }
3142   return false;
3143 }
3144
3145 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
3146    This will also create any varinfo structures necessary for fields
3147    of DECL.  */
3148
3149 static unsigned int
3150 create_variable_info_for (tree decl, const char *name)
3151 {
3152   unsigned int index = VEC_length (varinfo_t, varmap);
3153   varinfo_t vi;
3154   tree decltype = TREE_TYPE (decl);
3155   bool notokay = false;
3156   bool hasunion;
3157   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
3158   VEC (fieldoff_s,heap) *fieldstack = NULL;
3159   
3160
3161   hasunion = TREE_CODE (decltype) == UNION_TYPE
3162              || TREE_CODE (decltype) == QUAL_UNION_TYPE;
3163   if (var_can_have_subvars (decl) && use_field_sensitive && !hasunion)
3164     {
3165       push_fields_onto_fieldstack (decltype, &fieldstack, 0, &hasunion);
3166       if (hasunion)
3167         {
3168           VEC_free (fieldoff_s, heap, fieldstack);
3169           notokay = true;
3170         }        
3171     }
3172   
3173
3174   /* If the variable doesn't have subvars, we may end up needing to
3175      sort the field list and create fake variables for all the
3176      fields.  */
3177   vi = new_var_info (decl, index, name, index);
3178   vi->decl = decl;
3179   vi->offset = 0;
3180   vi->has_union = hasunion;
3181   if (!TYPE_SIZE (decltype) 
3182       || TREE_CODE (TYPE_SIZE (decltype)) != INTEGER_CST
3183       || TREE_CODE (decltype) == ARRAY_TYPE
3184       || TREE_CODE (decltype) == UNION_TYPE
3185       || TREE_CODE (decltype) == QUAL_UNION_TYPE)
3186     {
3187       vi->is_unknown_size_var = true;
3188       vi->fullsize = ~0;
3189       vi->size = ~0;
3190     }
3191   else
3192     {
3193       vi->fullsize = TREE_INT_CST_LOW (TYPE_SIZE (decltype));
3194       vi->size = vi->fullsize;
3195     }
3196   
3197   insert_id_for_tree (vi->decl, index);  
3198   VEC_safe_push (varinfo_t, heap, varmap, vi);
3199   if (is_global)
3200     make_constraint_to_anything (vi);
3201
3202   stats.total_vars++;
3203   if (use_field_sensitive 
3204       && !notokay 
3205       && !vi->is_unknown_size_var 
3206       && var_can_have_subvars (decl))
3207     {
3208       unsigned int newindex = VEC_length (varinfo_t, varmap);
3209       fieldoff_s *fo = NULL;
3210       unsigned int i;
3211       tree field;
3212
3213       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3214         {
3215           if (!DECL_SIZE (fo->field) 
3216               || TREE_CODE (DECL_SIZE (fo->field)) != INTEGER_CST
3217               || TREE_CODE (TREE_TYPE (fo->field)) == ARRAY_TYPE
3218               || fo->offset < 0)
3219             {
3220               notokay = true;
3221               break;
3222             }
3223         }
3224
3225       /* We can't sort them if we have a field with a variable sized type,
3226          which will make notokay = true.  In that case, we are going to return
3227          without creating varinfos for the fields anyway, so sorting them is a
3228          waste to boot.  */
3229       if (!notokay)
3230         {       
3231           sort_fieldstack (fieldstack);
3232           /* Due to some C++ FE issues, like PR 22488, we might end up
3233              what appear to be overlapping fields even though they,
3234              in reality, do not overlap.  Until the C++ FE is fixed,
3235              we will simply disable field-sensitivity for these cases.  */
3236           notokay = check_for_overlaps (fieldstack);
3237         }
3238       
3239       
3240       if (VEC_length (fieldoff_s, fieldstack) != 0)
3241         fo = VEC_index (fieldoff_s, fieldstack, 0);
3242
3243       if (fo == NULL || notokay)
3244         {
3245           vi->is_unknown_size_var = 1;
3246           vi->fullsize = ~0;
3247           vi->size = ~0;
3248           VEC_free (fieldoff_s, heap, fieldstack);
3249           return index;
3250         }
3251       
3252       field = fo->field;
3253       vi->size = TREE_INT_CST_LOW (DECL_SIZE (field));
3254       vi->offset = fo->offset;
3255       for (i = 1; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3256         {
3257           varinfo_t newvi;
3258           const char *newname;
3259           char *tempname;
3260
3261           field = fo->field;
3262           newindex = VEC_length (varinfo_t, varmap);
3263           asprintf (&tempname, "%s.%s", vi->name, alias_get_name (field));
3264           newname = ggc_strdup (tempname);
3265           free (tempname);
3266           newvi = new_var_info (decl, newindex, newname, newindex);
3267           newvi->offset = fo->offset;
3268           newvi->size = TREE_INT_CST_LOW (DECL_SIZE (field));
3269           newvi->fullsize = vi->fullsize;
3270           insert_into_field_list (vi, newvi);
3271           VEC_safe_push (varinfo_t, heap, varmap, newvi);
3272           if (is_global)
3273             make_constraint_to_anything (newvi);
3274
3275           stats.total_vars++;     
3276         }
3277       VEC_free (fieldoff_s, heap, fieldstack);
3278     }
3279   return index;
3280 }
3281
3282 /* Print out the points-to solution for VAR to FILE.  */
3283
3284 void
3285 dump_solution_for_var (FILE *file, unsigned int var)
3286 {
3287   varinfo_t vi = get_varinfo (var);
3288   unsigned int i;
3289   bitmap_iterator bi; 
3290   
3291   fprintf (file, "%s = { ", vi->name);
3292   EXECUTE_IF_SET_IN_BITMAP (get_varinfo (vi->node)->solution, 0, i, bi)
3293     {
3294       fprintf (file, "%s ", get_varinfo (i)->name);
3295     }
3296   fprintf (file, "}\n");
3297 }
3298
3299 /* Print the points-to solution for VAR to stdout.  */
3300
3301 void
3302 debug_solution_for_var (unsigned int var)
3303 {
3304   dump_solution_for_var (stdout, var);
3305 }
3306
3307
3308 /* Create varinfo structures for all of the variables in the
3309    function for intraprocedural mode.  */
3310
3311 static void
3312 intra_create_variable_infos (void)
3313 {
3314   tree t;
3315
3316   /* For each incoming argument arg, ARG = &ANYTHING */
3317   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
3318     {
3319       struct constraint_expr lhs;
3320       struct constraint_expr rhs;
3321       varinfo_t p;
3322       
3323       lhs.offset = 0;
3324       lhs.type = SCALAR;
3325       lhs.var  = create_variable_info_for (t, alias_get_name (t));
3326       
3327       rhs.var = anything_id;
3328       rhs.type = ADDRESSOF;
3329       rhs.offset = 0;
3330
3331       for (p = get_varinfo (lhs.var); p; p = p->next)
3332         {
3333           struct constraint_expr temp = lhs;
3334           temp.var = p->id;
3335           process_constraint (new_constraint (temp, rhs));
3336         }
3337     }   
3338
3339 }
3340
3341 /* Set bits in INTO corresponding to the variable uids in solution set
3342    FROM  */
3343
3344 static void
3345 set_uids_in_ptset (bitmap into, bitmap from)
3346 {
3347   unsigned int i;
3348   bitmap_iterator bi;
3349   bool found_anyoffset = false;
3350   subvar_t sv;
3351
3352   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
3353     {
3354       varinfo_t vi = get_varinfo (i);
3355
3356       /* If we find ANYOFFSET in the solution and the solution
3357          includes SFTs for some structure, then all the SFTs in that
3358          structure will need to be added to the alias set.  */
3359       if (vi->id == anyoffset_id)
3360         {
3361           found_anyoffset = true;
3362           continue;
3363         }
3364
3365       /* The only artificial variables that are allowed in a may-alias
3366          set are heap variables.  */
3367       if (vi->is_artificial_var && !vi->is_heap_var)
3368         continue;
3369       
3370       if (vi->has_union && get_subvars_for_var (vi->decl) != NULL)
3371         {
3372           /* Variables containing unions may need to be converted to
3373              their SFT's, because SFT's can have unions and we cannot.  */
3374           for (sv = get_subvars_for_var (vi->decl); sv; sv = sv->next)
3375             bitmap_set_bit (into, DECL_UID (sv->var));
3376         }
3377       else if (TREE_CODE (vi->decl) == VAR_DECL 
3378                || TREE_CODE (vi->decl) == PARM_DECL)
3379         {
3380           if (found_anyoffset
3381               && var_can_have_subvars (vi->decl)
3382               && get_subvars_for_var (vi->decl))
3383             {
3384               /* If ANYOFFSET is in the solution set and VI->DECL is
3385                  an aggregate variable with sub-variables, then any of
3386                  the SFTs inside VI->DECL may have been accessed.  Add
3387                  all the sub-vars for VI->DECL.  */
3388               for (sv = get_subvars_for_var (vi->decl); sv; sv = sv->next)
3389                 bitmap_set_bit (into, DECL_UID (sv->var));
3390             }
3391           else if (var_can_have_subvars (vi->decl)
3392                    && get_subvars_for_var (vi->decl))
3393             {
3394               /* If VI->DECL is an aggregate for which we created
3395                  SFTs, add the SFT corresponding to VI->OFFSET.  */
3396               tree sft = get_subvar_at (vi->decl, vi->offset);
3397               bitmap_set_bit (into, DECL_UID (sft));
3398             }
3399           else
3400             {
3401               /* Otherwise, just add VI->DECL to the alias set.  */
3402               bitmap_set_bit (into, DECL_UID (vi->decl));
3403             }
3404         }
3405     }
3406 }
3407
3408
3409 static bool have_alias_info = false;
3410
3411 /* Given a pointer variable P, fill in its points-to set, or return
3412    false if we can't.  */
3413
3414 bool
3415 find_what_p_points_to (tree p)
3416 {
3417   unsigned int id = 0;
3418
3419   if (!have_alias_info)
3420     return false;
3421
3422   if (lookup_id_for_tree (p, &id))
3423     {
3424       varinfo_t vi = get_varinfo (id);
3425       
3426       if (vi->is_artificial_var)
3427         return false;
3428
3429       /* See if this is a field or a structure.  */
3430       if (vi->size != vi->fullsize)
3431         {
3432           /* Nothing currently asks about structure fields directly,
3433              but when they do, we need code here to hand back the
3434              points-to set.  */
3435           if (!var_can_have_subvars (vi->decl)
3436               || get_subvars_for_var (vi->decl) == NULL)
3437             return false;
3438         } 
3439       else
3440         {
3441           struct ptr_info_def *pi = get_ptr_info (p);
3442           unsigned int i;
3443           bitmap_iterator bi;
3444
3445           /* This variable may have been collapsed, let's get the real
3446              variable.  */
3447           vi = get_varinfo (vi->node);
3448           
3449           /* Translate artificial variables into SSA_NAME_PTR_INFO
3450              attributes.  */
3451           EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
3452             {
3453               varinfo_t vi = get_varinfo (i);
3454
3455               if (vi->is_artificial_var)
3456                 {
3457                   /* FIXME.  READONLY should be handled better so that
3458                      flow insensitive aliasing can disregard writable
3459                      aliases.  */
3460                   if (vi->id == nothing_id)
3461                     pi->pt_null = 1;
3462                   else if (vi->id == anything_id)
3463                     pi->pt_anything = 1;
3464                   else if (vi->id == readonly_id)
3465                     pi->pt_anything = 1;
3466                   else if (vi->id == integer_id)
3467                     pi->pt_anything = 1;
3468                   else if (vi->is_heap_var)
3469                     pi->pt_global_mem = 1;
3470                 }
3471             }
3472
3473           if (pi->pt_anything)
3474             return false;
3475
3476           if (!pi->pt_vars)
3477             pi->pt_vars = BITMAP_GGC_ALLOC ();
3478
3479           set_uids_in_ptset (pi->pt_vars, vi->solution);
3480
3481           if (bitmap_empty_p (pi->pt_vars))
3482             pi->pt_vars = NULL;
3483
3484           return true;
3485         }
3486     }
3487
3488   return false;
3489 }
3490
3491
3492 /* Initialize things necessary to perform PTA */
3493
3494 static void
3495 init_alias_vars (void)
3496 {
3497   bitmap_obstack_initialize (&ptabitmap_obstack);
3498 }
3499
3500
3501 /* Dump points-to information to OUTFILE.  */
3502
3503 void
3504 dump_sa_points_to_info (FILE *outfile)
3505 {
3506   unsigned int i;
3507
3508   fprintf (outfile, "\nPoints-to sets\n\n");
3509
3510   if (dump_flags & TDF_STATS)
3511     {
3512       fprintf (outfile, "Stats:\n");
3513       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
3514       fprintf (outfile, "Statically unified vars:  %d\n",
3515                stats.unified_vars_static);
3516       fprintf (outfile, "Collapsed vars:           %d\n", stats.collapsed_vars);
3517       fprintf (outfile, "Dynamically unified vars: %d\n",
3518                stats.unified_vars_dynamic);
3519       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
3520     }
3521
3522   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
3523     dump_solution_for_var (outfile, i);
3524 }
3525
3526
3527 /* Debug points-to information to stderr.  */
3528
3529 void
3530 debug_sa_points_to_info (void)
3531 {
3532   dump_sa_points_to_info (stderr);
3533 }
3534
3535
3536 /* Initialize the always-existing constraint variables for NULL
3537    ANYTHING, READONLY, and INTEGER */
3538
3539 static void
3540 init_base_vars (void)
3541 {
3542   struct constraint_expr lhs, rhs;
3543
3544   /* Create the NULL variable, used to represent that a variable points
3545      to NULL.  */
3546   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
3547   var_nothing = new_var_info (nothing_tree, 0, "NULL", 0);
3548   insert_id_for_tree (nothing_tree, 0);
3549   var_nothing->is_artificial_var = 1;
3550   var_nothing->offset = 0;
3551   var_nothing->size = ~0;
3552   var_nothing->fullsize = ~0;
3553   var_nothing->is_special_var = 1;
3554   nothing_id = 0;
3555   VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
3556
3557   /* Create the ANYTHING variable, used to represent that a variable
3558      points to some unknown piece of memory.  */
3559   anything_tree = create_tmp_var_raw (void_type_node, "ANYTHING");
3560   var_anything = new_var_info (anything_tree, 1, "ANYTHING", 1); 
3561   insert_id_for_tree (anything_tree, 1);
3562   var_anything->is_artificial_var = 1;
3563   var_anything->size = ~0;
3564   var_anything->offset = 0;
3565   var_anything->next = NULL;
3566   var_anything->fullsize = ~0;
3567   var_anything->is_special_var = 1;
3568   anything_id = 1;
3569
3570   /* Anything points to anything.  This makes deref constraints just
3571      work in the presence of linked list and other p = *p type loops, 
3572      by saying that *ANYTHING = ANYTHING. */
3573   VEC_safe_push (varinfo_t, heap, varmap, var_anything);
3574   lhs.type = SCALAR;
3575   lhs.var = anything_id;
3576   lhs.offset = 0;
3577   rhs.type = ADDRESSOF;
3578   rhs.var = anything_id;
3579   rhs.offset = 0;
3580   var_anything->address_taken = true;
3581
3582   /* This specifically does not use process_constraint because
3583      process_constraint ignores all anything = anything constraints, since all
3584      but this one are redundant.  */
3585   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
3586   
3587   /* Create the READONLY variable, used to represent that a variable
3588      points to readonly memory.  */
3589   readonly_tree = create_tmp_var_raw (void_type_node, "READONLY");
3590   var_readonly = new_var_info (readonly_tree, 2, "READONLY", 2);
3591   var_readonly->is_artificial_var = 1;
3592   var_readonly->offset = 0;
3593   var_readonly->size = ~0;
3594   var_readonly->fullsize = ~0;
3595   var_readonly->next = NULL;
3596   var_readonly->is_special_var = 1;
3597   insert_id_for_tree (readonly_tree, 2);
3598   readonly_id = 2;
3599   VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
3600
3601   /* readonly memory points to anything, in order to make deref
3602      easier.  In reality, it points to anything the particular
3603      readonly variable can point to, but we don't track this
3604      separately. */
3605   lhs.type = SCALAR;
3606   lhs.var = readonly_id;
3607   lhs.offset = 0;
3608   rhs.type = ADDRESSOF;
3609   rhs.var = anything_id;
3610   rhs.offset = 0;
3611   
3612   process_constraint (new_constraint (lhs, rhs));
3613   
3614   /* Create the INTEGER variable, used to represent that a variable points
3615      to an INTEGER.  */
3616   integer_tree = create_tmp_var_raw (void_type_node, "INTEGER");
3617   var_integer = new_var_info (integer_tree, 3, "INTEGER", 3);
3618   insert_id_for_tree (integer_tree, 3);
3619   var_integer->is_artificial_var = 1;
3620   var_integer->size = ~0;
3621   var_integer->fullsize = ~0;
3622   var_integer->offset = 0;
3623   var_integer->next = NULL;
3624   var_integer->is_special_var = 1;
3625   integer_id = 3;
3626   VEC_safe_push (varinfo_t, heap, varmap, var_integer);
3627
3628   /* *INTEGER = ANYTHING, because we don't know where a dereference of a random
3629      integer will point to.  */
3630   lhs.type = SCALAR;
3631   lhs.var = integer_id;
3632   lhs.offset = 0;
3633   rhs.type = ADDRESSOF;
3634   rhs.var = anything_id;
3635   rhs.offset = 0;
3636   process_constraint (new_constraint (lhs, rhs));
3637
3638   /* Create the ANYOFFSET variable, used to represent an arbitrary offset
3639      inside an object.  This is similar to ANYTHING, but less drastic.
3640      It means that the pointer can point anywhere inside an object,
3641      but not outside of it.  */
3642   anyoffset_tree = create_tmp_var_raw (void_type_node, "ANYOFFSET");
3643   anyoffset_id = 4;
3644   var_anyoffset = new_var_info (anyoffset_tree, anyoffset_id, "ANYOFFSET",
3645                                 anyoffset_id); 
3646   insert_id_for_tree (anyoffset_tree, anyoffset_id);
3647   var_anyoffset->is_artificial_var = 1;
3648   var_anyoffset->size = ~0;
3649   var_anyoffset->offset = 0;
3650   var_anyoffset->next = NULL;
3651   var_anyoffset->fullsize = ~0;
3652   var_anyoffset->is_special_var = 1;
3653   VEC_safe_push (varinfo_t, heap, varmap, var_anyoffset);
3654
3655   /* ANYOFFSET points to ANYOFFSET.  */
3656   lhs.type = SCALAR;
3657   lhs.var = anyoffset_id;
3658   lhs.offset = 0;
3659   rhs.type = ADDRESSOF;
3660   rhs.var = anyoffset_id;
3661   rhs.offset = 0;
3662   process_constraint (new_constraint (lhs, rhs));
3663 }  
3664
3665 /* Return true if we actually need to solve the constraint graph in order to
3666    get our points-to sets.  This is false when, for example, no addresses are
3667    taken other than special vars, or all points-to sets with members already
3668    contain the anything variable and there are no predecessors for other
3669    sets.  */
3670
3671 static bool
3672 need_to_solve (void)
3673 {
3674   int i;
3675   varinfo_t v;
3676   bool found_address_taken = false;
3677   bool found_non_anything = false;
3678
3679   for (i = 0; VEC_iterate (varinfo_t, varmap, i, v); i++)
3680     {
3681       if (v->is_special_var)
3682         continue;
3683
3684       if (v->address_taken)
3685         found_address_taken = true;
3686
3687       if (v->solution 
3688           && !bitmap_empty_p (v->solution) 
3689           && !bitmap_bit_p (v->solution, anything_id))
3690         found_non_anything = true;
3691       else if (bitmap_empty_p (v->solution)
3692                && VEC_length (constraint_edge_t, graph->preds[v->id]) != 0)
3693         found_non_anything = true;
3694
3695       if (found_address_taken && found_non_anything)
3696         return true;
3697     }
3698
3699   return false;
3700 }
3701
3702 /* Create points-to sets for the current function.  See the comments
3703    at the start of the file for an algorithmic overview.  */
3704
3705 void
3706 compute_points_to_sets (struct alias_info *ai)
3707 {
3708   basic_block bb;
3709
3710   timevar_push (TV_TREE_PTA);
3711
3712   init_alias_vars ();
3713
3714   constraint_pool = create_alloc_pool ("Constraint pool", 
3715                                        sizeof (struct constraint), 30);
3716   variable_info_pool = create_alloc_pool ("Variable info pool",
3717                                           sizeof (struct variable_info), 30);
3718   constraint_edge_pool = create_alloc_pool ("Constraint edges",
3719                                             sizeof (struct constraint_edge), 30);
3720   
3721   constraints = VEC_alloc (constraint_t, heap, 8);
3722   varmap = VEC_alloc (varinfo_t, heap, 8);
3723   id_for_tree = htab_create (10, tree_id_hash, tree_id_eq, free);
3724   memset (&stats, 0, sizeof (stats));
3725
3726   init_base_vars ();
3727
3728   intra_create_variable_infos ();
3729
3730   /* Now walk all statements and derive aliases.  */
3731   FOR_EACH_BB (bb)
3732     {
3733       block_stmt_iterator bsi; 
3734       tree phi;
3735
3736       for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
3737         if (is_gimple_reg (PHI_RESULT (phi)))
3738           find_func_aliases (phi, ai);
3739
3740       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3741         find_func_aliases (bsi_stmt (bsi), ai);
3742     }
3743
3744   build_constraint_graph ();
3745
3746   if (dump_file)
3747     {
3748       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
3749       dump_constraints (dump_file);
3750     }
3751   
3752   if (need_to_solve ())
3753     {
3754       if (dump_file)
3755         fprintf (dump_file, "\nCollapsing static cycles and doing variable "
3756                  "substitution:\n");
3757       
3758       find_and_collapse_graph_cycles (graph, false);
3759       perform_var_substitution (graph);
3760       
3761       if (dump_file)
3762         fprintf (dump_file, "\nSolving graph:\n");
3763       
3764       solve_graph (graph);
3765     }
3766   
3767   if (dump_file)
3768     dump_sa_points_to_info (dump_file);
3769   
3770   have_alias_info = true;
3771
3772   timevar_pop (TV_TREE_PTA);
3773 }
3774
3775
3776 /* Delete created points-to sets.  */
3777
3778 void
3779 delete_points_to_sets (void)
3780 {
3781   varinfo_t v;
3782   int i;
3783
3784   htab_delete (id_for_tree);
3785   bitmap_obstack_release (&ptabitmap_obstack);
3786   VEC_free (constraint_t, heap, constraints);
3787   
3788   for (i = 0; VEC_iterate (varinfo_t, varmap, i, v); i++)
3789     {
3790       VEC_free (constraint_edge_t, heap, graph->succs[i]);
3791       VEC_free (constraint_edge_t, heap, graph->preds[i]);
3792       VEC_free (constraint_t, heap, v->complex);
3793     }
3794   free (graph->succs);
3795   free (graph->preds);
3796   free (graph);
3797
3798   VEC_free (varinfo_t, heap, varmap);
3799   free_alloc_pool (variable_info_pool);
3800   free_alloc_pool (constraint_pool); 
3801   free_alloc_pool (constraint_edge_pool);
3802
3803   have_alias_info = false;
3804 }
3805
3806 /* Initialize the heapvar for statement mapping.  */
3807 void 
3808 init_alias_heapvars (void)
3809 {
3810   heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq, NULL);
3811 }
3812
3813 void
3814 delete_alias_heapvars (void)
3815 {
3816   htab_delete (heapvar_for_stmt);  
3817 }
3818
3819   
3820 #include "gt-tree-ssa-structalias.h"