OSDN Git Service

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