OSDN Git Service

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