[AArch64] PR target/68129: Define TARGET_SUPPORTS_WIDE_INT
[official-gcc.git] / gcc / tree-ssa-structalias.c
blobf24ebeba815b1629d1b41e97b010488c9b173bfb
1 /* Tree based points-to analysis
2 Copyright (C) 2005-2015 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 3 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; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "alloc-pool.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "tree-pretty-print.h"
33 #include "diagnostic-core.h"
34 #include "fold-const.h"
35 #include "stor-layout.h"
36 #include "stmt.h"
37 #include "gimple-iterator.h"
38 #include "tree-into-ssa.h"
39 #include "tree-dfa.h"
40 #include "params.h"
41 #include "gimple-walk.h"
43 /* The idea behind this analyzer is to generate set constraints from the
44 program, then solve the resulting constraints in order to generate the
45 points-to sets.
47 Set constraints are a way of modeling program analysis problems that
48 involve sets. They consist of an inclusion constraint language,
49 describing the variables (each variable is a set) and operations that
50 are involved on the variables, and a set of rules that derive facts
51 from these operations. To solve a system of set constraints, you derive
52 all possible facts under the rules, which gives you the correct sets
53 as a consequence.
55 See "Efficient Field-sensitive pointer analysis for C" by "David
56 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
57 http://citeseer.ist.psu.edu/pearce04efficient.html
59 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
60 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
61 http://citeseer.ist.psu.edu/heintze01ultrafast.html
63 There are three types of real constraint expressions, DEREF,
64 ADDRESSOF, and SCALAR. Each constraint expression consists
65 of a constraint type, a variable, and an offset.
67 SCALAR is a constraint expression type used to represent x, whether
68 it appears on the LHS or the RHS of a statement.
69 DEREF is a constraint expression type used to represent *x, whether
70 it appears on the LHS or the RHS of a statement.
71 ADDRESSOF is a constraint expression used to represent &x, whether
72 it appears on the LHS or the RHS of a statement.
74 Each pointer variable in the program is assigned an integer id, and
75 each field of a structure variable is assigned an integer id as well.
77 Structure variables are linked to their list of fields through a "next
78 field" in each variable that points to the next field in offset
79 order.
80 Each variable for a structure field has
82 1. "size", that tells the size in bits of that field.
83 2. "fullsize, that tells the size in bits of the entire structure.
84 3. "offset", that tells the offset in bits from the beginning of the
85 structure to this field.
87 Thus,
88 struct f
90 int a;
91 int b;
92 } foo;
93 int *bar;
95 looks like
97 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
98 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
99 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
102 In order to solve the system of set constraints, the following is
103 done:
105 1. Each constraint variable x has a solution set associated with it,
106 Sol(x).
108 2. Constraints are separated into direct, copy, and complex.
109 Direct constraints are ADDRESSOF constraints that require no extra
110 processing, such as P = &Q
111 Copy constraints are those of the form P = Q.
112 Complex constraints are all the constraints involving dereferences
113 and offsets (including offsetted copies).
115 3. All direct constraints of the form P = &Q are processed, such
116 that Q is added to Sol(P)
118 4. All complex constraints for a given constraint variable are stored in a
119 linked list attached to that variable's node.
121 5. A directed graph is built out of the copy constraints. Each
122 constraint variable is a node in the graph, and an edge from
123 Q to P is added for each copy constraint of the form P = Q
125 6. The graph is then walked, and solution sets are
126 propagated along the copy edges, such that an edge from Q to P
127 causes Sol(P) <- Sol(P) union Sol(Q).
129 7. As we visit each node, all complex constraints associated with
130 that node are processed by adding appropriate copy edges to the graph, or the
131 appropriate variables to the solution set.
133 8. The process of walking the graph is iterated until no solution
134 sets change.
136 Prior to walking the graph in steps 6 and 7, We perform static
137 cycle elimination on the constraint graph, as well
138 as off-line variable substitution.
140 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
141 on and turned into anything), but isn't. You can just see what offset
142 inside the pointed-to struct it's going to access.
144 TODO: Constant bounded arrays can be handled as if they were structs of the
145 same number of elements.
147 TODO: Modeling heap and incoming pointers becomes much better if we
148 add fields to them as we discover them, which we could do.
150 TODO: We could handle unions, but to be honest, it's probably not
151 worth the pain or slowdown. */
153 /* IPA-PTA optimizations possible.
155 When the indirect function called is ANYTHING we can add disambiguation
156 based on the function signatures (or simply the parameter count which
157 is the varinfo size). We also do not need to consider functions that
158 do not have their address taken.
160 The is_global_var bit which marks escape points is overly conservative
161 in IPA mode. Split it to is_escape_point and is_global_var - only
162 externally visible globals are escape points in IPA mode. This is
163 also needed to fix the pt_solution_includes_global predicate
164 (and thus ptr_deref_may_alias_global_p).
166 The way we introduce DECL_PT_UID to avoid fixing up all points-to
167 sets in the translation unit when we copy a DECL during inlining
168 pessimizes precision. The advantage is that the DECL_PT_UID keeps
169 compile-time and memory usage overhead low - the points-to sets
170 do not grow or get unshared as they would during a fixup phase.
171 An alternative solution is to delay IPA PTA until after all
172 inlining transformations have been applied.
174 The way we propagate clobber/use information isn't optimized.
175 It should use a new complex constraint that properly filters
176 out local variables of the callee (though that would make
177 the sets invalid after inlining). OTOH we might as well
178 admit defeat to WHOPR and simply do all the clobber/use analysis
179 and propagation after PTA finished but before we threw away
180 points-to information for memory variables. WHOPR and PTA
181 do not play along well anyway - the whole constraint solving
182 would need to be done in WPA phase and it will be very interesting
183 to apply the results to local SSA names during LTRANS phase.
185 We probably should compute a per-function unit-ESCAPE solution
186 propagating it simply like the clobber / uses solutions. The
187 solution can go alongside the non-IPA espaced solution and be
188 used to query which vars escape the unit through a function.
190 We never put function decls in points-to sets so we do not
191 keep the set of called functions for indirect calls.
193 And probably more. */
195 static bool use_field_sensitive = true;
196 static int in_ipa_mode = 0;
198 /* Used for predecessor bitmaps. */
199 static bitmap_obstack predbitmap_obstack;
201 /* Used for points-to sets. */
202 static bitmap_obstack pta_obstack;
204 /* Used for oldsolution members of variables. */
205 static bitmap_obstack oldpta_obstack;
207 /* Used for per-solver-iteration bitmaps. */
208 static bitmap_obstack iteration_obstack;
210 static unsigned int create_variable_info_for (tree, const char *, bool);
211 typedef struct constraint_graph *constraint_graph_t;
212 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
214 struct constraint;
215 typedef struct constraint *constraint_t;
218 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
219 if (a) \
220 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
222 static struct constraint_stats
224 unsigned int total_vars;
225 unsigned int nonpointer_vars;
226 unsigned int unified_vars_static;
227 unsigned int unified_vars_dynamic;
228 unsigned int iterations;
229 unsigned int num_edges;
230 unsigned int num_implicit_edges;
231 unsigned int points_to_sets_created;
232 } stats;
234 struct variable_info
236 /* ID of this variable */
237 unsigned int id;
239 /* True if this is a variable created by the constraint analysis, such as
240 heap variables and constraints we had to break up. */
241 unsigned int is_artificial_var : 1;
243 /* True if this is a special variable whose solution set should not be
244 changed. */
245 unsigned int is_special_var : 1;
247 /* True for variables whose size is not known or variable. */
248 unsigned int is_unknown_size_var : 1;
250 /* True for (sub-)fields that represent a whole variable. */
251 unsigned int is_full_var : 1;
253 /* True if this is a heap variable. */
254 unsigned int is_heap_var : 1;
256 /* True if this field may contain pointers. */
257 unsigned int may_have_pointers : 1;
259 /* True if this field has only restrict qualified pointers. */
260 unsigned int only_restrict_pointers : 1;
262 /* True if this represents a heap var created for a restrict qualified
263 pointer. */
264 unsigned int is_restrict_var : 1;
266 /* True if this represents a global variable. */
267 unsigned int is_global_var : 1;
269 /* True if this represents a IPA function info. */
270 unsigned int is_fn_info : 1;
272 /* ??? Store somewhere better. */
273 unsigned short ruid;
275 /* The ID of the variable for the next field in this structure
276 or zero for the last field in this structure. */
277 unsigned next;
279 /* The ID of the variable for the first field in this structure. */
280 unsigned head;
282 /* Offset of this variable, in bits, from the base variable */
283 unsigned HOST_WIDE_INT offset;
285 /* Size of the variable, in bits. */
286 unsigned HOST_WIDE_INT size;
288 /* Full size of the base variable, in bits. */
289 unsigned HOST_WIDE_INT fullsize;
291 /* Name of this variable */
292 const char *name;
294 /* Tree that this variable is associated with. */
295 tree decl;
297 /* Points-to set for this variable. */
298 bitmap solution;
300 /* Old points-to set for this variable. */
301 bitmap oldsolution;
303 typedef struct variable_info *varinfo_t;
305 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
306 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
307 unsigned HOST_WIDE_INT);
308 static varinfo_t lookup_vi_for_tree (tree);
309 static inline bool type_can_have_subvars (const_tree);
310 static void make_param_constraints (varinfo_t);
312 /* Pool of variable info structures. */
313 static object_allocator<variable_info> variable_info_pool
314 ("Variable info pool");
316 /* Map varinfo to final pt_solution. */
317 static hash_map<varinfo_t, pt_solution *> *final_solutions;
318 struct obstack final_solutions_obstack;
320 /* Table of variable info structures for constraint variables.
321 Indexed directly by variable info id. */
322 static vec<varinfo_t> varmap;
324 /* Return the varmap element N */
326 static inline varinfo_t
327 get_varinfo (unsigned int n)
329 return varmap[n];
332 /* Return the next variable in the list of sub-variables of VI
333 or NULL if VI is the last sub-variable. */
335 static inline varinfo_t
336 vi_next (varinfo_t vi)
338 return get_varinfo (vi->next);
341 /* Static IDs for the special variables. Variable ID zero is unused
342 and used as terminator for the sub-variable chain. */
343 enum { nothing_id = 1, anything_id = 2, string_id = 3,
344 escaped_id = 4, nonlocal_id = 5,
345 storedanything_id = 6, integer_id = 7 };
347 /* Return a new variable info structure consisting for a variable
348 named NAME, and using constraint graph node NODE. Append it
349 to the vector of variable info structures. */
351 static varinfo_t
352 new_var_info (tree t, const char *name, bool add_id)
354 unsigned index = varmap.length ();
355 varinfo_t ret = variable_info_pool.allocate ();
357 if (dump_file && add_id)
359 char *tempname = xasprintf ("%s(%d)", name, index);
360 name = ggc_strdup (tempname);
361 free (tempname);
364 ret->id = index;
365 ret->name = name;
366 ret->decl = t;
367 /* Vars without decl are artificial and do not have sub-variables. */
368 ret->is_artificial_var = (t == NULL_TREE);
369 ret->is_special_var = false;
370 ret->is_unknown_size_var = false;
371 ret->is_full_var = (t == NULL_TREE);
372 ret->is_heap_var = false;
373 ret->may_have_pointers = true;
374 ret->only_restrict_pointers = false;
375 ret->is_restrict_var = false;
376 ret->ruid = 0;
377 ret->is_global_var = (t == NULL_TREE);
378 ret->is_fn_info = false;
379 if (t && DECL_P (t))
380 ret->is_global_var = (is_global_var (t)
381 /* We have to treat even local register variables
382 as escape points. */
383 || (TREE_CODE (t) == VAR_DECL
384 && DECL_HARD_REGISTER (t)));
385 ret->solution = BITMAP_ALLOC (&pta_obstack);
386 ret->oldsolution = NULL;
387 ret->next = 0;
388 ret->head = ret->id;
390 stats.total_vars++;
392 varmap.safe_push (ret);
394 return ret;
397 /* A map mapping call statements to per-stmt variables for uses
398 and clobbers specific to the call. */
399 static hash_map<gimple *, varinfo_t> *call_stmt_vars;
401 /* Lookup or create the variable for the call statement CALL. */
403 static varinfo_t
404 get_call_vi (gcall *call)
406 varinfo_t vi, vi2;
408 bool existed;
409 varinfo_t *slot_p = &call_stmt_vars->get_or_insert (call, &existed);
410 if (existed)
411 return *slot_p;
413 vi = new_var_info (NULL_TREE, "CALLUSED", true);
414 vi->offset = 0;
415 vi->size = 1;
416 vi->fullsize = 2;
417 vi->is_full_var = true;
419 vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED", true);
420 vi2->offset = 1;
421 vi2->size = 1;
422 vi2->fullsize = 2;
423 vi2->is_full_var = true;
425 vi->next = vi2->id;
427 *slot_p = vi;
428 return vi;
431 /* Lookup the variable for the call statement CALL representing
432 the uses. Returns NULL if there is nothing special about this call. */
434 static varinfo_t
435 lookup_call_use_vi (gcall *call)
437 varinfo_t *slot_p = call_stmt_vars->get (call);
438 if (slot_p)
439 return *slot_p;
441 return NULL;
444 /* Lookup the variable for the call statement CALL representing
445 the clobbers. Returns NULL if there is nothing special about this call. */
447 static varinfo_t
448 lookup_call_clobber_vi (gcall *call)
450 varinfo_t uses = lookup_call_use_vi (call);
451 if (!uses)
452 return NULL;
454 return vi_next (uses);
457 /* Lookup or create the variable for the call statement CALL representing
458 the uses. */
460 static varinfo_t
461 get_call_use_vi (gcall *call)
463 return get_call_vi (call);
466 /* Lookup or create the variable for the call statement CALL representing
467 the clobbers. */
469 static varinfo_t ATTRIBUTE_UNUSED
470 get_call_clobber_vi (gcall *call)
472 return vi_next (get_call_vi (call));
476 enum constraint_expr_type {SCALAR, DEREF, ADDRESSOF};
478 /* An expression that appears in a constraint. */
480 struct constraint_expr
482 /* Constraint type. */
483 constraint_expr_type type;
485 /* Variable we are referring to in the constraint. */
486 unsigned int var;
488 /* Offset, in bits, of this constraint from the beginning of
489 variables it ends up referring to.
491 IOW, in a deref constraint, we would deref, get the result set,
492 then add OFFSET to each member. */
493 HOST_WIDE_INT offset;
496 /* Use 0x8000... as special unknown offset. */
497 #define UNKNOWN_OFFSET HOST_WIDE_INT_MIN
499 typedef struct constraint_expr ce_s;
500 static void get_constraint_for_1 (tree, vec<ce_s> *, bool, bool);
501 static void get_constraint_for (tree, vec<ce_s> *);
502 static void get_constraint_for_rhs (tree, vec<ce_s> *);
503 static void do_deref (vec<ce_s> *);
505 /* Our set constraints are made up of two constraint expressions, one
506 LHS, and one RHS.
508 As described in the introduction, our set constraints each represent an
509 operation between set valued variables.
511 struct constraint
513 struct constraint_expr lhs;
514 struct constraint_expr rhs;
517 /* List of constraints that we use to build the constraint graph from. */
519 static vec<constraint_t> constraints;
520 static object_allocator<constraint> constraint_pool ("Constraint pool");
522 /* The constraint graph is represented as an array of bitmaps
523 containing successor nodes. */
525 struct constraint_graph
527 /* Size of this graph, which may be different than the number of
528 nodes in the variable map. */
529 unsigned int size;
531 /* Explicit successors of each node. */
532 bitmap *succs;
534 /* Implicit predecessors of each node (Used for variable
535 substitution). */
536 bitmap *implicit_preds;
538 /* Explicit predecessors of each node (Used for variable substitution). */
539 bitmap *preds;
541 /* Indirect cycle representatives, or -1 if the node has no indirect
542 cycles. */
543 int *indirect_cycles;
545 /* Representative node for a node. rep[a] == a unless the node has
546 been unified. */
547 unsigned int *rep;
549 /* Equivalence class representative for a label. This is used for
550 variable substitution. */
551 int *eq_rep;
553 /* Pointer equivalence label for a node. All nodes with the same
554 pointer equivalence label can be unified together at some point
555 (either during constraint optimization or after the constraint
556 graph is built). */
557 unsigned int *pe;
559 /* Pointer equivalence representative for a label. This is used to
560 handle nodes that are pointer equivalent but not location
561 equivalent. We can unite these once the addressof constraints
562 are transformed into initial points-to sets. */
563 int *pe_rep;
565 /* Pointer equivalence label for each node, used during variable
566 substitution. */
567 unsigned int *pointer_label;
569 /* Location equivalence label for each node, used during location
570 equivalence finding. */
571 unsigned int *loc_label;
573 /* Pointed-by set for each node, used during location equivalence
574 finding. This is pointed-by rather than pointed-to, because it
575 is constructed using the predecessor graph. */
576 bitmap *pointed_by;
578 /* Points to sets for pointer equivalence. This is *not* the actual
579 points-to sets for nodes. */
580 bitmap *points_to;
582 /* Bitmap of nodes where the bit is set if the node is a direct
583 node. Used for variable substitution. */
584 sbitmap direct_nodes;
586 /* Bitmap of nodes where the bit is set if the node is address
587 taken. Used for variable substitution. */
588 bitmap address_taken;
590 /* Vector of complex constraints for each graph node. Complex
591 constraints are those involving dereferences or offsets that are
592 not 0. */
593 vec<constraint_t> *complex;
596 static constraint_graph_t graph;
598 /* During variable substitution and the offline version of indirect
599 cycle finding, we create nodes to represent dereferences and
600 address taken constraints. These represent where these start and
601 end. */
602 #define FIRST_REF_NODE (varmap).length ()
603 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
605 /* Return the representative node for NODE, if NODE has been unioned
606 with another NODE.
607 This function performs path compression along the way to finding
608 the representative. */
610 static unsigned int
611 find (unsigned int node)
613 gcc_checking_assert (node < graph->size);
614 if (graph->rep[node] != node)
615 return graph->rep[node] = find (graph->rep[node]);
616 return node;
619 /* Union the TO and FROM nodes to the TO nodes.
620 Note that at some point in the future, we may want to do
621 union-by-rank, in which case we are going to have to return the
622 node we unified to. */
624 static bool
625 unite (unsigned int to, unsigned int from)
627 gcc_checking_assert (to < graph->size && from < graph->size);
628 if (to != from && graph->rep[from] != to)
630 graph->rep[from] = to;
631 return true;
633 return false;
636 /* Create a new constraint consisting of LHS and RHS expressions. */
638 static constraint_t
639 new_constraint (const struct constraint_expr lhs,
640 const struct constraint_expr rhs)
642 constraint_t ret = constraint_pool.allocate ();
643 ret->lhs = lhs;
644 ret->rhs = rhs;
645 return ret;
648 /* Print out constraint C to FILE. */
650 static void
651 dump_constraint (FILE *file, constraint_t c)
653 if (c->lhs.type == ADDRESSOF)
654 fprintf (file, "&");
655 else if (c->lhs.type == DEREF)
656 fprintf (file, "*");
657 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
658 if (c->lhs.offset == UNKNOWN_OFFSET)
659 fprintf (file, " + UNKNOWN");
660 else if (c->lhs.offset != 0)
661 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
662 fprintf (file, " = ");
663 if (c->rhs.type == ADDRESSOF)
664 fprintf (file, "&");
665 else if (c->rhs.type == DEREF)
666 fprintf (file, "*");
667 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
668 if (c->rhs.offset == UNKNOWN_OFFSET)
669 fprintf (file, " + UNKNOWN");
670 else if (c->rhs.offset != 0)
671 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
675 void debug_constraint (constraint_t);
676 void debug_constraints (void);
677 void debug_constraint_graph (void);
678 void debug_solution_for_var (unsigned int);
679 void debug_sa_points_to_info (void);
681 /* Print out constraint C to stderr. */
683 DEBUG_FUNCTION void
684 debug_constraint (constraint_t c)
686 dump_constraint (stderr, c);
687 fprintf (stderr, "\n");
690 /* Print out all constraints to FILE */
692 static void
693 dump_constraints (FILE *file, int from)
695 int i;
696 constraint_t c;
697 for (i = from; constraints.iterate (i, &c); i++)
698 if (c)
700 dump_constraint (file, c);
701 fprintf (file, "\n");
705 /* Print out all constraints to stderr. */
707 DEBUG_FUNCTION void
708 debug_constraints (void)
710 dump_constraints (stderr, 0);
713 /* Print the constraint graph in dot format. */
715 static void
716 dump_constraint_graph (FILE *file)
718 unsigned int i;
720 /* Only print the graph if it has already been initialized: */
721 if (!graph)
722 return;
724 /* Prints the header of the dot file: */
725 fprintf (file, "strict digraph {\n");
726 fprintf (file, " node [\n shape = box\n ]\n");
727 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
728 fprintf (file, "\n // List of nodes and complex constraints in "
729 "the constraint graph:\n");
731 /* The next lines print the nodes in the graph together with the
732 complex constraints attached to them. */
733 for (i = 1; i < graph->size; i++)
735 if (i == FIRST_REF_NODE)
736 continue;
737 if (find (i) != i)
738 continue;
739 if (i < FIRST_REF_NODE)
740 fprintf (file, "\"%s\"", get_varinfo (i)->name);
741 else
742 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
743 if (graph->complex[i].exists ())
745 unsigned j;
746 constraint_t c;
747 fprintf (file, " [label=\"\\N\\n");
748 for (j = 0; graph->complex[i].iterate (j, &c); ++j)
750 dump_constraint (file, c);
751 fprintf (file, "\\l");
753 fprintf (file, "\"]");
755 fprintf (file, ";\n");
758 /* Go over the edges. */
759 fprintf (file, "\n // Edges in the constraint graph:\n");
760 for (i = 1; i < graph->size; i++)
762 unsigned j;
763 bitmap_iterator bi;
764 if (find (i) != i)
765 continue;
766 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
768 unsigned to = find (j);
769 if (i == to)
770 continue;
771 if (i < FIRST_REF_NODE)
772 fprintf (file, "\"%s\"", get_varinfo (i)->name);
773 else
774 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
775 fprintf (file, " -> ");
776 if (to < FIRST_REF_NODE)
777 fprintf (file, "\"%s\"", get_varinfo (to)->name);
778 else
779 fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
780 fprintf (file, ";\n");
784 /* Prints the tail of the dot file. */
785 fprintf (file, "}\n");
788 /* Print out the constraint graph to stderr. */
790 DEBUG_FUNCTION void
791 debug_constraint_graph (void)
793 dump_constraint_graph (stderr);
796 /* SOLVER FUNCTIONS
798 The solver is a simple worklist solver, that works on the following
799 algorithm:
801 sbitmap changed_nodes = all zeroes;
802 changed_count = 0;
803 For each node that is not already collapsed:
804 changed_count++;
805 set bit in changed nodes
807 while (changed_count > 0)
809 compute topological ordering for constraint graph
811 find and collapse cycles in the constraint graph (updating
812 changed if necessary)
814 for each node (n) in the graph in topological order:
815 changed_count--;
817 Process each complex constraint associated with the node,
818 updating changed if necessary.
820 For each outgoing edge from n, propagate the solution from n to
821 the destination of the edge, updating changed as necessary.
823 } */
825 /* Return true if two constraint expressions A and B are equal. */
827 static bool
828 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
830 return a.type == b.type && a.var == b.var && a.offset == b.offset;
833 /* Return true if constraint expression A is less than constraint expression
834 B. This is just arbitrary, but consistent, in order to give them an
835 ordering. */
837 static bool
838 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
840 if (a.type == b.type)
842 if (a.var == b.var)
843 return a.offset < b.offset;
844 else
845 return a.var < b.var;
847 else
848 return a.type < b.type;
851 /* Return true if constraint A is less than constraint B. This is just
852 arbitrary, but consistent, in order to give them an ordering. */
854 static bool
855 constraint_less (const constraint_t &a, const constraint_t &b)
857 if (constraint_expr_less (a->lhs, b->lhs))
858 return true;
859 else if (constraint_expr_less (b->lhs, a->lhs))
860 return false;
861 else
862 return constraint_expr_less (a->rhs, b->rhs);
865 /* Return true if two constraints A and B are equal. */
867 static bool
868 constraint_equal (struct constraint a, struct constraint b)
870 return constraint_expr_equal (a.lhs, b.lhs)
871 && constraint_expr_equal (a.rhs, b.rhs);
875 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
877 static constraint_t
878 constraint_vec_find (vec<constraint_t> vec,
879 struct constraint lookfor)
881 unsigned int place;
882 constraint_t found;
884 if (!vec.exists ())
885 return NULL;
887 place = vec.lower_bound (&lookfor, constraint_less);
888 if (place >= vec.length ())
889 return NULL;
890 found = vec[place];
891 if (!constraint_equal (*found, lookfor))
892 return NULL;
893 return found;
896 /* Union two constraint vectors, TO and FROM. Put the result in TO.
897 Returns true of TO set is changed. */
899 static bool
900 constraint_set_union (vec<constraint_t> *to,
901 vec<constraint_t> *from)
903 int i;
904 constraint_t c;
905 bool any_change = false;
907 FOR_EACH_VEC_ELT (*from, i, c)
909 if (constraint_vec_find (*to, *c) == NULL)
911 unsigned int place = to->lower_bound (c, constraint_less);
912 to->safe_insert (place, c);
913 any_change = true;
916 return any_change;
919 /* Expands the solution in SET to all sub-fields of variables included. */
921 static bitmap
922 solution_set_expand (bitmap set, bitmap *expanded)
924 bitmap_iterator bi;
925 unsigned j;
927 if (*expanded)
928 return *expanded;
930 *expanded = BITMAP_ALLOC (&iteration_obstack);
932 /* In a first pass expand to the head of the variables we need to
933 add all sub-fields off. This avoids quadratic behavior. */
934 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
936 varinfo_t v = get_varinfo (j);
937 if (v->is_artificial_var
938 || v->is_full_var)
939 continue;
940 bitmap_set_bit (*expanded, v->head);
943 /* In the second pass now expand all head variables with subfields. */
944 EXECUTE_IF_SET_IN_BITMAP (*expanded, 0, j, bi)
946 varinfo_t v = get_varinfo (j);
947 if (v->head != j)
948 continue;
949 for (v = vi_next (v); v != NULL; v = vi_next (v))
950 bitmap_set_bit (*expanded, v->id);
953 /* And finally set the rest of the bits from SET. */
954 bitmap_ior_into (*expanded, set);
956 return *expanded;
959 /* Union solution sets TO and DELTA, and add INC to each member of DELTA in the
960 process. */
962 static bool
963 set_union_with_increment (bitmap to, bitmap delta, HOST_WIDE_INT inc,
964 bitmap *expanded_delta)
966 bool changed = false;
967 bitmap_iterator bi;
968 unsigned int i;
970 /* If the solution of DELTA contains anything it is good enough to transfer
971 this to TO. */
972 if (bitmap_bit_p (delta, anything_id))
973 return bitmap_set_bit (to, anything_id);
975 /* If the offset is unknown we have to expand the solution to
976 all subfields. */
977 if (inc == UNKNOWN_OFFSET)
979 delta = solution_set_expand (delta, expanded_delta);
980 changed |= bitmap_ior_into (to, delta);
981 return changed;
984 /* For non-zero offset union the offsetted solution into the destination. */
985 EXECUTE_IF_SET_IN_BITMAP (delta, 0, i, bi)
987 varinfo_t vi = get_varinfo (i);
989 /* If this is a variable with just one field just set its bit
990 in the result. */
991 if (vi->is_artificial_var
992 || vi->is_unknown_size_var
993 || vi->is_full_var)
994 changed |= bitmap_set_bit (to, i);
995 else
997 HOST_WIDE_INT fieldoffset = vi->offset + inc;
998 unsigned HOST_WIDE_INT size = vi->size;
1000 /* If the offset makes the pointer point to before the
1001 variable use offset zero for the field lookup. */
1002 if (fieldoffset < 0)
1003 vi = get_varinfo (vi->head);
1004 else
1005 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1009 changed |= bitmap_set_bit (to, vi->id);
1010 if (vi->is_full_var
1011 || vi->next == 0)
1012 break;
1014 /* We have to include all fields that overlap the current field
1015 shifted by inc. */
1016 vi = vi_next (vi);
1018 while (vi->offset < fieldoffset + size);
1022 return changed;
1025 /* Insert constraint C into the list of complex constraints for graph
1026 node VAR. */
1028 static void
1029 insert_into_complex (constraint_graph_t graph,
1030 unsigned int var, constraint_t c)
1032 vec<constraint_t> complex = graph->complex[var];
1033 unsigned int place = complex.lower_bound (c, constraint_less);
1035 /* Only insert constraints that do not already exist. */
1036 if (place >= complex.length ()
1037 || !constraint_equal (*c, *complex[place]))
1038 graph->complex[var].safe_insert (place, c);
1042 /* Condense two variable nodes into a single variable node, by moving
1043 all associated info from FROM to TO. Returns true if TO node's
1044 constraint set changes after the merge. */
1046 static bool
1047 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1048 unsigned int from)
1050 unsigned int i;
1051 constraint_t c;
1052 bool any_change = false;
1054 gcc_checking_assert (find (from) == to);
1056 /* Move all complex constraints from src node into to node */
1057 FOR_EACH_VEC_ELT (graph->complex[from], i, c)
1059 /* In complex constraints for node FROM, we may have either
1060 a = *FROM, and *FROM = a, or an offseted constraint which are
1061 always added to the rhs node's constraints. */
1063 if (c->rhs.type == DEREF)
1064 c->rhs.var = to;
1065 else if (c->lhs.type == DEREF)
1066 c->lhs.var = to;
1067 else
1068 c->rhs.var = to;
1071 any_change = constraint_set_union (&graph->complex[to],
1072 &graph->complex[from]);
1073 graph->complex[from].release ();
1074 return any_change;
1078 /* Remove edges involving NODE from GRAPH. */
1080 static void
1081 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1083 if (graph->succs[node])
1084 BITMAP_FREE (graph->succs[node]);
1087 /* Merge GRAPH nodes FROM and TO into node TO. */
1089 static void
1090 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1091 unsigned int from)
1093 if (graph->indirect_cycles[from] != -1)
1095 /* If we have indirect cycles with the from node, and we have
1096 none on the to node, the to node has indirect cycles from the
1097 from node now that they are unified.
1098 If indirect cycles exist on both, unify the nodes that they
1099 are in a cycle with, since we know they are in a cycle with
1100 each other. */
1101 if (graph->indirect_cycles[to] == -1)
1102 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1105 /* Merge all the successor edges. */
1106 if (graph->succs[from])
1108 if (!graph->succs[to])
1109 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1110 bitmap_ior_into (graph->succs[to],
1111 graph->succs[from]);
1114 clear_edges_for_node (graph, from);
1118 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1119 it doesn't exist in the graph already. */
1121 static void
1122 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1123 unsigned int from)
1125 if (to == from)
1126 return;
1128 if (!graph->implicit_preds[to])
1129 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1131 if (bitmap_set_bit (graph->implicit_preds[to], from))
1132 stats.num_implicit_edges++;
1135 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1136 it doesn't exist in the graph already.
1137 Return false if the edge already existed, true otherwise. */
1139 static void
1140 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1141 unsigned int from)
1143 if (!graph->preds[to])
1144 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1145 bitmap_set_bit (graph->preds[to], from);
1148 /* Add a graph edge to GRAPH, going from FROM to TO if
1149 it doesn't exist in the graph already.
1150 Return false if the edge already existed, true otherwise. */
1152 static bool
1153 add_graph_edge (constraint_graph_t graph, unsigned int to,
1154 unsigned int from)
1156 if (to == from)
1158 return false;
1160 else
1162 bool r = false;
1164 if (!graph->succs[from])
1165 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1166 if (bitmap_set_bit (graph->succs[from], to))
1168 r = true;
1169 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1170 stats.num_edges++;
1172 return r;
1177 /* Initialize the constraint graph structure to contain SIZE nodes. */
1179 static void
1180 init_graph (unsigned int size)
1182 unsigned int j;
1184 graph = XCNEW (struct constraint_graph);
1185 graph->size = size;
1186 graph->succs = XCNEWVEC (bitmap, graph->size);
1187 graph->indirect_cycles = XNEWVEC (int, graph->size);
1188 graph->rep = XNEWVEC (unsigned int, graph->size);
1189 /* ??? Macros do not support template types with multiple arguments,
1190 so we use a typedef to work around it. */
1191 typedef vec<constraint_t> vec_constraint_t_heap;
1192 graph->complex = XCNEWVEC (vec_constraint_t_heap, size);
1193 graph->pe = XCNEWVEC (unsigned int, graph->size);
1194 graph->pe_rep = XNEWVEC (int, graph->size);
1196 for (j = 0; j < graph->size; j++)
1198 graph->rep[j] = j;
1199 graph->pe_rep[j] = -1;
1200 graph->indirect_cycles[j] = -1;
1204 /* Build the constraint graph, adding only predecessor edges right now. */
1206 static void
1207 build_pred_graph (void)
1209 int i;
1210 constraint_t c;
1211 unsigned int j;
1213 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1214 graph->preds = XCNEWVEC (bitmap, graph->size);
1215 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1216 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1217 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1218 graph->points_to = XCNEWVEC (bitmap, graph->size);
1219 graph->eq_rep = XNEWVEC (int, graph->size);
1220 graph->direct_nodes = sbitmap_alloc (graph->size);
1221 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1222 bitmap_clear (graph->direct_nodes);
1224 for (j = 1; j < FIRST_REF_NODE; j++)
1226 if (!get_varinfo (j)->is_special_var)
1227 bitmap_set_bit (graph->direct_nodes, j);
1230 for (j = 0; j < graph->size; j++)
1231 graph->eq_rep[j] = -1;
1233 for (j = 0; j < varmap.length (); j++)
1234 graph->indirect_cycles[j] = -1;
1236 FOR_EACH_VEC_ELT (constraints, i, c)
1238 struct constraint_expr lhs = c->lhs;
1239 struct constraint_expr rhs = c->rhs;
1240 unsigned int lhsvar = lhs.var;
1241 unsigned int rhsvar = rhs.var;
1243 if (lhs.type == DEREF)
1245 /* *x = y. */
1246 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1247 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1249 else if (rhs.type == DEREF)
1251 /* x = *y */
1252 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1253 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1254 else
1255 bitmap_clear_bit (graph->direct_nodes, lhsvar);
1257 else if (rhs.type == ADDRESSOF)
1259 varinfo_t v;
1261 /* x = &y */
1262 if (graph->points_to[lhsvar] == NULL)
1263 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1264 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1266 if (graph->pointed_by[rhsvar] == NULL)
1267 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1268 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1270 /* Implicitly, *x = y */
1271 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1273 /* All related variables are no longer direct nodes. */
1274 bitmap_clear_bit (graph->direct_nodes, rhsvar);
1275 v = get_varinfo (rhsvar);
1276 if (!v->is_full_var)
1278 v = get_varinfo (v->head);
1281 bitmap_clear_bit (graph->direct_nodes, v->id);
1282 v = vi_next (v);
1284 while (v != NULL);
1286 bitmap_set_bit (graph->address_taken, rhsvar);
1288 else if (lhsvar > anything_id
1289 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1291 /* x = y */
1292 add_pred_graph_edge (graph, lhsvar, rhsvar);
1293 /* Implicitly, *x = *y */
1294 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1295 FIRST_REF_NODE + rhsvar);
1297 else if (lhs.offset != 0 || rhs.offset != 0)
1299 if (rhs.offset != 0)
1300 bitmap_clear_bit (graph->direct_nodes, lhs.var);
1301 else if (lhs.offset != 0)
1302 bitmap_clear_bit (graph->direct_nodes, rhs.var);
1307 /* Build the constraint graph, adding successor edges. */
1309 static void
1310 build_succ_graph (void)
1312 unsigned i, t;
1313 constraint_t c;
1315 FOR_EACH_VEC_ELT (constraints, i, c)
1317 struct constraint_expr lhs;
1318 struct constraint_expr rhs;
1319 unsigned int lhsvar;
1320 unsigned int rhsvar;
1322 if (!c)
1323 continue;
1325 lhs = c->lhs;
1326 rhs = c->rhs;
1327 lhsvar = find (lhs.var);
1328 rhsvar = find (rhs.var);
1330 if (lhs.type == DEREF)
1332 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1333 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1335 else if (rhs.type == DEREF)
1337 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1338 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1340 else if (rhs.type == ADDRESSOF)
1342 /* x = &y */
1343 gcc_checking_assert (find (rhs.var) == rhs.var);
1344 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1346 else if (lhsvar > anything_id
1347 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1349 add_graph_edge (graph, lhsvar, rhsvar);
1353 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1354 receive pointers. */
1355 t = find (storedanything_id);
1356 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1358 if (!bitmap_bit_p (graph->direct_nodes, i)
1359 && get_varinfo (i)->may_have_pointers)
1360 add_graph_edge (graph, find (i), t);
1363 /* Everything stored to ANYTHING also potentially escapes. */
1364 add_graph_edge (graph, find (escaped_id), t);
1368 /* Changed variables on the last iteration. */
1369 static bitmap changed;
1371 /* Strongly Connected Component visitation info. */
1373 struct scc_info
1375 sbitmap visited;
1376 sbitmap deleted;
1377 unsigned int *dfs;
1378 unsigned int *node_mapping;
1379 int current_index;
1380 vec<unsigned> scc_stack;
1384 /* Recursive routine to find strongly connected components in GRAPH.
1385 SI is the SCC info to store the information in, and N is the id of current
1386 graph node we are processing.
1388 This is Tarjan's strongly connected component finding algorithm, as
1389 modified by Nuutila to keep only non-root nodes on the stack.
1390 The algorithm can be found in "On finding the strongly connected
1391 connected components in a directed graph" by Esko Nuutila and Eljas
1392 Soisalon-Soininen, in Information Processing Letters volume 49,
1393 number 1, pages 9-14. */
1395 static void
1396 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1398 unsigned int i;
1399 bitmap_iterator bi;
1400 unsigned int my_dfs;
1402 bitmap_set_bit (si->visited, n);
1403 si->dfs[n] = si->current_index ++;
1404 my_dfs = si->dfs[n];
1406 /* Visit all the successors. */
1407 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1409 unsigned int w;
1411 if (i > LAST_REF_NODE)
1412 break;
1414 w = find (i);
1415 if (bitmap_bit_p (si->deleted, w))
1416 continue;
1418 if (!bitmap_bit_p (si->visited, w))
1419 scc_visit (graph, si, w);
1421 unsigned int t = find (w);
1422 gcc_checking_assert (find (n) == n);
1423 if (si->dfs[t] < si->dfs[n])
1424 si->dfs[n] = si->dfs[t];
1427 /* See if any components have been identified. */
1428 if (si->dfs[n] == my_dfs)
1430 if (si->scc_stack.length () > 0
1431 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1433 bitmap scc = BITMAP_ALLOC (NULL);
1434 unsigned int lowest_node;
1435 bitmap_iterator bi;
1437 bitmap_set_bit (scc, n);
1439 while (si->scc_stack.length () != 0
1440 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1442 unsigned int w = si->scc_stack.pop ();
1444 bitmap_set_bit (scc, w);
1447 lowest_node = bitmap_first_set_bit (scc);
1448 gcc_assert (lowest_node < FIRST_REF_NODE);
1450 /* Collapse the SCC nodes into a single node, and mark the
1451 indirect cycles. */
1452 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1454 if (i < FIRST_REF_NODE)
1456 if (unite (lowest_node, i))
1457 unify_nodes (graph, lowest_node, i, false);
1459 else
1461 unite (lowest_node, i);
1462 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1466 bitmap_set_bit (si->deleted, n);
1468 else
1469 si->scc_stack.safe_push (n);
1472 /* Unify node FROM into node TO, updating the changed count if
1473 necessary when UPDATE_CHANGED is true. */
1475 static void
1476 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1477 bool update_changed)
1479 gcc_checking_assert (to != from && find (to) == to);
1481 if (dump_file && (dump_flags & TDF_DETAILS))
1482 fprintf (dump_file, "Unifying %s to %s\n",
1483 get_varinfo (from)->name,
1484 get_varinfo (to)->name);
1486 if (update_changed)
1487 stats.unified_vars_dynamic++;
1488 else
1489 stats.unified_vars_static++;
1491 merge_graph_nodes (graph, to, from);
1492 if (merge_node_constraints (graph, to, from))
1494 if (update_changed)
1495 bitmap_set_bit (changed, to);
1498 /* Mark TO as changed if FROM was changed. If TO was already marked
1499 as changed, decrease the changed count. */
1501 if (update_changed
1502 && bitmap_clear_bit (changed, from))
1503 bitmap_set_bit (changed, to);
1504 varinfo_t fromvi = get_varinfo (from);
1505 if (fromvi->solution)
1507 /* If the solution changes because of the merging, we need to mark
1508 the variable as changed. */
1509 varinfo_t tovi = get_varinfo (to);
1510 if (bitmap_ior_into (tovi->solution, fromvi->solution))
1512 if (update_changed)
1513 bitmap_set_bit (changed, to);
1516 BITMAP_FREE (fromvi->solution);
1517 if (fromvi->oldsolution)
1518 BITMAP_FREE (fromvi->oldsolution);
1520 if (stats.iterations > 0
1521 && tovi->oldsolution)
1522 BITMAP_FREE (tovi->oldsolution);
1524 if (graph->succs[to])
1525 bitmap_clear_bit (graph->succs[to], to);
1528 /* Information needed to compute the topological ordering of a graph. */
1530 struct topo_info
1532 /* sbitmap of visited nodes. */
1533 sbitmap visited;
1534 /* Array that stores the topological order of the graph, *in
1535 reverse*. */
1536 vec<unsigned> topo_order;
1540 /* Initialize and return a topological info structure. */
1542 static struct topo_info *
1543 init_topo_info (void)
1545 size_t size = graph->size;
1546 struct topo_info *ti = XNEW (struct topo_info);
1547 ti->visited = sbitmap_alloc (size);
1548 bitmap_clear (ti->visited);
1549 ti->topo_order.create (1);
1550 return ti;
1554 /* Free the topological sort info pointed to by TI. */
1556 static void
1557 free_topo_info (struct topo_info *ti)
1559 sbitmap_free (ti->visited);
1560 ti->topo_order.release ();
1561 free (ti);
1564 /* Visit the graph in topological order, and store the order in the
1565 topo_info structure. */
1567 static void
1568 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1569 unsigned int n)
1571 bitmap_iterator bi;
1572 unsigned int j;
1574 bitmap_set_bit (ti->visited, n);
1576 if (graph->succs[n])
1577 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1579 if (!bitmap_bit_p (ti->visited, j))
1580 topo_visit (graph, ti, j);
1583 ti->topo_order.safe_push (n);
1586 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1587 starting solution for y. */
1589 static void
1590 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1591 bitmap delta, bitmap *expanded_delta)
1593 unsigned int lhs = c->lhs.var;
1594 bool flag = false;
1595 bitmap sol = get_varinfo (lhs)->solution;
1596 unsigned int j;
1597 bitmap_iterator bi;
1598 HOST_WIDE_INT roffset = c->rhs.offset;
1600 /* Our IL does not allow this. */
1601 gcc_checking_assert (c->lhs.offset == 0);
1603 /* If the solution of Y contains anything it is good enough to transfer
1604 this to the LHS. */
1605 if (bitmap_bit_p (delta, anything_id))
1607 flag |= bitmap_set_bit (sol, anything_id);
1608 goto done;
1611 /* If we do not know at with offset the rhs is dereferenced compute
1612 the reachability set of DELTA, conservatively assuming it is
1613 dereferenced at all valid offsets. */
1614 if (roffset == UNKNOWN_OFFSET)
1616 delta = solution_set_expand (delta, expanded_delta);
1617 /* No further offset processing is necessary. */
1618 roffset = 0;
1621 /* For each variable j in delta (Sol(y)), add
1622 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1623 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1625 varinfo_t v = get_varinfo (j);
1626 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1627 unsigned HOST_WIDE_INT size = v->size;
1628 unsigned int t;
1630 if (v->is_full_var)
1632 else if (roffset != 0)
1634 if (fieldoffset < 0)
1635 v = get_varinfo (v->head);
1636 else
1637 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1640 /* We have to include all fields that overlap the current field
1641 shifted by roffset. */
1644 t = find (v->id);
1646 /* Adding edges from the special vars is pointless.
1647 They don't have sets that can change. */
1648 if (get_varinfo (t)->is_special_var)
1649 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1650 /* Merging the solution from ESCAPED needlessly increases
1651 the set. Use ESCAPED as representative instead. */
1652 else if (v->id == escaped_id)
1653 flag |= bitmap_set_bit (sol, escaped_id);
1654 else if (v->may_have_pointers
1655 && add_graph_edge (graph, lhs, t))
1656 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1658 if (v->is_full_var
1659 || v->next == 0)
1660 break;
1662 v = vi_next (v);
1664 while (v->offset < fieldoffset + size);
1667 done:
1668 /* If the LHS solution changed, mark the var as changed. */
1669 if (flag)
1671 get_varinfo (lhs)->solution = sol;
1672 bitmap_set_bit (changed, lhs);
1676 /* Process a constraint C that represents *(x + off) = y using DELTA
1677 as the starting solution for x. */
1679 static void
1680 do_ds_constraint (constraint_t c, bitmap delta, bitmap *expanded_delta)
1682 unsigned int rhs = c->rhs.var;
1683 bitmap sol = get_varinfo (rhs)->solution;
1684 unsigned int j;
1685 bitmap_iterator bi;
1686 HOST_WIDE_INT loff = c->lhs.offset;
1687 bool escaped_p = false;
1689 /* Our IL does not allow this. */
1690 gcc_checking_assert (c->rhs.offset == 0);
1692 /* If the solution of y contains ANYTHING simply use the ANYTHING
1693 solution. This avoids needlessly increasing the points-to sets. */
1694 if (bitmap_bit_p (sol, anything_id))
1695 sol = get_varinfo (find (anything_id))->solution;
1697 /* If the solution for x contains ANYTHING we have to merge the
1698 solution of y into all pointer variables which we do via
1699 STOREDANYTHING. */
1700 if (bitmap_bit_p (delta, anything_id))
1702 unsigned t = find (storedanything_id);
1703 if (add_graph_edge (graph, t, rhs))
1705 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1706 bitmap_set_bit (changed, t);
1708 return;
1711 /* If we do not know at with offset the rhs is dereferenced compute
1712 the reachability set of DELTA, conservatively assuming it is
1713 dereferenced at all valid offsets. */
1714 if (loff == UNKNOWN_OFFSET)
1716 delta = solution_set_expand (delta, expanded_delta);
1717 loff = 0;
1720 /* For each member j of delta (Sol(x)), add an edge from y to j and
1721 union Sol(y) into Sol(j) */
1722 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1724 varinfo_t v = get_varinfo (j);
1725 unsigned int t;
1726 HOST_WIDE_INT fieldoffset = v->offset + loff;
1727 unsigned HOST_WIDE_INT size = v->size;
1729 if (v->is_full_var)
1731 else if (loff != 0)
1733 if (fieldoffset < 0)
1734 v = get_varinfo (v->head);
1735 else
1736 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1739 /* We have to include all fields that overlap the current field
1740 shifted by loff. */
1743 if (v->may_have_pointers)
1745 /* If v is a global variable then this is an escape point. */
1746 if (v->is_global_var
1747 && !escaped_p)
1749 t = find (escaped_id);
1750 if (add_graph_edge (graph, t, rhs)
1751 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1752 bitmap_set_bit (changed, t);
1753 /* Enough to let rhs escape once. */
1754 escaped_p = true;
1757 if (v->is_special_var)
1758 break;
1760 t = find (v->id);
1761 if (add_graph_edge (graph, t, rhs)
1762 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1763 bitmap_set_bit (changed, t);
1766 if (v->is_full_var
1767 || v->next == 0)
1768 break;
1770 v = vi_next (v);
1772 while (v->offset < fieldoffset + size);
1776 /* Handle a non-simple (simple meaning requires no iteration),
1777 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1779 static void
1780 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta,
1781 bitmap *expanded_delta)
1783 if (c->lhs.type == DEREF)
1785 if (c->rhs.type == ADDRESSOF)
1787 gcc_unreachable ();
1789 else
1791 /* *x = y */
1792 do_ds_constraint (c, delta, expanded_delta);
1795 else if (c->rhs.type == DEREF)
1797 /* x = *y */
1798 if (!(get_varinfo (c->lhs.var)->is_special_var))
1799 do_sd_constraint (graph, c, delta, expanded_delta);
1801 else
1803 bitmap tmp;
1804 bool flag = false;
1806 gcc_checking_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR
1807 && c->rhs.offset != 0 && c->lhs.offset == 0);
1808 tmp = get_varinfo (c->lhs.var)->solution;
1810 flag = set_union_with_increment (tmp, delta, c->rhs.offset,
1811 expanded_delta);
1813 if (flag)
1814 bitmap_set_bit (changed, c->lhs.var);
1818 /* Initialize and return a new SCC info structure. */
1820 static struct scc_info *
1821 init_scc_info (size_t size)
1823 struct scc_info *si = XNEW (struct scc_info);
1824 size_t i;
1826 si->current_index = 0;
1827 si->visited = sbitmap_alloc (size);
1828 bitmap_clear (si->visited);
1829 si->deleted = sbitmap_alloc (size);
1830 bitmap_clear (si->deleted);
1831 si->node_mapping = XNEWVEC (unsigned int, size);
1832 si->dfs = XCNEWVEC (unsigned int, size);
1834 for (i = 0; i < size; i++)
1835 si->node_mapping[i] = i;
1837 si->scc_stack.create (1);
1838 return si;
1841 /* Free an SCC info structure pointed to by SI */
1843 static void
1844 free_scc_info (struct scc_info *si)
1846 sbitmap_free (si->visited);
1847 sbitmap_free (si->deleted);
1848 free (si->node_mapping);
1849 free (si->dfs);
1850 si->scc_stack.release ();
1851 free (si);
1855 /* Find indirect cycles in GRAPH that occur, using strongly connected
1856 components, and note them in the indirect cycles map.
1858 This technique comes from Ben Hardekopf and Calvin Lin,
1859 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1860 Lines of Code", submitted to PLDI 2007. */
1862 static void
1863 find_indirect_cycles (constraint_graph_t graph)
1865 unsigned int i;
1866 unsigned int size = graph->size;
1867 struct scc_info *si = init_scc_info (size);
1869 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1870 if (!bitmap_bit_p (si->visited, i) && find (i) == i)
1871 scc_visit (graph, si, i);
1873 free_scc_info (si);
1876 /* Compute a topological ordering for GRAPH, and store the result in the
1877 topo_info structure TI. */
1879 static void
1880 compute_topo_order (constraint_graph_t graph,
1881 struct topo_info *ti)
1883 unsigned int i;
1884 unsigned int size = graph->size;
1886 for (i = 0; i != size; ++i)
1887 if (!bitmap_bit_p (ti->visited, i) && find (i) == i)
1888 topo_visit (graph, ti, i);
1891 /* Structure used to for hash value numbering of pointer equivalence
1892 classes. */
1894 typedef struct equiv_class_label
1896 hashval_t hashcode;
1897 unsigned int equivalence_class;
1898 bitmap labels;
1899 } *equiv_class_label_t;
1900 typedef const struct equiv_class_label *const_equiv_class_label_t;
1902 /* Equiv_class_label hashtable helpers. */
1904 struct equiv_class_hasher : free_ptr_hash <equiv_class_label>
1906 static inline hashval_t hash (const equiv_class_label *);
1907 static inline bool equal (const equiv_class_label *,
1908 const equiv_class_label *);
1911 /* Hash function for a equiv_class_label_t */
1913 inline hashval_t
1914 equiv_class_hasher::hash (const equiv_class_label *ecl)
1916 return ecl->hashcode;
1919 /* Equality function for two equiv_class_label_t's. */
1921 inline bool
1922 equiv_class_hasher::equal (const equiv_class_label *eql1,
1923 const equiv_class_label *eql2)
1925 return (eql1->hashcode == eql2->hashcode
1926 && bitmap_equal_p (eql1->labels, eql2->labels));
1929 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1930 classes. */
1931 static hash_table<equiv_class_hasher> *pointer_equiv_class_table;
1933 /* A hashtable for mapping a bitmap of labels->location equivalence
1934 classes. */
1935 static hash_table<equiv_class_hasher> *location_equiv_class_table;
1937 /* Lookup a equivalence class in TABLE by the bitmap of LABELS with
1938 hash HAS it contains. Sets *REF_LABELS to the bitmap LABELS
1939 is equivalent to. */
1941 static equiv_class_label *
1942 equiv_class_lookup_or_add (hash_table<equiv_class_hasher> *table,
1943 bitmap labels)
1945 equiv_class_label **slot;
1946 equiv_class_label ecl;
1948 ecl.labels = labels;
1949 ecl.hashcode = bitmap_hash (labels);
1950 slot = table->find_slot (&ecl, INSERT);
1951 if (!*slot)
1953 *slot = XNEW (struct equiv_class_label);
1954 (*slot)->labels = labels;
1955 (*slot)->hashcode = ecl.hashcode;
1956 (*slot)->equivalence_class = 0;
1959 return *slot;
1962 /* Perform offline variable substitution.
1964 This is a worst case quadratic time way of identifying variables
1965 that must have equivalent points-to sets, including those caused by
1966 static cycles, and single entry subgraphs, in the constraint graph.
1968 The technique is described in "Exploiting Pointer and Location
1969 Equivalence to Optimize Pointer Analysis. In the 14th International
1970 Static Analysis Symposium (SAS), August 2007." It is known as the
1971 "HU" algorithm, and is equivalent to value numbering the collapsed
1972 constraint graph including evaluating unions.
1974 The general method of finding equivalence classes is as follows:
1975 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1976 Initialize all non-REF nodes to be direct nodes.
1977 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1978 variable}
1979 For each constraint containing the dereference, we also do the same
1980 thing.
1982 We then compute SCC's in the graph and unify nodes in the same SCC,
1983 including pts sets.
1985 For each non-collapsed node x:
1986 Visit all unvisited explicit incoming edges.
1987 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1988 where y->x.
1989 Lookup the equivalence class for pts(x).
1990 If we found one, equivalence_class(x) = found class.
1991 Otherwise, equivalence_class(x) = new class, and new_class is
1992 added to the lookup table.
1994 All direct nodes with the same equivalence class can be replaced
1995 with a single representative node.
1996 All unlabeled nodes (label == 0) are not pointers and all edges
1997 involving them can be eliminated.
1998 We perform these optimizations during rewrite_constraints
2000 In addition to pointer equivalence class finding, we also perform
2001 location equivalence class finding. This is the set of variables
2002 that always appear together in points-to sets. We use this to
2003 compress the size of the points-to sets. */
2005 /* Current maximum pointer equivalence class id. */
2006 static int pointer_equiv_class;
2008 /* Current maximum location equivalence class id. */
2009 static int location_equiv_class;
2011 /* Recursive routine to find strongly connected components in GRAPH,
2012 and label it's nodes with DFS numbers. */
2014 static void
2015 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2017 unsigned int i;
2018 bitmap_iterator bi;
2019 unsigned int my_dfs;
2021 gcc_checking_assert (si->node_mapping[n] == n);
2022 bitmap_set_bit (si->visited, n);
2023 si->dfs[n] = si->current_index ++;
2024 my_dfs = si->dfs[n];
2026 /* Visit all the successors. */
2027 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2029 unsigned int w = si->node_mapping[i];
2031 if (bitmap_bit_p (si->deleted, w))
2032 continue;
2034 if (!bitmap_bit_p (si->visited, w))
2035 condense_visit (graph, si, w);
2037 unsigned int t = si->node_mapping[w];
2038 gcc_checking_assert (si->node_mapping[n] == n);
2039 if (si->dfs[t] < si->dfs[n])
2040 si->dfs[n] = si->dfs[t];
2043 /* Visit all the implicit predecessors. */
2044 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2046 unsigned int w = si->node_mapping[i];
2048 if (bitmap_bit_p (si->deleted, w))
2049 continue;
2051 if (!bitmap_bit_p (si->visited, w))
2052 condense_visit (graph, si, w);
2054 unsigned int t = si->node_mapping[w];
2055 gcc_assert (si->node_mapping[n] == n);
2056 if (si->dfs[t] < si->dfs[n])
2057 si->dfs[n] = si->dfs[t];
2060 /* See if any components have been identified. */
2061 if (si->dfs[n] == my_dfs)
2063 while (si->scc_stack.length () != 0
2064 && si->dfs[si->scc_stack.last ()] >= my_dfs)
2066 unsigned int w = si->scc_stack.pop ();
2067 si->node_mapping[w] = n;
2069 if (!bitmap_bit_p (graph->direct_nodes, w))
2070 bitmap_clear_bit (graph->direct_nodes, n);
2072 /* Unify our nodes. */
2073 if (graph->preds[w])
2075 if (!graph->preds[n])
2076 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2077 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2079 if (graph->implicit_preds[w])
2081 if (!graph->implicit_preds[n])
2082 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2083 bitmap_ior_into (graph->implicit_preds[n],
2084 graph->implicit_preds[w]);
2086 if (graph->points_to[w])
2088 if (!graph->points_to[n])
2089 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2090 bitmap_ior_into (graph->points_to[n],
2091 graph->points_to[w]);
2094 bitmap_set_bit (si->deleted, n);
2096 else
2097 si->scc_stack.safe_push (n);
2100 /* Label pointer equivalences.
2102 This performs a value numbering of the constraint graph to
2103 discover which variables will always have the same points-to sets
2104 under the current set of constraints.
2106 The way it value numbers is to store the set of points-to bits
2107 generated by the constraints and graph edges. This is just used as a
2108 hash and equality comparison. The *actual set of points-to bits* is
2109 completely irrelevant, in that we don't care about being able to
2110 extract them later.
2112 The equality values (currently bitmaps) just have to satisfy a few
2113 constraints, the main ones being:
2114 1. The combining operation must be order independent.
2115 2. The end result of a given set of operations must be unique iff the
2116 combination of input values is unique
2117 3. Hashable. */
2119 static void
2120 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2122 unsigned int i, first_pred;
2123 bitmap_iterator bi;
2125 bitmap_set_bit (si->visited, n);
2127 /* Label and union our incoming edges's points to sets. */
2128 first_pred = -1U;
2129 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2131 unsigned int w = si->node_mapping[i];
2132 if (!bitmap_bit_p (si->visited, w))
2133 label_visit (graph, si, w);
2135 /* Skip unused edges */
2136 if (w == n || graph->pointer_label[w] == 0)
2137 continue;
2139 if (graph->points_to[w])
2141 if (!graph->points_to[n])
2143 if (first_pred == -1U)
2144 first_pred = w;
2145 else
2147 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2148 bitmap_ior (graph->points_to[n],
2149 graph->points_to[first_pred],
2150 graph->points_to[w]);
2153 else
2154 bitmap_ior_into (graph->points_to[n], graph->points_to[w]);
2158 /* Indirect nodes get fresh variables and a new pointer equiv class. */
2159 if (!bitmap_bit_p (graph->direct_nodes, n))
2161 if (!graph->points_to[n])
2163 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2164 if (first_pred != -1U)
2165 bitmap_copy (graph->points_to[n], graph->points_to[first_pred]);
2167 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2168 graph->pointer_label[n] = pointer_equiv_class++;
2169 equiv_class_label_t ecl;
2170 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2171 graph->points_to[n]);
2172 ecl->equivalence_class = graph->pointer_label[n];
2173 return;
2176 /* If there was only a single non-empty predecessor the pointer equiv
2177 class is the same. */
2178 if (!graph->points_to[n])
2180 if (first_pred != -1U)
2182 graph->pointer_label[n] = graph->pointer_label[first_pred];
2183 graph->points_to[n] = graph->points_to[first_pred];
2185 return;
2188 if (!bitmap_empty_p (graph->points_to[n]))
2190 equiv_class_label_t ecl;
2191 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2192 graph->points_to[n]);
2193 if (ecl->equivalence_class == 0)
2194 ecl->equivalence_class = pointer_equiv_class++;
2195 else
2197 BITMAP_FREE (graph->points_to[n]);
2198 graph->points_to[n] = ecl->labels;
2200 graph->pointer_label[n] = ecl->equivalence_class;
2204 /* Print the pred graph in dot format. */
2206 static void
2207 dump_pred_graph (struct scc_info *si, FILE *file)
2209 unsigned int i;
2211 /* Only print the graph if it has already been initialized: */
2212 if (!graph)
2213 return;
2215 /* Prints the header of the dot file: */
2216 fprintf (file, "strict digraph {\n");
2217 fprintf (file, " node [\n shape = box\n ]\n");
2218 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
2219 fprintf (file, "\n // List of nodes and complex constraints in "
2220 "the constraint graph:\n");
2222 /* The next lines print the nodes in the graph together with the
2223 complex constraints attached to them. */
2224 for (i = 1; i < graph->size; i++)
2226 if (i == FIRST_REF_NODE)
2227 continue;
2228 if (si->node_mapping[i] != i)
2229 continue;
2230 if (i < FIRST_REF_NODE)
2231 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2232 else
2233 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2234 if (graph->points_to[i]
2235 && !bitmap_empty_p (graph->points_to[i]))
2237 fprintf (file, "[label=\"%s = {", get_varinfo (i)->name);
2238 unsigned j;
2239 bitmap_iterator bi;
2240 EXECUTE_IF_SET_IN_BITMAP (graph->points_to[i], 0, j, bi)
2241 fprintf (file, " %d", j);
2242 fprintf (file, " }\"]");
2244 fprintf (file, ";\n");
2247 /* Go over the edges. */
2248 fprintf (file, "\n // Edges in the constraint graph:\n");
2249 for (i = 1; i < graph->size; i++)
2251 unsigned j;
2252 bitmap_iterator bi;
2253 if (si->node_mapping[i] != i)
2254 continue;
2255 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[i], 0, j, bi)
2257 unsigned from = si->node_mapping[j];
2258 if (from < FIRST_REF_NODE)
2259 fprintf (file, "\"%s\"", get_varinfo (from)->name);
2260 else
2261 fprintf (file, "\"*%s\"", get_varinfo (from - FIRST_REF_NODE)->name);
2262 fprintf (file, " -> ");
2263 if (i < FIRST_REF_NODE)
2264 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2265 else
2266 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2267 fprintf (file, ";\n");
2271 /* Prints the tail of the dot file. */
2272 fprintf (file, "}\n");
2275 /* Perform offline variable substitution, discovering equivalence
2276 classes, and eliminating non-pointer variables. */
2278 static struct scc_info *
2279 perform_var_substitution (constraint_graph_t graph)
2281 unsigned int i;
2282 unsigned int size = graph->size;
2283 struct scc_info *si = init_scc_info (size);
2285 bitmap_obstack_initialize (&iteration_obstack);
2286 pointer_equiv_class_table = new hash_table<equiv_class_hasher> (511);
2287 location_equiv_class_table
2288 = new hash_table<equiv_class_hasher> (511);
2289 pointer_equiv_class = 1;
2290 location_equiv_class = 1;
2292 /* Condense the nodes, which means to find SCC's, count incoming
2293 predecessors, and unite nodes in SCC's. */
2294 for (i = 1; i < FIRST_REF_NODE; i++)
2295 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2296 condense_visit (graph, si, si->node_mapping[i]);
2298 if (dump_file && (dump_flags & TDF_GRAPH))
2300 fprintf (dump_file, "\n\n// The constraint graph before var-substitution "
2301 "in dot format:\n");
2302 dump_pred_graph (si, dump_file);
2303 fprintf (dump_file, "\n\n");
2306 bitmap_clear (si->visited);
2307 /* Actually the label the nodes for pointer equivalences */
2308 for (i = 1; i < FIRST_REF_NODE; i++)
2309 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2310 label_visit (graph, si, si->node_mapping[i]);
2312 /* Calculate location equivalence labels. */
2313 for (i = 1; i < FIRST_REF_NODE; i++)
2315 bitmap pointed_by;
2316 bitmap_iterator bi;
2317 unsigned int j;
2319 if (!graph->pointed_by[i])
2320 continue;
2321 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2323 /* Translate the pointed-by mapping for pointer equivalence
2324 labels. */
2325 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2327 bitmap_set_bit (pointed_by,
2328 graph->pointer_label[si->node_mapping[j]]);
2330 /* The original pointed_by is now dead. */
2331 BITMAP_FREE (graph->pointed_by[i]);
2333 /* Look up the location equivalence label if one exists, or make
2334 one otherwise. */
2335 equiv_class_label_t ecl;
2336 ecl = equiv_class_lookup_or_add (location_equiv_class_table, pointed_by);
2337 if (ecl->equivalence_class == 0)
2338 ecl->equivalence_class = location_equiv_class++;
2339 else
2341 if (dump_file && (dump_flags & TDF_DETAILS))
2342 fprintf (dump_file, "Found location equivalence for node %s\n",
2343 get_varinfo (i)->name);
2344 BITMAP_FREE (pointed_by);
2346 graph->loc_label[i] = ecl->equivalence_class;
2350 if (dump_file && (dump_flags & TDF_DETAILS))
2351 for (i = 1; i < FIRST_REF_NODE; i++)
2353 unsigned j = si->node_mapping[i];
2354 if (j != i)
2356 fprintf (dump_file, "%s node id %d ",
2357 bitmap_bit_p (graph->direct_nodes, i)
2358 ? "Direct" : "Indirect", i);
2359 if (i < FIRST_REF_NODE)
2360 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2361 else
2362 fprintf (dump_file, "\"*%s\"",
2363 get_varinfo (i - FIRST_REF_NODE)->name);
2364 fprintf (dump_file, " mapped to SCC leader node id %d ", j);
2365 if (j < FIRST_REF_NODE)
2366 fprintf (dump_file, "\"%s\"\n", get_varinfo (j)->name);
2367 else
2368 fprintf (dump_file, "\"*%s\"\n",
2369 get_varinfo (j - FIRST_REF_NODE)->name);
2371 else
2373 fprintf (dump_file,
2374 "Equivalence classes for %s node id %d ",
2375 bitmap_bit_p (graph->direct_nodes, i)
2376 ? "direct" : "indirect", i);
2377 if (i < FIRST_REF_NODE)
2378 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2379 else
2380 fprintf (dump_file, "\"*%s\"",
2381 get_varinfo (i - FIRST_REF_NODE)->name);
2382 fprintf (dump_file,
2383 ": pointer %d, location %d\n",
2384 graph->pointer_label[i], graph->loc_label[i]);
2388 /* Quickly eliminate our non-pointer variables. */
2390 for (i = 1; i < FIRST_REF_NODE; i++)
2392 unsigned int node = si->node_mapping[i];
2394 if (graph->pointer_label[node] == 0)
2396 if (dump_file && (dump_flags & TDF_DETAILS))
2397 fprintf (dump_file,
2398 "%s is a non-pointer variable, eliminating edges.\n",
2399 get_varinfo (node)->name);
2400 stats.nonpointer_vars++;
2401 clear_edges_for_node (graph, node);
2405 return si;
2408 /* Free information that was only necessary for variable
2409 substitution. */
2411 static void
2412 free_var_substitution_info (struct scc_info *si)
2414 free_scc_info (si);
2415 free (graph->pointer_label);
2416 free (graph->loc_label);
2417 free (graph->pointed_by);
2418 free (graph->points_to);
2419 free (graph->eq_rep);
2420 sbitmap_free (graph->direct_nodes);
2421 delete pointer_equiv_class_table;
2422 pointer_equiv_class_table = NULL;
2423 delete location_equiv_class_table;
2424 location_equiv_class_table = NULL;
2425 bitmap_obstack_release (&iteration_obstack);
2428 /* Return an existing node that is equivalent to NODE, which has
2429 equivalence class LABEL, if one exists. Return NODE otherwise. */
2431 static unsigned int
2432 find_equivalent_node (constraint_graph_t graph,
2433 unsigned int node, unsigned int label)
2435 /* If the address version of this variable is unused, we can
2436 substitute it for anything else with the same label.
2437 Otherwise, we know the pointers are equivalent, but not the
2438 locations, and we can unite them later. */
2440 if (!bitmap_bit_p (graph->address_taken, node))
2442 gcc_checking_assert (label < graph->size);
2444 if (graph->eq_rep[label] != -1)
2446 /* Unify the two variables since we know they are equivalent. */
2447 if (unite (graph->eq_rep[label], node))
2448 unify_nodes (graph, graph->eq_rep[label], node, false);
2449 return graph->eq_rep[label];
2451 else
2453 graph->eq_rep[label] = node;
2454 graph->pe_rep[label] = node;
2457 else
2459 gcc_checking_assert (label < graph->size);
2460 graph->pe[node] = label;
2461 if (graph->pe_rep[label] == -1)
2462 graph->pe_rep[label] = node;
2465 return node;
2468 /* Unite pointer equivalent but not location equivalent nodes in
2469 GRAPH. This may only be performed once variable substitution is
2470 finished. */
2472 static void
2473 unite_pointer_equivalences (constraint_graph_t graph)
2475 unsigned int i;
2477 /* Go through the pointer equivalences and unite them to their
2478 representative, if they aren't already. */
2479 for (i = 1; i < FIRST_REF_NODE; i++)
2481 unsigned int label = graph->pe[i];
2482 if (label)
2484 int label_rep = graph->pe_rep[label];
2486 if (label_rep == -1)
2487 continue;
2489 label_rep = find (label_rep);
2490 if (label_rep >= 0 && unite (label_rep, find (i)))
2491 unify_nodes (graph, label_rep, i, false);
2496 /* Move complex constraints to the GRAPH nodes they belong to. */
2498 static void
2499 move_complex_constraints (constraint_graph_t graph)
2501 int i;
2502 constraint_t c;
2504 FOR_EACH_VEC_ELT (constraints, i, c)
2506 if (c)
2508 struct constraint_expr lhs = c->lhs;
2509 struct constraint_expr rhs = c->rhs;
2511 if (lhs.type == DEREF)
2513 insert_into_complex (graph, lhs.var, c);
2515 else if (rhs.type == DEREF)
2517 if (!(get_varinfo (lhs.var)->is_special_var))
2518 insert_into_complex (graph, rhs.var, c);
2520 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2521 && (lhs.offset != 0 || rhs.offset != 0))
2523 insert_into_complex (graph, rhs.var, c);
2530 /* Optimize and rewrite complex constraints while performing
2531 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2532 result of perform_variable_substitution. */
2534 static void
2535 rewrite_constraints (constraint_graph_t graph,
2536 struct scc_info *si)
2538 int i;
2539 constraint_t c;
2541 if (flag_checking)
2543 for (unsigned int j = 0; j < graph->size; j++)
2544 gcc_assert (find (j) == j);
2547 FOR_EACH_VEC_ELT (constraints, i, c)
2549 struct constraint_expr lhs = c->lhs;
2550 struct constraint_expr rhs = c->rhs;
2551 unsigned int lhsvar = find (lhs.var);
2552 unsigned int rhsvar = find (rhs.var);
2553 unsigned int lhsnode, rhsnode;
2554 unsigned int lhslabel, rhslabel;
2556 lhsnode = si->node_mapping[lhsvar];
2557 rhsnode = si->node_mapping[rhsvar];
2558 lhslabel = graph->pointer_label[lhsnode];
2559 rhslabel = graph->pointer_label[rhsnode];
2561 /* See if it is really a non-pointer variable, and if so, ignore
2562 the constraint. */
2563 if (lhslabel == 0)
2565 if (dump_file && (dump_flags & TDF_DETAILS))
2568 fprintf (dump_file, "%s is a non-pointer variable,"
2569 "ignoring constraint:",
2570 get_varinfo (lhs.var)->name);
2571 dump_constraint (dump_file, c);
2572 fprintf (dump_file, "\n");
2574 constraints[i] = NULL;
2575 continue;
2578 if (rhslabel == 0)
2580 if (dump_file && (dump_flags & TDF_DETAILS))
2583 fprintf (dump_file, "%s is a non-pointer variable,"
2584 "ignoring constraint:",
2585 get_varinfo (rhs.var)->name);
2586 dump_constraint (dump_file, c);
2587 fprintf (dump_file, "\n");
2589 constraints[i] = NULL;
2590 continue;
2593 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2594 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2595 c->lhs.var = lhsvar;
2596 c->rhs.var = rhsvar;
2600 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2601 part of an SCC, false otherwise. */
2603 static bool
2604 eliminate_indirect_cycles (unsigned int node)
2606 if (graph->indirect_cycles[node] != -1
2607 && !bitmap_empty_p (get_varinfo (node)->solution))
2609 unsigned int i;
2610 auto_vec<unsigned> queue;
2611 int queuepos;
2612 unsigned int to = find (graph->indirect_cycles[node]);
2613 bitmap_iterator bi;
2615 /* We can't touch the solution set and call unify_nodes
2616 at the same time, because unify_nodes is going to do
2617 bitmap unions into it. */
2619 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2621 if (find (i) == i && i != to)
2623 if (unite (to, i))
2624 queue.safe_push (i);
2628 for (queuepos = 0;
2629 queue.iterate (queuepos, &i);
2630 queuepos++)
2632 unify_nodes (graph, to, i, true);
2634 return true;
2636 return false;
2639 /* Solve the constraint graph GRAPH using our worklist solver.
2640 This is based on the PW* family of solvers from the "Efficient Field
2641 Sensitive Pointer Analysis for C" paper.
2642 It works by iterating over all the graph nodes, processing the complex
2643 constraints and propagating the copy constraints, until everything stops
2644 changed. This corresponds to steps 6-8 in the solving list given above. */
2646 static void
2647 solve_graph (constraint_graph_t graph)
2649 unsigned int size = graph->size;
2650 unsigned int i;
2651 bitmap pts;
2653 changed = BITMAP_ALLOC (NULL);
2655 /* Mark all initial non-collapsed nodes as changed. */
2656 for (i = 1; i < size; i++)
2658 varinfo_t ivi = get_varinfo (i);
2659 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2660 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2661 || graph->complex[i].length () > 0))
2662 bitmap_set_bit (changed, i);
2665 /* Allocate a bitmap to be used to store the changed bits. */
2666 pts = BITMAP_ALLOC (&pta_obstack);
2668 while (!bitmap_empty_p (changed))
2670 unsigned int i;
2671 struct topo_info *ti = init_topo_info ();
2672 stats.iterations++;
2674 bitmap_obstack_initialize (&iteration_obstack);
2676 compute_topo_order (graph, ti);
2678 while (ti->topo_order.length () != 0)
2681 i = ti->topo_order.pop ();
2683 /* If this variable is not a representative, skip it. */
2684 if (find (i) != i)
2685 continue;
2687 /* In certain indirect cycle cases, we may merge this
2688 variable to another. */
2689 if (eliminate_indirect_cycles (i) && find (i) != i)
2690 continue;
2692 /* If the node has changed, we need to process the
2693 complex constraints and outgoing edges again. */
2694 if (bitmap_clear_bit (changed, i))
2696 unsigned int j;
2697 constraint_t c;
2698 bitmap solution;
2699 vec<constraint_t> complex = graph->complex[i];
2700 varinfo_t vi = get_varinfo (i);
2701 bool solution_empty;
2703 /* Compute the changed set of solution bits. If anything
2704 is in the solution just propagate that. */
2705 if (bitmap_bit_p (vi->solution, anything_id))
2707 /* If anything is also in the old solution there is
2708 nothing to do.
2709 ??? But we shouldn't ended up with "changed" set ... */
2710 if (vi->oldsolution
2711 && bitmap_bit_p (vi->oldsolution, anything_id))
2712 continue;
2713 bitmap_copy (pts, get_varinfo (find (anything_id))->solution);
2715 else if (vi->oldsolution)
2716 bitmap_and_compl (pts, vi->solution, vi->oldsolution);
2717 else
2718 bitmap_copy (pts, vi->solution);
2720 if (bitmap_empty_p (pts))
2721 continue;
2723 if (vi->oldsolution)
2724 bitmap_ior_into (vi->oldsolution, pts);
2725 else
2727 vi->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
2728 bitmap_copy (vi->oldsolution, pts);
2731 solution = vi->solution;
2732 solution_empty = bitmap_empty_p (solution);
2734 /* Process the complex constraints */
2735 bitmap expanded_pts = NULL;
2736 FOR_EACH_VEC_ELT (complex, j, c)
2738 /* XXX: This is going to unsort the constraints in
2739 some cases, which will occasionally add duplicate
2740 constraints during unification. This does not
2741 affect correctness. */
2742 c->lhs.var = find (c->lhs.var);
2743 c->rhs.var = find (c->rhs.var);
2745 /* The only complex constraint that can change our
2746 solution to non-empty, given an empty solution,
2747 is a constraint where the lhs side is receiving
2748 some set from elsewhere. */
2749 if (!solution_empty || c->lhs.type != DEREF)
2750 do_complex_constraint (graph, c, pts, &expanded_pts);
2752 BITMAP_FREE (expanded_pts);
2754 solution_empty = bitmap_empty_p (solution);
2756 if (!solution_empty)
2758 bitmap_iterator bi;
2759 unsigned eff_escaped_id = find (escaped_id);
2761 /* Propagate solution to all successors. */
2762 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2763 0, j, bi)
2765 bitmap tmp;
2766 bool flag;
2768 unsigned int to = find (j);
2769 tmp = get_varinfo (to)->solution;
2770 flag = false;
2772 /* Don't try to propagate to ourselves. */
2773 if (to == i)
2774 continue;
2776 /* If we propagate from ESCAPED use ESCAPED as
2777 placeholder. */
2778 if (i == eff_escaped_id)
2779 flag = bitmap_set_bit (tmp, escaped_id);
2780 else
2781 flag = bitmap_ior_into (tmp, pts);
2783 if (flag)
2784 bitmap_set_bit (changed, to);
2789 free_topo_info (ti);
2790 bitmap_obstack_release (&iteration_obstack);
2793 BITMAP_FREE (pts);
2794 BITMAP_FREE (changed);
2795 bitmap_obstack_release (&oldpta_obstack);
2798 /* Map from trees to variable infos. */
2799 static hash_map<tree, varinfo_t> *vi_for_tree;
2802 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2804 static void
2805 insert_vi_for_tree (tree t, varinfo_t vi)
2807 gcc_assert (vi);
2808 gcc_assert (!vi_for_tree->put (t, vi));
2811 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2812 exist in the map, return NULL, otherwise, return the varinfo we found. */
2814 static varinfo_t
2815 lookup_vi_for_tree (tree t)
2817 varinfo_t *slot = vi_for_tree->get (t);
2818 if (slot == NULL)
2819 return NULL;
2821 return *slot;
2824 /* Return a printable name for DECL */
2826 static const char *
2827 alias_get_name (tree decl)
2829 const char *res = NULL;
2830 char *temp;
2831 int num_printed = 0;
2833 if (!dump_file)
2834 return "NULL";
2836 if (TREE_CODE (decl) == SSA_NAME)
2838 res = get_name (decl);
2839 if (res)
2840 num_printed = asprintf (&temp, "%s_%u", res, SSA_NAME_VERSION (decl));
2841 else
2842 num_printed = asprintf (&temp, "_%u", SSA_NAME_VERSION (decl));
2843 if (num_printed > 0)
2845 res = ggc_strdup (temp);
2846 free (temp);
2849 else if (DECL_P (decl))
2851 if (DECL_ASSEMBLER_NAME_SET_P (decl))
2852 res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2853 else
2855 res = get_name (decl);
2856 if (!res)
2858 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2859 if (num_printed > 0)
2861 res = ggc_strdup (temp);
2862 free (temp);
2867 if (res != NULL)
2868 return res;
2870 return "NULL";
2873 /* Find the variable id for tree T in the map.
2874 If T doesn't exist in the map, create an entry for it and return it. */
2876 static varinfo_t
2877 get_vi_for_tree (tree t)
2879 varinfo_t *slot = vi_for_tree->get (t);
2880 if (slot == NULL)
2882 unsigned int id = create_variable_info_for (t, alias_get_name (t), false);
2883 return get_varinfo (id);
2886 return *slot;
2889 /* Get a scalar constraint expression for a new temporary variable. */
2891 static struct constraint_expr
2892 new_scalar_tmp_constraint_exp (const char *name, bool add_id)
2894 struct constraint_expr tmp;
2895 varinfo_t vi;
2897 vi = new_var_info (NULL_TREE, name, add_id);
2898 vi->offset = 0;
2899 vi->size = -1;
2900 vi->fullsize = -1;
2901 vi->is_full_var = 1;
2903 tmp.var = vi->id;
2904 tmp.type = SCALAR;
2905 tmp.offset = 0;
2907 return tmp;
2910 /* Get a constraint expression vector from an SSA_VAR_P node.
2911 If address_p is true, the result will be taken its address of. */
2913 static void
2914 get_constraint_for_ssa_var (tree t, vec<ce_s> *results, bool address_p)
2916 struct constraint_expr cexpr;
2917 varinfo_t vi;
2919 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2920 gcc_assert (TREE_CODE (t) == SSA_NAME || DECL_P (t));
2922 /* For parameters, get at the points-to set for the actual parm
2923 decl. */
2924 if (TREE_CODE (t) == SSA_NAME
2925 && SSA_NAME_IS_DEFAULT_DEF (t)
2926 && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2927 || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL))
2929 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2930 return;
2933 /* For global variables resort to the alias target. */
2934 if (TREE_CODE (t) == VAR_DECL
2935 && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2937 varpool_node *node = varpool_node::get (t);
2938 if (node && node->alias && node->analyzed)
2940 node = node->ultimate_alias_target ();
2941 t = node->decl;
2945 vi = get_vi_for_tree (t);
2946 cexpr.var = vi->id;
2947 cexpr.type = SCALAR;
2948 cexpr.offset = 0;
2950 /* If we are not taking the address of the constraint expr, add all
2951 sub-fiels of the variable as well. */
2952 if (!address_p
2953 && !vi->is_full_var)
2955 for (; vi; vi = vi_next (vi))
2957 cexpr.var = vi->id;
2958 results->safe_push (cexpr);
2960 return;
2963 results->safe_push (cexpr);
2966 /* Process constraint T, performing various simplifications and then
2967 adding it to our list of overall constraints. */
2969 static void
2970 process_constraint (constraint_t t)
2972 struct constraint_expr rhs = t->rhs;
2973 struct constraint_expr lhs = t->lhs;
2975 gcc_assert (rhs.var < varmap.length ());
2976 gcc_assert (lhs.var < varmap.length ());
2978 /* If we didn't get any useful constraint from the lhs we get
2979 &ANYTHING as fallback from get_constraint_for. Deal with
2980 it here by turning it into *ANYTHING. */
2981 if (lhs.type == ADDRESSOF
2982 && lhs.var == anything_id)
2983 lhs.type = DEREF;
2985 /* ADDRESSOF on the lhs is invalid. */
2986 gcc_assert (lhs.type != ADDRESSOF);
2988 /* We shouldn't add constraints from things that cannot have pointers.
2989 It's not completely trivial to avoid in the callers, so do it here. */
2990 if (rhs.type != ADDRESSOF
2991 && !get_varinfo (rhs.var)->may_have_pointers)
2992 return;
2994 /* Likewise adding to the solution of a non-pointer var isn't useful. */
2995 if (!get_varinfo (lhs.var)->may_have_pointers)
2996 return;
2998 /* This can happen in our IR with things like n->a = *p */
2999 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
3001 /* Split into tmp = *rhs, *lhs = tmp */
3002 struct constraint_expr tmplhs;
3003 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp", true);
3004 process_constraint (new_constraint (tmplhs, rhs));
3005 process_constraint (new_constraint (lhs, tmplhs));
3007 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
3009 /* Split into tmp = &rhs, *lhs = tmp */
3010 struct constraint_expr tmplhs;
3011 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp", true);
3012 process_constraint (new_constraint (tmplhs, rhs));
3013 process_constraint (new_constraint (lhs, tmplhs));
3015 else
3017 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
3018 constraints.safe_push (t);
3023 /* Return the position, in bits, of FIELD_DECL from the beginning of its
3024 structure. */
3026 static HOST_WIDE_INT
3027 bitpos_of_field (const tree fdecl)
3029 if (!tree_fits_shwi_p (DECL_FIELD_OFFSET (fdecl))
3030 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fdecl)))
3031 return -1;
3033 return (tree_to_shwi (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
3034 + tree_to_shwi (DECL_FIELD_BIT_OFFSET (fdecl)));
3038 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
3039 resulting constraint expressions in *RESULTS. */
3041 static void
3042 get_constraint_for_ptr_offset (tree ptr, tree offset,
3043 vec<ce_s> *results)
3045 struct constraint_expr c;
3046 unsigned int j, n;
3047 HOST_WIDE_INT rhsoffset;
3049 /* If we do not do field-sensitive PTA adding offsets to pointers
3050 does not change the points-to solution. */
3051 if (!use_field_sensitive)
3053 get_constraint_for_rhs (ptr, results);
3054 return;
3057 /* If the offset is not a non-negative integer constant that fits
3058 in a HOST_WIDE_INT, we have to fall back to a conservative
3059 solution which includes all sub-fields of all pointed-to
3060 variables of ptr. */
3061 if (offset == NULL_TREE
3062 || TREE_CODE (offset) != INTEGER_CST)
3063 rhsoffset = UNKNOWN_OFFSET;
3064 else
3066 /* Sign-extend the offset. */
3067 offset_int soffset = offset_int::from (offset, SIGNED);
3068 if (!wi::fits_shwi_p (soffset))
3069 rhsoffset = UNKNOWN_OFFSET;
3070 else
3072 /* Make sure the bit-offset also fits. */
3073 HOST_WIDE_INT rhsunitoffset = soffset.to_shwi ();
3074 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
3075 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
3076 rhsoffset = UNKNOWN_OFFSET;
3080 get_constraint_for_rhs (ptr, results);
3081 if (rhsoffset == 0)
3082 return;
3084 /* As we are eventually appending to the solution do not use
3085 vec::iterate here. */
3086 n = results->length ();
3087 for (j = 0; j < n; j++)
3089 varinfo_t curr;
3090 c = (*results)[j];
3091 curr = get_varinfo (c.var);
3093 if (c.type == ADDRESSOF
3094 /* If this varinfo represents a full variable just use it. */
3095 && curr->is_full_var)
3097 else if (c.type == ADDRESSOF
3098 /* If we do not know the offset add all subfields. */
3099 && rhsoffset == UNKNOWN_OFFSET)
3101 varinfo_t temp = get_varinfo (curr->head);
3104 struct constraint_expr c2;
3105 c2.var = temp->id;
3106 c2.type = ADDRESSOF;
3107 c2.offset = 0;
3108 if (c2.var != c.var)
3109 results->safe_push (c2);
3110 temp = vi_next (temp);
3112 while (temp);
3114 else if (c.type == ADDRESSOF)
3116 varinfo_t temp;
3117 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3119 /* If curr->offset + rhsoffset is less than zero adjust it. */
3120 if (rhsoffset < 0
3121 && curr->offset < offset)
3122 offset = 0;
3124 /* We have to include all fields that overlap the current
3125 field shifted by rhsoffset. And we include at least
3126 the last or the first field of the variable to represent
3127 reachability of off-bound addresses, in particular &object + 1,
3128 conservatively correct. */
3129 temp = first_or_preceding_vi_for_offset (curr, offset);
3130 c.var = temp->id;
3131 c.offset = 0;
3132 temp = vi_next (temp);
3133 while (temp
3134 && temp->offset < offset + curr->size)
3136 struct constraint_expr c2;
3137 c2.var = temp->id;
3138 c2.type = ADDRESSOF;
3139 c2.offset = 0;
3140 results->safe_push (c2);
3141 temp = vi_next (temp);
3144 else if (c.type == SCALAR)
3146 gcc_assert (c.offset == 0);
3147 c.offset = rhsoffset;
3149 else
3150 /* We shouldn't get any DEREFs here. */
3151 gcc_unreachable ();
3153 (*results)[j] = c;
3158 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3159 If address_p is true the result will be taken its address of.
3160 If lhs_p is true then the constraint expression is assumed to be used
3161 as the lhs. */
3163 static void
3164 get_constraint_for_component_ref (tree t, vec<ce_s> *results,
3165 bool address_p, bool lhs_p)
3167 tree orig_t = t;
3168 HOST_WIDE_INT bitsize = -1;
3169 HOST_WIDE_INT bitmaxsize = -1;
3170 HOST_WIDE_INT bitpos;
3171 bool reverse;
3172 tree forzero;
3174 /* Some people like to do cute things like take the address of
3175 &0->a.b */
3176 forzero = t;
3177 while (handled_component_p (forzero)
3178 || INDIRECT_REF_P (forzero)
3179 || TREE_CODE (forzero) == MEM_REF)
3180 forzero = TREE_OPERAND (forzero, 0);
3182 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3184 struct constraint_expr temp;
3186 temp.offset = 0;
3187 temp.var = integer_id;
3188 temp.type = SCALAR;
3189 results->safe_push (temp);
3190 return;
3193 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize, &reverse);
3195 /* Pretend to take the address of the base, we'll take care of
3196 adding the required subset of sub-fields below. */
3197 get_constraint_for_1 (t, results, true, lhs_p);
3198 gcc_assert (results->length () == 1);
3199 struct constraint_expr &result = results->last ();
3201 if (result.type == SCALAR
3202 && get_varinfo (result.var)->is_full_var)
3203 /* For single-field vars do not bother about the offset. */
3204 result.offset = 0;
3205 else if (result.type == SCALAR)
3207 /* In languages like C, you can access one past the end of an
3208 array. You aren't allowed to dereference it, so we can
3209 ignore this constraint. When we handle pointer subtraction,
3210 we may have to do something cute here. */
3212 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result.var)->fullsize
3213 && bitmaxsize != 0)
3215 /* It's also not true that the constraint will actually start at the
3216 right offset, it may start in some padding. We only care about
3217 setting the constraint to the first actual field it touches, so
3218 walk to find it. */
3219 struct constraint_expr cexpr = result;
3220 varinfo_t curr;
3221 results->pop ();
3222 cexpr.offset = 0;
3223 for (curr = get_varinfo (cexpr.var); curr; curr = vi_next (curr))
3225 if (ranges_overlap_p (curr->offset, curr->size,
3226 bitpos, bitmaxsize))
3228 cexpr.var = curr->id;
3229 results->safe_push (cexpr);
3230 if (address_p)
3231 break;
3234 /* If we are going to take the address of this field then
3235 to be able to compute reachability correctly add at least
3236 the last field of the variable. */
3237 if (address_p && results->length () == 0)
3239 curr = get_varinfo (cexpr.var);
3240 while (curr->next != 0)
3241 curr = vi_next (curr);
3242 cexpr.var = curr->id;
3243 results->safe_push (cexpr);
3245 else if (results->length () == 0)
3246 /* Assert that we found *some* field there. The user couldn't be
3247 accessing *only* padding. */
3248 /* Still the user could access one past the end of an array
3249 embedded in a struct resulting in accessing *only* padding. */
3250 /* Or accessing only padding via type-punning to a type
3251 that has a filed just in padding space. */
3253 cexpr.type = SCALAR;
3254 cexpr.var = anything_id;
3255 cexpr.offset = 0;
3256 results->safe_push (cexpr);
3259 else if (bitmaxsize == 0)
3261 if (dump_file && (dump_flags & TDF_DETAILS))
3262 fprintf (dump_file, "Access to zero-sized part of variable,"
3263 "ignoring\n");
3265 else
3266 if (dump_file && (dump_flags & TDF_DETAILS))
3267 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3269 else if (result.type == DEREF)
3271 /* If we do not know exactly where the access goes say so. Note
3272 that only for non-structure accesses we know that we access
3273 at most one subfiled of any variable. */
3274 if (bitpos == -1
3275 || bitsize != bitmaxsize
3276 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3277 || result.offset == UNKNOWN_OFFSET)
3278 result.offset = UNKNOWN_OFFSET;
3279 else
3280 result.offset += bitpos;
3282 else if (result.type == ADDRESSOF)
3284 /* We can end up here for component references on a
3285 VIEW_CONVERT_EXPR <>(&foobar). */
3286 result.type = SCALAR;
3287 result.var = anything_id;
3288 result.offset = 0;
3290 else
3291 gcc_unreachable ();
3295 /* Dereference the constraint expression CONS, and return the result.
3296 DEREF (ADDRESSOF) = SCALAR
3297 DEREF (SCALAR) = DEREF
3298 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3299 This is needed so that we can handle dereferencing DEREF constraints. */
3301 static void
3302 do_deref (vec<ce_s> *constraints)
3304 struct constraint_expr *c;
3305 unsigned int i = 0;
3307 FOR_EACH_VEC_ELT (*constraints, i, c)
3309 if (c->type == SCALAR)
3310 c->type = DEREF;
3311 else if (c->type == ADDRESSOF)
3312 c->type = SCALAR;
3313 else if (c->type == DEREF)
3315 struct constraint_expr tmplhs;
3316 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp", true);
3317 process_constraint (new_constraint (tmplhs, *c));
3318 c->var = tmplhs.var;
3320 else
3321 gcc_unreachable ();
3325 /* Given a tree T, return the constraint expression for taking the
3326 address of it. */
3328 static void
3329 get_constraint_for_address_of (tree t, vec<ce_s> *results)
3331 struct constraint_expr *c;
3332 unsigned int i;
3334 get_constraint_for_1 (t, results, true, true);
3336 FOR_EACH_VEC_ELT (*results, i, c)
3338 if (c->type == DEREF)
3339 c->type = SCALAR;
3340 else
3341 c->type = ADDRESSOF;
3345 /* Given a tree T, return the constraint expression for it. */
3347 static void
3348 get_constraint_for_1 (tree t, vec<ce_s> *results, bool address_p,
3349 bool lhs_p)
3351 struct constraint_expr temp;
3353 /* x = integer is all glommed to a single variable, which doesn't
3354 point to anything by itself. That is, of course, unless it is an
3355 integer constant being treated as a pointer, in which case, we
3356 will return that this is really the addressof anything. This
3357 happens below, since it will fall into the default case. The only
3358 case we know something about an integer treated like a pointer is
3359 when it is the NULL pointer, and then we just say it points to
3360 NULL.
3362 Do not do that if -fno-delete-null-pointer-checks though, because
3363 in that case *NULL does not fail, so it _should_ alias *anything.
3364 It is not worth adding a new option or renaming the existing one,
3365 since this case is relatively obscure. */
3366 if ((TREE_CODE (t) == INTEGER_CST
3367 && integer_zerop (t))
3368 /* The only valid CONSTRUCTORs in gimple with pointer typed
3369 elements are zero-initializer. But in IPA mode we also
3370 process global initializers, so verify at least. */
3371 || (TREE_CODE (t) == CONSTRUCTOR
3372 && CONSTRUCTOR_NELTS (t) == 0))
3374 if (flag_delete_null_pointer_checks)
3375 temp.var = nothing_id;
3376 else
3377 temp.var = nonlocal_id;
3378 temp.type = ADDRESSOF;
3379 temp.offset = 0;
3380 results->safe_push (temp);
3381 return;
3384 /* String constants are read-only, ideally we'd have a CONST_DECL
3385 for those. */
3386 if (TREE_CODE (t) == STRING_CST)
3388 temp.var = string_id;
3389 temp.type = SCALAR;
3390 temp.offset = 0;
3391 results->safe_push (temp);
3392 return;
3395 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3397 case tcc_expression:
3399 switch (TREE_CODE (t))
3401 case ADDR_EXPR:
3402 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3403 return;
3404 default:;
3406 break;
3408 case tcc_reference:
3410 switch (TREE_CODE (t))
3412 case MEM_REF:
3414 struct constraint_expr cs;
3415 varinfo_t vi, curr;
3416 get_constraint_for_ptr_offset (TREE_OPERAND (t, 0),
3417 TREE_OPERAND (t, 1), results);
3418 do_deref (results);
3420 /* If we are not taking the address then make sure to process
3421 all subvariables we might access. */
3422 if (address_p)
3423 return;
3425 cs = results->last ();
3426 if (cs.type == DEREF
3427 && type_can_have_subvars (TREE_TYPE (t)))
3429 /* For dereferences this means we have to defer it
3430 to solving time. */
3431 results->last ().offset = UNKNOWN_OFFSET;
3432 return;
3434 if (cs.type != SCALAR)
3435 return;
3437 vi = get_varinfo (cs.var);
3438 curr = vi_next (vi);
3439 if (!vi->is_full_var
3440 && curr)
3442 unsigned HOST_WIDE_INT size;
3443 if (tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (t))))
3444 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (t)));
3445 else
3446 size = -1;
3447 for (; curr; curr = vi_next (curr))
3449 if (curr->offset - vi->offset < size)
3451 cs.var = curr->id;
3452 results->safe_push (cs);
3454 else
3455 break;
3458 return;
3460 case ARRAY_REF:
3461 case ARRAY_RANGE_REF:
3462 case COMPONENT_REF:
3463 case IMAGPART_EXPR:
3464 case REALPART_EXPR:
3465 case BIT_FIELD_REF:
3466 get_constraint_for_component_ref (t, results, address_p, lhs_p);
3467 return;
3468 case VIEW_CONVERT_EXPR:
3469 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3470 lhs_p);
3471 return;
3472 /* We are missing handling for TARGET_MEM_REF here. */
3473 default:;
3475 break;
3477 case tcc_exceptional:
3479 switch (TREE_CODE (t))
3481 case SSA_NAME:
3483 get_constraint_for_ssa_var (t, results, address_p);
3484 return;
3486 case CONSTRUCTOR:
3488 unsigned int i;
3489 tree val;
3490 auto_vec<ce_s> tmp;
3491 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3493 struct constraint_expr *rhsp;
3494 unsigned j;
3495 get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3496 FOR_EACH_VEC_ELT (tmp, j, rhsp)
3497 results->safe_push (*rhsp);
3498 tmp.truncate (0);
3500 /* We do not know whether the constructor was complete,
3501 so technically we have to add &NOTHING or &ANYTHING
3502 like we do for an empty constructor as well. */
3503 return;
3505 default:;
3507 break;
3509 case tcc_declaration:
3511 get_constraint_for_ssa_var (t, results, address_p);
3512 return;
3514 case tcc_constant:
3516 /* We cannot refer to automatic variables through constants. */
3517 temp.type = ADDRESSOF;
3518 temp.var = nonlocal_id;
3519 temp.offset = 0;
3520 results->safe_push (temp);
3521 return;
3523 default:;
3526 /* The default fallback is a constraint from anything. */
3527 temp.type = ADDRESSOF;
3528 temp.var = anything_id;
3529 temp.offset = 0;
3530 results->safe_push (temp);
3533 /* Given a gimple tree T, return the constraint expression vector for it. */
3535 static void
3536 get_constraint_for (tree t, vec<ce_s> *results)
3538 gcc_assert (results->length () == 0);
3540 get_constraint_for_1 (t, results, false, true);
3543 /* Given a gimple tree T, return the constraint expression vector for it
3544 to be used as the rhs of a constraint. */
3546 static void
3547 get_constraint_for_rhs (tree t, vec<ce_s> *results)
3549 gcc_assert (results->length () == 0);
3551 get_constraint_for_1 (t, results, false, false);
3555 /* Efficiently generates constraints from all entries in *RHSC to all
3556 entries in *LHSC. */
3558 static void
3559 process_all_all_constraints (vec<ce_s> lhsc,
3560 vec<ce_s> rhsc)
3562 struct constraint_expr *lhsp, *rhsp;
3563 unsigned i, j;
3565 if (lhsc.length () <= 1 || rhsc.length () <= 1)
3567 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3568 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
3569 process_constraint (new_constraint (*lhsp, *rhsp));
3571 else
3573 struct constraint_expr tmp;
3574 tmp = new_scalar_tmp_constraint_exp ("allalltmp", true);
3575 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
3576 process_constraint (new_constraint (tmp, *rhsp));
3577 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3578 process_constraint (new_constraint (*lhsp, tmp));
3582 /* Handle aggregate copies by expanding into copies of the respective
3583 fields of the structures. */
3585 static void
3586 do_structure_copy (tree lhsop, tree rhsop)
3588 struct constraint_expr *lhsp, *rhsp;
3589 auto_vec<ce_s> lhsc;
3590 auto_vec<ce_s> rhsc;
3591 unsigned j;
3593 get_constraint_for (lhsop, &lhsc);
3594 get_constraint_for_rhs (rhsop, &rhsc);
3595 lhsp = &lhsc[0];
3596 rhsp = &rhsc[0];
3597 if (lhsp->type == DEREF
3598 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3599 || rhsp->type == DEREF)
3601 if (lhsp->type == DEREF)
3603 gcc_assert (lhsc.length () == 1);
3604 lhsp->offset = UNKNOWN_OFFSET;
3606 if (rhsp->type == DEREF)
3608 gcc_assert (rhsc.length () == 1);
3609 rhsp->offset = UNKNOWN_OFFSET;
3611 process_all_all_constraints (lhsc, rhsc);
3613 else if (lhsp->type == SCALAR
3614 && (rhsp->type == SCALAR
3615 || rhsp->type == ADDRESSOF))
3617 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3618 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3619 bool reverse;
3620 unsigned k = 0;
3621 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize,
3622 &reverse);
3623 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize,
3624 &reverse);
3625 for (j = 0; lhsc.iterate (j, &lhsp);)
3627 varinfo_t lhsv, rhsv;
3628 rhsp = &rhsc[k];
3629 lhsv = get_varinfo (lhsp->var);
3630 rhsv = get_varinfo (rhsp->var);
3631 if (lhsv->may_have_pointers
3632 && (lhsv->is_full_var
3633 || rhsv->is_full_var
3634 || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3635 rhsv->offset + lhsoffset, rhsv->size)))
3636 process_constraint (new_constraint (*lhsp, *rhsp));
3637 if (!rhsv->is_full_var
3638 && (lhsv->is_full_var
3639 || (lhsv->offset + rhsoffset + lhsv->size
3640 > rhsv->offset + lhsoffset + rhsv->size)))
3642 ++k;
3643 if (k >= rhsc.length ())
3644 break;
3646 else
3647 ++j;
3650 else
3651 gcc_unreachable ();
3654 /* Create constraints ID = { rhsc }. */
3656 static void
3657 make_constraints_to (unsigned id, vec<ce_s> rhsc)
3659 struct constraint_expr *c;
3660 struct constraint_expr includes;
3661 unsigned int j;
3663 includes.var = id;
3664 includes.offset = 0;
3665 includes.type = SCALAR;
3667 FOR_EACH_VEC_ELT (rhsc, j, c)
3668 process_constraint (new_constraint (includes, *c));
3671 /* Create a constraint ID = OP. */
3673 static void
3674 make_constraint_to (unsigned id, tree op)
3676 auto_vec<ce_s> rhsc;
3677 get_constraint_for_rhs (op, &rhsc);
3678 make_constraints_to (id, rhsc);
3681 /* Create a constraint ID = &FROM. */
3683 static void
3684 make_constraint_from (varinfo_t vi, int from)
3686 struct constraint_expr lhs, rhs;
3688 lhs.var = vi->id;
3689 lhs.offset = 0;
3690 lhs.type = SCALAR;
3692 rhs.var = from;
3693 rhs.offset = 0;
3694 rhs.type = ADDRESSOF;
3695 process_constraint (new_constraint (lhs, rhs));
3698 /* Create a constraint ID = FROM. */
3700 static void
3701 make_copy_constraint (varinfo_t vi, int from)
3703 struct constraint_expr lhs, rhs;
3705 lhs.var = vi->id;
3706 lhs.offset = 0;
3707 lhs.type = SCALAR;
3709 rhs.var = from;
3710 rhs.offset = 0;
3711 rhs.type = SCALAR;
3712 process_constraint (new_constraint (lhs, rhs));
3715 /* Make constraints necessary to make OP escape. */
3717 static void
3718 make_escape_constraint (tree op)
3720 make_constraint_to (escaped_id, op);
3723 /* Add constraints to that the solution of VI is transitively closed. */
3725 static void
3726 make_transitive_closure_constraints (varinfo_t vi)
3728 struct constraint_expr lhs, rhs;
3730 /* VAR = *VAR; */
3731 lhs.type = SCALAR;
3732 lhs.var = vi->id;
3733 lhs.offset = 0;
3734 rhs.type = DEREF;
3735 rhs.var = vi->id;
3736 rhs.offset = UNKNOWN_OFFSET;
3737 process_constraint (new_constraint (lhs, rhs));
3740 /* Temporary storage for fake var decls. */
3741 struct obstack fake_var_decl_obstack;
3743 /* Build a fake VAR_DECL acting as referrer to a DECL_UID. */
3745 static tree
3746 build_fake_var_decl (tree type)
3748 tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3749 memset (decl, 0, sizeof (struct tree_var_decl));
3750 TREE_SET_CODE (decl, VAR_DECL);
3751 TREE_TYPE (decl) = type;
3752 DECL_UID (decl) = allocate_decl_uid ();
3753 SET_DECL_PT_UID (decl, -1);
3754 layout_decl (decl, 0);
3755 return decl;
3758 /* Create a new artificial heap variable with NAME.
3759 Return the created variable. */
3761 static varinfo_t
3762 make_heapvar (const char *name, bool add_id)
3764 varinfo_t vi;
3765 tree heapvar;
3767 heapvar = build_fake_var_decl (ptr_type_node);
3768 DECL_EXTERNAL (heapvar) = 1;
3770 vi = new_var_info (heapvar, name, add_id);
3771 vi->is_artificial_var = true;
3772 vi->is_heap_var = true;
3773 vi->is_unknown_size_var = true;
3774 vi->offset = 0;
3775 vi->fullsize = ~0;
3776 vi->size = ~0;
3777 vi->is_full_var = true;
3778 insert_vi_for_tree (heapvar, vi);
3780 return vi;
3783 /* Create a new artificial heap variable with NAME and make a
3784 constraint from it to LHS. Set flags according to a tag used
3785 for tracking restrict pointers. */
3787 static varinfo_t
3788 make_constraint_from_restrict (varinfo_t lhs, const char *name, bool add_id)
3790 varinfo_t vi = make_heapvar (name, add_id);
3791 vi->is_restrict_var = 1;
3792 vi->is_global_var = 1;
3793 vi->may_have_pointers = 1;
3794 make_constraint_from (lhs, vi->id);
3795 return vi;
3798 /* Create a new artificial heap variable with NAME and make a
3799 constraint from it to LHS. Set flags according to a tag used
3800 for tracking restrict pointers and make the artificial heap
3801 point to global memory. */
3803 static varinfo_t
3804 make_constraint_from_global_restrict (varinfo_t lhs, const char *name,
3805 bool add_id)
3807 varinfo_t vi = make_constraint_from_restrict (lhs, name, add_id);
3808 make_copy_constraint (vi, nonlocal_id);
3809 return vi;
3812 /* In IPA mode there are varinfos for different aspects of reach
3813 function designator. One for the points-to set of the return
3814 value, one for the variables that are clobbered by the function,
3815 one for its uses and one for each parameter (including a single
3816 glob for remaining variadic arguments). */
3818 enum { fi_clobbers = 1, fi_uses = 2,
3819 fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3821 /* Get a constraint for the requested part of a function designator FI
3822 when operating in IPA mode. */
3824 static struct constraint_expr
3825 get_function_part_constraint (varinfo_t fi, unsigned part)
3827 struct constraint_expr c;
3829 gcc_assert (in_ipa_mode);
3831 if (fi->id == anything_id)
3833 /* ??? We probably should have a ANYFN special variable. */
3834 c.var = anything_id;
3835 c.offset = 0;
3836 c.type = SCALAR;
3838 else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3840 varinfo_t ai = first_vi_for_offset (fi, part);
3841 if (ai)
3842 c.var = ai->id;
3843 else
3844 c.var = anything_id;
3845 c.offset = 0;
3846 c.type = SCALAR;
3848 else
3850 c.var = fi->id;
3851 c.offset = part;
3852 c.type = DEREF;
3855 return c;
3858 /* For non-IPA mode, generate constraints necessary for a call on the
3859 RHS. */
3861 static void
3862 handle_rhs_call (gcall *stmt, vec<ce_s> *results)
3864 struct constraint_expr rhsc;
3865 unsigned i;
3866 bool returns_uses = false;
3868 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3870 tree arg = gimple_call_arg (stmt, i);
3871 int flags = gimple_call_arg_flags (stmt, i);
3873 /* If the argument is not used we can ignore it. */
3874 if (flags & EAF_UNUSED)
3875 continue;
3877 /* As we compute ESCAPED context-insensitive we do not gain
3878 any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3879 set. The argument would still get clobbered through the
3880 escape solution. */
3881 if ((flags & EAF_NOCLOBBER)
3882 && (flags & EAF_NOESCAPE))
3884 varinfo_t uses = get_call_use_vi (stmt);
3885 if (!(flags & EAF_DIRECT))
3887 varinfo_t tem = new_var_info (NULL_TREE, "callarg", true);
3888 make_constraint_to (tem->id, arg);
3889 make_transitive_closure_constraints (tem);
3890 make_copy_constraint (uses, tem->id);
3892 else
3893 make_constraint_to (uses->id, arg);
3894 returns_uses = true;
3896 else if (flags & EAF_NOESCAPE)
3898 struct constraint_expr lhs, rhs;
3899 varinfo_t uses = get_call_use_vi (stmt);
3900 varinfo_t clobbers = get_call_clobber_vi (stmt);
3901 varinfo_t tem = new_var_info (NULL_TREE, "callarg", true);
3902 make_constraint_to (tem->id, arg);
3903 if (!(flags & EAF_DIRECT))
3904 make_transitive_closure_constraints (tem);
3905 make_copy_constraint (uses, tem->id);
3906 make_copy_constraint (clobbers, tem->id);
3907 /* Add *tem = nonlocal, do not add *tem = callused as
3908 EAF_NOESCAPE parameters do not escape to other parameters
3909 and all other uses appear in NONLOCAL as well. */
3910 lhs.type = DEREF;
3911 lhs.var = tem->id;
3912 lhs.offset = 0;
3913 rhs.type = SCALAR;
3914 rhs.var = nonlocal_id;
3915 rhs.offset = 0;
3916 process_constraint (new_constraint (lhs, rhs));
3917 returns_uses = true;
3919 else
3920 make_escape_constraint (arg);
3923 /* If we added to the calls uses solution make sure we account for
3924 pointers to it to be returned. */
3925 if (returns_uses)
3927 rhsc.var = get_call_use_vi (stmt)->id;
3928 rhsc.offset = 0;
3929 rhsc.type = SCALAR;
3930 results->safe_push (rhsc);
3933 /* The static chain escapes as well. */
3934 if (gimple_call_chain (stmt))
3935 make_escape_constraint (gimple_call_chain (stmt));
3937 /* And if we applied NRV the address of the return slot escapes as well. */
3938 if (gimple_call_return_slot_opt_p (stmt)
3939 && gimple_call_lhs (stmt) != NULL_TREE
3940 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3942 auto_vec<ce_s> tmpc;
3943 struct constraint_expr lhsc, *c;
3944 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3945 lhsc.var = escaped_id;
3946 lhsc.offset = 0;
3947 lhsc.type = SCALAR;
3948 FOR_EACH_VEC_ELT (tmpc, i, c)
3949 process_constraint (new_constraint (lhsc, *c));
3952 /* Regular functions return nonlocal memory. */
3953 rhsc.var = nonlocal_id;
3954 rhsc.offset = 0;
3955 rhsc.type = SCALAR;
3956 results->safe_push (rhsc);
3959 /* For non-IPA mode, generate constraints necessary for a call
3960 that returns a pointer and assigns it to LHS. This simply makes
3961 the LHS point to global and escaped variables. */
3963 static void
3964 handle_lhs_call (gcall *stmt, tree lhs, int flags, vec<ce_s> rhsc,
3965 tree fndecl)
3967 auto_vec<ce_s> lhsc;
3969 get_constraint_for (lhs, &lhsc);
3970 /* If the store is to a global decl make sure to
3971 add proper escape constraints. */
3972 lhs = get_base_address (lhs);
3973 if (lhs
3974 && DECL_P (lhs)
3975 && is_global_var (lhs))
3977 struct constraint_expr tmpc;
3978 tmpc.var = escaped_id;
3979 tmpc.offset = 0;
3980 tmpc.type = SCALAR;
3981 lhsc.safe_push (tmpc);
3984 /* If the call returns an argument unmodified override the rhs
3985 constraints. */
3986 if (flags & ERF_RETURNS_ARG
3987 && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
3989 tree arg;
3990 rhsc.create (0);
3991 arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
3992 get_constraint_for (arg, &rhsc);
3993 process_all_all_constraints (lhsc, rhsc);
3994 rhsc.release ();
3996 else if (flags & ERF_NOALIAS)
3998 varinfo_t vi;
3999 struct constraint_expr tmpc;
4000 rhsc.create (0);
4001 vi = make_heapvar ("HEAP", true);
4002 /* We are marking allocated storage local, we deal with it becoming
4003 global by escaping and setting of vars_contains_escaped_heap. */
4004 DECL_EXTERNAL (vi->decl) = 0;
4005 vi->is_global_var = 0;
4006 /* If this is not a real malloc call assume the memory was
4007 initialized and thus may point to global memory. All
4008 builtin functions with the malloc attribute behave in a sane way. */
4009 if (!fndecl
4010 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
4011 make_constraint_from (vi, nonlocal_id);
4012 tmpc.var = vi->id;
4013 tmpc.offset = 0;
4014 tmpc.type = ADDRESSOF;
4015 rhsc.safe_push (tmpc);
4016 process_all_all_constraints (lhsc, rhsc);
4017 rhsc.release ();
4019 else
4020 process_all_all_constraints (lhsc, rhsc);
4023 /* For non-IPA mode, generate constraints necessary for a call of a
4024 const function that returns a pointer in the statement STMT. */
4026 static void
4027 handle_const_call (gcall *stmt, vec<ce_s> *results)
4029 struct constraint_expr rhsc;
4030 unsigned int k;
4032 /* Treat nested const functions the same as pure functions as far
4033 as the static chain is concerned. */
4034 if (gimple_call_chain (stmt))
4036 varinfo_t uses = get_call_use_vi (stmt);
4037 make_transitive_closure_constraints (uses);
4038 make_constraint_to (uses->id, gimple_call_chain (stmt));
4039 rhsc.var = uses->id;
4040 rhsc.offset = 0;
4041 rhsc.type = SCALAR;
4042 results->safe_push (rhsc);
4045 /* May return arguments. */
4046 for (k = 0; k < gimple_call_num_args (stmt); ++k)
4048 tree arg = gimple_call_arg (stmt, k);
4049 auto_vec<ce_s> argc;
4050 unsigned i;
4051 struct constraint_expr *argp;
4052 get_constraint_for_rhs (arg, &argc);
4053 FOR_EACH_VEC_ELT (argc, i, argp)
4054 results->safe_push (*argp);
4057 /* May return addresses of globals. */
4058 rhsc.var = nonlocal_id;
4059 rhsc.offset = 0;
4060 rhsc.type = ADDRESSOF;
4061 results->safe_push (rhsc);
4064 /* For non-IPA mode, generate constraints necessary for a call to a
4065 pure function in statement STMT. */
4067 static void
4068 handle_pure_call (gcall *stmt, vec<ce_s> *results)
4070 struct constraint_expr rhsc;
4071 unsigned i;
4072 varinfo_t uses = NULL;
4074 /* Memory reached from pointer arguments is call-used. */
4075 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4077 tree arg = gimple_call_arg (stmt, i);
4078 if (!uses)
4080 uses = get_call_use_vi (stmt);
4081 make_transitive_closure_constraints (uses);
4083 make_constraint_to (uses->id, arg);
4086 /* The static chain is used as well. */
4087 if (gimple_call_chain (stmt))
4089 if (!uses)
4091 uses = get_call_use_vi (stmt);
4092 make_transitive_closure_constraints (uses);
4094 make_constraint_to (uses->id, gimple_call_chain (stmt));
4097 /* Pure functions may return call-used and nonlocal memory. */
4098 if (uses)
4100 rhsc.var = uses->id;
4101 rhsc.offset = 0;
4102 rhsc.type = SCALAR;
4103 results->safe_push (rhsc);
4105 rhsc.var = nonlocal_id;
4106 rhsc.offset = 0;
4107 rhsc.type = SCALAR;
4108 results->safe_push (rhsc);
4112 /* Return the varinfo for the callee of CALL. */
4114 static varinfo_t
4115 get_fi_for_callee (gcall *call)
4117 tree decl, fn = gimple_call_fn (call);
4119 if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
4120 fn = OBJ_TYPE_REF_EXPR (fn);
4122 /* If we can directly resolve the function being called, do so.
4123 Otherwise, it must be some sort of indirect expression that
4124 we should still be able to handle. */
4125 decl = gimple_call_addr_fndecl (fn);
4126 if (decl)
4127 return get_vi_for_tree (decl);
4129 /* If the function is anything other than a SSA name pointer we have no
4130 clue and should be getting ANYFN (well, ANYTHING for now). */
4131 if (!fn || TREE_CODE (fn) != SSA_NAME)
4132 return get_varinfo (anything_id);
4134 if (SSA_NAME_IS_DEFAULT_DEF (fn)
4135 && (TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
4136 || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL))
4137 fn = SSA_NAME_VAR (fn);
4139 return get_vi_for_tree (fn);
4142 /* Create constraints for the builtin call T. Return true if the call
4143 was handled, otherwise false. */
4145 static bool
4146 find_func_aliases_for_builtin_call (struct function *fn, gcall *t)
4148 tree fndecl = gimple_call_fndecl (t);
4149 auto_vec<ce_s, 2> lhsc;
4150 auto_vec<ce_s, 4> rhsc;
4151 varinfo_t fi;
4153 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4154 /* ??? All builtins that are handled here need to be handled
4155 in the alias-oracle query functions explicitly! */
4156 switch (DECL_FUNCTION_CODE (fndecl))
4158 /* All the following functions return a pointer to the same object
4159 as their first argument points to. The functions do not add
4160 to the ESCAPED solution. The functions make the first argument
4161 pointed to memory point to what the second argument pointed to
4162 memory points to. */
4163 case BUILT_IN_STRCPY:
4164 case BUILT_IN_STRNCPY:
4165 case BUILT_IN_BCOPY:
4166 case BUILT_IN_MEMCPY:
4167 case BUILT_IN_MEMMOVE:
4168 case BUILT_IN_MEMPCPY:
4169 case BUILT_IN_STPCPY:
4170 case BUILT_IN_STPNCPY:
4171 case BUILT_IN_STRCAT:
4172 case BUILT_IN_STRNCAT:
4173 case BUILT_IN_STRCPY_CHK:
4174 case BUILT_IN_STRNCPY_CHK:
4175 case BUILT_IN_MEMCPY_CHK:
4176 case BUILT_IN_MEMMOVE_CHK:
4177 case BUILT_IN_MEMPCPY_CHK:
4178 case BUILT_IN_STPCPY_CHK:
4179 case BUILT_IN_STPNCPY_CHK:
4180 case BUILT_IN_STRCAT_CHK:
4181 case BUILT_IN_STRNCAT_CHK:
4182 case BUILT_IN_TM_MEMCPY:
4183 case BUILT_IN_TM_MEMMOVE:
4185 tree res = gimple_call_lhs (t);
4186 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4187 == BUILT_IN_BCOPY ? 1 : 0));
4188 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4189 == BUILT_IN_BCOPY ? 0 : 1));
4190 if (res != NULL_TREE)
4192 get_constraint_for (res, &lhsc);
4193 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4194 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4195 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4196 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4197 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK
4198 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY_CHK)
4199 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4200 else
4201 get_constraint_for (dest, &rhsc);
4202 process_all_all_constraints (lhsc, rhsc);
4203 lhsc.truncate (0);
4204 rhsc.truncate (0);
4206 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4207 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4208 do_deref (&lhsc);
4209 do_deref (&rhsc);
4210 process_all_all_constraints (lhsc, rhsc);
4211 return true;
4213 case BUILT_IN_MEMSET:
4214 case BUILT_IN_MEMSET_CHK:
4215 case BUILT_IN_TM_MEMSET:
4217 tree res = gimple_call_lhs (t);
4218 tree dest = gimple_call_arg (t, 0);
4219 unsigned i;
4220 ce_s *lhsp;
4221 struct constraint_expr ac;
4222 if (res != NULL_TREE)
4224 get_constraint_for (res, &lhsc);
4225 get_constraint_for (dest, &rhsc);
4226 process_all_all_constraints (lhsc, rhsc);
4227 lhsc.truncate (0);
4229 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4230 do_deref (&lhsc);
4231 if (flag_delete_null_pointer_checks
4232 && integer_zerop (gimple_call_arg (t, 1)))
4234 ac.type = ADDRESSOF;
4235 ac.var = nothing_id;
4237 else
4239 ac.type = SCALAR;
4240 ac.var = integer_id;
4242 ac.offset = 0;
4243 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4244 process_constraint (new_constraint (*lhsp, ac));
4245 return true;
4247 case BUILT_IN_POSIX_MEMALIGN:
4249 tree ptrptr = gimple_call_arg (t, 0);
4250 get_constraint_for (ptrptr, &lhsc);
4251 do_deref (&lhsc);
4252 varinfo_t vi = make_heapvar ("HEAP", true);
4253 /* We are marking allocated storage local, we deal with it becoming
4254 global by escaping and setting of vars_contains_escaped_heap. */
4255 DECL_EXTERNAL (vi->decl) = 0;
4256 vi->is_global_var = 0;
4257 struct constraint_expr tmpc;
4258 tmpc.var = vi->id;
4259 tmpc.offset = 0;
4260 tmpc.type = ADDRESSOF;
4261 rhsc.safe_push (tmpc);
4262 process_all_all_constraints (lhsc, rhsc);
4263 return true;
4265 case BUILT_IN_ASSUME_ALIGNED:
4267 tree res = gimple_call_lhs (t);
4268 tree dest = gimple_call_arg (t, 0);
4269 if (res != NULL_TREE)
4271 get_constraint_for (res, &lhsc);
4272 get_constraint_for (dest, &rhsc);
4273 process_all_all_constraints (lhsc, rhsc);
4275 return true;
4277 /* All the following functions do not return pointers, do not
4278 modify the points-to sets of memory reachable from their
4279 arguments and do not add to the ESCAPED solution. */
4280 case BUILT_IN_SINCOS:
4281 case BUILT_IN_SINCOSF:
4282 case BUILT_IN_SINCOSL:
4283 case BUILT_IN_FREXP:
4284 case BUILT_IN_FREXPF:
4285 case BUILT_IN_FREXPL:
4286 case BUILT_IN_GAMMA_R:
4287 case BUILT_IN_GAMMAF_R:
4288 case BUILT_IN_GAMMAL_R:
4289 case BUILT_IN_LGAMMA_R:
4290 case BUILT_IN_LGAMMAF_R:
4291 case BUILT_IN_LGAMMAL_R:
4292 case BUILT_IN_MODF:
4293 case BUILT_IN_MODFF:
4294 case BUILT_IN_MODFL:
4295 case BUILT_IN_REMQUO:
4296 case BUILT_IN_REMQUOF:
4297 case BUILT_IN_REMQUOL:
4298 case BUILT_IN_FREE:
4299 return true;
4300 case BUILT_IN_STRDUP:
4301 case BUILT_IN_STRNDUP:
4302 case BUILT_IN_REALLOC:
4303 if (gimple_call_lhs (t))
4305 handle_lhs_call (t, gimple_call_lhs (t),
4306 gimple_call_return_flags (t) | ERF_NOALIAS,
4307 vNULL, fndecl);
4308 get_constraint_for_ptr_offset (gimple_call_lhs (t),
4309 NULL_TREE, &lhsc);
4310 get_constraint_for_ptr_offset (gimple_call_arg (t, 0),
4311 NULL_TREE, &rhsc);
4312 do_deref (&lhsc);
4313 do_deref (&rhsc);
4314 process_all_all_constraints (lhsc, rhsc);
4315 lhsc.truncate (0);
4316 rhsc.truncate (0);
4317 /* For realloc the resulting pointer can be equal to the
4318 argument as well. But only doing this wouldn't be
4319 correct because with ptr == 0 realloc behaves like malloc. */
4320 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_REALLOC)
4322 get_constraint_for (gimple_call_lhs (t), &lhsc);
4323 get_constraint_for (gimple_call_arg (t, 0), &rhsc);
4324 process_all_all_constraints (lhsc, rhsc);
4326 return true;
4328 break;
4329 /* String / character search functions return a pointer into the
4330 source string or NULL. */
4331 case BUILT_IN_INDEX:
4332 case BUILT_IN_STRCHR:
4333 case BUILT_IN_STRRCHR:
4334 case BUILT_IN_MEMCHR:
4335 case BUILT_IN_STRSTR:
4336 case BUILT_IN_STRPBRK:
4337 if (gimple_call_lhs (t))
4339 tree src = gimple_call_arg (t, 0);
4340 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4341 constraint_expr nul;
4342 nul.var = nothing_id;
4343 nul.offset = 0;
4344 nul.type = ADDRESSOF;
4345 rhsc.safe_push (nul);
4346 get_constraint_for (gimple_call_lhs (t), &lhsc);
4347 process_all_all_constraints (lhsc, rhsc);
4349 return true;
4350 /* Trampolines are special - they set up passing the static
4351 frame. */
4352 case BUILT_IN_INIT_TRAMPOLINE:
4354 tree tramp = gimple_call_arg (t, 0);
4355 tree nfunc = gimple_call_arg (t, 1);
4356 tree frame = gimple_call_arg (t, 2);
4357 unsigned i;
4358 struct constraint_expr lhs, *rhsp;
4359 if (in_ipa_mode)
4361 varinfo_t nfi = NULL;
4362 gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4363 nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4364 if (nfi)
4366 lhs = get_function_part_constraint (nfi, fi_static_chain);
4367 get_constraint_for (frame, &rhsc);
4368 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4369 process_constraint (new_constraint (lhs, *rhsp));
4370 rhsc.truncate (0);
4372 /* Make the frame point to the function for
4373 the trampoline adjustment call. */
4374 get_constraint_for (tramp, &lhsc);
4375 do_deref (&lhsc);
4376 get_constraint_for (nfunc, &rhsc);
4377 process_all_all_constraints (lhsc, rhsc);
4379 return true;
4382 /* Else fallthru to generic handling which will let
4383 the frame escape. */
4384 break;
4386 case BUILT_IN_ADJUST_TRAMPOLINE:
4388 tree tramp = gimple_call_arg (t, 0);
4389 tree res = gimple_call_lhs (t);
4390 if (in_ipa_mode && res)
4392 get_constraint_for (res, &lhsc);
4393 get_constraint_for (tramp, &rhsc);
4394 do_deref (&rhsc);
4395 process_all_all_constraints (lhsc, rhsc);
4397 return true;
4399 CASE_BUILT_IN_TM_STORE (1):
4400 CASE_BUILT_IN_TM_STORE (2):
4401 CASE_BUILT_IN_TM_STORE (4):
4402 CASE_BUILT_IN_TM_STORE (8):
4403 CASE_BUILT_IN_TM_STORE (FLOAT):
4404 CASE_BUILT_IN_TM_STORE (DOUBLE):
4405 CASE_BUILT_IN_TM_STORE (LDOUBLE):
4406 CASE_BUILT_IN_TM_STORE (M64):
4407 CASE_BUILT_IN_TM_STORE (M128):
4408 CASE_BUILT_IN_TM_STORE (M256):
4410 tree addr = gimple_call_arg (t, 0);
4411 tree src = gimple_call_arg (t, 1);
4413 get_constraint_for (addr, &lhsc);
4414 do_deref (&lhsc);
4415 get_constraint_for (src, &rhsc);
4416 process_all_all_constraints (lhsc, rhsc);
4417 return true;
4419 CASE_BUILT_IN_TM_LOAD (1):
4420 CASE_BUILT_IN_TM_LOAD (2):
4421 CASE_BUILT_IN_TM_LOAD (4):
4422 CASE_BUILT_IN_TM_LOAD (8):
4423 CASE_BUILT_IN_TM_LOAD (FLOAT):
4424 CASE_BUILT_IN_TM_LOAD (DOUBLE):
4425 CASE_BUILT_IN_TM_LOAD (LDOUBLE):
4426 CASE_BUILT_IN_TM_LOAD (M64):
4427 CASE_BUILT_IN_TM_LOAD (M128):
4428 CASE_BUILT_IN_TM_LOAD (M256):
4430 tree dest = gimple_call_lhs (t);
4431 tree addr = gimple_call_arg (t, 0);
4433 get_constraint_for (dest, &lhsc);
4434 get_constraint_for (addr, &rhsc);
4435 do_deref (&rhsc);
4436 process_all_all_constraints (lhsc, rhsc);
4437 return true;
4439 /* Variadic argument handling needs to be handled in IPA
4440 mode as well. */
4441 case BUILT_IN_VA_START:
4443 tree valist = gimple_call_arg (t, 0);
4444 struct constraint_expr rhs, *lhsp;
4445 unsigned i;
4446 get_constraint_for (valist, &lhsc);
4447 do_deref (&lhsc);
4448 /* The va_list gets access to pointers in variadic
4449 arguments. Which we know in the case of IPA analysis
4450 and otherwise are just all nonlocal variables. */
4451 if (in_ipa_mode)
4453 fi = lookup_vi_for_tree (fn->decl);
4454 rhs = get_function_part_constraint (fi, ~0);
4455 rhs.type = ADDRESSOF;
4457 else
4459 rhs.var = nonlocal_id;
4460 rhs.type = ADDRESSOF;
4461 rhs.offset = 0;
4463 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4464 process_constraint (new_constraint (*lhsp, rhs));
4465 /* va_list is clobbered. */
4466 make_constraint_to (get_call_clobber_vi (t)->id, valist);
4467 return true;
4469 /* va_end doesn't have any effect that matters. */
4470 case BUILT_IN_VA_END:
4471 return true;
4472 /* Alternate return. Simply give up for now. */
4473 case BUILT_IN_RETURN:
4475 fi = NULL;
4476 if (!in_ipa_mode
4477 || !(fi = get_vi_for_tree (fn->decl)))
4478 make_constraint_from (get_varinfo (escaped_id), anything_id);
4479 else if (in_ipa_mode
4480 && fi != NULL)
4482 struct constraint_expr lhs, rhs;
4483 lhs = get_function_part_constraint (fi, fi_result);
4484 rhs.var = anything_id;
4485 rhs.offset = 0;
4486 rhs.type = SCALAR;
4487 process_constraint (new_constraint (lhs, rhs));
4489 return true;
4491 /* printf-style functions may have hooks to set pointers to
4492 point to somewhere into the generated string. Leave them
4493 for a later exercise... */
4494 default:
4495 /* Fallthru to general call handling. */;
4498 return false;
4501 /* Create constraints for the call T. */
4503 static void
4504 find_func_aliases_for_call (struct function *fn, gcall *t)
4506 tree fndecl = gimple_call_fndecl (t);
4507 varinfo_t fi;
4509 if (fndecl != NULL_TREE
4510 && DECL_BUILT_IN (fndecl)
4511 && find_func_aliases_for_builtin_call (fn, t))
4512 return;
4514 fi = get_fi_for_callee (t);
4515 if (!in_ipa_mode
4516 || (fndecl && !fi->is_fn_info))
4518 auto_vec<ce_s, 16> rhsc;
4519 int flags = gimple_call_flags (t);
4521 /* Const functions can return their arguments and addresses
4522 of global memory but not of escaped memory. */
4523 if (flags & (ECF_CONST|ECF_NOVOPS))
4525 if (gimple_call_lhs (t))
4526 handle_const_call (t, &rhsc);
4528 /* Pure functions can return addresses in and of memory
4529 reachable from their arguments, but they are not an escape
4530 point for reachable memory of their arguments. */
4531 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4532 handle_pure_call (t, &rhsc);
4533 else
4534 handle_rhs_call (t, &rhsc);
4535 if (gimple_call_lhs (t))
4536 handle_lhs_call (t, gimple_call_lhs (t),
4537 gimple_call_return_flags (t), rhsc, fndecl);
4539 else
4541 auto_vec<ce_s, 2> rhsc;
4542 tree lhsop;
4543 unsigned j;
4545 /* Assign all the passed arguments to the appropriate incoming
4546 parameters of the function. */
4547 for (j = 0; j < gimple_call_num_args (t); j++)
4549 struct constraint_expr lhs ;
4550 struct constraint_expr *rhsp;
4551 tree arg = gimple_call_arg (t, j);
4553 get_constraint_for_rhs (arg, &rhsc);
4554 lhs = get_function_part_constraint (fi, fi_parm_base + j);
4555 while (rhsc.length () != 0)
4557 rhsp = &rhsc.last ();
4558 process_constraint (new_constraint (lhs, *rhsp));
4559 rhsc.pop ();
4563 /* If we are returning a value, assign it to the result. */
4564 lhsop = gimple_call_lhs (t);
4565 if (lhsop)
4567 auto_vec<ce_s, 2> lhsc;
4568 struct constraint_expr rhs;
4569 struct constraint_expr *lhsp;
4571 get_constraint_for (lhsop, &lhsc);
4572 rhs = get_function_part_constraint (fi, fi_result);
4573 if (fndecl
4574 && DECL_RESULT (fndecl)
4575 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4577 auto_vec<ce_s, 2> tem;
4578 tem.quick_push (rhs);
4579 do_deref (&tem);
4580 gcc_checking_assert (tem.length () == 1);
4581 rhs = tem[0];
4583 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4584 process_constraint (new_constraint (*lhsp, rhs));
4587 /* If we pass the result decl by reference, honor that. */
4588 if (lhsop
4589 && fndecl
4590 && DECL_RESULT (fndecl)
4591 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4593 struct constraint_expr lhs;
4594 struct constraint_expr *rhsp;
4596 get_constraint_for_address_of (lhsop, &rhsc);
4597 lhs = get_function_part_constraint (fi, fi_result);
4598 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4599 process_constraint (new_constraint (lhs, *rhsp));
4600 rhsc.truncate (0);
4603 /* If we use a static chain, pass it along. */
4604 if (gimple_call_chain (t))
4606 struct constraint_expr lhs;
4607 struct constraint_expr *rhsp;
4609 get_constraint_for (gimple_call_chain (t), &rhsc);
4610 lhs = get_function_part_constraint (fi, fi_static_chain);
4611 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4612 process_constraint (new_constraint (lhs, *rhsp));
4617 /* Walk statement T setting up aliasing constraints according to the
4618 references found in T. This function is the main part of the
4619 constraint builder. AI points to auxiliary alias information used
4620 when building alias sets and computing alias grouping heuristics. */
4622 static void
4623 find_func_aliases (struct function *fn, gimple *origt)
4625 gimple *t = origt;
4626 auto_vec<ce_s, 16> lhsc;
4627 auto_vec<ce_s, 16> rhsc;
4628 struct constraint_expr *c;
4629 varinfo_t fi;
4631 /* Now build constraints expressions. */
4632 if (gimple_code (t) == GIMPLE_PHI)
4634 size_t i;
4635 unsigned int j;
4637 /* For a phi node, assign all the arguments to
4638 the result. */
4639 get_constraint_for (gimple_phi_result (t), &lhsc);
4640 for (i = 0; i < gimple_phi_num_args (t); i++)
4642 tree strippedrhs = PHI_ARG_DEF (t, i);
4644 STRIP_NOPS (strippedrhs);
4645 get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4647 FOR_EACH_VEC_ELT (lhsc, j, c)
4649 struct constraint_expr *c2;
4650 while (rhsc.length () > 0)
4652 c2 = &rhsc.last ();
4653 process_constraint (new_constraint (*c, *c2));
4654 rhsc.pop ();
4659 /* In IPA mode, we need to generate constraints to pass call
4660 arguments through their calls. There are two cases,
4661 either a GIMPLE_CALL returning a value, or just a plain
4662 GIMPLE_CALL when we are not.
4664 In non-ipa mode, we need to generate constraints for each
4665 pointer passed by address. */
4666 else if (is_gimple_call (t))
4667 find_func_aliases_for_call (fn, as_a <gcall *> (t));
4669 /* Otherwise, just a regular assignment statement. Only care about
4670 operations with pointer result, others are dealt with as escape
4671 points if they have pointer operands. */
4672 else if (is_gimple_assign (t))
4674 /* Otherwise, just a regular assignment statement. */
4675 tree lhsop = gimple_assign_lhs (t);
4676 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4678 if (rhsop && TREE_CLOBBER_P (rhsop))
4679 /* Ignore clobbers, they don't actually store anything into
4680 the LHS. */
4682 else if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4683 do_structure_copy (lhsop, rhsop);
4684 else
4686 enum tree_code code = gimple_assign_rhs_code (t);
4688 get_constraint_for (lhsop, &lhsc);
4690 if (code == POINTER_PLUS_EXPR)
4691 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4692 gimple_assign_rhs2 (t), &rhsc);
4693 else if (code == BIT_AND_EXPR
4694 && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4696 /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4697 the pointer. Handle it by offsetting it by UNKNOWN. */
4698 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4699 NULL_TREE, &rhsc);
4701 else if ((CONVERT_EXPR_CODE_P (code)
4702 && !(POINTER_TYPE_P (gimple_expr_type (t))
4703 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4704 || gimple_assign_single_p (t))
4705 get_constraint_for_rhs (rhsop, &rhsc);
4706 else if (code == COND_EXPR)
4708 /* The result is a merge of both COND_EXPR arms. */
4709 auto_vec<ce_s, 2> tmp;
4710 struct constraint_expr *rhsp;
4711 unsigned i;
4712 get_constraint_for_rhs (gimple_assign_rhs2 (t), &rhsc);
4713 get_constraint_for_rhs (gimple_assign_rhs3 (t), &tmp);
4714 FOR_EACH_VEC_ELT (tmp, i, rhsp)
4715 rhsc.safe_push (*rhsp);
4717 else if (truth_value_p (code))
4718 /* Truth value results are not pointer (parts). Or at least
4719 very unreasonable obfuscation of a part. */
4721 else
4723 /* All other operations are merges. */
4724 auto_vec<ce_s, 4> tmp;
4725 struct constraint_expr *rhsp;
4726 unsigned i, j;
4727 get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4728 for (i = 2; i < gimple_num_ops (t); ++i)
4730 get_constraint_for_rhs (gimple_op (t, i), &tmp);
4731 FOR_EACH_VEC_ELT (tmp, j, rhsp)
4732 rhsc.safe_push (*rhsp);
4733 tmp.truncate (0);
4736 process_all_all_constraints (lhsc, rhsc);
4738 /* If there is a store to a global variable the rhs escapes. */
4739 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4740 && DECL_P (lhsop)
4741 && is_global_var (lhsop)
4742 && (!in_ipa_mode
4743 || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4744 make_escape_constraint (rhsop);
4746 /* Handle escapes through return. */
4747 else if (gimple_code (t) == GIMPLE_RETURN
4748 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE)
4750 greturn *return_stmt = as_a <greturn *> (t);
4751 fi = NULL;
4752 if (!in_ipa_mode
4753 || !(fi = get_vi_for_tree (fn->decl)))
4754 make_escape_constraint (gimple_return_retval (return_stmt));
4755 else if (in_ipa_mode
4756 && fi != NULL)
4758 struct constraint_expr lhs ;
4759 struct constraint_expr *rhsp;
4760 unsigned i;
4762 lhs = get_function_part_constraint (fi, fi_result);
4763 get_constraint_for_rhs (gimple_return_retval (return_stmt), &rhsc);
4764 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4765 process_constraint (new_constraint (lhs, *rhsp));
4768 /* Handle asms conservatively by adding escape constraints to everything. */
4769 else if (gasm *asm_stmt = dyn_cast <gasm *> (t))
4771 unsigned i, noutputs;
4772 const char **oconstraints;
4773 const char *constraint;
4774 bool allows_mem, allows_reg, is_inout;
4776 noutputs = gimple_asm_noutputs (asm_stmt);
4777 oconstraints = XALLOCAVEC (const char *, noutputs);
4779 for (i = 0; i < noutputs; ++i)
4781 tree link = gimple_asm_output_op (asm_stmt, i);
4782 tree op = TREE_VALUE (link);
4784 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4785 oconstraints[i] = constraint;
4786 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4787 &allows_reg, &is_inout);
4789 /* A memory constraint makes the address of the operand escape. */
4790 if (!allows_reg && allows_mem)
4791 make_escape_constraint (build_fold_addr_expr (op));
4793 /* The asm may read global memory, so outputs may point to
4794 any global memory. */
4795 if (op)
4797 auto_vec<ce_s, 2> lhsc;
4798 struct constraint_expr rhsc, *lhsp;
4799 unsigned j;
4800 get_constraint_for (op, &lhsc);
4801 rhsc.var = nonlocal_id;
4802 rhsc.offset = 0;
4803 rhsc.type = SCALAR;
4804 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4805 process_constraint (new_constraint (*lhsp, rhsc));
4808 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4810 tree link = gimple_asm_input_op (asm_stmt, i);
4811 tree op = TREE_VALUE (link);
4813 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4815 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4816 &allows_mem, &allows_reg);
4818 /* A memory constraint makes the address of the operand escape. */
4819 if (!allows_reg && allows_mem)
4820 make_escape_constraint (build_fold_addr_expr (op));
4821 /* Strictly we'd only need the constraint to ESCAPED if
4822 the asm clobbers memory, otherwise using something
4823 along the lines of per-call clobbers/uses would be enough. */
4824 else if (op)
4825 make_escape_constraint (op);
4831 /* Create a constraint adding to the clobber set of FI the memory
4832 pointed to by PTR. */
4834 static void
4835 process_ipa_clobber (varinfo_t fi, tree ptr)
4837 vec<ce_s> ptrc = vNULL;
4838 struct constraint_expr *c, lhs;
4839 unsigned i;
4840 get_constraint_for_rhs (ptr, &ptrc);
4841 lhs = get_function_part_constraint (fi, fi_clobbers);
4842 FOR_EACH_VEC_ELT (ptrc, i, c)
4843 process_constraint (new_constraint (lhs, *c));
4844 ptrc.release ();
4847 /* Walk statement T setting up clobber and use constraints according to the
4848 references found in T. This function is a main part of the
4849 IPA constraint builder. */
4851 static void
4852 find_func_clobbers (struct function *fn, gimple *origt)
4854 gimple *t = origt;
4855 auto_vec<ce_s, 16> lhsc;
4856 auto_vec<ce_s, 16> rhsc;
4857 varinfo_t fi;
4859 /* Add constraints for clobbered/used in IPA mode.
4860 We are not interested in what automatic variables are clobbered
4861 or used as we only use the information in the caller to which
4862 they do not escape. */
4863 gcc_assert (in_ipa_mode);
4865 /* If the stmt refers to memory in any way it better had a VUSE. */
4866 if (gimple_vuse (t) == NULL_TREE)
4867 return;
4869 /* We'd better have function information for the current function. */
4870 fi = lookup_vi_for_tree (fn->decl);
4871 gcc_assert (fi != NULL);
4873 /* Account for stores in assignments and calls. */
4874 if (gimple_vdef (t) != NULL_TREE
4875 && gimple_has_lhs (t))
4877 tree lhs = gimple_get_lhs (t);
4878 tree tem = lhs;
4879 while (handled_component_p (tem))
4880 tem = TREE_OPERAND (tem, 0);
4881 if ((DECL_P (tem)
4882 && !auto_var_in_fn_p (tem, fn->decl))
4883 || INDIRECT_REF_P (tem)
4884 || (TREE_CODE (tem) == MEM_REF
4885 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4886 && auto_var_in_fn_p
4887 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4889 struct constraint_expr lhsc, *rhsp;
4890 unsigned i;
4891 lhsc = get_function_part_constraint (fi, fi_clobbers);
4892 get_constraint_for_address_of (lhs, &rhsc);
4893 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4894 process_constraint (new_constraint (lhsc, *rhsp));
4895 rhsc.truncate (0);
4899 /* Account for uses in assigments and returns. */
4900 if (gimple_assign_single_p (t)
4901 || (gimple_code (t) == GIMPLE_RETURN
4902 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE))
4904 tree rhs = (gimple_assign_single_p (t)
4905 ? gimple_assign_rhs1 (t)
4906 : gimple_return_retval (as_a <greturn *> (t)));
4907 tree tem = rhs;
4908 while (handled_component_p (tem))
4909 tem = TREE_OPERAND (tem, 0);
4910 if ((DECL_P (tem)
4911 && !auto_var_in_fn_p (tem, fn->decl))
4912 || INDIRECT_REF_P (tem)
4913 || (TREE_CODE (tem) == MEM_REF
4914 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4915 && auto_var_in_fn_p
4916 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4918 struct constraint_expr lhs, *rhsp;
4919 unsigned i;
4920 lhs = get_function_part_constraint (fi, fi_uses);
4921 get_constraint_for_address_of (rhs, &rhsc);
4922 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4923 process_constraint (new_constraint (lhs, *rhsp));
4924 rhsc.truncate (0);
4928 if (gcall *call_stmt = dyn_cast <gcall *> (t))
4930 varinfo_t cfi = NULL;
4931 tree decl = gimple_call_fndecl (t);
4932 struct constraint_expr lhs, rhs;
4933 unsigned i, j;
4935 /* For builtins we do not have separate function info. For those
4936 we do not generate escapes for we have to generate clobbers/uses. */
4937 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4938 switch (DECL_FUNCTION_CODE (decl))
4940 /* The following functions use and clobber memory pointed to
4941 by their arguments. */
4942 case BUILT_IN_STRCPY:
4943 case BUILT_IN_STRNCPY:
4944 case BUILT_IN_BCOPY:
4945 case BUILT_IN_MEMCPY:
4946 case BUILT_IN_MEMMOVE:
4947 case BUILT_IN_MEMPCPY:
4948 case BUILT_IN_STPCPY:
4949 case BUILT_IN_STPNCPY:
4950 case BUILT_IN_STRCAT:
4951 case BUILT_IN_STRNCAT:
4952 case BUILT_IN_STRCPY_CHK:
4953 case BUILT_IN_STRNCPY_CHK:
4954 case BUILT_IN_MEMCPY_CHK:
4955 case BUILT_IN_MEMMOVE_CHK:
4956 case BUILT_IN_MEMPCPY_CHK:
4957 case BUILT_IN_STPCPY_CHK:
4958 case BUILT_IN_STPNCPY_CHK:
4959 case BUILT_IN_STRCAT_CHK:
4960 case BUILT_IN_STRNCAT_CHK:
4962 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4963 == BUILT_IN_BCOPY ? 1 : 0));
4964 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4965 == BUILT_IN_BCOPY ? 0 : 1));
4966 unsigned i;
4967 struct constraint_expr *rhsp, *lhsp;
4968 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4969 lhs = get_function_part_constraint (fi, fi_clobbers);
4970 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4971 process_constraint (new_constraint (lhs, *lhsp));
4972 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4973 lhs = get_function_part_constraint (fi, fi_uses);
4974 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4975 process_constraint (new_constraint (lhs, *rhsp));
4976 return;
4978 /* The following function clobbers memory pointed to by
4979 its argument. */
4980 case BUILT_IN_MEMSET:
4981 case BUILT_IN_MEMSET_CHK:
4982 case BUILT_IN_POSIX_MEMALIGN:
4984 tree dest = gimple_call_arg (t, 0);
4985 unsigned i;
4986 ce_s *lhsp;
4987 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4988 lhs = get_function_part_constraint (fi, fi_clobbers);
4989 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4990 process_constraint (new_constraint (lhs, *lhsp));
4991 return;
4993 /* The following functions clobber their second and third
4994 arguments. */
4995 case BUILT_IN_SINCOS:
4996 case BUILT_IN_SINCOSF:
4997 case BUILT_IN_SINCOSL:
4999 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5000 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5001 return;
5003 /* The following functions clobber their second argument. */
5004 case BUILT_IN_FREXP:
5005 case BUILT_IN_FREXPF:
5006 case BUILT_IN_FREXPL:
5007 case BUILT_IN_LGAMMA_R:
5008 case BUILT_IN_LGAMMAF_R:
5009 case BUILT_IN_LGAMMAL_R:
5010 case BUILT_IN_GAMMA_R:
5011 case BUILT_IN_GAMMAF_R:
5012 case BUILT_IN_GAMMAL_R:
5013 case BUILT_IN_MODF:
5014 case BUILT_IN_MODFF:
5015 case BUILT_IN_MODFL:
5017 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5018 return;
5020 /* The following functions clobber their third argument. */
5021 case BUILT_IN_REMQUO:
5022 case BUILT_IN_REMQUOF:
5023 case BUILT_IN_REMQUOL:
5025 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5026 return;
5028 /* The following functions neither read nor clobber memory. */
5029 case BUILT_IN_ASSUME_ALIGNED:
5030 case BUILT_IN_FREE:
5031 return;
5032 /* Trampolines are of no interest to us. */
5033 case BUILT_IN_INIT_TRAMPOLINE:
5034 case BUILT_IN_ADJUST_TRAMPOLINE:
5035 return;
5036 case BUILT_IN_VA_START:
5037 case BUILT_IN_VA_END:
5038 return;
5039 /* printf-style functions may have hooks to set pointers to
5040 point to somewhere into the generated string. Leave them
5041 for a later exercise... */
5042 default:
5043 /* Fallthru to general call handling. */;
5046 /* Parameters passed by value are used. */
5047 lhs = get_function_part_constraint (fi, fi_uses);
5048 for (i = 0; i < gimple_call_num_args (t); i++)
5050 struct constraint_expr *rhsp;
5051 tree arg = gimple_call_arg (t, i);
5053 if (TREE_CODE (arg) == SSA_NAME
5054 || is_gimple_min_invariant (arg))
5055 continue;
5057 get_constraint_for_address_of (arg, &rhsc);
5058 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5059 process_constraint (new_constraint (lhs, *rhsp));
5060 rhsc.truncate (0);
5063 /* Build constraints for propagating clobbers/uses along the
5064 callgraph edges. */
5065 cfi = get_fi_for_callee (call_stmt);
5066 if (cfi->id == anything_id)
5068 if (gimple_vdef (t))
5069 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5070 anything_id);
5071 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5072 anything_id);
5073 return;
5076 /* For callees without function info (that's external functions),
5077 ESCAPED is clobbered and used. */
5078 if (gimple_call_fndecl (t)
5079 && !cfi->is_fn_info)
5081 varinfo_t vi;
5083 if (gimple_vdef (t))
5084 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5085 escaped_id);
5086 make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
5088 /* Also honor the call statement use/clobber info. */
5089 if ((vi = lookup_call_clobber_vi (call_stmt)) != NULL)
5090 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5091 vi->id);
5092 if ((vi = lookup_call_use_vi (call_stmt)) != NULL)
5093 make_copy_constraint (first_vi_for_offset (fi, fi_uses),
5094 vi->id);
5095 return;
5098 /* Otherwise the caller clobbers and uses what the callee does.
5099 ??? This should use a new complex constraint that filters
5100 local variables of the callee. */
5101 if (gimple_vdef (t))
5103 lhs = get_function_part_constraint (fi, fi_clobbers);
5104 rhs = get_function_part_constraint (cfi, fi_clobbers);
5105 process_constraint (new_constraint (lhs, rhs));
5107 lhs = get_function_part_constraint (fi, fi_uses);
5108 rhs = get_function_part_constraint (cfi, fi_uses);
5109 process_constraint (new_constraint (lhs, rhs));
5111 else if (gimple_code (t) == GIMPLE_ASM)
5113 /* ??? Ick. We can do better. */
5114 if (gimple_vdef (t))
5115 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5116 anything_id);
5117 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5118 anything_id);
5123 /* Find the first varinfo in the same variable as START that overlaps with
5124 OFFSET. Return NULL if we can't find one. */
5126 static varinfo_t
5127 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
5129 /* If the offset is outside of the variable, bail out. */
5130 if (offset >= start->fullsize)
5131 return NULL;
5133 /* If we cannot reach offset from start, lookup the first field
5134 and start from there. */
5135 if (start->offset > offset)
5136 start = get_varinfo (start->head);
5138 while (start)
5140 /* We may not find a variable in the field list with the actual
5141 offset when we have glommed a structure to a variable.
5142 In that case, however, offset should still be within the size
5143 of the variable. */
5144 if (offset >= start->offset
5145 && (offset - start->offset) < start->size)
5146 return start;
5148 start = vi_next (start);
5151 return NULL;
5154 /* Find the first varinfo in the same variable as START that overlaps with
5155 OFFSET. If there is no such varinfo the varinfo directly preceding
5156 OFFSET is returned. */
5158 static varinfo_t
5159 first_or_preceding_vi_for_offset (varinfo_t start,
5160 unsigned HOST_WIDE_INT offset)
5162 /* If we cannot reach offset from start, lookup the first field
5163 and start from there. */
5164 if (start->offset > offset)
5165 start = get_varinfo (start->head);
5167 /* We may not find a variable in the field list with the actual
5168 offset when we have glommed a structure to a variable.
5169 In that case, however, offset should still be within the size
5170 of the variable.
5171 If we got beyond the offset we look for return the field
5172 directly preceding offset which may be the last field. */
5173 while (start->next
5174 && offset >= start->offset
5175 && !((offset - start->offset) < start->size))
5176 start = vi_next (start);
5178 return start;
5182 /* This structure is used during pushing fields onto the fieldstack
5183 to track the offset of the field, since bitpos_of_field gives it
5184 relative to its immediate containing type, and we want it relative
5185 to the ultimate containing object. */
5187 struct fieldoff
5189 /* Offset from the base of the base containing object to this field. */
5190 HOST_WIDE_INT offset;
5192 /* Size, in bits, of the field. */
5193 unsigned HOST_WIDE_INT size;
5195 unsigned has_unknown_size : 1;
5197 unsigned must_have_pointers : 1;
5199 unsigned may_have_pointers : 1;
5201 unsigned only_restrict_pointers : 1;
5203 tree restrict_pointed_type;
5205 typedef struct fieldoff fieldoff_s;
5208 /* qsort comparison function for two fieldoff's PA and PB */
5210 static int
5211 fieldoff_compare (const void *pa, const void *pb)
5213 const fieldoff_s *foa = (const fieldoff_s *)pa;
5214 const fieldoff_s *fob = (const fieldoff_s *)pb;
5215 unsigned HOST_WIDE_INT foasize, fobsize;
5217 if (foa->offset < fob->offset)
5218 return -1;
5219 else if (foa->offset > fob->offset)
5220 return 1;
5222 foasize = foa->size;
5223 fobsize = fob->size;
5224 if (foasize < fobsize)
5225 return -1;
5226 else if (foasize > fobsize)
5227 return 1;
5228 return 0;
5231 /* Sort a fieldstack according to the field offset and sizes. */
5232 static void
5233 sort_fieldstack (vec<fieldoff_s> fieldstack)
5235 fieldstack.qsort (fieldoff_compare);
5238 /* Return true if T is a type that can have subvars. */
5240 static inline bool
5241 type_can_have_subvars (const_tree t)
5243 /* Aggregates without overlapping fields can have subvars. */
5244 return TREE_CODE (t) == RECORD_TYPE;
5247 /* Return true if V is a tree that we can have subvars for.
5248 Normally, this is any aggregate type. Also complex
5249 types which are not gimple registers can have subvars. */
5251 static inline bool
5252 var_can_have_subvars (const_tree v)
5254 /* Volatile variables should never have subvars. */
5255 if (TREE_THIS_VOLATILE (v))
5256 return false;
5258 /* Non decls or memory tags can never have subvars. */
5259 if (!DECL_P (v))
5260 return false;
5262 return type_can_have_subvars (TREE_TYPE (v));
5265 /* Return true if T is a type that does contain pointers. */
5267 static bool
5268 type_must_have_pointers (tree type)
5270 if (POINTER_TYPE_P (type))
5271 return true;
5273 if (TREE_CODE (type) == ARRAY_TYPE)
5274 return type_must_have_pointers (TREE_TYPE (type));
5276 /* A function or method can have pointers as arguments, so track
5277 those separately. */
5278 if (TREE_CODE (type) == FUNCTION_TYPE
5279 || TREE_CODE (type) == METHOD_TYPE)
5280 return true;
5282 return false;
5285 static bool
5286 field_must_have_pointers (tree t)
5288 return type_must_have_pointers (TREE_TYPE (t));
5291 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5292 the fields of TYPE onto fieldstack, recording their offsets along
5293 the way.
5295 OFFSET is used to keep track of the offset in this entire
5296 structure, rather than just the immediately containing structure.
5297 Returns false if the caller is supposed to handle the field we
5298 recursed for. */
5300 static bool
5301 push_fields_onto_fieldstack (tree type, vec<fieldoff_s> *fieldstack,
5302 HOST_WIDE_INT offset)
5304 tree field;
5305 bool empty_p = true;
5307 if (TREE_CODE (type) != RECORD_TYPE)
5308 return false;
5310 /* If the vector of fields is growing too big, bail out early.
5311 Callers check for vec::length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5312 sure this fails. */
5313 if (fieldstack->length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5314 return false;
5316 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5317 if (TREE_CODE (field) == FIELD_DECL)
5319 bool push = false;
5320 HOST_WIDE_INT foff = bitpos_of_field (field);
5321 tree field_type = TREE_TYPE (field);
5323 if (!var_can_have_subvars (field)
5324 || TREE_CODE (field_type) == QUAL_UNION_TYPE
5325 || TREE_CODE (field_type) == UNION_TYPE)
5326 push = true;
5327 else if (!push_fields_onto_fieldstack
5328 (field_type, fieldstack, offset + foff)
5329 && (DECL_SIZE (field)
5330 && !integer_zerop (DECL_SIZE (field))))
5331 /* Empty structures may have actual size, like in C++. So
5332 see if we didn't push any subfields and the size is
5333 nonzero, push the field onto the stack. */
5334 push = true;
5336 if (push)
5338 fieldoff_s *pair = NULL;
5339 bool has_unknown_size = false;
5340 bool must_have_pointers_p;
5342 if (!fieldstack->is_empty ())
5343 pair = &fieldstack->last ();
5345 /* If there isn't anything at offset zero, create sth. */
5346 if (!pair
5347 && offset + foff != 0)
5349 fieldoff_s e
5350 = {0, offset + foff, false, false, false, false, NULL_TREE};
5351 pair = fieldstack->safe_push (e);
5354 if (!DECL_SIZE (field)
5355 || !tree_fits_uhwi_p (DECL_SIZE (field)))
5356 has_unknown_size = true;
5358 /* If adjacent fields do not contain pointers merge them. */
5359 must_have_pointers_p = field_must_have_pointers (field);
5360 if (pair
5361 && !has_unknown_size
5362 && !must_have_pointers_p
5363 && !pair->must_have_pointers
5364 && !pair->has_unknown_size
5365 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5367 pair->size += tree_to_uhwi (DECL_SIZE (field));
5369 else
5371 fieldoff_s e;
5372 e.offset = offset + foff;
5373 e.has_unknown_size = has_unknown_size;
5374 if (!has_unknown_size)
5375 e.size = tree_to_uhwi (DECL_SIZE (field));
5376 else
5377 e.size = -1;
5378 e.must_have_pointers = must_have_pointers_p;
5379 e.may_have_pointers = true;
5380 e.only_restrict_pointers
5381 = (!has_unknown_size
5382 && POINTER_TYPE_P (field_type)
5383 && TYPE_RESTRICT (field_type));
5384 if (e.only_restrict_pointers)
5385 e.restrict_pointed_type = TREE_TYPE (field_type);
5386 fieldstack->safe_push (e);
5390 empty_p = false;
5393 return !empty_p;
5396 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5397 if it is a varargs function. */
5399 static unsigned int
5400 count_num_arguments (tree decl, bool *is_varargs)
5402 unsigned int num = 0;
5403 tree t;
5405 /* Capture named arguments for K&R functions. They do not
5406 have a prototype and thus no TYPE_ARG_TYPES. */
5407 for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5408 ++num;
5410 /* Check if the function has variadic arguments. */
5411 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5412 if (TREE_VALUE (t) == void_type_node)
5413 break;
5414 if (!t)
5415 *is_varargs = true;
5417 return num;
5420 /* Creation function node for DECL, using NAME, and return the index
5421 of the variable we've created for the function. If NONLOCAL_p, create
5422 initial constraints. */
5424 static varinfo_t
5425 create_function_info_for (tree decl, const char *name, bool add_id,
5426 bool nonlocal_p)
5428 struct function *fn = DECL_STRUCT_FUNCTION (decl);
5429 varinfo_t vi, prev_vi;
5430 tree arg;
5431 unsigned int i;
5432 bool is_varargs = false;
5433 unsigned int num_args = count_num_arguments (decl, &is_varargs);
5435 /* Create the variable info. */
5437 vi = new_var_info (decl, name, add_id);
5438 vi->offset = 0;
5439 vi->size = 1;
5440 vi->fullsize = fi_parm_base + num_args;
5441 vi->is_fn_info = 1;
5442 vi->may_have_pointers = false;
5443 if (is_varargs)
5444 vi->fullsize = ~0;
5445 insert_vi_for_tree (vi->decl, vi);
5447 prev_vi = vi;
5449 /* Create a variable for things the function clobbers and one for
5450 things the function uses. */
5452 varinfo_t clobbervi, usevi;
5453 const char *newname;
5454 char *tempname;
5456 tempname = xasprintf ("%s.clobber", name);
5457 newname = ggc_strdup (tempname);
5458 free (tempname);
5460 clobbervi = new_var_info (NULL, newname, false);
5461 clobbervi->offset = fi_clobbers;
5462 clobbervi->size = 1;
5463 clobbervi->fullsize = vi->fullsize;
5464 clobbervi->is_full_var = true;
5465 clobbervi->is_global_var = false;
5467 gcc_assert (prev_vi->offset < clobbervi->offset);
5468 prev_vi->next = clobbervi->id;
5469 prev_vi = clobbervi;
5471 tempname = xasprintf ("%s.use", name);
5472 newname = ggc_strdup (tempname);
5473 free (tempname);
5475 usevi = new_var_info (NULL, newname, false);
5476 usevi->offset = fi_uses;
5477 usevi->size = 1;
5478 usevi->fullsize = vi->fullsize;
5479 usevi->is_full_var = true;
5480 usevi->is_global_var = false;
5482 gcc_assert (prev_vi->offset < usevi->offset);
5483 prev_vi->next = usevi->id;
5484 prev_vi = usevi;
5487 /* And one for the static chain. */
5488 if (fn->static_chain_decl != NULL_TREE)
5490 varinfo_t chainvi;
5491 const char *newname;
5492 char *tempname;
5494 tempname = xasprintf ("%s.chain", name);
5495 newname = ggc_strdup (tempname);
5496 free (tempname);
5498 chainvi = new_var_info (fn->static_chain_decl, newname, false);
5499 chainvi->offset = fi_static_chain;
5500 chainvi->size = 1;
5501 chainvi->fullsize = vi->fullsize;
5502 chainvi->is_full_var = true;
5503 chainvi->is_global_var = false;
5505 insert_vi_for_tree (fn->static_chain_decl, chainvi);
5507 if (nonlocal_p
5508 && chainvi->may_have_pointers)
5509 make_constraint_from (chainvi, nonlocal_id);
5511 gcc_assert (prev_vi->offset < chainvi->offset);
5512 prev_vi->next = chainvi->id;
5513 prev_vi = chainvi;
5516 /* Create a variable for the return var. */
5517 if (DECL_RESULT (decl) != NULL
5518 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5520 varinfo_t resultvi;
5521 const char *newname;
5522 char *tempname;
5523 tree resultdecl = decl;
5525 if (DECL_RESULT (decl))
5526 resultdecl = DECL_RESULT (decl);
5528 tempname = xasprintf ("%s.result", name);
5529 newname = ggc_strdup (tempname);
5530 free (tempname);
5532 resultvi = new_var_info (resultdecl, newname, false);
5533 resultvi->offset = fi_result;
5534 resultvi->size = 1;
5535 resultvi->fullsize = vi->fullsize;
5536 resultvi->is_full_var = true;
5537 if (DECL_RESULT (decl))
5538 resultvi->may_have_pointers = true;
5540 if (DECL_RESULT (decl))
5541 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5543 gcc_assert (prev_vi->offset < resultvi->offset);
5544 prev_vi->next = resultvi->id;
5545 prev_vi = resultvi;
5548 /* We also need to make function return values escape. Nothing
5549 escapes by returning from main though. */
5550 if (nonlocal_p
5551 && !MAIN_NAME_P (DECL_NAME (decl)))
5553 varinfo_t fi, rvi;
5554 fi = lookup_vi_for_tree (decl);
5555 rvi = first_vi_for_offset (fi, fi_result);
5556 if (rvi && rvi->offset == fi_result)
5557 make_copy_constraint (get_varinfo (escaped_id), rvi->id);
5560 /* Set up variables for each argument. */
5561 arg = DECL_ARGUMENTS (decl);
5562 for (i = 0; i < num_args; i++)
5564 varinfo_t argvi;
5565 const char *newname;
5566 char *tempname;
5567 tree argdecl = decl;
5569 if (arg)
5570 argdecl = arg;
5572 tempname = xasprintf ("%s.arg%d", name, i);
5573 newname = ggc_strdup (tempname);
5574 free (tempname);
5576 argvi = new_var_info (argdecl, newname, false);
5577 argvi->offset = fi_parm_base + i;
5578 argvi->size = 1;
5579 argvi->is_full_var = true;
5580 argvi->fullsize = vi->fullsize;
5581 if (arg)
5582 argvi->may_have_pointers = true;
5584 if (arg)
5585 insert_vi_for_tree (arg, argvi);
5587 if (nonlocal_p
5588 && argvi->may_have_pointers)
5589 make_constraint_from (argvi, nonlocal_id);
5591 gcc_assert (prev_vi->offset < argvi->offset);
5592 prev_vi->next = argvi->id;
5593 prev_vi = argvi;
5594 if (arg)
5595 arg = DECL_CHAIN (arg);
5598 /* Add one representative for all further args. */
5599 if (is_varargs)
5601 varinfo_t argvi;
5602 const char *newname;
5603 char *tempname;
5604 tree decl;
5606 tempname = xasprintf ("%s.varargs", name);
5607 newname = ggc_strdup (tempname);
5608 free (tempname);
5610 /* We need sth that can be pointed to for va_start. */
5611 decl = build_fake_var_decl (ptr_type_node);
5613 argvi = new_var_info (decl, newname, false);
5614 argvi->offset = fi_parm_base + num_args;
5615 argvi->size = ~0;
5616 argvi->is_full_var = true;
5617 argvi->is_heap_var = true;
5618 argvi->fullsize = vi->fullsize;
5620 if (nonlocal_p
5621 && argvi->may_have_pointers)
5622 make_constraint_from (argvi, nonlocal_id);
5624 gcc_assert (prev_vi->offset < argvi->offset);
5625 prev_vi->next = argvi->id;
5626 prev_vi = argvi;
5629 return vi;
5633 /* Return true if FIELDSTACK contains fields that overlap.
5634 FIELDSTACK is assumed to be sorted by offset. */
5636 static bool
5637 check_for_overlaps (vec<fieldoff_s> fieldstack)
5639 fieldoff_s *fo = NULL;
5640 unsigned int i;
5641 HOST_WIDE_INT lastoffset = -1;
5643 FOR_EACH_VEC_ELT (fieldstack, i, fo)
5645 if (fo->offset == lastoffset)
5646 return true;
5647 lastoffset = fo->offset;
5649 return false;
5652 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5653 This will also create any varinfo structures necessary for fields
5654 of DECL. DECL is a function parameter if HANDLE_PARAM is set. */
5656 static varinfo_t
5657 create_variable_info_for_1 (tree decl, const char *name, bool add_id,
5658 bool handle_param)
5660 varinfo_t vi, newvi;
5661 tree decl_type = TREE_TYPE (decl);
5662 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5663 auto_vec<fieldoff_s> fieldstack;
5664 fieldoff_s *fo;
5665 unsigned int i;
5667 if (!declsize
5668 || !tree_fits_uhwi_p (declsize))
5670 vi = new_var_info (decl, name, add_id);
5671 vi->offset = 0;
5672 vi->size = ~0;
5673 vi->fullsize = ~0;
5674 vi->is_unknown_size_var = true;
5675 vi->is_full_var = true;
5676 vi->may_have_pointers = true;
5677 return vi;
5680 /* Collect field information. */
5681 if (use_field_sensitive
5682 && var_can_have_subvars (decl)
5683 /* ??? Force us to not use subfields for globals in IPA mode.
5684 Else we'd have to parse arbitrary initializers. */
5685 && !(in_ipa_mode
5686 && is_global_var (decl)))
5688 fieldoff_s *fo = NULL;
5689 bool notokay = false;
5690 unsigned int i;
5692 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5694 for (i = 0; !notokay && fieldstack.iterate (i, &fo); i++)
5695 if (fo->has_unknown_size
5696 || fo->offset < 0)
5698 notokay = true;
5699 break;
5702 /* We can't sort them if we have a field with a variable sized type,
5703 which will make notokay = true. In that case, we are going to return
5704 without creating varinfos for the fields anyway, so sorting them is a
5705 waste to boot. */
5706 if (!notokay)
5708 sort_fieldstack (fieldstack);
5709 /* Due to some C++ FE issues, like PR 22488, we might end up
5710 what appear to be overlapping fields even though they,
5711 in reality, do not overlap. Until the C++ FE is fixed,
5712 we will simply disable field-sensitivity for these cases. */
5713 notokay = check_for_overlaps (fieldstack);
5716 if (notokay)
5717 fieldstack.release ();
5720 /* If we didn't end up collecting sub-variables create a full
5721 variable for the decl. */
5722 if (fieldstack.length () == 0
5723 || fieldstack.length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5725 vi = new_var_info (decl, name, add_id);
5726 vi->offset = 0;
5727 vi->may_have_pointers = true;
5728 vi->fullsize = tree_to_uhwi (declsize);
5729 vi->size = vi->fullsize;
5730 vi->is_full_var = true;
5731 if (POINTER_TYPE_P (decl_type)
5732 && TYPE_RESTRICT (decl_type))
5733 vi->only_restrict_pointers = 1;
5734 if (vi->only_restrict_pointers
5735 && !type_contains_placeholder_p (TREE_TYPE (decl_type))
5736 && handle_param)
5738 varinfo_t rvi;
5739 tree heapvar = build_fake_var_decl (TREE_TYPE (decl_type));
5740 DECL_EXTERNAL (heapvar) = 1;
5741 rvi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS", true,
5742 true);
5743 rvi->is_restrict_var = 1;
5744 insert_vi_for_tree (heapvar, rvi);
5745 make_constraint_from (vi, rvi->id);
5746 make_param_constraints (rvi);
5748 fieldstack.release ();
5749 return vi;
5752 vi = new_var_info (decl, name, add_id);
5753 vi->fullsize = tree_to_uhwi (declsize);
5754 if (fieldstack.length () == 1)
5755 vi->is_full_var = true;
5756 for (i = 0, newvi = vi;
5757 fieldstack.iterate (i, &fo);
5758 ++i, newvi = vi_next (newvi))
5760 const char *newname = NULL;
5761 char *tempname;
5763 if (dump_file)
5765 if (fieldstack.length () != 1)
5767 tempname
5768 = xasprintf ("%s." HOST_WIDE_INT_PRINT_DEC
5769 "+" HOST_WIDE_INT_PRINT_DEC, name,
5770 fo->offset, fo->size);
5771 newname = ggc_strdup (tempname);
5772 free (tempname);
5775 else
5776 newname = "NULL";
5778 if (newname)
5779 newvi->name = newname;
5780 newvi->offset = fo->offset;
5781 newvi->size = fo->size;
5782 newvi->fullsize = vi->fullsize;
5783 newvi->may_have_pointers = fo->may_have_pointers;
5784 newvi->only_restrict_pointers = fo->only_restrict_pointers;
5785 if (handle_param
5786 && newvi->only_restrict_pointers
5787 && !type_contains_placeholder_p (fo->restrict_pointed_type))
5789 varinfo_t rvi;
5790 tree heapvar = build_fake_var_decl (fo->restrict_pointed_type);
5791 DECL_EXTERNAL (heapvar) = 1;
5792 rvi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS", true,
5793 true);
5794 rvi->is_restrict_var = 1;
5795 insert_vi_for_tree (heapvar, rvi);
5796 make_constraint_from (newvi, rvi->id);
5797 make_param_constraints (rvi);
5799 if (i + 1 < fieldstack.length ())
5801 varinfo_t tem = new_var_info (decl, name, false);
5802 newvi->next = tem->id;
5803 tem->head = vi->id;
5807 return vi;
5810 static unsigned int
5811 create_variable_info_for (tree decl, const char *name, bool add_id)
5813 varinfo_t vi = create_variable_info_for_1 (decl, name, add_id, false);
5814 unsigned int id = vi->id;
5816 insert_vi_for_tree (decl, vi);
5818 if (TREE_CODE (decl) != VAR_DECL)
5819 return id;
5821 /* Create initial constraints for globals. */
5822 for (; vi; vi = vi_next (vi))
5824 if (!vi->may_have_pointers
5825 || !vi->is_global_var)
5826 continue;
5828 /* Mark global restrict qualified pointers. */
5829 if ((POINTER_TYPE_P (TREE_TYPE (decl))
5830 && TYPE_RESTRICT (TREE_TYPE (decl)))
5831 || vi->only_restrict_pointers)
5833 varinfo_t rvi
5834 = make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT",
5835 true);
5836 /* ??? For now exclude reads from globals as restrict sources
5837 if those are not (indirectly) from incoming parameters. */
5838 rvi->is_restrict_var = false;
5839 continue;
5842 /* In non-IPA mode the initializer from nonlocal is all we need. */
5843 if (!in_ipa_mode
5844 || DECL_HARD_REGISTER (decl))
5845 make_copy_constraint (vi, nonlocal_id);
5847 /* In IPA mode parse the initializer and generate proper constraints
5848 for it. */
5849 else
5851 varpool_node *vnode = varpool_node::get (decl);
5853 /* For escaped variables initialize them from nonlocal. */
5854 if (!vnode->all_refs_explicit_p ())
5855 make_copy_constraint (vi, nonlocal_id);
5857 /* If this is a global variable with an initializer and we are in
5858 IPA mode generate constraints for it. */
5859 ipa_ref *ref;
5860 for (unsigned idx = 0; vnode->iterate_reference (idx, ref); ++idx)
5862 auto_vec<ce_s> rhsc;
5863 struct constraint_expr lhs, *rhsp;
5864 unsigned i;
5865 get_constraint_for_address_of (ref->referred->decl, &rhsc);
5866 lhs.var = vi->id;
5867 lhs.offset = 0;
5868 lhs.type = SCALAR;
5869 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5870 process_constraint (new_constraint (lhs, *rhsp));
5871 /* If this is a variable that escapes from the unit
5872 the initializer escapes as well. */
5873 if (!vnode->all_refs_explicit_p ())
5875 lhs.var = escaped_id;
5876 lhs.offset = 0;
5877 lhs.type = SCALAR;
5878 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5879 process_constraint (new_constraint (lhs, *rhsp));
5885 return id;
5888 /* Print out the points-to solution for VAR to FILE. */
5890 static void
5891 dump_solution_for_var (FILE *file, unsigned int var)
5893 varinfo_t vi = get_varinfo (var);
5894 unsigned int i;
5895 bitmap_iterator bi;
5897 /* Dump the solution for unified vars anyway, this avoids difficulties
5898 in scanning dumps in the testsuite. */
5899 fprintf (file, "%s = { ", vi->name);
5900 vi = get_varinfo (find (var));
5901 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5902 fprintf (file, "%s ", get_varinfo (i)->name);
5903 fprintf (file, "}");
5905 /* But note when the variable was unified. */
5906 if (vi->id != var)
5907 fprintf (file, " same as %s", vi->name);
5909 fprintf (file, "\n");
5912 /* Print the points-to solution for VAR to stderr. */
5914 DEBUG_FUNCTION void
5915 debug_solution_for_var (unsigned int var)
5917 dump_solution_for_var (stderr, var);
5920 /* Register the constraints for function parameter related VI. */
5922 static void
5923 make_param_constraints (varinfo_t vi)
5925 for (; vi; vi = vi_next (vi))
5927 if (vi->only_restrict_pointers)
5929 else if (vi->may_have_pointers)
5930 make_constraint_from (vi, nonlocal_id);
5932 if (vi->is_full_var)
5933 break;
5937 /* Create varinfo structures for all of the variables in the
5938 function for intraprocedural mode. */
5940 static void
5941 intra_create_variable_infos (struct function *fn)
5943 tree t;
5945 /* For each incoming pointer argument arg, create the constraint ARG
5946 = NONLOCAL or a dummy variable if it is a restrict qualified
5947 passed-by-reference argument. */
5948 for (t = DECL_ARGUMENTS (fn->decl); t; t = DECL_CHAIN (t))
5950 varinfo_t p
5951 = create_variable_info_for_1 (t, alias_get_name (t), false, true);
5952 insert_vi_for_tree (t, p);
5954 make_param_constraints (p);
5957 /* Add a constraint for a result decl that is passed by reference. */
5958 if (DECL_RESULT (fn->decl)
5959 && DECL_BY_REFERENCE (DECL_RESULT (fn->decl)))
5961 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (fn->decl));
5963 for (p = result_vi; p; p = vi_next (p))
5964 make_constraint_from (p, nonlocal_id);
5967 /* Add a constraint for the incoming static chain parameter. */
5968 if (fn->static_chain_decl != NULL_TREE)
5970 varinfo_t p, chain_vi = get_vi_for_tree (fn->static_chain_decl);
5972 for (p = chain_vi; p; p = vi_next (p))
5973 make_constraint_from (p, nonlocal_id);
5977 /* Structure used to put solution bitmaps in a hashtable so they can
5978 be shared among variables with the same points-to set. */
5980 typedef struct shared_bitmap_info
5982 bitmap pt_vars;
5983 hashval_t hashcode;
5984 } *shared_bitmap_info_t;
5985 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5987 /* Shared_bitmap hashtable helpers. */
5989 struct shared_bitmap_hasher : free_ptr_hash <shared_bitmap_info>
5991 static inline hashval_t hash (const shared_bitmap_info *);
5992 static inline bool equal (const shared_bitmap_info *,
5993 const shared_bitmap_info *);
5996 /* Hash function for a shared_bitmap_info_t */
5998 inline hashval_t
5999 shared_bitmap_hasher::hash (const shared_bitmap_info *bi)
6001 return bi->hashcode;
6004 /* Equality function for two shared_bitmap_info_t's. */
6006 inline bool
6007 shared_bitmap_hasher::equal (const shared_bitmap_info *sbi1,
6008 const shared_bitmap_info *sbi2)
6010 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
6013 /* Shared_bitmap hashtable. */
6015 static hash_table<shared_bitmap_hasher> *shared_bitmap_table;
6017 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
6018 existing instance if there is one, NULL otherwise. */
6020 static bitmap
6021 shared_bitmap_lookup (bitmap pt_vars)
6023 shared_bitmap_info **slot;
6024 struct shared_bitmap_info sbi;
6026 sbi.pt_vars = pt_vars;
6027 sbi.hashcode = bitmap_hash (pt_vars);
6029 slot = shared_bitmap_table->find_slot (&sbi, NO_INSERT);
6030 if (!slot)
6031 return NULL;
6032 else
6033 return (*slot)->pt_vars;
6037 /* Add a bitmap to the shared bitmap hashtable. */
6039 static void
6040 shared_bitmap_add (bitmap pt_vars)
6042 shared_bitmap_info **slot;
6043 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
6045 sbi->pt_vars = pt_vars;
6046 sbi->hashcode = bitmap_hash (pt_vars);
6048 slot = shared_bitmap_table->find_slot (sbi, INSERT);
6049 gcc_assert (!*slot);
6050 *slot = sbi;
6054 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
6056 static void
6057 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
6059 unsigned int i;
6060 bitmap_iterator bi;
6061 varinfo_t escaped_vi = get_varinfo (find (escaped_id));
6062 bool everything_escaped
6063 = escaped_vi->solution && bitmap_bit_p (escaped_vi->solution, anything_id);
6065 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
6067 varinfo_t vi = get_varinfo (i);
6069 /* The only artificial variables that are allowed in a may-alias
6070 set are heap variables. */
6071 if (vi->is_artificial_var && !vi->is_heap_var)
6072 continue;
6074 if (everything_escaped
6075 || (escaped_vi->solution
6076 && bitmap_bit_p (escaped_vi->solution, i)))
6078 pt->vars_contains_escaped = true;
6079 pt->vars_contains_escaped_heap = vi->is_heap_var;
6082 if (TREE_CODE (vi->decl) == VAR_DECL
6083 || TREE_CODE (vi->decl) == PARM_DECL
6084 || TREE_CODE (vi->decl) == RESULT_DECL)
6086 /* If we are in IPA mode we will not recompute points-to
6087 sets after inlining so make sure they stay valid. */
6088 if (in_ipa_mode
6089 && !DECL_PT_UID_SET_P (vi->decl))
6090 SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
6092 /* Add the decl to the points-to set. Note that the points-to
6093 set contains global variables. */
6094 bitmap_set_bit (into, DECL_PT_UID (vi->decl));
6095 if (vi->is_global_var)
6096 pt->vars_contains_nonlocal = true;
6102 /* Compute the points-to solution *PT for the variable VI. */
6104 static struct pt_solution
6105 find_what_var_points_to (varinfo_t orig_vi)
6107 unsigned int i;
6108 bitmap_iterator bi;
6109 bitmap finished_solution;
6110 bitmap result;
6111 varinfo_t vi;
6112 struct pt_solution *pt;
6114 /* This variable may have been collapsed, let's get the real
6115 variable. */
6116 vi = get_varinfo (find (orig_vi->id));
6118 /* See if we have already computed the solution and return it. */
6119 pt_solution **slot = &final_solutions->get_or_insert (vi);
6120 if (*slot != NULL)
6121 return **slot;
6123 *slot = pt = XOBNEW (&final_solutions_obstack, struct pt_solution);
6124 memset (pt, 0, sizeof (struct pt_solution));
6126 /* Translate artificial variables into SSA_NAME_PTR_INFO
6127 attributes. */
6128 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6130 varinfo_t vi = get_varinfo (i);
6132 if (vi->is_artificial_var)
6134 if (vi->id == nothing_id)
6135 pt->null = 1;
6136 else if (vi->id == escaped_id)
6138 if (in_ipa_mode)
6139 pt->ipa_escaped = 1;
6140 else
6141 pt->escaped = 1;
6142 /* Expand some special vars of ESCAPED in-place here. */
6143 varinfo_t evi = get_varinfo (find (escaped_id));
6144 if (bitmap_bit_p (evi->solution, nonlocal_id))
6145 pt->nonlocal = 1;
6147 else if (vi->id == nonlocal_id)
6148 pt->nonlocal = 1;
6149 else if (vi->is_heap_var)
6150 /* We represent heapvars in the points-to set properly. */
6152 else if (vi->id == string_id)
6153 /* Nobody cares - STRING_CSTs are read-only entities. */
6155 else if (vi->id == anything_id
6156 || vi->id == integer_id)
6157 pt->anything = 1;
6161 /* Instead of doing extra work, simply do not create
6162 elaborate points-to information for pt_anything pointers. */
6163 if (pt->anything)
6164 return *pt;
6166 /* Share the final set of variables when possible. */
6167 finished_solution = BITMAP_GGC_ALLOC ();
6168 stats.points_to_sets_created++;
6170 set_uids_in_ptset (finished_solution, vi->solution, pt);
6171 result = shared_bitmap_lookup (finished_solution);
6172 if (!result)
6174 shared_bitmap_add (finished_solution);
6175 pt->vars = finished_solution;
6177 else
6179 pt->vars = result;
6180 bitmap_clear (finished_solution);
6183 return *pt;
6186 /* Given a pointer variable P, fill in its points-to set. */
6188 static void
6189 find_what_p_points_to (tree p)
6191 struct ptr_info_def *pi;
6192 tree lookup_p = p;
6193 varinfo_t vi;
6195 /* For parameters, get at the points-to set for the actual parm
6196 decl. */
6197 if (TREE_CODE (p) == SSA_NAME
6198 && SSA_NAME_IS_DEFAULT_DEF (p)
6199 && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
6200 || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL))
6201 lookup_p = SSA_NAME_VAR (p);
6203 vi = lookup_vi_for_tree (lookup_p);
6204 if (!vi)
6205 return;
6207 pi = get_ptr_info (p);
6208 pi->pt = find_what_var_points_to (vi);
6212 /* Query statistics for points-to solutions. */
6214 static struct {
6215 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
6216 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
6217 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
6218 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
6219 } pta_stats;
6221 void
6222 dump_pta_stats (FILE *s)
6224 fprintf (s, "\nPTA query stats:\n");
6225 fprintf (s, " pt_solution_includes: "
6226 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6227 HOST_WIDE_INT_PRINT_DEC" queries\n",
6228 pta_stats.pt_solution_includes_no_alias,
6229 pta_stats.pt_solution_includes_no_alias
6230 + pta_stats.pt_solution_includes_may_alias);
6231 fprintf (s, " pt_solutions_intersect: "
6232 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6233 HOST_WIDE_INT_PRINT_DEC" queries\n",
6234 pta_stats.pt_solutions_intersect_no_alias,
6235 pta_stats.pt_solutions_intersect_no_alias
6236 + pta_stats.pt_solutions_intersect_may_alias);
6240 /* Reset the points-to solution *PT to a conservative default
6241 (point to anything). */
6243 void
6244 pt_solution_reset (struct pt_solution *pt)
6246 memset (pt, 0, sizeof (struct pt_solution));
6247 pt->anything = true;
6250 /* Set the points-to solution *PT to point only to the variables
6251 in VARS. VARS_CONTAINS_GLOBAL specifies whether that contains
6252 global variables and VARS_CONTAINS_RESTRICT specifies whether
6253 it contains restrict tag variables. */
6255 void
6256 pt_solution_set (struct pt_solution *pt, bitmap vars,
6257 bool vars_contains_nonlocal)
6259 memset (pt, 0, sizeof (struct pt_solution));
6260 pt->vars = vars;
6261 pt->vars_contains_nonlocal = vars_contains_nonlocal;
6262 pt->vars_contains_escaped
6263 = (cfun->gimple_df->escaped.anything
6264 || bitmap_intersect_p (cfun->gimple_df->escaped.vars, vars));
6267 /* Set the points-to solution *PT to point only to the variable VAR. */
6269 void
6270 pt_solution_set_var (struct pt_solution *pt, tree var)
6272 memset (pt, 0, sizeof (struct pt_solution));
6273 pt->vars = BITMAP_GGC_ALLOC ();
6274 bitmap_set_bit (pt->vars, DECL_PT_UID (var));
6275 pt->vars_contains_nonlocal = is_global_var (var);
6276 pt->vars_contains_escaped
6277 = (cfun->gimple_df->escaped.anything
6278 || bitmap_bit_p (cfun->gimple_df->escaped.vars, DECL_PT_UID (var)));
6281 /* Computes the union of the points-to solutions *DEST and *SRC and
6282 stores the result in *DEST. This changes the points-to bitmap
6283 of *DEST and thus may not be used if that might be shared.
6284 The points-to bitmap of *SRC and *DEST will not be shared after
6285 this function if they were not before. */
6287 static void
6288 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
6290 dest->anything |= src->anything;
6291 if (dest->anything)
6293 pt_solution_reset (dest);
6294 return;
6297 dest->nonlocal |= src->nonlocal;
6298 dest->escaped |= src->escaped;
6299 dest->ipa_escaped |= src->ipa_escaped;
6300 dest->null |= src->null;
6301 dest->vars_contains_nonlocal |= src->vars_contains_nonlocal;
6302 dest->vars_contains_escaped |= src->vars_contains_escaped;
6303 dest->vars_contains_escaped_heap |= src->vars_contains_escaped_heap;
6304 if (!src->vars)
6305 return;
6307 if (!dest->vars)
6308 dest->vars = BITMAP_GGC_ALLOC ();
6309 bitmap_ior_into (dest->vars, src->vars);
6312 /* Return true if the points-to solution *PT is empty. */
6314 bool
6315 pt_solution_empty_p (struct pt_solution *pt)
6317 if (pt->anything
6318 || pt->nonlocal)
6319 return false;
6321 if (pt->vars
6322 && !bitmap_empty_p (pt->vars))
6323 return false;
6325 /* If the solution includes ESCAPED, check if that is empty. */
6326 if (pt->escaped
6327 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6328 return false;
6330 /* If the solution includes ESCAPED, check if that is empty. */
6331 if (pt->ipa_escaped
6332 && !pt_solution_empty_p (&ipa_escaped_pt))
6333 return false;
6335 return true;
6338 /* Return true if the points-to solution *PT only point to a single var, and
6339 return the var uid in *UID. */
6341 bool
6342 pt_solution_singleton_p (struct pt_solution *pt, unsigned *uid)
6344 if (pt->anything || pt->nonlocal || pt->escaped || pt->ipa_escaped
6345 || pt->null || pt->vars == NULL
6346 || !bitmap_single_bit_set_p (pt->vars))
6347 return false;
6349 *uid = bitmap_first_set_bit (pt->vars);
6350 return true;
6353 /* Return true if the points-to solution *PT includes global memory. */
6355 bool
6356 pt_solution_includes_global (struct pt_solution *pt)
6358 if (pt->anything
6359 || pt->nonlocal
6360 || pt->vars_contains_nonlocal
6361 /* The following is a hack to make the malloc escape hack work.
6362 In reality we'd need different sets for escaped-through-return
6363 and escaped-to-callees and passes would need to be updated. */
6364 || pt->vars_contains_escaped_heap)
6365 return true;
6367 /* 'escaped' is also a placeholder so we have to look into it. */
6368 if (pt->escaped)
6369 return pt_solution_includes_global (&cfun->gimple_df->escaped);
6371 if (pt->ipa_escaped)
6372 return pt_solution_includes_global (&ipa_escaped_pt);
6374 /* ??? This predicate is not correct for the IPA-PTA solution
6375 as we do not properly distinguish between unit escape points
6376 and global variables. */
6377 if (cfun->gimple_df->ipa_pta)
6378 return true;
6380 return false;
6383 /* Return true if the points-to solution *PT includes the variable
6384 declaration DECL. */
6386 static bool
6387 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6389 if (pt->anything)
6390 return true;
6392 if (pt->nonlocal
6393 && is_global_var (decl))
6394 return true;
6396 if (pt->vars
6397 && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6398 return true;
6400 /* If the solution includes ESCAPED, check it. */
6401 if (pt->escaped
6402 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6403 return true;
6405 /* If the solution includes ESCAPED, check it. */
6406 if (pt->ipa_escaped
6407 && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6408 return true;
6410 return false;
6413 bool
6414 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6416 bool res = pt_solution_includes_1 (pt, decl);
6417 if (res)
6418 ++pta_stats.pt_solution_includes_may_alias;
6419 else
6420 ++pta_stats.pt_solution_includes_no_alias;
6421 return res;
6424 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6425 intersection. */
6427 static bool
6428 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6430 if (pt1->anything || pt2->anything)
6431 return true;
6433 /* If either points to unknown global memory and the other points to
6434 any global memory they alias. */
6435 if ((pt1->nonlocal
6436 && (pt2->nonlocal
6437 || pt2->vars_contains_nonlocal))
6438 || (pt2->nonlocal
6439 && pt1->vars_contains_nonlocal))
6440 return true;
6442 /* If either points to all escaped memory and the other points to
6443 any escaped memory they alias. */
6444 if ((pt1->escaped
6445 && (pt2->escaped
6446 || pt2->vars_contains_escaped))
6447 || (pt2->escaped
6448 && pt1->vars_contains_escaped))
6449 return true;
6451 /* Check the escaped solution if required.
6452 ??? Do we need to check the local against the IPA escaped sets? */
6453 if ((pt1->ipa_escaped || pt2->ipa_escaped)
6454 && !pt_solution_empty_p (&ipa_escaped_pt))
6456 /* If both point to escaped memory and that solution
6457 is not empty they alias. */
6458 if (pt1->ipa_escaped && pt2->ipa_escaped)
6459 return true;
6461 /* If either points to escaped memory see if the escaped solution
6462 intersects with the other. */
6463 if ((pt1->ipa_escaped
6464 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6465 || (pt2->ipa_escaped
6466 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6467 return true;
6470 /* Now both pointers alias if their points-to solution intersects. */
6471 return (pt1->vars
6472 && pt2->vars
6473 && bitmap_intersect_p (pt1->vars, pt2->vars));
6476 bool
6477 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6479 bool res = pt_solutions_intersect_1 (pt1, pt2);
6480 if (res)
6481 ++pta_stats.pt_solutions_intersect_may_alias;
6482 else
6483 ++pta_stats.pt_solutions_intersect_no_alias;
6484 return res;
6488 /* Dump points-to information to OUTFILE. */
6490 static void
6491 dump_sa_points_to_info (FILE *outfile)
6493 unsigned int i;
6495 fprintf (outfile, "\nPoints-to sets\n\n");
6497 if (dump_flags & TDF_STATS)
6499 fprintf (outfile, "Stats:\n");
6500 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
6501 fprintf (outfile, "Non-pointer vars: %d\n",
6502 stats.nonpointer_vars);
6503 fprintf (outfile, "Statically unified vars: %d\n",
6504 stats.unified_vars_static);
6505 fprintf (outfile, "Dynamically unified vars: %d\n",
6506 stats.unified_vars_dynamic);
6507 fprintf (outfile, "Iterations: %d\n", stats.iterations);
6508 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
6509 fprintf (outfile, "Number of implicit edges: %d\n",
6510 stats.num_implicit_edges);
6513 for (i = 1; i < varmap.length (); i++)
6515 varinfo_t vi = get_varinfo (i);
6516 if (!vi->may_have_pointers)
6517 continue;
6518 dump_solution_for_var (outfile, i);
6523 /* Debug points-to information to stderr. */
6525 DEBUG_FUNCTION void
6526 debug_sa_points_to_info (void)
6528 dump_sa_points_to_info (stderr);
6532 /* Initialize the always-existing constraint variables for NULL
6533 ANYTHING, READONLY, and INTEGER */
6535 static void
6536 init_base_vars (void)
6538 struct constraint_expr lhs, rhs;
6539 varinfo_t var_anything;
6540 varinfo_t var_nothing;
6541 varinfo_t var_string;
6542 varinfo_t var_escaped;
6543 varinfo_t var_nonlocal;
6544 varinfo_t var_storedanything;
6545 varinfo_t var_integer;
6547 /* Variable ID zero is reserved and should be NULL. */
6548 varmap.safe_push (NULL);
6550 /* Create the NULL variable, used to represent that a variable points
6551 to NULL. */
6552 var_nothing = new_var_info (NULL_TREE, "NULL", false);
6553 gcc_assert (var_nothing->id == nothing_id);
6554 var_nothing->is_artificial_var = 1;
6555 var_nothing->offset = 0;
6556 var_nothing->size = ~0;
6557 var_nothing->fullsize = ~0;
6558 var_nothing->is_special_var = 1;
6559 var_nothing->may_have_pointers = 0;
6560 var_nothing->is_global_var = 0;
6562 /* Create the ANYTHING variable, used to represent that a variable
6563 points to some unknown piece of memory. */
6564 var_anything = new_var_info (NULL_TREE, "ANYTHING", false);
6565 gcc_assert (var_anything->id == anything_id);
6566 var_anything->is_artificial_var = 1;
6567 var_anything->size = ~0;
6568 var_anything->offset = 0;
6569 var_anything->fullsize = ~0;
6570 var_anything->is_special_var = 1;
6572 /* Anything points to anything. This makes deref constraints just
6573 work in the presence of linked list and other p = *p type loops,
6574 by saying that *ANYTHING = ANYTHING. */
6575 lhs.type = SCALAR;
6576 lhs.var = anything_id;
6577 lhs.offset = 0;
6578 rhs.type = ADDRESSOF;
6579 rhs.var = anything_id;
6580 rhs.offset = 0;
6582 /* This specifically does not use process_constraint because
6583 process_constraint ignores all anything = anything constraints, since all
6584 but this one are redundant. */
6585 constraints.safe_push (new_constraint (lhs, rhs));
6587 /* Create the STRING variable, used to represent that a variable
6588 points to a string literal. String literals don't contain
6589 pointers so STRING doesn't point to anything. */
6590 var_string = new_var_info (NULL_TREE, "STRING", false);
6591 gcc_assert (var_string->id == string_id);
6592 var_string->is_artificial_var = 1;
6593 var_string->offset = 0;
6594 var_string->size = ~0;
6595 var_string->fullsize = ~0;
6596 var_string->is_special_var = 1;
6597 var_string->may_have_pointers = 0;
6599 /* Create the ESCAPED variable, used to represent the set of escaped
6600 memory. */
6601 var_escaped = new_var_info (NULL_TREE, "ESCAPED", false);
6602 gcc_assert (var_escaped->id == escaped_id);
6603 var_escaped->is_artificial_var = 1;
6604 var_escaped->offset = 0;
6605 var_escaped->size = ~0;
6606 var_escaped->fullsize = ~0;
6607 var_escaped->is_special_var = 0;
6609 /* Create the NONLOCAL variable, used to represent the set of nonlocal
6610 memory. */
6611 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL", false);
6612 gcc_assert (var_nonlocal->id == nonlocal_id);
6613 var_nonlocal->is_artificial_var = 1;
6614 var_nonlocal->offset = 0;
6615 var_nonlocal->size = ~0;
6616 var_nonlocal->fullsize = ~0;
6617 var_nonlocal->is_special_var = 1;
6619 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
6620 lhs.type = SCALAR;
6621 lhs.var = escaped_id;
6622 lhs.offset = 0;
6623 rhs.type = DEREF;
6624 rhs.var = escaped_id;
6625 rhs.offset = 0;
6626 process_constraint (new_constraint (lhs, rhs));
6628 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6629 whole variable escapes. */
6630 lhs.type = SCALAR;
6631 lhs.var = escaped_id;
6632 lhs.offset = 0;
6633 rhs.type = SCALAR;
6634 rhs.var = escaped_id;
6635 rhs.offset = UNKNOWN_OFFSET;
6636 process_constraint (new_constraint (lhs, rhs));
6638 /* *ESCAPED = NONLOCAL. This is true because we have to assume
6639 everything pointed to by escaped points to what global memory can
6640 point to. */
6641 lhs.type = DEREF;
6642 lhs.var = escaped_id;
6643 lhs.offset = 0;
6644 rhs.type = SCALAR;
6645 rhs.var = nonlocal_id;
6646 rhs.offset = 0;
6647 process_constraint (new_constraint (lhs, rhs));
6649 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
6650 global memory may point to global memory and escaped memory. */
6651 lhs.type = SCALAR;
6652 lhs.var = nonlocal_id;
6653 lhs.offset = 0;
6654 rhs.type = ADDRESSOF;
6655 rhs.var = nonlocal_id;
6656 rhs.offset = 0;
6657 process_constraint (new_constraint (lhs, rhs));
6658 rhs.type = ADDRESSOF;
6659 rhs.var = escaped_id;
6660 rhs.offset = 0;
6661 process_constraint (new_constraint (lhs, rhs));
6663 /* Create the STOREDANYTHING variable, used to represent the set of
6664 variables stored to *ANYTHING. */
6665 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING", false);
6666 gcc_assert (var_storedanything->id == storedanything_id);
6667 var_storedanything->is_artificial_var = 1;
6668 var_storedanything->offset = 0;
6669 var_storedanything->size = ~0;
6670 var_storedanything->fullsize = ~0;
6671 var_storedanything->is_special_var = 0;
6673 /* Create the INTEGER variable, used to represent that a variable points
6674 to what an INTEGER "points to". */
6675 var_integer = new_var_info (NULL_TREE, "INTEGER", false);
6676 gcc_assert (var_integer->id == integer_id);
6677 var_integer->is_artificial_var = 1;
6678 var_integer->size = ~0;
6679 var_integer->fullsize = ~0;
6680 var_integer->offset = 0;
6681 var_integer->is_special_var = 1;
6683 /* INTEGER = ANYTHING, because we don't know where a dereference of
6684 a random integer will point to. */
6685 lhs.type = SCALAR;
6686 lhs.var = integer_id;
6687 lhs.offset = 0;
6688 rhs.type = ADDRESSOF;
6689 rhs.var = anything_id;
6690 rhs.offset = 0;
6691 process_constraint (new_constraint (lhs, rhs));
6694 /* Initialize things necessary to perform PTA */
6696 static void
6697 init_alias_vars (void)
6699 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6701 bitmap_obstack_initialize (&pta_obstack);
6702 bitmap_obstack_initialize (&oldpta_obstack);
6703 bitmap_obstack_initialize (&predbitmap_obstack);
6705 constraints.create (8);
6706 varmap.create (8);
6707 vi_for_tree = new hash_map<tree, varinfo_t>;
6708 call_stmt_vars = new hash_map<gimple *, varinfo_t>;
6710 memset (&stats, 0, sizeof (stats));
6711 shared_bitmap_table = new hash_table<shared_bitmap_hasher> (511);
6712 init_base_vars ();
6714 gcc_obstack_init (&fake_var_decl_obstack);
6716 final_solutions = new hash_map<varinfo_t, pt_solution *>;
6717 gcc_obstack_init (&final_solutions_obstack);
6720 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6721 predecessor edges. */
6723 static void
6724 remove_preds_and_fake_succs (constraint_graph_t graph)
6726 unsigned int i;
6728 /* Clear the implicit ref and address nodes from the successor
6729 lists. */
6730 for (i = 1; i < FIRST_REF_NODE; i++)
6732 if (graph->succs[i])
6733 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6734 FIRST_REF_NODE * 2);
6737 /* Free the successor list for the non-ref nodes. */
6738 for (i = FIRST_REF_NODE + 1; i < graph->size; i++)
6740 if (graph->succs[i])
6741 BITMAP_FREE (graph->succs[i]);
6744 /* Now reallocate the size of the successor list as, and blow away
6745 the predecessor bitmaps. */
6746 graph->size = varmap.length ();
6747 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6749 free (graph->implicit_preds);
6750 graph->implicit_preds = NULL;
6751 free (graph->preds);
6752 graph->preds = NULL;
6753 bitmap_obstack_release (&predbitmap_obstack);
6756 /* Solve the constraint set. */
6758 static void
6759 solve_constraints (void)
6761 struct scc_info *si;
6763 if (dump_file)
6764 fprintf (dump_file,
6765 "\nCollapsing static cycles and doing variable "
6766 "substitution\n");
6768 init_graph (varmap.length () * 2);
6770 if (dump_file)
6771 fprintf (dump_file, "Building predecessor graph\n");
6772 build_pred_graph ();
6774 if (dump_file)
6775 fprintf (dump_file, "Detecting pointer and location "
6776 "equivalences\n");
6777 si = perform_var_substitution (graph);
6779 if (dump_file)
6780 fprintf (dump_file, "Rewriting constraints and unifying "
6781 "variables\n");
6782 rewrite_constraints (graph, si);
6784 build_succ_graph ();
6786 free_var_substitution_info (si);
6788 /* Attach complex constraints to graph nodes. */
6789 move_complex_constraints (graph);
6791 if (dump_file)
6792 fprintf (dump_file, "Uniting pointer but not location equivalent "
6793 "variables\n");
6794 unite_pointer_equivalences (graph);
6796 if (dump_file)
6797 fprintf (dump_file, "Finding indirect cycles\n");
6798 find_indirect_cycles (graph);
6800 /* Implicit nodes and predecessors are no longer necessary at this
6801 point. */
6802 remove_preds_and_fake_succs (graph);
6804 if (dump_file && (dump_flags & TDF_GRAPH))
6806 fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
6807 "in dot format:\n");
6808 dump_constraint_graph (dump_file);
6809 fprintf (dump_file, "\n\n");
6812 if (dump_file)
6813 fprintf (dump_file, "Solving graph\n");
6815 solve_graph (graph);
6817 if (dump_file && (dump_flags & TDF_GRAPH))
6819 fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
6820 "in dot format:\n");
6821 dump_constraint_graph (dump_file);
6822 fprintf (dump_file, "\n\n");
6825 if (dump_file)
6826 dump_sa_points_to_info (dump_file);
6829 /* Create points-to sets for the current function. See the comments
6830 at the start of the file for an algorithmic overview. */
6832 static void
6833 compute_points_to_sets (void)
6835 basic_block bb;
6836 unsigned i;
6837 varinfo_t vi;
6839 timevar_push (TV_TREE_PTA);
6841 init_alias_vars ();
6843 intra_create_variable_infos (cfun);
6845 /* Now walk all statements and build the constraint set. */
6846 FOR_EACH_BB_FN (bb, cfun)
6848 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6849 gsi_next (&gsi))
6851 gphi *phi = gsi.phi ();
6853 if (! virtual_operand_p (gimple_phi_result (phi)))
6854 find_func_aliases (cfun, phi);
6857 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
6858 gsi_next (&gsi))
6860 gimple *stmt = gsi_stmt (gsi);
6862 find_func_aliases (cfun, stmt);
6866 if (dump_file)
6868 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6869 dump_constraints (dump_file, 0);
6872 /* From the constraints compute the points-to sets. */
6873 solve_constraints ();
6875 /* Compute the points-to set for ESCAPED used for call-clobber analysis. */
6876 cfun->gimple_df->escaped = find_what_var_points_to (get_varinfo (escaped_id));
6878 /* Make sure the ESCAPED solution (which is used as placeholder in
6879 other solutions) does not reference itself. This simplifies
6880 points-to solution queries. */
6881 cfun->gimple_df->escaped.escaped = 0;
6883 /* Compute the points-to sets for pointer SSA_NAMEs. */
6884 for (i = 0; i < num_ssa_names; ++i)
6886 tree ptr = ssa_name (i);
6887 if (ptr
6888 && POINTER_TYPE_P (TREE_TYPE (ptr)))
6889 find_what_p_points_to (ptr);
6892 /* Compute the call-used/clobbered sets. */
6893 FOR_EACH_BB_FN (bb, cfun)
6895 gimple_stmt_iterator gsi;
6897 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6899 gcall *stmt;
6900 struct pt_solution *pt;
6902 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
6903 if (!stmt)
6904 continue;
6906 pt = gimple_call_use_set (stmt);
6907 if (gimple_call_flags (stmt) & ECF_CONST)
6908 memset (pt, 0, sizeof (struct pt_solution));
6909 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6911 *pt = find_what_var_points_to (vi);
6912 /* Escaped (and thus nonlocal) variables are always
6913 implicitly used by calls. */
6914 /* ??? ESCAPED can be empty even though NONLOCAL
6915 always escaped. */
6916 pt->nonlocal = 1;
6917 pt->escaped = 1;
6919 else
6921 /* If there is nothing special about this call then
6922 we have made everything that is used also escape. */
6923 *pt = cfun->gimple_df->escaped;
6924 pt->nonlocal = 1;
6927 pt = gimple_call_clobber_set (stmt);
6928 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6929 memset (pt, 0, sizeof (struct pt_solution));
6930 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6932 *pt = find_what_var_points_to (vi);
6933 /* Escaped (and thus nonlocal) variables are always
6934 implicitly clobbered by calls. */
6935 /* ??? ESCAPED can be empty even though NONLOCAL
6936 always escaped. */
6937 pt->nonlocal = 1;
6938 pt->escaped = 1;
6940 else
6942 /* If there is nothing special about this call then
6943 we have made everything that is used also escape. */
6944 *pt = cfun->gimple_df->escaped;
6945 pt->nonlocal = 1;
6950 timevar_pop (TV_TREE_PTA);
6954 /* Delete created points-to sets. */
6956 static void
6957 delete_points_to_sets (void)
6959 unsigned int i;
6961 delete shared_bitmap_table;
6962 shared_bitmap_table = NULL;
6963 if (dump_file && (dump_flags & TDF_STATS))
6964 fprintf (dump_file, "Points to sets created:%d\n",
6965 stats.points_to_sets_created);
6967 delete vi_for_tree;
6968 delete call_stmt_vars;
6969 bitmap_obstack_release (&pta_obstack);
6970 constraints.release ();
6972 for (i = 0; i < graph->size; i++)
6973 graph->complex[i].release ();
6974 free (graph->complex);
6976 free (graph->rep);
6977 free (graph->succs);
6978 free (graph->pe);
6979 free (graph->pe_rep);
6980 free (graph->indirect_cycles);
6981 free (graph);
6983 varmap.release ();
6984 variable_info_pool.release ();
6985 constraint_pool.release ();
6987 obstack_free (&fake_var_decl_obstack, NULL);
6989 delete final_solutions;
6990 obstack_free (&final_solutions_obstack, NULL);
6993 /* Mark "other" loads and stores as belonging to CLIQUE and with
6994 base zero. */
6996 static bool
6997 visit_loadstore (gimple *, tree base, tree ref, void *clique_)
6999 unsigned short clique = (uintptr_t)clique_;
7000 if (TREE_CODE (base) == MEM_REF
7001 || TREE_CODE (base) == TARGET_MEM_REF)
7003 tree ptr = TREE_OPERAND (base, 0);
7004 if (TREE_CODE (ptr) == SSA_NAME
7005 && ! SSA_NAME_IS_DEFAULT_DEF (ptr))
7007 /* ??? We need to make sure 'ptr' doesn't include any of
7008 the restrict tags we added bases for in its points-to set. */
7009 return false;
7012 /* For now let decls through. */
7014 /* Do not overwrite existing cliques (that includes clique, base
7015 pairs we just set). */
7016 if (MR_DEPENDENCE_CLIQUE (base) == 0)
7018 MR_DEPENDENCE_CLIQUE (base) = clique;
7019 MR_DEPENDENCE_BASE (base) = 0;
7023 /* For plain decl accesses see whether they are accesses to globals
7024 and rewrite them to MEM_REFs with { clique, 0 }. */
7025 if (TREE_CODE (base) == VAR_DECL
7026 && is_global_var (base)
7027 /* ??? We can't rewrite a plain decl with the walk_stmt_load_store
7028 ops callback. */
7029 && base != ref)
7031 tree *basep = &ref;
7032 while (handled_component_p (*basep))
7033 basep = &TREE_OPERAND (*basep, 0);
7034 gcc_assert (TREE_CODE (*basep) == VAR_DECL);
7035 tree ptr = build_fold_addr_expr (*basep);
7036 tree zero = build_int_cst (TREE_TYPE (ptr), 0);
7037 *basep = build2 (MEM_REF, TREE_TYPE (*basep), ptr, zero);
7038 MR_DEPENDENCE_CLIQUE (*basep) = clique;
7039 MR_DEPENDENCE_BASE (*basep) = 0;
7042 return false;
7045 /* If REF is a MEM_REF then assign a clique, base pair to it, updating
7046 CLIQUE, *RESTRICT_VAR and LAST_RUID. Return whether dependence info
7047 was assigned to REF. */
7049 static bool
7050 maybe_set_dependence_info (tree ref, tree ptr,
7051 unsigned short &clique, varinfo_t restrict_var,
7052 unsigned short &last_ruid)
7054 while (handled_component_p (ref))
7055 ref = TREE_OPERAND (ref, 0);
7056 if ((TREE_CODE (ref) == MEM_REF
7057 || TREE_CODE (ref) == TARGET_MEM_REF)
7058 && TREE_OPERAND (ref, 0) == ptr)
7060 /* Do not overwrite existing cliques. This avoids overwriting dependence
7061 info inlined from a function with restrict parameters inlined
7062 into a function with restrict parameters. This usually means we
7063 prefer to be precise in innermost loops. */
7064 if (MR_DEPENDENCE_CLIQUE (ref) == 0)
7066 if (clique == 0)
7067 clique = ++cfun->last_clique;
7068 if (restrict_var->ruid == 0)
7069 restrict_var->ruid = ++last_ruid;
7070 MR_DEPENDENCE_CLIQUE (ref) = clique;
7071 MR_DEPENDENCE_BASE (ref) = restrict_var->ruid;
7072 return true;
7075 return false;
7078 /* Compute the set of independend memory references based on restrict
7079 tags and their conservative propagation to the points-to sets. */
7081 static void
7082 compute_dependence_clique (void)
7084 unsigned short clique = 0;
7085 unsigned short last_ruid = 0;
7086 for (unsigned i = 0; i < num_ssa_names; ++i)
7088 tree ptr = ssa_name (i);
7089 if (!ptr || !POINTER_TYPE_P (TREE_TYPE (ptr)))
7090 continue;
7092 /* Avoid all this when ptr is not dereferenced? */
7093 tree p = ptr;
7094 if (SSA_NAME_IS_DEFAULT_DEF (ptr)
7095 && (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
7096 || TREE_CODE (SSA_NAME_VAR (ptr)) == RESULT_DECL))
7097 p = SSA_NAME_VAR (ptr);
7098 varinfo_t vi = lookup_vi_for_tree (p);
7099 if (!vi)
7100 continue;
7101 vi = get_varinfo (find (vi->id));
7102 bitmap_iterator bi;
7103 unsigned j;
7104 varinfo_t restrict_var = NULL;
7105 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, j, bi)
7107 varinfo_t oi = get_varinfo (j);
7108 if (oi->is_restrict_var)
7110 if (restrict_var)
7112 if (dump_file && (dump_flags & TDF_DETAILS))
7114 fprintf (dump_file, "found restrict pointed-to "
7115 "for ");
7116 print_generic_expr (dump_file, ptr, 0);
7117 fprintf (dump_file, " but not exclusively\n");
7119 restrict_var = NULL;
7120 break;
7122 restrict_var = oi;
7124 /* NULL is the only other valid points-to entry. */
7125 else if (oi->id != nothing_id)
7127 restrict_var = NULL;
7128 break;
7131 /* Ok, found that ptr must(!) point to a single(!) restrict
7132 variable. */
7133 /* ??? PTA isn't really a proper propagation engine to compute
7134 this property.
7135 ??? We could handle merging of two restricts by unifying them. */
7136 if (restrict_var)
7138 /* Now look at possible dereferences of ptr. */
7139 imm_use_iterator ui;
7140 gimple *use_stmt;
7141 FOR_EACH_IMM_USE_STMT (use_stmt, ui, ptr)
7143 /* ??? Calls and asms. */
7144 if (!gimple_assign_single_p (use_stmt))
7145 continue;
7146 maybe_set_dependence_info (gimple_assign_lhs (use_stmt), ptr,
7147 clique, restrict_var, last_ruid);
7148 maybe_set_dependence_info (gimple_assign_rhs1 (use_stmt), ptr,
7149 clique, restrict_var, last_ruid);
7154 if (clique == 0)
7155 return;
7157 /* Assign the BASE id zero to all accesses not based on a restrict
7158 pointer. That way they get disabiguated against restrict
7159 accesses but not against each other. */
7160 /* ??? For restricts derived from globals (thus not incoming
7161 parameters) we can't restrict scoping properly thus the following
7162 is too aggressive there. For now we have excluded those globals from
7163 getting into the MR_DEPENDENCE machinery. */
7164 basic_block bb;
7165 FOR_EACH_BB_FN (bb, cfun)
7166 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7167 !gsi_end_p (gsi); gsi_next (&gsi))
7169 gimple *stmt = gsi_stmt (gsi);
7170 walk_stmt_load_store_ops (stmt, (void *)(uintptr_t)clique,
7171 visit_loadstore, visit_loadstore);
7175 /* Compute points-to information for every SSA_NAME pointer in the
7176 current function and compute the transitive closure of escaped
7177 variables to re-initialize the call-clobber states of local variables. */
7179 unsigned int
7180 compute_may_aliases (void)
7182 if (cfun->gimple_df->ipa_pta)
7184 if (dump_file)
7186 fprintf (dump_file, "\nNot re-computing points-to information "
7187 "because IPA points-to information is available.\n\n");
7189 /* But still dump what we have remaining it. */
7190 dump_alias_info (dump_file);
7193 return 0;
7196 /* For each pointer P_i, determine the sets of variables that P_i may
7197 point-to. Compute the reachability set of escaped and call-used
7198 variables. */
7199 compute_points_to_sets ();
7201 /* Debugging dumps. */
7202 if (dump_file)
7203 dump_alias_info (dump_file);
7205 /* Compute restrict-based memory disambiguations. */
7206 compute_dependence_clique ();
7208 /* Deallocate memory used by aliasing data structures and the internal
7209 points-to solution. */
7210 delete_points_to_sets ();
7212 gcc_assert (!need_ssa_update_p (cfun));
7214 return 0;
7217 /* A dummy pass to cause points-to information to be computed via
7218 TODO_rebuild_alias. */
7220 namespace {
7222 const pass_data pass_data_build_alias =
7224 GIMPLE_PASS, /* type */
7225 "alias", /* name */
7226 OPTGROUP_NONE, /* optinfo_flags */
7227 TV_NONE, /* tv_id */
7228 ( PROP_cfg | PROP_ssa ), /* properties_required */
7229 0, /* properties_provided */
7230 0, /* properties_destroyed */
7231 0, /* todo_flags_start */
7232 TODO_rebuild_alias, /* todo_flags_finish */
7235 class pass_build_alias : public gimple_opt_pass
7237 public:
7238 pass_build_alias (gcc::context *ctxt)
7239 : gimple_opt_pass (pass_data_build_alias, ctxt)
7242 /* opt_pass methods: */
7243 virtual bool gate (function *) { return flag_tree_pta; }
7245 }; // class pass_build_alias
7247 } // anon namespace
7249 gimple_opt_pass *
7250 make_pass_build_alias (gcc::context *ctxt)
7252 return new pass_build_alias (ctxt);
7255 /* A dummy pass to cause points-to information to be computed via
7256 TODO_rebuild_alias. */
7258 namespace {
7260 const pass_data pass_data_build_ealias =
7262 GIMPLE_PASS, /* type */
7263 "ealias", /* name */
7264 OPTGROUP_NONE, /* optinfo_flags */
7265 TV_NONE, /* tv_id */
7266 ( PROP_cfg | PROP_ssa ), /* properties_required */
7267 0, /* properties_provided */
7268 0, /* properties_destroyed */
7269 0, /* todo_flags_start */
7270 TODO_rebuild_alias, /* todo_flags_finish */
7273 class pass_build_ealias : public gimple_opt_pass
7275 public:
7276 pass_build_ealias (gcc::context *ctxt)
7277 : gimple_opt_pass (pass_data_build_ealias, ctxt)
7280 /* opt_pass methods: */
7281 virtual bool gate (function *) { return flag_tree_pta; }
7283 }; // class pass_build_ealias
7285 } // anon namespace
7287 gimple_opt_pass *
7288 make_pass_build_ealias (gcc::context *ctxt)
7290 return new pass_build_ealias (ctxt);
7294 /* IPA PTA solutions for ESCAPED. */
7295 struct pt_solution ipa_escaped_pt
7296 = { true, false, false, false, false, false, false, false, NULL };
7298 /* Associate node with varinfo DATA. Worker for
7299 cgraph_for_node_and_aliases. */
7300 static bool
7301 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
7303 if ((node->alias || node->thunk.thunk_p)
7304 && node->analyzed)
7305 insert_vi_for_tree (node->decl, (varinfo_t)data);
7306 return false;
7309 /* Execute the driver for IPA PTA. */
7310 static unsigned int
7311 ipa_pta_execute (void)
7313 struct cgraph_node *node;
7314 varpool_node *var;
7315 unsigned int from = 0;
7317 in_ipa_mode = 1;
7319 init_alias_vars ();
7321 if (dump_file && (dump_flags & TDF_DETAILS))
7323 symtab_node::dump_table (dump_file);
7324 fprintf (dump_file, "\n");
7327 if (dump_file)
7329 fprintf (dump_file, "Generating generic constraints\n\n");
7330 dump_constraints (dump_file, from);
7331 fprintf (dump_file, "\n");
7332 from = constraints.length ();
7335 /* Build the constraints. */
7336 FOR_EACH_DEFINED_FUNCTION (node)
7338 varinfo_t vi;
7339 /* Nodes without a body are not interesting. Especially do not
7340 visit clones at this point for now - we get duplicate decls
7341 there for inline clones at least. */
7342 if (!node->has_gimple_body_p () || node->global.inlined_to)
7343 continue;
7344 node->get_body ();
7346 gcc_assert (!node->clone_of);
7348 /* For externally visible or attribute used annotated functions use
7349 local constraints for their arguments.
7350 For local functions we see all callers and thus do not need initial
7351 constraints for parameters. */
7352 bool nonlocal_p = (node->used_from_other_partition
7353 || node->externally_visible
7354 || node->force_output
7355 || node->address_taken);
7357 vi = create_function_info_for (node->decl,
7358 alias_get_name (node->decl), false,
7359 nonlocal_p);
7360 if (dump_file
7361 && from != constraints.length ())
7363 fprintf (dump_file,
7364 "Generating intial constraints for %s", node->name ());
7365 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7366 fprintf (dump_file, " (%s)",
7367 IDENTIFIER_POINTER
7368 (DECL_ASSEMBLER_NAME (node->decl)));
7369 fprintf (dump_file, "\n\n");
7370 dump_constraints (dump_file, from);
7371 fprintf (dump_file, "\n");
7373 from = constraints.length ();
7376 node->call_for_symbol_thunks_and_aliases
7377 (associate_varinfo_to_alias, vi, true);
7380 /* Create constraints for global variables and their initializers. */
7381 FOR_EACH_VARIABLE (var)
7383 if (var->alias && var->analyzed)
7384 continue;
7386 get_vi_for_tree (var->decl);
7389 if (dump_file
7390 && from != constraints.length ())
7392 fprintf (dump_file,
7393 "Generating constraints for global initializers\n\n");
7394 dump_constraints (dump_file, from);
7395 fprintf (dump_file, "\n");
7396 from = constraints.length ();
7399 FOR_EACH_DEFINED_FUNCTION (node)
7401 struct function *func;
7402 basic_block bb;
7404 /* Nodes without a body are not interesting. */
7405 if (!node->has_gimple_body_p () || node->clone_of)
7406 continue;
7408 if (dump_file)
7410 fprintf (dump_file,
7411 "Generating constraints for %s", node->name ());
7412 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7413 fprintf (dump_file, " (%s)",
7414 IDENTIFIER_POINTER
7415 (DECL_ASSEMBLER_NAME (node->decl)));
7416 fprintf (dump_file, "\n");
7419 func = DECL_STRUCT_FUNCTION (node->decl);
7420 gcc_assert (cfun == NULL);
7422 /* Build constriants for the function body. */
7423 FOR_EACH_BB_FN (bb, func)
7425 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7426 gsi_next (&gsi))
7428 gphi *phi = gsi.phi ();
7430 if (! virtual_operand_p (gimple_phi_result (phi)))
7431 find_func_aliases (func, phi);
7434 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7435 gsi_next (&gsi))
7437 gimple *stmt = gsi_stmt (gsi);
7439 find_func_aliases (func, stmt);
7440 find_func_clobbers (func, stmt);
7444 if (dump_file)
7446 fprintf (dump_file, "\n");
7447 dump_constraints (dump_file, from);
7448 fprintf (dump_file, "\n");
7449 from = constraints.length ();
7453 /* From the constraints compute the points-to sets. */
7454 solve_constraints ();
7456 /* Compute the global points-to sets for ESCAPED.
7457 ??? Note that the computed escape set is not correct
7458 for the whole unit as we fail to consider graph edges to
7459 externally visible functions. */
7460 ipa_escaped_pt = find_what_var_points_to (get_varinfo (escaped_id));
7462 /* Make sure the ESCAPED solution (which is used as placeholder in
7463 other solutions) does not reference itself. This simplifies
7464 points-to solution queries. */
7465 ipa_escaped_pt.ipa_escaped = 0;
7467 /* Assign the points-to sets to the SSA names in the unit. */
7468 FOR_EACH_DEFINED_FUNCTION (node)
7470 tree ptr;
7471 struct function *fn;
7472 unsigned i;
7473 basic_block bb;
7475 /* Nodes without a body are not interesting. */
7476 if (!node->has_gimple_body_p () || node->clone_of)
7477 continue;
7479 fn = DECL_STRUCT_FUNCTION (node->decl);
7481 /* Compute the points-to sets for pointer SSA_NAMEs. */
7482 FOR_EACH_VEC_ELT (*fn->gimple_df->ssa_names, i, ptr)
7484 if (ptr
7485 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7486 find_what_p_points_to (ptr);
7489 /* Compute the call-use and call-clobber sets for indirect calls
7490 and calls to external functions. */
7491 FOR_EACH_BB_FN (bb, fn)
7493 gimple_stmt_iterator gsi;
7495 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7497 gcall *stmt;
7498 struct pt_solution *pt;
7499 varinfo_t vi, fi;
7500 tree decl;
7502 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7503 if (!stmt)
7504 continue;
7506 /* Handle direct calls to functions with body. */
7507 decl = gimple_call_fndecl (stmt);
7508 if (decl
7509 && (fi = lookup_vi_for_tree (decl))
7510 && fi->is_fn_info)
7512 *gimple_call_clobber_set (stmt)
7513 = find_what_var_points_to
7514 (first_vi_for_offset (fi, fi_clobbers));
7515 *gimple_call_use_set (stmt)
7516 = find_what_var_points_to
7517 (first_vi_for_offset (fi, fi_uses));
7519 /* Handle direct calls to external functions. */
7520 else if (decl)
7522 pt = gimple_call_use_set (stmt);
7523 if (gimple_call_flags (stmt) & ECF_CONST)
7524 memset (pt, 0, sizeof (struct pt_solution));
7525 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7527 *pt = find_what_var_points_to (vi);
7528 /* Escaped (and thus nonlocal) variables are always
7529 implicitly used by calls. */
7530 /* ??? ESCAPED can be empty even though NONLOCAL
7531 always escaped. */
7532 pt->nonlocal = 1;
7533 pt->ipa_escaped = 1;
7535 else
7537 /* If there is nothing special about this call then
7538 we have made everything that is used also escape. */
7539 *pt = ipa_escaped_pt;
7540 pt->nonlocal = 1;
7543 pt = gimple_call_clobber_set (stmt);
7544 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7545 memset (pt, 0, sizeof (struct pt_solution));
7546 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7548 *pt = find_what_var_points_to (vi);
7549 /* Escaped (and thus nonlocal) variables are always
7550 implicitly clobbered by calls. */
7551 /* ??? ESCAPED can be empty even though NONLOCAL
7552 always escaped. */
7553 pt->nonlocal = 1;
7554 pt->ipa_escaped = 1;
7556 else
7558 /* If there is nothing special about this call then
7559 we have made everything that is used also escape. */
7560 *pt = ipa_escaped_pt;
7561 pt->nonlocal = 1;
7564 /* Handle indirect calls. */
7565 else if (!decl
7566 && (fi = get_fi_for_callee (stmt)))
7568 /* We need to accumulate all clobbers/uses of all possible
7569 callees. */
7570 fi = get_varinfo (find (fi->id));
7571 /* If we cannot constrain the set of functions we'll end up
7572 calling we end up using/clobbering everything. */
7573 if (bitmap_bit_p (fi->solution, anything_id)
7574 || bitmap_bit_p (fi->solution, nonlocal_id)
7575 || bitmap_bit_p (fi->solution, escaped_id))
7577 pt_solution_reset (gimple_call_clobber_set (stmt));
7578 pt_solution_reset (gimple_call_use_set (stmt));
7580 else
7582 bitmap_iterator bi;
7583 unsigned i;
7584 struct pt_solution *uses, *clobbers;
7586 uses = gimple_call_use_set (stmt);
7587 clobbers = gimple_call_clobber_set (stmt);
7588 memset (uses, 0, sizeof (struct pt_solution));
7589 memset (clobbers, 0, sizeof (struct pt_solution));
7590 EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7592 struct pt_solution sol;
7594 vi = get_varinfo (i);
7595 if (!vi->is_fn_info)
7597 /* ??? We could be more precise here? */
7598 uses->nonlocal = 1;
7599 uses->ipa_escaped = 1;
7600 clobbers->nonlocal = 1;
7601 clobbers->ipa_escaped = 1;
7602 continue;
7605 if (!uses->anything)
7607 sol = find_what_var_points_to
7608 (first_vi_for_offset (vi, fi_uses));
7609 pt_solution_ior_into (uses, &sol);
7611 if (!clobbers->anything)
7613 sol = find_what_var_points_to
7614 (first_vi_for_offset (vi, fi_clobbers));
7615 pt_solution_ior_into (clobbers, &sol);
7623 fn->gimple_df->ipa_pta = true;
7626 delete_points_to_sets ();
7628 in_ipa_mode = 0;
7630 return 0;
7633 namespace {
7635 const pass_data pass_data_ipa_pta =
7637 SIMPLE_IPA_PASS, /* type */
7638 "pta", /* name */
7639 OPTGROUP_NONE, /* optinfo_flags */
7640 TV_IPA_PTA, /* tv_id */
7641 0, /* properties_required */
7642 0, /* properties_provided */
7643 0, /* properties_destroyed */
7644 0, /* todo_flags_start */
7645 0, /* todo_flags_finish */
7648 class pass_ipa_pta : public simple_ipa_opt_pass
7650 public:
7651 pass_ipa_pta (gcc::context *ctxt)
7652 : simple_ipa_opt_pass (pass_data_ipa_pta, ctxt)
7655 /* opt_pass methods: */
7656 virtual bool gate (function *)
7658 return (optimize
7659 && flag_ipa_pta
7660 /* Don't bother doing anything if the program has errors. */
7661 && !seen_error ());
7664 virtual unsigned int execute (function *) { return ipa_pta_execute (); }
7666 }; // class pass_ipa_pta
7668 } // anon namespace
7670 simple_ipa_opt_pass *
7671 make_pass_ipa_pta (gcc::context *ctxt)
7673 return new pass_ipa_pta (ctxt);