2007-05-22 H.J. Lu <hongjiu.lu@intel.com>
[official-gcc.git] / gcc / tree-ssa-structalias.c
blob50ef512209bd662116f22b95bb4a3c374c5867d4
1 /* Tree based points-to analysis
2 Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dberlin@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
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.
17 You should have received a copy of the GNU General Public License
18 along with GCC; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "flags.h"
30 #include "rtl.h"
31 #include "tm_p.h"
32 #include "hard-reg-set.h"
33 #include "basic-block.h"
34 #include "output.h"
35 #include "errors.h"
36 #include "diagnostic.h"
37 #include "tree.h"
38 #include "c-common.h"
39 #include "tree-flow.h"
40 #include "tree-inline.h"
41 #include "varray.h"
42 #include "c-tree.h"
43 #include "tree-gimple.h"
44 #include "hashtab.h"
45 #include "function.h"
46 #include "cgraph.h"
47 #include "tree-pass.h"
48 #include "timevar.h"
49 #include "alloc-pool.h"
50 #include "splay-tree.h"
51 #include "params.h"
52 #include "tree-ssa-structalias.h"
53 #include "cgraph.h"
54 #include "alias.h"
55 #include "pointer-set.h"
57 /* The idea behind this analyzer is to generate set constraints from the
58 program, then solve the resulting constraints in order to generate the
59 points-to sets.
61 Set constraints are a way of modeling program analysis problems that
62 involve sets. They consist of an inclusion constraint language,
63 describing the variables (each variable is a set) and operations that
64 are involved on the variables, and a set of rules that derive facts
65 from these operations. To solve a system of set constraints, you derive
66 all possible facts under the rules, which gives you the correct sets
67 as a consequence.
69 See "Efficient Field-sensitive pointer analysis for C" by "David
70 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
71 http://citeseer.ist.psu.edu/pearce04efficient.html
73 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
74 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
75 http://citeseer.ist.psu.edu/heintze01ultrafast.html
77 There are three types of real constraint expressions, DEREF,
78 ADDRESSOF, and SCALAR. Each constraint expression consists
79 of a constraint type, a variable, and an offset.
81 SCALAR is a constraint expression type used to represent x, whether
82 it appears on the LHS or the RHS of a statement.
83 DEREF is a constraint expression type used to represent *x, whether
84 it appears on the LHS or the RHS of a statement.
85 ADDRESSOF is a constraint expression used to represent &x, whether
86 it appears on the LHS or the RHS of a statement.
88 Each pointer variable in the program is assigned an integer id, and
89 each field of a structure variable is assigned an integer id as well.
91 Structure variables are linked to their list of fields through a "next
92 field" in each variable that points to the next field in offset
93 order.
94 Each variable for a structure field has
96 1. "size", that tells the size in bits of that field.
97 2. "fullsize, that tells the size in bits of the entire structure.
98 3. "offset", that tells the offset in bits from the beginning of the
99 structure to this field.
101 Thus,
102 struct f
104 int a;
105 int b;
106 } foo;
107 int *bar;
109 looks like
111 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
112 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
113 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
116 In order to solve the system of set constraints, the following is
117 done:
119 1. Each constraint variable x has a solution set associated with it,
120 Sol(x).
122 2. Constraints are separated into direct, copy, and complex.
123 Direct constraints are ADDRESSOF constraints that require no extra
124 processing, such as P = &Q
125 Copy constraints are those of the form P = Q.
126 Complex constraints are all the constraints involving dereferences
127 and offsets (including offsetted copies).
129 3. All direct constraints of the form P = &Q are processed, such
130 that Q is added to Sol(P)
132 4. All complex constraints for a given constraint variable are stored in a
133 linked list attached to that variable's node.
135 5. A directed graph is built out of the copy constraints. Each
136 constraint variable is a node in the graph, and an edge from
137 Q to P is added for each copy constraint of the form P = Q
139 6. The graph is then walked, and solution sets are
140 propagated along the copy edges, such that an edge from Q to P
141 causes Sol(P) <- Sol(P) union Sol(Q).
143 7. As we visit each node, all complex constraints associated with
144 that node are processed by adding appropriate copy edges to the graph, or the
145 appropriate variables to the solution set.
147 8. The process of walking the graph is iterated until no solution
148 sets change.
150 Prior to walking the graph in steps 6 and 7, We perform static
151 cycle elimination on the constraint graph, as well
152 as off-line variable substitution.
154 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
155 on and turned into anything), but isn't. You can just see what offset
156 inside the pointed-to struct it's going to access.
158 TODO: Constant bounded arrays can be handled as if they were structs of the
159 same number of elements.
161 TODO: Modeling heap and incoming pointers becomes much better if we
162 add fields to them as we discover them, which we could do.
164 TODO: We could handle unions, but to be honest, it's probably not
165 worth the pain or slowdown. */
167 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
168 htab_t heapvar_for_stmt;
170 static bool use_field_sensitive = true;
171 static int in_ipa_mode = 0;
173 /* Used for predecessor bitmaps. */
174 static bitmap_obstack predbitmap_obstack;
176 /* Used for points-to sets. */
177 static bitmap_obstack pta_obstack;
179 /* Used for oldsolution members of variables. */
180 static bitmap_obstack oldpta_obstack;
182 /* Used for per-solver-iteration bitmaps. */
183 static bitmap_obstack iteration_obstack;
185 static unsigned int create_variable_info_for (tree, const char *);
186 typedef struct constraint_graph *constraint_graph_t;
187 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
189 DEF_VEC_P(constraint_t);
190 DEF_VEC_ALLOC_P(constraint_t,heap);
192 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
193 if (a) \
194 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
196 static struct constraint_stats
198 unsigned int total_vars;
199 unsigned int nonpointer_vars;
200 unsigned int unified_vars_static;
201 unsigned int unified_vars_dynamic;
202 unsigned int iterations;
203 unsigned int num_edges;
204 unsigned int num_implicit_edges;
205 unsigned int points_to_sets_created;
206 } stats;
208 struct variable_info
210 /* ID of this variable */
211 unsigned int id;
213 /* Name of this variable */
214 const char *name;
216 /* Tree that this variable is associated with. */
217 tree decl;
219 /* Offset of this variable, in bits, from the base variable */
220 unsigned HOST_WIDE_INT offset;
222 /* Size of the variable, in bits. */
223 unsigned HOST_WIDE_INT size;
225 /* Full size of the base variable, in bits. */
226 unsigned HOST_WIDE_INT fullsize;
228 /* A link to the variable for the next field in this structure. */
229 struct variable_info *next;
231 /* True if the variable is directly the target of a dereference.
232 This is used to track which variables are *actually* dereferenced
233 so we can prune their points to listed. */
234 unsigned int directly_dereferenced:1;
236 /* True if this is a variable created by the constraint analysis, such as
237 heap variables and constraints we had to break up. */
238 unsigned int is_artificial_var:1;
240 /* True if this is a special variable whose solution set should not be
241 changed. */
242 unsigned int is_special_var:1;
244 /* True for variables whose size is not known or variable. */
245 unsigned int is_unknown_size_var:1;
247 /* True for variables that have unions somewhere in them. */
248 unsigned int has_union:1;
250 /* True if this is a heap variable. */
251 unsigned int is_heap_var:1;
253 /* Points-to set for this variable. */
254 bitmap solution;
256 /* Old points-to set for this variable. */
257 bitmap oldsolution;
259 /* Variable ids represented by this node. */
260 bitmap variables;
262 /* Variable id this was collapsed to due to type unsafety. This
263 should be unused completely after build_succ_graph, or something
264 is broken. */
265 struct variable_info *collapsed_to;
267 typedef struct variable_info *varinfo_t;
269 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
271 /* Pool of variable info structures. */
272 static alloc_pool variable_info_pool;
274 DEF_VEC_P(varinfo_t);
276 DEF_VEC_ALLOC_P(varinfo_t, heap);
278 /* Table of variable info structures for constraint variables.
279 Indexed directly by variable info id. */
280 static VEC(varinfo_t,heap) *varmap;
282 /* Return the varmap element N */
284 static inline varinfo_t
285 get_varinfo (unsigned int n)
287 return VEC_index (varinfo_t, varmap, n);
290 /* Return the varmap element N, following the collapsed_to link. */
292 static inline varinfo_t
293 get_varinfo_fc (unsigned int n)
295 varinfo_t v = VEC_index (varinfo_t, varmap, n);
297 if (v->collapsed_to)
298 return v->collapsed_to;
299 return v;
302 /* Variable that represents the unknown pointer. */
303 static varinfo_t var_anything;
304 static tree anything_tree;
305 static unsigned int anything_id;
307 /* Variable that represents the NULL pointer. */
308 static varinfo_t var_nothing;
309 static tree nothing_tree;
310 static unsigned int nothing_id;
312 /* Variable that represents read only memory. */
313 static varinfo_t var_readonly;
314 static tree readonly_tree;
315 static unsigned int readonly_id;
317 /* Variable that represents integers. This is used for when people do things
318 like &0->a.b. */
319 static varinfo_t var_integer;
320 static tree integer_tree;
321 static unsigned int integer_id;
323 /* Lookup a heap var for FROM, and return it if we find one. */
325 static tree
326 heapvar_lookup (tree from)
328 struct tree_map *h, in;
329 in.base.from = from;
331 h = htab_find_with_hash (heapvar_for_stmt, &in, htab_hash_pointer (from));
332 if (h)
333 return h->to;
334 return NULL_TREE;
337 /* Insert a mapping FROM->TO in the heap var for statement
338 hashtable. */
340 static void
341 heapvar_insert (tree from, tree to)
343 struct tree_map *h;
344 void **loc;
346 h = ggc_alloc (sizeof (struct tree_map));
347 h->hash = htab_hash_pointer (from);
348 h->base.from = from;
349 h->to = to;
350 loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
351 *(struct tree_map **) loc = h;
354 /* Return a new variable info structure consisting for a variable
355 named NAME, and using constraint graph node NODE. */
357 static varinfo_t
358 new_var_info (tree t, unsigned int id, const char *name)
360 varinfo_t ret = pool_alloc (variable_info_pool);
362 ret->id = id;
363 ret->name = name;
364 ret->decl = t;
365 ret->directly_dereferenced = false;
366 ret->is_artificial_var = false;
367 ret->is_heap_var = false;
368 ret->is_special_var = false;
369 ret->is_unknown_size_var = false;
370 ret->has_union = false;
371 ret->solution = BITMAP_ALLOC (&pta_obstack);
372 ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
373 ret->next = NULL;
374 ret->collapsed_to = NULL;
375 return ret;
378 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
380 /* An expression that appears in a constraint. */
382 struct constraint_expr
384 /* Constraint type. */
385 constraint_expr_type type;
387 /* Variable we are referring to in the constraint. */
388 unsigned int var;
390 /* Offset, in bits, of this constraint from the beginning of
391 variables it ends up referring to.
393 IOW, in a deref constraint, we would deref, get the result set,
394 then add OFFSET to each member. */
395 unsigned HOST_WIDE_INT offset;
398 typedef struct constraint_expr ce_s;
399 DEF_VEC_O(ce_s);
400 DEF_VEC_ALLOC_O(ce_s, heap);
401 static void get_constraint_for (tree, VEC(ce_s, heap) **);
402 static void do_deref (VEC (ce_s, heap) **);
404 /* Our set constraints are made up of two constraint expressions, one
405 LHS, and one RHS.
407 As described in the introduction, our set constraints each represent an
408 operation between set valued variables.
410 struct constraint
412 struct constraint_expr lhs;
413 struct constraint_expr rhs;
416 /* List of constraints that we use to build the constraint graph from. */
418 static VEC(constraint_t,heap) *constraints;
419 static alloc_pool constraint_pool;
422 DEF_VEC_I(int);
423 DEF_VEC_ALLOC_I(int, heap);
425 /* The constraint graph is represented as an array of bitmaps
426 containing successor nodes. */
428 struct constraint_graph
430 /* Size of this graph, which may be different than the number of
431 nodes in the variable map. */
432 unsigned int size;
434 /* Explicit successors of each node. */
435 bitmap *succs;
437 /* Implicit predecessors of each node (Used for variable
438 substitution). */
439 bitmap *implicit_preds;
441 /* Explicit predecessors of each node (Used for variable substitution). */
442 bitmap *preds;
444 /* Indirect cycle representatives, or -1 if the node has no indirect
445 cycles. */
446 int *indirect_cycles;
448 /* Representative node for a node. rep[a] == a unless the node has
449 been unified. */
450 unsigned int *rep;
452 /* Equivalence class representative for a node. This is used for
453 variable substitution. */
454 int *eq_rep;
456 /* Label for each node, used during variable substitution. */
457 unsigned int *label;
459 /* Bitmap of nodes where the bit is set if the node is a direct
460 node. Used for variable substitution. */
461 sbitmap direct_nodes;
463 /* Vector of complex constraints for each graph node. Complex
464 constraints are those involving dereferences or offsets that are
465 not 0. */
466 VEC(constraint_t,heap) **complex;
469 static constraint_graph_t graph;
471 /* During variable substitution and the offline version of indirect
472 cycle finding, we create nodes to represent dereferences and
473 address taken constraints. These represent where these start and
474 end. */
475 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
476 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
477 #define FIRST_ADDR_NODE (LAST_REF_NODE + 1)
479 /* Return the representative node for NODE, if NODE has been unioned
480 with another NODE.
481 This function performs path compression along the way to finding
482 the representative. */
484 static unsigned int
485 find (unsigned int node)
487 gcc_assert (node < graph->size);
488 if (graph->rep[node] != node)
489 return graph->rep[node] = find (graph->rep[node]);
490 return node;
493 /* Union the TO and FROM nodes to the TO nodes.
494 Note that at some point in the future, we may want to do
495 union-by-rank, in which case we are going to have to return the
496 node we unified to. */
498 static bool
499 unite (unsigned int to, unsigned int from)
501 gcc_assert (to < graph->size && from < graph->size);
502 if (to != from && graph->rep[from] != to)
504 graph->rep[from] = to;
505 return true;
507 return false;
510 /* Create a new constraint consisting of LHS and RHS expressions. */
512 static constraint_t
513 new_constraint (const struct constraint_expr lhs,
514 const struct constraint_expr rhs)
516 constraint_t ret = pool_alloc (constraint_pool);
517 ret->lhs = lhs;
518 ret->rhs = rhs;
519 return ret;
522 /* Print out constraint C to FILE. */
524 void
525 dump_constraint (FILE *file, constraint_t c)
527 if (c->lhs.type == ADDRESSOF)
528 fprintf (file, "&");
529 else if (c->lhs.type == DEREF)
530 fprintf (file, "*");
531 fprintf (file, "%s", get_varinfo_fc (c->lhs.var)->name);
532 if (c->lhs.offset != 0)
533 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
534 fprintf (file, " = ");
535 if (c->rhs.type == ADDRESSOF)
536 fprintf (file, "&");
537 else if (c->rhs.type == DEREF)
538 fprintf (file, "*");
539 fprintf (file, "%s", get_varinfo_fc (c->rhs.var)->name);
540 if (c->rhs.offset != 0)
541 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
542 fprintf (file, "\n");
545 /* Print out constraint C to stderr. */
547 void
548 debug_constraint (constraint_t c)
550 dump_constraint (stderr, c);
553 /* Print out all constraints to FILE */
555 void
556 dump_constraints (FILE *file)
558 int i;
559 constraint_t c;
560 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
561 dump_constraint (file, c);
564 /* Print out all constraints to stderr. */
566 void
567 debug_constraints (void)
569 dump_constraints (stderr);
572 /* SOLVER FUNCTIONS
574 The solver is a simple worklist solver, that works on the following
575 algorithm:
577 sbitmap changed_nodes = all zeroes;
578 changed_count = 0;
579 For each node that is not already collapsed:
580 changed_count++;
581 set bit in changed nodes
583 while (changed_count > 0)
585 compute topological ordering for constraint graph
587 find and collapse cycles in the constraint graph (updating
588 changed if necessary)
590 for each node (n) in the graph in topological order:
591 changed_count--;
593 Process each complex constraint associated with the node,
594 updating changed if necessary.
596 For each outgoing edge from n, propagate the solution from n to
597 the destination of the edge, updating changed as necessary.
599 } */
601 /* Return true if two constraint expressions A and B are equal. */
603 static bool
604 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
606 return a.type == b.type && a.var == b.var && a.offset == b.offset;
609 /* Return true if constraint expression A is less than constraint expression
610 B. This is just arbitrary, but consistent, in order to give them an
611 ordering. */
613 static bool
614 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
616 if (a.type == b.type)
618 if (a.var == b.var)
619 return a.offset < b.offset;
620 else
621 return a.var < b.var;
623 else
624 return a.type < b.type;
627 /* Return true if constraint A is less than constraint B. This is just
628 arbitrary, but consistent, in order to give them an ordering. */
630 static bool
631 constraint_less (const constraint_t a, const constraint_t b)
633 if (constraint_expr_less (a->lhs, b->lhs))
634 return true;
635 else if (constraint_expr_less (b->lhs, a->lhs))
636 return false;
637 else
638 return constraint_expr_less (a->rhs, b->rhs);
641 /* Return true if two constraints A and B are equal. */
643 static bool
644 constraint_equal (struct constraint a, struct constraint b)
646 return constraint_expr_equal (a.lhs, b.lhs)
647 && constraint_expr_equal (a.rhs, b.rhs);
651 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
653 static constraint_t
654 constraint_vec_find (VEC(constraint_t,heap) *vec,
655 struct constraint lookfor)
657 unsigned int place;
658 constraint_t found;
660 if (vec == NULL)
661 return NULL;
663 place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
664 if (place >= VEC_length (constraint_t, vec))
665 return NULL;
666 found = VEC_index (constraint_t, vec, place);
667 if (!constraint_equal (*found, lookfor))
668 return NULL;
669 return found;
672 /* Union two constraint vectors, TO and FROM. Put the result in TO. */
674 static void
675 constraint_set_union (VEC(constraint_t,heap) **to,
676 VEC(constraint_t,heap) **from)
678 int i;
679 constraint_t c;
681 for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
683 if (constraint_vec_find (*to, *c) == NULL)
685 unsigned int place = VEC_lower_bound (constraint_t, *to, c,
686 constraint_less);
687 VEC_safe_insert (constraint_t, heap, *to, place, c);
692 /* Take a solution set SET, add OFFSET to each member of the set, and
693 overwrite SET with the result when done. */
695 static void
696 solution_set_add (bitmap set, unsigned HOST_WIDE_INT offset)
698 bitmap result = BITMAP_ALLOC (&iteration_obstack);
699 unsigned int i;
700 bitmap_iterator bi;
702 EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
704 /* If this is a properly sized variable, only add offset if it's
705 less than end. Otherwise, it is globbed to a single
706 variable. */
708 if ((get_varinfo (i)->offset + offset) < get_varinfo (i)->fullsize)
710 unsigned HOST_WIDE_INT fieldoffset = get_varinfo (i)->offset + offset;
711 varinfo_t v = first_vi_for_offset (get_varinfo (i), fieldoffset);
712 if (!v)
713 continue;
714 bitmap_set_bit (result, v->id);
716 else if (get_varinfo (i)->is_artificial_var
717 || get_varinfo (i)->has_union
718 || get_varinfo (i)->is_unknown_size_var)
720 bitmap_set_bit (result, i);
724 bitmap_copy (set, result);
725 BITMAP_FREE (result);
728 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
729 process. */
731 static bool
732 set_union_with_increment (bitmap to, bitmap from, unsigned HOST_WIDE_INT inc)
734 if (inc == 0)
735 return bitmap_ior_into (to, from);
736 else
738 bitmap tmp;
739 bool res;
741 tmp = BITMAP_ALLOC (&iteration_obstack);
742 bitmap_copy (tmp, from);
743 solution_set_add (tmp, inc);
744 res = bitmap_ior_into (to, tmp);
745 BITMAP_FREE (tmp);
746 return res;
750 /* Insert constraint C into the list of complex constraints for graph
751 node VAR. */
753 static void
754 insert_into_complex (constraint_graph_t graph,
755 unsigned int var, constraint_t c)
757 VEC (constraint_t, heap) *complex = graph->complex[var];
758 unsigned int place = VEC_lower_bound (constraint_t, complex, c,
759 constraint_less);
761 /* Only insert constraints that do not already exist. */
762 if (place >= VEC_length (constraint_t, complex)
763 || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
764 VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
768 /* Condense two variable nodes into a single variable node, by moving
769 all associated info from SRC to TO. */
771 static void
772 merge_node_constraints (constraint_graph_t graph, unsigned int to,
773 unsigned int from)
775 unsigned int i;
776 constraint_t c;
778 gcc_assert (find (from) == to);
780 /* Move all complex constraints from src node into to node */
781 for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
783 /* In complex constraints for node src, we may have either
784 a = *src, and *src = a, or an offseted constraint which are
785 always added to the rhs node's constraints. */
787 if (c->rhs.type == DEREF)
788 c->rhs.var = to;
789 else if (c->lhs.type == DEREF)
790 c->lhs.var = to;
791 else
792 c->rhs.var = to;
794 constraint_set_union (&graph->complex[to], &graph->complex[from]);
795 VEC_free (constraint_t, heap, graph->complex[from]);
796 graph->complex[from] = NULL;
800 /* Remove edges involving NODE from GRAPH. */
802 static void
803 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
805 if (graph->succs[node])
806 BITMAP_FREE (graph->succs[node]);
809 /* Merge GRAPH nodes FROM and TO into node TO. */
811 static void
812 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
813 unsigned int from)
815 if (graph->indirect_cycles[from] != -1)
817 /* If we have indirect cycles with the from node, and we have
818 none on the to node, the to node has indirect cycles from the
819 from node now that they are unified.
820 If indirect cycles exist on both, unify the nodes that they
821 are in a cycle with, since we know they are in a cycle with
822 each other. */
823 if (graph->indirect_cycles[to] == -1)
825 graph->indirect_cycles[to] = graph->indirect_cycles[from];
827 else
829 unsigned int tonode = find (graph->indirect_cycles[to]);
830 unsigned int fromnode = find (graph->indirect_cycles[from]);
832 if (unite (tonode, fromnode))
833 unify_nodes (graph, tonode, fromnode, true);
837 /* Merge all the successor edges. */
838 if (graph->succs[from])
840 if (!graph->succs[to])
841 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
842 bitmap_ior_into (graph->succs[to],
843 graph->succs[from]);
846 clear_edges_for_node (graph, from);
850 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
851 it doesn't exist in the graph already. */
853 static void
854 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
855 unsigned int from)
857 if (to == from)
858 return;
860 if (!graph->implicit_preds[to])
861 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
863 if (!bitmap_bit_p (graph->implicit_preds[to], from))
865 stats.num_implicit_edges++;
866 bitmap_set_bit (graph->implicit_preds[to], from);
870 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
871 it doesn't exist in the graph already.
872 Return false if the edge already existed, true otherwise. */
874 static void
875 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
876 unsigned int from)
878 if (!graph->preds[to])
879 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
880 if (!bitmap_bit_p (graph->preds[to], from))
881 bitmap_set_bit (graph->preds[to], from);
884 /* Add a graph edge to GRAPH, going from FROM to TO if
885 it doesn't exist in the graph already.
886 Return false if the edge already existed, true otherwise. */
888 static bool
889 add_graph_edge (constraint_graph_t graph, unsigned int to,
890 unsigned int from)
892 if (to == from)
894 return false;
896 else
898 bool r = false;
900 if (!graph->succs[from])
901 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
902 if (!bitmap_bit_p (graph->succs[from], to))
904 r = true;
905 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
906 stats.num_edges++;
907 bitmap_set_bit (graph->succs[from], to);
909 return r;
914 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH. */
916 static bool
917 valid_graph_edge (constraint_graph_t graph, unsigned int src,
918 unsigned int dest)
920 return (graph->succs[dest]
921 && bitmap_bit_p (graph->succs[dest], src));
924 /* Build the constraint graph, adding only predecessor edges right now. */
926 static void
927 build_pred_graph (void)
929 int i;
930 constraint_t c;
931 unsigned int j;
933 graph = XNEW (struct constraint_graph);
934 graph->size = (VEC_length (varinfo_t, varmap)) * 3;
935 graph->succs = XCNEWVEC (bitmap, graph->size);
936 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
937 graph->preds = XCNEWVEC (bitmap, graph->size);
938 graph->indirect_cycles = XNEWVEC (int, VEC_length (varinfo_t, varmap));
939 graph->label = XCNEWVEC (unsigned int, graph->size);
940 graph->rep = XNEWVEC (unsigned int, graph->size);
941 graph->eq_rep = XNEWVEC (int, graph->size);
942 graph->complex = XCNEWVEC (VEC(constraint_t, heap) *,
943 VEC_length (varinfo_t, varmap));
944 graph->direct_nodes = sbitmap_alloc (graph->size);
945 sbitmap_zero (graph->direct_nodes);
947 for (j = 0; j < FIRST_REF_NODE; j++)
949 if (!get_varinfo (j)->is_special_var)
950 SET_BIT (graph->direct_nodes, j);
953 for (j = 0; j < graph->size; j++)
955 graph->rep[j] = j;
956 graph->eq_rep[j] = -1;
959 for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
960 graph->indirect_cycles[j] = -1;
962 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
964 struct constraint_expr lhs = c->lhs;
965 struct constraint_expr rhs = c->rhs;
966 unsigned int lhsvar = get_varinfo_fc (lhs.var)->id;
967 unsigned int rhsvar = get_varinfo_fc (rhs.var)->id;
969 if (lhs.type == DEREF)
971 /* *x = y. */
972 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
973 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
974 if (rhs.type == ADDRESSOF)
975 RESET_BIT (graph->direct_nodes, rhsvar);
977 else if (rhs.type == DEREF)
979 /* x = *y */
980 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
981 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
982 else
983 RESET_BIT (graph->direct_nodes, lhsvar);
985 else if (rhs.type == ADDRESSOF)
987 /* x = &y */
988 add_pred_graph_edge (graph, lhsvar, FIRST_ADDR_NODE + rhsvar);
989 /* Implicitly, *x = y */
990 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
992 RESET_BIT (graph->direct_nodes, rhsvar);
994 else if (lhsvar > anything_id
995 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
997 /* x = y */
998 add_pred_graph_edge (graph, lhsvar, rhsvar);
999 /* Implicitly, *x = *y */
1000 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1001 FIRST_REF_NODE + rhsvar);
1003 else if (lhs.offset != 0 || rhs.offset != 0)
1005 if (rhs.offset != 0)
1006 RESET_BIT (graph->direct_nodes, lhs.var);
1007 if (lhs.offset != 0)
1008 RESET_BIT (graph->direct_nodes, rhs.var);
1013 /* Build the constraint graph, adding successor edges. */
1015 static void
1016 build_succ_graph (void)
1018 int i;
1019 constraint_t c;
1021 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1023 struct constraint_expr lhs;
1024 struct constraint_expr rhs;
1025 unsigned int lhsvar;
1026 unsigned int rhsvar;
1028 if (!c)
1029 continue;
1031 lhs = c->lhs;
1032 rhs = c->rhs;
1033 lhsvar = find (get_varinfo_fc (lhs.var)->id);
1034 rhsvar = find (get_varinfo_fc (rhs.var)->id);
1036 if (lhs.type == DEREF)
1038 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1039 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1041 else if (rhs.type == DEREF)
1043 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1044 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1046 else if (rhs.type == ADDRESSOF)
1048 /* x = &y */
1049 gcc_assert (find (get_varinfo_fc (rhs.var)->id)
1050 == get_varinfo_fc (rhs.var)->id);
1051 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1053 else if (lhsvar > anything_id
1054 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1056 add_graph_edge (graph, lhsvar, rhsvar);
1062 /* Changed variables on the last iteration. */
1063 static unsigned int changed_count;
1064 static sbitmap changed;
1066 DEF_VEC_I(unsigned);
1067 DEF_VEC_ALLOC_I(unsigned,heap);
1070 /* Strongly Connected Component visitation info. */
1072 struct scc_info
1074 sbitmap visited;
1075 sbitmap roots;
1076 unsigned int *dfs;
1077 unsigned int *node_mapping;
1078 int current_index;
1079 VEC(unsigned,heap) *scc_stack;
1083 /* Recursive routine to find strongly connected components in GRAPH.
1084 SI is the SCC info to store the information in, and N is the id of current
1085 graph node we are processing.
1087 This is Tarjan's strongly connected component finding algorithm, as
1088 modified by Nuutila to keep only non-root nodes on the stack.
1089 The algorithm can be found in "On finding the strongly connected
1090 connected components in a directed graph" by Esko Nuutila and Eljas
1091 Soisalon-Soininen, in Information Processing Letters volume 49,
1092 number 1, pages 9-14. */
1094 static void
1095 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1097 unsigned int i;
1098 bitmap_iterator bi;
1099 unsigned int my_dfs;
1101 SET_BIT (si->visited, n);
1102 si->dfs[n] = si->current_index ++;
1103 my_dfs = si->dfs[n];
1105 /* Visit all the successors. */
1106 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1108 unsigned int w;
1110 if (i > LAST_REF_NODE)
1111 break;
1113 w = find (i);
1114 if (TEST_BIT (si->roots, w))
1115 continue;
1117 if (!TEST_BIT (si->visited, w))
1118 scc_visit (graph, si, w);
1120 unsigned int t = find (w);
1121 unsigned int nnode = find (n);
1122 gcc_assert (nnode == n);
1124 if (si->dfs[t] < si->dfs[nnode])
1125 si->dfs[n] = si->dfs[t];
1129 /* See if any components have been identified. */
1130 if (si->dfs[n] == my_dfs)
1132 if (VEC_length (unsigned, si->scc_stack) > 0
1133 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1135 bitmap scc = BITMAP_ALLOC (NULL);
1136 bool have_ref_node = n >= FIRST_REF_NODE;
1137 unsigned int lowest_node;
1138 bitmap_iterator bi;
1140 bitmap_set_bit (scc, n);
1142 while (VEC_length (unsigned, si->scc_stack) != 0
1143 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1145 unsigned int w = VEC_pop (unsigned, si->scc_stack);
1147 bitmap_set_bit (scc, w);
1148 if (w >= FIRST_REF_NODE)
1149 have_ref_node = true;
1152 lowest_node = bitmap_first_set_bit (scc);
1153 gcc_assert (lowest_node < FIRST_REF_NODE);
1154 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1156 if (i < FIRST_REF_NODE)
1158 /* Mark this node for collapsing. */
1159 if (unite (lowest_node, i))
1160 unify_nodes (graph, lowest_node, i, false);
1162 else
1164 unite (lowest_node, i);
1165 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1169 SET_BIT (si->roots, n);
1171 else
1172 VEC_safe_push (unsigned, heap, si->scc_stack, n);
1175 /* Unify node FROM into node TO, updating the changed count if
1176 necessary when UPDATE_CHANGED is true. */
1178 static void
1179 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1180 bool update_changed)
1183 gcc_assert (to != from && find (to) == to);
1184 if (dump_file && (dump_flags & TDF_DETAILS))
1185 fprintf (dump_file, "Unifying %s to %s\n",
1186 get_varinfo (from)->name,
1187 get_varinfo (to)->name);
1189 if (update_changed)
1190 stats.unified_vars_dynamic++;
1191 else
1192 stats.unified_vars_static++;
1194 merge_graph_nodes (graph, to, from);
1195 merge_node_constraints (graph, to, from);
1197 if (update_changed && TEST_BIT (changed, from))
1199 RESET_BIT (changed, from);
1200 if (!TEST_BIT (changed, to))
1201 SET_BIT (changed, to);
1202 else
1204 gcc_assert (changed_count > 0);
1205 changed_count--;
1209 /* If the solution changes because of the merging, we need to mark
1210 the variable as changed. */
1211 if (bitmap_ior_into (get_varinfo (to)->solution,
1212 get_varinfo (from)->solution))
1214 if (update_changed && !TEST_BIT (changed, to))
1216 SET_BIT (changed, to);
1217 changed_count++;
1221 BITMAP_FREE (get_varinfo (from)->solution);
1222 BITMAP_FREE (get_varinfo (from)->oldsolution);
1224 if (stats.iterations > 0)
1226 BITMAP_FREE (get_varinfo (to)->oldsolution);
1227 get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1230 if (valid_graph_edge (graph, to, to))
1232 if (graph->succs[to])
1233 bitmap_clear_bit (graph->succs[to], to);
1237 /* Information needed to compute the topological ordering of a graph. */
1239 struct topo_info
1241 /* sbitmap of visited nodes. */
1242 sbitmap visited;
1243 /* Array that stores the topological order of the graph, *in
1244 reverse*. */
1245 VEC(unsigned,heap) *topo_order;
1249 /* Initialize and return a topological info structure. */
1251 static struct topo_info *
1252 init_topo_info (void)
1254 size_t size = VEC_length (varinfo_t, varmap);
1255 struct topo_info *ti = XNEW (struct topo_info);
1256 ti->visited = sbitmap_alloc (size);
1257 sbitmap_zero (ti->visited);
1258 ti->topo_order = VEC_alloc (unsigned, heap, 1);
1259 return ti;
1263 /* Free the topological sort info pointed to by TI. */
1265 static void
1266 free_topo_info (struct topo_info *ti)
1268 sbitmap_free (ti->visited);
1269 VEC_free (unsigned, heap, ti->topo_order);
1270 free (ti);
1273 /* Visit the graph in topological order, and store the order in the
1274 topo_info structure. */
1276 static void
1277 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1278 unsigned int n)
1280 bitmap_iterator bi;
1281 unsigned int j;
1283 SET_BIT (ti->visited, n);
1285 if (graph->succs[n])
1286 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1288 if (!TEST_BIT (ti->visited, j))
1289 topo_visit (graph, ti, j);
1292 VEC_safe_push (unsigned, heap, ti->topo_order, n);
1295 /* Return true if variable N + OFFSET is a legal field of N. */
1297 static bool
1298 type_safe (unsigned int n, unsigned HOST_WIDE_INT *offset)
1300 varinfo_t ninfo = get_varinfo (n);
1302 /* For things we've globbed to single variables, any offset into the
1303 variable acts like the entire variable, so that it becomes offset
1304 0. */
1305 if (ninfo->is_special_var
1306 || ninfo->is_artificial_var
1307 || ninfo->is_unknown_size_var)
1309 *offset = 0;
1310 return true;
1312 return (get_varinfo (n)->offset + *offset) < get_varinfo (n)->fullsize;
1315 /* Process a constraint C that represents *x = &y. */
1317 static void
1318 do_da_constraint (constraint_graph_t graph ATTRIBUTE_UNUSED,
1319 constraint_t c, bitmap delta)
1321 unsigned int rhs = c->rhs.var;
1322 unsigned int j;
1323 bitmap_iterator bi;
1325 /* For each member j of Delta (Sol(x)), add x to Sol(j) */
1326 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1328 unsigned HOST_WIDE_INT offset = c->lhs.offset;
1329 if (type_safe (j, &offset) && !(get_varinfo (j)->is_special_var))
1331 /* *x != NULL && *x != ANYTHING*/
1332 varinfo_t v;
1333 unsigned int t;
1334 bitmap sol;
1335 unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + offset;
1337 v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1338 if (!v)
1339 continue;
1340 t = find (v->id);
1341 sol = get_varinfo (t)->solution;
1342 if (!bitmap_bit_p (sol, rhs))
1344 bitmap_set_bit (sol, rhs);
1345 if (!TEST_BIT (changed, t))
1347 SET_BIT (changed, t);
1348 changed_count++;
1352 else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1353 fprintf (dump_file, "Untypesafe usage in do_da_constraint.\n");
1358 /* Process a constraint C that represents x = *y, using DELTA as the
1359 starting solution. */
1361 static void
1362 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1363 bitmap delta)
1365 unsigned int lhs = find (c->lhs.var);
1366 bool flag = false;
1367 bitmap sol = get_varinfo (lhs)->solution;
1368 unsigned int j;
1369 bitmap_iterator bi;
1371 if (bitmap_bit_p (delta, anything_id))
1373 flag = !bitmap_bit_p (sol, anything_id);
1374 if (flag)
1375 bitmap_set_bit (sol, anything_id);
1376 goto done;
1378 /* For each variable j in delta (Sol(y)), add
1379 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1380 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1382 unsigned HOST_WIDE_INT roffset = c->rhs.offset;
1383 if (type_safe (j, &roffset))
1385 varinfo_t v;
1386 unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + roffset;
1387 unsigned int t;
1389 v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1390 if (!v)
1391 continue;
1392 t = find (v->id);
1394 /* Adding edges from the special vars is pointless.
1395 They don't have sets that can change. */
1396 if (get_varinfo (t) ->is_special_var)
1397 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1398 else if (add_graph_edge (graph, lhs, t))
1399 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1401 else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1402 fprintf (dump_file, "Untypesafe usage in do_sd_constraint\n");
1406 done:
1407 /* If the LHS solution changed, mark the var as changed. */
1408 if (flag)
1410 get_varinfo (lhs)->solution = sol;
1411 if (!TEST_BIT (changed, lhs))
1413 SET_BIT (changed, lhs);
1414 changed_count++;
1419 /* Process a constraint C that represents *x = y. */
1421 static void
1422 do_ds_constraint (constraint_t c, bitmap delta)
1424 unsigned int rhs = find (c->rhs.var);
1425 unsigned HOST_WIDE_INT roff = c->rhs.offset;
1426 bitmap sol = get_varinfo (rhs)->solution;
1427 unsigned int j;
1428 bitmap_iterator bi;
1430 if (bitmap_bit_p (sol, anything_id))
1432 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1434 varinfo_t jvi = get_varinfo (j);
1435 unsigned int t;
1436 unsigned int loff = c->lhs.offset;
1437 unsigned HOST_WIDE_INT fieldoffset = jvi->offset + loff;
1438 varinfo_t v;
1440 v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1441 if (!v)
1442 continue;
1443 t = find (v->id);
1445 if (!bitmap_bit_p (get_varinfo (t)->solution, anything_id))
1447 bitmap_set_bit (get_varinfo (t)->solution, anything_id);
1448 if (!TEST_BIT (changed, t))
1450 SET_BIT (changed, t);
1451 changed_count++;
1455 return;
1458 /* For each member j of delta (Sol(x)), add an edge from y to j and
1459 union Sol(y) into Sol(j) */
1460 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1462 unsigned HOST_WIDE_INT loff = c->lhs.offset;
1463 if (type_safe (j, &loff) && !(get_varinfo (j)->is_special_var))
1465 varinfo_t v;
1466 unsigned int t;
1467 unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + loff;
1468 bitmap tmp;
1470 v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1471 if (!v)
1472 continue;
1473 t = find (v->id);
1474 tmp = get_varinfo (t)->solution;
1476 if (set_union_with_increment (tmp, sol, roff))
1478 get_varinfo (t)->solution = tmp;
1479 if (t == rhs)
1480 sol = get_varinfo (rhs)->solution;
1481 if (!TEST_BIT (changed, t))
1483 SET_BIT (changed, t);
1484 changed_count++;
1488 else if (0 && dump_file && !(get_varinfo (j)->is_special_var))
1489 fprintf (dump_file, "Untypesafe usage in do_ds_constraint\n");
1493 /* Handle a non-simple (simple meaning requires no iteration),
1494 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1496 static void
1497 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1499 if (c->lhs.type == DEREF)
1501 if (c->rhs.type == ADDRESSOF)
1503 /* *x = &y */
1504 do_da_constraint (graph, c, delta);
1506 else
1508 /* *x = y */
1509 do_ds_constraint (c, delta);
1512 else if (c->rhs.type == DEREF)
1514 /* x = *y */
1515 if (!(get_varinfo (c->lhs.var)->is_special_var))
1516 do_sd_constraint (graph, c, delta);
1518 else
1520 bitmap tmp;
1521 bitmap solution;
1522 bool flag = false;
1523 unsigned int t;
1525 gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1526 t = find (c->rhs.var);
1527 solution = get_varinfo (t)->solution;
1528 t = find (c->lhs.var);
1529 tmp = get_varinfo (t)->solution;
1531 flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1533 if (flag)
1535 get_varinfo (t)->solution = tmp;
1536 if (!TEST_BIT (changed, t))
1538 SET_BIT (changed, t);
1539 changed_count++;
1545 /* Initialize and return a new SCC info structure. */
1547 static struct scc_info *
1548 init_scc_info (size_t size)
1550 struct scc_info *si = XNEW (struct scc_info);
1551 size_t i;
1553 si->current_index = 0;
1554 si->visited = sbitmap_alloc (size);
1555 sbitmap_zero (si->visited);
1556 si->roots = sbitmap_alloc (size);
1557 sbitmap_zero (si->roots);
1558 si->node_mapping = XNEWVEC (unsigned int, size);
1559 si->dfs = XCNEWVEC (unsigned int, size);
1561 for (i = 0; i < size; i++)
1562 si->node_mapping[i] = i;
1564 si->scc_stack = VEC_alloc (unsigned, heap, 1);
1565 return si;
1568 /* Free an SCC info structure pointed to by SI */
1570 static void
1571 free_scc_info (struct scc_info *si)
1573 sbitmap_free (si->visited);
1574 sbitmap_free (si->roots);
1575 free (si->node_mapping);
1576 free (si->dfs);
1577 VEC_free (unsigned, heap, si->scc_stack);
1578 free (si);
1582 /* Find indirect cycles in GRAPH that occur, using strongly connected
1583 components, and note them in the indirect cycles map.
1585 This technique comes from Ben Hardekopf and Calvin Lin,
1586 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1587 Lines of Code", submitted to PLDI 2007. */
1589 static void
1590 find_indirect_cycles (constraint_graph_t graph)
1592 unsigned int i;
1593 unsigned int size = graph->size;
1594 struct scc_info *si = init_scc_info (size);
1596 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1597 if (!TEST_BIT (si->visited, i) && find (i) == i)
1598 scc_visit (graph, si, i);
1600 free_scc_info (si);
1603 /* Compute a topological ordering for GRAPH, and store the result in the
1604 topo_info structure TI. */
1606 static void
1607 compute_topo_order (constraint_graph_t graph,
1608 struct topo_info *ti)
1610 unsigned int i;
1611 unsigned int size = VEC_length (varinfo_t, varmap);
1613 for (i = 0; i != size; ++i)
1614 if (!TEST_BIT (ti->visited, i) && find (i) == i)
1615 topo_visit (graph, ti, i);
1618 /* Perform offline variable substitution.
1620 This is a linear time way of identifying variables that must have
1621 equivalent points-to sets, including those caused by static cycles,
1622 and single entry subgraphs, in the constraint graph.
1624 The technique is described in "Off-line variable substitution for
1625 scaling points-to analysis" by Atanas Rountev and Satish Chandra,
1626 in "ACM SIGPLAN Notices" volume 35, number 5, pages 47-56.
1628 There is an optimal way to do this involving hash based value
1629 numbering, once the technique is published i will implement it
1630 here.
1632 The general method of finding equivalence classes is as follows:
1633 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1634 Add fake nodes (ADDRESS nodes) and edges for a = &b constraints.
1635 Initialize all non-REF/ADDRESS nodes to be direct nodes
1636 For each SCC in the predecessor graph:
1637 for each member (x) of the SCC
1638 if x is not a direct node:
1639 set rootnode(SCC) to be not a direct node
1640 collapse node x into rootnode(SCC).
1641 if rootnode(SCC) is not a direct node:
1642 label rootnode(SCC) with a new equivalence class
1643 else:
1644 if all labeled predecessors of rootnode(SCC) have the same
1645 label:
1646 label rootnode(SCC) with this label
1647 else:
1648 label rootnode(SCC) with a new equivalence class
1650 All direct nodes with the same equivalence class can be replaced
1651 with a single representative node.
1652 All unlabeled nodes (label == 0) are not pointers and all edges
1653 involving them can be eliminated.
1654 We perform these optimizations during move_complex_constraints.
1657 static int equivalence_class;
1659 /* Recursive routine to find strongly connected components in GRAPH,
1660 and label it's nodes with equivalence classes.
1661 This is used during variable substitution to find cycles involving
1662 the regular or implicit predecessors, and label them as equivalent.
1663 The SCC finding algorithm used is the same as that for scc_visit. */
1665 static void
1666 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1668 unsigned int i;
1669 bitmap_iterator bi;
1670 unsigned int my_dfs;
1672 gcc_assert (si->node_mapping[n] == n);
1673 SET_BIT (si->visited, n);
1674 si->dfs[n] = si->current_index ++;
1675 my_dfs = si->dfs[n];
1677 /* Visit all the successors. */
1678 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1680 unsigned int w = si->node_mapping[i];
1682 if (TEST_BIT (si->roots, w))
1683 continue;
1685 if (!TEST_BIT (si->visited, w))
1686 label_visit (graph, si, w);
1688 unsigned int t = si->node_mapping[w];
1689 unsigned int nnode = si->node_mapping[n];
1690 gcc_assert (nnode == n);
1692 if (si->dfs[t] < si->dfs[nnode])
1693 si->dfs[n] = si->dfs[t];
1697 /* Visit all the implicit predecessors. */
1698 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
1700 unsigned int w = si->node_mapping[i];
1702 if (TEST_BIT (si->roots, w))
1703 continue;
1705 if (!TEST_BIT (si->visited, w))
1706 label_visit (graph, si, w);
1708 unsigned int t = si->node_mapping[w];
1709 unsigned int nnode = si->node_mapping[n];
1710 gcc_assert (nnode == n);
1712 if (si->dfs[t] < si->dfs[nnode])
1713 si->dfs[n] = si->dfs[t];
1717 /* See if any components have been identified. */
1718 if (si->dfs[n] == my_dfs)
1720 while (VEC_length (unsigned, si->scc_stack) != 0
1721 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1723 unsigned int w = VEC_pop (unsigned, si->scc_stack);
1724 si->node_mapping[w] = n;
1726 if (!TEST_BIT (graph->direct_nodes, w))
1727 RESET_BIT (graph->direct_nodes, n);
1729 SET_BIT (si->roots, n);
1731 if (!TEST_BIT (graph->direct_nodes, n))
1733 graph->label[n] = equivalence_class++;
1735 else
1737 unsigned int size = 0;
1738 unsigned int firstlabel = ~0;
1740 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1742 unsigned int j = si->node_mapping[i];
1744 if (j == n || graph->label[j] == 0)
1745 continue;
1747 if (firstlabel == (unsigned int)~0)
1749 firstlabel = graph->label[j];
1750 size++;
1752 else if (graph->label[j] != firstlabel)
1753 size++;
1756 if (size == 0)
1757 graph->label[n] = 0;
1758 else if (size == 1)
1759 graph->label[n] = firstlabel;
1760 else
1761 graph->label[n] = equivalence_class++;
1764 else
1765 VEC_safe_push (unsigned, heap, si->scc_stack, n);
1768 /* Perform offline variable substitution, discovering equivalence
1769 classes, and eliminating non-pointer variables. */
1771 static struct scc_info *
1772 perform_var_substitution (constraint_graph_t graph)
1774 unsigned int i;
1775 unsigned int size = graph->size;
1776 struct scc_info *si = init_scc_info (size);
1778 bitmap_obstack_initialize (&iteration_obstack);
1779 equivalence_class = 0;
1781 /* We only need to visit the non-address nodes for labeling
1782 purposes, as the address nodes will never have any predecessors,
1783 because &x never appears on the LHS of a constraint. */
1784 for (i = 0; i < LAST_REF_NODE; i++)
1785 if (!TEST_BIT (si->visited, si->node_mapping[i]))
1786 label_visit (graph, si, si->node_mapping[i]);
1788 if (dump_file && (dump_flags & TDF_DETAILS))
1789 for (i = 0; i < FIRST_REF_NODE; i++)
1791 bool direct_node = TEST_BIT (graph->direct_nodes, i);
1792 fprintf (dump_file,
1793 "Equivalence class for %s node id %d:%s is %d\n",
1794 direct_node ? "Direct node" : "Indirect node", i,
1795 get_varinfo (i)->name,
1796 graph->label[si->node_mapping[i]]);
1799 /* Quickly eliminate our non-pointer variables. */
1801 for (i = 0; i < FIRST_REF_NODE; i++)
1803 unsigned int node = si->node_mapping[i];
1805 if (graph->label[node] == 0 && TEST_BIT (graph->direct_nodes, node))
1807 if (dump_file && (dump_flags & TDF_DETAILS))
1808 fprintf (dump_file,
1809 "%s is a non-pointer variable, eliminating edges.\n",
1810 get_varinfo (node)->name);
1811 stats.nonpointer_vars++;
1812 clear_edges_for_node (graph, node);
1815 return si;
1818 /* Free information that was only necessary for variable
1819 substitution. */
1821 static void
1822 free_var_substitution_info (struct scc_info *si)
1824 free_scc_info (si);
1825 free (graph->label);
1826 free (graph->eq_rep);
1827 sbitmap_free (graph->direct_nodes);
1828 bitmap_obstack_release (&iteration_obstack);
1831 /* Return an existing node that is equivalent to NODE, which has
1832 equivalence class LABEL, if one exists. Return NODE otherwise. */
1834 static unsigned int
1835 find_equivalent_node (constraint_graph_t graph,
1836 unsigned int node, unsigned int label)
1838 /* If the address version of this variable is unused, we can
1839 substitute it for anything else with the same label.
1840 Otherwise, we know the pointers are equivalent, but not the
1841 locations. */
1843 if (graph->label[FIRST_ADDR_NODE + node] == 0)
1845 gcc_assert (label < graph->size);
1847 if (graph->eq_rep[label] != -1)
1849 /* Unify the two variables since we know they are equivalent. */
1850 if (unite (graph->eq_rep[label], node))
1851 unify_nodes (graph, graph->eq_rep[label], node, false);
1852 return graph->eq_rep[label];
1854 else
1856 graph->eq_rep[label] = node;
1859 return node;
1862 /* Move complex constraints to the appropriate nodes, and collapse
1863 variables we've discovered are equivalent during variable
1864 substitution. SI is the SCC_INFO that is the result of
1865 perform_variable_substitution. */
1867 static void
1868 move_complex_constraints (constraint_graph_t graph,
1869 struct scc_info *si)
1871 int i;
1872 unsigned int j;
1873 constraint_t c;
1875 for (j = 0; j < graph->size; j++)
1876 gcc_assert (find (j) == j);
1878 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1880 struct constraint_expr lhs = c->lhs;
1881 struct constraint_expr rhs = c->rhs;
1882 unsigned int lhsvar = find (get_varinfo_fc (lhs.var)->id);
1883 unsigned int rhsvar = find (get_varinfo_fc (rhs.var)->id);
1884 unsigned int lhsnode, rhsnode;
1885 unsigned int lhslabel, rhslabel;
1887 lhsnode = si->node_mapping[lhsvar];
1888 rhsnode = si->node_mapping[rhsvar];
1889 lhslabel = graph->label[lhsnode];
1890 rhslabel = graph->label[rhsnode];
1892 /* See if it is really a non-pointer variable, and if so, ignore
1893 the constraint. */
1894 if (lhslabel == 0)
1896 if (!TEST_BIT (graph->direct_nodes, lhsnode))
1897 lhslabel = graph->label[lhsnode] = equivalence_class++;
1898 else
1900 if (dump_file && (dump_flags & TDF_DETAILS))
1903 fprintf (dump_file, "%s is a non-pointer variable,"
1904 "ignoring constraint:",
1905 get_varinfo (lhs.var)->name);
1906 dump_constraint (dump_file, c);
1908 VEC_replace (constraint_t, constraints, i, NULL);
1909 continue;
1913 if (rhslabel == 0)
1915 if (!TEST_BIT (graph->direct_nodes, rhsnode))
1916 rhslabel = graph->label[rhsnode] = equivalence_class++;
1917 else
1919 if (dump_file && (dump_flags & TDF_DETAILS))
1922 fprintf (dump_file, "%s is a non-pointer variable,"
1923 "ignoring constraint:",
1924 get_varinfo (rhs.var)->name);
1925 dump_constraint (dump_file, c);
1927 VEC_replace (constraint_t, constraints, i, NULL);
1928 continue;
1932 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
1933 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
1934 c->lhs.var = lhsvar;
1935 c->rhs.var = rhsvar;
1937 if (lhs.type == DEREF)
1939 if (rhs.type == ADDRESSOF || rhsvar > anything_id)
1940 insert_into_complex (graph, lhsvar, c);
1942 else if (rhs.type == DEREF)
1944 if (!(get_varinfo (lhsvar)->is_special_var))
1945 insert_into_complex (graph, rhsvar, c);
1947 else if (rhs.type != ADDRESSOF && lhsvar > anything_id
1948 && (lhs.offset != 0 || rhs.offset != 0))
1950 insert_into_complex (graph, rhsvar, c);
1956 /* Eliminate indirect cycles involving NODE. Return true if NODE was
1957 part of an SCC, false otherwise. */
1959 static bool
1960 eliminate_indirect_cycles (unsigned int node)
1962 if (graph->indirect_cycles[node] != -1
1963 && !bitmap_empty_p (get_varinfo (node)->solution))
1965 unsigned int i;
1966 VEC(unsigned,heap) *queue = NULL;
1967 int queuepos;
1968 unsigned int to = find (graph->indirect_cycles[node]);
1969 bitmap_iterator bi;
1971 /* We can't touch the solution set and call unify_nodes
1972 at the same time, because unify_nodes is going to do
1973 bitmap unions into it. */
1975 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
1977 if (find (i) == i && i != to)
1979 if (unite (to, i))
1980 VEC_safe_push (unsigned, heap, queue, i);
1984 for (queuepos = 0;
1985 VEC_iterate (unsigned, queue, queuepos, i);
1986 queuepos++)
1988 unify_nodes (graph, to, i, true);
1990 VEC_free (unsigned, heap, queue);
1991 return true;
1993 return false;
1996 /* Solve the constraint graph GRAPH using our worklist solver.
1997 This is based on the PW* family of solvers from the "Efficient Field
1998 Sensitive Pointer Analysis for C" paper.
1999 It works by iterating over all the graph nodes, processing the complex
2000 constraints and propagating the copy constraints, until everything stops
2001 changed. This corresponds to steps 6-8 in the solving list given above. */
2003 static void
2004 solve_graph (constraint_graph_t graph)
2006 unsigned int size = VEC_length (varinfo_t, varmap);
2007 unsigned int i;
2008 bitmap pts;
2010 changed_count = 0;
2011 changed = sbitmap_alloc (size);
2012 sbitmap_zero (changed);
2014 /* Mark all initial non-collapsed nodes as changed. */
2015 for (i = 0; i < size; i++)
2017 varinfo_t ivi = get_varinfo (i);
2018 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2019 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2020 || VEC_length (constraint_t, graph->complex[i]) > 0))
2022 SET_BIT (changed, i);
2023 changed_count++;
2027 /* Allocate a bitmap to be used to store the changed bits. */
2028 pts = BITMAP_ALLOC (&pta_obstack);
2030 while (changed_count > 0)
2032 unsigned int i;
2033 struct topo_info *ti = init_topo_info ();
2034 stats.iterations++;
2036 bitmap_obstack_initialize (&iteration_obstack);
2038 compute_topo_order (graph, ti);
2040 while (VEC_length (unsigned, ti->topo_order) != 0)
2043 i = VEC_pop (unsigned, ti->topo_order);
2045 /* If this variable is not a representative, skip it. */
2046 if (find (i) != i)
2047 continue;
2049 /* In certain indirect cycle cases, we may merge this
2050 variable to another. */
2051 if (eliminate_indirect_cycles (i) && find (i) != i)
2052 continue;
2054 /* If the node has changed, we need to process the
2055 complex constraints and outgoing edges again. */
2056 if (TEST_BIT (changed, i))
2058 unsigned int j;
2059 constraint_t c;
2060 bitmap solution;
2061 VEC(constraint_t,heap) *complex = graph->complex[i];
2062 bool solution_empty;
2064 RESET_BIT (changed, i);
2065 changed_count--;
2067 /* Compute the changed set of solution bits. */
2068 bitmap_and_compl (pts, get_varinfo (i)->solution,
2069 get_varinfo (i)->oldsolution);
2071 if (bitmap_empty_p (pts))
2072 continue;
2074 bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2076 solution = get_varinfo (i)->solution;
2077 solution_empty = bitmap_empty_p (solution);
2079 /* Process the complex constraints */
2080 for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2082 /* The only complex constraint that can change our
2083 solution to non-empty, given an empty solution,
2084 is a constraint where the lhs side is receiving
2085 some set from elsewhere. */
2086 if (!solution_empty || c->lhs.type != DEREF)
2087 do_complex_constraint (graph, c, pts);
2090 solution_empty = bitmap_empty_p (solution);
2092 if (!solution_empty)
2094 bitmap_iterator bi;
2096 /* Propagate solution to all successors. */
2097 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2098 0, j, bi)
2100 bitmap tmp;
2101 bool flag;
2103 unsigned int to = find (j);
2104 tmp = get_varinfo (to)->solution;
2105 flag = false;
2107 /* Don't try to propagate to ourselves. */
2108 if (to == i)
2109 continue;
2111 flag = set_union_with_increment (tmp, pts, 0);
2113 if (flag)
2115 get_varinfo (to)->solution = tmp;
2116 if (!TEST_BIT (changed, to))
2118 SET_BIT (changed, to);
2119 changed_count++;
2126 free_topo_info (ti);
2127 bitmap_obstack_release (&iteration_obstack);
2130 BITMAP_FREE (pts);
2131 sbitmap_free (changed);
2132 bitmap_obstack_release (&oldpta_obstack);
2135 /* Map from trees to variable infos. */
2136 static struct pointer_map_t *vi_for_tree;
2139 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2141 static void
2142 insert_vi_for_tree (tree t, varinfo_t vi)
2144 void **slot = pointer_map_insert (vi_for_tree, t);
2145 gcc_assert (vi);
2146 gcc_assert (*slot == NULL);
2147 *slot = vi;
2150 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2151 exist in the map, return NULL, otherwise, return the varinfo we found. */
2153 static varinfo_t
2154 lookup_vi_for_tree (tree t)
2156 void **slot = pointer_map_contains (vi_for_tree, t);
2157 if (slot == NULL)
2158 return NULL;
2160 return (varinfo_t) *slot;
2163 /* Return a printable name for DECL */
2165 static const char *
2166 alias_get_name (tree decl)
2168 const char *res = get_name (decl);
2169 char *temp;
2170 int num_printed = 0;
2172 if (res != NULL)
2173 return res;
2175 res = "NULL";
2176 if (!dump_file)
2177 return res;
2179 if (TREE_CODE (decl) == SSA_NAME)
2181 num_printed = asprintf (&temp, "%s_%u",
2182 alias_get_name (SSA_NAME_VAR (decl)),
2183 SSA_NAME_VERSION (decl));
2185 else if (DECL_P (decl))
2187 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2189 if (num_printed > 0)
2191 res = ggc_strdup (temp);
2192 free (temp);
2194 return res;
2197 /* Find the variable id for tree T in the map.
2198 If T doesn't exist in the map, create an entry for it and return it. */
2200 static varinfo_t
2201 get_vi_for_tree (tree t)
2203 void **slot = pointer_map_contains (vi_for_tree, t);
2204 if (slot == NULL)
2205 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2207 return (varinfo_t) *slot;
2210 /* Get a constraint expression from an SSA_VAR_P node. */
2212 static struct constraint_expr
2213 get_constraint_exp_from_ssa_var (tree t)
2215 struct constraint_expr cexpr;
2217 gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2219 /* For parameters, get at the points-to set for the actual parm
2220 decl. */
2221 if (TREE_CODE (t) == SSA_NAME
2222 && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2223 && SSA_NAME_IS_DEFAULT_DEF (t))
2224 return get_constraint_exp_from_ssa_var (SSA_NAME_VAR (t));
2226 cexpr.type = SCALAR;
2228 cexpr.var = get_vi_for_tree (t)->id;
2229 /* If we determine the result is "anything", and we know this is readonly,
2230 say it points to readonly memory instead. */
2231 if (cexpr.var == anything_id && TREE_READONLY (t))
2233 cexpr.type = ADDRESSOF;
2234 cexpr.var = readonly_id;
2237 cexpr.offset = 0;
2238 return cexpr;
2241 /* Process a completed constraint T, and add it to the constraint
2242 list. */
2244 static void
2245 process_constraint (constraint_t t)
2247 struct constraint_expr rhs = t->rhs;
2248 struct constraint_expr lhs = t->lhs;
2250 gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2251 gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2253 if (lhs.type == DEREF)
2254 get_varinfo (lhs.var)->directly_dereferenced = true;
2255 if (rhs.type == DEREF)
2256 get_varinfo (rhs.var)->directly_dereferenced = true;
2258 if (!use_field_sensitive)
2260 t->rhs.offset = 0;
2261 t->lhs.offset = 0;
2264 /* ANYTHING == ANYTHING is pointless. */
2265 if (lhs.var == anything_id && rhs.var == anything_id)
2266 return;
2268 /* If we have &ANYTHING = something, convert to SOMETHING = &ANYTHING) */
2269 else if (lhs.var == anything_id && lhs.type == ADDRESSOF)
2271 rhs = t->lhs;
2272 t->lhs = t->rhs;
2273 t->rhs = rhs;
2274 process_constraint (t);
2276 /* This can happen in our IR with things like n->a = *p */
2277 else if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2279 /* Split into tmp = *rhs, *lhs = tmp */
2280 tree rhsdecl = get_varinfo (rhs.var)->decl;
2281 tree pointertype = TREE_TYPE (rhsdecl);
2282 tree pointedtotype = TREE_TYPE (pointertype);
2283 tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
2284 struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2286 /* If this is an aggregate of known size, we should have passed
2287 this off to do_structure_copy, and it should have broken it
2288 up. */
2289 gcc_assert (!AGGREGATE_TYPE_P (pointedtotype)
2290 || get_varinfo (rhs.var)->is_unknown_size_var);
2292 process_constraint (new_constraint (tmplhs, rhs));
2293 process_constraint (new_constraint (lhs, tmplhs));
2295 else
2297 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2298 VEC_safe_push (constraint_t, heap, constraints, t);
2302 /* Return true if T is a variable of a type that could contain
2303 pointers. */
2305 static bool
2306 could_have_pointers (tree t)
2308 tree type = TREE_TYPE (t);
2310 if (POINTER_TYPE_P (type)
2311 || AGGREGATE_TYPE_P (type)
2312 || TREE_CODE (type) == COMPLEX_TYPE)
2313 return true;
2315 return false;
2318 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2319 structure. */
2321 static unsigned HOST_WIDE_INT
2322 bitpos_of_field (const tree fdecl)
2325 if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
2326 || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
2327 return -1;
2329 return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8)
2330 + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
2334 /* Return true if an access to [ACCESSPOS, ACCESSSIZE]
2335 overlaps with a field at [FIELDPOS, FIELDSIZE] */
2337 static bool
2338 offset_overlaps_with_access (const unsigned HOST_WIDE_INT fieldpos,
2339 const unsigned HOST_WIDE_INT fieldsize,
2340 const unsigned HOST_WIDE_INT accesspos,
2341 const unsigned HOST_WIDE_INT accesssize)
2343 if (fieldpos == accesspos && fieldsize == accesssize)
2344 return true;
2345 if (accesspos >= fieldpos && accesspos < (fieldpos + fieldsize))
2346 return true;
2347 if (accesspos < fieldpos && (accesspos + accesssize > fieldpos))
2348 return true;
2350 return false;
2353 /* Given a COMPONENT_REF T, return the constraint_expr for it. */
2355 static void
2356 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results)
2358 tree orig_t = t;
2359 HOST_WIDE_INT bitsize = -1;
2360 HOST_WIDE_INT bitmaxsize = -1;
2361 HOST_WIDE_INT bitpos;
2362 tree forzero;
2363 struct constraint_expr *result;
2364 unsigned int beforelength = VEC_length (ce_s, *results);
2366 /* Some people like to do cute things like take the address of
2367 &0->a.b */
2368 forzero = t;
2369 while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2370 forzero = TREE_OPERAND (forzero, 0);
2372 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2374 struct constraint_expr temp;
2376 temp.offset = 0;
2377 temp.var = integer_id;
2378 temp.type = SCALAR;
2379 VEC_safe_push (ce_s, heap, *results, &temp);
2380 return;
2383 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2385 /* String constants are readonly, so there is nothing to really do
2386 here. */
2387 if (TREE_CODE (t) == STRING_CST)
2388 return;
2390 get_constraint_for (t, results);
2391 result = VEC_last (ce_s, *results);
2392 result->offset = bitpos;
2394 gcc_assert (beforelength + 1 == VEC_length (ce_s, *results));
2396 /* This can also happen due to weird offsetof type macros. */
2397 if (TREE_CODE (t) != ADDR_EXPR && result->type == ADDRESSOF)
2398 result->type = SCALAR;
2400 if (result->type == SCALAR)
2402 /* In languages like C, you can access one past the end of an
2403 array. You aren't allowed to dereference it, so we can
2404 ignore this constraint. When we handle pointer subtraction,
2405 we may have to do something cute here. */
2407 if (result->offset < get_varinfo (result->var)->fullsize
2408 && bitmaxsize != 0)
2410 /* It's also not true that the constraint will actually start at the
2411 right offset, it may start in some padding. We only care about
2412 setting the constraint to the first actual field it touches, so
2413 walk to find it. */
2414 varinfo_t curr;
2415 for (curr = get_varinfo (result->var); curr; curr = curr->next)
2417 if (offset_overlaps_with_access (curr->offset, curr->size,
2418 result->offset, bitmaxsize))
2420 result->var = curr->id;
2421 break;
2424 /* assert that we found *some* field there. The user couldn't be
2425 accessing *only* padding. */
2426 /* Still the user could access one past the end of an array
2427 embedded in a struct resulting in accessing *only* padding. */
2428 gcc_assert (curr || ref_contains_array_ref (orig_t));
2430 else if (bitmaxsize == 0)
2432 if (dump_file && (dump_flags & TDF_DETAILS))
2433 fprintf (dump_file, "Access to zero-sized part of variable,"
2434 "ignoring\n");
2436 else
2437 if (dump_file && (dump_flags & TDF_DETAILS))
2438 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
2440 result->offset = 0;
2445 /* Dereference the constraint expression CONS, and return the result.
2446 DEREF (ADDRESSOF) = SCALAR
2447 DEREF (SCALAR) = DEREF
2448 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
2449 This is needed so that we can handle dereferencing DEREF constraints. */
2451 static void
2452 do_deref (VEC (ce_s, heap) **constraints)
2454 struct constraint_expr *c;
2455 unsigned int i = 0;
2457 for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
2459 if (c->type == SCALAR)
2460 c->type = DEREF;
2461 else if (c->type == ADDRESSOF)
2462 c->type = SCALAR;
2463 else if (c->type == DEREF)
2465 tree tmpvar = create_tmp_var_raw (ptr_type_node, "dereftmp");
2466 struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2467 process_constraint (new_constraint (tmplhs, *c));
2468 c->var = tmplhs.var;
2470 else
2471 gcc_unreachable ();
2475 /* Given a tree T, return the constraint expression for it. */
2477 static void
2478 get_constraint_for (tree t, VEC (ce_s, heap) **results)
2480 struct constraint_expr temp;
2482 /* x = integer is all glommed to a single variable, which doesn't
2483 point to anything by itself. That is, of course, unless it is an
2484 integer constant being treated as a pointer, in which case, we
2485 will return that this is really the addressof anything. This
2486 happens below, since it will fall into the default case. The only
2487 case we know something about an integer treated like a pointer is
2488 when it is the NULL pointer, and then we just say it points to
2489 NULL. */
2490 if (TREE_CODE (t) == INTEGER_CST
2491 && !POINTER_TYPE_P (TREE_TYPE (t)))
2493 temp.var = integer_id;
2494 temp.type = SCALAR;
2495 temp.offset = 0;
2496 VEC_safe_push (ce_s, heap, *results, &temp);
2497 return;
2499 else if (TREE_CODE (t) == INTEGER_CST
2500 && integer_zerop (t))
2502 temp.var = nothing_id;
2503 temp.type = ADDRESSOF;
2504 temp.offset = 0;
2505 VEC_safe_push (ce_s, heap, *results, &temp);
2506 return;
2509 switch (TREE_CODE_CLASS (TREE_CODE (t)))
2511 case tcc_expression:
2512 case tcc_vl_exp:
2514 switch (TREE_CODE (t))
2516 case ADDR_EXPR:
2518 struct constraint_expr *c;
2519 unsigned int i;
2520 tree exp = TREE_OPERAND (t, 0);
2521 tree pttype = TREE_TYPE (TREE_TYPE (t));
2523 get_constraint_for (exp, results);
2525 /* Make sure we capture constraints to all elements
2526 of an array. */
2527 if ((handled_component_p (exp)
2528 && ref_contains_array_ref (exp))
2529 || TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
2531 struct constraint_expr *origrhs;
2532 varinfo_t origvar;
2533 struct constraint_expr tmp;
2535 if (VEC_length (ce_s, *results) == 0)
2536 return;
2538 gcc_assert (VEC_length (ce_s, *results) == 1);
2539 origrhs = VEC_last (ce_s, *results);
2540 tmp = *origrhs;
2541 VEC_pop (ce_s, *results);
2542 origvar = get_varinfo (origrhs->var);
2543 for (; origvar; origvar = origvar->next)
2545 tmp.var = origvar->id;
2546 VEC_safe_push (ce_s, heap, *results, &tmp);
2549 else if (VEC_length (ce_s, *results) == 1
2550 && (AGGREGATE_TYPE_P (pttype)
2551 || TREE_CODE (pttype) == COMPLEX_TYPE))
2553 struct constraint_expr *origrhs;
2554 varinfo_t origvar;
2555 struct constraint_expr tmp;
2557 gcc_assert (VEC_length (ce_s, *results) == 1);
2558 origrhs = VEC_last (ce_s, *results);
2559 tmp = *origrhs;
2560 VEC_pop (ce_s, *results);
2561 origvar = get_varinfo (origrhs->var);
2562 for (; origvar; origvar = origvar->next)
2564 tmp.var = origvar->id;
2565 VEC_safe_push (ce_s, heap, *results, &tmp);
2569 for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
2571 if (c->type == DEREF)
2572 c->type = SCALAR;
2573 else
2574 c->type = ADDRESSOF;
2576 return;
2578 break;
2579 case CALL_EXPR:
2580 /* XXX: In interprocedural mode, if we didn't have the
2581 body, we would need to do *each pointer argument =
2582 &ANYTHING added. */
2583 if (call_expr_flags (t) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA))
2585 varinfo_t vi;
2586 tree heapvar = heapvar_lookup (t);
2588 if (heapvar == NULL)
2590 heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
2591 DECL_EXTERNAL (heapvar) = 1;
2592 get_var_ann (heapvar)->is_heapvar = 1;
2593 if (gimple_referenced_vars (cfun))
2594 add_referenced_var (heapvar);
2595 heapvar_insert (t, heapvar);
2598 temp.var = create_variable_info_for (heapvar,
2599 alias_get_name (heapvar));
2601 vi = get_varinfo (temp.var);
2602 vi->is_artificial_var = 1;
2603 vi->is_heap_var = 1;
2604 temp.type = ADDRESSOF;
2605 temp.offset = 0;
2606 VEC_safe_push (ce_s, heap, *results, &temp);
2607 return;
2609 else
2611 temp.var = anything_id;
2612 temp.type = SCALAR;
2613 temp.offset = 0;
2614 VEC_safe_push (ce_s, heap, *results, &temp);
2615 return;
2617 break;
2618 default:
2620 temp.type = ADDRESSOF;
2621 temp.var = anything_id;
2622 temp.offset = 0;
2623 VEC_safe_push (ce_s, heap, *results, &temp);
2624 return;
2628 case tcc_reference:
2630 switch (TREE_CODE (t))
2632 case INDIRECT_REF:
2634 get_constraint_for (TREE_OPERAND (t, 0), results);
2635 do_deref (results);
2636 return;
2638 case ARRAY_REF:
2639 case ARRAY_RANGE_REF:
2640 case COMPONENT_REF:
2641 get_constraint_for_component_ref (t, results);
2642 return;
2643 default:
2645 temp.type = ADDRESSOF;
2646 temp.var = anything_id;
2647 temp.offset = 0;
2648 VEC_safe_push (ce_s, heap, *results, &temp);
2649 return;
2653 case tcc_unary:
2655 switch (TREE_CODE (t))
2657 case NOP_EXPR:
2658 case CONVERT_EXPR:
2659 case NON_LVALUE_EXPR:
2661 tree op = TREE_OPERAND (t, 0);
2663 /* Cast from non-pointer to pointers are bad news for us.
2664 Anything else, we see through */
2665 if (!(POINTER_TYPE_P (TREE_TYPE (t))
2666 && ! POINTER_TYPE_P (TREE_TYPE (op))))
2668 get_constraint_for (op, results);
2669 return;
2672 /* FALLTHRU */
2674 default:
2676 temp.type = ADDRESSOF;
2677 temp.var = anything_id;
2678 temp.offset = 0;
2679 VEC_safe_push (ce_s, heap, *results, &temp);
2680 return;
2684 case tcc_exceptional:
2686 switch (TREE_CODE (t))
2688 case PHI_NODE:
2690 get_constraint_for (PHI_RESULT (t), results);
2691 return;
2693 break;
2694 case SSA_NAME:
2696 struct constraint_expr temp;
2697 temp = get_constraint_exp_from_ssa_var (t);
2698 VEC_safe_push (ce_s, heap, *results, &temp);
2699 return;
2701 break;
2702 default:
2704 temp.type = ADDRESSOF;
2705 temp.var = anything_id;
2706 temp.offset = 0;
2707 VEC_safe_push (ce_s, heap, *results, &temp);
2708 return;
2712 case tcc_declaration:
2714 struct constraint_expr temp;
2715 temp = get_constraint_exp_from_ssa_var (t);
2716 VEC_safe_push (ce_s, heap, *results, &temp);
2717 return;
2719 default:
2721 temp.type = ADDRESSOF;
2722 temp.var = anything_id;
2723 temp.offset = 0;
2724 VEC_safe_push (ce_s, heap, *results, &temp);
2725 return;
2731 /* Handle the structure copy case where we have a simple structure copy
2732 between LHS and RHS that is of SIZE (in bits)
2734 For each field of the lhs variable (lhsfield)
2735 For each field of the rhs variable at lhsfield.offset (rhsfield)
2736 add the constraint lhsfield = rhsfield
2738 If we fail due to some kind of type unsafety or other thing we
2739 can't handle, return false. We expect the caller to collapse the
2740 variable in that case. */
2742 static bool
2743 do_simple_structure_copy (const struct constraint_expr lhs,
2744 const struct constraint_expr rhs,
2745 const unsigned HOST_WIDE_INT size)
2747 varinfo_t p = get_varinfo (lhs.var);
2748 unsigned HOST_WIDE_INT pstart, last;
2749 pstart = p->offset;
2750 last = p->offset + size;
2751 for (; p && p->offset < last; p = p->next)
2753 varinfo_t q;
2754 struct constraint_expr templhs = lhs;
2755 struct constraint_expr temprhs = rhs;
2756 unsigned HOST_WIDE_INT fieldoffset;
2758 templhs.var = p->id;
2759 q = get_varinfo (temprhs.var);
2760 fieldoffset = p->offset - pstart;
2761 q = first_vi_for_offset (q, q->offset + fieldoffset);
2762 if (!q)
2763 return false;
2764 temprhs.var = q->id;
2765 process_constraint (new_constraint (templhs, temprhs));
2767 return true;
2771 /* Handle the structure copy case where we have a structure copy between a
2772 aggregate on the LHS and a dereference of a pointer on the RHS
2773 that is of SIZE (in bits)
2775 For each field of the lhs variable (lhsfield)
2776 rhs.offset = lhsfield->offset
2777 add the constraint lhsfield = rhs
2780 static void
2781 do_rhs_deref_structure_copy (const struct constraint_expr lhs,
2782 const struct constraint_expr rhs,
2783 const unsigned HOST_WIDE_INT size)
2785 varinfo_t p = get_varinfo (lhs.var);
2786 unsigned HOST_WIDE_INT pstart,last;
2787 pstart = p->offset;
2788 last = p->offset + size;
2790 for (; p && p->offset < last; p = p->next)
2792 varinfo_t q;
2793 struct constraint_expr templhs = lhs;
2794 struct constraint_expr temprhs = rhs;
2795 unsigned HOST_WIDE_INT fieldoffset;
2798 if (templhs.type == SCALAR)
2799 templhs.var = p->id;
2800 else
2801 templhs.offset = p->offset;
2803 q = get_varinfo (temprhs.var);
2804 fieldoffset = p->offset - pstart;
2805 temprhs.offset += fieldoffset;
2806 process_constraint (new_constraint (templhs, temprhs));
2810 /* Handle the structure copy case where we have a structure copy
2811 between a aggregate on the RHS and a dereference of a pointer on
2812 the LHS that is of SIZE (in bits)
2814 For each field of the rhs variable (rhsfield)
2815 lhs.offset = rhsfield->offset
2816 add the constraint lhs = rhsfield
2819 static void
2820 do_lhs_deref_structure_copy (const struct constraint_expr lhs,
2821 const struct constraint_expr rhs,
2822 const unsigned HOST_WIDE_INT size)
2824 varinfo_t p = get_varinfo (rhs.var);
2825 unsigned HOST_WIDE_INT pstart,last;
2826 pstart = p->offset;
2827 last = p->offset + size;
2829 for (; p && p->offset < last; p = p->next)
2831 varinfo_t q;
2832 struct constraint_expr templhs = lhs;
2833 struct constraint_expr temprhs = rhs;
2834 unsigned HOST_WIDE_INT fieldoffset;
2837 if (temprhs.type == SCALAR)
2838 temprhs.var = p->id;
2839 else
2840 temprhs.offset = p->offset;
2842 q = get_varinfo (templhs.var);
2843 fieldoffset = p->offset - pstart;
2844 templhs.offset += fieldoffset;
2845 process_constraint (new_constraint (templhs, temprhs));
2849 /* Sometimes, frontends like to give us bad type information. This
2850 function will collapse all the fields from VAR to the end of VAR,
2851 into VAR, so that we treat those fields as a single variable.
2852 We return the variable they were collapsed into. */
2854 static unsigned int
2855 collapse_rest_of_var (unsigned int var)
2857 varinfo_t currvar = get_varinfo (var);
2858 varinfo_t field;
2860 for (field = currvar->next; field; field = field->next)
2862 if (dump_file)
2863 fprintf (dump_file, "Type safety: Collapsing var %s into %s\n",
2864 field->name, currvar->name);
2866 gcc_assert (!field->collapsed_to);
2867 field->collapsed_to = currvar;
2870 currvar->next = NULL;
2871 currvar->size = currvar->fullsize - currvar->offset;
2873 return currvar->id;
2876 /* Handle aggregate copies by expanding into copies of the respective
2877 fields of the structures. */
2879 static void
2880 do_structure_copy (tree lhsop, tree rhsop)
2882 struct constraint_expr lhs, rhs, tmp;
2883 VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
2884 varinfo_t p;
2885 unsigned HOST_WIDE_INT lhssize;
2886 unsigned HOST_WIDE_INT rhssize;
2888 get_constraint_for (lhsop, &lhsc);
2889 get_constraint_for (rhsop, &rhsc);
2890 gcc_assert (VEC_length (ce_s, lhsc) == 1);
2891 gcc_assert (VEC_length (ce_s, rhsc) == 1);
2892 lhs = *(VEC_last (ce_s, lhsc));
2893 rhs = *(VEC_last (ce_s, rhsc));
2895 VEC_free (ce_s, heap, lhsc);
2896 VEC_free (ce_s, heap, rhsc);
2898 /* If we have special var = x, swap it around. */
2899 if (lhs.var <= integer_id && !(get_varinfo (rhs.var)->is_special_var))
2901 tmp = lhs;
2902 lhs = rhs;
2903 rhs = tmp;
2906 /* This is fairly conservative for the RHS == ADDRESSOF case, in that it's
2907 possible it's something we could handle. However, most cases falling
2908 into this are dealing with transparent unions, which are slightly
2909 weird. */
2910 if (rhs.type == ADDRESSOF && !(get_varinfo (rhs.var)->is_special_var))
2912 rhs.type = ADDRESSOF;
2913 rhs.var = anything_id;
2916 /* If the RHS is a special var, or an addressof, set all the LHS fields to
2917 that special var. */
2918 if (rhs.var <= integer_id)
2920 for (p = get_varinfo (lhs.var); p; p = p->next)
2922 struct constraint_expr templhs = lhs;
2923 struct constraint_expr temprhs = rhs;
2925 if (templhs.type == SCALAR )
2926 templhs.var = p->id;
2927 else
2928 templhs.offset += p->offset;
2929 process_constraint (new_constraint (templhs, temprhs));
2932 else
2934 tree rhstype = TREE_TYPE (rhsop);
2935 tree lhstype = TREE_TYPE (lhsop);
2936 tree rhstypesize;
2937 tree lhstypesize;
2939 lhstypesize = DECL_P (lhsop) ? DECL_SIZE (lhsop) : TYPE_SIZE (lhstype);
2940 rhstypesize = DECL_P (rhsop) ? DECL_SIZE (rhsop) : TYPE_SIZE (rhstype);
2942 /* If we have a variably sized types on the rhs or lhs, and a deref
2943 constraint, add the constraint, lhsconstraint = &ANYTHING.
2944 This is conservatively correct because either the lhs is an unknown
2945 sized var (if the constraint is SCALAR), or the lhs is a DEREF
2946 constraint, and every variable it can point to must be unknown sized
2947 anyway, so we don't need to worry about fields at all. */
2948 if ((rhs.type == DEREF && TREE_CODE (rhstypesize) != INTEGER_CST)
2949 || (lhs.type == DEREF && TREE_CODE (lhstypesize) != INTEGER_CST))
2951 rhs.var = anything_id;
2952 rhs.type = ADDRESSOF;
2953 rhs.offset = 0;
2954 process_constraint (new_constraint (lhs, rhs));
2955 return;
2958 /* The size only really matters insofar as we don't set more or less of
2959 the variable. If we hit an unknown size var, the size should be the
2960 whole darn thing. */
2961 if (get_varinfo (rhs.var)->is_unknown_size_var)
2962 rhssize = ~0;
2963 else
2964 rhssize = TREE_INT_CST_LOW (rhstypesize);
2966 if (get_varinfo (lhs.var)->is_unknown_size_var)
2967 lhssize = ~0;
2968 else
2969 lhssize = TREE_INT_CST_LOW (lhstypesize);
2972 if (rhs.type == SCALAR && lhs.type == SCALAR)
2974 if (!do_simple_structure_copy (lhs, rhs, MIN (lhssize, rhssize)))
2976 lhs.var = collapse_rest_of_var (lhs.var);
2977 rhs.var = collapse_rest_of_var (rhs.var);
2978 lhs.offset = 0;
2979 rhs.offset = 0;
2980 lhs.type = SCALAR;
2981 rhs.type = SCALAR;
2982 process_constraint (new_constraint (lhs, rhs));
2985 else if (lhs.type != DEREF && rhs.type == DEREF)
2986 do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2987 else if (lhs.type == DEREF && rhs.type != DEREF)
2988 do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2989 else
2991 tree pointedtotype = lhstype;
2992 tree tmpvar;
2994 gcc_assert (rhs.type == DEREF && lhs.type == DEREF);
2995 tmpvar = create_tmp_var_raw (pointedtotype, "structcopydereftmp");
2996 do_structure_copy (tmpvar, rhsop);
2997 do_structure_copy (lhsop, tmpvar);
3003 /* Update related alias information kept in AI. This is used when
3004 building name tags, alias sets and deciding grouping heuristics.
3005 STMT is the statement to process. This function also updates
3006 ADDRESSABLE_VARS. */
3008 static void
3009 update_alias_info (tree stmt, struct alias_info *ai)
3011 bitmap addr_taken;
3012 use_operand_p use_p;
3013 ssa_op_iter iter;
3014 bool stmt_dereferences_ptr_p;
3015 enum escape_type stmt_escape_type = is_escape_site (stmt);
3016 struct mem_ref_stats_d *mem_ref_stats = gimple_mem_ref_stats (cfun);
3018 stmt_dereferences_ptr_p = false;
3020 if (stmt_escape_type == ESCAPE_TO_CALL
3021 || stmt_escape_type == ESCAPE_TO_PURE_CONST)
3023 mem_ref_stats->num_call_sites++;
3024 if (stmt_escape_type == ESCAPE_TO_PURE_CONST)
3025 mem_ref_stats->num_pure_const_call_sites++;
3027 else if (stmt_escape_type == ESCAPE_TO_ASM)
3028 mem_ref_stats->num_asm_sites++;
3030 /* Mark all the variables whose address are taken by the statement. */
3031 addr_taken = addresses_taken (stmt);
3032 if (addr_taken)
3034 bitmap_ior_into (gimple_addressable_vars (cfun), addr_taken);
3036 /* If STMT is an escape point, all the addresses taken by it are
3037 call-clobbered. */
3038 if (stmt_escape_type != NO_ESCAPE)
3040 bitmap_iterator bi;
3041 unsigned i;
3043 EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
3045 tree rvar = referenced_var (i);
3046 if (!unmodifiable_var_p (rvar))
3047 mark_call_clobbered (rvar, stmt_escape_type);
3052 /* Process each operand use. For pointers, determine whether they
3053 are dereferenced by the statement, or whether their value
3054 escapes, etc. */
3055 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
3057 tree op, var;
3058 var_ann_t v_ann;
3059 struct ptr_info_def *pi;
3060 unsigned num_uses, num_loads, num_stores;
3062 op = USE_FROM_PTR (use_p);
3064 /* If STMT is a PHI node, OP may be an ADDR_EXPR. If so, add it
3065 to the set of addressable variables. */
3066 if (TREE_CODE (op) == ADDR_EXPR)
3068 bitmap addressable_vars = gimple_addressable_vars (cfun);
3070 gcc_assert (TREE_CODE (stmt) == PHI_NODE);
3071 gcc_assert (addressable_vars);
3073 /* PHI nodes don't have annotations for pinning the set
3074 of addresses taken, so we collect them here.
3076 FIXME, should we allow PHI nodes to have annotations
3077 so that they can be treated like regular statements?
3078 Currently, they are treated as second-class
3079 statements. */
3080 add_to_addressable_set (TREE_OPERAND (op, 0), &addressable_vars);
3081 continue;
3084 /* Ignore constants (they may occur in PHI node arguments). */
3085 if (TREE_CODE (op) != SSA_NAME)
3086 continue;
3088 var = SSA_NAME_VAR (op);
3089 v_ann = var_ann (var);
3091 /* The base variable of an SSA name must be a GIMPLE register, and thus
3092 it cannot be aliased. */
3093 gcc_assert (!may_be_aliased (var));
3095 /* We are only interested in pointers. */
3096 if (!POINTER_TYPE_P (TREE_TYPE (op)))
3097 continue;
3099 pi = get_ptr_info (op);
3101 /* Add OP to AI->PROCESSED_PTRS, if it's not there already. */
3102 if (!TEST_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op)))
3104 SET_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (op));
3105 VEC_safe_push (tree, heap, ai->processed_ptrs, op);
3108 /* If STMT is a PHI node, then it will not have pointer
3109 dereferences and it will not be an escape point. */
3110 if (TREE_CODE (stmt) == PHI_NODE)
3111 continue;
3113 /* Determine whether OP is a dereferenced pointer, and if STMT
3114 is an escape point, whether OP escapes. */
3115 count_uses_and_derefs (op, stmt, &num_uses, &num_loads, &num_stores);
3117 /* Handle a corner case involving address expressions of the
3118 form '&PTR->FLD'. The problem with these expressions is that
3119 they do not represent a dereference of PTR. However, if some
3120 other transformation propagates them into an INDIRECT_REF
3121 expression, we end up with '*(&PTR->FLD)' which is folded
3122 into 'PTR->FLD'.
3124 So, if the original code had no other dereferences of PTR,
3125 the aliaser will not create memory tags for it, and when
3126 &PTR->FLD gets propagated to INDIRECT_REF expressions, the
3127 memory operations will receive no VDEF/VUSE operands.
3129 One solution would be to have count_uses_and_derefs consider
3130 &PTR->FLD a dereference of PTR. But that is wrong, since it
3131 is not really a dereference but an offset calculation.
3133 What we do here is to recognize these special ADDR_EXPR
3134 nodes. Since these expressions are never GIMPLE values (they
3135 are not GIMPLE invariants), they can only appear on the RHS
3136 of an assignment and their base address is always an
3137 INDIRECT_REF expression. */
3138 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3139 && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == ADDR_EXPR
3140 && !is_gimple_val (GIMPLE_STMT_OPERAND (stmt, 1)))
3142 /* If the RHS if of the form &PTR->FLD and PTR == OP, then
3143 this represents a potential dereference of PTR. */
3144 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
3145 tree base = get_base_address (TREE_OPERAND (rhs, 0));
3146 if (TREE_CODE (base) == INDIRECT_REF
3147 && TREE_OPERAND (base, 0) == op)
3148 num_loads++;
3151 if (num_loads + num_stores > 0)
3153 /* Mark OP as dereferenced. In a subsequent pass,
3154 dereferenced pointers that point to a set of
3155 variables will be assigned a name tag to alias
3156 all the variables OP points to. */
3157 pi->is_dereferenced = 1;
3159 /* If this is a store operation, mark OP as being
3160 dereferenced to store, otherwise mark it as being
3161 dereferenced to load. */
3162 if (num_stores > 0)
3163 pointer_set_insert (ai->dereferenced_ptrs_store, var);
3164 else
3165 pointer_set_insert (ai->dereferenced_ptrs_load, var);
3167 /* Update the frequency estimate for all the dereferences of
3168 pointer OP. */
3169 update_mem_sym_stats_from_stmt (op, stmt, num_loads, num_stores);
3171 /* Indicate that STMT contains pointer dereferences. */
3172 stmt_dereferences_ptr_p = true;
3175 if (stmt_escape_type != NO_ESCAPE && num_loads + num_stores < num_uses)
3177 /* If STMT is an escape point and STMT contains at
3178 least one direct use of OP, then the value of OP
3179 escapes and so the pointed-to variables need to
3180 be marked call-clobbered. */
3181 pi->value_escapes_p = 1;
3182 pi->escape_mask |= stmt_escape_type;
3184 /* If the statement makes a function call, assume
3185 that pointer OP will be dereferenced in a store
3186 operation inside the called function. */
3187 if (get_call_expr_in (stmt)
3188 || stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3190 pointer_set_insert (ai->dereferenced_ptrs_store, var);
3191 pi->is_dereferenced = 1;
3196 if (TREE_CODE (stmt) == PHI_NODE)
3197 return;
3199 /* Mark stored variables in STMT as being written to and update the
3200 memory reference stats for all memory symbols referenced by STMT. */
3201 if (stmt_references_memory_p (stmt))
3203 unsigned i;
3204 bitmap_iterator bi;
3206 mem_ref_stats->num_mem_stmts++;
3208 /* Notice that we only update memory reference stats for symbols
3209 loaded and stored by the statement if the statement does not
3210 contain pointer dereferences and it is not a call/asm site.
3211 This is to avoid double accounting problems when creating
3212 memory partitions. After computing points-to information,
3213 pointer dereference statistics are used to update the
3214 reference stats of the pointed-to variables, so here we
3215 should only update direct references to symbols.
3217 Indirect references are not updated here for two reasons: (1)
3218 The first time we compute alias information, the sets
3219 LOADED/STORED are empty for pointer dereferences, (2) After
3220 partitioning, LOADED/STORED may have references to
3221 partitions, not the original pointed-to variables. So, if we
3222 always counted LOADED/STORED here and during partitioning, we
3223 would count many symbols more than once.
3225 This does cause some imprecision when a statement has a
3226 combination of direct symbol references and pointer
3227 dereferences (e.g., MEMORY_VAR = *PTR) or if a call site has
3228 memory symbols in its argument list, but these cases do not
3229 occur so frequently as to constitute a serious problem. */
3230 if (STORED_SYMS (stmt))
3231 EXECUTE_IF_SET_IN_BITMAP (STORED_SYMS (stmt), 0, i, bi)
3233 tree sym = referenced_var (i);
3234 pointer_set_insert (ai->written_vars, sym);
3235 if (!stmt_dereferences_ptr_p
3236 && stmt_escape_type != ESCAPE_TO_CALL
3237 && stmt_escape_type != ESCAPE_TO_PURE_CONST
3238 && stmt_escape_type != ESCAPE_TO_ASM)
3239 update_mem_sym_stats_from_stmt (sym, stmt, 0, 1);
3242 if (!stmt_dereferences_ptr_p
3243 && LOADED_SYMS (stmt)
3244 && stmt_escape_type != ESCAPE_TO_CALL
3245 && stmt_escape_type != ESCAPE_TO_PURE_CONST
3246 && stmt_escape_type != ESCAPE_TO_ASM)
3247 EXECUTE_IF_SET_IN_BITMAP (LOADED_SYMS (stmt), 0, i, bi)
3248 update_mem_sym_stats_from_stmt (referenced_var (i), stmt, 1, 0);
3253 /* Handle pointer arithmetic EXPR when creating aliasing constraints.
3254 Expressions of the type PTR + CST can be handled in two ways:
3256 1- If the constraint for PTR is ADDRESSOF for a non-structure
3257 variable, then we can use it directly because adding or
3258 subtracting a constant may not alter the original ADDRESSOF
3259 constraint (i.e., pointer arithmetic may not legally go outside
3260 an object's boundaries).
3262 2- If the constraint for PTR is ADDRESSOF for a structure variable,
3263 then if CST is a compile-time constant that can be used as an
3264 offset, we can determine which sub-variable will be pointed-to
3265 by the expression.
3267 Return true if the expression is handled. For any other kind of
3268 expression, return false so that each operand can be added as a
3269 separate constraint by the caller. */
3271 static bool
3272 handle_ptr_arith (VEC (ce_s, heap) *lhsc, tree expr)
3274 tree op0, op1;
3275 struct constraint_expr *c, *c2;
3276 unsigned int i = 0;
3277 unsigned int j = 0;
3278 VEC (ce_s, heap) *temp = NULL;
3279 unsigned int rhsoffset = 0;
3281 if (TREE_CODE (expr) != PLUS_EXPR
3282 && TREE_CODE (expr) != MINUS_EXPR)
3283 return false;
3285 op0 = TREE_OPERAND (expr, 0);
3286 op1 = TREE_OPERAND (expr, 1);
3288 get_constraint_for (op0, &temp);
3289 if (POINTER_TYPE_P (TREE_TYPE (op0))
3290 && TREE_CODE (op1) == INTEGER_CST
3291 && TREE_CODE (expr) == PLUS_EXPR)
3293 rhsoffset = TREE_INT_CST_LOW (op1) * BITS_PER_UNIT;
3295 else
3296 return false;
3299 for (i = 0; VEC_iterate (ce_s, lhsc, i, c); i++)
3300 for (j = 0; VEC_iterate (ce_s, temp, j, c2); j++)
3302 if (c2->type == ADDRESSOF && rhsoffset != 0)
3304 varinfo_t temp = get_varinfo (c2->var);
3306 /* An access one after the end of an array is valid,
3307 so simply punt on accesses we cannot resolve. */
3308 temp = first_vi_for_offset (temp, rhsoffset);
3309 if (temp == NULL)
3310 continue;
3311 c2->var = temp->id;
3312 c2->offset = 0;
3314 else
3315 c2->offset = rhsoffset;
3316 process_constraint (new_constraint (*c, *c2));
3319 VEC_free (ce_s, heap, temp);
3321 return true;
3325 /* Walk statement T setting up aliasing constraints according to the
3326 references found in T. This function is the main part of the
3327 constraint builder. AI points to auxiliary alias information used
3328 when building alias sets and computing alias grouping heuristics. */
3330 static void
3331 find_func_aliases (tree origt)
3333 tree t = origt;
3334 VEC(ce_s, heap) *lhsc = NULL;
3335 VEC(ce_s, heap) *rhsc = NULL;
3336 struct constraint_expr *c;
3338 if (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0))
3339 t = TREE_OPERAND (t, 0);
3341 /* Now build constraints expressions. */
3342 if (TREE_CODE (t) == PHI_NODE)
3344 gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (PHI_RESULT (t))));
3346 /* Only care about pointers and structures containing
3347 pointers. */
3348 if (could_have_pointers (PHI_RESULT (t)))
3350 int i;
3351 unsigned int j;
3353 /* For a phi node, assign all the arguments to
3354 the result. */
3355 get_constraint_for (PHI_RESULT (t), &lhsc);
3356 for (i = 0; i < PHI_NUM_ARGS (t); i++)
3358 tree rhstype;
3359 tree strippedrhs = PHI_ARG_DEF (t, i);
3361 STRIP_NOPS (strippedrhs);
3362 rhstype = TREE_TYPE (strippedrhs);
3363 get_constraint_for (PHI_ARG_DEF (t, i), &rhsc);
3365 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3367 struct constraint_expr *c2;
3368 while (VEC_length (ce_s, rhsc) > 0)
3370 c2 = VEC_last (ce_s, rhsc);
3371 process_constraint (new_constraint (*c, *c2));
3372 VEC_pop (ce_s, rhsc);
3378 /* In IPA mode, we need to generate constraints to pass call
3379 arguments through their calls. There are two cases, either a
3380 GIMPLE_MODIFY_STMT when we are returning a value, or just a plain
3381 CALL_EXPR when we are not. */
3382 else if (in_ipa_mode
3383 && ((TREE_CODE (t) == GIMPLE_MODIFY_STMT
3384 && TREE_CODE (GIMPLE_STMT_OPERAND (t, 1)) == CALL_EXPR
3385 && !(call_expr_flags (GIMPLE_STMT_OPERAND (t, 1))
3386 & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))
3387 || (TREE_CODE (t) == CALL_EXPR
3388 && !(call_expr_flags (t)
3389 & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))))
3391 tree lhsop;
3392 tree rhsop;
3393 tree arg;
3394 call_expr_arg_iterator iter;
3395 varinfo_t fi;
3396 int i = 1;
3397 tree decl;
3398 if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
3400 lhsop = GIMPLE_STMT_OPERAND (t, 0);
3401 rhsop = GIMPLE_STMT_OPERAND (t, 1);
3403 else
3405 lhsop = NULL;
3406 rhsop = t;
3408 decl = get_callee_fndecl (rhsop);
3410 /* If we can directly resolve the function being called, do so.
3411 Otherwise, it must be some sort of indirect expression that
3412 we should still be able to handle. */
3413 if (decl)
3415 fi = get_vi_for_tree (decl);
3417 else
3419 decl = CALL_EXPR_FN (rhsop);
3420 fi = get_vi_for_tree (decl);
3423 /* Assign all the passed arguments to the appropriate incoming
3424 parameters of the function. */
3426 FOR_EACH_CALL_EXPR_ARG (arg, iter, rhsop)
3428 struct constraint_expr lhs ;
3429 struct constraint_expr *rhsp;
3431 get_constraint_for (arg, &rhsc);
3432 if (TREE_CODE (decl) != FUNCTION_DECL)
3434 lhs.type = DEREF;
3435 lhs.var = fi->id;
3436 lhs.offset = i;
3438 else
3440 lhs.type = SCALAR;
3441 lhs.var = first_vi_for_offset (fi, i)->id;
3442 lhs.offset = 0;
3444 while (VEC_length (ce_s, rhsc) != 0)
3446 rhsp = VEC_last (ce_s, rhsc);
3447 process_constraint (new_constraint (lhs, *rhsp));
3448 VEC_pop (ce_s, rhsc);
3450 i++;
3453 /* If we are returning a value, assign it to the result. */
3454 if (lhsop)
3456 struct constraint_expr rhs;
3457 struct constraint_expr *lhsp;
3458 unsigned int j = 0;
3460 get_constraint_for (lhsop, &lhsc);
3461 if (TREE_CODE (decl) != FUNCTION_DECL)
3463 rhs.type = DEREF;
3464 rhs.var = fi->id;
3465 rhs.offset = i;
3467 else
3469 rhs.type = SCALAR;
3470 rhs.var = first_vi_for_offset (fi, i)->id;
3471 rhs.offset = 0;
3473 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3474 process_constraint (new_constraint (*lhsp, rhs));
3477 /* Otherwise, just a regular assignment statement. */
3478 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
3480 tree lhsop = GIMPLE_STMT_OPERAND (t, 0);
3481 tree rhsop = GIMPLE_STMT_OPERAND (t, 1);
3482 int i;
3484 if ((AGGREGATE_TYPE_P (TREE_TYPE (lhsop))
3485 || TREE_CODE (TREE_TYPE (lhsop)) == COMPLEX_TYPE)
3486 && (AGGREGATE_TYPE_P (TREE_TYPE (rhsop))
3487 || TREE_CODE (TREE_TYPE (lhsop)) == COMPLEX_TYPE))
3489 do_structure_copy (lhsop, rhsop);
3491 else
3493 /* Only care about operations with pointers, structures
3494 containing pointers, dereferences, and call expressions. */
3495 if (could_have_pointers (lhsop)
3496 || TREE_CODE (rhsop) == CALL_EXPR)
3498 get_constraint_for (lhsop, &lhsc);
3499 switch (TREE_CODE_CLASS (TREE_CODE (rhsop)))
3501 /* RHS that consist of unary operations,
3502 exceptional types, or bare decls/constants, get
3503 handled directly by get_constraint_for. */
3504 case tcc_reference:
3505 case tcc_declaration:
3506 case tcc_constant:
3507 case tcc_exceptional:
3508 case tcc_expression:
3509 case tcc_vl_exp:
3510 case tcc_unary:
3512 unsigned int j;
3514 get_constraint_for (rhsop, &rhsc);
3515 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3517 struct constraint_expr *c2;
3518 unsigned int k;
3520 for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3521 process_constraint (new_constraint (*c, *c2));
3525 break;
3527 case tcc_binary:
3529 /* For pointer arithmetic of the form
3530 PTR + CST, we can simply use PTR's
3531 constraint because pointer arithmetic is
3532 not allowed to go out of bounds. */
3533 if (handle_ptr_arith (lhsc, rhsop))
3534 break;
3536 /* FALLTHRU */
3538 /* Otherwise, walk each operand. Notice that we
3539 can't use the operand interface because we need
3540 to process expressions other than simple operands
3541 (e.g. INDIRECT_REF, ADDR_EXPR, CALL_EXPR). */
3542 default:
3543 for (i = 0; i < TREE_OPERAND_LENGTH (rhsop); i++)
3545 tree op = TREE_OPERAND (rhsop, i);
3546 unsigned int j;
3548 gcc_assert (VEC_length (ce_s, rhsc) == 0);
3549 get_constraint_for (op, &rhsc);
3550 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3552 struct constraint_expr *c2;
3553 while (VEC_length (ce_s, rhsc) > 0)
3555 c2 = VEC_last (ce_s, rhsc);
3556 process_constraint (new_constraint (*c, *c2));
3557 VEC_pop (ce_s, rhsc);
3566 /* After promoting variables and computing aliasing we will
3567 need to re-scan most statements. FIXME: Try to minimize the
3568 number of statements re-scanned. It's not really necessary to
3569 re-scan *all* statements. */
3570 mark_stmt_modified (origt);
3571 VEC_free (ce_s, heap, rhsc);
3572 VEC_free (ce_s, heap, lhsc);
3576 /* Find the first varinfo in the same variable as START that overlaps with
3577 OFFSET.
3578 Effectively, walk the chain of fields for the variable START to find the
3579 first field that overlaps with OFFSET.
3580 Return NULL if we can't find one. */
3582 static varinfo_t
3583 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3585 varinfo_t curr = start;
3586 while (curr)
3588 /* We may not find a variable in the field list with the actual
3589 offset when when we have glommed a structure to a variable.
3590 In that case, however, offset should still be within the size
3591 of the variable. */
3592 if (offset >= curr->offset && offset < (curr->offset + curr->size))
3593 return curr;
3594 curr = curr->next;
3596 return NULL;
3600 /* Insert the varinfo FIELD into the field list for BASE, at the front
3601 of the list. */
3603 static void
3604 insert_into_field_list (varinfo_t base, varinfo_t field)
3606 varinfo_t prev = base;
3607 varinfo_t curr = base->next;
3609 field->next = curr;
3610 prev->next = field;
3613 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3614 offset. */
3616 static void
3617 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3619 varinfo_t prev = base;
3620 varinfo_t curr = base->next;
3622 if (curr == NULL)
3624 prev->next = field;
3625 field->next = NULL;
3627 else
3629 while (curr)
3631 if (field->offset <= curr->offset)
3632 break;
3633 prev = curr;
3634 curr = curr->next;
3636 field->next = prev->next;
3637 prev->next = field;
3641 /* qsort comparison function for two fieldoff's PA and PB */
3643 static int
3644 fieldoff_compare (const void *pa, const void *pb)
3646 const fieldoff_s *foa = (const fieldoff_s *)pa;
3647 const fieldoff_s *fob = (const fieldoff_s *)pb;
3648 HOST_WIDE_INT foasize, fobsize;
3650 if (foa->offset != fob->offset)
3651 return foa->offset - fob->offset;
3653 foasize = TREE_INT_CST_LOW (foa->size);
3654 fobsize = TREE_INT_CST_LOW (fob->size);
3655 return foasize - fobsize;
3658 /* Sort a fieldstack according to the field offset and sizes. */
3659 void
3660 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3662 qsort (VEC_address (fieldoff_s, fieldstack),
3663 VEC_length (fieldoff_s, fieldstack),
3664 sizeof (fieldoff_s),
3665 fieldoff_compare);
3668 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
3669 of TYPE onto fieldstack, recording their offsets along the way.
3670 OFFSET is used to keep track of the offset in this entire structure, rather
3671 than just the immediately containing structure. Returns the number
3672 of fields pushed.
3673 HAS_UNION is set to true if we find a union type as a field of
3674 TYPE. */
3677 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
3678 HOST_WIDE_INT offset, bool *has_union)
3680 tree field;
3681 int count = 0;
3683 if (TREE_CODE (type) == COMPLEX_TYPE)
3685 fieldoff_s *real_part, *img_part;
3686 real_part = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3687 real_part->type = TREE_TYPE (type);
3688 real_part->size = TYPE_SIZE (TREE_TYPE (type));
3689 real_part->offset = offset;
3690 real_part->decl = NULL_TREE;
3692 img_part = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3693 img_part->type = TREE_TYPE (type);
3694 img_part->size = TYPE_SIZE (TREE_TYPE (type));
3695 img_part->offset = offset + TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (type)));
3696 img_part->decl = NULL_TREE;
3698 return 2;
3701 if (TREE_CODE (type) == ARRAY_TYPE)
3703 tree sz = TYPE_SIZE (type);
3704 tree elsz = TYPE_SIZE (TREE_TYPE (type));
3705 HOST_WIDE_INT nr;
3706 int i;
3708 if (! sz
3709 || ! host_integerp (sz, 1)
3710 || TREE_INT_CST_LOW (sz) == 0
3711 || ! elsz
3712 || ! host_integerp (elsz, 1)
3713 || TREE_INT_CST_LOW (elsz) == 0)
3714 return 0;
3716 nr = TREE_INT_CST_LOW (sz) / TREE_INT_CST_LOW (elsz);
3717 if (nr > SALIAS_MAX_ARRAY_ELEMENTS)
3718 return 0;
3720 for (i = 0; i < nr; ++i)
3722 bool push = false;
3723 int pushed = 0;
3725 if (has_union
3726 && (TREE_CODE (TREE_TYPE (type)) == QUAL_UNION_TYPE
3727 || TREE_CODE (TREE_TYPE (type)) == UNION_TYPE))
3728 *has_union = true;
3730 if (!AGGREGATE_TYPE_P (TREE_TYPE (type))) /* var_can_have_subvars */
3731 push = true;
3732 else if (!(pushed = push_fields_onto_fieldstack
3733 (TREE_TYPE (type), fieldstack,
3734 offset + i * TREE_INT_CST_LOW (elsz), has_union)))
3735 /* Empty structures may have actual size, like in C++. So
3736 see if we didn't push any subfields and the size is
3737 nonzero, push the field onto the stack */
3738 push = true;
3740 if (push)
3742 fieldoff_s *pair;
3744 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3745 pair->type = TREE_TYPE (type);
3746 pair->size = elsz;
3747 pair->decl = NULL_TREE;
3748 pair->offset = offset + i * TREE_INT_CST_LOW (elsz);
3749 count++;
3751 else
3752 count += pushed;
3755 return count;
3758 for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3759 if (TREE_CODE (field) == FIELD_DECL)
3761 bool push = false;
3762 int pushed = 0;
3764 if (has_union
3765 && (TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
3766 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE))
3767 *has_union = true;
3769 if (!var_can_have_subvars (field))
3770 push = true;
3771 else if (!(pushed = push_fields_onto_fieldstack
3772 (TREE_TYPE (field), fieldstack,
3773 offset + bitpos_of_field (field), has_union))
3774 && DECL_SIZE (field)
3775 && !integer_zerop (DECL_SIZE (field)))
3776 /* Empty structures may have actual size, like in C++. So
3777 see if we didn't push any subfields and the size is
3778 nonzero, push the field onto the stack */
3779 push = true;
3781 if (push)
3783 fieldoff_s *pair;
3785 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
3786 pair->type = TREE_TYPE (field);
3787 pair->size = DECL_SIZE (field);
3788 pair->decl = field;
3789 pair->offset = offset + bitpos_of_field (field);
3790 count++;
3792 else
3793 count += pushed;
3796 return count;
3799 /* Create a constraint from ANYTHING variable to VI. */
3800 static void
3801 make_constraint_from_anything (varinfo_t vi)
3803 struct constraint_expr lhs, rhs;
3805 lhs.var = vi->id;
3806 lhs.offset = 0;
3807 lhs.type = SCALAR;
3809 rhs.var = anything_id;
3810 rhs.offset = 0;
3811 rhs.type = ADDRESSOF;
3812 process_constraint (new_constraint (lhs, rhs));
3815 /* Count the number of arguments DECL has, and set IS_VARARGS to true
3816 if it is a varargs function. */
3818 static unsigned int
3819 count_num_arguments (tree decl, bool *is_varargs)
3821 unsigned int i = 0;
3822 tree t;
3824 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
3826 t = TREE_CHAIN (t))
3828 if (TREE_VALUE (t) == void_type_node)
3829 break;
3830 i++;
3833 if (!t)
3834 *is_varargs = true;
3835 return i;
3838 /* Creation function node for DECL, using NAME, and return the index
3839 of the variable we've created for the function. */
3841 static unsigned int
3842 create_function_info_for (tree decl, const char *name)
3844 unsigned int index = VEC_length (varinfo_t, varmap);
3845 varinfo_t vi;
3846 tree arg;
3847 unsigned int i;
3848 bool is_varargs = false;
3850 /* Create the variable info. */
3852 vi = new_var_info (decl, index, name);
3853 vi->decl = decl;
3854 vi->offset = 0;
3855 vi->has_union = 0;
3856 vi->size = 1;
3857 vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
3858 insert_vi_for_tree (vi->decl, vi);
3859 VEC_safe_push (varinfo_t, heap, varmap, vi);
3861 stats.total_vars++;
3863 /* If it's varargs, we don't know how many arguments it has, so we
3864 can't do much.
3866 if (is_varargs)
3868 vi->fullsize = ~0;
3869 vi->size = ~0;
3870 vi->is_unknown_size_var = true;
3871 return index;
3875 arg = DECL_ARGUMENTS (decl);
3877 /* Set up variables for each argument. */
3878 for (i = 1; i < vi->fullsize; i++)
3880 varinfo_t argvi;
3881 const char *newname;
3882 char *tempname;
3883 unsigned int newindex;
3884 tree argdecl = decl;
3886 if (arg)
3887 argdecl = arg;
3889 newindex = VEC_length (varinfo_t, varmap);
3890 asprintf (&tempname, "%s.arg%d", name, i-1);
3891 newname = ggc_strdup (tempname);
3892 free (tempname);
3894 argvi = new_var_info (argdecl, newindex, newname);
3895 argvi->decl = argdecl;
3896 VEC_safe_push (varinfo_t, heap, varmap, argvi);
3897 argvi->offset = i;
3898 argvi->size = 1;
3899 argvi->fullsize = vi->fullsize;
3900 argvi->has_union = false;
3901 insert_into_field_list_sorted (vi, argvi);
3902 stats.total_vars ++;
3903 if (arg)
3905 insert_vi_for_tree (arg, argvi);
3906 arg = TREE_CHAIN (arg);
3910 /* Create a variable for the return var. */
3911 if (DECL_RESULT (decl) != NULL
3912 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
3914 varinfo_t resultvi;
3915 const char *newname;
3916 char *tempname;
3917 unsigned int newindex;
3918 tree resultdecl = decl;
3920 vi->fullsize ++;
3922 if (DECL_RESULT (decl))
3923 resultdecl = DECL_RESULT (decl);
3925 newindex = VEC_length (varinfo_t, varmap);
3926 asprintf (&tempname, "%s.result", name);
3927 newname = ggc_strdup (tempname);
3928 free (tempname);
3930 resultvi = new_var_info (resultdecl, newindex, newname);
3931 resultvi->decl = resultdecl;
3932 VEC_safe_push (varinfo_t, heap, varmap, resultvi);
3933 resultvi->offset = i;
3934 resultvi->size = 1;
3935 resultvi->fullsize = vi->fullsize;
3936 resultvi->has_union = false;
3937 insert_into_field_list_sorted (vi, resultvi);
3938 stats.total_vars ++;
3939 if (DECL_RESULT (decl))
3940 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
3942 return index;
3946 /* Return true if FIELDSTACK contains fields that overlap.
3947 FIELDSTACK is assumed to be sorted by offset. */
3949 static bool
3950 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
3952 fieldoff_s *fo = NULL;
3953 unsigned int i;
3954 HOST_WIDE_INT lastoffset = -1;
3956 for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3958 if (fo->offset == lastoffset)
3959 return true;
3960 lastoffset = fo->offset;
3962 return false;
3965 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
3966 This will also create any varinfo structures necessary for fields
3967 of DECL. */
3969 static unsigned int
3970 create_variable_info_for (tree decl, const char *name)
3972 unsigned int index = VEC_length (varinfo_t, varmap);
3973 varinfo_t vi;
3974 tree decltype = TREE_TYPE (decl);
3975 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decltype);
3976 bool notokay = false;
3977 bool hasunion;
3978 bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
3979 VEC (fieldoff_s,heap) *fieldstack = NULL;
3981 if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
3982 return create_function_info_for (decl, name);
3984 hasunion = TREE_CODE (decltype) == UNION_TYPE
3985 || TREE_CODE (decltype) == QUAL_UNION_TYPE;
3986 if (var_can_have_subvars (decl) && use_field_sensitive && !hasunion)
3988 push_fields_onto_fieldstack (decltype, &fieldstack, 0, &hasunion);
3989 if (hasunion)
3991 VEC_free (fieldoff_s, heap, fieldstack);
3992 notokay = true;
3997 /* If the variable doesn't have subvars, we may end up needing to
3998 sort the field list and create fake variables for all the
3999 fields. */
4000 vi = new_var_info (decl, index, name);
4001 vi->decl = decl;
4002 vi->offset = 0;
4003 vi->has_union = hasunion;
4004 if (!declsize
4005 || TREE_CODE (declsize) != INTEGER_CST
4006 || TREE_CODE (decltype) == UNION_TYPE
4007 || TREE_CODE (decltype) == QUAL_UNION_TYPE)
4009 vi->is_unknown_size_var = true;
4010 vi->fullsize = ~0;
4011 vi->size = ~0;
4013 else
4015 vi->fullsize = TREE_INT_CST_LOW (declsize);
4016 vi->size = vi->fullsize;
4019 insert_vi_for_tree (vi->decl, vi);
4020 VEC_safe_push (varinfo_t, heap, varmap, vi);
4021 if (is_global && (!flag_whole_program || !in_ipa_mode))
4022 make_constraint_from_anything (vi);
4024 stats.total_vars++;
4025 if (use_field_sensitive
4026 && !notokay
4027 && !vi->is_unknown_size_var
4028 && var_can_have_subvars (decl)
4029 && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4031 unsigned int newindex = VEC_length (varinfo_t, varmap);
4032 fieldoff_s *fo = NULL;
4033 unsigned int i;
4035 for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4037 if (! fo->size
4038 || TREE_CODE (fo->size) != INTEGER_CST
4039 || fo->offset < 0)
4041 notokay = true;
4042 break;
4046 /* We can't sort them if we have a field with a variable sized type,
4047 which will make notokay = true. In that case, we are going to return
4048 without creating varinfos for the fields anyway, so sorting them is a
4049 waste to boot. */
4050 if (!notokay)
4052 sort_fieldstack (fieldstack);
4053 /* Due to some C++ FE issues, like PR 22488, we might end up
4054 what appear to be overlapping fields even though they,
4055 in reality, do not overlap. Until the C++ FE is fixed,
4056 we will simply disable field-sensitivity for these cases. */
4057 notokay = check_for_overlaps (fieldstack);
4061 if (VEC_length (fieldoff_s, fieldstack) != 0)
4062 fo = VEC_index (fieldoff_s, fieldstack, 0);
4064 if (fo == NULL || notokay)
4066 vi->is_unknown_size_var = 1;
4067 vi->fullsize = ~0;
4068 vi->size = ~0;
4069 VEC_free (fieldoff_s, heap, fieldstack);
4070 return index;
4073 vi->size = TREE_INT_CST_LOW (fo->size);
4074 vi->offset = fo->offset;
4075 for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4076 i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4077 i--)
4079 varinfo_t newvi;
4080 const char *newname = "NULL";
4081 char *tempname;
4083 newindex = VEC_length (varinfo_t, varmap);
4084 if (dump_file)
4086 if (fo->decl)
4087 asprintf (&tempname, "%s.%s",
4088 vi->name, alias_get_name (fo->decl));
4089 else
4090 asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC,
4091 vi->name, fo->offset);
4092 newname = ggc_strdup (tempname);
4093 free (tempname);
4095 newvi = new_var_info (decl, newindex, newname);
4096 newvi->offset = fo->offset;
4097 newvi->size = TREE_INT_CST_LOW (fo->size);
4098 newvi->fullsize = vi->fullsize;
4099 insert_into_field_list (vi, newvi);
4100 VEC_safe_push (varinfo_t, heap, varmap, newvi);
4101 if (is_global && (!flag_whole_program || !in_ipa_mode))
4102 make_constraint_from_anything (newvi);
4104 stats.total_vars++;
4106 VEC_free (fieldoff_s, heap, fieldstack);
4108 return index;
4111 /* Print out the points-to solution for VAR to FILE. */
4113 void
4114 dump_solution_for_var (FILE *file, unsigned int var)
4116 varinfo_t vi = get_varinfo (var);
4117 unsigned int i;
4118 bitmap_iterator bi;
4120 if (find (var) != var)
4122 varinfo_t vipt = get_varinfo (find (var));
4123 fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4125 else
4127 fprintf (file, "%s = { ", vi->name);
4128 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4130 fprintf (file, "%s ", get_varinfo (i)->name);
4132 fprintf (file, "}\n");
4136 /* Print the points-to solution for VAR to stdout. */
4138 void
4139 debug_solution_for_var (unsigned int var)
4141 dump_solution_for_var (stdout, var);
4144 /* Create varinfo structures for all of the variables in the
4145 function for intraprocedural mode. */
4147 static void
4148 intra_create_variable_infos (void)
4150 tree t;
4151 struct constraint_expr lhs, rhs;
4153 /* For each incoming pointer argument arg, create the constraint ARG
4154 = ANYTHING or a dummy variable if flag_argument_noalias is set. */
4155 for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4157 varinfo_t p;
4159 if (!could_have_pointers (t))
4160 continue;
4162 /* If flag_argument_noalias is set, then function pointer
4163 arguments are guaranteed not to point to each other. In that
4164 case, create an artificial variable PARM_NOALIAS and the
4165 constraint ARG = &PARM_NOALIAS. */
4166 if (POINTER_TYPE_P (TREE_TYPE (t)) && flag_argument_noalias > 0)
4168 varinfo_t vi;
4169 tree heapvar = heapvar_lookup (t);
4171 lhs.offset = 0;
4172 lhs.type = SCALAR;
4173 lhs.var = get_vi_for_tree (t)->id;
4175 if (heapvar == NULL_TREE)
4177 var_ann_t ann;
4178 heapvar = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (t)),
4179 "PARM_NOALIAS");
4180 DECL_EXTERNAL (heapvar) = 1;
4181 if (gimple_referenced_vars (cfun))
4182 add_referenced_var (heapvar);
4184 heapvar_insert (t, heapvar);
4186 ann = get_var_ann (heapvar);
4187 if (flag_argument_noalias == 1)
4188 ann->noalias_state = NO_ALIAS;
4189 else if (flag_argument_noalias == 2)
4190 ann->noalias_state = NO_ALIAS_GLOBAL;
4191 else if (flag_argument_noalias == 3)
4192 ann->noalias_state = NO_ALIAS_ANYTHING;
4193 else
4194 gcc_unreachable ();
4197 vi = get_vi_for_tree (heapvar);
4198 vi->is_artificial_var = 1;
4199 vi->is_heap_var = 1;
4200 rhs.var = vi->id;
4201 rhs.type = ADDRESSOF;
4202 rhs.offset = 0;
4203 for (p = get_varinfo (lhs.var); p; p = p->next)
4205 struct constraint_expr temp = lhs;
4206 temp.var = p->id;
4207 process_constraint (new_constraint (temp, rhs));
4210 else
4212 varinfo_t arg_vi = get_vi_for_tree (t);
4214 for (p = arg_vi; p; p = p->next)
4215 make_constraint_from_anything (p);
4220 /* Structure used to put solution bitmaps in a hashtable so they can
4221 be shared among variables with the same points-to set. */
4223 typedef struct shared_bitmap_info
4225 bitmap pt_vars;
4226 hashval_t hashcode;
4227 } *shared_bitmap_info_t;
4229 static htab_t shared_bitmap_table;
4231 /* Hash function for a shared_bitmap_info_t */
4233 static hashval_t
4234 shared_bitmap_hash (const void *p)
4236 const shared_bitmap_info_t bi = (shared_bitmap_info_t) p;
4237 return bi->hashcode;
4240 /* Equality function for two shared_bitmap_info_t's. */
4242 static int
4243 shared_bitmap_eq (const void *p1, const void *p2)
4245 const shared_bitmap_info_t sbi1 = (shared_bitmap_info_t) p1;
4246 const shared_bitmap_info_t sbi2 = (shared_bitmap_info_t) p2;
4247 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4250 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4251 existing instance if there is one, NULL otherwise. */
4253 static bitmap
4254 shared_bitmap_lookup (bitmap pt_vars)
4256 void **slot;
4257 struct shared_bitmap_info sbi;
4259 sbi.pt_vars = pt_vars;
4260 sbi.hashcode = bitmap_hash (pt_vars);
4262 slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4263 sbi.hashcode, NO_INSERT);
4264 if (!slot)
4265 return NULL;
4266 else
4267 return ((shared_bitmap_info_t) *slot)->pt_vars;
4271 /* Add a bitmap to the shared bitmap hashtable. */
4273 static void
4274 shared_bitmap_add (bitmap pt_vars)
4276 void **slot;
4277 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4279 sbi->pt_vars = pt_vars;
4280 sbi->hashcode = bitmap_hash (pt_vars);
4282 slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4283 sbi->hashcode, INSERT);
4284 gcc_assert (!*slot);
4285 *slot = (void *) sbi;
4289 /* Set bits in INTO corresponding to the variable uids in solution set
4290 FROM, which came from variable PTR.
4291 For variables that are actually dereferenced, we also use type
4292 based alias analysis to prune the points-to sets. */
4294 static void
4295 set_uids_in_ptset (tree ptr, bitmap into, bitmap from)
4297 unsigned int i;
4298 bitmap_iterator bi;
4299 subvar_t sv;
4300 HOST_WIDE_INT ptr_alias_set = get_alias_set (TREE_TYPE (ptr));
4302 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4304 varinfo_t vi = get_varinfo (i);
4305 unsigned HOST_WIDE_INT var_alias_set;
4307 /* The only artificial variables that are allowed in a may-alias
4308 set are heap variables. */
4309 if (vi->is_artificial_var && !vi->is_heap_var)
4310 continue;
4312 if (vi->has_union && get_subvars_for_var (vi->decl) != NULL)
4314 /* Variables containing unions may need to be converted to
4315 their SFT's, because SFT's can have unions and we cannot. */
4316 for (sv = get_subvars_for_var (vi->decl); sv; sv = sv->next)
4317 bitmap_set_bit (into, DECL_UID (sv->var));
4319 else if (TREE_CODE (vi->decl) == VAR_DECL
4320 || TREE_CODE (vi->decl) == PARM_DECL)
4322 if (var_can_have_subvars (vi->decl)
4323 && get_subvars_for_var (vi->decl))
4325 /* If VI->DECL is an aggregate for which we created
4326 SFTs, add the SFT corresponding to VI->OFFSET. */
4327 tree sft = get_subvar_at (vi->decl, vi->offset);
4328 if (sft)
4330 var_alias_set = get_alias_set (sft);
4331 if (!vi->directly_dereferenced
4332 || alias_sets_conflict_p (ptr_alias_set, var_alias_set))
4333 bitmap_set_bit (into, DECL_UID (sft));
4336 else
4338 /* Otherwise, just add VI->DECL to the alias set.
4339 Don't type prune artificial vars. */
4340 if (vi->is_artificial_var)
4341 bitmap_set_bit (into, DECL_UID (vi->decl));
4342 else
4344 var_alias_set = get_alias_set (vi->decl);
4345 if (!vi->directly_dereferenced
4346 || alias_sets_conflict_p (ptr_alias_set, var_alias_set))
4347 bitmap_set_bit (into, DECL_UID (vi->decl));
4355 static bool have_alias_info = false;
4357 /* The list of SMT's that are in use by our pointer variables. This
4358 is the set of SMT's for all pointers that can point to anything. */
4359 static bitmap used_smts;
4361 /* Due to the ordering of points-to set calculation and SMT
4362 calculation being a bit co-dependent, we can't just calculate SMT
4363 used info whenever we want, we have to calculate it around the time
4364 that find_what_p_points_to is called. */
4366 /* Mark which SMT's are in use by points-to anything variables. */
4368 void
4369 set_used_smts (void)
4371 int i;
4372 varinfo_t vi;
4373 used_smts = BITMAP_ALLOC (&pta_obstack);
4375 for (i = 0; VEC_iterate (varinfo_t, varmap, i, vi); i++)
4377 tree var = vi->decl;
4378 tree smt;
4379 var_ann_t va;
4380 struct ptr_info_def *pi = NULL;
4382 /* For parm decls, the pointer info may be under the default
4383 def. */
4384 if (TREE_CODE (vi->decl) == PARM_DECL
4385 && gimple_default_def (cfun, var))
4386 pi = SSA_NAME_PTR_INFO (gimple_default_def (cfun, var));
4387 else if (TREE_CODE (var) == SSA_NAME)
4388 pi = SSA_NAME_PTR_INFO (var);
4390 /* Skip the special variables and those without their own
4391 solution set. */
4392 if (vi->is_special_var || find (vi->id) != vi->id
4393 || !SSA_VAR_P (var)
4394 || (pi && !pi->is_dereferenced)
4395 || (TREE_CODE (var) == VAR_DECL && !may_be_aliased (var))
4396 || !POINTER_TYPE_P (TREE_TYPE (var)))
4397 continue;
4399 if (TREE_CODE (var) == SSA_NAME)
4400 var = SSA_NAME_VAR (var);
4402 va = var_ann (var);
4403 if (!va)
4404 continue;
4406 smt = va->symbol_mem_tag;
4407 if (smt && bitmap_bit_p (vi->solution, anything_id))
4408 bitmap_set_bit (used_smts, DECL_UID (smt));
4412 /* Merge the necessary SMT's into the bitmap INTO, which is
4413 P's varinfo. This involves merging all SMT's that are a subset of
4414 the SMT necessary for P. */
4416 static void
4417 merge_smts_into (tree p, bitmap solution)
4419 unsigned int i;
4420 bitmap_iterator bi;
4421 tree smt;
4422 bitmap aliases;
4423 tree var = p;
4425 if (TREE_CODE (p) == SSA_NAME)
4426 var = SSA_NAME_VAR (p);
4428 smt = var_ann (var)->symbol_mem_tag;
4429 if (smt)
4431 HOST_WIDE_INT smtset = get_alias_set (TREE_TYPE (smt));
4433 /* Need to set the SMT subsets first before this
4434 will work properly. */
4435 bitmap_set_bit (solution, DECL_UID (smt));
4436 EXECUTE_IF_SET_IN_BITMAP (used_smts, 0, i, bi)
4438 tree newsmt = referenced_var (i);
4439 tree newsmttype = TREE_TYPE (newsmt);
4441 if (alias_set_subset_of (get_alias_set (newsmttype),
4442 smtset))
4443 bitmap_set_bit (solution, i);
4446 aliases = MTAG_ALIASES (smt);
4447 if (aliases)
4448 bitmap_ior_into (solution, aliases);
4452 /* Given a pointer variable P, fill in its points-to set, or return
4453 false if we can't.
4454 Rather than return false for variables that point-to anything, we
4455 instead find the corresponding SMT, and merge in it's aliases. In
4456 addition to these aliases, we also set the bits for the SMT's
4457 themselves and their subsets, as SMT's are still in use by
4458 non-SSA_NAME's, and pruning may eliminate every one of their
4459 aliases. In such a case, if we did not include the right set of
4460 SMT's in the points-to set of the variable, we'd end up with
4461 statements that do not conflict but should. */
4463 bool
4464 find_what_p_points_to (tree p)
4466 tree lookup_p = p;
4467 varinfo_t vi;
4469 if (!have_alias_info)
4470 return false;
4472 /* For parameters, get at the points-to set for the actual parm
4473 decl. */
4474 if (TREE_CODE (p) == SSA_NAME
4475 && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4476 && SSA_NAME_IS_DEFAULT_DEF (p))
4477 lookup_p = SSA_NAME_VAR (p);
4479 vi = lookup_vi_for_tree (lookup_p);
4480 if (vi)
4482 if (vi->is_artificial_var)
4483 return false;
4485 /* See if this is a field or a structure. */
4486 if (vi->size != vi->fullsize)
4488 /* Nothing currently asks about structure fields directly,
4489 but when they do, we need code here to hand back the
4490 points-to set. */
4491 if (!var_can_have_subvars (vi->decl)
4492 || get_subvars_for_var (vi->decl) == NULL)
4493 return false;
4495 else
4497 struct ptr_info_def *pi = get_ptr_info (p);
4498 unsigned int i;
4499 bitmap_iterator bi;
4500 bool was_pt_anything = false;
4501 bitmap finished_solution;
4502 bitmap result;
4504 if (!pi->is_dereferenced)
4505 return false;
4507 /* This variable may have been collapsed, let's get the real
4508 variable. */
4509 vi = get_varinfo (find (vi->id));
4511 /* Translate artificial variables into SSA_NAME_PTR_INFO
4512 attributes. */
4513 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4515 varinfo_t vi = get_varinfo (i);
4517 if (vi->is_artificial_var)
4519 /* FIXME. READONLY should be handled better so that
4520 flow insensitive aliasing can disregard writable
4521 aliases. */
4522 if (vi->id == nothing_id)
4523 pi->pt_null = 1;
4524 else if (vi->id == anything_id)
4525 was_pt_anything = 1;
4526 else if (vi->id == readonly_id)
4527 was_pt_anything = 1;
4528 else if (vi->id == integer_id)
4529 was_pt_anything = 1;
4530 else if (vi->is_heap_var)
4531 pi->pt_global_mem = 1;
4535 /* Share the final set of variables when possible. */
4537 finished_solution = BITMAP_GGC_ALLOC ();
4538 stats.points_to_sets_created++;
4540 /* Instead of using pt_anything, we instead merge in the SMT
4541 aliases for the underlying SMT. */
4542 if (was_pt_anything)
4544 merge_smts_into (p, finished_solution);
4545 pi->pt_global_mem = 1;
4548 set_uids_in_ptset (vi->decl, finished_solution, vi->solution);
4549 result = shared_bitmap_lookup (finished_solution);
4551 if (!result)
4553 shared_bitmap_add (finished_solution);
4554 pi->pt_vars = finished_solution;
4556 else
4558 pi->pt_vars = result;
4559 bitmap_clear (finished_solution);
4562 if (bitmap_empty_p (pi->pt_vars))
4563 pi->pt_vars = NULL;
4565 return true;
4569 return false;
4574 /* Dump points-to information to OUTFILE. */
4576 void
4577 dump_sa_points_to_info (FILE *outfile)
4579 unsigned int i;
4581 fprintf (outfile, "\nPoints-to sets\n\n");
4583 if (dump_flags & TDF_STATS)
4585 fprintf (outfile, "Stats:\n");
4586 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
4587 fprintf (outfile, "Non-pointer vars: %d\n",
4588 stats.nonpointer_vars);
4589 fprintf (outfile, "Statically unified vars: %d\n",
4590 stats.unified_vars_static);
4591 fprintf (outfile, "Dynamically unified vars: %d\n",
4592 stats.unified_vars_dynamic);
4593 fprintf (outfile, "Iterations: %d\n", stats.iterations);
4594 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
4595 fprintf (outfile, "Number of implicit edges: %d\n",
4596 stats.num_implicit_edges);
4599 for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
4600 dump_solution_for_var (outfile, i);
4604 /* Debug points-to information to stderr. */
4606 void
4607 debug_sa_points_to_info (void)
4609 dump_sa_points_to_info (stderr);
4613 /* Initialize the always-existing constraint variables for NULL
4614 ANYTHING, READONLY, and INTEGER */
4616 static void
4617 init_base_vars (void)
4619 struct constraint_expr lhs, rhs;
4621 /* Create the NULL variable, used to represent that a variable points
4622 to NULL. */
4623 nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
4624 var_nothing = new_var_info (nothing_tree, 0, "NULL");
4625 insert_vi_for_tree (nothing_tree, var_nothing);
4626 var_nothing->is_artificial_var = 1;
4627 var_nothing->offset = 0;
4628 var_nothing->size = ~0;
4629 var_nothing->fullsize = ~0;
4630 var_nothing->is_special_var = 1;
4631 nothing_id = 0;
4632 VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
4634 /* Create the ANYTHING variable, used to represent that a variable
4635 points to some unknown piece of memory. */
4636 anything_tree = create_tmp_var_raw (void_type_node, "ANYTHING");
4637 var_anything = new_var_info (anything_tree, 1, "ANYTHING");
4638 insert_vi_for_tree (anything_tree, var_anything);
4639 var_anything->is_artificial_var = 1;
4640 var_anything->size = ~0;
4641 var_anything->offset = 0;
4642 var_anything->next = NULL;
4643 var_anything->fullsize = ~0;
4644 var_anything->is_special_var = 1;
4645 anything_id = 1;
4647 /* Anything points to anything. This makes deref constraints just
4648 work in the presence of linked list and other p = *p type loops,
4649 by saying that *ANYTHING = ANYTHING. */
4650 VEC_safe_push (varinfo_t, heap, varmap, var_anything);
4651 lhs.type = SCALAR;
4652 lhs.var = anything_id;
4653 lhs.offset = 0;
4654 rhs.type = ADDRESSOF;
4655 rhs.var = anything_id;
4656 rhs.offset = 0;
4658 /* This specifically does not use process_constraint because
4659 process_constraint ignores all anything = anything constraints, since all
4660 but this one are redundant. */
4661 VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
4663 /* Create the READONLY variable, used to represent that a variable
4664 points to readonly memory. */
4665 readonly_tree = create_tmp_var_raw (void_type_node, "READONLY");
4666 var_readonly = new_var_info (readonly_tree, 2, "READONLY");
4667 var_readonly->is_artificial_var = 1;
4668 var_readonly->offset = 0;
4669 var_readonly->size = ~0;
4670 var_readonly->fullsize = ~0;
4671 var_readonly->next = NULL;
4672 var_readonly->is_special_var = 1;
4673 insert_vi_for_tree (readonly_tree, var_readonly);
4674 readonly_id = 2;
4675 VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
4677 /* readonly memory points to anything, in order to make deref
4678 easier. In reality, it points to anything the particular
4679 readonly variable can point to, but we don't track this
4680 separately. */
4681 lhs.type = SCALAR;
4682 lhs.var = readonly_id;
4683 lhs.offset = 0;
4684 rhs.type = ADDRESSOF;
4685 rhs.var = anything_id;
4686 rhs.offset = 0;
4688 process_constraint (new_constraint (lhs, rhs));
4690 /* Create the INTEGER variable, used to represent that a variable points
4691 to an INTEGER. */
4692 integer_tree = create_tmp_var_raw (void_type_node, "INTEGER");
4693 var_integer = new_var_info (integer_tree, 3, "INTEGER");
4694 insert_vi_for_tree (integer_tree, var_integer);
4695 var_integer->is_artificial_var = 1;
4696 var_integer->size = ~0;
4697 var_integer->fullsize = ~0;
4698 var_integer->offset = 0;
4699 var_integer->next = NULL;
4700 var_integer->is_special_var = 1;
4701 integer_id = 3;
4702 VEC_safe_push (varinfo_t, heap, varmap, var_integer);
4704 /* INTEGER = ANYTHING, because we don't know where a dereference of
4705 a random integer will point to. */
4706 lhs.type = SCALAR;
4707 lhs.var = integer_id;
4708 lhs.offset = 0;
4709 rhs.type = ADDRESSOF;
4710 rhs.var = anything_id;
4711 rhs.offset = 0;
4712 process_constraint (new_constraint (lhs, rhs));
4715 /* Initialize things necessary to perform PTA */
4717 static void
4718 init_alias_vars (void)
4720 bitmap_obstack_initialize (&pta_obstack);
4721 bitmap_obstack_initialize (&oldpta_obstack);
4722 bitmap_obstack_initialize (&predbitmap_obstack);
4724 constraint_pool = create_alloc_pool ("Constraint pool",
4725 sizeof (struct constraint), 30);
4726 variable_info_pool = create_alloc_pool ("Variable info pool",
4727 sizeof (struct variable_info), 30);
4728 constraints = VEC_alloc (constraint_t, heap, 8);
4729 varmap = VEC_alloc (varinfo_t, heap, 8);
4730 vi_for_tree = pointer_map_create ();
4732 memset (&stats, 0, sizeof (stats));
4733 shared_bitmap_table = htab_create (511, shared_bitmap_hash,
4734 shared_bitmap_eq, free);
4735 init_base_vars ();
4738 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
4739 predecessor edges. */
4741 static void
4742 remove_preds_and_fake_succs (constraint_graph_t graph)
4744 unsigned int i;
4746 /* Clear the implicit ref and address nodes from the successor
4747 lists. */
4748 for (i = 0; i < FIRST_REF_NODE; i++)
4750 if (graph->succs[i])
4751 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
4752 FIRST_REF_NODE * 2);
4755 /* Free the successor list for the non-ref nodes. */
4756 for (i = FIRST_REF_NODE; i < graph->size; i++)
4758 if (graph->succs[i])
4759 BITMAP_FREE (graph->succs[i]);
4762 /* Now reallocate the size of the successor list as, and blow away
4763 the predecessor bitmaps. */
4764 graph->size = VEC_length (varinfo_t, varmap);
4765 graph->succs = xrealloc (graph->succs, graph->size * sizeof (bitmap));
4767 free (graph->implicit_preds);
4768 graph->implicit_preds = NULL;
4769 free (graph->preds);
4770 graph->preds = NULL;
4771 bitmap_obstack_release (&predbitmap_obstack);
4774 /* Create points-to sets for the current function. See the comments
4775 at the start of the file for an algorithmic overview. */
4777 void
4778 compute_points_to_sets (struct alias_info *ai)
4780 struct scc_info *si;
4781 basic_block bb;
4783 timevar_push (TV_TREE_PTA);
4785 init_alias_vars ();
4786 init_alias_heapvars ();
4788 intra_create_variable_infos ();
4790 /* Now walk all statements and derive aliases. */
4791 FOR_EACH_BB (bb)
4793 block_stmt_iterator bsi;
4794 tree phi;
4796 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
4798 if (is_gimple_reg (PHI_RESULT (phi)))
4800 find_func_aliases (phi);
4802 /* Update various related attributes like escaped
4803 addresses, pointer dereferences for loads and stores.
4804 This is used when creating name tags and alias
4805 sets. */
4806 update_alias_info (phi, ai);
4810 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4812 tree stmt = bsi_stmt (bsi);
4814 find_func_aliases (stmt);
4816 /* Update various related attributes like escaped
4817 addresses, pointer dereferences for loads and stores.
4818 This is used when creating name tags and alias
4819 sets. */
4820 update_alias_info (stmt, ai);
4825 if (dump_file)
4827 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
4828 dump_constraints (dump_file);
4831 if (dump_file)
4832 fprintf (dump_file,
4833 "\nCollapsing static cycles and doing variable "
4834 "substitution:\n");
4835 build_pred_graph ();
4836 si = perform_var_substitution (graph);
4837 move_complex_constraints (graph, si);
4838 free_var_substitution_info (si);
4840 build_succ_graph ();
4841 find_indirect_cycles (graph);
4843 /* Implicit nodes and predecessors are no longer necessary at this
4844 point. */
4845 remove_preds_and_fake_succs (graph);
4847 if (dump_file)
4848 fprintf (dump_file, "\nSolving graph:\n");
4850 solve_graph (graph);
4852 if (dump_file)
4853 dump_sa_points_to_info (dump_file);
4855 have_alias_info = true;
4857 timevar_pop (TV_TREE_PTA);
4861 /* Delete created points-to sets. */
4863 void
4864 delete_points_to_sets (void)
4866 varinfo_t v;
4867 int i;
4869 htab_delete (shared_bitmap_table);
4870 if (dump_file && (dump_flags & TDF_STATS))
4871 fprintf (dump_file, "Points to sets created:%d\n",
4872 stats.points_to_sets_created);
4874 pointer_map_destroy (vi_for_tree);
4875 bitmap_obstack_release (&pta_obstack);
4876 VEC_free (constraint_t, heap, constraints);
4878 for (i = 0; VEC_iterate (varinfo_t, varmap, i, v); i++)
4879 VEC_free (constraint_t, heap, graph->complex[i]);
4880 free (graph->complex);
4882 free (graph->rep);
4883 free (graph->succs);
4884 free (graph->indirect_cycles);
4885 free (graph);
4887 VEC_free (varinfo_t, heap, varmap);
4888 free_alloc_pool (variable_info_pool);
4889 free_alloc_pool (constraint_pool);
4890 have_alias_info = false;
4893 /* Return true if we should execute IPA PTA. */
4894 static bool
4895 gate_ipa_pta (void)
4897 return (flag_unit_at_a_time != 0
4898 && flag_ipa_pta
4899 /* Don't bother doing anything if the program has errors. */
4900 && !(errorcount || sorrycount));
4903 /* Execute the driver for IPA PTA. */
4904 static unsigned int
4905 ipa_pta_execute (void)
4907 struct cgraph_node *node;
4908 struct scc_info *si;
4910 in_ipa_mode = 1;
4911 init_alias_heapvars ();
4912 init_alias_vars ();
4914 for (node = cgraph_nodes; node; node = node->next)
4916 if (!node->analyzed || cgraph_is_master_clone (node))
4918 unsigned int varid;
4920 varid = create_function_info_for (node->decl,
4921 cgraph_node_name (node));
4922 if (node->local.externally_visible)
4924 varinfo_t fi = get_varinfo (varid);
4925 for (; fi; fi = fi->next)
4926 make_constraint_from_anything (fi);
4930 for (node = cgraph_nodes; node; node = node->next)
4932 if (node->analyzed && cgraph_is_master_clone (node))
4934 struct function *cfun = DECL_STRUCT_FUNCTION (node->decl);
4935 basic_block bb;
4936 tree old_func_decl = current_function_decl;
4937 if (dump_file)
4938 fprintf (dump_file,
4939 "Generating constraints for %s\n",
4940 cgraph_node_name (node));
4941 push_cfun (cfun);
4942 current_function_decl = node->decl;
4944 FOR_EACH_BB_FN (bb, cfun)
4946 block_stmt_iterator bsi;
4947 tree phi;
4949 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
4951 if (is_gimple_reg (PHI_RESULT (phi)))
4953 find_func_aliases (phi);
4957 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4959 tree stmt = bsi_stmt (bsi);
4960 find_func_aliases (stmt);
4963 current_function_decl = old_func_decl;
4964 pop_cfun ();
4966 else
4968 /* Make point to anything. */
4974 if (dump_file)
4976 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
4977 dump_constraints (dump_file);
4980 if (dump_file)
4981 fprintf (dump_file,
4982 "\nCollapsing static cycles and doing variable "
4983 "substitution:\n");
4985 build_pred_graph ();
4986 si = perform_var_substitution (graph);
4987 move_complex_constraints (graph, si);
4988 free_var_substitution_info (si);
4990 build_succ_graph ();
4991 find_indirect_cycles (graph);
4993 /* Implicit nodes and predecessors are no longer necessary at this
4994 point. */
4995 remove_preds_and_fake_succs (graph);
4997 if (dump_file)
4998 fprintf (dump_file, "\nSolving graph:\n");
5000 solve_graph (graph);
5002 if (dump_file)
5003 dump_sa_points_to_info (dump_file);
5005 in_ipa_mode = 0;
5006 delete_alias_heapvars ();
5007 delete_points_to_sets ();
5008 return 0;
5011 struct tree_opt_pass pass_ipa_pta =
5013 "pta", /* name */
5014 gate_ipa_pta, /* gate */
5015 ipa_pta_execute, /* execute */
5016 NULL, /* sub */
5017 NULL, /* next */
5018 0, /* static_pass_number */
5019 TV_IPA_PTA, /* tv_id */
5020 0, /* properties_required */
5021 0, /* properties_provided */
5022 0, /* properties_destroyed */
5023 0, /* todo_flags_start */
5024 0, /* todo_flags_finish */
5025 0 /* letter */
5028 /* Initialize the heapvar for statement mapping. */
5029 void
5030 init_alias_heapvars (void)
5032 if (!heapvar_for_stmt)
5033 heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
5034 NULL);
5037 void
5038 delete_alias_heapvars (void)
5040 htab_delete (heapvar_for_stmt);
5041 heapvar_for_stmt = NULL;
5045 #include "gt-tree-ssa-structalias.h"