OSDN Git Service

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