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