2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-ssa-structalias.c
blob1ed0bc4fbf9bfc273b323d6a33295c60d675e7a0
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 "tm.h"
25 #include "obstack.h"
26 #include "bitmap.h"
27 #include "sbitmap.h"
28 #include "flags.h"
29 #include "predict.h"
30 #include "hard-reg-set.h"
31 #include "input.h"
32 #include "function.h"
33 #include "dominance.h"
34 #include "cfg.h"
35 #include "basic-block.h"
36 #include "alias.h"
37 #include "symtab.h"
38 #include "tree.h"
39 #include "fold-const.h"
40 #include "stor-layout.h"
41 #include "stmt.h"
42 #include "tree-ssa-alias.h"
43 #include "internal-fn.h"
44 #include "gimple-expr.h"
45 #include "is-a.h"
46 #include "gimple.h"
47 #include "gimple-iterator.h"
48 #include "gimple-ssa.h"
49 #include "plugin-api.h"
50 #include "ipa-ref.h"
51 #include "cgraph.h"
52 #include "stringpool.h"
53 #include "tree-ssanames.h"
54 #include "tree-into-ssa.h"
55 #include "rtl.h"
56 #include "insn-config.h"
57 #include "expmed.h"
58 #include "dojump.h"
59 #include "explow.h"
60 #include "calls.h"
61 #include "emit-rtl.h"
62 #include "varasm.h"
63 #include "expr.h"
64 #include "tree-dfa.h"
65 #include "tree-inline.h"
66 #include "diagnostic-core.h"
67 #include "tree-pass.h"
68 #include "alloc-pool.h"
69 #include "splay-tree.h"
70 #include "params.h"
71 #include "tree-phinodes.h"
72 #include "ssa-iterators.h"
73 #include "tree-pretty-print.h"
74 #include "gimple-walk.h"
76 /* The idea behind this analyzer is to generate set constraints from the
77 program, then solve the resulting constraints in order to generate the
78 points-to sets.
80 Set constraints are a way of modeling program analysis problems that
81 involve sets. They consist of an inclusion constraint language,
82 describing the variables (each variable is a set) and operations that
83 are involved on the variables, and a set of rules that derive facts
84 from these operations. To solve a system of set constraints, you derive
85 all possible facts under the rules, which gives you the correct sets
86 as a consequence.
88 See "Efficient Field-sensitive pointer analysis for C" by "David
89 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
90 http://citeseer.ist.psu.edu/pearce04efficient.html
92 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
93 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
94 http://citeseer.ist.psu.edu/heintze01ultrafast.html
96 There are three types of real constraint expressions, DEREF,
97 ADDRESSOF, and SCALAR. Each constraint expression consists
98 of a constraint type, a variable, and an offset.
100 SCALAR is a constraint expression type used to represent x, whether
101 it appears on the LHS or the RHS of a statement.
102 DEREF is a constraint expression type used to represent *x, whether
103 it appears on the LHS or the RHS of a statement.
104 ADDRESSOF is a constraint expression used to represent &x, whether
105 it appears on the LHS or the RHS of a statement.
107 Each pointer variable in the program is assigned an integer id, and
108 each field of a structure variable is assigned an integer id as well.
110 Structure variables are linked to their list of fields through a "next
111 field" in each variable that points to the next field in offset
112 order.
113 Each variable for a structure field has
115 1. "size", that tells the size in bits of that field.
116 2. "fullsize, that tells the size in bits of the entire structure.
117 3. "offset", that tells the offset in bits from the beginning of the
118 structure to this field.
120 Thus,
121 struct f
123 int a;
124 int b;
125 } foo;
126 int *bar;
128 looks like
130 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
131 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
132 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
135 In order to solve the system of set constraints, the following is
136 done:
138 1. Each constraint variable x has a solution set associated with it,
139 Sol(x).
141 2. Constraints are separated into direct, copy, and complex.
142 Direct constraints are ADDRESSOF constraints that require no extra
143 processing, such as P = &Q
144 Copy constraints are those of the form P = Q.
145 Complex constraints are all the constraints involving dereferences
146 and offsets (including offsetted copies).
148 3. All direct constraints of the form P = &Q are processed, such
149 that Q is added to Sol(P)
151 4. All complex constraints for a given constraint variable are stored in a
152 linked list attached to that variable's node.
154 5. A directed graph is built out of the copy constraints. Each
155 constraint variable is a node in the graph, and an edge from
156 Q to P is added for each copy constraint of the form P = Q
158 6. The graph is then walked, and solution sets are
159 propagated along the copy edges, such that an edge from Q to P
160 causes Sol(P) <- Sol(P) union Sol(Q).
162 7. As we visit each node, all complex constraints associated with
163 that node are processed by adding appropriate copy edges to the graph, or the
164 appropriate variables to the solution set.
166 8. The process of walking the graph is iterated until no solution
167 sets change.
169 Prior to walking the graph in steps 6 and 7, We perform static
170 cycle elimination on the constraint graph, as well
171 as off-line variable substitution.
173 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
174 on and turned into anything), but isn't. You can just see what offset
175 inside the pointed-to struct it's going to access.
177 TODO: Constant bounded arrays can be handled as if they were structs of the
178 same number of elements.
180 TODO: Modeling heap and incoming pointers becomes much better if we
181 add fields to them as we discover them, which we could do.
183 TODO: We could handle unions, but to be honest, it's probably not
184 worth the pain or slowdown. */
186 /* IPA-PTA optimizations possible.
188 When the indirect function called is ANYTHING we can add disambiguation
189 based on the function signatures (or simply the parameter count which
190 is the varinfo size). We also do not need to consider functions that
191 do not have their address taken.
193 The is_global_var bit which marks escape points is overly conservative
194 in IPA mode. Split it to is_escape_point and is_global_var - only
195 externally visible globals are escape points in IPA mode. This is
196 also needed to fix the pt_solution_includes_global predicate
197 (and thus ptr_deref_may_alias_global_p).
199 The way we introduce DECL_PT_UID to avoid fixing up all points-to
200 sets in the translation unit when we copy a DECL during inlining
201 pessimizes precision. The advantage is that the DECL_PT_UID keeps
202 compile-time and memory usage overhead low - the points-to sets
203 do not grow or get unshared as they would during a fixup phase.
204 An alternative solution is to delay IPA PTA until after all
205 inlining transformations have been applied.
207 The way we propagate clobber/use information isn't optimized.
208 It should use a new complex constraint that properly filters
209 out local variables of the callee (though that would make
210 the sets invalid after inlining). OTOH we might as well
211 admit defeat to WHOPR and simply do all the clobber/use analysis
212 and propagation after PTA finished but before we threw away
213 points-to information for memory variables. WHOPR and PTA
214 do not play along well anyway - the whole constraint solving
215 would need to be done in WPA phase and it will be very interesting
216 to apply the results to local SSA names during LTRANS phase.
218 We probably should compute a per-function unit-ESCAPE solution
219 propagating it simply like the clobber / uses solutions. The
220 solution can go alongside the non-IPA espaced solution and be
221 used to query which vars escape the unit through a function.
223 We never put function decls in points-to sets so we do not
224 keep the set of called functions for indirect calls.
226 And probably more. */
228 static bool use_field_sensitive = true;
229 static int in_ipa_mode = 0;
231 /* Used for predecessor bitmaps. */
232 static bitmap_obstack predbitmap_obstack;
234 /* Used for points-to sets. */
235 static bitmap_obstack pta_obstack;
237 /* Used for oldsolution members of variables. */
238 static bitmap_obstack oldpta_obstack;
240 /* Used for per-solver-iteration bitmaps. */
241 static bitmap_obstack iteration_obstack;
243 static unsigned int create_variable_info_for (tree, const char *);
244 typedef struct constraint_graph *constraint_graph_t;
245 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
247 struct constraint;
248 typedef struct constraint *constraint_t;
251 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
252 if (a) \
253 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
255 static struct constraint_stats
257 unsigned int total_vars;
258 unsigned int nonpointer_vars;
259 unsigned int unified_vars_static;
260 unsigned int unified_vars_dynamic;
261 unsigned int iterations;
262 unsigned int num_edges;
263 unsigned int num_implicit_edges;
264 unsigned int points_to_sets_created;
265 } stats;
267 struct variable_info
269 /* ID of this variable */
270 unsigned int id;
272 /* True if this is a variable created by the constraint analysis, such as
273 heap variables and constraints we had to break up. */
274 unsigned int is_artificial_var : 1;
276 /* True if this is a special variable whose solution set should not be
277 changed. */
278 unsigned int is_special_var : 1;
280 /* True for variables whose size is not known or variable. */
281 unsigned int is_unknown_size_var : 1;
283 /* True for (sub-)fields that represent a whole variable. */
284 unsigned int is_full_var : 1;
286 /* True if this is a heap variable. */
287 unsigned int is_heap_var : 1;
289 /* True if this field may contain pointers. */
290 unsigned int may_have_pointers : 1;
292 /* True if this field has only restrict qualified pointers. */
293 unsigned int only_restrict_pointers : 1;
295 /* True if this represents a heap var created for a restrict qualified
296 pointer. */
297 unsigned int is_restrict_var : 1;
299 /* True if this represents a global variable. */
300 unsigned int is_global_var : 1;
302 /* True if this represents a IPA function info. */
303 unsigned int is_fn_info : 1;
305 /* ??? Store somewhere better. */
306 unsigned short ruid;
308 /* The ID of the variable for the next field in this structure
309 or zero for the last field in this structure. */
310 unsigned next;
312 /* The ID of the variable for the first field in this structure. */
313 unsigned head;
315 /* Offset of this variable, in bits, from the base variable */
316 unsigned HOST_WIDE_INT offset;
318 /* Size of the variable, in bits. */
319 unsigned HOST_WIDE_INT size;
321 /* Full size of the base variable, in bits. */
322 unsigned HOST_WIDE_INT fullsize;
324 /* Name of this variable */
325 const char *name;
327 /* Tree that this variable is associated with. */
328 tree decl;
330 /* Points-to set for this variable. */
331 bitmap solution;
333 /* Old points-to set for this variable. */
334 bitmap oldsolution;
336 typedef struct variable_info *varinfo_t;
338 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
339 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
340 unsigned HOST_WIDE_INT);
341 static varinfo_t lookup_vi_for_tree (tree);
342 static inline bool type_can_have_subvars (const_tree);
344 /* Pool of variable info structures. */
345 static pool_allocator<variable_info> variable_info_pool
346 ("Variable info pool", 30);
348 /* Map varinfo to final pt_solution. */
349 static hash_map<varinfo_t, pt_solution *> *final_solutions;
350 struct obstack final_solutions_obstack;
352 /* Table of variable info structures for constraint variables.
353 Indexed directly by variable info id. */
354 static vec<varinfo_t> varmap;
356 /* Return the varmap element N */
358 static inline varinfo_t
359 get_varinfo (unsigned int n)
361 return varmap[n];
364 /* Return the next variable in the list of sub-variables of VI
365 or NULL if VI is the last sub-variable. */
367 static inline varinfo_t
368 vi_next (varinfo_t vi)
370 return get_varinfo (vi->next);
373 /* Static IDs for the special variables. Variable ID zero is unused
374 and used as terminator for the sub-variable chain. */
375 enum { nothing_id = 1, anything_id = 2, string_id = 3,
376 escaped_id = 4, nonlocal_id = 5,
377 storedanything_id = 6, integer_id = 7 };
379 /* Return a new variable info structure consisting for a variable
380 named NAME, and using constraint graph node NODE. Append it
381 to the vector of variable info structures. */
383 static varinfo_t
384 new_var_info (tree t, const char *name)
386 unsigned index = varmap.length ();
387 varinfo_t ret = variable_info_pool.allocate ();
389 ret->id = index;
390 ret->name = name;
391 ret->decl = t;
392 /* Vars without decl are artificial and do not have sub-variables. */
393 ret->is_artificial_var = (t == NULL_TREE);
394 ret->is_special_var = false;
395 ret->is_unknown_size_var = false;
396 ret->is_full_var = (t == NULL_TREE);
397 ret->is_heap_var = false;
398 ret->may_have_pointers = true;
399 ret->only_restrict_pointers = false;
400 ret->is_restrict_var = false;
401 ret->ruid = 0;
402 ret->is_global_var = (t == NULL_TREE);
403 ret->is_fn_info = false;
404 if (t && DECL_P (t))
405 ret->is_global_var = (is_global_var (t)
406 /* We have to treat even local register variables
407 as escape points. */
408 || (TREE_CODE (t) == VAR_DECL
409 && DECL_HARD_REGISTER (t)));
410 ret->solution = BITMAP_ALLOC (&pta_obstack);
411 ret->oldsolution = NULL;
412 ret->next = 0;
413 ret->head = ret->id;
415 stats.total_vars++;
417 varmap.safe_push (ret);
419 return ret;
423 /* A map mapping call statements to per-stmt variables for uses
424 and clobbers specific to the call. */
425 static hash_map<gimple, varinfo_t> *call_stmt_vars;
427 /* Lookup or create the variable for the call statement CALL. */
429 static varinfo_t
430 get_call_vi (gcall *call)
432 varinfo_t vi, vi2;
434 bool existed;
435 varinfo_t *slot_p = &call_stmt_vars->get_or_insert (call, &existed);
436 if (existed)
437 return *slot_p;
439 vi = new_var_info (NULL_TREE, "CALLUSED");
440 vi->offset = 0;
441 vi->size = 1;
442 vi->fullsize = 2;
443 vi->is_full_var = true;
445 vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED");
446 vi2->offset = 1;
447 vi2->size = 1;
448 vi2->fullsize = 2;
449 vi2->is_full_var = true;
451 vi->next = vi2->id;
453 *slot_p = vi;
454 return vi;
457 /* Lookup the variable for the call statement CALL representing
458 the uses. Returns NULL if there is nothing special about this call. */
460 static varinfo_t
461 lookup_call_use_vi (gcall *call)
463 varinfo_t *slot_p = call_stmt_vars->get (call);
464 if (slot_p)
465 return *slot_p;
467 return NULL;
470 /* Lookup the variable for the call statement CALL representing
471 the clobbers. Returns NULL if there is nothing special about this call. */
473 static varinfo_t
474 lookup_call_clobber_vi (gcall *call)
476 varinfo_t uses = lookup_call_use_vi (call);
477 if (!uses)
478 return NULL;
480 return vi_next (uses);
483 /* Lookup or create the variable for the call statement CALL representing
484 the uses. */
486 static varinfo_t
487 get_call_use_vi (gcall *call)
489 return get_call_vi (call);
492 /* Lookup or create the variable for the call statement CALL representing
493 the clobbers. */
495 static varinfo_t ATTRIBUTE_UNUSED
496 get_call_clobber_vi (gcall *call)
498 return vi_next (get_call_vi (call));
502 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
504 /* An expression that appears in a constraint. */
506 struct constraint_expr
508 /* Constraint type. */
509 constraint_expr_type type;
511 /* Variable we are referring to in the constraint. */
512 unsigned int var;
514 /* Offset, in bits, of this constraint from the beginning of
515 variables it ends up referring to.
517 IOW, in a deref constraint, we would deref, get the result set,
518 then add OFFSET to each member. */
519 HOST_WIDE_INT offset;
522 /* Use 0x8000... as special unknown offset. */
523 #define UNKNOWN_OFFSET HOST_WIDE_INT_MIN
525 typedef struct constraint_expr ce_s;
526 static void get_constraint_for_1 (tree, vec<ce_s> *, bool, bool);
527 static void get_constraint_for (tree, vec<ce_s> *);
528 static void get_constraint_for_rhs (tree, vec<ce_s> *);
529 static void do_deref (vec<ce_s> *);
531 /* Our set constraints are made up of two constraint expressions, one
532 LHS, and one RHS.
534 As described in the introduction, our set constraints each represent an
535 operation between set valued variables.
537 struct constraint
539 struct constraint_expr lhs;
540 struct constraint_expr rhs;
543 /* List of constraints that we use to build the constraint graph from. */
545 static vec<constraint_t> constraints;
546 static pool_allocator<constraint> constraint_pool ("Constraint pool", 30);
548 /* The constraint graph is represented as an array of bitmaps
549 containing successor nodes. */
551 struct constraint_graph
553 /* Size of this graph, which may be different than the number of
554 nodes in the variable map. */
555 unsigned int size;
557 /* Explicit successors of each node. */
558 bitmap *succs;
560 /* Implicit predecessors of each node (Used for variable
561 substitution). */
562 bitmap *implicit_preds;
564 /* Explicit predecessors of each node (Used for variable substitution). */
565 bitmap *preds;
567 /* Indirect cycle representatives, or -1 if the node has no indirect
568 cycles. */
569 int *indirect_cycles;
571 /* Representative node for a node. rep[a] == a unless the node has
572 been unified. */
573 unsigned int *rep;
575 /* Equivalence class representative for a label. This is used for
576 variable substitution. */
577 int *eq_rep;
579 /* Pointer equivalence label for a node. All nodes with the same
580 pointer equivalence label can be unified together at some point
581 (either during constraint optimization or after the constraint
582 graph is built). */
583 unsigned int *pe;
585 /* Pointer equivalence representative for a label. This is used to
586 handle nodes that are pointer equivalent but not location
587 equivalent. We can unite these once the addressof constraints
588 are transformed into initial points-to sets. */
589 int *pe_rep;
591 /* Pointer equivalence label for each node, used during variable
592 substitution. */
593 unsigned int *pointer_label;
595 /* Location equivalence label for each node, used during location
596 equivalence finding. */
597 unsigned int *loc_label;
599 /* Pointed-by set for each node, used during location equivalence
600 finding. This is pointed-by rather than pointed-to, because it
601 is constructed using the predecessor graph. */
602 bitmap *pointed_by;
604 /* Points to sets for pointer equivalence. This is *not* the actual
605 points-to sets for nodes. */
606 bitmap *points_to;
608 /* Bitmap of nodes where the bit is set if the node is a direct
609 node. Used for variable substitution. */
610 sbitmap direct_nodes;
612 /* Bitmap of nodes where the bit is set if the node is address
613 taken. Used for variable substitution. */
614 bitmap address_taken;
616 /* Vector of complex constraints for each graph node. Complex
617 constraints are those involving dereferences or offsets that are
618 not 0. */
619 vec<constraint_t> *complex;
622 static constraint_graph_t graph;
624 /* During variable substitution and the offline version of indirect
625 cycle finding, we create nodes to represent dereferences and
626 address taken constraints. These represent where these start and
627 end. */
628 #define FIRST_REF_NODE (varmap).length ()
629 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
631 /* Return the representative node for NODE, if NODE has been unioned
632 with another NODE.
633 This function performs path compression along the way to finding
634 the representative. */
636 static unsigned int
637 find (unsigned int node)
639 gcc_checking_assert (node < graph->size);
640 if (graph->rep[node] != node)
641 return graph->rep[node] = find (graph->rep[node]);
642 return node;
645 /* Union the TO and FROM nodes to the TO nodes.
646 Note that at some point in the future, we may want to do
647 union-by-rank, in which case we are going to have to return the
648 node we unified to. */
650 static bool
651 unite (unsigned int to, unsigned int from)
653 gcc_checking_assert (to < graph->size && from < graph->size);
654 if (to != from && graph->rep[from] != to)
656 graph->rep[from] = to;
657 return true;
659 return false;
662 /* Create a new constraint consisting of LHS and RHS expressions. */
664 static constraint_t
665 new_constraint (const struct constraint_expr lhs,
666 const struct constraint_expr rhs)
668 constraint_t ret = constraint_pool.allocate ();
669 ret->lhs = lhs;
670 ret->rhs = rhs;
671 return ret;
674 /* Print out constraint C to FILE. */
676 static void
677 dump_constraint (FILE *file, constraint_t c)
679 if (c->lhs.type == ADDRESSOF)
680 fprintf (file, "&");
681 else if (c->lhs.type == DEREF)
682 fprintf (file, "*");
683 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
684 if (c->lhs.offset == UNKNOWN_OFFSET)
685 fprintf (file, " + UNKNOWN");
686 else if (c->lhs.offset != 0)
687 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
688 fprintf (file, " = ");
689 if (c->rhs.type == ADDRESSOF)
690 fprintf (file, "&");
691 else if (c->rhs.type == DEREF)
692 fprintf (file, "*");
693 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
694 if (c->rhs.offset == UNKNOWN_OFFSET)
695 fprintf (file, " + UNKNOWN");
696 else if (c->rhs.offset != 0)
697 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
701 void debug_constraint (constraint_t);
702 void debug_constraints (void);
703 void debug_constraint_graph (void);
704 void debug_solution_for_var (unsigned int);
705 void debug_sa_points_to_info (void);
707 /* Print out constraint C to stderr. */
709 DEBUG_FUNCTION void
710 debug_constraint (constraint_t c)
712 dump_constraint (stderr, c);
713 fprintf (stderr, "\n");
716 /* Print out all constraints to FILE */
718 static void
719 dump_constraints (FILE *file, int from)
721 int i;
722 constraint_t c;
723 for (i = from; constraints.iterate (i, &c); i++)
724 if (c)
726 dump_constraint (file, c);
727 fprintf (file, "\n");
731 /* Print out all constraints to stderr. */
733 DEBUG_FUNCTION void
734 debug_constraints (void)
736 dump_constraints (stderr, 0);
739 /* Print the constraint graph in dot format. */
741 static void
742 dump_constraint_graph (FILE *file)
744 unsigned int i;
746 /* Only print the graph if it has already been initialized: */
747 if (!graph)
748 return;
750 /* Prints the header of the dot file: */
751 fprintf (file, "strict digraph {\n");
752 fprintf (file, " node [\n shape = box\n ]\n");
753 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
754 fprintf (file, "\n // List of nodes and complex constraints in "
755 "the constraint graph:\n");
757 /* The next lines print the nodes in the graph together with the
758 complex constraints attached to them. */
759 for (i = 1; i < graph->size; i++)
761 if (i == FIRST_REF_NODE)
762 continue;
763 if (find (i) != i)
764 continue;
765 if (i < FIRST_REF_NODE)
766 fprintf (file, "\"%s\"", get_varinfo (i)->name);
767 else
768 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
769 if (graph->complex[i].exists ())
771 unsigned j;
772 constraint_t c;
773 fprintf (file, " [label=\"\\N\\n");
774 for (j = 0; graph->complex[i].iterate (j, &c); ++j)
776 dump_constraint (file, c);
777 fprintf (file, "\\l");
779 fprintf (file, "\"]");
781 fprintf (file, ";\n");
784 /* Go over the edges. */
785 fprintf (file, "\n // Edges in the constraint graph:\n");
786 for (i = 1; i < graph->size; i++)
788 unsigned j;
789 bitmap_iterator bi;
790 if (find (i) != i)
791 continue;
792 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
794 unsigned to = find (j);
795 if (i == to)
796 continue;
797 if (i < FIRST_REF_NODE)
798 fprintf (file, "\"%s\"", get_varinfo (i)->name);
799 else
800 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
801 fprintf (file, " -> ");
802 if (to < FIRST_REF_NODE)
803 fprintf (file, "\"%s\"", get_varinfo (to)->name);
804 else
805 fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
806 fprintf (file, ";\n");
810 /* Prints the tail of the dot file. */
811 fprintf (file, "}\n");
814 /* Print out the constraint graph to stderr. */
816 DEBUG_FUNCTION void
817 debug_constraint_graph (void)
819 dump_constraint_graph (stderr);
822 /* SOLVER FUNCTIONS
824 The solver is a simple worklist solver, that works on the following
825 algorithm:
827 sbitmap changed_nodes = all zeroes;
828 changed_count = 0;
829 For each node that is not already collapsed:
830 changed_count++;
831 set bit in changed nodes
833 while (changed_count > 0)
835 compute topological ordering for constraint graph
837 find and collapse cycles in the constraint graph (updating
838 changed if necessary)
840 for each node (n) in the graph in topological order:
841 changed_count--;
843 Process each complex constraint associated with the node,
844 updating changed if necessary.
846 For each outgoing edge from n, propagate the solution from n to
847 the destination of the edge, updating changed as necessary.
849 } */
851 /* Return true if two constraint expressions A and B are equal. */
853 static bool
854 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
856 return a.type == b.type && a.var == b.var && a.offset == b.offset;
859 /* Return true if constraint expression A is less than constraint expression
860 B. This is just arbitrary, but consistent, in order to give them an
861 ordering. */
863 static bool
864 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
866 if (a.type == b.type)
868 if (a.var == b.var)
869 return a.offset < b.offset;
870 else
871 return a.var < b.var;
873 else
874 return a.type < b.type;
877 /* Return true if constraint A is less than constraint B. This is just
878 arbitrary, but consistent, in order to give them an ordering. */
880 static bool
881 constraint_less (const constraint_t &a, const constraint_t &b)
883 if (constraint_expr_less (a->lhs, b->lhs))
884 return true;
885 else if (constraint_expr_less (b->lhs, a->lhs))
886 return false;
887 else
888 return constraint_expr_less (a->rhs, b->rhs);
891 /* Return true if two constraints A and B are equal. */
893 static bool
894 constraint_equal (struct constraint a, struct constraint b)
896 return constraint_expr_equal (a.lhs, b.lhs)
897 && constraint_expr_equal (a.rhs, b.rhs);
901 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
903 static constraint_t
904 constraint_vec_find (vec<constraint_t> vec,
905 struct constraint lookfor)
907 unsigned int place;
908 constraint_t found;
910 if (!vec.exists ())
911 return NULL;
913 place = vec.lower_bound (&lookfor, constraint_less);
914 if (place >= vec.length ())
915 return NULL;
916 found = vec[place];
917 if (!constraint_equal (*found, lookfor))
918 return NULL;
919 return found;
922 /* Union two constraint vectors, TO and FROM. Put the result in TO.
923 Returns true of TO set is changed. */
925 static bool
926 constraint_set_union (vec<constraint_t> *to,
927 vec<constraint_t> *from)
929 int i;
930 constraint_t c;
931 bool any_change = false;
933 FOR_EACH_VEC_ELT (*from, i, c)
935 if (constraint_vec_find (*to, *c) == NULL)
937 unsigned int place = to->lower_bound (c, constraint_less);
938 to->safe_insert (place, c);
939 any_change = true;
942 return any_change;
945 /* Expands the solution in SET to all sub-fields of variables included. */
947 static bitmap
948 solution_set_expand (bitmap set, bitmap *expanded)
950 bitmap_iterator bi;
951 unsigned j;
953 if (*expanded)
954 return *expanded;
956 *expanded = BITMAP_ALLOC (&iteration_obstack);
958 /* In a first pass expand to the head of the variables we need to
959 add all sub-fields off. This avoids quadratic behavior. */
960 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
962 varinfo_t v = get_varinfo (j);
963 if (v->is_artificial_var
964 || v->is_full_var)
965 continue;
966 bitmap_set_bit (*expanded, v->head);
969 /* In the second pass now expand all head variables with subfields. */
970 EXECUTE_IF_SET_IN_BITMAP (*expanded, 0, j, bi)
972 varinfo_t v = get_varinfo (j);
973 if (v->head != j)
974 continue;
975 for (v = vi_next (v); v != NULL; v = vi_next (v))
976 bitmap_set_bit (*expanded, v->id);
979 /* And finally set the rest of the bits from SET. */
980 bitmap_ior_into (*expanded, set);
982 return *expanded;
985 /* Union solution sets TO and DELTA, and add INC to each member of DELTA in the
986 process. */
988 static bool
989 set_union_with_increment (bitmap to, bitmap delta, HOST_WIDE_INT inc,
990 bitmap *expanded_delta)
992 bool changed = false;
993 bitmap_iterator bi;
994 unsigned int i;
996 /* If the solution of DELTA contains anything it is good enough to transfer
997 this to TO. */
998 if (bitmap_bit_p (delta, anything_id))
999 return bitmap_set_bit (to, anything_id);
1001 /* If the offset is unknown we have to expand the solution to
1002 all subfields. */
1003 if (inc == UNKNOWN_OFFSET)
1005 delta = solution_set_expand (delta, expanded_delta);
1006 changed |= bitmap_ior_into (to, delta);
1007 return changed;
1010 /* For non-zero offset union the offsetted solution into the destination. */
1011 EXECUTE_IF_SET_IN_BITMAP (delta, 0, i, bi)
1013 varinfo_t vi = get_varinfo (i);
1015 /* If this is a variable with just one field just set its bit
1016 in the result. */
1017 if (vi->is_artificial_var
1018 || vi->is_unknown_size_var
1019 || vi->is_full_var)
1020 changed |= bitmap_set_bit (to, i);
1021 else
1023 HOST_WIDE_INT fieldoffset = vi->offset + inc;
1024 unsigned HOST_WIDE_INT size = vi->size;
1026 /* If the offset makes the pointer point to before the
1027 variable use offset zero for the field lookup. */
1028 if (fieldoffset < 0)
1029 vi = get_varinfo (vi->head);
1030 else
1031 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1035 changed |= bitmap_set_bit (to, vi->id);
1036 if (vi->is_full_var
1037 || vi->next == 0)
1038 break;
1040 /* We have to include all fields that overlap the current field
1041 shifted by inc. */
1042 vi = vi_next (vi);
1044 while (vi->offset < fieldoffset + size);
1048 return changed;
1051 /* Insert constraint C into the list of complex constraints for graph
1052 node VAR. */
1054 static void
1055 insert_into_complex (constraint_graph_t graph,
1056 unsigned int var, constraint_t c)
1058 vec<constraint_t> complex = graph->complex[var];
1059 unsigned int place = complex.lower_bound (c, constraint_less);
1061 /* Only insert constraints that do not already exist. */
1062 if (place >= complex.length ()
1063 || !constraint_equal (*c, *complex[place]))
1064 graph->complex[var].safe_insert (place, c);
1068 /* Condense two variable nodes into a single variable node, by moving
1069 all associated info from FROM to TO. Returns true if TO node's
1070 constraint set changes after the merge. */
1072 static bool
1073 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1074 unsigned int from)
1076 unsigned int i;
1077 constraint_t c;
1078 bool any_change = false;
1080 gcc_checking_assert (find (from) == to);
1082 /* Move all complex constraints from src node into to node */
1083 FOR_EACH_VEC_ELT (graph->complex[from], i, c)
1085 /* In complex constraints for node FROM, we may have either
1086 a = *FROM, and *FROM = a, or an offseted constraint which are
1087 always added to the rhs node's constraints. */
1089 if (c->rhs.type == DEREF)
1090 c->rhs.var = to;
1091 else if (c->lhs.type == DEREF)
1092 c->lhs.var = to;
1093 else
1094 c->rhs.var = to;
1097 any_change = constraint_set_union (&graph->complex[to],
1098 &graph->complex[from]);
1099 graph->complex[from].release ();
1100 return any_change;
1104 /* Remove edges involving NODE from GRAPH. */
1106 static void
1107 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1109 if (graph->succs[node])
1110 BITMAP_FREE (graph->succs[node]);
1113 /* Merge GRAPH nodes FROM and TO into node TO. */
1115 static void
1116 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1117 unsigned int from)
1119 if (graph->indirect_cycles[from] != -1)
1121 /* If we have indirect cycles with the from node, and we have
1122 none on the to node, the to node has indirect cycles from the
1123 from node now that they are unified.
1124 If indirect cycles exist on both, unify the nodes that they
1125 are in a cycle with, since we know they are in a cycle with
1126 each other. */
1127 if (graph->indirect_cycles[to] == -1)
1128 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1131 /* Merge all the successor edges. */
1132 if (graph->succs[from])
1134 if (!graph->succs[to])
1135 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1136 bitmap_ior_into (graph->succs[to],
1137 graph->succs[from]);
1140 clear_edges_for_node (graph, from);
1144 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1145 it doesn't exist in the graph already. */
1147 static void
1148 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1149 unsigned int from)
1151 if (to == from)
1152 return;
1154 if (!graph->implicit_preds[to])
1155 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1157 if (bitmap_set_bit (graph->implicit_preds[to], from))
1158 stats.num_implicit_edges++;
1161 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1162 it doesn't exist in the graph already.
1163 Return false if the edge already existed, true otherwise. */
1165 static void
1166 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1167 unsigned int from)
1169 if (!graph->preds[to])
1170 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1171 bitmap_set_bit (graph->preds[to], from);
1174 /* Add a graph edge to GRAPH, going from FROM to TO if
1175 it doesn't exist in the graph already.
1176 Return false if the edge already existed, true otherwise. */
1178 static bool
1179 add_graph_edge (constraint_graph_t graph, unsigned int to,
1180 unsigned int from)
1182 if (to == from)
1184 return false;
1186 else
1188 bool r = false;
1190 if (!graph->succs[from])
1191 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1192 if (bitmap_set_bit (graph->succs[from], to))
1194 r = true;
1195 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1196 stats.num_edges++;
1198 return r;
1203 /* Initialize the constraint graph structure to contain SIZE nodes. */
1205 static void
1206 init_graph (unsigned int size)
1208 unsigned int j;
1210 graph = XCNEW (struct constraint_graph);
1211 graph->size = size;
1212 graph->succs = XCNEWVEC (bitmap, graph->size);
1213 graph->indirect_cycles = XNEWVEC (int, graph->size);
1214 graph->rep = XNEWVEC (unsigned int, graph->size);
1215 /* ??? Macros do not support template types with multiple arguments,
1216 so we use a typedef to work around it. */
1217 typedef vec<constraint_t> vec_constraint_t_heap;
1218 graph->complex = XCNEWVEC (vec_constraint_t_heap, size);
1219 graph->pe = XCNEWVEC (unsigned int, graph->size);
1220 graph->pe_rep = XNEWVEC (int, graph->size);
1222 for (j = 0; j < graph->size; j++)
1224 graph->rep[j] = j;
1225 graph->pe_rep[j] = -1;
1226 graph->indirect_cycles[j] = -1;
1230 /* Build the constraint graph, adding only predecessor edges right now. */
1232 static void
1233 build_pred_graph (void)
1235 int i;
1236 constraint_t c;
1237 unsigned int j;
1239 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1240 graph->preds = XCNEWVEC (bitmap, graph->size);
1241 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1242 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1243 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1244 graph->points_to = XCNEWVEC (bitmap, graph->size);
1245 graph->eq_rep = XNEWVEC (int, graph->size);
1246 graph->direct_nodes = sbitmap_alloc (graph->size);
1247 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1248 bitmap_clear (graph->direct_nodes);
1250 for (j = 1; j < FIRST_REF_NODE; j++)
1252 if (!get_varinfo (j)->is_special_var)
1253 bitmap_set_bit (graph->direct_nodes, j);
1256 for (j = 0; j < graph->size; j++)
1257 graph->eq_rep[j] = -1;
1259 for (j = 0; j < varmap.length (); j++)
1260 graph->indirect_cycles[j] = -1;
1262 FOR_EACH_VEC_ELT (constraints, i, c)
1264 struct constraint_expr lhs = c->lhs;
1265 struct constraint_expr rhs = c->rhs;
1266 unsigned int lhsvar = lhs.var;
1267 unsigned int rhsvar = rhs.var;
1269 if (lhs.type == DEREF)
1271 /* *x = y. */
1272 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1273 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1275 else if (rhs.type == DEREF)
1277 /* x = *y */
1278 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1279 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1280 else
1281 bitmap_clear_bit (graph->direct_nodes, lhsvar);
1283 else if (rhs.type == ADDRESSOF)
1285 varinfo_t v;
1287 /* x = &y */
1288 if (graph->points_to[lhsvar] == NULL)
1289 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1290 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1292 if (graph->pointed_by[rhsvar] == NULL)
1293 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1294 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1296 /* Implicitly, *x = y */
1297 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1299 /* All related variables are no longer direct nodes. */
1300 bitmap_clear_bit (graph->direct_nodes, rhsvar);
1301 v = get_varinfo (rhsvar);
1302 if (!v->is_full_var)
1304 v = get_varinfo (v->head);
1307 bitmap_clear_bit (graph->direct_nodes, v->id);
1308 v = vi_next (v);
1310 while (v != NULL);
1312 bitmap_set_bit (graph->address_taken, rhsvar);
1314 else if (lhsvar > anything_id
1315 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1317 /* x = y */
1318 add_pred_graph_edge (graph, lhsvar, rhsvar);
1319 /* Implicitly, *x = *y */
1320 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1321 FIRST_REF_NODE + rhsvar);
1323 else if (lhs.offset != 0 || rhs.offset != 0)
1325 if (rhs.offset != 0)
1326 bitmap_clear_bit (graph->direct_nodes, lhs.var);
1327 else if (lhs.offset != 0)
1328 bitmap_clear_bit (graph->direct_nodes, rhs.var);
1333 /* Build the constraint graph, adding successor edges. */
1335 static void
1336 build_succ_graph (void)
1338 unsigned i, t;
1339 constraint_t c;
1341 FOR_EACH_VEC_ELT (constraints, i, c)
1343 struct constraint_expr lhs;
1344 struct constraint_expr rhs;
1345 unsigned int lhsvar;
1346 unsigned int rhsvar;
1348 if (!c)
1349 continue;
1351 lhs = c->lhs;
1352 rhs = c->rhs;
1353 lhsvar = find (lhs.var);
1354 rhsvar = find (rhs.var);
1356 if (lhs.type == DEREF)
1358 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1359 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1361 else if (rhs.type == DEREF)
1363 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1364 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1366 else if (rhs.type == ADDRESSOF)
1368 /* x = &y */
1369 gcc_checking_assert (find (rhs.var) == rhs.var);
1370 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1372 else if (lhsvar > anything_id
1373 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1375 add_graph_edge (graph, lhsvar, rhsvar);
1379 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1380 receive pointers. */
1381 t = find (storedanything_id);
1382 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1384 if (!bitmap_bit_p (graph->direct_nodes, i)
1385 && get_varinfo (i)->may_have_pointers)
1386 add_graph_edge (graph, find (i), t);
1389 /* Everything stored to ANYTHING also potentially escapes. */
1390 add_graph_edge (graph, find (escaped_id), t);
1394 /* Changed variables on the last iteration. */
1395 static bitmap changed;
1397 /* Strongly Connected Component visitation info. */
1399 struct scc_info
1401 sbitmap visited;
1402 sbitmap deleted;
1403 unsigned int *dfs;
1404 unsigned int *node_mapping;
1405 int current_index;
1406 vec<unsigned> scc_stack;
1410 /* Recursive routine to find strongly connected components in GRAPH.
1411 SI is the SCC info to store the information in, and N is the id of current
1412 graph node we are processing.
1414 This is Tarjan's strongly connected component finding algorithm, as
1415 modified by Nuutila to keep only non-root nodes on the stack.
1416 The algorithm can be found in "On finding the strongly connected
1417 connected components in a directed graph" by Esko Nuutila and Eljas
1418 Soisalon-Soininen, in Information Processing Letters volume 49,
1419 number 1, pages 9-14. */
1421 static void
1422 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1424 unsigned int i;
1425 bitmap_iterator bi;
1426 unsigned int my_dfs;
1428 bitmap_set_bit (si->visited, n);
1429 si->dfs[n] = si->current_index ++;
1430 my_dfs = si->dfs[n];
1432 /* Visit all the successors. */
1433 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1435 unsigned int w;
1437 if (i > LAST_REF_NODE)
1438 break;
1440 w = find (i);
1441 if (bitmap_bit_p (si->deleted, w))
1442 continue;
1444 if (!bitmap_bit_p (si->visited, w))
1445 scc_visit (graph, si, w);
1447 unsigned int t = find (w);
1448 gcc_checking_assert (find (n) == n);
1449 if (si->dfs[t] < si->dfs[n])
1450 si->dfs[n] = si->dfs[t];
1453 /* See if any components have been identified. */
1454 if (si->dfs[n] == my_dfs)
1456 if (si->scc_stack.length () > 0
1457 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1459 bitmap scc = BITMAP_ALLOC (NULL);
1460 unsigned int lowest_node;
1461 bitmap_iterator bi;
1463 bitmap_set_bit (scc, n);
1465 while (si->scc_stack.length () != 0
1466 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1468 unsigned int w = si->scc_stack.pop ();
1470 bitmap_set_bit (scc, w);
1473 lowest_node = bitmap_first_set_bit (scc);
1474 gcc_assert (lowest_node < FIRST_REF_NODE);
1476 /* Collapse the SCC nodes into a single node, and mark the
1477 indirect cycles. */
1478 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1480 if (i < FIRST_REF_NODE)
1482 if (unite (lowest_node, i))
1483 unify_nodes (graph, lowest_node, i, false);
1485 else
1487 unite (lowest_node, i);
1488 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1492 bitmap_set_bit (si->deleted, n);
1494 else
1495 si->scc_stack.safe_push (n);
1498 /* Unify node FROM into node TO, updating the changed count if
1499 necessary when UPDATE_CHANGED is true. */
1501 static void
1502 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1503 bool update_changed)
1505 gcc_checking_assert (to != from && find (to) == to);
1507 if (dump_file && (dump_flags & TDF_DETAILS))
1508 fprintf (dump_file, "Unifying %s to %s\n",
1509 get_varinfo (from)->name,
1510 get_varinfo (to)->name);
1512 if (update_changed)
1513 stats.unified_vars_dynamic++;
1514 else
1515 stats.unified_vars_static++;
1517 merge_graph_nodes (graph, to, from);
1518 if (merge_node_constraints (graph, to, from))
1520 if (update_changed)
1521 bitmap_set_bit (changed, to);
1524 /* Mark TO as changed if FROM was changed. If TO was already marked
1525 as changed, decrease the changed count. */
1527 if (update_changed
1528 && bitmap_clear_bit (changed, from))
1529 bitmap_set_bit (changed, to);
1530 varinfo_t fromvi = get_varinfo (from);
1531 if (fromvi->solution)
1533 /* If the solution changes because of the merging, we need to mark
1534 the variable as changed. */
1535 varinfo_t tovi = get_varinfo (to);
1536 if (bitmap_ior_into (tovi->solution, fromvi->solution))
1538 if (update_changed)
1539 bitmap_set_bit (changed, to);
1542 BITMAP_FREE (fromvi->solution);
1543 if (fromvi->oldsolution)
1544 BITMAP_FREE (fromvi->oldsolution);
1546 if (stats.iterations > 0
1547 && tovi->oldsolution)
1548 BITMAP_FREE (tovi->oldsolution);
1550 if (graph->succs[to])
1551 bitmap_clear_bit (graph->succs[to], to);
1554 /* Information needed to compute the topological ordering of a graph. */
1556 struct topo_info
1558 /* sbitmap of visited nodes. */
1559 sbitmap visited;
1560 /* Array that stores the topological order of the graph, *in
1561 reverse*. */
1562 vec<unsigned> topo_order;
1566 /* Initialize and return a topological info structure. */
1568 static struct topo_info *
1569 init_topo_info (void)
1571 size_t size = graph->size;
1572 struct topo_info *ti = XNEW (struct topo_info);
1573 ti->visited = sbitmap_alloc (size);
1574 bitmap_clear (ti->visited);
1575 ti->topo_order.create (1);
1576 return ti;
1580 /* Free the topological sort info pointed to by TI. */
1582 static void
1583 free_topo_info (struct topo_info *ti)
1585 sbitmap_free (ti->visited);
1586 ti->topo_order.release ();
1587 free (ti);
1590 /* Visit the graph in topological order, and store the order in the
1591 topo_info structure. */
1593 static void
1594 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1595 unsigned int n)
1597 bitmap_iterator bi;
1598 unsigned int j;
1600 bitmap_set_bit (ti->visited, n);
1602 if (graph->succs[n])
1603 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1605 if (!bitmap_bit_p (ti->visited, j))
1606 topo_visit (graph, ti, j);
1609 ti->topo_order.safe_push (n);
1612 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1613 starting solution for y. */
1615 static void
1616 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1617 bitmap delta, bitmap *expanded_delta)
1619 unsigned int lhs = c->lhs.var;
1620 bool flag = false;
1621 bitmap sol = get_varinfo (lhs)->solution;
1622 unsigned int j;
1623 bitmap_iterator bi;
1624 HOST_WIDE_INT roffset = c->rhs.offset;
1626 /* Our IL does not allow this. */
1627 gcc_checking_assert (c->lhs.offset == 0);
1629 /* If the solution of Y contains anything it is good enough to transfer
1630 this to the LHS. */
1631 if (bitmap_bit_p (delta, anything_id))
1633 flag |= bitmap_set_bit (sol, anything_id);
1634 goto done;
1637 /* If we do not know at with offset the rhs is dereferenced compute
1638 the reachability set of DELTA, conservatively assuming it is
1639 dereferenced at all valid offsets. */
1640 if (roffset == UNKNOWN_OFFSET)
1642 delta = solution_set_expand (delta, expanded_delta);
1643 /* No further offset processing is necessary. */
1644 roffset = 0;
1647 /* For each variable j in delta (Sol(y)), add
1648 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1649 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1651 varinfo_t v = get_varinfo (j);
1652 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1653 unsigned HOST_WIDE_INT size = v->size;
1654 unsigned int t;
1656 if (v->is_full_var)
1658 else if (roffset != 0)
1660 if (fieldoffset < 0)
1661 v = get_varinfo (v->head);
1662 else
1663 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1666 /* We have to include all fields that overlap the current field
1667 shifted by roffset. */
1670 t = find (v->id);
1672 /* Adding edges from the special vars is pointless.
1673 They don't have sets that can change. */
1674 if (get_varinfo (t)->is_special_var)
1675 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1676 /* Merging the solution from ESCAPED needlessly increases
1677 the set. Use ESCAPED as representative instead. */
1678 else if (v->id == escaped_id)
1679 flag |= bitmap_set_bit (sol, escaped_id);
1680 else if (v->may_have_pointers
1681 && add_graph_edge (graph, lhs, t))
1682 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1684 if (v->is_full_var
1685 || v->next == 0)
1686 break;
1688 v = vi_next (v);
1690 while (v->offset < fieldoffset + size);
1693 done:
1694 /* If the LHS solution changed, mark the var as changed. */
1695 if (flag)
1697 get_varinfo (lhs)->solution = sol;
1698 bitmap_set_bit (changed, lhs);
1702 /* Process a constraint C that represents *(x + off) = y using DELTA
1703 as the starting solution for x. */
1705 static void
1706 do_ds_constraint (constraint_t c, bitmap delta, bitmap *expanded_delta)
1708 unsigned int rhs = c->rhs.var;
1709 bitmap sol = get_varinfo (rhs)->solution;
1710 unsigned int j;
1711 bitmap_iterator bi;
1712 HOST_WIDE_INT loff = c->lhs.offset;
1713 bool escaped_p = false;
1715 /* Our IL does not allow this. */
1716 gcc_checking_assert (c->rhs.offset == 0);
1718 /* If the solution of y contains ANYTHING simply use the ANYTHING
1719 solution. This avoids needlessly increasing the points-to sets. */
1720 if (bitmap_bit_p (sol, anything_id))
1721 sol = get_varinfo (find (anything_id))->solution;
1723 /* If the solution for x contains ANYTHING we have to merge the
1724 solution of y into all pointer variables which we do via
1725 STOREDANYTHING. */
1726 if (bitmap_bit_p (delta, anything_id))
1728 unsigned t = find (storedanything_id);
1729 if (add_graph_edge (graph, t, rhs))
1731 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1732 bitmap_set_bit (changed, t);
1734 return;
1737 /* If we do not know at with offset the rhs is dereferenced compute
1738 the reachability set of DELTA, conservatively assuming it is
1739 dereferenced at all valid offsets. */
1740 if (loff == UNKNOWN_OFFSET)
1742 delta = solution_set_expand (delta, expanded_delta);
1743 loff = 0;
1746 /* For each member j of delta (Sol(x)), add an edge from y to j and
1747 union Sol(y) into Sol(j) */
1748 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1750 varinfo_t v = get_varinfo (j);
1751 unsigned int t;
1752 HOST_WIDE_INT fieldoffset = v->offset + loff;
1753 unsigned HOST_WIDE_INT size = v->size;
1755 if (v->is_full_var)
1757 else if (loff != 0)
1759 if (fieldoffset < 0)
1760 v = get_varinfo (v->head);
1761 else
1762 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1765 /* We have to include all fields that overlap the current field
1766 shifted by loff. */
1769 if (v->may_have_pointers)
1771 /* If v is a global variable then this is an escape point. */
1772 if (v->is_global_var
1773 && !escaped_p)
1775 t = find (escaped_id);
1776 if (add_graph_edge (graph, t, rhs)
1777 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1778 bitmap_set_bit (changed, t);
1779 /* Enough to let rhs escape once. */
1780 escaped_p = true;
1783 if (v->is_special_var)
1784 break;
1786 t = find (v->id);
1787 if (add_graph_edge (graph, t, rhs)
1788 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1789 bitmap_set_bit (changed, t);
1792 if (v->is_full_var
1793 || v->next == 0)
1794 break;
1796 v = vi_next (v);
1798 while (v->offset < fieldoffset + size);
1802 /* Handle a non-simple (simple meaning requires no iteration),
1803 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1805 static void
1806 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta,
1807 bitmap *expanded_delta)
1809 if (c->lhs.type == DEREF)
1811 if (c->rhs.type == ADDRESSOF)
1813 gcc_unreachable ();
1815 else
1817 /* *x = y */
1818 do_ds_constraint (c, delta, expanded_delta);
1821 else if (c->rhs.type == DEREF)
1823 /* x = *y */
1824 if (!(get_varinfo (c->lhs.var)->is_special_var))
1825 do_sd_constraint (graph, c, delta, expanded_delta);
1827 else
1829 bitmap tmp;
1830 bool flag = false;
1832 gcc_checking_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR
1833 && c->rhs.offset != 0 && c->lhs.offset == 0);
1834 tmp = get_varinfo (c->lhs.var)->solution;
1836 flag = set_union_with_increment (tmp, delta, c->rhs.offset,
1837 expanded_delta);
1839 if (flag)
1840 bitmap_set_bit (changed, c->lhs.var);
1844 /* Initialize and return a new SCC info structure. */
1846 static struct scc_info *
1847 init_scc_info (size_t size)
1849 struct scc_info *si = XNEW (struct scc_info);
1850 size_t i;
1852 si->current_index = 0;
1853 si->visited = sbitmap_alloc (size);
1854 bitmap_clear (si->visited);
1855 si->deleted = sbitmap_alloc (size);
1856 bitmap_clear (si->deleted);
1857 si->node_mapping = XNEWVEC (unsigned int, size);
1858 si->dfs = XCNEWVEC (unsigned int, size);
1860 for (i = 0; i < size; i++)
1861 si->node_mapping[i] = i;
1863 si->scc_stack.create (1);
1864 return si;
1867 /* Free an SCC info structure pointed to by SI */
1869 static void
1870 free_scc_info (struct scc_info *si)
1872 sbitmap_free (si->visited);
1873 sbitmap_free (si->deleted);
1874 free (si->node_mapping);
1875 free (si->dfs);
1876 si->scc_stack.release ();
1877 free (si);
1881 /* Find indirect cycles in GRAPH that occur, using strongly connected
1882 components, and note them in the indirect cycles map.
1884 This technique comes from Ben Hardekopf and Calvin Lin,
1885 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1886 Lines of Code", submitted to PLDI 2007. */
1888 static void
1889 find_indirect_cycles (constraint_graph_t graph)
1891 unsigned int i;
1892 unsigned int size = graph->size;
1893 struct scc_info *si = init_scc_info (size);
1895 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1896 if (!bitmap_bit_p (si->visited, i) && find (i) == i)
1897 scc_visit (graph, si, i);
1899 free_scc_info (si);
1902 /* Compute a topological ordering for GRAPH, and store the result in the
1903 topo_info structure TI. */
1905 static void
1906 compute_topo_order (constraint_graph_t graph,
1907 struct topo_info *ti)
1909 unsigned int i;
1910 unsigned int size = graph->size;
1912 for (i = 0; i != size; ++i)
1913 if (!bitmap_bit_p (ti->visited, i) && find (i) == i)
1914 topo_visit (graph, ti, i);
1917 /* Structure used to for hash value numbering of pointer equivalence
1918 classes. */
1920 typedef struct equiv_class_label
1922 hashval_t hashcode;
1923 unsigned int equivalence_class;
1924 bitmap labels;
1925 } *equiv_class_label_t;
1926 typedef const struct equiv_class_label *const_equiv_class_label_t;
1928 /* Equiv_class_label hashtable helpers. */
1930 struct equiv_class_hasher : typed_free_remove <equiv_class_label>
1932 typedef equiv_class_label *value_type;
1933 typedef equiv_class_label *compare_type;
1934 static inline hashval_t hash (const equiv_class_label *);
1935 static inline bool equal (const equiv_class_label *,
1936 const equiv_class_label *);
1939 /* Hash function for a equiv_class_label_t */
1941 inline hashval_t
1942 equiv_class_hasher::hash (const equiv_class_label *ecl)
1944 return ecl->hashcode;
1947 /* Equality function for two equiv_class_label_t's. */
1949 inline bool
1950 equiv_class_hasher::equal (const equiv_class_label *eql1,
1951 const equiv_class_label *eql2)
1953 return (eql1->hashcode == eql2->hashcode
1954 && bitmap_equal_p (eql1->labels, eql2->labels));
1957 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1958 classes. */
1959 static hash_table<equiv_class_hasher> *pointer_equiv_class_table;
1961 /* A hashtable for mapping a bitmap of labels->location equivalence
1962 classes. */
1963 static hash_table<equiv_class_hasher> *location_equiv_class_table;
1965 /* Lookup a equivalence class in TABLE by the bitmap of LABELS with
1966 hash HAS it contains. Sets *REF_LABELS to the bitmap LABELS
1967 is equivalent to. */
1969 static equiv_class_label *
1970 equiv_class_lookup_or_add (hash_table<equiv_class_hasher> *table,
1971 bitmap labels)
1973 equiv_class_label **slot;
1974 equiv_class_label ecl;
1976 ecl.labels = labels;
1977 ecl.hashcode = bitmap_hash (labels);
1978 slot = table->find_slot (&ecl, INSERT);
1979 if (!*slot)
1981 *slot = XNEW (struct equiv_class_label);
1982 (*slot)->labels = labels;
1983 (*slot)->hashcode = ecl.hashcode;
1984 (*slot)->equivalence_class = 0;
1987 return *slot;
1990 /* Perform offline variable substitution.
1992 This is a worst case quadratic time way of identifying variables
1993 that must have equivalent points-to sets, including those caused by
1994 static cycles, and single entry subgraphs, in the constraint graph.
1996 The technique is described in "Exploiting Pointer and Location
1997 Equivalence to Optimize Pointer Analysis. In the 14th International
1998 Static Analysis Symposium (SAS), August 2007." It is known as the
1999 "HU" algorithm, and is equivalent to value numbering the collapsed
2000 constraint graph including evaluating unions.
2002 The general method of finding equivalence classes is as follows:
2003 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
2004 Initialize all non-REF nodes to be direct nodes.
2005 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
2006 variable}
2007 For each constraint containing the dereference, we also do the same
2008 thing.
2010 We then compute SCC's in the graph and unify nodes in the same SCC,
2011 including pts sets.
2013 For each non-collapsed node x:
2014 Visit all unvisited explicit incoming edges.
2015 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
2016 where y->x.
2017 Lookup the equivalence class for pts(x).
2018 If we found one, equivalence_class(x) = found class.
2019 Otherwise, equivalence_class(x) = new class, and new_class is
2020 added to the lookup table.
2022 All direct nodes with the same equivalence class can be replaced
2023 with a single representative node.
2024 All unlabeled nodes (label == 0) are not pointers and all edges
2025 involving them can be eliminated.
2026 We perform these optimizations during rewrite_constraints
2028 In addition to pointer equivalence class finding, we also perform
2029 location equivalence class finding. This is the set of variables
2030 that always appear together in points-to sets. We use this to
2031 compress the size of the points-to sets. */
2033 /* Current maximum pointer equivalence class id. */
2034 static int pointer_equiv_class;
2036 /* Current maximum location equivalence class id. */
2037 static int location_equiv_class;
2039 /* Recursive routine to find strongly connected components in GRAPH,
2040 and label it's nodes with DFS numbers. */
2042 static void
2043 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2045 unsigned int i;
2046 bitmap_iterator bi;
2047 unsigned int my_dfs;
2049 gcc_checking_assert (si->node_mapping[n] == n);
2050 bitmap_set_bit (si->visited, n);
2051 si->dfs[n] = si->current_index ++;
2052 my_dfs = si->dfs[n];
2054 /* Visit all the successors. */
2055 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2057 unsigned int w = si->node_mapping[i];
2059 if (bitmap_bit_p (si->deleted, w))
2060 continue;
2062 if (!bitmap_bit_p (si->visited, w))
2063 condense_visit (graph, si, w);
2065 unsigned int t = si->node_mapping[w];
2066 gcc_checking_assert (si->node_mapping[n] == n);
2067 if (si->dfs[t] < si->dfs[n])
2068 si->dfs[n] = si->dfs[t];
2071 /* Visit all the implicit predecessors. */
2072 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2074 unsigned int w = si->node_mapping[i];
2076 if (bitmap_bit_p (si->deleted, w))
2077 continue;
2079 if (!bitmap_bit_p (si->visited, w))
2080 condense_visit (graph, si, w);
2082 unsigned int t = si->node_mapping[w];
2083 gcc_assert (si->node_mapping[n] == n);
2084 if (si->dfs[t] < si->dfs[n])
2085 si->dfs[n] = si->dfs[t];
2088 /* See if any components have been identified. */
2089 if (si->dfs[n] == my_dfs)
2091 while (si->scc_stack.length () != 0
2092 && si->dfs[si->scc_stack.last ()] >= my_dfs)
2094 unsigned int w = si->scc_stack.pop ();
2095 si->node_mapping[w] = n;
2097 if (!bitmap_bit_p (graph->direct_nodes, w))
2098 bitmap_clear_bit (graph->direct_nodes, n);
2100 /* Unify our nodes. */
2101 if (graph->preds[w])
2103 if (!graph->preds[n])
2104 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2105 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2107 if (graph->implicit_preds[w])
2109 if (!graph->implicit_preds[n])
2110 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2111 bitmap_ior_into (graph->implicit_preds[n],
2112 graph->implicit_preds[w]);
2114 if (graph->points_to[w])
2116 if (!graph->points_to[n])
2117 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2118 bitmap_ior_into (graph->points_to[n],
2119 graph->points_to[w]);
2122 bitmap_set_bit (si->deleted, n);
2124 else
2125 si->scc_stack.safe_push (n);
2128 /* Label pointer equivalences.
2130 This performs a value numbering of the constraint graph to
2131 discover which variables will always have the same points-to sets
2132 under the current set of constraints.
2134 The way it value numbers is to store the set of points-to bits
2135 generated by the constraints and graph edges. This is just used as a
2136 hash and equality comparison. The *actual set of points-to bits* is
2137 completely irrelevant, in that we don't care about being able to
2138 extract them later.
2140 The equality values (currently bitmaps) just have to satisfy a few
2141 constraints, the main ones being:
2142 1. The combining operation must be order independent.
2143 2. The end result of a given set of operations must be unique iff the
2144 combination of input values is unique
2145 3. Hashable. */
2147 static void
2148 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2150 unsigned int i, first_pred;
2151 bitmap_iterator bi;
2153 bitmap_set_bit (si->visited, n);
2155 /* Label and union our incoming edges's points to sets. */
2156 first_pred = -1U;
2157 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2159 unsigned int w = si->node_mapping[i];
2160 if (!bitmap_bit_p (si->visited, w))
2161 label_visit (graph, si, w);
2163 /* Skip unused edges */
2164 if (w == n || graph->pointer_label[w] == 0)
2165 continue;
2167 if (graph->points_to[w])
2169 if (!graph->points_to[n])
2171 if (first_pred == -1U)
2172 first_pred = w;
2173 else
2175 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2176 bitmap_ior (graph->points_to[n],
2177 graph->points_to[first_pred],
2178 graph->points_to[w]);
2181 else
2182 bitmap_ior_into (graph->points_to[n], graph->points_to[w]);
2186 /* Indirect nodes get fresh variables and a new pointer equiv class. */
2187 if (!bitmap_bit_p (graph->direct_nodes, n))
2189 if (!graph->points_to[n])
2191 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2192 if (first_pred != -1U)
2193 bitmap_copy (graph->points_to[n], graph->points_to[first_pred]);
2195 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2196 graph->pointer_label[n] = pointer_equiv_class++;
2197 equiv_class_label_t ecl;
2198 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2199 graph->points_to[n]);
2200 ecl->equivalence_class = graph->pointer_label[n];
2201 return;
2204 /* If there was only a single non-empty predecessor the pointer equiv
2205 class is the same. */
2206 if (!graph->points_to[n])
2208 if (first_pred != -1U)
2210 graph->pointer_label[n] = graph->pointer_label[first_pred];
2211 graph->points_to[n] = graph->points_to[first_pred];
2213 return;
2216 if (!bitmap_empty_p (graph->points_to[n]))
2218 equiv_class_label_t ecl;
2219 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2220 graph->points_to[n]);
2221 if (ecl->equivalence_class == 0)
2222 ecl->equivalence_class = pointer_equiv_class++;
2223 else
2225 BITMAP_FREE (graph->points_to[n]);
2226 graph->points_to[n] = ecl->labels;
2228 graph->pointer_label[n] = ecl->equivalence_class;
2232 /* Print the pred graph in dot format. */
2234 static void
2235 dump_pred_graph (struct scc_info *si, FILE *file)
2237 unsigned int i;
2239 /* Only print the graph if it has already been initialized: */
2240 if (!graph)
2241 return;
2243 /* Prints the header of the dot file: */
2244 fprintf (file, "strict digraph {\n");
2245 fprintf (file, " node [\n shape = box\n ]\n");
2246 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
2247 fprintf (file, "\n // List of nodes and complex constraints in "
2248 "the constraint graph:\n");
2250 /* The next lines print the nodes in the graph together with the
2251 complex constraints attached to them. */
2252 for (i = 1; i < graph->size; i++)
2254 if (i == FIRST_REF_NODE)
2255 continue;
2256 if (si->node_mapping[i] != i)
2257 continue;
2258 if (i < FIRST_REF_NODE)
2259 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2260 else
2261 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2262 if (graph->points_to[i]
2263 && !bitmap_empty_p (graph->points_to[i]))
2265 fprintf (file, "[label=\"%s = {", get_varinfo (i)->name);
2266 unsigned j;
2267 bitmap_iterator bi;
2268 EXECUTE_IF_SET_IN_BITMAP (graph->points_to[i], 0, j, bi)
2269 fprintf (file, " %d", j);
2270 fprintf (file, " }\"]");
2272 fprintf (file, ";\n");
2275 /* Go over the edges. */
2276 fprintf (file, "\n // Edges in the constraint graph:\n");
2277 for (i = 1; i < graph->size; i++)
2279 unsigned j;
2280 bitmap_iterator bi;
2281 if (si->node_mapping[i] != i)
2282 continue;
2283 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[i], 0, j, bi)
2285 unsigned from = si->node_mapping[j];
2286 if (from < FIRST_REF_NODE)
2287 fprintf (file, "\"%s\"", get_varinfo (from)->name);
2288 else
2289 fprintf (file, "\"*%s\"", get_varinfo (from - FIRST_REF_NODE)->name);
2290 fprintf (file, " -> ");
2291 if (i < FIRST_REF_NODE)
2292 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2293 else
2294 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2295 fprintf (file, ";\n");
2299 /* Prints the tail of the dot file. */
2300 fprintf (file, "}\n");
2303 /* Perform offline variable substitution, discovering equivalence
2304 classes, and eliminating non-pointer variables. */
2306 static struct scc_info *
2307 perform_var_substitution (constraint_graph_t graph)
2309 unsigned int i;
2310 unsigned int size = graph->size;
2311 struct scc_info *si = init_scc_info (size);
2313 bitmap_obstack_initialize (&iteration_obstack);
2314 pointer_equiv_class_table = new hash_table<equiv_class_hasher> (511);
2315 location_equiv_class_table
2316 = new hash_table<equiv_class_hasher> (511);
2317 pointer_equiv_class = 1;
2318 location_equiv_class = 1;
2320 /* Condense the nodes, which means to find SCC's, count incoming
2321 predecessors, and unite nodes in SCC's. */
2322 for (i = 1; i < FIRST_REF_NODE; i++)
2323 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2324 condense_visit (graph, si, si->node_mapping[i]);
2326 if (dump_file && (dump_flags & TDF_GRAPH))
2328 fprintf (dump_file, "\n\n// The constraint graph before var-substitution "
2329 "in dot format:\n");
2330 dump_pred_graph (si, dump_file);
2331 fprintf (dump_file, "\n\n");
2334 bitmap_clear (si->visited);
2335 /* Actually the label the nodes for pointer equivalences */
2336 for (i = 1; i < FIRST_REF_NODE; i++)
2337 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2338 label_visit (graph, si, si->node_mapping[i]);
2340 /* Calculate location equivalence labels. */
2341 for (i = 1; i < FIRST_REF_NODE; i++)
2343 bitmap pointed_by;
2344 bitmap_iterator bi;
2345 unsigned int j;
2347 if (!graph->pointed_by[i])
2348 continue;
2349 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2351 /* Translate the pointed-by mapping for pointer equivalence
2352 labels. */
2353 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2355 bitmap_set_bit (pointed_by,
2356 graph->pointer_label[si->node_mapping[j]]);
2358 /* The original pointed_by is now dead. */
2359 BITMAP_FREE (graph->pointed_by[i]);
2361 /* Look up the location equivalence label if one exists, or make
2362 one otherwise. */
2363 equiv_class_label_t ecl;
2364 ecl = equiv_class_lookup_or_add (location_equiv_class_table, pointed_by);
2365 if (ecl->equivalence_class == 0)
2366 ecl->equivalence_class = location_equiv_class++;
2367 else
2369 if (dump_file && (dump_flags & TDF_DETAILS))
2370 fprintf (dump_file, "Found location equivalence for node %s\n",
2371 get_varinfo (i)->name);
2372 BITMAP_FREE (pointed_by);
2374 graph->loc_label[i] = ecl->equivalence_class;
2378 if (dump_file && (dump_flags & TDF_DETAILS))
2379 for (i = 1; i < FIRST_REF_NODE; i++)
2381 unsigned j = si->node_mapping[i];
2382 if (j != i)
2384 fprintf (dump_file, "%s node id %d ",
2385 bitmap_bit_p (graph->direct_nodes, i)
2386 ? "Direct" : "Indirect", i);
2387 if (i < FIRST_REF_NODE)
2388 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2389 else
2390 fprintf (dump_file, "\"*%s\"",
2391 get_varinfo (i - FIRST_REF_NODE)->name);
2392 fprintf (dump_file, " mapped to SCC leader node id %d ", j);
2393 if (j < FIRST_REF_NODE)
2394 fprintf (dump_file, "\"%s\"\n", get_varinfo (j)->name);
2395 else
2396 fprintf (dump_file, "\"*%s\"\n",
2397 get_varinfo (j - FIRST_REF_NODE)->name);
2399 else
2401 fprintf (dump_file,
2402 "Equivalence classes for %s node id %d ",
2403 bitmap_bit_p (graph->direct_nodes, i)
2404 ? "direct" : "indirect", i);
2405 if (i < FIRST_REF_NODE)
2406 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2407 else
2408 fprintf (dump_file, "\"*%s\"",
2409 get_varinfo (i - FIRST_REF_NODE)->name);
2410 fprintf (dump_file,
2411 ": pointer %d, location %d\n",
2412 graph->pointer_label[i], graph->loc_label[i]);
2416 /* Quickly eliminate our non-pointer variables. */
2418 for (i = 1; i < FIRST_REF_NODE; i++)
2420 unsigned int node = si->node_mapping[i];
2422 if (graph->pointer_label[node] == 0)
2424 if (dump_file && (dump_flags & TDF_DETAILS))
2425 fprintf (dump_file,
2426 "%s is a non-pointer variable, eliminating edges.\n",
2427 get_varinfo (node)->name);
2428 stats.nonpointer_vars++;
2429 clear_edges_for_node (graph, node);
2433 return si;
2436 /* Free information that was only necessary for variable
2437 substitution. */
2439 static void
2440 free_var_substitution_info (struct scc_info *si)
2442 free_scc_info (si);
2443 free (graph->pointer_label);
2444 free (graph->loc_label);
2445 free (graph->pointed_by);
2446 free (graph->points_to);
2447 free (graph->eq_rep);
2448 sbitmap_free (graph->direct_nodes);
2449 delete pointer_equiv_class_table;
2450 pointer_equiv_class_table = NULL;
2451 delete location_equiv_class_table;
2452 location_equiv_class_table = NULL;
2453 bitmap_obstack_release (&iteration_obstack);
2456 /* Return an existing node that is equivalent to NODE, which has
2457 equivalence class LABEL, if one exists. Return NODE otherwise. */
2459 static unsigned int
2460 find_equivalent_node (constraint_graph_t graph,
2461 unsigned int node, unsigned int label)
2463 /* If the address version of this variable is unused, we can
2464 substitute it for anything else with the same label.
2465 Otherwise, we know the pointers are equivalent, but not the
2466 locations, and we can unite them later. */
2468 if (!bitmap_bit_p (graph->address_taken, node))
2470 gcc_checking_assert (label < graph->size);
2472 if (graph->eq_rep[label] != -1)
2474 /* Unify the two variables since we know they are equivalent. */
2475 if (unite (graph->eq_rep[label], node))
2476 unify_nodes (graph, graph->eq_rep[label], node, false);
2477 return graph->eq_rep[label];
2479 else
2481 graph->eq_rep[label] = node;
2482 graph->pe_rep[label] = node;
2485 else
2487 gcc_checking_assert (label < graph->size);
2488 graph->pe[node] = label;
2489 if (graph->pe_rep[label] == -1)
2490 graph->pe_rep[label] = node;
2493 return node;
2496 /* Unite pointer equivalent but not location equivalent nodes in
2497 GRAPH. This may only be performed once variable substitution is
2498 finished. */
2500 static void
2501 unite_pointer_equivalences (constraint_graph_t graph)
2503 unsigned int i;
2505 /* Go through the pointer equivalences and unite them to their
2506 representative, if they aren't already. */
2507 for (i = 1; i < FIRST_REF_NODE; i++)
2509 unsigned int label = graph->pe[i];
2510 if (label)
2512 int label_rep = graph->pe_rep[label];
2514 if (label_rep == -1)
2515 continue;
2517 label_rep = find (label_rep);
2518 if (label_rep >= 0 && unite (label_rep, find (i)))
2519 unify_nodes (graph, label_rep, i, false);
2524 /* Move complex constraints to the GRAPH nodes they belong to. */
2526 static void
2527 move_complex_constraints (constraint_graph_t graph)
2529 int i;
2530 constraint_t c;
2532 FOR_EACH_VEC_ELT (constraints, i, c)
2534 if (c)
2536 struct constraint_expr lhs = c->lhs;
2537 struct constraint_expr rhs = c->rhs;
2539 if (lhs.type == DEREF)
2541 insert_into_complex (graph, lhs.var, c);
2543 else if (rhs.type == DEREF)
2545 if (!(get_varinfo (lhs.var)->is_special_var))
2546 insert_into_complex (graph, rhs.var, c);
2548 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2549 && (lhs.offset != 0 || rhs.offset != 0))
2551 insert_into_complex (graph, rhs.var, c);
2558 /* Optimize and rewrite complex constraints while performing
2559 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2560 result of perform_variable_substitution. */
2562 static void
2563 rewrite_constraints (constraint_graph_t graph,
2564 struct scc_info *si)
2566 int i;
2567 constraint_t c;
2569 #ifdef ENABLE_CHECKING
2570 for (unsigned int j = 0; j < graph->size; j++)
2571 gcc_assert (find (j) == j);
2572 #endif
2574 FOR_EACH_VEC_ELT (constraints, i, c)
2576 struct constraint_expr lhs = c->lhs;
2577 struct constraint_expr rhs = c->rhs;
2578 unsigned int lhsvar = find (lhs.var);
2579 unsigned int rhsvar = find (rhs.var);
2580 unsigned int lhsnode, rhsnode;
2581 unsigned int lhslabel, rhslabel;
2583 lhsnode = si->node_mapping[lhsvar];
2584 rhsnode = si->node_mapping[rhsvar];
2585 lhslabel = graph->pointer_label[lhsnode];
2586 rhslabel = graph->pointer_label[rhsnode];
2588 /* See if it is really a non-pointer variable, and if so, ignore
2589 the constraint. */
2590 if (lhslabel == 0)
2592 if (dump_file && (dump_flags & TDF_DETAILS))
2595 fprintf (dump_file, "%s is a non-pointer variable,"
2596 "ignoring constraint:",
2597 get_varinfo (lhs.var)->name);
2598 dump_constraint (dump_file, c);
2599 fprintf (dump_file, "\n");
2601 constraints[i] = NULL;
2602 continue;
2605 if (rhslabel == 0)
2607 if (dump_file && (dump_flags & TDF_DETAILS))
2610 fprintf (dump_file, "%s is a non-pointer variable,"
2611 "ignoring constraint:",
2612 get_varinfo (rhs.var)->name);
2613 dump_constraint (dump_file, c);
2614 fprintf (dump_file, "\n");
2616 constraints[i] = NULL;
2617 continue;
2620 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2621 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2622 c->lhs.var = lhsvar;
2623 c->rhs.var = rhsvar;
2627 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2628 part of an SCC, false otherwise. */
2630 static bool
2631 eliminate_indirect_cycles (unsigned int node)
2633 if (graph->indirect_cycles[node] != -1
2634 && !bitmap_empty_p (get_varinfo (node)->solution))
2636 unsigned int i;
2637 auto_vec<unsigned> queue;
2638 int queuepos;
2639 unsigned int to = find (graph->indirect_cycles[node]);
2640 bitmap_iterator bi;
2642 /* We can't touch the solution set and call unify_nodes
2643 at the same time, because unify_nodes is going to do
2644 bitmap unions into it. */
2646 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2648 if (find (i) == i && i != to)
2650 if (unite (to, i))
2651 queue.safe_push (i);
2655 for (queuepos = 0;
2656 queue.iterate (queuepos, &i);
2657 queuepos++)
2659 unify_nodes (graph, to, i, true);
2661 return true;
2663 return false;
2666 /* Solve the constraint graph GRAPH using our worklist solver.
2667 This is based on the PW* family of solvers from the "Efficient Field
2668 Sensitive Pointer Analysis for C" paper.
2669 It works by iterating over all the graph nodes, processing the complex
2670 constraints and propagating the copy constraints, until everything stops
2671 changed. This corresponds to steps 6-8 in the solving list given above. */
2673 static void
2674 solve_graph (constraint_graph_t graph)
2676 unsigned int size = graph->size;
2677 unsigned int i;
2678 bitmap pts;
2680 changed = BITMAP_ALLOC (NULL);
2682 /* Mark all initial non-collapsed nodes as changed. */
2683 for (i = 1; i < size; i++)
2685 varinfo_t ivi = get_varinfo (i);
2686 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2687 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2688 || graph->complex[i].length () > 0))
2689 bitmap_set_bit (changed, i);
2692 /* Allocate a bitmap to be used to store the changed bits. */
2693 pts = BITMAP_ALLOC (&pta_obstack);
2695 while (!bitmap_empty_p (changed))
2697 unsigned int i;
2698 struct topo_info *ti = init_topo_info ();
2699 stats.iterations++;
2701 bitmap_obstack_initialize (&iteration_obstack);
2703 compute_topo_order (graph, ti);
2705 while (ti->topo_order.length () != 0)
2708 i = ti->topo_order.pop ();
2710 /* If this variable is not a representative, skip it. */
2711 if (find (i) != i)
2712 continue;
2714 /* In certain indirect cycle cases, we may merge this
2715 variable to another. */
2716 if (eliminate_indirect_cycles (i) && find (i) != i)
2717 continue;
2719 /* If the node has changed, we need to process the
2720 complex constraints and outgoing edges again. */
2721 if (bitmap_clear_bit (changed, i))
2723 unsigned int j;
2724 constraint_t c;
2725 bitmap solution;
2726 vec<constraint_t> complex = graph->complex[i];
2727 varinfo_t vi = get_varinfo (i);
2728 bool solution_empty;
2730 /* Compute the changed set of solution bits. If anything
2731 is in the solution just propagate that. */
2732 if (bitmap_bit_p (vi->solution, anything_id))
2734 /* If anything is also in the old solution there is
2735 nothing to do.
2736 ??? But we shouldn't ended up with "changed" set ... */
2737 if (vi->oldsolution
2738 && bitmap_bit_p (vi->oldsolution, anything_id))
2739 continue;
2740 bitmap_copy (pts, get_varinfo (find (anything_id))->solution);
2742 else if (vi->oldsolution)
2743 bitmap_and_compl (pts, vi->solution, vi->oldsolution);
2744 else
2745 bitmap_copy (pts, vi->solution);
2747 if (bitmap_empty_p (pts))
2748 continue;
2750 if (vi->oldsolution)
2751 bitmap_ior_into (vi->oldsolution, pts);
2752 else
2754 vi->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
2755 bitmap_copy (vi->oldsolution, pts);
2758 solution = vi->solution;
2759 solution_empty = bitmap_empty_p (solution);
2761 /* Process the complex constraints */
2762 bitmap expanded_pts = NULL;
2763 FOR_EACH_VEC_ELT (complex, j, c)
2765 /* XXX: This is going to unsort the constraints in
2766 some cases, which will occasionally add duplicate
2767 constraints during unification. This does not
2768 affect correctness. */
2769 c->lhs.var = find (c->lhs.var);
2770 c->rhs.var = find (c->rhs.var);
2772 /* The only complex constraint that can change our
2773 solution to non-empty, given an empty solution,
2774 is a constraint where the lhs side is receiving
2775 some set from elsewhere. */
2776 if (!solution_empty || c->lhs.type != DEREF)
2777 do_complex_constraint (graph, c, pts, &expanded_pts);
2779 BITMAP_FREE (expanded_pts);
2781 solution_empty = bitmap_empty_p (solution);
2783 if (!solution_empty)
2785 bitmap_iterator bi;
2786 unsigned eff_escaped_id = find (escaped_id);
2788 /* Propagate solution to all successors. */
2789 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2790 0, j, bi)
2792 bitmap tmp;
2793 bool flag;
2795 unsigned int to = find (j);
2796 tmp = get_varinfo (to)->solution;
2797 flag = false;
2799 /* Don't try to propagate to ourselves. */
2800 if (to == i)
2801 continue;
2803 /* If we propagate from ESCAPED use ESCAPED as
2804 placeholder. */
2805 if (i == eff_escaped_id)
2806 flag = bitmap_set_bit (tmp, escaped_id);
2807 else
2808 flag = bitmap_ior_into (tmp, pts);
2810 if (flag)
2811 bitmap_set_bit (changed, to);
2816 free_topo_info (ti);
2817 bitmap_obstack_release (&iteration_obstack);
2820 BITMAP_FREE (pts);
2821 BITMAP_FREE (changed);
2822 bitmap_obstack_release (&oldpta_obstack);
2825 /* Map from trees to variable infos. */
2826 static hash_map<tree, varinfo_t> *vi_for_tree;
2829 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2831 static void
2832 insert_vi_for_tree (tree t, varinfo_t vi)
2834 gcc_assert (vi);
2835 gcc_assert (!vi_for_tree->put (t, vi));
2838 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2839 exist in the map, return NULL, otherwise, return the varinfo we found. */
2841 static varinfo_t
2842 lookup_vi_for_tree (tree t)
2844 varinfo_t *slot = vi_for_tree->get (t);
2845 if (slot == NULL)
2846 return NULL;
2848 return *slot;
2851 /* Return a printable name for DECL */
2853 static const char *
2854 alias_get_name (tree decl)
2856 const char *res = NULL;
2857 char *temp;
2858 int num_printed = 0;
2860 if (!dump_file)
2861 return "NULL";
2863 if (TREE_CODE (decl) == SSA_NAME)
2865 res = get_name (decl);
2866 if (res)
2867 num_printed = asprintf (&temp, "%s_%u", res, SSA_NAME_VERSION (decl));
2868 else
2869 num_printed = asprintf (&temp, "_%u", SSA_NAME_VERSION (decl));
2870 if (num_printed > 0)
2872 res = ggc_strdup (temp);
2873 free (temp);
2876 else if (DECL_P (decl))
2878 if (DECL_ASSEMBLER_NAME_SET_P (decl))
2879 res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2880 else
2882 res = get_name (decl);
2883 if (!res)
2885 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2886 if (num_printed > 0)
2888 res = ggc_strdup (temp);
2889 free (temp);
2894 if (res != NULL)
2895 return res;
2897 return "NULL";
2900 /* Find the variable id for tree T in the map.
2901 If T doesn't exist in the map, create an entry for it and return it. */
2903 static varinfo_t
2904 get_vi_for_tree (tree t)
2906 varinfo_t *slot = vi_for_tree->get (t);
2907 if (slot == NULL)
2908 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2910 return *slot;
2913 /* Get a scalar constraint expression for a new temporary variable. */
2915 static struct constraint_expr
2916 new_scalar_tmp_constraint_exp (const char *name)
2918 struct constraint_expr tmp;
2919 varinfo_t vi;
2921 vi = new_var_info (NULL_TREE, name);
2922 vi->offset = 0;
2923 vi->size = -1;
2924 vi->fullsize = -1;
2925 vi->is_full_var = 1;
2927 tmp.var = vi->id;
2928 tmp.type = SCALAR;
2929 tmp.offset = 0;
2931 return tmp;
2934 /* Get a constraint expression vector from an SSA_VAR_P node.
2935 If address_p is true, the result will be taken its address of. */
2937 static void
2938 get_constraint_for_ssa_var (tree t, vec<ce_s> *results, bool address_p)
2940 struct constraint_expr cexpr;
2941 varinfo_t vi;
2943 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2944 gcc_assert (TREE_CODE (t) == SSA_NAME || DECL_P (t));
2946 /* For parameters, get at the points-to set for the actual parm
2947 decl. */
2948 if (TREE_CODE (t) == SSA_NAME
2949 && SSA_NAME_IS_DEFAULT_DEF (t)
2950 && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2951 || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL))
2953 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2954 return;
2957 /* For global variables resort to the alias target. */
2958 if (TREE_CODE (t) == VAR_DECL
2959 && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2961 varpool_node *node = varpool_node::get (t);
2962 if (node && node->alias && node->analyzed)
2964 node = node->ultimate_alias_target ();
2965 t = node->decl;
2969 vi = get_vi_for_tree (t);
2970 cexpr.var = vi->id;
2971 cexpr.type = SCALAR;
2972 cexpr.offset = 0;
2974 /* If we are not taking the address of the constraint expr, add all
2975 sub-fiels of the variable as well. */
2976 if (!address_p
2977 && !vi->is_full_var)
2979 for (; vi; vi = vi_next (vi))
2981 cexpr.var = vi->id;
2982 results->safe_push (cexpr);
2984 return;
2987 results->safe_push (cexpr);
2990 /* Process constraint T, performing various simplifications and then
2991 adding it to our list of overall constraints. */
2993 static void
2994 process_constraint (constraint_t t)
2996 struct constraint_expr rhs = t->rhs;
2997 struct constraint_expr lhs = t->lhs;
2999 gcc_assert (rhs.var < varmap.length ());
3000 gcc_assert (lhs.var < varmap.length ());
3002 /* If we didn't get any useful constraint from the lhs we get
3003 &ANYTHING as fallback from get_constraint_for. Deal with
3004 it here by turning it into *ANYTHING. */
3005 if (lhs.type == ADDRESSOF
3006 && lhs.var == anything_id)
3007 lhs.type = DEREF;
3009 /* ADDRESSOF on the lhs is invalid. */
3010 gcc_assert (lhs.type != ADDRESSOF);
3012 /* We shouldn't add constraints from things that cannot have pointers.
3013 It's not completely trivial to avoid in the callers, so do it here. */
3014 if (rhs.type != ADDRESSOF
3015 && !get_varinfo (rhs.var)->may_have_pointers)
3016 return;
3018 /* Likewise adding to the solution of a non-pointer var isn't useful. */
3019 if (!get_varinfo (lhs.var)->may_have_pointers)
3020 return;
3022 /* This can happen in our IR with things like n->a = *p */
3023 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
3025 /* Split into tmp = *rhs, *lhs = tmp */
3026 struct constraint_expr tmplhs;
3027 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
3028 process_constraint (new_constraint (tmplhs, rhs));
3029 process_constraint (new_constraint (lhs, tmplhs));
3031 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
3033 /* Split into tmp = &rhs, *lhs = tmp */
3034 struct constraint_expr tmplhs;
3035 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
3036 process_constraint (new_constraint (tmplhs, rhs));
3037 process_constraint (new_constraint (lhs, tmplhs));
3039 else
3041 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
3042 constraints.safe_push (t);
3047 /* Return the position, in bits, of FIELD_DECL from the beginning of its
3048 structure. */
3050 static HOST_WIDE_INT
3051 bitpos_of_field (const tree fdecl)
3053 if (!tree_fits_shwi_p (DECL_FIELD_OFFSET (fdecl))
3054 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fdecl)))
3055 return -1;
3057 return (tree_to_shwi (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
3058 + tree_to_shwi (DECL_FIELD_BIT_OFFSET (fdecl)));
3062 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
3063 resulting constraint expressions in *RESULTS. */
3065 static void
3066 get_constraint_for_ptr_offset (tree ptr, tree offset,
3067 vec<ce_s> *results)
3069 struct constraint_expr c;
3070 unsigned int j, n;
3071 HOST_WIDE_INT rhsoffset;
3073 /* If we do not do field-sensitive PTA adding offsets to pointers
3074 does not change the points-to solution. */
3075 if (!use_field_sensitive)
3077 get_constraint_for_rhs (ptr, results);
3078 return;
3081 /* If the offset is not a non-negative integer constant that fits
3082 in a HOST_WIDE_INT, we have to fall back to a conservative
3083 solution which includes all sub-fields of all pointed-to
3084 variables of ptr. */
3085 if (offset == NULL_TREE
3086 || TREE_CODE (offset) != INTEGER_CST)
3087 rhsoffset = UNKNOWN_OFFSET;
3088 else
3090 /* Sign-extend the offset. */
3091 offset_int soffset = offset_int::from (offset, SIGNED);
3092 if (!wi::fits_shwi_p (soffset))
3093 rhsoffset = UNKNOWN_OFFSET;
3094 else
3096 /* Make sure the bit-offset also fits. */
3097 HOST_WIDE_INT rhsunitoffset = soffset.to_shwi ();
3098 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
3099 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
3100 rhsoffset = UNKNOWN_OFFSET;
3104 get_constraint_for_rhs (ptr, results);
3105 if (rhsoffset == 0)
3106 return;
3108 /* As we are eventually appending to the solution do not use
3109 vec::iterate here. */
3110 n = results->length ();
3111 for (j = 0; j < n; j++)
3113 varinfo_t curr;
3114 c = (*results)[j];
3115 curr = get_varinfo (c.var);
3117 if (c.type == ADDRESSOF
3118 /* If this varinfo represents a full variable just use it. */
3119 && curr->is_full_var)
3121 else if (c.type == ADDRESSOF
3122 /* If we do not know the offset add all subfields. */
3123 && rhsoffset == UNKNOWN_OFFSET)
3125 varinfo_t temp = get_varinfo (curr->head);
3128 struct constraint_expr c2;
3129 c2.var = temp->id;
3130 c2.type = ADDRESSOF;
3131 c2.offset = 0;
3132 if (c2.var != c.var)
3133 results->safe_push (c2);
3134 temp = vi_next (temp);
3136 while (temp);
3138 else if (c.type == ADDRESSOF)
3140 varinfo_t temp;
3141 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3143 /* If curr->offset + rhsoffset is less than zero adjust it. */
3144 if (rhsoffset < 0
3145 && curr->offset < offset)
3146 offset = 0;
3148 /* We have to include all fields that overlap the current
3149 field shifted by rhsoffset. And we include at least
3150 the last or the first field of the variable to represent
3151 reachability of off-bound addresses, in particular &object + 1,
3152 conservatively correct. */
3153 temp = first_or_preceding_vi_for_offset (curr, offset);
3154 c.var = temp->id;
3155 c.offset = 0;
3156 temp = vi_next (temp);
3157 while (temp
3158 && temp->offset < offset + curr->size)
3160 struct constraint_expr c2;
3161 c2.var = temp->id;
3162 c2.type = ADDRESSOF;
3163 c2.offset = 0;
3164 results->safe_push (c2);
3165 temp = vi_next (temp);
3168 else if (c.type == SCALAR)
3170 gcc_assert (c.offset == 0);
3171 c.offset = rhsoffset;
3173 else
3174 /* We shouldn't get any DEREFs here. */
3175 gcc_unreachable ();
3177 (*results)[j] = c;
3182 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3183 If address_p is true the result will be taken its address of.
3184 If lhs_p is true then the constraint expression is assumed to be used
3185 as the lhs. */
3187 static void
3188 get_constraint_for_component_ref (tree t, vec<ce_s> *results,
3189 bool address_p, bool lhs_p)
3191 tree orig_t = t;
3192 HOST_WIDE_INT bitsize = -1;
3193 HOST_WIDE_INT bitmaxsize = -1;
3194 HOST_WIDE_INT bitpos;
3195 tree forzero;
3197 /* Some people like to do cute things like take the address of
3198 &0->a.b */
3199 forzero = t;
3200 while (handled_component_p (forzero)
3201 || INDIRECT_REF_P (forzero)
3202 || TREE_CODE (forzero) == MEM_REF)
3203 forzero = TREE_OPERAND (forzero, 0);
3205 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3207 struct constraint_expr temp;
3209 temp.offset = 0;
3210 temp.var = integer_id;
3211 temp.type = SCALAR;
3212 results->safe_push (temp);
3213 return;
3216 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
3218 /* Pretend to take the address of the base, we'll take care of
3219 adding the required subset of sub-fields below. */
3220 get_constraint_for_1 (t, results, true, lhs_p);
3221 gcc_assert (results->length () == 1);
3222 struct constraint_expr &result = results->last ();
3224 if (result.type == SCALAR
3225 && get_varinfo (result.var)->is_full_var)
3226 /* For single-field vars do not bother about the offset. */
3227 result.offset = 0;
3228 else if (result.type == SCALAR)
3230 /* In languages like C, you can access one past the end of an
3231 array. You aren't allowed to dereference it, so we can
3232 ignore this constraint. When we handle pointer subtraction,
3233 we may have to do something cute here. */
3235 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result.var)->fullsize
3236 && bitmaxsize != 0)
3238 /* It's also not true that the constraint will actually start at the
3239 right offset, it may start in some padding. We only care about
3240 setting the constraint to the first actual field it touches, so
3241 walk to find it. */
3242 struct constraint_expr cexpr = result;
3243 varinfo_t curr;
3244 results->pop ();
3245 cexpr.offset = 0;
3246 for (curr = get_varinfo (cexpr.var); curr; curr = vi_next (curr))
3248 if (ranges_overlap_p (curr->offset, curr->size,
3249 bitpos, bitmaxsize))
3251 cexpr.var = curr->id;
3252 results->safe_push (cexpr);
3253 if (address_p)
3254 break;
3257 /* If we are going to take the address of this field then
3258 to be able to compute reachability correctly add at least
3259 the last field of the variable. */
3260 if (address_p && results->length () == 0)
3262 curr = get_varinfo (cexpr.var);
3263 while (curr->next != 0)
3264 curr = vi_next (curr);
3265 cexpr.var = curr->id;
3266 results->safe_push (cexpr);
3268 else if (results->length () == 0)
3269 /* Assert that we found *some* field there. The user couldn't be
3270 accessing *only* padding. */
3271 /* Still the user could access one past the end of an array
3272 embedded in a struct resulting in accessing *only* padding. */
3273 /* Or accessing only padding via type-punning to a type
3274 that has a filed just in padding space. */
3276 cexpr.type = SCALAR;
3277 cexpr.var = anything_id;
3278 cexpr.offset = 0;
3279 results->safe_push (cexpr);
3282 else if (bitmaxsize == 0)
3284 if (dump_file && (dump_flags & TDF_DETAILS))
3285 fprintf (dump_file, "Access to zero-sized part of variable,"
3286 "ignoring\n");
3288 else
3289 if (dump_file && (dump_flags & TDF_DETAILS))
3290 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3292 else if (result.type == DEREF)
3294 /* If we do not know exactly where the access goes say so. Note
3295 that only for non-structure accesses we know that we access
3296 at most one subfiled of any variable. */
3297 if (bitpos == -1
3298 || bitsize != bitmaxsize
3299 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3300 || result.offset == UNKNOWN_OFFSET)
3301 result.offset = UNKNOWN_OFFSET;
3302 else
3303 result.offset += bitpos;
3305 else if (result.type == ADDRESSOF)
3307 /* We can end up here for component references on a
3308 VIEW_CONVERT_EXPR <>(&foobar). */
3309 result.type = SCALAR;
3310 result.var = anything_id;
3311 result.offset = 0;
3313 else
3314 gcc_unreachable ();
3318 /* Dereference the constraint expression CONS, and return the result.
3319 DEREF (ADDRESSOF) = SCALAR
3320 DEREF (SCALAR) = DEREF
3321 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3322 This is needed so that we can handle dereferencing DEREF constraints. */
3324 static void
3325 do_deref (vec<ce_s> *constraints)
3327 struct constraint_expr *c;
3328 unsigned int i = 0;
3330 FOR_EACH_VEC_ELT (*constraints, i, c)
3332 if (c->type == SCALAR)
3333 c->type = DEREF;
3334 else if (c->type == ADDRESSOF)
3335 c->type = SCALAR;
3336 else if (c->type == DEREF)
3338 struct constraint_expr tmplhs;
3339 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3340 process_constraint (new_constraint (tmplhs, *c));
3341 c->var = tmplhs.var;
3343 else
3344 gcc_unreachable ();
3348 /* Given a tree T, return the constraint expression for taking the
3349 address of it. */
3351 static void
3352 get_constraint_for_address_of (tree t, vec<ce_s> *results)
3354 struct constraint_expr *c;
3355 unsigned int i;
3357 get_constraint_for_1 (t, results, true, true);
3359 FOR_EACH_VEC_ELT (*results, i, c)
3361 if (c->type == DEREF)
3362 c->type = SCALAR;
3363 else
3364 c->type = ADDRESSOF;
3368 /* Given a tree T, return the constraint expression for it. */
3370 static void
3371 get_constraint_for_1 (tree t, vec<ce_s> *results, bool address_p,
3372 bool lhs_p)
3374 struct constraint_expr temp;
3376 /* x = integer is all glommed to a single variable, which doesn't
3377 point to anything by itself. That is, of course, unless it is an
3378 integer constant being treated as a pointer, in which case, we
3379 will return that this is really the addressof anything. This
3380 happens below, since it will fall into the default case. The only
3381 case we know something about an integer treated like a pointer is
3382 when it is the NULL pointer, and then we just say it points to
3383 NULL.
3385 Do not do that if -fno-delete-null-pointer-checks though, because
3386 in that case *NULL does not fail, so it _should_ alias *anything.
3387 It is not worth adding a new option or renaming the existing one,
3388 since this case is relatively obscure. */
3389 if ((TREE_CODE (t) == INTEGER_CST
3390 && integer_zerop (t))
3391 /* The only valid CONSTRUCTORs in gimple with pointer typed
3392 elements are zero-initializer. But in IPA mode we also
3393 process global initializers, so verify at least. */
3394 || (TREE_CODE (t) == CONSTRUCTOR
3395 && CONSTRUCTOR_NELTS (t) == 0))
3397 if (flag_delete_null_pointer_checks)
3398 temp.var = nothing_id;
3399 else
3400 temp.var = nonlocal_id;
3401 temp.type = ADDRESSOF;
3402 temp.offset = 0;
3403 results->safe_push (temp);
3404 return;
3407 /* String constants are read-only, ideally we'd have a CONST_DECL
3408 for those. */
3409 if (TREE_CODE (t) == STRING_CST)
3411 temp.var = string_id;
3412 temp.type = SCALAR;
3413 temp.offset = 0;
3414 results->safe_push (temp);
3415 return;
3418 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3420 case tcc_expression:
3422 switch (TREE_CODE (t))
3424 case ADDR_EXPR:
3425 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3426 return;
3427 default:;
3429 break;
3431 case tcc_reference:
3433 switch (TREE_CODE (t))
3435 case MEM_REF:
3437 struct constraint_expr cs;
3438 varinfo_t vi, curr;
3439 get_constraint_for_ptr_offset (TREE_OPERAND (t, 0),
3440 TREE_OPERAND (t, 1), results);
3441 do_deref (results);
3443 /* If we are not taking the address then make sure to process
3444 all subvariables we might access. */
3445 if (address_p)
3446 return;
3448 cs = results->last ();
3449 if (cs.type == DEREF
3450 && type_can_have_subvars (TREE_TYPE (t)))
3452 /* For dereferences this means we have to defer it
3453 to solving time. */
3454 results->last ().offset = UNKNOWN_OFFSET;
3455 return;
3457 if (cs.type != SCALAR)
3458 return;
3460 vi = get_varinfo (cs.var);
3461 curr = vi_next (vi);
3462 if (!vi->is_full_var
3463 && curr)
3465 unsigned HOST_WIDE_INT size;
3466 if (tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (t))))
3467 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (t)));
3468 else
3469 size = -1;
3470 for (; curr; curr = vi_next (curr))
3472 if (curr->offset - vi->offset < size)
3474 cs.var = curr->id;
3475 results->safe_push (cs);
3477 else
3478 break;
3481 return;
3483 case ARRAY_REF:
3484 case ARRAY_RANGE_REF:
3485 case COMPONENT_REF:
3486 case IMAGPART_EXPR:
3487 case REALPART_EXPR:
3488 case BIT_FIELD_REF:
3489 get_constraint_for_component_ref (t, results, address_p, lhs_p);
3490 return;
3491 case VIEW_CONVERT_EXPR:
3492 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3493 lhs_p);
3494 return;
3495 /* We are missing handling for TARGET_MEM_REF here. */
3496 default:;
3498 break;
3500 case tcc_exceptional:
3502 switch (TREE_CODE (t))
3504 case SSA_NAME:
3506 get_constraint_for_ssa_var (t, results, address_p);
3507 return;
3509 case CONSTRUCTOR:
3511 unsigned int i;
3512 tree val;
3513 auto_vec<ce_s> tmp;
3514 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3516 struct constraint_expr *rhsp;
3517 unsigned j;
3518 get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3519 FOR_EACH_VEC_ELT (tmp, j, rhsp)
3520 results->safe_push (*rhsp);
3521 tmp.truncate (0);
3523 /* We do not know whether the constructor was complete,
3524 so technically we have to add &NOTHING or &ANYTHING
3525 like we do for an empty constructor as well. */
3526 return;
3528 default:;
3530 break;
3532 case tcc_declaration:
3534 get_constraint_for_ssa_var (t, results, address_p);
3535 return;
3537 case tcc_constant:
3539 /* We cannot refer to automatic variables through constants. */
3540 temp.type = ADDRESSOF;
3541 temp.var = nonlocal_id;
3542 temp.offset = 0;
3543 results->safe_push (temp);
3544 return;
3546 default:;
3549 /* The default fallback is a constraint from anything. */
3550 temp.type = ADDRESSOF;
3551 temp.var = anything_id;
3552 temp.offset = 0;
3553 results->safe_push (temp);
3556 /* Given a gimple tree T, return the constraint expression vector for it. */
3558 static void
3559 get_constraint_for (tree t, vec<ce_s> *results)
3561 gcc_assert (results->length () == 0);
3563 get_constraint_for_1 (t, results, false, true);
3566 /* Given a gimple tree T, return the constraint expression vector for it
3567 to be used as the rhs of a constraint. */
3569 static void
3570 get_constraint_for_rhs (tree t, vec<ce_s> *results)
3572 gcc_assert (results->length () == 0);
3574 get_constraint_for_1 (t, results, false, false);
3578 /* Efficiently generates constraints from all entries in *RHSC to all
3579 entries in *LHSC. */
3581 static void
3582 process_all_all_constraints (vec<ce_s> lhsc,
3583 vec<ce_s> rhsc)
3585 struct constraint_expr *lhsp, *rhsp;
3586 unsigned i, j;
3588 if (lhsc.length () <= 1 || rhsc.length () <= 1)
3590 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3591 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
3592 process_constraint (new_constraint (*lhsp, *rhsp));
3594 else
3596 struct constraint_expr tmp;
3597 tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3598 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
3599 process_constraint (new_constraint (tmp, *rhsp));
3600 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3601 process_constraint (new_constraint (*lhsp, tmp));
3605 /* Handle aggregate copies by expanding into copies of the respective
3606 fields of the structures. */
3608 static void
3609 do_structure_copy (tree lhsop, tree rhsop)
3611 struct constraint_expr *lhsp, *rhsp;
3612 auto_vec<ce_s> lhsc;
3613 auto_vec<ce_s> rhsc;
3614 unsigned j;
3616 get_constraint_for (lhsop, &lhsc);
3617 get_constraint_for_rhs (rhsop, &rhsc);
3618 lhsp = &lhsc[0];
3619 rhsp = &rhsc[0];
3620 if (lhsp->type == DEREF
3621 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3622 || rhsp->type == DEREF)
3624 if (lhsp->type == DEREF)
3626 gcc_assert (lhsc.length () == 1);
3627 lhsp->offset = UNKNOWN_OFFSET;
3629 if (rhsp->type == DEREF)
3631 gcc_assert (rhsc.length () == 1);
3632 rhsp->offset = UNKNOWN_OFFSET;
3634 process_all_all_constraints (lhsc, rhsc);
3636 else if (lhsp->type == SCALAR
3637 && (rhsp->type == SCALAR
3638 || rhsp->type == ADDRESSOF))
3640 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3641 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3642 unsigned k = 0;
3643 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3644 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3645 for (j = 0; lhsc.iterate (j, &lhsp);)
3647 varinfo_t lhsv, rhsv;
3648 rhsp = &rhsc[k];
3649 lhsv = get_varinfo (lhsp->var);
3650 rhsv = get_varinfo (rhsp->var);
3651 if (lhsv->may_have_pointers
3652 && (lhsv->is_full_var
3653 || rhsv->is_full_var
3654 || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3655 rhsv->offset + lhsoffset, rhsv->size)))
3656 process_constraint (new_constraint (*lhsp, *rhsp));
3657 if (!rhsv->is_full_var
3658 && (lhsv->is_full_var
3659 || (lhsv->offset + rhsoffset + lhsv->size
3660 > rhsv->offset + lhsoffset + rhsv->size)))
3662 ++k;
3663 if (k >= rhsc.length ())
3664 break;
3666 else
3667 ++j;
3670 else
3671 gcc_unreachable ();
3674 /* Create constraints ID = { rhsc }. */
3676 static void
3677 make_constraints_to (unsigned id, vec<ce_s> rhsc)
3679 struct constraint_expr *c;
3680 struct constraint_expr includes;
3681 unsigned int j;
3683 includes.var = id;
3684 includes.offset = 0;
3685 includes.type = SCALAR;
3687 FOR_EACH_VEC_ELT (rhsc, j, c)
3688 process_constraint (new_constraint (includes, *c));
3691 /* Create a constraint ID = OP. */
3693 static void
3694 make_constraint_to (unsigned id, tree op)
3696 auto_vec<ce_s> rhsc;
3697 get_constraint_for_rhs (op, &rhsc);
3698 make_constraints_to (id, rhsc);
3701 /* Create a constraint ID = &FROM. */
3703 static void
3704 make_constraint_from (varinfo_t vi, int from)
3706 struct constraint_expr lhs, rhs;
3708 lhs.var = vi->id;
3709 lhs.offset = 0;
3710 lhs.type = SCALAR;
3712 rhs.var = from;
3713 rhs.offset = 0;
3714 rhs.type = ADDRESSOF;
3715 process_constraint (new_constraint (lhs, rhs));
3718 /* Create a constraint ID = FROM. */
3720 static void
3721 make_copy_constraint (varinfo_t vi, int from)
3723 struct constraint_expr lhs, rhs;
3725 lhs.var = vi->id;
3726 lhs.offset = 0;
3727 lhs.type = SCALAR;
3729 rhs.var = from;
3730 rhs.offset = 0;
3731 rhs.type = SCALAR;
3732 process_constraint (new_constraint (lhs, rhs));
3735 /* Make constraints necessary to make OP escape. */
3737 static void
3738 make_escape_constraint (tree op)
3740 make_constraint_to (escaped_id, op);
3743 /* Add constraints to that the solution of VI is transitively closed. */
3745 static void
3746 make_transitive_closure_constraints (varinfo_t vi)
3748 struct constraint_expr lhs, rhs;
3750 /* VAR = *VAR; */
3751 lhs.type = SCALAR;
3752 lhs.var = vi->id;
3753 lhs.offset = 0;
3754 rhs.type = DEREF;
3755 rhs.var = vi->id;
3756 rhs.offset = UNKNOWN_OFFSET;
3757 process_constraint (new_constraint (lhs, rhs));
3760 /* Temporary storage for fake var decls. */
3761 struct obstack fake_var_decl_obstack;
3763 /* Build a fake VAR_DECL acting as referrer to a DECL_UID. */
3765 static tree
3766 build_fake_var_decl (tree type)
3768 tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3769 memset (decl, 0, sizeof (struct tree_var_decl));
3770 TREE_SET_CODE (decl, VAR_DECL);
3771 TREE_TYPE (decl) = type;
3772 DECL_UID (decl) = allocate_decl_uid ();
3773 SET_DECL_PT_UID (decl, -1);
3774 layout_decl (decl, 0);
3775 return decl;
3778 /* Create a new artificial heap variable with NAME.
3779 Return the created variable. */
3781 static varinfo_t
3782 make_heapvar (const char *name)
3784 varinfo_t vi;
3785 tree heapvar;
3787 heapvar = build_fake_var_decl (ptr_type_node);
3788 DECL_EXTERNAL (heapvar) = 1;
3790 vi = new_var_info (heapvar, name);
3791 vi->is_artificial_var = true;
3792 vi->is_heap_var = true;
3793 vi->is_unknown_size_var = true;
3794 vi->offset = 0;
3795 vi->fullsize = ~0;
3796 vi->size = ~0;
3797 vi->is_full_var = true;
3798 insert_vi_for_tree (heapvar, vi);
3800 return vi;
3803 /* Create a new artificial heap variable with NAME and make a
3804 constraint from it to LHS. Set flags according to a tag used
3805 for tracking restrict pointers. */
3807 static varinfo_t
3808 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3810 varinfo_t vi = make_heapvar (name);
3811 vi->is_restrict_var = 1;
3812 vi->is_global_var = 1;
3813 vi->may_have_pointers = 1;
3814 make_constraint_from (lhs, vi->id);
3815 return vi;
3818 /* Create a new artificial heap variable with NAME and make a
3819 constraint from it to LHS. Set flags according to a tag used
3820 for tracking restrict pointers and make the artificial heap
3821 point to global memory. */
3823 static varinfo_t
3824 make_constraint_from_global_restrict (varinfo_t lhs, const char *name)
3826 varinfo_t vi = make_constraint_from_restrict (lhs, name);
3827 make_copy_constraint (vi, nonlocal_id);
3828 return vi;
3831 /* In IPA mode there are varinfos for different aspects of reach
3832 function designator. One for the points-to set of the return
3833 value, one for the variables that are clobbered by the function,
3834 one for its uses and one for each parameter (including a single
3835 glob for remaining variadic arguments). */
3837 enum { fi_clobbers = 1, fi_uses = 2,
3838 fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3840 /* Get a constraint for the requested part of a function designator FI
3841 when operating in IPA mode. */
3843 static struct constraint_expr
3844 get_function_part_constraint (varinfo_t fi, unsigned part)
3846 struct constraint_expr c;
3848 gcc_assert (in_ipa_mode);
3850 if (fi->id == anything_id)
3852 /* ??? We probably should have a ANYFN special variable. */
3853 c.var = anything_id;
3854 c.offset = 0;
3855 c.type = SCALAR;
3857 else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3859 varinfo_t ai = first_vi_for_offset (fi, part);
3860 if (ai)
3861 c.var = ai->id;
3862 else
3863 c.var = anything_id;
3864 c.offset = 0;
3865 c.type = SCALAR;
3867 else
3869 c.var = fi->id;
3870 c.offset = part;
3871 c.type = DEREF;
3874 return c;
3877 /* For non-IPA mode, generate constraints necessary for a call on the
3878 RHS. */
3880 static void
3881 handle_rhs_call (gcall *stmt, vec<ce_s> *results)
3883 struct constraint_expr rhsc;
3884 unsigned i;
3885 bool returns_uses = false;
3887 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3889 tree arg = gimple_call_arg (stmt, i);
3890 int flags = gimple_call_arg_flags (stmt, i);
3892 /* If the argument is not used we can ignore it. */
3893 if (flags & EAF_UNUSED)
3894 continue;
3896 /* As we compute ESCAPED context-insensitive we do not gain
3897 any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3898 set. The argument would still get clobbered through the
3899 escape solution. */
3900 if ((flags & EAF_NOCLOBBER)
3901 && (flags & EAF_NOESCAPE))
3903 varinfo_t uses = get_call_use_vi (stmt);
3904 if (!(flags & EAF_DIRECT))
3906 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3907 make_constraint_to (tem->id, arg);
3908 make_transitive_closure_constraints (tem);
3909 make_copy_constraint (uses, tem->id);
3911 else
3912 make_constraint_to (uses->id, arg);
3913 returns_uses = true;
3915 else if (flags & EAF_NOESCAPE)
3917 struct constraint_expr lhs, rhs;
3918 varinfo_t uses = get_call_use_vi (stmt);
3919 varinfo_t clobbers = get_call_clobber_vi (stmt);
3920 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3921 make_constraint_to (tem->id, arg);
3922 if (!(flags & EAF_DIRECT))
3923 make_transitive_closure_constraints (tem);
3924 make_copy_constraint (uses, tem->id);
3925 make_copy_constraint (clobbers, tem->id);
3926 /* Add *tem = nonlocal, do not add *tem = callused as
3927 EAF_NOESCAPE parameters do not escape to other parameters
3928 and all other uses appear in NONLOCAL as well. */
3929 lhs.type = DEREF;
3930 lhs.var = tem->id;
3931 lhs.offset = 0;
3932 rhs.type = SCALAR;
3933 rhs.var = nonlocal_id;
3934 rhs.offset = 0;
3935 process_constraint (new_constraint (lhs, rhs));
3936 returns_uses = true;
3938 else
3939 make_escape_constraint (arg);
3942 /* If we added to the calls uses solution make sure we account for
3943 pointers to it to be returned. */
3944 if (returns_uses)
3946 rhsc.var = get_call_use_vi (stmt)->id;
3947 rhsc.offset = 0;
3948 rhsc.type = SCALAR;
3949 results->safe_push (rhsc);
3952 /* The static chain escapes as well. */
3953 if (gimple_call_chain (stmt))
3954 make_escape_constraint (gimple_call_chain (stmt));
3956 /* And if we applied NRV the address of the return slot escapes as well. */
3957 if (gimple_call_return_slot_opt_p (stmt)
3958 && gimple_call_lhs (stmt) != NULL_TREE
3959 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3961 auto_vec<ce_s> tmpc;
3962 struct constraint_expr lhsc, *c;
3963 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3964 lhsc.var = escaped_id;
3965 lhsc.offset = 0;
3966 lhsc.type = SCALAR;
3967 FOR_EACH_VEC_ELT (tmpc, i, c)
3968 process_constraint (new_constraint (lhsc, *c));
3971 /* Regular functions return nonlocal memory. */
3972 rhsc.var = nonlocal_id;
3973 rhsc.offset = 0;
3974 rhsc.type = SCALAR;
3975 results->safe_push (rhsc);
3978 /* For non-IPA mode, generate constraints necessary for a call
3979 that returns a pointer and assigns it to LHS. This simply makes
3980 the LHS point to global and escaped variables. */
3982 static void
3983 handle_lhs_call (gcall *stmt, tree lhs, int flags, vec<ce_s> rhsc,
3984 tree fndecl)
3986 auto_vec<ce_s> lhsc;
3988 get_constraint_for (lhs, &lhsc);
3989 /* If the store is to a global decl make sure to
3990 add proper escape constraints. */
3991 lhs = get_base_address (lhs);
3992 if (lhs
3993 && DECL_P (lhs)
3994 && is_global_var (lhs))
3996 struct constraint_expr tmpc;
3997 tmpc.var = escaped_id;
3998 tmpc.offset = 0;
3999 tmpc.type = SCALAR;
4000 lhsc.safe_push (tmpc);
4003 /* If the call returns an argument unmodified override the rhs
4004 constraints. */
4005 if (flags & ERF_RETURNS_ARG
4006 && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
4008 tree arg;
4009 rhsc.create (0);
4010 arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
4011 get_constraint_for (arg, &rhsc);
4012 process_all_all_constraints (lhsc, rhsc);
4013 rhsc.release ();
4015 else if (flags & ERF_NOALIAS)
4017 varinfo_t vi;
4018 struct constraint_expr tmpc;
4019 rhsc.create (0);
4020 vi = make_heapvar ("HEAP");
4021 /* We are marking allocated storage local, we deal with it becoming
4022 global by escaping and setting of vars_contains_escaped_heap. */
4023 DECL_EXTERNAL (vi->decl) = 0;
4024 vi->is_global_var = 0;
4025 /* If this is not a real malloc call assume the memory was
4026 initialized and thus may point to global memory. All
4027 builtin functions with the malloc attribute behave in a sane way. */
4028 if (!fndecl
4029 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
4030 make_constraint_from (vi, nonlocal_id);
4031 tmpc.var = vi->id;
4032 tmpc.offset = 0;
4033 tmpc.type = ADDRESSOF;
4034 rhsc.safe_push (tmpc);
4035 process_all_all_constraints (lhsc, rhsc);
4036 rhsc.release ();
4038 else
4039 process_all_all_constraints (lhsc, rhsc);
4042 /* For non-IPA mode, generate constraints necessary for a call of a
4043 const function that returns a pointer in the statement STMT. */
4045 static void
4046 handle_const_call (gcall *stmt, vec<ce_s> *results)
4048 struct constraint_expr rhsc;
4049 unsigned int k;
4051 /* Treat nested const functions the same as pure functions as far
4052 as the static chain is concerned. */
4053 if (gimple_call_chain (stmt))
4055 varinfo_t uses = get_call_use_vi (stmt);
4056 make_transitive_closure_constraints (uses);
4057 make_constraint_to (uses->id, gimple_call_chain (stmt));
4058 rhsc.var = uses->id;
4059 rhsc.offset = 0;
4060 rhsc.type = SCALAR;
4061 results->safe_push (rhsc);
4064 /* May return arguments. */
4065 for (k = 0; k < gimple_call_num_args (stmt); ++k)
4067 tree arg = gimple_call_arg (stmt, k);
4068 auto_vec<ce_s> argc;
4069 unsigned i;
4070 struct constraint_expr *argp;
4071 get_constraint_for_rhs (arg, &argc);
4072 FOR_EACH_VEC_ELT (argc, i, argp)
4073 results->safe_push (*argp);
4076 /* May return addresses of globals. */
4077 rhsc.var = nonlocal_id;
4078 rhsc.offset = 0;
4079 rhsc.type = ADDRESSOF;
4080 results->safe_push (rhsc);
4083 /* For non-IPA mode, generate constraints necessary for a call to a
4084 pure function in statement STMT. */
4086 static void
4087 handle_pure_call (gcall *stmt, vec<ce_s> *results)
4089 struct constraint_expr rhsc;
4090 unsigned i;
4091 varinfo_t uses = NULL;
4093 /* Memory reached from pointer arguments is call-used. */
4094 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4096 tree arg = gimple_call_arg (stmt, i);
4097 if (!uses)
4099 uses = get_call_use_vi (stmt);
4100 make_transitive_closure_constraints (uses);
4102 make_constraint_to (uses->id, arg);
4105 /* The static chain is used as well. */
4106 if (gimple_call_chain (stmt))
4108 if (!uses)
4110 uses = get_call_use_vi (stmt);
4111 make_transitive_closure_constraints (uses);
4113 make_constraint_to (uses->id, gimple_call_chain (stmt));
4116 /* Pure functions may return call-used and nonlocal memory. */
4117 if (uses)
4119 rhsc.var = uses->id;
4120 rhsc.offset = 0;
4121 rhsc.type = SCALAR;
4122 results->safe_push (rhsc);
4124 rhsc.var = nonlocal_id;
4125 rhsc.offset = 0;
4126 rhsc.type = SCALAR;
4127 results->safe_push (rhsc);
4131 /* Return the varinfo for the callee of CALL. */
4133 static varinfo_t
4134 get_fi_for_callee (gcall *call)
4136 tree decl, fn = gimple_call_fn (call);
4138 if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
4139 fn = OBJ_TYPE_REF_EXPR (fn);
4141 /* If we can directly resolve the function being called, do so.
4142 Otherwise, it must be some sort of indirect expression that
4143 we should still be able to handle. */
4144 decl = gimple_call_addr_fndecl (fn);
4145 if (decl)
4146 return get_vi_for_tree (decl);
4148 /* If the function is anything other than a SSA name pointer we have no
4149 clue and should be getting ANYFN (well, ANYTHING for now). */
4150 if (!fn || TREE_CODE (fn) != SSA_NAME)
4151 return get_varinfo (anything_id);
4153 if (SSA_NAME_IS_DEFAULT_DEF (fn)
4154 && (TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
4155 || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL))
4156 fn = SSA_NAME_VAR (fn);
4158 return get_vi_for_tree (fn);
4161 /* Create constraints for the builtin call T. Return true if the call
4162 was handled, otherwise false. */
4164 static bool
4165 find_func_aliases_for_builtin_call (struct function *fn, gcall *t)
4167 tree fndecl = gimple_call_fndecl (t);
4168 auto_vec<ce_s, 2> lhsc;
4169 auto_vec<ce_s, 4> rhsc;
4170 varinfo_t fi;
4172 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4173 /* ??? All builtins that are handled here need to be handled
4174 in the alias-oracle query functions explicitly! */
4175 switch (DECL_FUNCTION_CODE (fndecl))
4177 /* All the following functions return a pointer to the same object
4178 as their first argument points to. The functions do not add
4179 to the ESCAPED solution. The functions make the first argument
4180 pointed to memory point to what the second argument pointed to
4181 memory points to. */
4182 case BUILT_IN_STRCPY:
4183 case BUILT_IN_STRNCPY:
4184 case BUILT_IN_BCOPY:
4185 case BUILT_IN_MEMCPY:
4186 case BUILT_IN_MEMMOVE:
4187 case BUILT_IN_MEMPCPY:
4188 case BUILT_IN_STPCPY:
4189 case BUILT_IN_STPNCPY:
4190 case BUILT_IN_STRCAT:
4191 case BUILT_IN_STRNCAT:
4192 case BUILT_IN_STRCPY_CHK:
4193 case BUILT_IN_STRNCPY_CHK:
4194 case BUILT_IN_MEMCPY_CHK:
4195 case BUILT_IN_MEMMOVE_CHK:
4196 case BUILT_IN_MEMPCPY_CHK:
4197 case BUILT_IN_STPCPY_CHK:
4198 case BUILT_IN_STPNCPY_CHK:
4199 case BUILT_IN_STRCAT_CHK:
4200 case BUILT_IN_STRNCAT_CHK:
4201 case BUILT_IN_TM_MEMCPY:
4202 case BUILT_IN_TM_MEMMOVE:
4204 tree res = gimple_call_lhs (t);
4205 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4206 == BUILT_IN_BCOPY ? 1 : 0));
4207 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4208 == BUILT_IN_BCOPY ? 0 : 1));
4209 if (res != NULL_TREE)
4211 get_constraint_for (res, &lhsc);
4212 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4213 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4214 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4215 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4216 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK
4217 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY_CHK)
4218 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4219 else
4220 get_constraint_for (dest, &rhsc);
4221 process_all_all_constraints (lhsc, rhsc);
4222 lhsc.truncate (0);
4223 rhsc.truncate (0);
4225 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4226 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4227 do_deref (&lhsc);
4228 do_deref (&rhsc);
4229 process_all_all_constraints (lhsc, rhsc);
4230 return true;
4232 case BUILT_IN_MEMSET:
4233 case BUILT_IN_MEMSET_CHK:
4234 case BUILT_IN_TM_MEMSET:
4236 tree res = gimple_call_lhs (t);
4237 tree dest = gimple_call_arg (t, 0);
4238 unsigned i;
4239 ce_s *lhsp;
4240 struct constraint_expr ac;
4241 if (res != NULL_TREE)
4243 get_constraint_for (res, &lhsc);
4244 get_constraint_for (dest, &rhsc);
4245 process_all_all_constraints (lhsc, rhsc);
4246 lhsc.truncate (0);
4248 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4249 do_deref (&lhsc);
4250 if (flag_delete_null_pointer_checks
4251 && integer_zerop (gimple_call_arg (t, 1)))
4253 ac.type = ADDRESSOF;
4254 ac.var = nothing_id;
4256 else
4258 ac.type = SCALAR;
4259 ac.var = integer_id;
4261 ac.offset = 0;
4262 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4263 process_constraint (new_constraint (*lhsp, ac));
4264 return true;
4266 case BUILT_IN_POSIX_MEMALIGN:
4268 tree ptrptr = gimple_call_arg (t, 0);
4269 get_constraint_for (ptrptr, &lhsc);
4270 do_deref (&lhsc);
4271 varinfo_t vi = make_heapvar ("HEAP");
4272 /* We are marking allocated storage local, we deal with it becoming
4273 global by escaping and setting of vars_contains_escaped_heap. */
4274 DECL_EXTERNAL (vi->decl) = 0;
4275 vi->is_global_var = 0;
4276 struct constraint_expr tmpc;
4277 tmpc.var = vi->id;
4278 tmpc.offset = 0;
4279 tmpc.type = ADDRESSOF;
4280 rhsc.safe_push (tmpc);
4281 process_all_all_constraints (lhsc, rhsc);
4282 return true;
4284 case BUILT_IN_ASSUME_ALIGNED:
4286 tree res = gimple_call_lhs (t);
4287 tree dest = gimple_call_arg (t, 0);
4288 if (res != NULL_TREE)
4290 get_constraint_for (res, &lhsc);
4291 get_constraint_for (dest, &rhsc);
4292 process_all_all_constraints (lhsc, rhsc);
4294 return true;
4296 /* All the following functions do not return pointers, do not
4297 modify the points-to sets of memory reachable from their
4298 arguments and do not add to the ESCAPED solution. */
4299 case BUILT_IN_SINCOS:
4300 case BUILT_IN_SINCOSF:
4301 case BUILT_IN_SINCOSL:
4302 case BUILT_IN_FREXP:
4303 case BUILT_IN_FREXPF:
4304 case BUILT_IN_FREXPL:
4305 case BUILT_IN_GAMMA_R:
4306 case BUILT_IN_GAMMAF_R:
4307 case BUILT_IN_GAMMAL_R:
4308 case BUILT_IN_LGAMMA_R:
4309 case BUILT_IN_LGAMMAF_R:
4310 case BUILT_IN_LGAMMAL_R:
4311 case BUILT_IN_MODF:
4312 case BUILT_IN_MODFF:
4313 case BUILT_IN_MODFL:
4314 case BUILT_IN_REMQUO:
4315 case BUILT_IN_REMQUOF:
4316 case BUILT_IN_REMQUOL:
4317 case BUILT_IN_FREE:
4318 return true;
4319 case BUILT_IN_STRDUP:
4320 case BUILT_IN_STRNDUP:
4321 case BUILT_IN_REALLOC:
4322 if (gimple_call_lhs (t))
4324 handle_lhs_call (t, gimple_call_lhs (t),
4325 gimple_call_return_flags (t) | ERF_NOALIAS,
4326 vNULL, fndecl);
4327 get_constraint_for_ptr_offset (gimple_call_lhs (t),
4328 NULL_TREE, &lhsc);
4329 get_constraint_for_ptr_offset (gimple_call_arg (t, 0),
4330 NULL_TREE, &rhsc);
4331 do_deref (&lhsc);
4332 do_deref (&rhsc);
4333 process_all_all_constraints (lhsc, rhsc);
4334 lhsc.truncate (0);
4335 rhsc.truncate (0);
4336 /* For realloc the resulting pointer can be equal to the
4337 argument as well. But only doing this wouldn't be
4338 correct because with ptr == 0 realloc behaves like malloc. */
4339 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_REALLOC)
4341 get_constraint_for (gimple_call_lhs (t), &lhsc);
4342 get_constraint_for (gimple_call_arg (t, 0), &rhsc);
4343 process_all_all_constraints (lhsc, rhsc);
4345 return true;
4347 break;
4348 /* String / character search functions return a pointer into the
4349 source string or NULL. */
4350 case BUILT_IN_INDEX:
4351 case BUILT_IN_STRCHR:
4352 case BUILT_IN_STRRCHR:
4353 case BUILT_IN_MEMCHR:
4354 case BUILT_IN_STRSTR:
4355 case BUILT_IN_STRPBRK:
4356 if (gimple_call_lhs (t))
4358 tree src = gimple_call_arg (t, 0);
4359 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4360 constraint_expr nul;
4361 nul.var = nothing_id;
4362 nul.offset = 0;
4363 nul.type = ADDRESSOF;
4364 rhsc.safe_push (nul);
4365 get_constraint_for (gimple_call_lhs (t), &lhsc);
4366 process_all_all_constraints (lhsc, rhsc);
4368 return true;
4369 /* Trampolines are special - they set up passing the static
4370 frame. */
4371 case BUILT_IN_INIT_TRAMPOLINE:
4373 tree tramp = gimple_call_arg (t, 0);
4374 tree nfunc = gimple_call_arg (t, 1);
4375 tree frame = gimple_call_arg (t, 2);
4376 unsigned i;
4377 struct constraint_expr lhs, *rhsp;
4378 if (in_ipa_mode)
4380 varinfo_t nfi = NULL;
4381 gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4382 nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4383 if (nfi)
4385 lhs = get_function_part_constraint (nfi, fi_static_chain);
4386 get_constraint_for (frame, &rhsc);
4387 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4388 process_constraint (new_constraint (lhs, *rhsp));
4389 rhsc.truncate (0);
4391 /* Make the frame point to the function for
4392 the trampoline adjustment call. */
4393 get_constraint_for (tramp, &lhsc);
4394 do_deref (&lhsc);
4395 get_constraint_for (nfunc, &rhsc);
4396 process_all_all_constraints (lhsc, rhsc);
4398 return true;
4401 /* Else fallthru to generic handling which will let
4402 the frame escape. */
4403 break;
4405 case BUILT_IN_ADJUST_TRAMPOLINE:
4407 tree tramp = gimple_call_arg (t, 0);
4408 tree res = gimple_call_lhs (t);
4409 if (in_ipa_mode && res)
4411 get_constraint_for (res, &lhsc);
4412 get_constraint_for (tramp, &rhsc);
4413 do_deref (&rhsc);
4414 process_all_all_constraints (lhsc, rhsc);
4416 return true;
4418 CASE_BUILT_IN_TM_STORE (1):
4419 CASE_BUILT_IN_TM_STORE (2):
4420 CASE_BUILT_IN_TM_STORE (4):
4421 CASE_BUILT_IN_TM_STORE (8):
4422 CASE_BUILT_IN_TM_STORE (FLOAT):
4423 CASE_BUILT_IN_TM_STORE (DOUBLE):
4424 CASE_BUILT_IN_TM_STORE (LDOUBLE):
4425 CASE_BUILT_IN_TM_STORE (M64):
4426 CASE_BUILT_IN_TM_STORE (M128):
4427 CASE_BUILT_IN_TM_STORE (M256):
4429 tree addr = gimple_call_arg (t, 0);
4430 tree src = gimple_call_arg (t, 1);
4432 get_constraint_for (addr, &lhsc);
4433 do_deref (&lhsc);
4434 get_constraint_for (src, &rhsc);
4435 process_all_all_constraints (lhsc, rhsc);
4436 return true;
4438 CASE_BUILT_IN_TM_LOAD (1):
4439 CASE_BUILT_IN_TM_LOAD (2):
4440 CASE_BUILT_IN_TM_LOAD (4):
4441 CASE_BUILT_IN_TM_LOAD (8):
4442 CASE_BUILT_IN_TM_LOAD (FLOAT):
4443 CASE_BUILT_IN_TM_LOAD (DOUBLE):
4444 CASE_BUILT_IN_TM_LOAD (LDOUBLE):
4445 CASE_BUILT_IN_TM_LOAD (M64):
4446 CASE_BUILT_IN_TM_LOAD (M128):
4447 CASE_BUILT_IN_TM_LOAD (M256):
4449 tree dest = gimple_call_lhs (t);
4450 tree addr = gimple_call_arg (t, 0);
4452 get_constraint_for (dest, &lhsc);
4453 get_constraint_for (addr, &rhsc);
4454 do_deref (&rhsc);
4455 process_all_all_constraints (lhsc, rhsc);
4456 return true;
4458 /* Variadic argument handling needs to be handled in IPA
4459 mode as well. */
4460 case BUILT_IN_VA_START:
4462 tree valist = gimple_call_arg (t, 0);
4463 struct constraint_expr rhs, *lhsp;
4464 unsigned i;
4465 get_constraint_for (valist, &lhsc);
4466 do_deref (&lhsc);
4467 /* The va_list gets access to pointers in variadic
4468 arguments. Which we know in the case of IPA analysis
4469 and otherwise are just all nonlocal variables. */
4470 if (in_ipa_mode)
4472 fi = lookup_vi_for_tree (fn->decl);
4473 rhs = get_function_part_constraint (fi, ~0);
4474 rhs.type = ADDRESSOF;
4476 else
4478 rhs.var = nonlocal_id;
4479 rhs.type = ADDRESSOF;
4480 rhs.offset = 0;
4482 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4483 process_constraint (new_constraint (*lhsp, rhs));
4484 /* va_list is clobbered. */
4485 make_constraint_to (get_call_clobber_vi (t)->id, valist);
4486 return true;
4488 /* va_end doesn't have any effect that matters. */
4489 case BUILT_IN_VA_END:
4490 return true;
4491 /* Alternate return. Simply give up for now. */
4492 case BUILT_IN_RETURN:
4494 fi = NULL;
4495 if (!in_ipa_mode
4496 || !(fi = get_vi_for_tree (fn->decl)))
4497 make_constraint_from (get_varinfo (escaped_id), anything_id);
4498 else if (in_ipa_mode
4499 && fi != NULL)
4501 struct constraint_expr lhs, rhs;
4502 lhs = get_function_part_constraint (fi, fi_result);
4503 rhs.var = anything_id;
4504 rhs.offset = 0;
4505 rhs.type = SCALAR;
4506 process_constraint (new_constraint (lhs, rhs));
4508 return true;
4510 /* printf-style functions may have hooks to set pointers to
4511 point to somewhere into the generated string. Leave them
4512 for a later exercise... */
4513 default:
4514 /* Fallthru to general call handling. */;
4517 return false;
4520 /* Create constraints for the call T. */
4522 static void
4523 find_func_aliases_for_call (struct function *fn, gcall *t)
4525 tree fndecl = gimple_call_fndecl (t);
4526 varinfo_t fi;
4528 if (fndecl != NULL_TREE
4529 && DECL_BUILT_IN (fndecl)
4530 && find_func_aliases_for_builtin_call (fn, t))
4531 return;
4533 fi = get_fi_for_callee (t);
4534 if (!in_ipa_mode
4535 || (fndecl && !fi->is_fn_info))
4537 auto_vec<ce_s, 16> rhsc;
4538 int flags = gimple_call_flags (t);
4540 /* Const functions can return their arguments and addresses
4541 of global memory but not of escaped memory. */
4542 if (flags & (ECF_CONST|ECF_NOVOPS))
4544 if (gimple_call_lhs (t))
4545 handle_const_call (t, &rhsc);
4547 /* Pure functions can return addresses in and of memory
4548 reachable from their arguments, but they are not an escape
4549 point for reachable memory of their arguments. */
4550 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4551 handle_pure_call (t, &rhsc);
4552 else
4553 handle_rhs_call (t, &rhsc);
4554 if (gimple_call_lhs (t))
4555 handle_lhs_call (t, gimple_call_lhs (t),
4556 gimple_call_return_flags (t), rhsc, fndecl);
4558 else
4560 auto_vec<ce_s, 2> rhsc;
4561 tree lhsop;
4562 unsigned j;
4564 /* Assign all the passed arguments to the appropriate incoming
4565 parameters of the function. */
4566 for (j = 0; j < gimple_call_num_args (t); j++)
4568 struct constraint_expr lhs ;
4569 struct constraint_expr *rhsp;
4570 tree arg = gimple_call_arg (t, j);
4572 get_constraint_for_rhs (arg, &rhsc);
4573 lhs = get_function_part_constraint (fi, fi_parm_base + j);
4574 while (rhsc.length () != 0)
4576 rhsp = &rhsc.last ();
4577 process_constraint (new_constraint (lhs, *rhsp));
4578 rhsc.pop ();
4582 /* If we are returning a value, assign it to the result. */
4583 lhsop = gimple_call_lhs (t);
4584 if (lhsop)
4586 auto_vec<ce_s, 2> lhsc;
4587 struct constraint_expr rhs;
4588 struct constraint_expr *lhsp;
4590 get_constraint_for (lhsop, &lhsc);
4591 rhs = get_function_part_constraint (fi, fi_result);
4592 if (fndecl
4593 && DECL_RESULT (fndecl)
4594 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4596 auto_vec<ce_s, 2> tem;
4597 tem.quick_push (rhs);
4598 do_deref (&tem);
4599 gcc_checking_assert (tem.length () == 1);
4600 rhs = tem[0];
4602 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4603 process_constraint (new_constraint (*lhsp, rhs));
4606 /* If we pass the result decl by reference, honor that. */
4607 if (lhsop
4608 && fndecl
4609 && DECL_RESULT (fndecl)
4610 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4612 struct constraint_expr lhs;
4613 struct constraint_expr *rhsp;
4615 get_constraint_for_address_of (lhsop, &rhsc);
4616 lhs = get_function_part_constraint (fi, fi_result);
4617 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4618 process_constraint (new_constraint (lhs, *rhsp));
4619 rhsc.truncate (0);
4622 /* If we use a static chain, pass it along. */
4623 if (gimple_call_chain (t))
4625 struct constraint_expr lhs;
4626 struct constraint_expr *rhsp;
4628 get_constraint_for (gimple_call_chain (t), &rhsc);
4629 lhs = get_function_part_constraint (fi, fi_static_chain);
4630 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4631 process_constraint (new_constraint (lhs, *rhsp));
4636 /* Walk statement T setting up aliasing constraints according to the
4637 references found in T. This function is the main part of the
4638 constraint builder. AI points to auxiliary alias information used
4639 when building alias sets and computing alias grouping heuristics. */
4641 static void
4642 find_func_aliases (struct function *fn, gimple origt)
4644 gimple t = origt;
4645 auto_vec<ce_s, 16> lhsc;
4646 auto_vec<ce_s, 16> rhsc;
4647 struct constraint_expr *c;
4648 varinfo_t fi;
4650 /* Now build constraints expressions. */
4651 if (gimple_code (t) == GIMPLE_PHI)
4653 size_t i;
4654 unsigned int j;
4656 /* For a phi node, assign all the arguments to
4657 the result. */
4658 get_constraint_for (gimple_phi_result (t), &lhsc);
4659 for (i = 0; i < gimple_phi_num_args (t); i++)
4661 tree strippedrhs = PHI_ARG_DEF (t, i);
4663 STRIP_NOPS (strippedrhs);
4664 get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4666 FOR_EACH_VEC_ELT (lhsc, j, c)
4668 struct constraint_expr *c2;
4669 while (rhsc.length () > 0)
4671 c2 = &rhsc.last ();
4672 process_constraint (new_constraint (*c, *c2));
4673 rhsc.pop ();
4678 /* In IPA mode, we need to generate constraints to pass call
4679 arguments through their calls. There are two cases,
4680 either a GIMPLE_CALL returning a value, or just a plain
4681 GIMPLE_CALL when we are not.
4683 In non-ipa mode, we need to generate constraints for each
4684 pointer passed by address. */
4685 else if (is_gimple_call (t))
4686 find_func_aliases_for_call (fn, as_a <gcall *> (t));
4688 /* Otherwise, just a regular assignment statement. Only care about
4689 operations with pointer result, others are dealt with as escape
4690 points if they have pointer operands. */
4691 else if (is_gimple_assign (t))
4693 /* Otherwise, just a regular assignment statement. */
4694 tree lhsop = gimple_assign_lhs (t);
4695 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4697 if (rhsop && TREE_CLOBBER_P (rhsop))
4698 /* Ignore clobbers, they don't actually store anything into
4699 the LHS. */
4701 else if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4702 do_structure_copy (lhsop, rhsop);
4703 else
4705 enum tree_code code = gimple_assign_rhs_code (t);
4707 get_constraint_for (lhsop, &lhsc);
4709 if (code == POINTER_PLUS_EXPR)
4710 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4711 gimple_assign_rhs2 (t), &rhsc);
4712 else if (code == BIT_AND_EXPR
4713 && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4715 /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4716 the pointer. Handle it by offsetting it by UNKNOWN. */
4717 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4718 NULL_TREE, &rhsc);
4720 else if ((CONVERT_EXPR_CODE_P (code)
4721 && !(POINTER_TYPE_P (gimple_expr_type (t))
4722 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4723 || gimple_assign_single_p (t))
4724 get_constraint_for_rhs (rhsop, &rhsc);
4725 else if (code == COND_EXPR)
4727 /* The result is a merge of both COND_EXPR arms. */
4728 auto_vec<ce_s, 2> tmp;
4729 struct constraint_expr *rhsp;
4730 unsigned i;
4731 get_constraint_for_rhs (gimple_assign_rhs2 (t), &rhsc);
4732 get_constraint_for_rhs (gimple_assign_rhs3 (t), &tmp);
4733 FOR_EACH_VEC_ELT (tmp, i, rhsp)
4734 rhsc.safe_push (*rhsp);
4736 else if (truth_value_p (code))
4737 /* Truth value results are not pointer (parts). Or at least
4738 very very unreasonable obfuscation of a part. */
4740 else
4742 /* All other operations are merges. */
4743 auto_vec<ce_s, 4> tmp;
4744 struct constraint_expr *rhsp;
4745 unsigned i, j;
4746 get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4747 for (i = 2; i < gimple_num_ops (t); ++i)
4749 get_constraint_for_rhs (gimple_op (t, i), &tmp);
4750 FOR_EACH_VEC_ELT (tmp, j, rhsp)
4751 rhsc.safe_push (*rhsp);
4752 tmp.truncate (0);
4755 process_all_all_constraints (lhsc, rhsc);
4757 /* If there is a store to a global variable the rhs escapes. */
4758 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4759 && DECL_P (lhsop)
4760 && is_global_var (lhsop)
4761 && (!in_ipa_mode
4762 || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4763 make_escape_constraint (rhsop);
4765 /* Handle escapes through return. */
4766 else if (gimple_code (t) == GIMPLE_RETURN
4767 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE)
4769 greturn *return_stmt = as_a <greturn *> (t);
4770 fi = NULL;
4771 if (!in_ipa_mode
4772 || !(fi = get_vi_for_tree (fn->decl)))
4773 make_escape_constraint (gimple_return_retval (return_stmt));
4774 else if (in_ipa_mode
4775 && fi != NULL)
4777 struct constraint_expr lhs ;
4778 struct constraint_expr *rhsp;
4779 unsigned i;
4781 lhs = get_function_part_constraint (fi, fi_result);
4782 get_constraint_for_rhs (gimple_return_retval (return_stmt), &rhsc);
4783 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4784 process_constraint (new_constraint (lhs, *rhsp));
4787 /* Handle asms conservatively by adding escape constraints to everything. */
4788 else if (gasm *asm_stmt = dyn_cast <gasm *> (t))
4790 unsigned i, noutputs;
4791 const char **oconstraints;
4792 const char *constraint;
4793 bool allows_mem, allows_reg, is_inout;
4795 noutputs = gimple_asm_noutputs (asm_stmt);
4796 oconstraints = XALLOCAVEC (const char *, noutputs);
4798 for (i = 0; i < noutputs; ++i)
4800 tree link = gimple_asm_output_op (asm_stmt, i);
4801 tree op = TREE_VALUE (link);
4803 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4804 oconstraints[i] = constraint;
4805 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4806 &allows_reg, &is_inout);
4808 /* A memory constraint makes the address of the operand escape. */
4809 if (!allows_reg && allows_mem)
4810 make_escape_constraint (build_fold_addr_expr (op));
4812 /* The asm may read global memory, so outputs may point to
4813 any global memory. */
4814 if (op)
4816 auto_vec<ce_s, 2> lhsc;
4817 struct constraint_expr rhsc, *lhsp;
4818 unsigned j;
4819 get_constraint_for (op, &lhsc);
4820 rhsc.var = nonlocal_id;
4821 rhsc.offset = 0;
4822 rhsc.type = SCALAR;
4823 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4824 process_constraint (new_constraint (*lhsp, rhsc));
4827 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4829 tree link = gimple_asm_input_op (asm_stmt, i);
4830 tree op = TREE_VALUE (link);
4832 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4834 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4835 &allows_mem, &allows_reg);
4837 /* A memory constraint makes the address of the operand escape. */
4838 if (!allows_reg && allows_mem)
4839 make_escape_constraint (build_fold_addr_expr (op));
4840 /* Strictly we'd only need the constraint to ESCAPED if
4841 the asm clobbers memory, otherwise using something
4842 along the lines of per-call clobbers/uses would be enough. */
4843 else if (op)
4844 make_escape_constraint (op);
4850 /* Create a constraint adding to the clobber set of FI the memory
4851 pointed to by PTR. */
4853 static void
4854 process_ipa_clobber (varinfo_t fi, tree ptr)
4856 vec<ce_s> ptrc = vNULL;
4857 struct constraint_expr *c, lhs;
4858 unsigned i;
4859 get_constraint_for_rhs (ptr, &ptrc);
4860 lhs = get_function_part_constraint (fi, fi_clobbers);
4861 FOR_EACH_VEC_ELT (ptrc, i, c)
4862 process_constraint (new_constraint (lhs, *c));
4863 ptrc.release ();
4866 /* Walk statement T setting up clobber and use constraints according to the
4867 references found in T. This function is a main part of the
4868 IPA constraint builder. */
4870 static void
4871 find_func_clobbers (struct function *fn, gimple origt)
4873 gimple t = origt;
4874 auto_vec<ce_s, 16> lhsc;
4875 auto_vec<ce_s, 16> rhsc;
4876 varinfo_t fi;
4878 /* Add constraints for clobbered/used in IPA mode.
4879 We are not interested in what automatic variables are clobbered
4880 or used as we only use the information in the caller to which
4881 they do not escape. */
4882 gcc_assert (in_ipa_mode);
4884 /* If the stmt refers to memory in any way it better had a VUSE. */
4885 if (gimple_vuse (t) == NULL_TREE)
4886 return;
4888 /* We'd better have function information for the current function. */
4889 fi = lookup_vi_for_tree (fn->decl);
4890 gcc_assert (fi != NULL);
4892 /* Account for stores in assignments and calls. */
4893 if (gimple_vdef (t) != NULL_TREE
4894 && gimple_has_lhs (t))
4896 tree lhs = gimple_get_lhs (t);
4897 tree tem = lhs;
4898 while (handled_component_p (tem))
4899 tem = TREE_OPERAND (tem, 0);
4900 if ((DECL_P (tem)
4901 && !auto_var_in_fn_p (tem, fn->decl))
4902 || INDIRECT_REF_P (tem)
4903 || (TREE_CODE (tem) == MEM_REF
4904 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4905 && auto_var_in_fn_p
4906 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4908 struct constraint_expr lhsc, *rhsp;
4909 unsigned i;
4910 lhsc = get_function_part_constraint (fi, fi_clobbers);
4911 get_constraint_for_address_of (lhs, &rhsc);
4912 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4913 process_constraint (new_constraint (lhsc, *rhsp));
4914 rhsc.truncate (0);
4918 /* Account for uses in assigments and returns. */
4919 if (gimple_assign_single_p (t)
4920 || (gimple_code (t) == GIMPLE_RETURN
4921 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE))
4923 tree rhs = (gimple_assign_single_p (t)
4924 ? gimple_assign_rhs1 (t)
4925 : gimple_return_retval (as_a <greturn *> (t)));
4926 tree tem = rhs;
4927 while (handled_component_p (tem))
4928 tem = TREE_OPERAND (tem, 0);
4929 if ((DECL_P (tem)
4930 && !auto_var_in_fn_p (tem, fn->decl))
4931 || INDIRECT_REF_P (tem)
4932 || (TREE_CODE (tem) == MEM_REF
4933 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4934 && auto_var_in_fn_p
4935 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4937 struct constraint_expr lhs, *rhsp;
4938 unsigned i;
4939 lhs = get_function_part_constraint (fi, fi_uses);
4940 get_constraint_for_address_of (rhs, &rhsc);
4941 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4942 process_constraint (new_constraint (lhs, *rhsp));
4943 rhsc.truncate (0);
4947 if (gcall *call_stmt = dyn_cast <gcall *> (t))
4949 varinfo_t cfi = NULL;
4950 tree decl = gimple_call_fndecl (t);
4951 struct constraint_expr lhs, rhs;
4952 unsigned i, j;
4954 /* For builtins we do not have separate function info. For those
4955 we do not generate escapes for we have to generate clobbers/uses. */
4956 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4957 switch (DECL_FUNCTION_CODE (decl))
4959 /* The following functions use and clobber memory pointed to
4960 by their arguments. */
4961 case BUILT_IN_STRCPY:
4962 case BUILT_IN_STRNCPY:
4963 case BUILT_IN_BCOPY:
4964 case BUILT_IN_MEMCPY:
4965 case BUILT_IN_MEMMOVE:
4966 case BUILT_IN_MEMPCPY:
4967 case BUILT_IN_STPCPY:
4968 case BUILT_IN_STPNCPY:
4969 case BUILT_IN_STRCAT:
4970 case BUILT_IN_STRNCAT:
4971 case BUILT_IN_STRCPY_CHK:
4972 case BUILT_IN_STRNCPY_CHK:
4973 case BUILT_IN_MEMCPY_CHK:
4974 case BUILT_IN_MEMMOVE_CHK:
4975 case BUILT_IN_MEMPCPY_CHK:
4976 case BUILT_IN_STPCPY_CHK:
4977 case BUILT_IN_STPNCPY_CHK:
4978 case BUILT_IN_STRCAT_CHK:
4979 case BUILT_IN_STRNCAT_CHK:
4981 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4982 == BUILT_IN_BCOPY ? 1 : 0));
4983 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4984 == BUILT_IN_BCOPY ? 0 : 1));
4985 unsigned i;
4986 struct constraint_expr *rhsp, *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 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4992 lhs = get_function_part_constraint (fi, fi_uses);
4993 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4994 process_constraint (new_constraint (lhs, *rhsp));
4995 return;
4997 /* The following function clobbers memory pointed to by
4998 its argument. */
4999 case BUILT_IN_MEMSET:
5000 case BUILT_IN_MEMSET_CHK:
5001 case BUILT_IN_POSIX_MEMALIGN:
5003 tree dest = gimple_call_arg (t, 0);
5004 unsigned i;
5005 ce_s *lhsp;
5006 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
5007 lhs = get_function_part_constraint (fi, fi_clobbers);
5008 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5009 process_constraint (new_constraint (lhs, *lhsp));
5010 return;
5012 /* The following functions clobber their second and third
5013 arguments. */
5014 case BUILT_IN_SINCOS:
5015 case BUILT_IN_SINCOSF:
5016 case BUILT_IN_SINCOSL:
5018 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5019 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5020 return;
5022 /* The following functions clobber their second argument. */
5023 case BUILT_IN_FREXP:
5024 case BUILT_IN_FREXPF:
5025 case BUILT_IN_FREXPL:
5026 case BUILT_IN_LGAMMA_R:
5027 case BUILT_IN_LGAMMAF_R:
5028 case BUILT_IN_LGAMMAL_R:
5029 case BUILT_IN_GAMMA_R:
5030 case BUILT_IN_GAMMAF_R:
5031 case BUILT_IN_GAMMAL_R:
5032 case BUILT_IN_MODF:
5033 case BUILT_IN_MODFF:
5034 case BUILT_IN_MODFL:
5036 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5037 return;
5039 /* The following functions clobber their third argument. */
5040 case BUILT_IN_REMQUO:
5041 case BUILT_IN_REMQUOF:
5042 case BUILT_IN_REMQUOL:
5044 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5045 return;
5047 /* The following functions neither read nor clobber memory. */
5048 case BUILT_IN_ASSUME_ALIGNED:
5049 case BUILT_IN_FREE:
5050 return;
5051 /* Trampolines are of no interest to us. */
5052 case BUILT_IN_INIT_TRAMPOLINE:
5053 case BUILT_IN_ADJUST_TRAMPOLINE:
5054 return;
5055 case BUILT_IN_VA_START:
5056 case BUILT_IN_VA_END:
5057 return;
5058 /* printf-style functions may have hooks to set pointers to
5059 point to somewhere into the generated string. Leave them
5060 for a later exercise... */
5061 default:
5062 /* Fallthru to general call handling. */;
5065 /* Parameters passed by value are used. */
5066 lhs = get_function_part_constraint (fi, fi_uses);
5067 for (i = 0; i < gimple_call_num_args (t); i++)
5069 struct constraint_expr *rhsp;
5070 tree arg = gimple_call_arg (t, i);
5072 if (TREE_CODE (arg) == SSA_NAME
5073 || is_gimple_min_invariant (arg))
5074 continue;
5076 get_constraint_for_address_of (arg, &rhsc);
5077 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5078 process_constraint (new_constraint (lhs, *rhsp));
5079 rhsc.truncate (0);
5082 /* Build constraints for propagating clobbers/uses along the
5083 callgraph edges. */
5084 cfi = get_fi_for_callee (call_stmt);
5085 if (cfi->id == anything_id)
5087 if (gimple_vdef (t))
5088 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5089 anything_id);
5090 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5091 anything_id);
5092 return;
5095 /* For callees without function info (that's external functions),
5096 ESCAPED is clobbered and used. */
5097 if (gimple_call_fndecl (t)
5098 && !cfi->is_fn_info)
5100 varinfo_t vi;
5102 if (gimple_vdef (t))
5103 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5104 escaped_id);
5105 make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
5107 /* Also honor the call statement use/clobber info. */
5108 if ((vi = lookup_call_clobber_vi (call_stmt)) != NULL)
5109 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5110 vi->id);
5111 if ((vi = lookup_call_use_vi (call_stmt)) != NULL)
5112 make_copy_constraint (first_vi_for_offset (fi, fi_uses),
5113 vi->id);
5114 return;
5117 /* Otherwise the caller clobbers and uses what the callee does.
5118 ??? This should use a new complex constraint that filters
5119 local variables of the callee. */
5120 if (gimple_vdef (t))
5122 lhs = get_function_part_constraint (fi, fi_clobbers);
5123 rhs = get_function_part_constraint (cfi, fi_clobbers);
5124 process_constraint (new_constraint (lhs, rhs));
5126 lhs = get_function_part_constraint (fi, fi_uses);
5127 rhs = get_function_part_constraint (cfi, fi_uses);
5128 process_constraint (new_constraint (lhs, rhs));
5130 else if (gimple_code (t) == GIMPLE_ASM)
5132 /* ??? Ick. We can do better. */
5133 if (gimple_vdef (t))
5134 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5135 anything_id);
5136 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5137 anything_id);
5142 /* Find the first varinfo in the same variable as START that overlaps with
5143 OFFSET. Return NULL if we can't find one. */
5145 static varinfo_t
5146 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
5148 /* If the offset is outside of the variable, bail out. */
5149 if (offset >= start->fullsize)
5150 return NULL;
5152 /* If we cannot reach offset from start, lookup the first field
5153 and start from there. */
5154 if (start->offset > offset)
5155 start = get_varinfo (start->head);
5157 while (start)
5159 /* We may not find a variable in the field list with the actual
5160 offset when when we have glommed a structure to a variable.
5161 In that case, however, offset should still be within the size
5162 of the variable. */
5163 if (offset >= start->offset
5164 && (offset - start->offset) < start->size)
5165 return start;
5167 start = vi_next (start);
5170 return NULL;
5173 /* Find the first varinfo in the same variable as START that overlaps with
5174 OFFSET. If there is no such varinfo the varinfo directly preceding
5175 OFFSET is returned. */
5177 static varinfo_t
5178 first_or_preceding_vi_for_offset (varinfo_t start,
5179 unsigned HOST_WIDE_INT offset)
5181 /* If we cannot reach offset from start, lookup the first field
5182 and start from there. */
5183 if (start->offset > offset)
5184 start = get_varinfo (start->head);
5186 /* We may not find a variable in the field list with the actual
5187 offset when when we have glommed a structure to a variable.
5188 In that case, however, offset should still be within the size
5189 of the variable.
5190 If we got beyond the offset we look for return the field
5191 directly preceding offset which may be the last field. */
5192 while (start->next
5193 && offset >= start->offset
5194 && !((offset - start->offset) < start->size))
5195 start = vi_next (start);
5197 return start;
5201 /* This structure is used during pushing fields onto the fieldstack
5202 to track the offset of the field, since bitpos_of_field gives it
5203 relative to its immediate containing type, and we want it relative
5204 to the ultimate containing object. */
5206 struct fieldoff
5208 /* Offset from the base of the base containing object to this field. */
5209 HOST_WIDE_INT offset;
5211 /* Size, in bits, of the field. */
5212 unsigned HOST_WIDE_INT size;
5214 unsigned has_unknown_size : 1;
5216 unsigned must_have_pointers : 1;
5218 unsigned may_have_pointers : 1;
5220 unsigned only_restrict_pointers : 1;
5222 typedef struct fieldoff fieldoff_s;
5225 /* qsort comparison function for two fieldoff's PA and PB */
5227 static int
5228 fieldoff_compare (const void *pa, const void *pb)
5230 const fieldoff_s *foa = (const fieldoff_s *)pa;
5231 const fieldoff_s *fob = (const fieldoff_s *)pb;
5232 unsigned HOST_WIDE_INT foasize, fobsize;
5234 if (foa->offset < fob->offset)
5235 return -1;
5236 else if (foa->offset > fob->offset)
5237 return 1;
5239 foasize = foa->size;
5240 fobsize = fob->size;
5241 if (foasize < fobsize)
5242 return -1;
5243 else if (foasize > fobsize)
5244 return 1;
5245 return 0;
5248 /* Sort a fieldstack according to the field offset and sizes. */
5249 static void
5250 sort_fieldstack (vec<fieldoff_s> fieldstack)
5252 fieldstack.qsort (fieldoff_compare);
5255 /* Return true if T is a type that can have subvars. */
5257 static inline bool
5258 type_can_have_subvars (const_tree t)
5260 /* Aggregates without overlapping fields can have subvars. */
5261 return TREE_CODE (t) == RECORD_TYPE;
5264 /* Return true if V is a tree that we can have subvars for.
5265 Normally, this is any aggregate type. Also complex
5266 types which are not gimple registers can have subvars. */
5268 static inline bool
5269 var_can_have_subvars (const_tree v)
5271 /* Volatile variables should never have subvars. */
5272 if (TREE_THIS_VOLATILE (v))
5273 return false;
5275 /* Non decls or memory tags can never have subvars. */
5276 if (!DECL_P (v))
5277 return false;
5279 return type_can_have_subvars (TREE_TYPE (v));
5282 /* Return true if T is a type that does contain pointers. */
5284 static bool
5285 type_must_have_pointers (tree type)
5287 if (POINTER_TYPE_P (type))
5288 return true;
5290 if (TREE_CODE (type) == ARRAY_TYPE)
5291 return type_must_have_pointers (TREE_TYPE (type));
5293 /* A function or method can have pointers as arguments, so track
5294 those separately. */
5295 if (TREE_CODE (type) == FUNCTION_TYPE
5296 || TREE_CODE (type) == METHOD_TYPE)
5297 return true;
5299 return false;
5302 static bool
5303 field_must_have_pointers (tree t)
5305 return type_must_have_pointers (TREE_TYPE (t));
5308 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5309 the fields of TYPE onto fieldstack, recording their offsets along
5310 the way.
5312 OFFSET is used to keep track of the offset in this entire
5313 structure, rather than just the immediately containing structure.
5314 Returns false if the caller is supposed to handle the field we
5315 recursed for. */
5317 static bool
5318 push_fields_onto_fieldstack (tree type, vec<fieldoff_s> *fieldstack,
5319 HOST_WIDE_INT offset)
5321 tree field;
5322 bool empty_p = true;
5324 if (TREE_CODE (type) != RECORD_TYPE)
5325 return false;
5327 /* If the vector of fields is growing too big, bail out early.
5328 Callers check for vec::length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5329 sure this fails. */
5330 if (fieldstack->length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5331 return false;
5333 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5334 if (TREE_CODE (field) == FIELD_DECL)
5336 bool push = false;
5337 HOST_WIDE_INT foff = bitpos_of_field (field);
5339 if (!var_can_have_subvars (field)
5340 || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
5341 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
5342 push = true;
5343 else if (!push_fields_onto_fieldstack
5344 (TREE_TYPE (field), fieldstack, offset + foff)
5345 && (DECL_SIZE (field)
5346 && !integer_zerop (DECL_SIZE (field))))
5347 /* Empty structures may have actual size, like in C++. So
5348 see if we didn't push any subfields and the size is
5349 nonzero, push the field onto the stack. */
5350 push = true;
5352 if (push)
5354 fieldoff_s *pair = NULL;
5355 bool has_unknown_size = false;
5356 bool must_have_pointers_p;
5358 if (!fieldstack->is_empty ())
5359 pair = &fieldstack->last ();
5361 /* If there isn't anything at offset zero, create sth. */
5362 if (!pair
5363 && offset + foff != 0)
5365 fieldoff_s e = {0, offset + foff, false, false, false, false};
5366 pair = fieldstack->safe_push (e);
5369 if (!DECL_SIZE (field)
5370 || !tree_fits_uhwi_p (DECL_SIZE (field)))
5371 has_unknown_size = true;
5373 /* If adjacent fields do not contain pointers merge them. */
5374 must_have_pointers_p = field_must_have_pointers (field);
5375 if (pair
5376 && !has_unknown_size
5377 && !must_have_pointers_p
5378 && !pair->must_have_pointers
5379 && !pair->has_unknown_size
5380 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5382 pair->size += tree_to_uhwi (DECL_SIZE (field));
5384 else
5386 fieldoff_s e;
5387 e.offset = offset + foff;
5388 e.has_unknown_size = has_unknown_size;
5389 if (!has_unknown_size)
5390 e.size = tree_to_uhwi (DECL_SIZE (field));
5391 else
5392 e.size = -1;
5393 e.must_have_pointers = must_have_pointers_p;
5394 e.may_have_pointers = true;
5395 e.only_restrict_pointers
5396 = (!has_unknown_size
5397 && POINTER_TYPE_P (TREE_TYPE (field))
5398 && TYPE_RESTRICT (TREE_TYPE (field)));
5399 fieldstack->safe_push (e);
5403 empty_p = false;
5406 return !empty_p;
5409 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5410 if it is a varargs function. */
5412 static unsigned int
5413 count_num_arguments (tree decl, bool *is_varargs)
5415 unsigned int num = 0;
5416 tree t;
5418 /* Capture named arguments for K&R functions. They do not
5419 have a prototype and thus no TYPE_ARG_TYPES. */
5420 for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5421 ++num;
5423 /* Check if the function has variadic arguments. */
5424 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5425 if (TREE_VALUE (t) == void_type_node)
5426 break;
5427 if (!t)
5428 *is_varargs = true;
5430 return num;
5433 /* Creation function node for DECL, using NAME, and return the index
5434 of the variable we've created for the function. */
5436 static varinfo_t
5437 create_function_info_for (tree decl, const char *name)
5439 struct function *fn = DECL_STRUCT_FUNCTION (decl);
5440 varinfo_t vi, prev_vi;
5441 tree arg;
5442 unsigned int i;
5443 bool is_varargs = false;
5444 unsigned int num_args = count_num_arguments (decl, &is_varargs);
5446 /* Create the variable info. */
5448 vi = new_var_info (decl, name);
5449 vi->offset = 0;
5450 vi->size = 1;
5451 vi->fullsize = fi_parm_base + num_args;
5452 vi->is_fn_info = 1;
5453 vi->may_have_pointers = false;
5454 if (is_varargs)
5455 vi->fullsize = ~0;
5456 insert_vi_for_tree (vi->decl, vi);
5458 prev_vi = vi;
5460 /* Create a variable for things the function clobbers and one for
5461 things the function uses. */
5463 varinfo_t clobbervi, usevi;
5464 const char *newname;
5465 char *tempname;
5467 tempname = xasprintf ("%s.clobber", name);
5468 newname = ggc_strdup (tempname);
5469 free (tempname);
5471 clobbervi = new_var_info (NULL, newname);
5472 clobbervi->offset = fi_clobbers;
5473 clobbervi->size = 1;
5474 clobbervi->fullsize = vi->fullsize;
5475 clobbervi->is_full_var = true;
5476 clobbervi->is_global_var = false;
5477 gcc_assert (prev_vi->offset < clobbervi->offset);
5478 prev_vi->next = clobbervi->id;
5479 prev_vi = clobbervi;
5481 tempname = xasprintf ("%s.use", name);
5482 newname = ggc_strdup (tempname);
5483 free (tempname);
5485 usevi = new_var_info (NULL, newname);
5486 usevi->offset = fi_uses;
5487 usevi->size = 1;
5488 usevi->fullsize = vi->fullsize;
5489 usevi->is_full_var = true;
5490 usevi->is_global_var = false;
5491 gcc_assert (prev_vi->offset < usevi->offset);
5492 prev_vi->next = usevi->id;
5493 prev_vi = usevi;
5496 /* And one for the static chain. */
5497 if (fn->static_chain_decl != NULL_TREE)
5499 varinfo_t chainvi;
5500 const char *newname;
5501 char *tempname;
5503 tempname = xasprintf ("%s.chain", name);
5504 newname = ggc_strdup (tempname);
5505 free (tempname);
5507 chainvi = new_var_info (fn->static_chain_decl, newname);
5508 chainvi->offset = fi_static_chain;
5509 chainvi->size = 1;
5510 chainvi->fullsize = vi->fullsize;
5511 chainvi->is_full_var = true;
5512 chainvi->is_global_var = false;
5513 gcc_assert (prev_vi->offset < chainvi->offset);
5514 prev_vi->next = chainvi->id;
5515 prev_vi = chainvi;
5516 insert_vi_for_tree (fn->static_chain_decl, chainvi);
5519 /* Create a variable for the return var. */
5520 if (DECL_RESULT (decl) != NULL
5521 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5523 varinfo_t resultvi;
5524 const char *newname;
5525 char *tempname;
5526 tree resultdecl = decl;
5528 if (DECL_RESULT (decl))
5529 resultdecl = DECL_RESULT (decl);
5531 tempname = xasprintf ("%s.result", name);
5532 newname = ggc_strdup (tempname);
5533 free (tempname);
5535 resultvi = new_var_info (resultdecl, newname);
5536 resultvi->offset = fi_result;
5537 resultvi->size = 1;
5538 resultvi->fullsize = vi->fullsize;
5539 resultvi->is_full_var = true;
5540 if (DECL_RESULT (decl))
5541 resultvi->may_have_pointers = true;
5542 gcc_assert (prev_vi->offset < resultvi->offset);
5543 prev_vi->next = resultvi->id;
5544 prev_vi = resultvi;
5545 if (DECL_RESULT (decl))
5546 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5549 /* Set up variables for each argument. */
5550 arg = DECL_ARGUMENTS (decl);
5551 for (i = 0; i < num_args; i++)
5553 varinfo_t argvi;
5554 const char *newname;
5555 char *tempname;
5556 tree argdecl = decl;
5558 if (arg)
5559 argdecl = arg;
5561 tempname = xasprintf ("%s.arg%d", name, i);
5562 newname = ggc_strdup (tempname);
5563 free (tempname);
5565 argvi = new_var_info (argdecl, newname);
5566 argvi->offset = fi_parm_base + i;
5567 argvi->size = 1;
5568 argvi->is_full_var = true;
5569 argvi->fullsize = vi->fullsize;
5570 if (arg)
5571 argvi->may_have_pointers = true;
5572 gcc_assert (prev_vi->offset < argvi->offset);
5573 prev_vi->next = argvi->id;
5574 prev_vi = argvi;
5575 if (arg)
5577 insert_vi_for_tree (arg, argvi);
5578 arg = DECL_CHAIN (arg);
5582 /* Add one representative for all further args. */
5583 if (is_varargs)
5585 varinfo_t argvi;
5586 const char *newname;
5587 char *tempname;
5588 tree decl;
5590 tempname = xasprintf ("%s.varargs", name);
5591 newname = ggc_strdup (tempname);
5592 free (tempname);
5594 /* We need sth that can be pointed to for va_start. */
5595 decl = build_fake_var_decl (ptr_type_node);
5597 argvi = new_var_info (decl, newname);
5598 argvi->offset = fi_parm_base + num_args;
5599 argvi->size = ~0;
5600 argvi->is_full_var = true;
5601 argvi->is_heap_var = true;
5602 argvi->fullsize = vi->fullsize;
5603 gcc_assert (prev_vi->offset < argvi->offset);
5604 prev_vi->next = argvi->id;
5605 prev_vi = argvi;
5608 return vi;
5612 /* Return true if FIELDSTACK contains fields that overlap.
5613 FIELDSTACK is assumed to be sorted by offset. */
5615 static bool
5616 check_for_overlaps (vec<fieldoff_s> fieldstack)
5618 fieldoff_s *fo = NULL;
5619 unsigned int i;
5620 HOST_WIDE_INT lastoffset = -1;
5622 FOR_EACH_VEC_ELT (fieldstack, i, fo)
5624 if (fo->offset == lastoffset)
5625 return true;
5626 lastoffset = fo->offset;
5628 return false;
5631 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5632 This will also create any varinfo structures necessary for fields
5633 of DECL. */
5635 static varinfo_t
5636 create_variable_info_for_1 (tree decl, const char *name)
5638 varinfo_t vi, newvi;
5639 tree decl_type = TREE_TYPE (decl);
5640 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5641 auto_vec<fieldoff_s> fieldstack;
5642 fieldoff_s *fo;
5643 unsigned int i;
5644 varpool_node *vnode;
5646 if (!declsize
5647 || !tree_fits_uhwi_p (declsize))
5649 vi = new_var_info (decl, name);
5650 vi->offset = 0;
5651 vi->size = ~0;
5652 vi->fullsize = ~0;
5653 vi->is_unknown_size_var = true;
5654 vi->is_full_var = true;
5655 vi->may_have_pointers = true;
5656 return vi;
5659 /* Collect field information. */
5660 if (use_field_sensitive
5661 && var_can_have_subvars (decl)
5662 /* ??? Force us to not use subfields for global initializers
5663 in IPA mode. Else we'd have to parse arbitrary initializers. */
5664 && !(in_ipa_mode
5665 && is_global_var (decl)
5666 && (vnode = varpool_node::get (decl))
5667 && vnode->get_constructor ()))
5669 fieldoff_s *fo = NULL;
5670 bool notokay = false;
5671 unsigned int i;
5673 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5675 for (i = 0; !notokay && fieldstack.iterate (i, &fo); i++)
5676 if (fo->has_unknown_size
5677 || fo->offset < 0)
5679 notokay = true;
5680 break;
5683 /* We can't sort them if we have a field with a variable sized type,
5684 which will make notokay = true. In that case, we are going to return
5685 without creating varinfos for the fields anyway, so sorting them is a
5686 waste to boot. */
5687 if (!notokay)
5689 sort_fieldstack (fieldstack);
5690 /* Due to some C++ FE issues, like PR 22488, we might end up
5691 what appear to be overlapping fields even though they,
5692 in reality, do not overlap. Until the C++ FE is fixed,
5693 we will simply disable field-sensitivity for these cases. */
5694 notokay = check_for_overlaps (fieldstack);
5697 if (notokay)
5698 fieldstack.release ();
5701 /* If we didn't end up collecting sub-variables create a full
5702 variable for the decl. */
5703 if (fieldstack.length () <= 1
5704 || fieldstack.length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5706 vi = new_var_info (decl, name);
5707 vi->offset = 0;
5708 vi->may_have_pointers = true;
5709 vi->fullsize = tree_to_uhwi (declsize);
5710 vi->size = vi->fullsize;
5711 vi->is_full_var = true;
5712 fieldstack.release ();
5713 return vi;
5716 vi = new_var_info (decl, name);
5717 vi->fullsize = tree_to_uhwi (declsize);
5718 for (i = 0, newvi = vi;
5719 fieldstack.iterate (i, &fo);
5720 ++i, newvi = vi_next (newvi))
5722 const char *newname = "NULL";
5723 char *tempname;
5725 if (dump_file)
5727 tempname
5728 = xasprintf ("%s." HOST_WIDE_INT_PRINT_DEC
5729 "+" HOST_WIDE_INT_PRINT_DEC, name,
5730 fo->offset, fo->size);
5731 newname = ggc_strdup (tempname);
5732 free (tempname);
5734 newvi->name = newname;
5735 newvi->offset = fo->offset;
5736 newvi->size = fo->size;
5737 newvi->fullsize = vi->fullsize;
5738 newvi->may_have_pointers = fo->may_have_pointers;
5739 newvi->only_restrict_pointers = fo->only_restrict_pointers;
5740 if (i + 1 < fieldstack.length ())
5742 varinfo_t tem = new_var_info (decl, name);
5743 newvi->next = tem->id;
5744 tem->head = vi->id;
5748 return vi;
5751 static unsigned int
5752 create_variable_info_for (tree decl, const char *name)
5754 varinfo_t vi = create_variable_info_for_1 (decl, name);
5755 unsigned int id = vi->id;
5757 insert_vi_for_tree (decl, vi);
5759 if (TREE_CODE (decl) != VAR_DECL)
5760 return id;
5762 /* Create initial constraints for globals. */
5763 for (; vi; vi = vi_next (vi))
5765 if (!vi->may_have_pointers
5766 || !vi->is_global_var)
5767 continue;
5769 /* Mark global restrict qualified pointers. */
5770 if ((POINTER_TYPE_P (TREE_TYPE (decl))
5771 && TYPE_RESTRICT (TREE_TYPE (decl)))
5772 || vi->only_restrict_pointers)
5774 varinfo_t rvi
5775 = make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5776 /* ??? For now exclude reads from globals as restrict sources
5777 if those are not (indirectly) from incoming parameters. */
5778 rvi->is_restrict_var = false;
5779 continue;
5782 /* In non-IPA mode the initializer from nonlocal is all we need. */
5783 if (!in_ipa_mode
5784 || DECL_HARD_REGISTER (decl))
5785 make_copy_constraint (vi, nonlocal_id);
5787 /* In IPA mode parse the initializer and generate proper constraints
5788 for it. */
5789 else
5791 varpool_node *vnode = varpool_node::get (decl);
5793 /* For escaped variables initialize them from nonlocal. */
5794 if (!vnode->all_refs_explicit_p ())
5795 make_copy_constraint (vi, nonlocal_id);
5797 /* If this is a global variable with an initializer and we are in
5798 IPA mode generate constraints for it. */
5799 if (vnode->get_constructor ()
5800 && vnode->definition)
5802 auto_vec<ce_s> rhsc;
5803 struct constraint_expr lhs, *rhsp;
5804 unsigned i;
5805 get_constraint_for_rhs (vnode->get_constructor (), &rhsc);
5806 lhs.var = vi->id;
5807 lhs.offset = 0;
5808 lhs.type = SCALAR;
5809 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5810 process_constraint (new_constraint (lhs, *rhsp));
5811 /* If this is a variable that escapes from the unit
5812 the initializer escapes as well. */
5813 if (!vnode->all_refs_explicit_p ())
5815 lhs.var = escaped_id;
5816 lhs.offset = 0;
5817 lhs.type = SCALAR;
5818 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5819 process_constraint (new_constraint (lhs, *rhsp));
5825 return id;
5828 /* Print out the points-to solution for VAR to FILE. */
5830 static void
5831 dump_solution_for_var (FILE *file, unsigned int var)
5833 varinfo_t vi = get_varinfo (var);
5834 unsigned int i;
5835 bitmap_iterator bi;
5837 /* Dump the solution for unified vars anyway, this avoids difficulties
5838 in scanning dumps in the testsuite. */
5839 fprintf (file, "%s = { ", vi->name);
5840 vi = get_varinfo (find (var));
5841 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5842 fprintf (file, "%s ", get_varinfo (i)->name);
5843 fprintf (file, "}");
5845 /* But note when the variable was unified. */
5846 if (vi->id != var)
5847 fprintf (file, " same as %s", vi->name);
5849 fprintf (file, "\n");
5852 /* Print the points-to solution for VAR to stderr. */
5854 DEBUG_FUNCTION void
5855 debug_solution_for_var (unsigned int var)
5857 dump_solution_for_var (stderr, var);
5860 /* Create varinfo structures for all of the variables in the
5861 function for intraprocedural mode. */
5863 static void
5864 intra_create_variable_infos (struct function *fn)
5866 tree t;
5868 /* For each incoming pointer argument arg, create the constraint ARG
5869 = NONLOCAL or a dummy variable if it is a restrict qualified
5870 passed-by-reference argument. */
5871 for (t = DECL_ARGUMENTS (fn->decl); t; t = DECL_CHAIN (t))
5873 varinfo_t p = get_vi_for_tree (t);
5875 /* For restrict qualified pointers to objects passed by
5876 reference build a real representative for the pointed-to object.
5877 Treat restrict qualified references the same. */
5878 if (TYPE_RESTRICT (TREE_TYPE (t))
5879 && ((DECL_BY_REFERENCE (t) && POINTER_TYPE_P (TREE_TYPE (t)))
5880 || TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
5881 && !type_contains_placeholder_p (TREE_TYPE (TREE_TYPE (t))))
5883 struct constraint_expr lhsc, rhsc;
5884 varinfo_t vi;
5885 tree heapvar = build_fake_var_decl (TREE_TYPE (TREE_TYPE (t)));
5886 DECL_EXTERNAL (heapvar) = 1;
5887 vi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS");
5888 vi->is_restrict_var = 1;
5889 insert_vi_for_tree (heapvar, vi);
5890 lhsc.var = p->id;
5891 lhsc.type = SCALAR;
5892 lhsc.offset = 0;
5893 rhsc.var = vi->id;
5894 rhsc.type = ADDRESSOF;
5895 rhsc.offset = 0;
5896 process_constraint (new_constraint (lhsc, rhsc));
5897 for (; vi; vi = vi_next (vi))
5898 if (vi->may_have_pointers)
5900 if (vi->only_restrict_pointers)
5901 make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5902 else
5903 make_copy_constraint (vi, nonlocal_id);
5905 continue;
5908 if (POINTER_TYPE_P (TREE_TYPE (t))
5909 && TYPE_RESTRICT (TREE_TYPE (t)))
5910 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5911 else
5913 for (; p; p = vi_next (p))
5915 if (p->only_restrict_pointers)
5916 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5917 else if (p->may_have_pointers)
5918 make_constraint_from (p, nonlocal_id);
5923 /* Add a constraint for a result decl that is passed by reference. */
5924 if (DECL_RESULT (fn->decl)
5925 && DECL_BY_REFERENCE (DECL_RESULT (fn->decl)))
5927 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (fn->decl));
5929 for (p = result_vi; p; p = vi_next (p))
5930 make_constraint_from (p, nonlocal_id);
5933 /* Add a constraint for the incoming static chain parameter. */
5934 if (fn->static_chain_decl != NULL_TREE)
5936 varinfo_t p, chain_vi = get_vi_for_tree (fn->static_chain_decl);
5938 for (p = chain_vi; p; p = vi_next (p))
5939 make_constraint_from (p, nonlocal_id);
5943 /* Structure used to put solution bitmaps in a hashtable so they can
5944 be shared among variables with the same points-to set. */
5946 typedef struct shared_bitmap_info
5948 bitmap pt_vars;
5949 hashval_t hashcode;
5950 } *shared_bitmap_info_t;
5951 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5953 /* Shared_bitmap hashtable helpers. */
5955 struct shared_bitmap_hasher : typed_free_remove <shared_bitmap_info>
5957 typedef shared_bitmap_info *value_type;
5958 typedef shared_bitmap_info *compare_type;
5959 static inline hashval_t hash (const shared_bitmap_info *);
5960 static inline bool equal (const shared_bitmap_info *,
5961 const shared_bitmap_info *);
5964 /* Hash function for a shared_bitmap_info_t */
5966 inline hashval_t
5967 shared_bitmap_hasher::hash (const shared_bitmap_info *bi)
5969 return bi->hashcode;
5972 /* Equality function for two shared_bitmap_info_t's. */
5974 inline bool
5975 shared_bitmap_hasher::equal (const shared_bitmap_info *sbi1,
5976 const shared_bitmap_info *sbi2)
5978 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
5981 /* Shared_bitmap hashtable. */
5983 static hash_table<shared_bitmap_hasher> *shared_bitmap_table;
5985 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
5986 existing instance if there is one, NULL otherwise. */
5988 static bitmap
5989 shared_bitmap_lookup (bitmap pt_vars)
5991 shared_bitmap_info **slot;
5992 struct shared_bitmap_info sbi;
5994 sbi.pt_vars = pt_vars;
5995 sbi.hashcode = bitmap_hash (pt_vars);
5997 slot = shared_bitmap_table->find_slot (&sbi, NO_INSERT);
5998 if (!slot)
5999 return NULL;
6000 else
6001 return (*slot)->pt_vars;
6005 /* Add a bitmap to the shared bitmap hashtable. */
6007 static void
6008 shared_bitmap_add (bitmap pt_vars)
6010 shared_bitmap_info **slot;
6011 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
6013 sbi->pt_vars = pt_vars;
6014 sbi->hashcode = bitmap_hash (pt_vars);
6016 slot = shared_bitmap_table->find_slot (sbi, INSERT);
6017 gcc_assert (!*slot);
6018 *slot = sbi;
6022 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
6024 static void
6025 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
6027 unsigned int i;
6028 bitmap_iterator bi;
6029 varinfo_t escaped_vi = get_varinfo (find (escaped_id));
6030 bool everything_escaped
6031 = escaped_vi->solution && bitmap_bit_p (escaped_vi->solution, anything_id);
6033 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
6035 varinfo_t vi = get_varinfo (i);
6037 /* The only artificial variables that are allowed in a may-alias
6038 set are heap variables. */
6039 if (vi->is_artificial_var && !vi->is_heap_var)
6040 continue;
6042 if (everything_escaped
6043 || (escaped_vi->solution
6044 && bitmap_bit_p (escaped_vi->solution, i)))
6046 pt->vars_contains_escaped = true;
6047 pt->vars_contains_escaped_heap = vi->is_heap_var;
6050 if (TREE_CODE (vi->decl) == VAR_DECL
6051 || TREE_CODE (vi->decl) == PARM_DECL
6052 || TREE_CODE (vi->decl) == RESULT_DECL)
6054 /* If we are in IPA mode we will not recompute points-to
6055 sets after inlining so make sure they stay valid. */
6056 if (in_ipa_mode
6057 && !DECL_PT_UID_SET_P (vi->decl))
6058 SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
6060 /* Add the decl to the points-to set. Note that the points-to
6061 set contains global variables. */
6062 bitmap_set_bit (into, DECL_PT_UID (vi->decl));
6063 if (vi->is_global_var)
6064 pt->vars_contains_nonlocal = true;
6070 /* Compute the points-to solution *PT for the variable VI. */
6072 static struct pt_solution
6073 find_what_var_points_to (varinfo_t orig_vi)
6075 unsigned int i;
6076 bitmap_iterator bi;
6077 bitmap finished_solution;
6078 bitmap result;
6079 varinfo_t vi;
6080 struct pt_solution *pt;
6082 /* This variable may have been collapsed, let's get the real
6083 variable. */
6084 vi = get_varinfo (find (orig_vi->id));
6086 /* See if we have already computed the solution and return it. */
6087 pt_solution **slot = &final_solutions->get_or_insert (vi);
6088 if (*slot != NULL)
6089 return **slot;
6091 *slot = pt = XOBNEW (&final_solutions_obstack, struct pt_solution);
6092 memset (pt, 0, sizeof (struct pt_solution));
6094 /* Translate artificial variables into SSA_NAME_PTR_INFO
6095 attributes. */
6096 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6098 varinfo_t vi = get_varinfo (i);
6100 if (vi->is_artificial_var)
6102 if (vi->id == nothing_id)
6103 pt->null = 1;
6104 else if (vi->id == escaped_id)
6106 if (in_ipa_mode)
6107 pt->ipa_escaped = 1;
6108 else
6109 pt->escaped = 1;
6110 /* Expand some special vars of ESCAPED in-place here. */
6111 varinfo_t evi = get_varinfo (find (escaped_id));
6112 if (bitmap_bit_p (evi->solution, nonlocal_id))
6113 pt->nonlocal = 1;
6115 else if (vi->id == nonlocal_id)
6116 pt->nonlocal = 1;
6117 else if (vi->is_heap_var)
6118 /* We represent heapvars in the points-to set properly. */
6120 else if (vi->id == string_id)
6121 /* Nobody cares - STRING_CSTs are read-only entities. */
6123 else if (vi->id == anything_id
6124 || vi->id == integer_id)
6125 pt->anything = 1;
6129 /* Instead of doing extra work, simply do not create
6130 elaborate points-to information for pt_anything pointers. */
6131 if (pt->anything)
6132 return *pt;
6134 /* Share the final set of variables when possible. */
6135 finished_solution = BITMAP_GGC_ALLOC ();
6136 stats.points_to_sets_created++;
6138 set_uids_in_ptset (finished_solution, vi->solution, pt);
6139 result = shared_bitmap_lookup (finished_solution);
6140 if (!result)
6142 shared_bitmap_add (finished_solution);
6143 pt->vars = finished_solution;
6145 else
6147 pt->vars = result;
6148 bitmap_clear (finished_solution);
6151 return *pt;
6154 /* Given a pointer variable P, fill in its points-to set. */
6156 static void
6157 find_what_p_points_to (tree p)
6159 struct ptr_info_def *pi;
6160 tree lookup_p = p;
6161 varinfo_t vi;
6163 /* For parameters, get at the points-to set for the actual parm
6164 decl. */
6165 if (TREE_CODE (p) == SSA_NAME
6166 && SSA_NAME_IS_DEFAULT_DEF (p)
6167 && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
6168 || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL))
6169 lookup_p = SSA_NAME_VAR (p);
6171 vi = lookup_vi_for_tree (lookup_p);
6172 if (!vi)
6173 return;
6175 pi = get_ptr_info (p);
6176 pi->pt = find_what_var_points_to (vi);
6180 /* Query statistics for points-to solutions. */
6182 static struct {
6183 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
6184 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
6185 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
6186 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
6187 } pta_stats;
6189 void
6190 dump_pta_stats (FILE *s)
6192 fprintf (s, "\nPTA query stats:\n");
6193 fprintf (s, " pt_solution_includes: "
6194 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6195 HOST_WIDE_INT_PRINT_DEC" queries\n",
6196 pta_stats.pt_solution_includes_no_alias,
6197 pta_stats.pt_solution_includes_no_alias
6198 + pta_stats.pt_solution_includes_may_alias);
6199 fprintf (s, " pt_solutions_intersect: "
6200 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6201 HOST_WIDE_INT_PRINT_DEC" queries\n",
6202 pta_stats.pt_solutions_intersect_no_alias,
6203 pta_stats.pt_solutions_intersect_no_alias
6204 + pta_stats.pt_solutions_intersect_may_alias);
6208 /* Reset the points-to solution *PT to a conservative default
6209 (point to anything). */
6211 void
6212 pt_solution_reset (struct pt_solution *pt)
6214 memset (pt, 0, sizeof (struct pt_solution));
6215 pt->anything = true;
6218 /* Set the points-to solution *PT to point only to the variables
6219 in VARS. VARS_CONTAINS_GLOBAL specifies whether that contains
6220 global variables and VARS_CONTAINS_RESTRICT specifies whether
6221 it contains restrict tag variables. */
6223 void
6224 pt_solution_set (struct pt_solution *pt, bitmap vars,
6225 bool vars_contains_nonlocal)
6227 memset (pt, 0, sizeof (struct pt_solution));
6228 pt->vars = vars;
6229 pt->vars_contains_nonlocal = vars_contains_nonlocal;
6230 pt->vars_contains_escaped
6231 = (cfun->gimple_df->escaped.anything
6232 || bitmap_intersect_p (cfun->gimple_df->escaped.vars, vars));
6235 /* Set the points-to solution *PT to point only to the variable VAR. */
6237 void
6238 pt_solution_set_var (struct pt_solution *pt, tree var)
6240 memset (pt, 0, sizeof (struct pt_solution));
6241 pt->vars = BITMAP_GGC_ALLOC ();
6242 bitmap_set_bit (pt->vars, DECL_PT_UID (var));
6243 pt->vars_contains_nonlocal = is_global_var (var);
6244 pt->vars_contains_escaped
6245 = (cfun->gimple_df->escaped.anything
6246 || bitmap_bit_p (cfun->gimple_df->escaped.vars, DECL_PT_UID (var)));
6249 /* Computes the union of the points-to solutions *DEST and *SRC and
6250 stores the result in *DEST. This changes the points-to bitmap
6251 of *DEST and thus may not be used if that might be shared.
6252 The points-to bitmap of *SRC and *DEST will not be shared after
6253 this function if they were not before. */
6255 static void
6256 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
6258 dest->anything |= src->anything;
6259 if (dest->anything)
6261 pt_solution_reset (dest);
6262 return;
6265 dest->nonlocal |= src->nonlocal;
6266 dest->escaped |= src->escaped;
6267 dest->ipa_escaped |= src->ipa_escaped;
6268 dest->null |= src->null;
6269 dest->vars_contains_nonlocal |= src->vars_contains_nonlocal;
6270 dest->vars_contains_escaped |= src->vars_contains_escaped;
6271 dest->vars_contains_escaped_heap |= src->vars_contains_escaped_heap;
6272 if (!src->vars)
6273 return;
6275 if (!dest->vars)
6276 dest->vars = BITMAP_GGC_ALLOC ();
6277 bitmap_ior_into (dest->vars, src->vars);
6280 /* Return true if the points-to solution *PT is empty. */
6282 bool
6283 pt_solution_empty_p (struct pt_solution *pt)
6285 if (pt->anything
6286 || pt->nonlocal)
6287 return false;
6289 if (pt->vars
6290 && !bitmap_empty_p (pt->vars))
6291 return false;
6293 /* If the solution includes ESCAPED, check if that is empty. */
6294 if (pt->escaped
6295 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6296 return false;
6298 /* If the solution includes ESCAPED, check if that is empty. */
6299 if (pt->ipa_escaped
6300 && !pt_solution_empty_p (&ipa_escaped_pt))
6301 return false;
6303 return true;
6306 /* Return true if the points-to solution *PT only point to a single var, and
6307 return the var uid in *UID. */
6309 bool
6310 pt_solution_singleton_p (struct pt_solution *pt, unsigned *uid)
6312 if (pt->anything || pt->nonlocal || pt->escaped || pt->ipa_escaped
6313 || pt->null || pt->vars == NULL
6314 || !bitmap_single_bit_set_p (pt->vars))
6315 return false;
6317 *uid = bitmap_first_set_bit (pt->vars);
6318 return true;
6321 /* Return true if the points-to solution *PT includes global memory. */
6323 bool
6324 pt_solution_includes_global (struct pt_solution *pt)
6326 if (pt->anything
6327 || pt->nonlocal
6328 || pt->vars_contains_nonlocal
6329 /* The following is a hack to make the malloc escape hack work.
6330 In reality we'd need different sets for escaped-through-return
6331 and escaped-to-callees and passes would need to be updated. */
6332 || pt->vars_contains_escaped_heap)
6333 return true;
6335 /* 'escaped' is also a placeholder so we have to look into it. */
6336 if (pt->escaped)
6337 return pt_solution_includes_global (&cfun->gimple_df->escaped);
6339 if (pt->ipa_escaped)
6340 return pt_solution_includes_global (&ipa_escaped_pt);
6342 /* ??? This predicate is not correct for the IPA-PTA solution
6343 as we do not properly distinguish between unit escape points
6344 and global variables. */
6345 if (cfun->gimple_df->ipa_pta)
6346 return true;
6348 return false;
6351 /* Return true if the points-to solution *PT includes the variable
6352 declaration DECL. */
6354 static bool
6355 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6357 if (pt->anything)
6358 return true;
6360 if (pt->nonlocal
6361 && is_global_var (decl))
6362 return true;
6364 if (pt->vars
6365 && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6366 return true;
6368 /* If the solution includes ESCAPED, check it. */
6369 if (pt->escaped
6370 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6371 return true;
6373 /* If the solution includes ESCAPED, check it. */
6374 if (pt->ipa_escaped
6375 && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6376 return true;
6378 return false;
6381 bool
6382 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6384 bool res = pt_solution_includes_1 (pt, decl);
6385 if (res)
6386 ++pta_stats.pt_solution_includes_may_alias;
6387 else
6388 ++pta_stats.pt_solution_includes_no_alias;
6389 return res;
6392 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6393 intersection. */
6395 static bool
6396 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6398 if (pt1->anything || pt2->anything)
6399 return true;
6401 /* If either points to unknown global memory and the other points to
6402 any global memory they alias. */
6403 if ((pt1->nonlocal
6404 && (pt2->nonlocal
6405 || pt2->vars_contains_nonlocal))
6406 || (pt2->nonlocal
6407 && pt1->vars_contains_nonlocal))
6408 return true;
6410 /* If either points to all escaped memory and the other points to
6411 any escaped memory they alias. */
6412 if ((pt1->escaped
6413 && (pt2->escaped
6414 || pt2->vars_contains_escaped))
6415 || (pt2->escaped
6416 && pt1->vars_contains_escaped))
6417 return true;
6419 /* Check the escaped solution if required.
6420 ??? Do we need to check the local against the IPA escaped sets? */
6421 if ((pt1->ipa_escaped || pt2->ipa_escaped)
6422 && !pt_solution_empty_p (&ipa_escaped_pt))
6424 /* If both point to escaped memory and that solution
6425 is not empty they alias. */
6426 if (pt1->ipa_escaped && pt2->ipa_escaped)
6427 return true;
6429 /* If either points to escaped memory see if the escaped solution
6430 intersects with the other. */
6431 if ((pt1->ipa_escaped
6432 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6433 || (pt2->ipa_escaped
6434 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6435 return true;
6438 /* Now both pointers alias if their points-to solution intersects. */
6439 return (pt1->vars
6440 && pt2->vars
6441 && bitmap_intersect_p (pt1->vars, pt2->vars));
6444 bool
6445 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6447 bool res = pt_solutions_intersect_1 (pt1, pt2);
6448 if (res)
6449 ++pta_stats.pt_solutions_intersect_may_alias;
6450 else
6451 ++pta_stats.pt_solutions_intersect_no_alias;
6452 return res;
6456 /* Dump points-to information to OUTFILE. */
6458 static void
6459 dump_sa_points_to_info (FILE *outfile)
6461 unsigned int i;
6463 fprintf (outfile, "\nPoints-to sets\n\n");
6465 if (dump_flags & TDF_STATS)
6467 fprintf (outfile, "Stats:\n");
6468 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
6469 fprintf (outfile, "Non-pointer vars: %d\n",
6470 stats.nonpointer_vars);
6471 fprintf (outfile, "Statically unified vars: %d\n",
6472 stats.unified_vars_static);
6473 fprintf (outfile, "Dynamically unified vars: %d\n",
6474 stats.unified_vars_dynamic);
6475 fprintf (outfile, "Iterations: %d\n", stats.iterations);
6476 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
6477 fprintf (outfile, "Number of implicit edges: %d\n",
6478 stats.num_implicit_edges);
6481 for (i = 1; i < varmap.length (); i++)
6483 varinfo_t vi = get_varinfo (i);
6484 if (!vi->may_have_pointers)
6485 continue;
6486 dump_solution_for_var (outfile, i);
6491 /* Debug points-to information to stderr. */
6493 DEBUG_FUNCTION void
6494 debug_sa_points_to_info (void)
6496 dump_sa_points_to_info (stderr);
6500 /* Initialize the always-existing constraint variables for NULL
6501 ANYTHING, READONLY, and INTEGER */
6503 static void
6504 init_base_vars (void)
6506 struct constraint_expr lhs, rhs;
6507 varinfo_t var_anything;
6508 varinfo_t var_nothing;
6509 varinfo_t var_string;
6510 varinfo_t var_escaped;
6511 varinfo_t var_nonlocal;
6512 varinfo_t var_storedanything;
6513 varinfo_t var_integer;
6515 /* Variable ID zero is reserved and should be NULL. */
6516 varmap.safe_push (NULL);
6518 /* Create the NULL variable, used to represent that a variable points
6519 to NULL. */
6520 var_nothing = new_var_info (NULL_TREE, "NULL");
6521 gcc_assert (var_nothing->id == nothing_id);
6522 var_nothing->is_artificial_var = 1;
6523 var_nothing->offset = 0;
6524 var_nothing->size = ~0;
6525 var_nothing->fullsize = ~0;
6526 var_nothing->is_special_var = 1;
6527 var_nothing->may_have_pointers = 0;
6528 var_nothing->is_global_var = 0;
6530 /* Create the ANYTHING variable, used to represent that a variable
6531 points to some unknown piece of memory. */
6532 var_anything = new_var_info (NULL_TREE, "ANYTHING");
6533 gcc_assert (var_anything->id == anything_id);
6534 var_anything->is_artificial_var = 1;
6535 var_anything->size = ~0;
6536 var_anything->offset = 0;
6537 var_anything->fullsize = ~0;
6538 var_anything->is_special_var = 1;
6540 /* Anything points to anything. This makes deref constraints just
6541 work in the presence of linked list and other p = *p type loops,
6542 by saying that *ANYTHING = ANYTHING. */
6543 lhs.type = SCALAR;
6544 lhs.var = anything_id;
6545 lhs.offset = 0;
6546 rhs.type = ADDRESSOF;
6547 rhs.var = anything_id;
6548 rhs.offset = 0;
6550 /* This specifically does not use process_constraint because
6551 process_constraint ignores all anything = anything constraints, since all
6552 but this one are redundant. */
6553 constraints.safe_push (new_constraint (lhs, rhs));
6555 /* Create the STRING variable, used to represent that a variable
6556 points to a string literal. String literals don't contain
6557 pointers so STRING doesn't point to anything. */
6558 var_string = new_var_info (NULL_TREE, "STRING");
6559 gcc_assert (var_string->id == string_id);
6560 var_string->is_artificial_var = 1;
6561 var_string->offset = 0;
6562 var_string->size = ~0;
6563 var_string->fullsize = ~0;
6564 var_string->is_special_var = 1;
6565 var_string->may_have_pointers = 0;
6567 /* Create the ESCAPED variable, used to represent the set of escaped
6568 memory. */
6569 var_escaped = new_var_info (NULL_TREE, "ESCAPED");
6570 gcc_assert (var_escaped->id == escaped_id);
6571 var_escaped->is_artificial_var = 1;
6572 var_escaped->offset = 0;
6573 var_escaped->size = ~0;
6574 var_escaped->fullsize = ~0;
6575 var_escaped->is_special_var = 0;
6577 /* Create the NONLOCAL variable, used to represent the set of nonlocal
6578 memory. */
6579 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
6580 gcc_assert (var_nonlocal->id == nonlocal_id);
6581 var_nonlocal->is_artificial_var = 1;
6582 var_nonlocal->offset = 0;
6583 var_nonlocal->size = ~0;
6584 var_nonlocal->fullsize = ~0;
6585 var_nonlocal->is_special_var = 1;
6587 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
6588 lhs.type = SCALAR;
6589 lhs.var = escaped_id;
6590 lhs.offset = 0;
6591 rhs.type = DEREF;
6592 rhs.var = escaped_id;
6593 rhs.offset = 0;
6594 process_constraint (new_constraint (lhs, rhs));
6596 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6597 whole variable escapes. */
6598 lhs.type = SCALAR;
6599 lhs.var = escaped_id;
6600 lhs.offset = 0;
6601 rhs.type = SCALAR;
6602 rhs.var = escaped_id;
6603 rhs.offset = UNKNOWN_OFFSET;
6604 process_constraint (new_constraint (lhs, rhs));
6606 /* *ESCAPED = NONLOCAL. This is true because we have to assume
6607 everything pointed to by escaped points to what global memory can
6608 point to. */
6609 lhs.type = DEREF;
6610 lhs.var = escaped_id;
6611 lhs.offset = 0;
6612 rhs.type = SCALAR;
6613 rhs.var = nonlocal_id;
6614 rhs.offset = 0;
6615 process_constraint (new_constraint (lhs, rhs));
6617 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
6618 global memory may point to global memory and escaped memory. */
6619 lhs.type = SCALAR;
6620 lhs.var = nonlocal_id;
6621 lhs.offset = 0;
6622 rhs.type = ADDRESSOF;
6623 rhs.var = nonlocal_id;
6624 rhs.offset = 0;
6625 process_constraint (new_constraint (lhs, rhs));
6626 rhs.type = ADDRESSOF;
6627 rhs.var = escaped_id;
6628 rhs.offset = 0;
6629 process_constraint (new_constraint (lhs, rhs));
6631 /* Create the STOREDANYTHING variable, used to represent the set of
6632 variables stored to *ANYTHING. */
6633 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
6634 gcc_assert (var_storedanything->id == storedanything_id);
6635 var_storedanything->is_artificial_var = 1;
6636 var_storedanything->offset = 0;
6637 var_storedanything->size = ~0;
6638 var_storedanything->fullsize = ~0;
6639 var_storedanything->is_special_var = 0;
6641 /* Create the INTEGER variable, used to represent that a variable points
6642 to what an INTEGER "points to". */
6643 var_integer = new_var_info (NULL_TREE, "INTEGER");
6644 gcc_assert (var_integer->id == integer_id);
6645 var_integer->is_artificial_var = 1;
6646 var_integer->size = ~0;
6647 var_integer->fullsize = ~0;
6648 var_integer->offset = 0;
6649 var_integer->is_special_var = 1;
6651 /* INTEGER = ANYTHING, because we don't know where a dereference of
6652 a random integer will point to. */
6653 lhs.type = SCALAR;
6654 lhs.var = integer_id;
6655 lhs.offset = 0;
6656 rhs.type = ADDRESSOF;
6657 rhs.var = anything_id;
6658 rhs.offset = 0;
6659 process_constraint (new_constraint (lhs, rhs));
6662 /* Initialize things necessary to perform PTA */
6664 static void
6665 init_alias_vars (void)
6667 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6669 bitmap_obstack_initialize (&pta_obstack);
6670 bitmap_obstack_initialize (&oldpta_obstack);
6671 bitmap_obstack_initialize (&predbitmap_obstack);
6673 constraints.create (8);
6674 varmap.create (8);
6675 vi_for_tree = new hash_map<tree, varinfo_t>;
6676 call_stmt_vars = new hash_map<gimple, varinfo_t>;
6678 memset (&stats, 0, sizeof (stats));
6679 shared_bitmap_table = new hash_table<shared_bitmap_hasher> (511);
6680 init_base_vars ();
6682 gcc_obstack_init (&fake_var_decl_obstack);
6684 final_solutions = new hash_map<varinfo_t, pt_solution *>;
6685 gcc_obstack_init (&final_solutions_obstack);
6688 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6689 predecessor edges. */
6691 static void
6692 remove_preds_and_fake_succs (constraint_graph_t graph)
6694 unsigned int i;
6696 /* Clear the implicit ref and address nodes from the successor
6697 lists. */
6698 for (i = 1; i < FIRST_REF_NODE; i++)
6700 if (graph->succs[i])
6701 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6702 FIRST_REF_NODE * 2);
6705 /* Free the successor list for the non-ref nodes. */
6706 for (i = FIRST_REF_NODE + 1; i < graph->size; i++)
6708 if (graph->succs[i])
6709 BITMAP_FREE (graph->succs[i]);
6712 /* Now reallocate the size of the successor list as, and blow away
6713 the predecessor bitmaps. */
6714 graph->size = varmap.length ();
6715 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6717 free (graph->implicit_preds);
6718 graph->implicit_preds = NULL;
6719 free (graph->preds);
6720 graph->preds = NULL;
6721 bitmap_obstack_release (&predbitmap_obstack);
6724 /* Solve the constraint set. */
6726 static void
6727 solve_constraints (void)
6729 struct scc_info *si;
6731 if (dump_file)
6732 fprintf (dump_file,
6733 "\nCollapsing static cycles and doing variable "
6734 "substitution\n");
6736 init_graph (varmap.length () * 2);
6738 if (dump_file)
6739 fprintf (dump_file, "Building predecessor graph\n");
6740 build_pred_graph ();
6742 if (dump_file)
6743 fprintf (dump_file, "Detecting pointer and location "
6744 "equivalences\n");
6745 si = perform_var_substitution (graph);
6747 if (dump_file)
6748 fprintf (dump_file, "Rewriting constraints and unifying "
6749 "variables\n");
6750 rewrite_constraints (graph, si);
6752 build_succ_graph ();
6754 free_var_substitution_info (si);
6756 /* Attach complex constraints to graph nodes. */
6757 move_complex_constraints (graph);
6759 if (dump_file)
6760 fprintf (dump_file, "Uniting pointer but not location equivalent "
6761 "variables\n");
6762 unite_pointer_equivalences (graph);
6764 if (dump_file)
6765 fprintf (dump_file, "Finding indirect cycles\n");
6766 find_indirect_cycles (graph);
6768 /* Implicit nodes and predecessors are no longer necessary at this
6769 point. */
6770 remove_preds_and_fake_succs (graph);
6772 if (dump_file && (dump_flags & TDF_GRAPH))
6774 fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
6775 "in dot format:\n");
6776 dump_constraint_graph (dump_file);
6777 fprintf (dump_file, "\n\n");
6780 if (dump_file)
6781 fprintf (dump_file, "Solving graph\n");
6783 solve_graph (graph);
6785 if (dump_file && (dump_flags & TDF_GRAPH))
6787 fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
6788 "in dot format:\n");
6789 dump_constraint_graph (dump_file);
6790 fprintf (dump_file, "\n\n");
6793 if (dump_file)
6794 dump_sa_points_to_info (dump_file);
6797 /* Create points-to sets for the current function. See the comments
6798 at the start of the file for an algorithmic overview. */
6800 static void
6801 compute_points_to_sets (void)
6803 basic_block bb;
6804 unsigned i;
6805 varinfo_t vi;
6807 timevar_push (TV_TREE_PTA);
6809 init_alias_vars ();
6811 intra_create_variable_infos (cfun);
6813 /* Now walk all statements and build the constraint set. */
6814 FOR_EACH_BB_FN (bb, cfun)
6816 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6817 gsi_next (&gsi))
6819 gphi *phi = gsi.phi ();
6821 if (! virtual_operand_p (gimple_phi_result (phi)))
6822 find_func_aliases (cfun, phi);
6825 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
6826 gsi_next (&gsi))
6828 gimple stmt = gsi_stmt (gsi);
6830 find_func_aliases (cfun, stmt);
6834 if (dump_file)
6836 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6837 dump_constraints (dump_file, 0);
6840 /* From the constraints compute the points-to sets. */
6841 solve_constraints ();
6843 /* Compute the points-to set for ESCAPED used for call-clobber analysis. */
6844 cfun->gimple_df->escaped = find_what_var_points_to (get_varinfo (escaped_id));
6846 /* Make sure the ESCAPED solution (which is used as placeholder in
6847 other solutions) does not reference itself. This simplifies
6848 points-to solution queries. */
6849 cfun->gimple_df->escaped.escaped = 0;
6851 /* Compute the points-to sets for pointer SSA_NAMEs. */
6852 for (i = 0; i < num_ssa_names; ++i)
6854 tree ptr = ssa_name (i);
6855 if (ptr
6856 && POINTER_TYPE_P (TREE_TYPE (ptr)))
6857 find_what_p_points_to (ptr);
6860 /* Compute the call-used/clobbered sets. */
6861 FOR_EACH_BB_FN (bb, cfun)
6863 gimple_stmt_iterator gsi;
6865 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6867 gcall *stmt;
6868 struct pt_solution *pt;
6870 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
6871 if (!stmt)
6872 continue;
6874 pt = gimple_call_use_set (stmt);
6875 if (gimple_call_flags (stmt) & ECF_CONST)
6876 memset (pt, 0, sizeof (struct pt_solution));
6877 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6879 *pt = find_what_var_points_to (vi);
6880 /* Escaped (and thus nonlocal) variables are always
6881 implicitly used by calls. */
6882 /* ??? ESCAPED can be empty even though NONLOCAL
6883 always escaped. */
6884 pt->nonlocal = 1;
6885 pt->escaped = 1;
6887 else
6889 /* If there is nothing special about this call then
6890 we have made everything that is used also escape. */
6891 *pt = cfun->gimple_df->escaped;
6892 pt->nonlocal = 1;
6895 pt = gimple_call_clobber_set (stmt);
6896 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6897 memset (pt, 0, sizeof (struct pt_solution));
6898 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6900 *pt = find_what_var_points_to (vi);
6901 /* Escaped (and thus nonlocal) variables are always
6902 implicitly clobbered by calls. */
6903 /* ??? ESCAPED can be empty even though NONLOCAL
6904 always escaped. */
6905 pt->nonlocal = 1;
6906 pt->escaped = 1;
6908 else
6910 /* If there is nothing special about this call then
6911 we have made everything that is used also escape. */
6912 *pt = cfun->gimple_df->escaped;
6913 pt->nonlocal = 1;
6918 timevar_pop (TV_TREE_PTA);
6922 /* Delete created points-to sets. */
6924 static void
6925 delete_points_to_sets (void)
6927 unsigned int i;
6929 delete shared_bitmap_table;
6930 shared_bitmap_table = NULL;
6931 if (dump_file && (dump_flags & TDF_STATS))
6932 fprintf (dump_file, "Points to sets created:%d\n",
6933 stats.points_to_sets_created);
6935 delete vi_for_tree;
6936 delete call_stmt_vars;
6937 bitmap_obstack_release (&pta_obstack);
6938 constraints.release ();
6940 for (i = 0; i < graph->size; i++)
6941 graph->complex[i].release ();
6942 free (graph->complex);
6944 free (graph->rep);
6945 free (graph->succs);
6946 free (graph->pe);
6947 free (graph->pe_rep);
6948 free (graph->indirect_cycles);
6949 free (graph);
6951 varmap.release ();
6952 variable_info_pool.release ();
6953 constraint_pool.release ();
6955 obstack_free (&fake_var_decl_obstack, NULL);
6957 delete final_solutions;
6958 obstack_free (&final_solutions_obstack, NULL);
6961 /* Mark "other" loads and stores as belonging to CLIQUE and with
6962 base zero. */
6964 static bool
6965 visit_loadstore (gimple, tree base, tree ref, void *clique_)
6967 unsigned short clique = (uintptr_t)clique_;
6968 if (TREE_CODE (base) == MEM_REF
6969 || TREE_CODE (base) == TARGET_MEM_REF)
6971 tree ptr = TREE_OPERAND (base, 0);
6972 if (TREE_CODE (ptr) == SSA_NAME)
6974 /* ??? We need to make sure 'ptr' doesn't include any of
6975 the restrict tags in its points-to set. */
6976 return false;
6979 /* For now let decls through. */
6981 /* Do not overwrite existing cliques (that includes clique, base
6982 pairs we just set). */
6983 if (MR_DEPENDENCE_CLIQUE (base) == 0)
6985 MR_DEPENDENCE_CLIQUE (base) = clique;
6986 MR_DEPENDENCE_BASE (base) = 0;
6990 /* For plain decl accesses see whether they are accesses to globals
6991 and rewrite them to MEM_REFs with { clique, 0 }. */
6992 if (TREE_CODE (base) == VAR_DECL
6993 && is_global_var (base)
6994 /* ??? We can't rewrite a plain decl with the walk_stmt_load_store
6995 ops callback. */
6996 && base != ref)
6998 tree *basep = &ref;
6999 while (handled_component_p (*basep))
7000 basep = &TREE_OPERAND (*basep, 0);
7001 gcc_assert (TREE_CODE (*basep) == VAR_DECL);
7002 tree ptr = build_fold_addr_expr (*basep);
7003 tree zero = build_int_cst (TREE_TYPE (ptr), 0);
7004 *basep = build2 (MEM_REF, TREE_TYPE (*basep), ptr, zero);
7005 MR_DEPENDENCE_CLIQUE (*basep) = clique;
7006 MR_DEPENDENCE_BASE (*basep) = 0;
7009 return false;
7012 /* If REF is a MEM_REF then assign a clique, base pair to it, updating
7013 CLIQUE, *RESTRICT_VAR and LAST_RUID. Return whether dependence info
7014 was assigned to REF. */
7016 static bool
7017 maybe_set_dependence_info (tree ref, tree ptr,
7018 unsigned short &clique, varinfo_t restrict_var,
7019 unsigned short &last_ruid)
7021 while (handled_component_p (ref))
7022 ref = TREE_OPERAND (ref, 0);
7023 if ((TREE_CODE (ref) == MEM_REF
7024 || TREE_CODE (ref) == TARGET_MEM_REF)
7025 && TREE_OPERAND (ref, 0) == ptr)
7027 /* Do not overwrite existing cliques. This avoids overwriting dependence
7028 info inlined from a function with restrict parameters inlined
7029 into a function with restrict parameters. This usually means we
7030 prefer to be precise in innermost loops. */
7031 if (MR_DEPENDENCE_CLIQUE (ref) == 0)
7033 if (clique == 0)
7034 clique = ++cfun->last_clique;
7035 if (restrict_var->ruid == 0)
7036 restrict_var->ruid = ++last_ruid;
7037 MR_DEPENDENCE_CLIQUE (ref) = clique;
7038 MR_DEPENDENCE_BASE (ref) = restrict_var->ruid;
7039 return true;
7042 return false;
7045 /* Compute the set of independend memory references based on restrict
7046 tags and their conservative propagation to the points-to sets. */
7048 static void
7049 compute_dependence_clique (void)
7051 unsigned short clique = 0;
7052 unsigned short last_ruid = 0;
7053 for (unsigned i = 0; i < num_ssa_names; ++i)
7055 tree ptr = ssa_name (i);
7056 if (!ptr || !POINTER_TYPE_P (TREE_TYPE (ptr)))
7057 continue;
7059 /* Avoid all this when ptr is not dereferenced? */
7060 tree p = ptr;
7061 if (SSA_NAME_IS_DEFAULT_DEF (ptr)
7062 && (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
7063 || TREE_CODE (SSA_NAME_VAR (ptr)) == RESULT_DECL))
7064 p = SSA_NAME_VAR (ptr);
7065 varinfo_t vi = lookup_vi_for_tree (p);
7066 if (!vi)
7067 continue;
7068 vi = get_varinfo (find (vi->id));
7069 bitmap_iterator bi;
7070 unsigned j;
7071 varinfo_t restrict_var = NULL;
7072 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, j, bi)
7074 varinfo_t oi = get_varinfo (j);
7075 if (oi->is_restrict_var)
7077 if (restrict_var)
7079 if (dump_file && (dump_flags & TDF_DETAILS))
7081 fprintf (dump_file, "found restrict pointed-to "
7082 "for ");
7083 print_generic_expr (dump_file, ptr, 0);
7084 fprintf (dump_file, " but not exclusively\n");
7086 restrict_var = NULL;
7087 break;
7089 restrict_var = oi;
7091 /* NULL is the only other valid points-to entry. */
7092 else if (oi->id != nothing_id)
7094 restrict_var = NULL;
7095 break;
7098 /* Ok, found that ptr must(!) point to a single(!) restrict
7099 variable. */
7100 /* ??? PTA isn't really a proper propagation engine to compute
7101 this property.
7102 ??? We could handle merging of two restricts by unifying them. */
7103 if (restrict_var)
7105 /* Now look at possible dereferences of ptr. */
7106 imm_use_iterator ui;
7107 gimple use_stmt;
7108 FOR_EACH_IMM_USE_STMT (use_stmt, ui, ptr)
7110 /* ??? Calls and asms. */
7111 if (!gimple_assign_single_p (use_stmt))
7112 continue;
7113 maybe_set_dependence_info (gimple_assign_lhs (use_stmt), ptr,
7114 clique, restrict_var, last_ruid);
7115 maybe_set_dependence_info (gimple_assign_rhs1 (use_stmt), ptr,
7116 clique, restrict_var, last_ruid);
7121 if (clique == 0)
7122 return;
7124 /* Assign the BASE id zero to all accesses not based on a restrict
7125 pointer. That way they get disabiguated against restrict
7126 accesses but not against each other. */
7127 /* ??? For restricts derived from globals (thus not incoming
7128 parameters) we can't restrict scoping properly thus the following
7129 is too aggressive there. For now we have excluded those globals from
7130 getting into the MR_DEPENDENCE machinery. */
7131 basic_block bb;
7132 FOR_EACH_BB_FN (bb, cfun)
7133 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7134 !gsi_end_p (gsi); gsi_next (&gsi))
7136 gimple stmt = gsi_stmt (gsi);
7137 walk_stmt_load_store_ops (stmt, (void *)(uintptr_t)clique,
7138 visit_loadstore, visit_loadstore);
7142 /* Compute points-to information for every SSA_NAME pointer in the
7143 current function and compute the transitive closure of escaped
7144 variables to re-initialize the call-clobber states of local variables. */
7146 unsigned int
7147 compute_may_aliases (void)
7149 if (cfun->gimple_df->ipa_pta)
7151 if (dump_file)
7153 fprintf (dump_file, "\nNot re-computing points-to information "
7154 "because IPA points-to information is available.\n\n");
7156 /* But still dump what we have remaining it. */
7157 dump_alias_info (dump_file);
7160 return 0;
7163 /* For each pointer P_i, determine the sets of variables that P_i may
7164 point-to. Compute the reachability set of escaped and call-used
7165 variables. */
7166 compute_points_to_sets ();
7168 /* Debugging dumps. */
7169 if (dump_file)
7170 dump_alias_info (dump_file);
7172 /* Compute restrict-based memory disambiguations. */
7173 compute_dependence_clique ();
7175 /* Deallocate memory used by aliasing data structures and the internal
7176 points-to solution. */
7177 delete_points_to_sets ();
7179 gcc_assert (!need_ssa_update_p (cfun));
7181 return 0;
7184 /* A dummy pass to cause points-to information to be computed via
7185 TODO_rebuild_alias. */
7187 namespace {
7189 const pass_data pass_data_build_alias =
7191 GIMPLE_PASS, /* type */
7192 "alias", /* name */
7193 OPTGROUP_NONE, /* optinfo_flags */
7194 TV_NONE, /* tv_id */
7195 ( PROP_cfg | PROP_ssa ), /* properties_required */
7196 0, /* properties_provided */
7197 0, /* properties_destroyed */
7198 0, /* todo_flags_start */
7199 TODO_rebuild_alias, /* todo_flags_finish */
7202 class pass_build_alias : public gimple_opt_pass
7204 public:
7205 pass_build_alias (gcc::context *ctxt)
7206 : gimple_opt_pass (pass_data_build_alias, ctxt)
7209 /* opt_pass methods: */
7210 virtual bool gate (function *) { return flag_tree_pta; }
7212 }; // class pass_build_alias
7214 } // anon namespace
7216 gimple_opt_pass *
7217 make_pass_build_alias (gcc::context *ctxt)
7219 return new pass_build_alias (ctxt);
7222 /* A dummy pass to cause points-to information to be computed via
7223 TODO_rebuild_alias. */
7225 namespace {
7227 const pass_data pass_data_build_ealias =
7229 GIMPLE_PASS, /* type */
7230 "ealias", /* name */
7231 OPTGROUP_NONE, /* optinfo_flags */
7232 TV_NONE, /* tv_id */
7233 ( PROP_cfg | PROP_ssa ), /* properties_required */
7234 0, /* properties_provided */
7235 0, /* properties_destroyed */
7236 0, /* todo_flags_start */
7237 TODO_rebuild_alias, /* todo_flags_finish */
7240 class pass_build_ealias : public gimple_opt_pass
7242 public:
7243 pass_build_ealias (gcc::context *ctxt)
7244 : gimple_opt_pass (pass_data_build_ealias, ctxt)
7247 /* opt_pass methods: */
7248 virtual bool gate (function *) { return flag_tree_pta; }
7250 }; // class pass_build_ealias
7252 } // anon namespace
7254 gimple_opt_pass *
7255 make_pass_build_ealias (gcc::context *ctxt)
7257 return new pass_build_ealias (ctxt);
7261 /* IPA PTA solutions for ESCAPED. */
7262 struct pt_solution ipa_escaped_pt
7263 = { true, false, false, false, false, false, false, false, NULL };
7265 /* Associate node with varinfo DATA. Worker for
7266 cgraph_for_node_and_aliases. */
7267 static bool
7268 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
7270 if ((node->alias || node->thunk.thunk_p)
7271 && node->analyzed)
7272 insert_vi_for_tree (node->decl, (varinfo_t)data);
7273 return false;
7276 /* Execute the driver for IPA PTA. */
7277 static unsigned int
7278 ipa_pta_execute (void)
7280 struct cgraph_node *node;
7281 varpool_node *var;
7282 int from;
7284 in_ipa_mode = 1;
7286 init_alias_vars ();
7288 if (dump_file && (dump_flags & TDF_DETAILS))
7290 symtab_node::dump_table (dump_file);
7291 fprintf (dump_file, "\n");
7294 /* Build the constraints. */
7295 FOR_EACH_DEFINED_FUNCTION (node)
7297 varinfo_t vi;
7298 /* Nodes without a body are not interesting. Especially do not
7299 visit clones at this point for now - we get duplicate decls
7300 there for inline clones at least. */
7301 if (!node->has_gimple_body_p () || node->global.inlined_to)
7302 continue;
7303 node->get_body ();
7305 gcc_assert (!node->clone_of);
7307 vi = create_function_info_for (node->decl,
7308 alias_get_name (node->decl));
7309 node->call_for_symbol_thunks_and_aliases
7310 (associate_varinfo_to_alias, vi, true);
7313 /* Create constraints for global variables and their initializers. */
7314 FOR_EACH_VARIABLE (var)
7316 if (var->alias && var->analyzed)
7317 continue;
7319 get_vi_for_tree (var->decl);
7322 if (dump_file)
7324 fprintf (dump_file,
7325 "Generating constraints for global initializers\n\n");
7326 dump_constraints (dump_file, 0);
7327 fprintf (dump_file, "\n");
7329 from = constraints.length ();
7331 FOR_EACH_DEFINED_FUNCTION (node)
7333 struct function *func;
7334 basic_block bb;
7336 /* Nodes without a body are not interesting. */
7337 if (!node->has_gimple_body_p () || node->clone_of)
7338 continue;
7340 if (dump_file)
7342 fprintf (dump_file,
7343 "Generating constraints for %s", node->name ());
7344 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7345 fprintf (dump_file, " (%s)",
7346 IDENTIFIER_POINTER
7347 (DECL_ASSEMBLER_NAME (node->decl)));
7348 fprintf (dump_file, "\n");
7351 func = DECL_STRUCT_FUNCTION (node->decl);
7352 gcc_assert (cfun == NULL);
7354 /* For externally visible or attribute used annotated functions use
7355 local constraints for their arguments.
7356 For local functions we see all callers and thus do not need initial
7357 constraints for parameters. */
7358 if (node->used_from_other_partition
7359 || node->externally_visible
7360 || node->force_output
7361 || node->address_taken)
7363 intra_create_variable_infos (func);
7365 /* We also need to make function return values escape. Nothing
7366 escapes by returning from main though. */
7367 if (!MAIN_NAME_P (DECL_NAME (node->decl)))
7369 varinfo_t fi, rvi;
7370 fi = lookup_vi_for_tree (node->decl);
7371 rvi = first_vi_for_offset (fi, fi_result);
7372 if (rvi && rvi->offset == fi_result)
7374 struct constraint_expr includes;
7375 struct constraint_expr var;
7376 includes.var = escaped_id;
7377 includes.offset = 0;
7378 includes.type = SCALAR;
7379 var.var = rvi->id;
7380 var.offset = 0;
7381 var.type = SCALAR;
7382 process_constraint (new_constraint (includes, var));
7387 /* Build constriants for the function body. */
7388 FOR_EACH_BB_FN (bb, func)
7390 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7391 gsi_next (&gsi))
7393 gphi *phi = gsi.phi ();
7395 if (! virtual_operand_p (gimple_phi_result (phi)))
7396 find_func_aliases (func, phi);
7399 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7400 gsi_next (&gsi))
7402 gimple stmt = gsi_stmt (gsi);
7404 find_func_aliases (func, stmt);
7405 find_func_clobbers (func, stmt);
7409 if (dump_file)
7411 fprintf (dump_file, "\n");
7412 dump_constraints (dump_file, from);
7413 fprintf (dump_file, "\n");
7415 from = constraints.length ();
7418 /* From the constraints compute the points-to sets. */
7419 solve_constraints ();
7421 /* Compute the global points-to sets for ESCAPED.
7422 ??? Note that the computed escape set is not correct
7423 for the whole unit as we fail to consider graph edges to
7424 externally visible functions. */
7425 ipa_escaped_pt = find_what_var_points_to (get_varinfo (escaped_id));
7427 /* Make sure the ESCAPED solution (which is used as placeholder in
7428 other solutions) does not reference itself. This simplifies
7429 points-to solution queries. */
7430 ipa_escaped_pt.ipa_escaped = 0;
7432 /* Assign the points-to sets to the SSA names in the unit. */
7433 FOR_EACH_DEFINED_FUNCTION (node)
7435 tree ptr;
7436 struct function *fn;
7437 unsigned i;
7438 basic_block bb;
7440 /* Nodes without a body are not interesting. */
7441 if (!node->has_gimple_body_p () || node->clone_of)
7442 continue;
7444 fn = DECL_STRUCT_FUNCTION (node->decl);
7446 /* Compute the points-to sets for pointer SSA_NAMEs. */
7447 FOR_EACH_VEC_ELT (*fn->gimple_df->ssa_names, i, ptr)
7449 if (ptr
7450 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7451 find_what_p_points_to (ptr);
7454 /* Compute the call-use and call-clobber sets for indirect calls
7455 and calls to external functions. */
7456 FOR_EACH_BB_FN (bb, fn)
7458 gimple_stmt_iterator gsi;
7460 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7462 gcall *stmt;
7463 struct pt_solution *pt;
7464 varinfo_t vi, fi;
7465 tree decl;
7467 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7468 if (!stmt)
7469 continue;
7471 /* Handle direct calls to functions with body. */
7472 decl = gimple_call_fndecl (stmt);
7473 if (decl
7474 && (fi = lookup_vi_for_tree (decl))
7475 && fi->is_fn_info)
7477 *gimple_call_clobber_set (stmt)
7478 = find_what_var_points_to
7479 (first_vi_for_offset (fi, fi_clobbers));
7480 *gimple_call_use_set (stmt)
7481 = find_what_var_points_to
7482 (first_vi_for_offset (fi, fi_uses));
7484 /* Handle direct calls to external functions. */
7485 else if (decl)
7487 pt = gimple_call_use_set (stmt);
7488 if (gimple_call_flags (stmt) & ECF_CONST)
7489 memset (pt, 0, sizeof (struct pt_solution));
7490 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7492 *pt = find_what_var_points_to (vi);
7493 /* Escaped (and thus nonlocal) variables are always
7494 implicitly used by calls. */
7495 /* ??? ESCAPED can be empty even though NONLOCAL
7496 always escaped. */
7497 pt->nonlocal = 1;
7498 pt->ipa_escaped = 1;
7500 else
7502 /* If there is nothing special about this call then
7503 we have made everything that is used also escape. */
7504 *pt = ipa_escaped_pt;
7505 pt->nonlocal = 1;
7508 pt = gimple_call_clobber_set (stmt);
7509 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7510 memset (pt, 0, sizeof (struct pt_solution));
7511 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7513 *pt = find_what_var_points_to (vi);
7514 /* Escaped (and thus nonlocal) variables are always
7515 implicitly clobbered by calls. */
7516 /* ??? ESCAPED can be empty even though NONLOCAL
7517 always escaped. */
7518 pt->nonlocal = 1;
7519 pt->ipa_escaped = 1;
7521 else
7523 /* If there is nothing special about this call then
7524 we have made everything that is used also escape. */
7525 *pt = ipa_escaped_pt;
7526 pt->nonlocal = 1;
7529 /* Handle indirect calls. */
7530 else if (!decl
7531 && (fi = get_fi_for_callee (stmt)))
7533 /* We need to accumulate all clobbers/uses of all possible
7534 callees. */
7535 fi = get_varinfo (find (fi->id));
7536 /* If we cannot constrain the set of functions we'll end up
7537 calling we end up using/clobbering everything. */
7538 if (bitmap_bit_p (fi->solution, anything_id)
7539 || bitmap_bit_p (fi->solution, nonlocal_id)
7540 || bitmap_bit_p (fi->solution, escaped_id))
7542 pt_solution_reset (gimple_call_clobber_set (stmt));
7543 pt_solution_reset (gimple_call_use_set (stmt));
7545 else
7547 bitmap_iterator bi;
7548 unsigned i;
7549 struct pt_solution *uses, *clobbers;
7551 uses = gimple_call_use_set (stmt);
7552 clobbers = gimple_call_clobber_set (stmt);
7553 memset (uses, 0, sizeof (struct pt_solution));
7554 memset (clobbers, 0, sizeof (struct pt_solution));
7555 EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7557 struct pt_solution sol;
7559 vi = get_varinfo (i);
7560 if (!vi->is_fn_info)
7562 /* ??? We could be more precise here? */
7563 uses->nonlocal = 1;
7564 uses->ipa_escaped = 1;
7565 clobbers->nonlocal = 1;
7566 clobbers->ipa_escaped = 1;
7567 continue;
7570 if (!uses->anything)
7572 sol = find_what_var_points_to
7573 (first_vi_for_offset (vi, fi_uses));
7574 pt_solution_ior_into (uses, &sol);
7576 if (!clobbers->anything)
7578 sol = find_what_var_points_to
7579 (first_vi_for_offset (vi, fi_clobbers));
7580 pt_solution_ior_into (clobbers, &sol);
7588 fn->gimple_df->ipa_pta = true;
7591 delete_points_to_sets ();
7593 in_ipa_mode = 0;
7595 return 0;
7598 namespace {
7600 const pass_data pass_data_ipa_pta =
7602 SIMPLE_IPA_PASS, /* type */
7603 "pta", /* name */
7604 OPTGROUP_NONE, /* optinfo_flags */
7605 TV_IPA_PTA, /* tv_id */
7606 0, /* properties_required */
7607 0, /* properties_provided */
7608 0, /* properties_destroyed */
7609 0, /* todo_flags_start */
7610 0, /* todo_flags_finish */
7613 class pass_ipa_pta : public simple_ipa_opt_pass
7615 public:
7616 pass_ipa_pta (gcc::context *ctxt)
7617 : simple_ipa_opt_pass (pass_data_ipa_pta, ctxt)
7620 /* opt_pass methods: */
7621 virtual bool gate (function *)
7623 return (optimize
7624 && flag_ipa_pta
7625 /* Don't bother doing anything if the program has errors. */
7626 && !seen_error ());
7629 virtual unsigned int execute (function *) { return ipa_pta_execute (); }
7631 }; // class pass_ipa_pta
7633 } // anon namespace
7635 simple_ipa_opt_pass *
7636 make_pass_ipa_pta (gcc::context *ctxt)
7638 return new pass_ipa_pta (ctxt);