Daily bump.
[official-gcc.git] / gcc / tree-ssa-structalias.c
blob07736e33923192d1b41e61b3c32f006e99d139c9
1 /* Tree based points-to analysis
2 Copyright (C) 2005-2016 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dberlin@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "alloc-pool.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "tree-pretty-print.h"
33 #include "diagnostic-core.h"
34 #include "fold-const.h"
35 #include "stor-layout.h"
36 #include "stmt.h"
37 #include "gimple-iterator.h"
38 #include "tree-into-ssa.h"
39 #include "tree-dfa.h"
40 #include "params.h"
41 #include "gimple-walk.h"
43 /* The idea behind this analyzer is to generate set constraints from the
44 program, then solve the resulting constraints in order to generate the
45 points-to sets.
47 Set constraints are a way of modeling program analysis problems that
48 involve sets. They consist of an inclusion constraint language,
49 describing the variables (each variable is a set) and operations that
50 are involved on the variables, and a set of rules that derive facts
51 from these operations. To solve a system of set constraints, you derive
52 all possible facts under the rules, which gives you the correct sets
53 as a consequence.
55 See "Efficient Field-sensitive pointer analysis for C" by "David
56 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
57 http://citeseer.ist.psu.edu/pearce04efficient.html
59 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
60 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
61 http://citeseer.ist.psu.edu/heintze01ultrafast.html
63 There are three types of real constraint expressions, DEREF,
64 ADDRESSOF, and SCALAR. Each constraint expression consists
65 of a constraint type, a variable, and an offset.
67 SCALAR is a constraint expression type used to represent x, whether
68 it appears on the LHS or the RHS of a statement.
69 DEREF is a constraint expression type used to represent *x, whether
70 it appears on the LHS or the RHS of a statement.
71 ADDRESSOF is a constraint expression used to represent &x, whether
72 it appears on the LHS or the RHS of a statement.
74 Each pointer variable in the program is assigned an integer id, and
75 each field of a structure variable is assigned an integer id as well.
77 Structure variables are linked to their list of fields through a "next
78 field" in each variable that points to the next field in offset
79 order.
80 Each variable for a structure field has
82 1. "size", that tells the size in bits of that field.
83 2. "fullsize, that tells the size in bits of the entire structure.
84 3. "offset", that tells the offset in bits from the beginning of the
85 structure to this field.
87 Thus,
88 struct f
90 int a;
91 int b;
92 } foo;
93 int *bar;
95 looks like
97 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
98 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
99 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
102 In order to solve the system of set constraints, the following is
103 done:
105 1. Each constraint variable x has a solution set associated with it,
106 Sol(x).
108 2. Constraints are separated into direct, copy, and complex.
109 Direct constraints are ADDRESSOF constraints that require no extra
110 processing, such as P = &Q
111 Copy constraints are those of the form P = Q.
112 Complex constraints are all the constraints involving dereferences
113 and offsets (including offsetted copies).
115 3. All direct constraints of the form P = &Q are processed, such
116 that Q is added to Sol(P)
118 4. All complex constraints for a given constraint variable are stored in a
119 linked list attached to that variable's node.
121 5. A directed graph is built out of the copy constraints. Each
122 constraint variable is a node in the graph, and an edge from
123 Q to P is added for each copy constraint of the form P = Q
125 6. The graph is then walked, and solution sets are
126 propagated along the copy edges, such that an edge from Q to P
127 causes Sol(P) <- Sol(P) union Sol(Q).
129 7. As we visit each node, all complex constraints associated with
130 that node are processed by adding appropriate copy edges to the graph, or the
131 appropriate variables to the solution set.
133 8. The process of walking the graph is iterated until no solution
134 sets change.
136 Prior to walking the graph in steps 6 and 7, We perform static
137 cycle elimination on the constraint graph, as well
138 as off-line variable substitution.
140 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
141 on and turned into anything), but isn't. You can just see what offset
142 inside the pointed-to struct it's going to access.
144 TODO: Constant bounded arrays can be handled as if they were structs of the
145 same number of elements.
147 TODO: Modeling heap and incoming pointers becomes much better if we
148 add fields to them as we discover them, which we could do.
150 TODO: We could handle unions, but to be honest, it's probably not
151 worth the pain or slowdown. */
153 /* IPA-PTA optimizations possible.
155 When the indirect function called is ANYTHING we can add disambiguation
156 based on the function signatures (or simply the parameter count which
157 is the varinfo size). We also do not need to consider functions that
158 do not have their address taken.
160 The is_global_var bit which marks escape points is overly conservative
161 in IPA mode. Split it to is_escape_point and is_global_var - only
162 externally visible globals are escape points in IPA mode.
163 There is now is_ipa_escape_point but this is only used in a few
164 selected places.
166 The way we introduce DECL_PT_UID to avoid fixing up all points-to
167 sets in the translation unit when we copy a DECL during inlining
168 pessimizes precision. The advantage is that the DECL_PT_UID keeps
169 compile-time and memory usage overhead low - the points-to sets
170 do not grow or get unshared as they would during a fixup phase.
171 An alternative solution is to delay IPA PTA until after all
172 inlining transformations have been applied.
174 The way we propagate clobber/use information isn't optimized.
175 It should use a new complex constraint that properly filters
176 out local variables of the callee (though that would make
177 the sets invalid after inlining). OTOH we might as well
178 admit defeat to WHOPR and simply do all the clobber/use analysis
179 and propagation after PTA finished but before we threw away
180 points-to information for memory variables. WHOPR and PTA
181 do not play along well anyway - the whole constraint solving
182 would need to be done in WPA phase and it will be very interesting
183 to apply the results to local SSA names during LTRANS phase.
185 We probably should compute a per-function unit-ESCAPE solution
186 propagating it simply like the clobber / uses solutions. The
187 solution can go alongside the non-IPA espaced solution and be
188 used to query which vars escape the unit through a function.
189 This is also required to make the escaped-HEAP trick work in IPA mode.
191 We never put function decls in points-to sets so we do not
192 keep the set of called functions for indirect calls.
194 And probably more. */
196 static bool use_field_sensitive = true;
197 static int in_ipa_mode = 0;
199 /* Used for predecessor bitmaps. */
200 static bitmap_obstack predbitmap_obstack;
202 /* Used for points-to sets. */
203 static bitmap_obstack pta_obstack;
205 /* Used for oldsolution members of variables. */
206 static bitmap_obstack oldpta_obstack;
208 /* Used for per-solver-iteration bitmaps. */
209 static bitmap_obstack iteration_obstack;
211 static unsigned int create_variable_info_for (tree, const char *, bool);
212 typedef struct constraint_graph *constraint_graph_t;
213 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
215 struct constraint;
216 typedef struct constraint *constraint_t;
219 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
220 if (a) \
221 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
223 static struct constraint_stats
225 unsigned int total_vars;
226 unsigned int nonpointer_vars;
227 unsigned int unified_vars_static;
228 unsigned int unified_vars_dynamic;
229 unsigned int iterations;
230 unsigned int num_edges;
231 unsigned int num_implicit_edges;
232 unsigned int points_to_sets_created;
233 } stats;
235 struct variable_info
237 /* ID of this variable */
238 unsigned int id;
240 /* True if this is a variable created by the constraint analysis, such as
241 heap variables and constraints we had to break up. */
242 unsigned int is_artificial_var : 1;
244 /* True if this is a special variable whose solution set should not be
245 changed. */
246 unsigned int is_special_var : 1;
248 /* True for variables whose size is not known or variable. */
249 unsigned int is_unknown_size_var : 1;
251 /* True for (sub-)fields that represent a whole variable. */
252 unsigned int is_full_var : 1;
254 /* True if this is a heap variable. */
255 unsigned int is_heap_var : 1;
257 /* True if this field may contain pointers. */
258 unsigned int may_have_pointers : 1;
260 /* True if this field has only restrict qualified pointers. */
261 unsigned int only_restrict_pointers : 1;
263 /* True if this represents a heap var created for a restrict qualified
264 pointer. */
265 unsigned int is_restrict_var : 1;
267 /* True if this represents a global variable. */
268 unsigned int is_global_var : 1;
270 /* True if this represents a module escape point for IPA analysis. */
271 unsigned int is_ipa_escape_point : 1;
273 /* True if this represents a IPA function info. */
274 unsigned int is_fn_info : 1;
276 /* ??? Store somewhere better. */
277 unsigned short ruid;
279 /* The ID of the variable for the next field in this structure
280 or zero for the last field in this structure. */
281 unsigned next;
283 /* The ID of the variable for the first field in this structure. */
284 unsigned head;
286 /* Offset of this variable, in bits, from the base variable */
287 unsigned HOST_WIDE_INT offset;
289 /* Size of the variable, in bits. */
290 unsigned HOST_WIDE_INT size;
292 /* Full size of the base variable, in bits. */
293 unsigned HOST_WIDE_INT fullsize;
295 /* Name of this variable */
296 const char *name;
298 /* Tree that this variable is associated with. */
299 tree decl;
301 /* Points-to set for this variable. */
302 bitmap solution;
304 /* Old points-to set for this variable. */
305 bitmap oldsolution;
307 typedef struct variable_info *varinfo_t;
309 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
310 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
311 unsigned HOST_WIDE_INT);
312 static varinfo_t lookup_vi_for_tree (tree);
313 static inline bool type_can_have_subvars (const_tree);
314 static void make_param_constraints (varinfo_t);
316 /* Pool of variable info structures. */
317 static object_allocator<variable_info> variable_info_pool
318 ("Variable info pool");
320 /* Map varinfo to final pt_solution. */
321 static hash_map<varinfo_t, pt_solution *> *final_solutions;
322 struct obstack final_solutions_obstack;
324 /* Table of variable info structures for constraint variables.
325 Indexed directly by variable info id. */
326 static vec<varinfo_t> varmap;
328 /* Return the varmap element N */
330 static inline varinfo_t
331 get_varinfo (unsigned int n)
333 return varmap[n];
336 /* Return the next variable in the list of sub-variables of VI
337 or NULL if VI is the last sub-variable. */
339 static inline varinfo_t
340 vi_next (varinfo_t vi)
342 return get_varinfo (vi->next);
345 /* Static IDs for the special variables. Variable ID zero is unused
346 and used as terminator for the sub-variable chain. */
347 enum { nothing_id = 1, anything_id = 2, string_id = 3,
348 escaped_id = 4, nonlocal_id = 5,
349 storedanything_id = 6, integer_id = 7 };
351 /* Return a new variable info structure consisting for a variable
352 named NAME, and using constraint graph node NODE. Append it
353 to the vector of variable info structures. */
355 static varinfo_t
356 new_var_info (tree t, const char *name, bool add_id)
358 unsigned index = varmap.length ();
359 varinfo_t ret = variable_info_pool.allocate ();
361 if (dump_file && add_id)
363 char *tempname = xasprintf ("%s(%d)", name, index);
364 name = ggc_strdup (tempname);
365 free (tempname);
368 ret->id = index;
369 ret->name = name;
370 ret->decl = t;
371 /* Vars without decl are artificial and do not have sub-variables. */
372 ret->is_artificial_var = (t == NULL_TREE);
373 ret->is_special_var = false;
374 ret->is_unknown_size_var = false;
375 ret->is_full_var = (t == NULL_TREE);
376 ret->is_heap_var = false;
377 ret->may_have_pointers = true;
378 ret->only_restrict_pointers = false;
379 ret->is_restrict_var = false;
380 ret->ruid = 0;
381 ret->is_global_var = (t == NULL_TREE);
382 ret->is_ipa_escape_point = false;
383 ret->is_fn_info = false;
384 if (t && DECL_P (t))
385 ret->is_global_var = (is_global_var (t)
386 /* We have to treat even local register variables
387 as escape points. */
388 || (TREE_CODE (t) == VAR_DECL
389 && DECL_HARD_REGISTER (t)));
390 ret->solution = BITMAP_ALLOC (&pta_obstack);
391 ret->oldsolution = NULL;
392 ret->next = 0;
393 ret->head = ret->id;
395 stats.total_vars++;
397 varmap.safe_push (ret);
399 return ret;
402 /* A map mapping call statements to per-stmt variables for uses
403 and clobbers specific to the call. */
404 static hash_map<gimple *, varinfo_t> *call_stmt_vars;
406 /* Lookup or create the variable for the call statement CALL. */
408 static varinfo_t
409 get_call_vi (gcall *call)
411 varinfo_t vi, vi2;
413 bool existed;
414 varinfo_t *slot_p = &call_stmt_vars->get_or_insert (call, &existed);
415 if (existed)
416 return *slot_p;
418 vi = new_var_info (NULL_TREE, "CALLUSED", true);
419 vi->offset = 0;
420 vi->size = 1;
421 vi->fullsize = 2;
422 vi->is_full_var = true;
424 vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED", true);
425 vi2->offset = 1;
426 vi2->size = 1;
427 vi2->fullsize = 2;
428 vi2->is_full_var = true;
430 vi->next = vi2->id;
432 *slot_p = vi;
433 return vi;
436 /* Lookup the variable for the call statement CALL representing
437 the uses. Returns NULL if there is nothing special about this call. */
439 static varinfo_t
440 lookup_call_use_vi (gcall *call)
442 varinfo_t *slot_p = call_stmt_vars->get (call);
443 if (slot_p)
444 return *slot_p;
446 return NULL;
449 /* Lookup the variable for the call statement CALL representing
450 the clobbers. Returns NULL if there is nothing special about this call. */
452 static varinfo_t
453 lookup_call_clobber_vi (gcall *call)
455 varinfo_t uses = lookup_call_use_vi (call);
456 if (!uses)
457 return NULL;
459 return vi_next (uses);
462 /* Lookup or create the variable for the call statement CALL representing
463 the uses. */
465 static varinfo_t
466 get_call_use_vi (gcall *call)
468 return get_call_vi (call);
471 /* Lookup or create the variable for the call statement CALL representing
472 the clobbers. */
474 static varinfo_t ATTRIBUTE_UNUSED
475 get_call_clobber_vi (gcall *call)
477 return vi_next (get_call_vi (call));
481 enum constraint_expr_type {SCALAR, DEREF, ADDRESSOF};
483 /* An expression that appears in a constraint. */
485 struct constraint_expr
487 /* Constraint type. */
488 constraint_expr_type type;
490 /* Variable we are referring to in the constraint. */
491 unsigned int var;
493 /* Offset, in bits, of this constraint from the beginning of
494 variables it ends up referring to.
496 IOW, in a deref constraint, we would deref, get the result set,
497 then add OFFSET to each member. */
498 HOST_WIDE_INT offset;
501 /* Use 0x8000... as special unknown offset. */
502 #define UNKNOWN_OFFSET HOST_WIDE_INT_MIN
504 typedef struct constraint_expr ce_s;
505 static void get_constraint_for_1 (tree, vec<ce_s> *, bool, bool);
506 static void get_constraint_for (tree, vec<ce_s> *);
507 static void get_constraint_for_rhs (tree, vec<ce_s> *);
508 static void do_deref (vec<ce_s> *);
510 /* Our set constraints are made up of two constraint expressions, one
511 LHS, and one RHS.
513 As described in the introduction, our set constraints each represent an
514 operation between set valued variables.
516 struct constraint
518 struct constraint_expr lhs;
519 struct constraint_expr rhs;
522 /* List of constraints that we use to build the constraint graph from. */
524 static vec<constraint_t> constraints;
525 static object_allocator<constraint> constraint_pool ("Constraint pool");
527 /* The constraint graph is represented as an array of bitmaps
528 containing successor nodes. */
530 struct constraint_graph
532 /* Size of this graph, which may be different than the number of
533 nodes in the variable map. */
534 unsigned int size;
536 /* Explicit successors of each node. */
537 bitmap *succs;
539 /* Implicit predecessors of each node (Used for variable
540 substitution). */
541 bitmap *implicit_preds;
543 /* Explicit predecessors of each node (Used for variable substitution). */
544 bitmap *preds;
546 /* Indirect cycle representatives, or -1 if the node has no indirect
547 cycles. */
548 int *indirect_cycles;
550 /* Representative node for a node. rep[a] == a unless the node has
551 been unified. */
552 unsigned int *rep;
554 /* Equivalence class representative for a label. This is used for
555 variable substitution. */
556 int *eq_rep;
558 /* Pointer equivalence label for a node. All nodes with the same
559 pointer equivalence label can be unified together at some point
560 (either during constraint optimization or after the constraint
561 graph is built). */
562 unsigned int *pe;
564 /* Pointer equivalence representative for a label. This is used to
565 handle nodes that are pointer equivalent but not location
566 equivalent. We can unite these once the addressof constraints
567 are transformed into initial points-to sets. */
568 int *pe_rep;
570 /* Pointer equivalence label for each node, used during variable
571 substitution. */
572 unsigned int *pointer_label;
574 /* Location equivalence label for each node, used during location
575 equivalence finding. */
576 unsigned int *loc_label;
578 /* Pointed-by set for each node, used during location equivalence
579 finding. This is pointed-by rather than pointed-to, because it
580 is constructed using the predecessor graph. */
581 bitmap *pointed_by;
583 /* Points to sets for pointer equivalence. This is *not* the actual
584 points-to sets for nodes. */
585 bitmap *points_to;
587 /* Bitmap of nodes where the bit is set if the node is a direct
588 node. Used for variable substitution. */
589 sbitmap direct_nodes;
591 /* Bitmap of nodes where the bit is set if the node is address
592 taken. Used for variable substitution. */
593 bitmap address_taken;
595 /* Vector of complex constraints for each graph node. Complex
596 constraints are those involving dereferences or offsets that are
597 not 0. */
598 vec<constraint_t> *complex;
601 static constraint_graph_t graph;
603 /* During variable substitution and the offline version of indirect
604 cycle finding, we create nodes to represent dereferences and
605 address taken constraints. These represent where these start and
606 end. */
607 #define FIRST_REF_NODE (varmap).length ()
608 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
610 /* Return the representative node for NODE, if NODE has been unioned
611 with another NODE.
612 This function performs path compression along the way to finding
613 the representative. */
615 static unsigned int
616 find (unsigned int node)
618 gcc_checking_assert (node < graph->size);
619 if (graph->rep[node] != node)
620 return graph->rep[node] = find (graph->rep[node]);
621 return node;
624 /* Union the TO and FROM nodes to the TO nodes.
625 Note that at some point in the future, we may want to do
626 union-by-rank, in which case we are going to have to return the
627 node we unified to. */
629 static bool
630 unite (unsigned int to, unsigned int from)
632 gcc_checking_assert (to < graph->size && from < graph->size);
633 if (to != from && graph->rep[from] != to)
635 graph->rep[from] = to;
636 return true;
638 return false;
641 /* Create a new constraint consisting of LHS and RHS expressions. */
643 static constraint_t
644 new_constraint (const struct constraint_expr lhs,
645 const struct constraint_expr rhs)
647 constraint_t ret = constraint_pool.allocate ();
648 ret->lhs = lhs;
649 ret->rhs = rhs;
650 return ret;
653 /* Print out constraint C to FILE. */
655 static void
656 dump_constraint (FILE *file, constraint_t c)
658 if (c->lhs.type == ADDRESSOF)
659 fprintf (file, "&");
660 else if (c->lhs.type == DEREF)
661 fprintf (file, "*");
662 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
663 if (c->lhs.offset == UNKNOWN_OFFSET)
664 fprintf (file, " + UNKNOWN");
665 else if (c->lhs.offset != 0)
666 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
667 fprintf (file, " = ");
668 if (c->rhs.type == ADDRESSOF)
669 fprintf (file, "&");
670 else if (c->rhs.type == DEREF)
671 fprintf (file, "*");
672 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
673 if (c->rhs.offset == UNKNOWN_OFFSET)
674 fprintf (file, " + UNKNOWN");
675 else if (c->rhs.offset != 0)
676 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
680 void debug_constraint (constraint_t);
681 void debug_constraints (void);
682 void debug_constraint_graph (void);
683 void debug_solution_for_var (unsigned int);
684 void debug_sa_points_to_info (void);
686 /* Print out constraint C to stderr. */
688 DEBUG_FUNCTION void
689 debug_constraint (constraint_t c)
691 dump_constraint (stderr, c);
692 fprintf (stderr, "\n");
695 /* Print out all constraints to FILE */
697 static void
698 dump_constraints (FILE *file, int from)
700 int i;
701 constraint_t c;
702 for (i = from; constraints.iterate (i, &c); i++)
703 if (c)
705 dump_constraint (file, c);
706 fprintf (file, "\n");
710 /* Print out all constraints to stderr. */
712 DEBUG_FUNCTION void
713 debug_constraints (void)
715 dump_constraints (stderr, 0);
718 /* Print the constraint graph in dot format. */
720 static void
721 dump_constraint_graph (FILE *file)
723 unsigned int i;
725 /* Only print the graph if it has already been initialized: */
726 if (!graph)
727 return;
729 /* Prints the header of the dot file: */
730 fprintf (file, "strict digraph {\n");
731 fprintf (file, " node [\n shape = box\n ]\n");
732 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
733 fprintf (file, "\n // List of nodes and complex constraints in "
734 "the constraint graph:\n");
736 /* The next lines print the nodes in the graph together with the
737 complex constraints attached to them. */
738 for (i = 1; i < graph->size; i++)
740 if (i == FIRST_REF_NODE)
741 continue;
742 if (find (i) != i)
743 continue;
744 if (i < FIRST_REF_NODE)
745 fprintf (file, "\"%s\"", get_varinfo (i)->name);
746 else
747 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
748 if (graph->complex[i].exists ())
750 unsigned j;
751 constraint_t c;
752 fprintf (file, " [label=\"\\N\\n");
753 for (j = 0; graph->complex[i].iterate (j, &c); ++j)
755 dump_constraint (file, c);
756 fprintf (file, "\\l");
758 fprintf (file, "\"]");
760 fprintf (file, ";\n");
763 /* Go over the edges. */
764 fprintf (file, "\n // Edges in the constraint graph:\n");
765 for (i = 1; i < graph->size; i++)
767 unsigned j;
768 bitmap_iterator bi;
769 if (find (i) != i)
770 continue;
771 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
773 unsigned to = find (j);
774 if (i == to)
775 continue;
776 if (i < FIRST_REF_NODE)
777 fprintf (file, "\"%s\"", get_varinfo (i)->name);
778 else
779 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
780 fprintf (file, " -> ");
781 if (to < FIRST_REF_NODE)
782 fprintf (file, "\"%s\"", get_varinfo (to)->name);
783 else
784 fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
785 fprintf (file, ";\n");
789 /* Prints the tail of the dot file. */
790 fprintf (file, "}\n");
793 /* Print out the constraint graph to stderr. */
795 DEBUG_FUNCTION void
796 debug_constraint_graph (void)
798 dump_constraint_graph (stderr);
801 /* SOLVER FUNCTIONS
803 The solver is a simple worklist solver, that works on the following
804 algorithm:
806 sbitmap changed_nodes = all zeroes;
807 changed_count = 0;
808 For each node that is not already collapsed:
809 changed_count++;
810 set bit in changed nodes
812 while (changed_count > 0)
814 compute topological ordering for constraint graph
816 find and collapse cycles in the constraint graph (updating
817 changed if necessary)
819 for each node (n) in the graph in topological order:
820 changed_count--;
822 Process each complex constraint associated with the node,
823 updating changed if necessary.
825 For each outgoing edge from n, propagate the solution from n to
826 the destination of the edge, updating changed as necessary.
828 } */
830 /* Return true if two constraint expressions A and B are equal. */
832 static bool
833 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
835 return a.type == b.type && a.var == b.var && a.offset == b.offset;
838 /* Return true if constraint expression A is less than constraint expression
839 B. This is just arbitrary, but consistent, in order to give them an
840 ordering. */
842 static bool
843 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
845 if (a.type == b.type)
847 if (a.var == b.var)
848 return a.offset < b.offset;
849 else
850 return a.var < b.var;
852 else
853 return a.type < b.type;
856 /* Return true if constraint A is less than constraint B. This is just
857 arbitrary, but consistent, in order to give them an ordering. */
859 static bool
860 constraint_less (const constraint_t &a, const constraint_t &b)
862 if (constraint_expr_less (a->lhs, b->lhs))
863 return true;
864 else if (constraint_expr_less (b->lhs, a->lhs))
865 return false;
866 else
867 return constraint_expr_less (a->rhs, b->rhs);
870 /* Return true if two constraints A and B are equal. */
872 static bool
873 constraint_equal (struct constraint a, struct constraint b)
875 return constraint_expr_equal (a.lhs, b.lhs)
876 && constraint_expr_equal (a.rhs, b.rhs);
880 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
882 static constraint_t
883 constraint_vec_find (vec<constraint_t> vec,
884 struct constraint lookfor)
886 unsigned int place;
887 constraint_t found;
889 if (!vec.exists ())
890 return NULL;
892 place = vec.lower_bound (&lookfor, constraint_less);
893 if (place >= vec.length ())
894 return NULL;
895 found = vec[place];
896 if (!constraint_equal (*found, lookfor))
897 return NULL;
898 return found;
901 /* Union two constraint vectors, TO and FROM. Put the result in TO.
902 Returns true of TO set is changed. */
904 static bool
905 constraint_set_union (vec<constraint_t> *to,
906 vec<constraint_t> *from)
908 int i;
909 constraint_t c;
910 bool any_change = false;
912 FOR_EACH_VEC_ELT (*from, i, c)
914 if (constraint_vec_find (*to, *c) == NULL)
916 unsigned int place = to->lower_bound (c, constraint_less);
917 to->safe_insert (place, c);
918 any_change = true;
921 return any_change;
924 /* Expands the solution in SET to all sub-fields of variables included. */
926 static bitmap
927 solution_set_expand (bitmap set, bitmap *expanded)
929 bitmap_iterator bi;
930 unsigned j;
932 if (*expanded)
933 return *expanded;
935 *expanded = BITMAP_ALLOC (&iteration_obstack);
937 /* In a first pass expand to the head of the variables we need to
938 add all sub-fields off. This avoids quadratic behavior. */
939 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
941 varinfo_t v = get_varinfo (j);
942 if (v->is_artificial_var
943 || v->is_full_var)
944 continue;
945 bitmap_set_bit (*expanded, v->head);
948 /* In the second pass now expand all head variables with subfields. */
949 EXECUTE_IF_SET_IN_BITMAP (*expanded, 0, j, bi)
951 varinfo_t v = get_varinfo (j);
952 if (v->head != j)
953 continue;
954 for (v = vi_next (v); v != NULL; v = vi_next (v))
955 bitmap_set_bit (*expanded, v->id);
958 /* And finally set the rest of the bits from SET. */
959 bitmap_ior_into (*expanded, set);
961 return *expanded;
964 /* Union solution sets TO and DELTA, and add INC to each member of DELTA in the
965 process. */
967 static bool
968 set_union_with_increment (bitmap to, bitmap delta, HOST_WIDE_INT inc,
969 bitmap *expanded_delta)
971 bool changed = false;
972 bitmap_iterator bi;
973 unsigned int i;
975 /* If the solution of DELTA contains anything it is good enough to transfer
976 this to TO. */
977 if (bitmap_bit_p (delta, anything_id))
978 return bitmap_set_bit (to, anything_id);
980 /* If the offset is unknown we have to expand the solution to
981 all subfields. */
982 if (inc == UNKNOWN_OFFSET)
984 delta = solution_set_expand (delta, expanded_delta);
985 changed |= bitmap_ior_into (to, delta);
986 return changed;
989 /* For non-zero offset union the offsetted solution into the destination. */
990 EXECUTE_IF_SET_IN_BITMAP (delta, 0, i, bi)
992 varinfo_t vi = get_varinfo (i);
994 /* If this is a variable with just one field just set its bit
995 in the result. */
996 if (vi->is_artificial_var
997 || vi->is_unknown_size_var
998 || vi->is_full_var)
999 changed |= bitmap_set_bit (to, i);
1000 else
1002 HOST_WIDE_INT fieldoffset = vi->offset + inc;
1003 unsigned HOST_WIDE_INT size = vi->size;
1005 /* If the offset makes the pointer point to before the
1006 variable use offset zero for the field lookup. */
1007 if (fieldoffset < 0)
1008 vi = get_varinfo (vi->head);
1009 else
1010 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1014 changed |= bitmap_set_bit (to, vi->id);
1015 if (vi->is_full_var
1016 || vi->next == 0)
1017 break;
1019 /* We have to include all fields that overlap the current field
1020 shifted by inc. */
1021 vi = vi_next (vi);
1023 while (vi->offset < fieldoffset + size);
1027 return changed;
1030 /* Insert constraint C into the list of complex constraints for graph
1031 node VAR. */
1033 static void
1034 insert_into_complex (constraint_graph_t graph,
1035 unsigned int var, constraint_t c)
1037 vec<constraint_t> complex = graph->complex[var];
1038 unsigned int place = complex.lower_bound (c, constraint_less);
1040 /* Only insert constraints that do not already exist. */
1041 if (place >= complex.length ()
1042 || !constraint_equal (*c, *complex[place]))
1043 graph->complex[var].safe_insert (place, c);
1047 /* Condense two variable nodes into a single variable node, by moving
1048 all associated info from FROM to TO. Returns true if TO node's
1049 constraint set changes after the merge. */
1051 static bool
1052 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1053 unsigned int from)
1055 unsigned int i;
1056 constraint_t c;
1057 bool any_change = false;
1059 gcc_checking_assert (find (from) == to);
1061 /* Move all complex constraints from src node into to node */
1062 FOR_EACH_VEC_ELT (graph->complex[from], i, c)
1064 /* In complex constraints for node FROM, we may have either
1065 a = *FROM, and *FROM = a, or an offseted constraint which are
1066 always added to the rhs node's constraints. */
1068 if (c->rhs.type == DEREF)
1069 c->rhs.var = to;
1070 else if (c->lhs.type == DEREF)
1071 c->lhs.var = to;
1072 else
1073 c->rhs.var = to;
1076 any_change = constraint_set_union (&graph->complex[to],
1077 &graph->complex[from]);
1078 graph->complex[from].release ();
1079 return any_change;
1083 /* Remove edges involving NODE from GRAPH. */
1085 static void
1086 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1088 if (graph->succs[node])
1089 BITMAP_FREE (graph->succs[node]);
1092 /* Merge GRAPH nodes FROM and TO into node TO. */
1094 static void
1095 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1096 unsigned int from)
1098 if (graph->indirect_cycles[from] != -1)
1100 /* If we have indirect cycles with the from node, and we have
1101 none on the to node, the to node has indirect cycles from the
1102 from node now that they are unified.
1103 If indirect cycles exist on both, unify the nodes that they
1104 are in a cycle with, since we know they are in a cycle with
1105 each other. */
1106 if (graph->indirect_cycles[to] == -1)
1107 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1110 /* Merge all the successor edges. */
1111 if (graph->succs[from])
1113 if (!graph->succs[to])
1114 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1115 bitmap_ior_into (graph->succs[to],
1116 graph->succs[from]);
1119 clear_edges_for_node (graph, from);
1123 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1124 it doesn't exist in the graph already. */
1126 static void
1127 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1128 unsigned int from)
1130 if (to == from)
1131 return;
1133 if (!graph->implicit_preds[to])
1134 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1136 if (bitmap_set_bit (graph->implicit_preds[to], from))
1137 stats.num_implicit_edges++;
1140 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1141 it doesn't exist in the graph already.
1142 Return false if the edge already existed, true otherwise. */
1144 static void
1145 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1146 unsigned int from)
1148 if (!graph->preds[to])
1149 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1150 bitmap_set_bit (graph->preds[to], from);
1153 /* Add a graph edge to GRAPH, going from FROM to TO if
1154 it doesn't exist in the graph already.
1155 Return false if the edge already existed, true otherwise. */
1157 static bool
1158 add_graph_edge (constraint_graph_t graph, unsigned int to,
1159 unsigned int from)
1161 if (to == from)
1163 return false;
1165 else
1167 bool r = false;
1169 if (!graph->succs[from])
1170 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1171 if (bitmap_set_bit (graph->succs[from], to))
1173 r = true;
1174 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1175 stats.num_edges++;
1177 return r;
1182 /* Initialize the constraint graph structure to contain SIZE nodes. */
1184 static void
1185 init_graph (unsigned int size)
1187 unsigned int j;
1189 graph = XCNEW (struct constraint_graph);
1190 graph->size = size;
1191 graph->succs = XCNEWVEC (bitmap, graph->size);
1192 graph->indirect_cycles = XNEWVEC (int, graph->size);
1193 graph->rep = XNEWVEC (unsigned int, graph->size);
1194 /* ??? Macros do not support template types with multiple arguments,
1195 so we use a typedef to work around it. */
1196 typedef vec<constraint_t> vec_constraint_t_heap;
1197 graph->complex = XCNEWVEC (vec_constraint_t_heap, size);
1198 graph->pe = XCNEWVEC (unsigned int, graph->size);
1199 graph->pe_rep = XNEWVEC (int, graph->size);
1201 for (j = 0; j < graph->size; j++)
1203 graph->rep[j] = j;
1204 graph->pe_rep[j] = -1;
1205 graph->indirect_cycles[j] = -1;
1209 /* Build the constraint graph, adding only predecessor edges right now. */
1211 static void
1212 build_pred_graph (void)
1214 int i;
1215 constraint_t c;
1216 unsigned int j;
1218 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1219 graph->preds = XCNEWVEC (bitmap, graph->size);
1220 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1221 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1222 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1223 graph->points_to = XCNEWVEC (bitmap, graph->size);
1224 graph->eq_rep = XNEWVEC (int, graph->size);
1225 graph->direct_nodes = sbitmap_alloc (graph->size);
1226 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1227 bitmap_clear (graph->direct_nodes);
1229 for (j = 1; j < FIRST_REF_NODE; j++)
1231 if (!get_varinfo (j)->is_special_var)
1232 bitmap_set_bit (graph->direct_nodes, j);
1235 for (j = 0; j < graph->size; j++)
1236 graph->eq_rep[j] = -1;
1238 for (j = 0; j < varmap.length (); j++)
1239 graph->indirect_cycles[j] = -1;
1241 FOR_EACH_VEC_ELT (constraints, i, c)
1243 struct constraint_expr lhs = c->lhs;
1244 struct constraint_expr rhs = c->rhs;
1245 unsigned int lhsvar = lhs.var;
1246 unsigned int rhsvar = rhs.var;
1248 if (lhs.type == DEREF)
1250 /* *x = y. */
1251 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1252 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1254 else if (rhs.type == DEREF)
1256 /* x = *y */
1257 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1258 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1259 else
1260 bitmap_clear_bit (graph->direct_nodes, lhsvar);
1262 else if (rhs.type == ADDRESSOF)
1264 varinfo_t v;
1266 /* x = &y */
1267 if (graph->points_to[lhsvar] == NULL)
1268 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1269 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1271 if (graph->pointed_by[rhsvar] == NULL)
1272 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1273 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1275 /* Implicitly, *x = y */
1276 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1278 /* All related variables are no longer direct nodes. */
1279 bitmap_clear_bit (graph->direct_nodes, rhsvar);
1280 v = get_varinfo (rhsvar);
1281 if (!v->is_full_var)
1283 v = get_varinfo (v->head);
1286 bitmap_clear_bit (graph->direct_nodes, v->id);
1287 v = vi_next (v);
1289 while (v != NULL);
1291 bitmap_set_bit (graph->address_taken, rhsvar);
1293 else if (lhsvar > anything_id
1294 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1296 /* x = y */
1297 add_pred_graph_edge (graph, lhsvar, rhsvar);
1298 /* Implicitly, *x = *y */
1299 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1300 FIRST_REF_NODE + rhsvar);
1302 else if (lhs.offset != 0 || rhs.offset != 0)
1304 if (rhs.offset != 0)
1305 bitmap_clear_bit (graph->direct_nodes, lhs.var);
1306 else if (lhs.offset != 0)
1307 bitmap_clear_bit (graph->direct_nodes, rhs.var);
1312 /* Build the constraint graph, adding successor edges. */
1314 static void
1315 build_succ_graph (void)
1317 unsigned i, t;
1318 constraint_t c;
1320 FOR_EACH_VEC_ELT (constraints, i, c)
1322 struct constraint_expr lhs;
1323 struct constraint_expr rhs;
1324 unsigned int lhsvar;
1325 unsigned int rhsvar;
1327 if (!c)
1328 continue;
1330 lhs = c->lhs;
1331 rhs = c->rhs;
1332 lhsvar = find (lhs.var);
1333 rhsvar = find (rhs.var);
1335 if (lhs.type == DEREF)
1337 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1338 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1340 else if (rhs.type == DEREF)
1342 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1343 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1345 else if (rhs.type == ADDRESSOF)
1347 /* x = &y */
1348 gcc_checking_assert (find (rhs.var) == rhs.var);
1349 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1351 else if (lhsvar > anything_id
1352 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1354 add_graph_edge (graph, lhsvar, rhsvar);
1358 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1359 receive pointers. */
1360 t = find (storedanything_id);
1361 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1363 if (!bitmap_bit_p (graph->direct_nodes, i)
1364 && get_varinfo (i)->may_have_pointers)
1365 add_graph_edge (graph, find (i), t);
1368 /* Everything stored to ANYTHING also potentially escapes. */
1369 add_graph_edge (graph, find (escaped_id), t);
1373 /* Changed variables on the last iteration. */
1374 static bitmap changed;
1376 /* Strongly Connected Component visitation info. */
1378 struct scc_info
1380 sbitmap visited;
1381 sbitmap deleted;
1382 unsigned int *dfs;
1383 unsigned int *node_mapping;
1384 int current_index;
1385 vec<unsigned> scc_stack;
1389 /* Recursive routine to find strongly connected components in GRAPH.
1390 SI is the SCC info to store the information in, and N is the id of current
1391 graph node we are processing.
1393 This is Tarjan's strongly connected component finding algorithm, as
1394 modified by Nuutila to keep only non-root nodes on the stack.
1395 The algorithm can be found in "On finding the strongly connected
1396 connected components in a directed graph" by Esko Nuutila and Eljas
1397 Soisalon-Soininen, in Information Processing Letters volume 49,
1398 number 1, pages 9-14. */
1400 static void
1401 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1403 unsigned int i;
1404 bitmap_iterator bi;
1405 unsigned int my_dfs;
1407 bitmap_set_bit (si->visited, n);
1408 si->dfs[n] = si->current_index ++;
1409 my_dfs = si->dfs[n];
1411 /* Visit all the successors. */
1412 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1414 unsigned int w;
1416 if (i > LAST_REF_NODE)
1417 break;
1419 w = find (i);
1420 if (bitmap_bit_p (si->deleted, w))
1421 continue;
1423 if (!bitmap_bit_p (si->visited, w))
1424 scc_visit (graph, si, w);
1426 unsigned int t = find (w);
1427 gcc_checking_assert (find (n) == n);
1428 if (si->dfs[t] < si->dfs[n])
1429 si->dfs[n] = si->dfs[t];
1432 /* See if any components have been identified. */
1433 if (si->dfs[n] == my_dfs)
1435 if (si->scc_stack.length () > 0
1436 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1438 bitmap scc = BITMAP_ALLOC (NULL);
1439 unsigned int lowest_node;
1440 bitmap_iterator bi;
1442 bitmap_set_bit (scc, n);
1444 while (si->scc_stack.length () != 0
1445 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1447 unsigned int w = si->scc_stack.pop ();
1449 bitmap_set_bit (scc, w);
1452 lowest_node = bitmap_first_set_bit (scc);
1453 gcc_assert (lowest_node < FIRST_REF_NODE);
1455 /* Collapse the SCC nodes into a single node, and mark the
1456 indirect cycles. */
1457 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1459 if (i < FIRST_REF_NODE)
1461 if (unite (lowest_node, i))
1462 unify_nodes (graph, lowest_node, i, false);
1464 else
1466 unite (lowest_node, i);
1467 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1471 bitmap_set_bit (si->deleted, n);
1473 else
1474 si->scc_stack.safe_push (n);
1477 /* Unify node FROM into node TO, updating the changed count if
1478 necessary when UPDATE_CHANGED is true. */
1480 static void
1481 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1482 bool update_changed)
1484 gcc_checking_assert (to != from && find (to) == to);
1486 if (dump_file && (dump_flags & TDF_DETAILS))
1487 fprintf (dump_file, "Unifying %s to %s\n",
1488 get_varinfo (from)->name,
1489 get_varinfo (to)->name);
1491 if (update_changed)
1492 stats.unified_vars_dynamic++;
1493 else
1494 stats.unified_vars_static++;
1496 merge_graph_nodes (graph, to, from);
1497 if (merge_node_constraints (graph, to, from))
1499 if (update_changed)
1500 bitmap_set_bit (changed, to);
1503 /* Mark TO as changed if FROM was changed. If TO was already marked
1504 as changed, decrease the changed count. */
1506 if (update_changed
1507 && bitmap_clear_bit (changed, from))
1508 bitmap_set_bit (changed, to);
1509 varinfo_t fromvi = get_varinfo (from);
1510 if (fromvi->solution)
1512 /* If the solution changes because of the merging, we need to mark
1513 the variable as changed. */
1514 varinfo_t tovi = get_varinfo (to);
1515 if (bitmap_ior_into (tovi->solution, fromvi->solution))
1517 if (update_changed)
1518 bitmap_set_bit (changed, to);
1521 BITMAP_FREE (fromvi->solution);
1522 if (fromvi->oldsolution)
1523 BITMAP_FREE (fromvi->oldsolution);
1525 if (stats.iterations > 0
1526 && tovi->oldsolution)
1527 BITMAP_FREE (tovi->oldsolution);
1529 if (graph->succs[to])
1530 bitmap_clear_bit (graph->succs[to], to);
1533 /* Information needed to compute the topological ordering of a graph. */
1535 struct topo_info
1537 /* sbitmap of visited nodes. */
1538 sbitmap visited;
1539 /* Array that stores the topological order of the graph, *in
1540 reverse*. */
1541 vec<unsigned> topo_order;
1545 /* Initialize and return a topological info structure. */
1547 static struct topo_info *
1548 init_topo_info (void)
1550 size_t size = graph->size;
1551 struct topo_info *ti = XNEW (struct topo_info);
1552 ti->visited = sbitmap_alloc (size);
1553 bitmap_clear (ti->visited);
1554 ti->topo_order.create (1);
1555 return ti;
1559 /* Free the topological sort info pointed to by TI. */
1561 static void
1562 free_topo_info (struct topo_info *ti)
1564 sbitmap_free (ti->visited);
1565 ti->topo_order.release ();
1566 free (ti);
1569 /* Visit the graph in topological order, and store the order in the
1570 topo_info structure. */
1572 static void
1573 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1574 unsigned int n)
1576 bitmap_iterator bi;
1577 unsigned int j;
1579 bitmap_set_bit (ti->visited, n);
1581 if (graph->succs[n])
1582 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1584 if (!bitmap_bit_p (ti->visited, j))
1585 topo_visit (graph, ti, j);
1588 ti->topo_order.safe_push (n);
1591 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1592 starting solution for y. */
1594 static void
1595 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1596 bitmap delta, bitmap *expanded_delta)
1598 unsigned int lhs = c->lhs.var;
1599 bool flag = false;
1600 bitmap sol = get_varinfo (lhs)->solution;
1601 unsigned int j;
1602 bitmap_iterator bi;
1603 HOST_WIDE_INT roffset = c->rhs.offset;
1605 /* Our IL does not allow this. */
1606 gcc_checking_assert (c->lhs.offset == 0);
1608 /* If the solution of Y contains anything it is good enough to transfer
1609 this to the LHS. */
1610 if (bitmap_bit_p (delta, anything_id))
1612 flag |= bitmap_set_bit (sol, anything_id);
1613 goto done;
1616 /* If we do not know at with offset the rhs is dereferenced compute
1617 the reachability set of DELTA, conservatively assuming it is
1618 dereferenced at all valid offsets. */
1619 if (roffset == UNKNOWN_OFFSET)
1621 delta = solution_set_expand (delta, expanded_delta);
1622 /* No further offset processing is necessary. */
1623 roffset = 0;
1626 /* For each variable j in delta (Sol(y)), add
1627 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1628 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1630 varinfo_t v = get_varinfo (j);
1631 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1632 unsigned HOST_WIDE_INT size = v->size;
1633 unsigned int t;
1635 if (v->is_full_var)
1637 else if (roffset != 0)
1639 if (fieldoffset < 0)
1640 v = get_varinfo (v->head);
1641 else
1642 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1645 /* We have to include all fields that overlap the current field
1646 shifted by roffset. */
1649 t = find (v->id);
1651 /* Adding edges from the special vars is pointless.
1652 They don't have sets that can change. */
1653 if (get_varinfo (t)->is_special_var)
1654 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1655 /* Merging the solution from ESCAPED needlessly increases
1656 the set. Use ESCAPED as representative instead. */
1657 else if (v->id == escaped_id)
1658 flag |= bitmap_set_bit (sol, escaped_id);
1659 else if (v->may_have_pointers
1660 && add_graph_edge (graph, lhs, t))
1661 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1663 if (v->is_full_var
1664 || v->next == 0)
1665 break;
1667 v = vi_next (v);
1669 while (v->offset < fieldoffset + size);
1672 done:
1673 /* If the LHS solution changed, mark the var as changed. */
1674 if (flag)
1676 get_varinfo (lhs)->solution = sol;
1677 bitmap_set_bit (changed, lhs);
1681 /* Process a constraint C that represents *(x + off) = y using DELTA
1682 as the starting solution for x. */
1684 static void
1685 do_ds_constraint (constraint_t c, bitmap delta, bitmap *expanded_delta)
1687 unsigned int rhs = c->rhs.var;
1688 bitmap sol = get_varinfo (rhs)->solution;
1689 unsigned int j;
1690 bitmap_iterator bi;
1691 HOST_WIDE_INT loff = c->lhs.offset;
1692 bool escaped_p = false;
1694 /* Our IL does not allow this. */
1695 gcc_checking_assert (c->rhs.offset == 0);
1697 /* If the solution of y contains ANYTHING simply use the ANYTHING
1698 solution. This avoids needlessly increasing the points-to sets. */
1699 if (bitmap_bit_p (sol, anything_id))
1700 sol = get_varinfo (find (anything_id))->solution;
1702 /* If the solution for x contains ANYTHING we have to merge the
1703 solution of y into all pointer variables which we do via
1704 STOREDANYTHING. */
1705 if (bitmap_bit_p (delta, anything_id))
1707 unsigned t = find (storedanything_id);
1708 if (add_graph_edge (graph, t, rhs))
1710 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1711 bitmap_set_bit (changed, t);
1713 return;
1716 /* If we do not know at with offset the rhs is dereferenced compute
1717 the reachability set of DELTA, conservatively assuming it is
1718 dereferenced at all valid offsets. */
1719 if (loff == UNKNOWN_OFFSET)
1721 delta = solution_set_expand (delta, expanded_delta);
1722 loff = 0;
1725 /* For each member j of delta (Sol(x)), add an edge from y to j and
1726 union Sol(y) into Sol(j) */
1727 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1729 varinfo_t v = get_varinfo (j);
1730 unsigned int t;
1731 HOST_WIDE_INT fieldoffset = v->offset + loff;
1732 unsigned HOST_WIDE_INT size = v->size;
1734 if (v->is_full_var)
1736 else if (loff != 0)
1738 if (fieldoffset < 0)
1739 v = get_varinfo (v->head);
1740 else
1741 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1744 /* We have to include all fields that overlap the current field
1745 shifted by loff. */
1748 if (v->may_have_pointers)
1750 /* If v is a global variable then this is an escape point. */
1751 if (v->is_global_var
1752 && !escaped_p)
1754 t = find (escaped_id);
1755 if (add_graph_edge (graph, t, rhs)
1756 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1757 bitmap_set_bit (changed, t);
1758 /* Enough to let rhs escape once. */
1759 escaped_p = true;
1762 if (v->is_special_var)
1763 break;
1765 t = find (v->id);
1766 if (add_graph_edge (graph, t, rhs)
1767 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1768 bitmap_set_bit (changed, t);
1771 if (v->is_full_var
1772 || v->next == 0)
1773 break;
1775 v = vi_next (v);
1777 while (v->offset < fieldoffset + size);
1781 /* Handle a non-simple (simple meaning requires no iteration),
1782 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1784 static void
1785 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta,
1786 bitmap *expanded_delta)
1788 if (c->lhs.type == DEREF)
1790 if (c->rhs.type == ADDRESSOF)
1792 gcc_unreachable ();
1794 else
1796 /* *x = y */
1797 do_ds_constraint (c, delta, expanded_delta);
1800 else if (c->rhs.type == DEREF)
1802 /* x = *y */
1803 if (!(get_varinfo (c->lhs.var)->is_special_var))
1804 do_sd_constraint (graph, c, delta, expanded_delta);
1806 else
1808 bitmap tmp;
1809 bool flag = false;
1811 gcc_checking_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR
1812 && c->rhs.offset != 0 && c->lhs.offset == 0);
1813 tmp = get_varinfo (c->lhs.var)->solution;
1815 flag = set_union_with_increment (tmp, delta, c->rhs.offset,
1816 expanded_delta);
1818 if (flag)
1819 bitmap_set_bit (changed, c->lhs.var);
1823 /* Initialize and return a new SCC info structure. */
1825 static struct scc_info *
1826 init_scc_info (size_t size)
1828 struct scc_info *si = XNEW (struct scc_info);
1829 size_t i;
1831 si->current_index = 0;
1832 si->visited = sbitmap_alloc (size);
1833 bitmap_clear (si->visited);
1834 si->deleted = sbitmap_alloc (size);
1835 bitmap_clear (si->deleted);
1836 si->node_mapping = XNEWVEC (unsigned int, size);
1837 si->dfs = XCNEWVEC (unsigned int, size);
1839 for (i = 0; i < size; i++)
1840 si->node_mapping[i] = i;
1842 si->scc_stack.create (1);
1843 return si;
1846 /* Free an SCC info structure pointed to by SI */
1848 static void
1849 free_scc_info (struct scc_info *si)
1851 sbitmap_free (si->visited);
1852 sbitmap_free (si->deleted);
1853 free (si->node_mapping);
1854 free (si->dfs);
1855 si->scc_stack.release ();
1856 free (si);
1860 /* Find indirect cycles in GRAPH that occur, using strongly connected
1861 components, and note them in the indirect cycles map.
1863 This technique comes from Ben Hardekopf and Calvin Lin,
1864 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1865 Lines of Code", submitted to PLDI 2007. */
1867 static void
1868 find_indirect_cycles (constraint_graph_t graph)
1870 unsigned int i;
1871 unsigned int size = graph->size;
1872 struct scc_info *si = init_scc_info (size);
1874 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1875 if (!bitmap_bit_p (si->visited, i) && find (i) == i)
1876 scc_visit (graph, si, i);
1878 free_scc_info (si);
1881 /* Compute a topological ordering for GRAPH, and store the result in the
1882 topo_info structure TI. */
1884 static void
1885 compute_topo_order (constraint_graph_t graph,
1886 struct topo_info *ti)
1888 unsigned int i;
1889 unsigned int size = graph->size;
1891 for (i = 0; i != size; ++i)
1892 if (!bitmap_bit_p (ti->visited, i) && find (i) == i)
1893 topo_visit (graph, ti, i);
1896 /* Structure used to for hash value numbering of pointer equivalence
1897 classes. */
1899 typedef struct equiv_class_label
1901 hashval_t hashcode;
1902 unsigned int equivalence_class;
1903 bitmap labels;
1904 } *equiv_class_label_t;
1905 typedef const struct equiv_class_label *const_equiv_class_label_t;
1907 /* Equiv_class_label hashtable helpers. */
1909 struct equiv_class_hasher : free_ptr_hash <equiv_class_label>
1911 static inline hashval_t hash (const equiv_class_label *);
1912 static inline bool equal (const equiv_class_label *,
1913 const equiv_class_label *);
1916 /* Hash function for a equiv_class_label_t */
1918 inline hashval_t
1919 equiv_class_hasher::hash (const equiv_class_label *ecl)
1921 return ecl->hashcode;
1924 /* Equality function for two equiv_class_label_t's. */
1926 inline bool
1927 equiv_class_hasher::equal (const equiv_class_label *eql1,
1928 const equiv_class_label *eql2)
1930 return (eql1->hashcode == eql2->hashcode
1931 && bitmap_equal_p (eql1->labels, eql2->labels));
1934 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1935 classes. */
1936 static hash_table<equiv_class_hasher> *pointer_equiv_class_table;
1938 /* A hashtable for mapping a bitmap of labels->location equivalence
1939 classes. */
1940 static hash_table<equiv_class_hasher> *location_equiv_class_table;
1942 /* Lookup a equivalence class in TABLE by the bitmap of LABELS with
1943 hash HAS it contains. Sets *REF_LABELS to the bitmap LABELS
1944 is equivalent to. */
1946 static equiv_class_label *
1947 equiv_class_lookup_or_add (hash_table<equiv_class_hasher> *table,
1948 bitmap labels)
1950 equiv_class_label **slot;
1951 equiv_class_label ecl;
1953 ecl.labels = labels;
1954 ecl.hashcode = bitmap_hash (labels);
1955 slot = table->find_slot (&ecl, INSERT);
1956 if (!*slot)
1958 *slot = XNEW (struct equiv_class_label);
1959 (*slot)->labels = labels;
1960 (*slot)->hashcode = ecl.hashcode;
1961 (*slot)->equivalence_class = 0;
1964 return *slot;
1967 /* Perform offline variable substitution.
1969 This is a worst case quadratic time way of identifying variables
1970 that must have equivalent points-to sets, including those caused by
1971 static cycles, and single entry subgraphs, in the constraint graph.
1973 The technique is described in "Exploiting Pointer and Location
1974 Equivalence to Optimize Pointer Analysis. In the 14th International
1975 Static Analysis Symposium (SAS), August 2007." It is known as the
1976 "HU" algorithm, and is equivalent to value numbering the collapsed
1977 constraint graph including evaluating unions.
1979 The general method of finding equivalence classes is as follows:
1980 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1981 Initialize all non-REF nodes to be direct nodes.
1982 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1983 variable}
1984 For each constraint containing the dereference, we also do the same
1985 thing.
1987 We then compute SCC's in the graph and unify nodes in the same SCC,
1988 including pts sets.
1990 For each non-collapsed node x:
1991 Visit all unvisited explicit incoming edges.
1992 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1993 where y->x.
1994 Lookup the equivalence class for pts(x).
1995 If we found one, equivalence_class(x) = found class.
1996 Otherwise, equivalence_class(x) = new class, and new_class is
1997 added to the lookup table.
1999 All direct nodes with the same equivalence class can be replaced
2000 with a single representative node.
2001 All unlabeled nodes (label == 0) are not pointers and all edges
2002 involving them can be eliminated.
2003 We perform these optimizations during rewrite_constraints
2005 In addition to pointer equivalence class finding, we also perform
2006 location equivalence class finding. This is the set of variables
2007 that always appear together in points-to sets. We use this to
2008 compress the size of the points-to sets. */
2010 /* Current maximum pointer equivalence class id. */
2011 static int pointer_equiv_class;
2013 /* Current maximum location equivalence class id. */
2014 static int location_equiv_class;
2016 /* Recursive routine to find strongly connected components in GRAPH,
2017 and label it's nodes with DFS numbers. */
2019 static void
2020 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2022 unsigned int i;
2023 bitmap_iterator bi;
2024 unsigned int my_dfs;
2026 gcc_checking_assert (si->node_mapping[n] == n);
2027 bitmap_set_bit (si->visited, n);
2028 si->dfs[n] = si->current_index ++;
2029 my_dfs = si->dfs[n];
2031 /* Visit all the successors. */
2032 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2034 unsigned int w = si->node_mapping[i];
2036 if (bitmap_bit_p (si->deleted, w))
2037 continue;
2039 if (!bitmap_bit_p (si->visited, w))
2040 condense_visit (graph, si, w);
2042 unsigned int t = si->node_mapping[w];
2043 gcc_checking_assert (si->node_mapping[n] == n);
2044 if (si->dfs[t] < si->dfs[n])
2045 si->dfs[n] = si->dfs[t];
2048 /* Visit all the implicit predecessors. */
2049 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2051 unsigned int w = si->node_mapping[i];
2053 if (bitmap_bit_p (si->deleted, w))
2054 continue;
2056 if (!bitmap_bit_p (si->visited, w))
2057 condense_visit (graph, si, w);
2059 unsigned int t = si->node_mapping[w];
2060 gcc_assert (si->node_mapping[n] == n);
2061 if (si->dfs[t] < si->dfs[n])
2062 si->dfs[n] = si->dfs[t];
2065 /* See if any components have been identified. */
2066 if (si->dfs[n] == my_dfs)
2068 while (si->scc_stack.length () != 0
2069 && si->dfs[si->scc_stack.last ()] >= my_dfs)
2071 unsigned int w = si->scc_stack.pop ();
2072 si->node_mapping[w] = n;
2074 if (!bitmap_bit_p (graph->direct_nodes, w))
2075 bitmap_clear_bit (graph->direct_nodes, n);
2077 /* Unify our nodes. */
2078 if (graph->preds[w])
2080 if (!graph->preds[n])
2081 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2082 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2084 if (graph->implicit_preds[w])
2086 if (!graph->implicit_preds[n])
2087 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2088 bitmap_ior_into (graph->implicit_preds[n],
2089 graph->implicit_preds[w]);
2091 if (graph->points_to[w])
2093 if (!graph->points_to[n])
2094 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2095 bitmap_ior_into (graph->points_to[n],
2096 graph->points_to[w]);
2099 bitmap_set_bit (si->deleted, n);
2101 else
2102 si->scc_stack.safe_push (n);
2105 /* Label pointer equivalences.
2107 This performs a value numbering of the constraint graph to
2108 discover which variables will always have the same points-to sets
2109 under the current set of constraints.
2111 The way it value numbers is to store the set of points-to bits
2112 generated by the constraints and graph edges. This is just used as a
2113 hash and equality comparison. The *actual set of points-to bits* is
2114 completely irrelevant, in that we don't care about being able to
2115 extract them later.
2117 The equality values (currently bitmaps) just have to satisfy a few
2118 constraints, the main ones being:
2119 1. The combining operation must be order independent.
2120 2. The end result of a given set of operations must be unique iff the
2121 combination of input values is unique
2122 3. Hashable. */
2124 static void
2125 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2127 unsigned int i, first_pred;
2128 bitmap_iterator bi;
2130 bitmap_set_bit (si->visited, n);
2132 /* Label and union our incoming edges's points to sets. */
2133 first_pred = -1U;
2134 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2136 unsigned int w = si->node_mapping[i];
2137 if (!bitmap_bit_p (si->visited, w))
2138 label_visit (graph, si, w);
2140 /* Skip unused edges */
2141 if (w == n || graph->pointer_label[w] == 0)
2142 continue;
2144 if (graph->points_to[w])
2146 if (!graph->points_to[n])
2148 if (first_pred == -1U)
2149 first_pred = w;
2150 else
2152 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2153 bitmap_ior (graph->points_to[n],
2154 graph->points_to[first_pred],
2155 graph->points_to[w]);
2158 else
2159 bitmap_ior_into (graph->points_to[n], graph->points_to[w]);
2163 /* Indirect nodes get fresh variables and a new pointer equiv class. */
2164 if (!bitmap_bit_p (graph->direct_nodes, n))
2166 if (!graph->points_to[n])
2168 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2169 if (first_pred != -1U)
2170 bitmap_copy (graph->points_to[n], graph->points_to[first_pred]);
2172 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2173 graph->pointer_label[n] = pointer_equiv_class++;
2174 equiv_class_label_t ecl;
2175 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2176 graph->points_to[n]);
2177 ecl->equivalence_class = graph->pointer_label[n];
2178 return;
2181 /* If there was only a single non-empty predecessor the pointer equiv
2182 class is the same. */
2183 if (!graph->points_to[n])
2185 if (first_pred != -1U)
2187 graph->pointer_label[n] = graph->pointer_label[first_pred];
2188 graph->points_to[n] = graph->points_to[first_pred];
2190 return;
2193 if (!bitmap_empty_p (graph->points_to[n]))
2195 equiv_class_label_t ecl;
2196 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2197 graph->points_to[n]);
2198 if (ecl->equivalence_class == 0)
2199 ecl->equivalence_class = pointer_equiv_class++;
2200 else
2202 BITMAP_FREE (graph->points_to[n]);
2203 graph->points_to[n] = ecl->labels;
2205 graph->pointer_label[n] = ecl->equivalence_class;
2209 /* Print the pred graph in dot format. */
2211 static void
2212 dump_pred_graph (struct scc_info *si, FILE *file)
2214 unsigned int i;
2216 /* Only print the graph if it has already been initialized: */
2217 if (!graph)
2218 return;
2220 /* Prints the header of the dot file: */
2221 fprintf (file, "strict digraph {\n");
2222 fprintf (file, " node [\n shape = box\n ]\n");
2223 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
2224 fprintf (file, "\n // List of nodes and complex constraints in "
2225 "the constraint graph:\n");
2227 /* The next lines print the nodes in the graph together with the
2228 complex constraints attached to them. */
2229 for (i = 1; i < graph->size; i++)
2231 if (i == FIRST_REF_NODE)
2232 continue;
2233 if (si->node_mapping[i] != i)
2234 continue;
2235 if (i < FIRST_REF_NODE)
2236 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2237 else
2238 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2239 if (graph->points_to[i]
2240 && !bitmap_empty_p (graph->points_to[i]))
2242 fprintf (file, "[label=\"%s = {", get_varinfo (i)->name);
2243 unsigned j;
2244 bitmap_iterator bi;
2245 EXECUTE_IF_SET_IN_BITMAP (graph->points_to[i], 0, j, bi)
2246 fprintf (file, " %d", j);
2247 fprintf (file, " }\"]");
2249 fprintf (file, ";\n");
2252 /* Go over the edges. */
2253 fprintf (file, "\n // Edges in the constraint graph:\n");
2254 for (i = 1; i < graph->size; i++)
2256 unsigned j;
2257 bitmap_iterator bi;
2258 if (si->node_mapping[i] != i)
2259 continue;
2260 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[i], 0, j, bi)
2262 unsigned from = si->node_mapping[j];
2263 if (from < FIRST_REF_NODE)
2264 fprintf (file, "\"%s\"", get_varinfo (from)->name);
2265 else
2266 fprintf (file, "\"*%s\"", get_varinfo (from - FIRST_REF_NODE)->name);
2267 fprintf (file, " -> ");
2268 if (i < FIRST_REF_NODE)
2269 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2270 else
2271 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2272 fprintf (file, ";\n");
2276 /* Prints the tail of the dot file. */
2277 fprintf (file, "}\n");
2280 /* Perform offline variable substitution, discovering equivalence
2281 classes, and eliminating non-pointer variables. */
2283 static struct scc_info *
2284 perform_var_substitution (constraint_graph_t graph)
2286 unsigned int i;
2287 unsigned int size = graph->size;
2288 struct scc_info *si = init_scc_info (size);
2290 bitmap_obstack_initialize (&iteration_obstack);
2291 pointer_equiv_class_table = new hash_table<equiv_class_hasher> (511);
2292 location_equiv_class_table
2293 = new hash_table<equiv_class_hasher> (511);
2294 pointer_equiv_class = 1;
2295 location_equiv_class = 1;
2297 /* Condense the nodes, which means to find SCC's, count incoming
2298 predecessors, and unite nodes in SCC's. */
2299 for (i = 1; i < FIRST_REF_NODE; i++)
2300 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2301 condense_visit (graph, si, si->node_mapping[i]);
2303 if (dump_file && (dump_flags & TDF_GRAPH))
2305 fprintf (dump_file, "\n\n// The constraint graph before var-substitution "
2306 "in dot format:\n");
2307 dump_pred_graph (si, dump_file);
2308 fprintf (dump_file, "\n\n");
2311 bitmap_clear (si->visited);
2312 /* Actually the label the nodes for pointer equivalences */
2313 for (i = 1; i < FIRST_REF_NODE; i++)
2314 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2315 label_visit (graph, si, si->node_mapping[i]);
2317 /* Calculate location equivalence labels. */
2318 for (i = 1; i < FIRST_REF_NODE; i++)
2320 bitmap pointed_by;
2321 bitmap_iterator bi;
2322 unsigned int j;
2324 if (!graph->pointed_by[i])
2325 continue;
2326 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2328 /* Translate the pointed-by mapping for pointer equivalence
2329 labels. */
2330 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2332 bitmap_set_bit (pointed_by,
2333 graph->pointer_label[si->node_mapping[j]]);
2335 /* The original pointed_by is now dead. */
2336 BITMAP_FREE (graph->pointed_by[i]);
2338 /* Look up the location equivalence label if one exists, or make
2339 one otherwise. */
2340 equiv_class_label_t ecl;
2341 ecl = equiv_class_lookup_or_add (location_equiv_class_table, pointed_by);
2342 if (ecl->equivalence_class == 0)
2343 ecl->equivalence_class = location_equiv_class++;
2344 else
2346 if (dump_file && (dump_flags & TDF_DETAILS))
2347 fprintf (dump_file, "Found location equivalence for node %s\n",
2348 get_varinfo (i)->name);
2349 BITMAP_FREE (pointed_by);
2351 graph->loc_label[i] = ecl->equivalence_class;
2355 if (dump_file && (dump_flags & TDF_DETAILS))
2356 for (i = 1; i < FIRST_REF_NODE; i++)
2358 unsigned j = si->node_mapping[i];
2359 if (j != i)
2361 fprintf (dump_file, "%s node id %d ",
2362 bitmap_bit_p (graph->direct_nodes, i)
2363 ? "Direct" : "Indirect", i);
2364 if (i < FIRST_REF_NODE)
2365 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2366 else
2367 fprintf (dump_file, "\"*%s\"",
2368 get_varinfo (i - FIRST_REF_NODE)->name);
2369 fprintf (dump_file, " mapped to SCC leader node id %d ", j);
2370 if (j < FIRST_REF_NODE)
2371 fprintf (dump_file, "\"%s\"\n", get_varinfo (j)->name);
2372 else
2373 fprintf (dump_file, "\"*%s\"\n",
2374 get_varinfo (j - FIRST_REF_NODE)->name);
2376 else
2378 fprintf (dump_file,
2379 "Equivalence classes for %s node id %d ",
2380 bitmap_bit_p (graph->direct_nodes, i)
2381 ? "direct" : "indirect", i);
2382 if (i < FIRST_REF_NODE)
2383 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2384 else
2385 fprintf (dump_file, "\"*%s\"",
2386 get_varinfo (i - FIRST_REF_NODE)->name);
2387 fprintf (dump_file,
2388 ": pointer %d, location %d\n",
2389 graph->pointer_label[i], graph->loc_label[i]);
2393 /* Quickly eliminate our non-pointer variables. */
2395 for (i = 1; i < FIRST_REF_NODE; i++)
2397 unsigned int node = si->node_mapping[i];
2399 if (graph->pointer_label[node] == 0)
2401 if (dump_file && (dump_flags & TDF_DETAILS))
2402 fprintf (dump_file,
2403 "%s is a non-pointer variable, eliminating edges.\n",
2404 get_varinfo (node)->name);
2405 stats.nonpointer_vars++;
2406 clear_edges_for_node (graph, node);
2410 return si;
2413 /* Free information that was only necessary for variable
2414 substitution. */
2416 static void
2417 free_var_substitution_info (struct scc_info *si)
2419 free_scc_info (si);
2420 free (graph->pointer_label);
2421 free (graph->loc_label);
2422 free (graph->pointed_by);
2423 free (graph->points_to);
2424 free (graph->eq_rep);
2425 sbitmap_free (graph->direct_nodes);
2426 delete pointer_equiv_class_table;
2427 pointer_equiv_class_table = NULL;
2428 delete location_equiv_class_table;
2429 location_equiv_class_table = NULL;
2430 bitmap_obstack_release (&iteration_obstack);
2433 /* Return an existing node that is equivalent to NODE, which has
2434 equivalence class LABEL, if one exists. Return NODE otherwise. */
2436 static unsigned int
2437 find_equivalent_node (constraint_graph_t graph,
2438 unsigned int node, unsigned int label)
2440 /* If the address version of this variable is unused, we can
2441 substitute it for anything else with the same label.
2442 Otherwise, we know the pointers are equivalent, but not the
2443 locations, and we can unite them later. */
2445 if (!bitmap_bit_p (graph->address_taken, node))
2447 gcc_checking_assert (label < graph->size);
2449 if (graph->eq_rep[label] != -1)
2451 /* Unify the two variables since we know they are equivalent. */
2452 if (unite (graph->eq_rep[label], node))
2453 unify_nodes (graph, graph->eq_rep[label], node, false);
2454 return graph->eq_rep[label];
2456 else
2458 graph->eq_rep[label] = node;
2459 graph->pe_rep[label] = node;
2462 else
2464 gcc_checking_assert (label < graph->size);
2465 graph->pe[node] = label;
2466 if (graph->pe_rep[label] == -1)
2467 graph->pe_rep[label] = node;
2470 return node;
2473 /* Unite pointer equivalent but not location equivalent nodes in
2474 GRAPH. This may only be performed once variable substitution is
2475 finished. */
2477 static void
2478 unite_pointer_equivalences (constraint_graph_t graph)
2480 unsigned int i;
2482 /* Go through the pointer equivalences and unite them to their
2483 representative, if they aren't already. */
2484 for (i = 1; i < FIRST_REF_NODE; i++)
2486 unsigned int label = graph->pe[i];
2487 if (label)
2489 int label_rep = graph->pe_rep[label];
2491 if (label_rep == -1)
2492 continue;
2494 label_rep = find (label_rep);
2495 if (label_rep >= 0 && unite (label_rep, find (i)))
2496 unify_nodes (graph, label_rep, i, false);
2501 /* Move complex constraints to the GRAPH nodes they belong to. */
2503 static void
2504 move_complex_constraints (constraint_graph_t graph)
2506 int i;
2507 constraint_t c;
2509 FOR_EACH_VEC_ELT (constraints, i, c)
2511 if (c)
2513 struct constraint_expr lhs = c->lhs;
2514 struct constraint_expr rhs = c->rhs;
2516 if (lhs.type == DEREF)
2518 insert_into_complex (graph, lhs.var, c);
2520 else if (rhs.type == DEREF)
2522 if (!(get_varinfo (lhs.var)->is_special_var))
2523 insert_into_complex (graph, rhs.var, c);
2525 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2526 && (lhs.offset != 0 || rhs.offset != 0))
2528 insert_into_complex (graph, rhs.var, c);
2535 /* Optimize and rewrite complex constraints while performing
2536 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2537 result of perform_variable_substitution. */
2539 static void
2540 rewrite_constraints (constraint_graph_t graph,
2541 struct scc_info *si)
2543 int i;
2544 constraint_t c;
2546 if (flag_checking)
2548 for (unsigned int j = 0; j < graph->size; j++)
2549 gcc_assert (find (j) == j);
2552 FOR_EACH_VEC_ELT (constraints, i, c)
2554 struct constraint_expr lhs = c->lhs;
2555 struct constraint_expr rhs = c->rhs;
2556 unsigned int lhsvar = find (lhs.var);
2557 unsigned int rhsvar = find (rhs.var);
2558 unsigned int lhsnode, rhsnode;
2559 unsigned int lhslabel, rhslabel;
2561 lhsnode = si->node_mapping[lhsvar];
2562 rhsnode = si->node_mapping[rhsvar];
2563 lhslabel = graph->pointer_label[lhsnode];
2564 rhslabel = graph->pointer_label[rhsnode];
2566 /* See if it is really a non-pointer variable, and if so, ignore
2567 the constraint. */
2568 if (lhslabel == 0)
2570 if (dump_file && (dump_flags & TDF_DETAILS))
2573 fprintf (dump_file, "%s is a non-pointer variable,"
2574 "ignoring constraint:",
2575 get_varinfo (lhs.var)->name);
2576 dump_constraint (dump_file, c);
2577 fprintf (dump_file, "\n");
2579 constraints[i] = NULL;
2580 continue;
2583 if (rhslabel == 0)
2585 if (dump_file && (dump_flags & TDF_DETAILS))
2588 fprintf (dump_file, "%s is a non-pointer variable,"
2589 "ignoring constraint:",
2590 get_varinfo (rhs.var)->name);
2591 dump_constraint (dump_file, c);
2592 fprintf (dump_file, "\n");
2594 constraints[i] = NULL;
2595 continue;
2598 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2599 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2600 c->lhs.var = lhsvar;
2601 c->rhs.var = rhsvar;
2605 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2606 part of an SCC, false otherwise. */
2608 static bool
2609 eliminate_indirect_cycles (unsigned int node)
2611 if (graph->indirect_cycles[node] != -1
2612 && !bitmap_empty_p (get_varinfo (node)->solution))
2614 unsigned int i;
2615 auto_vec<unsigned> queue;
2616 int queuepos;
2617 unsigned int to = find (graph->indirect_cycles[node]);
2618 bitmap_iterator bi;
2620 /* We can't touch the solution set and call unify_nodes
2621 at the same time, because unify_nodes is going to do
2622 bitmap unions into it. */
2624 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2626 if (find (i) == i && i != to)
2628 if (unite (to, i))
2629 queue.safe_push (i);
2633 for (queuepos = 0;
2634 queue.iterate (queuepos, &i);
2635 queuepos++)
2637 unify_nodes (graph, to, i, true);
2639 return true;
2641 return false;
2644 /* Solve the constraint graph GRAPH using our worklist solver.
2645 This is based on the PW* family of solvers from the "Efficient Field
2646 Sensitive Pointer Analysis for C" paper.
2647 It works by iterating over all the graph nodes, processing the complex
2648 constraints and propagating the copy constraints, until everything stops
2649 changed. This corresponds to steps 6-8 in the solving list given above. */
2651 static void
2652 solve_graph (constraint_graph_t graph)
2654 unsigned int size = graph->size;
2655 unsigned int i;
2656 bitmap pts;
2658 changed = BITMAP_ALLOC (NULL);
2660 /* Mark all initial non-collapsed nodes as changed. */
2661 for (i = 1; i < size; i++)
2663 varinfo_t ivi = get_varinfo (i);
2664 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2665 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2666 || graph->complex[i].length () > 0))
2667 bitmap_set_bit (changed, i);
2670 /* Allocate a bitmap to be used to store the changed bits. */
2671 pts = BITMAP_ALLOC (&pta_obstack);
2673 while (!bitmap_empty_p (changed))
2675 unsigned int i;
2676 struct topo_info *ti = init_topo_info ();
2677 stats.iterations++;
2679 bitmap_obstack_initialize (&iteration_obstack);
2681 compute_topo_order (graph, ti);
2683 while (ti->topo_order.length () != 0)
2686 i = ti->topo_order.pop ();
2688 /* If this variable is not a representative, skip it. */
2689 if (find (i) != i)
2690 continue;
2692 /* In certain indirect cycle cases, we may merge this
2693 variable to another. */
2694 if (eliminate_indirect_cycles (i) && find (i) != i)
2695 continue;
2697 /* If the node has changed, we need to process the
2698 complex constraints and outgoing edges again. */
2699 if (bitmap_clear_bit (changed, i))
2701 unsigned int j;
2702 constraint_t c;
2703 bitmap solution;
2704 vec<constraint_t> complex = graph->complex[i];
2705 varinfo_t vi = get_varinfo (i);
2706 bool solution_empty;
2708 /* Compute the changed set of solution bits. If anything
2709 is in the solution just propagate that. */
2710 if (bitmap_bit_p (vi->solution, anything_id))
2712 /* If anything is also in the old solution there is
2713 nothing to do.
2714 ??? But we shouldn't ended up with "changed" set ... */
2715 if (vi->oldsolution
2716 && bitmap_bit_p (vi->oldsolution, anything_id))
2717 continue;
2718 bitmap_copy (pts, get_varinfo (find (anything_id))->solution);
2720 else if (vi->oldsolution)
2721 bitmap_and_compl (pts, vi->solution, vi->oldsolution);
2722 else
2723 bitmap_copy (pts, vi->solution);
2725 if (bitmap_empty_p (pts))
2726 continue;
2728 if (vi->oldsolution)
2729 bitmap_ior_into (vi->oldsolution, pts);
2730 else
2732 vi->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
2733 bitmap_copy (vi->oldsolution, pts);
2736 solution = vi->solution;
2737 solution_empty = bitmap_empty_p (solution);
2739 /* Process the complex constraints */
2740 bitmap expanded_pts = NULL;
2741 FOR_EACH_VEC_ELT (complex, j, c)
2743 /* XXX: This is going to unsort the constraints in
2744 some cases, which will occasionally add duplicate
2745 constraints during unification. This does not
2746 affect correctness. */
2747 c->lhs.var = find (c->lhs.var);
2748 c->rhs.var = find (c->rhs.var);
2750 /* The only complex constraint that can change our
2751 solution to non-empty, given an empty solution,
2752 is a constraint where the lhs side is receiving
2753 some set from elsewhere. */
2754 if (!solution_empty || c->lhs.type != DEREF)
2755 do_complex_constraint (graph, c, pts, &expanded_pts);
2757 BITMAP_FREE (expanded_pts);
2759 solution_empty = bitmap_empty_p (solution);
2761 if (!solution_empty)
2763 bitmap_iterator bi;
2764 unsigned eff_escaped_id = find (escaped_id);
2766 /* Propagate solution to all successors. */
2767 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2768 0, j, bi)
2770 bitmap tmp;
2771 bool flag;
2773 unsigned int to = find (j);
2774 tmp = get_varinfo (to)->solution;
2775 flag = false;
2777 /* Don't try to propagate to ourselves. */
2778 if (to == i)
2779 continue;
2781 /* If we propagate from ESCAPED use ESCAPED as
2782 placeholder. */
2783 if (i == eff_escaped_id)
2784 flag = bitmap_set_bit (tmp, escaped_id);
2785 else
2786 flag = bitmap_ior_into (tmp, pts);
2788 if (flag)
2789 bitmap_set_bit (changed, to);
2794 free_topo_info (ti);
2795 bitmap_obstack_release (&iteration_obstack);
2798 BITMAP_FREE (pts);
2799 BITMAP_FREE (changed);
2800 bitmap_obstack_release (&oldpta_obstack);
2803 /* Map from trees to variable infos. */
2804 static hash_map<tree, varinfo_t> *vi_for_tree;
2807 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2809 static void
2810 insert_vi_for_tree (tree t, varinfo_t vi)
2812 gcc_assert (vi);
2813 gcc_assert (!vi_for_tree->put (t, vi));
2816 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2817 exist in the map, return NULL, otherwise, return the varinfo we found. */
2819 static varinfo_t
2820 lookup_vi_for_tree (tree t)
2822 varinfo_t *slot = vi_for_tree->get (t);
2823 if (slot == NULL)
2824 return NULL;
2826 return *slot;
2829 /* Return a printable name for DECL */
2831 static const char *
2832 alias_get_name (tree decl)
2834 const char *res = NULL;
2835 char *temp;
2836 int num_printed = 0;
2838 if (!dump_file)
2839 return "NULL";
2841 if (TREE_CODE (decl) == SSA_NAME)
2843 res = get_name (decl);
2844 if (res)
2845 num_printed = asprintf (&temp, "%s_%u", res, SSA_NAME_VERSION (decl));
2846 else
2847 num_printed = asprintf (&temp, "_%u", SSA_NAME_VERSION (decl));
2848 if (num_printed > 0)
2850 res = ggc_strdup (temp);
2851 free (temp);
2854 else if (DECL_P (decl))
2856 if (DECL_ASSEMBLER_NAME_SET_P (decl))
2857 res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2858 else
2860 res = get_name (decl);
2861 if (!res)
2863 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2864 if (num_printed > 0)
2866 res = ggc_strdup (temp);
2867 free (temp);
2872 if (res != NULL)
2873 return res;
2875 return "NULL";
2878 /* Find the variable id for tree T in the map.
2879 If T doesn't exist in the map, create an entry for it and return it. */
2881 static varinfo_t
2882 get_vi_for_tree (tree t)
2884 varinfo_t *slot = vi_for_tree->get (t);
2885 if (slot == NULL)
2887 unsigned int id = create_variable_info_for (t, alias_get_name (t), false);
2888 return get_varinfo (id);
2891 return *slot;
2894 /* Get a scalar constraint expression for a new temporary variable. */
2896 static struct constraint_expr
2897 new_scalar_tmp_constraint_exp (const char *name, bool add_id)
2899 struct constraint_expr tmp;
2900 varinfo_t vi;
2902 vi = new_var_info (NULL_TREE, name, add_id);
2903 vi->offset = 0;
2904 vi->size = -1;
2905 vi->fullsize = -1;
2906 vi->is_full_var = 1;
2908 tmp.var = vi->id;
2909 tmp.type = SCALAR;
2910 tmp.offset = 0;
2912 return tmp;
2915 /* Get a constraint expression vector from an SSA_VAR_P node.
2916 If address_p is true, the result will be taken its address of. */
2918 static void
2919 get_constraint_for_ssa_var (tree t, vec<ce_s> *results, bool address_p)
2921 struct constraint_expr cexpr;
2922 varinfo_t vi;
2924 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2925 gcc_assert (TREE_CODE (t) == SSA_NAME || DECL_P (t));
2927 /* For parameters, get at the points-to set for the actual parm
2928 decl. */
2929 if (TREE_CODE (t) == SSA_NAME
2930 && SSA_NAME_IS_DEFAULT_DEF (t)
2931 && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2932 || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL))
2934 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2935 return;
2938 /* For global variables resort to the alias target. */
2939 if (TREE_CODE (t) == VAR_DECL
2940 && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2942 varpool_node *node = varpool_node::get (t);
2943 if (node && node->alias && node->analyzed)
2945 node = node->ultimate_alias_target ();
2946 /* Canonicalize the PT uid of all aliases to the ultimate target.
2947 ??? Hopefully the set of aliases can't change in a way that
2948 changes the ultimate alias target. */
2949 gcc_assert ((! DECL_PT_UID_SET_P (node->decl)
2950 || DECL_PT_UID (node->decl) == DECL_UID (node->decl))
2951 && (! DECL_PT_UID_SET_P (t)
2952 || DECL_PT_UID (t) == DECL_UID (node->decl)));
2953 DECL_PT_UID (t) = DECL_UID (node->decl);
2954 t = node->decl;
2958 vi = get_vi_for_tree (t);
2959 cexpr.var = vi->id;
2960 cexpr.type = SCALAR;
2961 cexpr.offset = 0;
2963 /* If we are not taking the address of the constraint expr, add all
2964 sub-fiels of the variable as well. */
2965 if (!address_p
2966 && !vi->is_full_var)
2968 for (; vi; vi = vi_next (vi))
2970 cexpr.var = vi->id;
2971 results->safe_push (cexpr);
2973 return;
2976 results->safe_push (cexpr);
2979 /* Process constraint T, performing various simplifications and then
2980 adding it to our list of overall constraints. */
2982 static void
2983 process_constraint (constraint_t t)
2985 struct constraint_expr rhs = t->rhs;
2986 struct constraint_expr lhs = t->lhs;
2988 gcc_assert (rhs.var < varmap.length ());
2989 gcc_assert (lhs.var < varmap.length ());
2991 /* If we didn't get any useful constraint from the lhs we get
2992 &ANYTHING as fallback from get_constraint_for. Deal with
2993 it here by turning it into *ANYTHING. */
2994 if (lhs.type == ADDRESSOF
2995 && lhs.var == anything_id)
2996 lhs.type = DEREF;
2998 /* ADDRESSOF on the lhs is invalid. */
2999 gcc_assert (lhs.type != ADDRESSOF);
3001 /* We shouldn't add constraints from things that cannot have pointers.
3002 It's not completely trivial to avoid in the callers, so do it here. */
3003 if (rhs.type != ADDRESSOF
3004 && !get_varinfo (rhs.var)->may_have_pointers)
3005 return;
3007 /* Likewise adding to the solution of a non-pointer var isn't useful. */
3008 if (!get_varinfo (lhs.var)->may_have_pointers)
3009 return;
3011 /* This can happen in our IR with things like n->a = *p */
3012 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
3014 /* Split into tmp = *rhs, *lhs = tmp */
3015 struct constraint_expr tmplhs;
3016 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp", true);
3017 process_constraint (new_constraint (tmplhs, rhs));
3018 process_constraint (new_constraint (lhs, tmplhs));
3020 else if ((rhs.type != SCALAR || rhs.offset != 0) && lhs.type == DEREF)
3022 /* Split into tmp = &rhs, *lhs = tmp */
3023 struct constraint_expr tmplhs;
3024 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp", true);
3025 process_constraint (new_constraint (tmplhs, rhs));
3026 process_constraint (new_constraint (lhs, tmplhs));
3028 else
3030 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
3031 constraints.safe_push (t);
3036 /* Return the position, in bits, of FIELD_DECL from the beginning of its
3037 structure. */
3039 static HOST_WIDE_INT
3040 bitpos_of_field (const tree fdecl)
3042 if (!tree_fits_shwi_p (DECL_FIELD_OFFSET (fdecl))
3043 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fdecl)))
3044 return -1;
3046 return (tree_to_shwi (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
3047 + tree_to_shwi (DECL_FIELD_BIT_OFFSET (fdecl)));
3051 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
3052 resulting constraint expressions in *RESULTS. */
3054 static void
3055 get_constraint_for_ptr_offset (tree ptr, tree offset,
3056 vec<ce_s> *results)
3058 struct constraint_expr c;
3059 unsigned int j, n;
3060 HOST_WIDE_INT rhsoffset;
3062 /* If we do not do field-sensitive PTA adding offsets to pointers
3063 does not change the points-to solution. */
3064 if (!use_field_sensitive)
3066 get_constraint_for_rhs (ptr, results);
3067 return;
3070 /* If the offset is not a non-negative integer constant that fits
3071 in a HOST_WIDE_INT, we have to fall back to a conservative
3072 solution which includes all sub-fields of all pointed-to
3073 variables of ptr. */
3074 if (offset == NULL_TREE
3075 || TREE_CODE (offset) != INTEGER_CST)
3076 rhsoffset = UNKNOWN_OFFSET;
3077 else
3079 /* Sign-extend the offset. */
3080 offset_int soffset = offset_int::from (offset, SIGNED);
3081 if (!wi::fits_shwi_p (soffset))
3082 rhsoffset = UNKNOWN_OFFSET;
3083 else
3085 /* Make sure the bit-offset also fits. */
3086 HOST_WIDE_INT rhsunitoffset = soffset.to_shwi ();
3087 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
3088 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
3089 rhsoffset = UNKNOWN_OFFSET;
3093 get_constraint_for_rhs (ptr, results);
3094 if (rhsoffset == 0)
3095 return;
3097 /* As we are eventually appending to the solution do not use
3098 vec::iterate here. */
3099 n = results->length ();
3100 for (j = 0; j < n; j++)
3102 varinfo_t curr;
3103 c = (*results)[j];
3104 curr = get_varinfo (c.var);
3106 if (c.type == ADDRESSOF
3107 /* If this varinfo represents a full variable just use it. */
3108 && curr->is_full_var)
3110 else if (c.type == ADDRESSOF
3111 /* If we do not know the offset add all subfields. */
3112 && rhsoffset == UNKNOWN_OFFSET)
3114 varinfo_t temp = get_varinfo (curr->head);
3117 struct constraint_expr c2;
3118 c2.var = temp->id;
3119 c2.type = ADDRESSOF;
3120 c2.offset = 0;
3121 if (c2.var != c.var)
3122 results->safe_push (c2);
3123 temp = vi_next (temp);
3125 while (temp);
3127 else if (c.type == ADDRESSOF)
3129 varinfo_t temp;
3130 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3132 /* If curr->offset + rhsoffset is less than zero adjust it. */
3133 if (rhsoffset < 0
3134 && curr->offset < offset)
3135 offset = 0;
3137 /* We have to include all fields that overlap the current
3138 field shifted by rhsoffset. And we include at least
3139 the last or the first field of the variable to represent
3140 reachability of off-bound addresses, in particular &object + 1,
3141 conservatively correct. */
3142 temp = first_or_preceding_vi_for_offset (curr, offset);
3143 c.var = temp->id;
3144 c.offset = 0;
3145 temp = vi_next (temp);
3146 while (temp
3147 && temp->offset < offset + curr->size)
3149 struct constraint_expr c2;
3150 c2.var = temp->id;
3151 c2.type = ADDRESSOF;
3152 c2.offset = 0;
3153 results->safe_push (c2);
3154 temp = vi_next (temp);
3157 else if (c.type == SCALAR)
3159 gcc_assert (c.offset == 0);
3160 c.offset = rhsoffset;
3162 else
3163 /* We shouldn't get any DEREFs here. */
3164 gcc_unreachable ();
3166 (*results)[j] = c;
3171 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3172 If address_p is true the result will be taken its address of.
3173 If lhs_p is true then the constraint expression is assumed to be used
3174 as the lhs. */
3176 static void
3177 get_constraint_for_component_ref (tree t, vec<ce_s> *results,
3178 bool address_p, bool lhs_p)
3180 tree orig_t = t;
3181 HOST_WIDE_INT bitsize = -1;
3182 HOST_WIDE_INT bitmaxsize = -1;
3183 HOST_WIDE_INT bitpos;
3184 bool reverse;
3185 tree forzero;
3187 /* Some people like to do cute things like take the address of
3188 &0->a.b */
3189 forzero = t;
3190 while (handled_component_p (forzero)
3191 || INDIRECT_REF_P (forzero)
3192 || TREE_CODE (forzero) == MEM_REF)
3193 forzero = TREE_OPERAND (forzero, 0);
3195 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3197 struct constraint_expr temp;
3199 temp.offset = 0;
3200 temp.var = integer_id;
3201 temp.type = SCALAR;
3202 results->safe_push (temp);
3203 return;
3206 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize, &reverse);
3208 /* Pretend to take the address of the base, we'll take care of
3209 adding the required subset of sub-fields below. */
3210 get_constraint_for_1 (t, results, true, lhs_p);
3211 gcc_assert (results->length () == 1);
3212 struct constraint_expr &result = results->last ();
3214 if (result.type == SCALAR
3215 && get_varinfo (result.var)->is_full_var)
3216 /* For single-field vars do not bother about the offset. */
3217 result.offset = 0;
3218 else if (result.type == SCALAR)
3220 /* In languages like C, you can access one past the end of an
3221 array. You aren't allowed to dereference it, so we can
3222 ignore this constraint. When we handle pointer subtraction,
3223 we may have to do something cute here. */
3225 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result.var)->fullsize
3226 && bitmaxsize != 0)
3228 /* It's also not true that the constraint will actually start at the
3229 right offset, it may start in some padding. We only care about
3230 setting the constraint to the first actual field it touches, so
3231 walk to find it. */
3232 struct constraint_expr cexpr = result;
3233 varinfo_t curr;
3234 results->pop ();
3235 cexpr.offset = 0;
3236 for (curr = get_varinfo (cexpr.var); curr; curr = vi_next (curr))
3238 if (ranges_overlap_p (curr->offset, curr->size,
3239 bitpos, bitmaxsize))
3241 cexpr.var = curr->id;
3242 results->safe_push (cexpr);
3243 if (address_p)
3244 break;
3247 /* If we are going to take the address of this field then
3248 to be able to compute reachability correctly add at least
3249 the last field of the variable. */
3250 if (address_p && results->length () == 0)
3252 curr = get_varinfo (cexpr.var);
3253 while (curr->next != 0)
3254 curr = vi_next (curr);
3255 cexpr.var = curr->id;
3256 results->safe_push (cexpr);
3258 else if (results->length () == 0)
3259 /* Assert that we found *some* field there. The user couldn't be
3260 accessing *only* padding. */
3261 /* Still the user could access one past the end of an array
3262 embedded in a struct resulting in accessing *only* padding. */
3263 /* Or accessing only padding via type-punning to a type
3264 that has a filed just in padding space. */
3266 cexpr.type = SCALAR;
3267 cexpr.var = anything_id;
3268 cexpr.offset = 0;
3269 results->safe_push (cexpr);
3272 else if (bitmaxsize == 0)
3274 if (dump_file && (dump_flags & TDF_DETAILS))
3275 fprintf (dump_file, "Access to zero-sized part of variable,"
3276 "ignoring\n");
3278 else
3279 if (dump_file && (dump_flags & TDF_DETAILS))
3280 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3282 else if (result.type == DEREF)
3284 /* If we do not know exactly where the access goes say so. Note
3285 that only for non-structure accesses we know that we access
3286 at most one subfiled of any variable. */
3287 if (bitpos == -1
3288 || bitsize != bitmaxsize
3289 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3290 || result.offset == UNKNOWN_OFFSET)
3291 result.offset = UNKNOWN_OFFSET;
3292 else
3293 result.offset += bitpos;
3295 else if (result.type == ADDRESSOF)
3297 /* We can end up here for component references on a
3298 VIEW_CONVERT_EXPR <>(&foobar). */
3299 result.type = SCALAR;
3300 result.var = anything_id;
3301 result.offset = 0;
3303 else
3304 gcc_unreachable ();
3308 /* Dereference the constraint expression CONS, and return the result.
3309 DEREF (ADDRESSOF) = SCALAR
3310 DEREF (SCALAR) = DEREF
3311 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3312 This is needed so that we can handle dereferencing DEREF constraints. */
3314 static void
3315 do_deref (vec<ce_s> *constraints)
3317 struct constraint_expr *c;
3318 unsigned int i = 0;
3320 FOR_EACH_VEC_ELT (*constraints, i, c)
3322 if (c->type == SCALAR)
3323 c->type = DEREF;
3324 else if (c->type == ADDRESSOF)
3325 c->type = SCALAR;
3326 else if (c->type == DEREF)
3328 struct constraint_expr tmplhs;
3329 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp", true);
3330 process_constraint (new_constraint (tmplhs, *c));
3331 c->var = tmplhs.var;
3333 else
3334 gcc_unreachable ();
3338 /* Given a tree T, return the constraint expression for taking the
3339 address of it. */
3341 static void
3342 get_constraint_for_address_of (tree t, vec<ce_s> *results)
3344 struct constraint_expr *c;
3345 unsigned int i;
3347 get_constraint_for_1 (t, results, true, true);
3349 FOR_EACH_VEC_ELT (*results, i, c)
3351 if (c->type == DEREF)
3352 c->type = SCALAR;
3353 else
3354 c->type = ADDRESSOF;
3358 /* Given a tree T, return the constraint expression for it. */
3360 static void
3361 get_constraint_for_1 (tree t, vec<ce_s> *results, bool address_p,
3362 bool lhs_p)
3364 struct constraint_expr temp;
3366 /* x = integer is all glommed to a single variable, which doesn't
3367 point to anything by itself. That is, of course, unless it is an
3368 integer constant being treated as a pointer, in which case, we
3369 will return that this is really the addressof anything. This
3370 happens below, since it will fall into the default case. The only
3371 case we know something about an integer treated like a pointer is
3372 when it is the NULL pointer, and then we just say it points to
3373 NULL.
3375 Do not do that if -fno-delete-null-pointer-checks though, because
3376 in that case *NULL does not fail, so it _should_ alias *anything.
3377 It is not worth adding a new option or renaming the existing one,
3378 since this case is relatively obscure. */
3379 if ((TREE_CODE (t) == INTEGER_CST
3380 && integer_zerop (t))
3381 /* The only valid CONSTRUCTORs in gimple with pointer typed
3382 elements are zero-initializer. But in IPA mode we also
3383 process global initializers, so verify at least. */
3384 || (TREE_CODE (t) == CONSTRUCTOR
3385 && CONSTRUCTOR_NELTS (t) == 0))
3387 if (flag_delete_null_pointer_checks)
3388 temp.var = nothing_id;
3389 else
3390 temp.var = nonlocal_id;
3391 temp.type = ADDRESSOF;
3392 temp.offset = 0;
3393 results->safe_push (temp);
3394 return;
3397 /* String constants are read-only, ideally we'd have a CONST_DECL
3398 for those. */
3399 if (TREE_CODE (t) == STRING_CST)
3401 temp.var = string_id;
3402 temp.type = SCALAR;
3403 temp.offset = 0;
3404 results->safe_push (temp);
3405 return;
3408 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3410 case tcc_expression:
3412 switch (TREE_CODE (t))
3414 case ADDR_EXPR:
3415 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3416 return;
3417 default:;
3419 break;
3421 case tcc_reference:
3423 switch (TREE_CODE (t))
3425 case MEM_REF:
3427 struct constraint_expr cs;
3428 varinfo_t vi, curr;
3429 get_constraint_for_ptr_offset (TREE_OPERAND (t, 0),
3430 TREE_OPERAND (t, 1), results);
3431 do_deref (results);
3433 /* If we are not taking the address then make sure to process
3434 all subvariables we might access. */
3435 if (address_p)
3436 return;
3438 cs = results->last ();
3439 if (cs.type == DEREF
3440 && type_can_have_subvars (TREE_TYPE (t)))
3442 /* For dereferences this means we have to defer it
3443 to solving time. */
3444 results->last ().offset = UNKNOWN_OFFSET;
3445 return;
3447 if (cs.type != SCALAR)
3448 return;
3450 vi = get_varinfo (cs.var);
3451 curr = vi_next (vi);
3452 if (!vi->is_full_var
3453 && curr)
3455 unsigned HOST_WIDE_INT size;
3456 if (tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (t))))
3457 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (t)));
3458 else
3459 size = -1;
3460 for (; curr; curr = vi_next (curr))
3462 if (curr->offset - vi->offset < size)
3464 cs.var = curr->id;
3465 results->safe_push (cs);
3467 else
3468 break;
3471 return;
3473 case ARRAY_REF:
3474 case ARRAY_RANGE_REF:
3475 case COMPONENT_REF:
3476 case IMAGPART_EXPR:
3477 case REALPART_EXPR:
3478 case BIT_FIELD_REF:
3479 get_constraint_for_component_ref (t, results, address_p, lhs_p);
3480 return;
3481 case VIEW_CONVERT_EXPR:
3482 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3483 lhs_p);
3484 return;
3485 /* We are missing handling for TARGET_MEM_REF here. */
3486 default:;
3488 break;
3490 case tcc_exceptional:
3492 switch (TREE_CODE (t))
3494 case SSA_NAME:
3496 get_constraint_for_ssa_var (t, results, address_p);
3497 return;
3499 case CONSTRUCTOR:
3501 unsigned int i;
3502 tree val;
3503 auto_vec<ce_s> tmp;
3504 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3506 struct constraint_expr *rhsp;
3507 unsigned j;
3508 get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3509 FOR_EACH_VEC_ELT (tmp, j, rhsp)
3510 results->safe_push (*rhsp);
3511 tmp.truncate (0);
3513 /* We do not know whether the constructor was complete,
3514 so technically we have to add &NOTHING or &ANYTHING
3515 like we do for an empty constructor as well. */
3516 return;
3518 default:;
3520 break;
3522 case tcc_declaration:
3524 get_constraint_for_ssa_var (t, results, address_p);
3525 return;
3527 case tcc_constant:
3529 /* We cannot refer to automatic variables through constants. */
3530 temp.type = ADDRESSOF;
3531 temp.var = nonlocal_id;
3532 temp.offset = 0;
3533 results->safe_push (temp);
3534 return;
3536 default:;
3539 /* The default fallback is a constraint from anything. */
3540 temp.type = ADDRESSOF;
3541 temp.var = anything_id;
3542 temp.offset = 0;
3543 results->safe_push (temp);
3546 /* Given a gimple tree T, return the constraint expression vector for it. */
3548 static void
3549 get_constraint_for (tree t, vec<ce_s> *results)
3551 gcc_assert (results->length () == 0);
3553 get_constraint_for_1 (t, results, false, true);
3556 /* Given a gimple tree T, return the constraint expression vector for it
3557 to be used as the rhs of a constraint. */
3559 static void
3560 get_constraint_for_rhs (tree t, vec<ce_s> *results)
3562 gcc_assert (results->length () == 0);
3564 get_constraint_for_1 (t, results, false, false);
3568 /* Efficiently generates constraints from all entries in *RHSC to all
3569 entries in *LHSC. */
3571 static void
3572 process_all_all_constraints (vec<ce_s> lhsc,
3573 vec<ce_s> rhsc)
3575 struct constraint_expr *lhsp, *rhsp;
3576 unsigned i, j;
3578 if (lhsc.length () <= 1 || rhsc.length () <= 1)
3580 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3581 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
3582 process_constraint (new_constraint (*lhsp, *rhsp));
3584 else
3586 struct constraint_expr tmp;
3587 tmp = new_scalar_tmp_constraint_exp ("allalltmp", true);
3588 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
3589 process_constraint (new_constraint (tmp, *rhsp));
3590 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3591 process_constraint (new_constraint (*lhsp, tmp));
3595 /* Handle aggregate copies by expanding into copies of the respective
3596 fields of the structures. */
3598 static void
3599 do_structure_copy (tree lhsop, tree rhsop)
3601 struct constraint_expr *lhsp, *rhsp;
3602 auto_vec<ce_s> lhsc;
3603 auto_vec<ce_s> rhsc;
3604 unsigned j;
3606 get_constraint_for (lhsop, &lhsc);
3607 get_constraint_for_rhs (rhsop, &rhsc);
3608 lhsp = &lhsc[0];
3609 rhsp = &rhsc[0];
3610 if (lhsp->type == DEREF
3611 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3612 || rhsp->type == DEREF)
3614 if (lhsp->type == DEREF)
3616 gcc_assert (lhsc.length () == 1);
3617 lhsp->offset = UNKNOWN_OFFSET;
3619 if (rhsp->type == DEREF)
3621 gcc_assert (rhsc.length () == 1);
3622 rhsp->offset = UNKNOWN_OFFSET;
3624 process_all_all_constraints (lhsc, rhsc);
3626 else if (lhsp->type == SCALAR
3627 && (rhsp->type == SCALAR
3628 || rhsp->type == ADDRESSOF))
3630 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3631 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3632 bool reverse;
3633 unsigned k = 0;
3634 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize,
3635 &reverse);
3636 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize,
3637 &reverse);
3638 for (j = 0; lhsc.iterate (j, &lhsp);)
3640 varinfo_t lhsv, rhsv;
3641 rhsp = &rhsc[k];
3642 lhsv = get_varinfo (lhsp->var);
3643 rhsv = get_varinfo (rhsp->var);
3644 if (lhsv->may_have_pointers
3645 && (lhsv->is_full_var
3646 || rhsv->is_full_var
3647 || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3648 rhsv->offset + lhsoffset, rhsv->size)))
3649 process_constraint (new_constraint (*lhsp, *rhsp));
3650 if (!rhsv->is_full_var
3651 && (lhsv->is_full_var
3652 || (lhsv->offset + rhsoffset + lhsv->size
3653 > rhsv->offset + lhsoffset + rhsv->size)))
3655 ++k;
3656 if (k >= rhsc.length ())
3657 break;
3659 else
3660 ++j;
3663 else
3664 gcc_unreachable ();
3667 /* Create constraints ID = { rhsc }. */
3669 static void
3670 make_constraints_to (unsigned id, vec<ce_s> rhsc)
3672 struct constraint_expr *c;
3673 struct constraint_expr includes;
3674 unsigned int j;
3676 includes.var = id;
3677 includes.offset = 0;
3678 includes.type = SCALAR;
3680 FOR_EACH_VEC_ELT (rhsc, j, c)
3681 process_constraint (new_constraint (includes, *c));
3684 /* Create a constraint ID = OP. */
3686 static void
3687 make_constraint_to (unsigned id, tree op)
3689 auto_vec<ce_s> rhsc;
3690 get_constraint_for_rhs (op, &rhsc);
3691 make_constraints_to (id, rhsc);
3694 /* Create a constraint ID = &FROM. */
3696 static void
3697 make_constraint_from (varinfo_t vi, int from)
3699 struct constraint_expr lhs, rhs;
3701 lhs.var = vi->id;
3702 lhs.offset = 0;
3703 lhs.type = SCALAR;
3705 rhs.var = from;
3706 rhs.offset = 0;
3707 rhs.type = ADDRESSOF;
3708 process_constraint (new_constraint (lhs, rhs));
3711 /* Create a constraint ID = FROM. */
3713 static void
3714 make_copy_constraint (varinfo_t vi, int from)
3716 struct constraint_expr lhs, rhs;
3718 lhs.var = vi->id;
3719 lhs.offset = 0;
3720 lhs.type = SCALAR;
3722 rhs.var = from;
3723 rhs.offset = 0;
3724 rhs.type = SCALAR;
3725 process_constraint (new_constraint (lhs, rhs));
3728 /* Make constraints necessary to make OP escape. */
3730 static void
3731 make_escape_constraint (tree op)
3733 make_constraint_to (escaped_id, op);
3736 /* Add constraints to that the solution of VI is transitively closed. */
3738 static void
3739 make_transitive_closure_constraints (varinfo_t vi)
3741 struct constraint_expr lhs, rhs;
3743 /* VAR = *(VAR + UNKNOWN); */
3744 lhs.type = SCALAR;
3745 lhs.var = vi->id;
3746 lhs.offset = 0;
3747 rhs.type = DEREF;
3748 rhs.var = vi->id;
3749 rhs.offset = UNKNOWN_OFFSET;
3750 process_constraint (new_constraint (lhs, rhs));
3753 /* Add constraints to that the solution of VI has all subvariables added. */
3755 static void
3756 make_any_offset_constraints (varinfo_t vi)
3758 struct constraint_expr lhs, rhs;
3760 /* VAR = VAR + UNKNOWN; */
3761 lhs.type = SCALAR;
3762 lhs.var = vi->id;
3763 lhs.offset = 0;
3764 rhs.type = SCALAR;
3765 rhs.var = vi->id;
3766 rhs.offset = UNKNOWN_OFFSET;
3767 process_constraint (new_constraint (lhs, rhs));
3770 /* Temporary storage for fake var decls. */
3771 struct obstack fake_var_decl_obstack;
3773 /* Build a fake VAR_DECL acting as referrer to a DECL_UID. */
3775 static tree
3776 build_fake_var_decl (tree type)
3778 tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3779 memset (decl, 0, sizeof (struct tree_var_decl));
3780 TREE_SET_CODE (decl, VAR_DECL);
3781 TREE_TYPE (decl) = type;
3782 DECL_UID (decl) = allocate_decl_uid ();
3783 SET_DECL_PT_UID (decl, -1);
3784 layout_decl (decl, 0);
3785 return decl;
3788 /* Create a new artificial heap variable with NAME.
3789 Return the created variable. */
3791 static varinfo_t
3792 make_heapvar (const char *name, bool add_id)
3794 varinfo_t vi;
3795 tree heapvar;
3797 heapvar = build_fake_var_decl (ptr_type_node);
3798 DECL_EXTERNAL (heapvar) = 1;
3800 vi = new_var_info (heapvar, name, add_id);
3801 vi->is_artificial_var = true;
3802 vi->is_heap_var = true;
3803 vi->is_unknown_size_var = true;
3804 vi->offset = 0;
3805 vi->fullsize = ~0;
3806 vi->size = ~0;
3807 vi->is_full_var = true;
3808 insert_vi_for_tree (heapvar, vi);
3810 return vi;
3813 /* Create a new artificial heap variable with NAME and make a
3814 constraint from it to LHS. Set flags according to a tag used
3815 for tracking restrict pointers. */
3817 static varinfo_t
3818 make_constraint_from_restrict (varinfo_t lhs, const char *name, bool add_id)
3820 varinfo_t vi = make_heapvar (name, add_id);
3821 vi->is_restrict_var = 1;
3822 vi->is_global_var = 1;
3823 vi->may_have_pointers = 1;
3824 make_constraint_from (lhs, vi->id);
3825 return vi;
3828 /* Create a new artificial heap variable with NAME and make a
3829 constraint from it to LHS. Set flags according to a tag used
3830 for tracking restrict pointers and make the artificial heap
3831 point to global memory. */
3833 static varinfo_t
3834 make_constraint_from_global_restrict (varinfo_t lhs, const char *name,
3835 bool add_id)
3837 varinfo_t vi = make_constraint_from_restrict (lhs, name, add_id);
3838 make_copy_constraint (vi, nonlocal_id);
3839 return vi;
3842 /* In IPA mode there are varinfos for different aspects of reach
3843 function designator. One for the points-to set of the return
3844 value, one for the variables that are clobbered by the function,
3845 one for its uses and one for each parameter (including a single
3846 glob for remaining variadic arguments). */
3848 enum { fi_clobbers = 1, fi_uses = 2,
3849 fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3851 /* Get a constraint for the requested part of a function designator FI
3852 when operating in IPA mode. */
3854 static struct constraint_expr
3855 get_function_part_constraint (varinfo_t fi, unsigned part)
3857 struct constraint_expr c;
3859 gcc_assert (in_ipa_mode);
3861 if (fi->id == anything_id)
3863 /* ??? We probably should have a ANYFN special variable. */
3864 c.var = anything_id;
3865 c.offset = 0;
3866 c.type = SCALAR;
3868 else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3870 varinfo_t ai = first_vi_for_offset (fi, part);
3871 if (ai)
3872 c.var = ai->id;
3873 else
3874 c.var = anything_id;
3875 c.offset = 0;
3876 c.type = SCALAR;
3878 else
3880 c.var = fi->id;
3881 c.offset = part;
3882 c.type = DEREF;
3885 return c;
3888 /* For non-IPA mode, generate constraints necessary for a call on the
3889 RHS. */
3891 static void
3892 handle_rhs_call (gcall *stmt, vec<ce_s> *results)
3894 struct constraint_expr rhsc;
3895 unsigned i;
3896 bool returns_uses = false;
3898 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3900 tree arg = gimple_call_arg (stmt, i);
3901 int flags = gimple_call_arg_flags (stmt, i);
3903 /* If the argument is not used we can ignore it. */
3904 if (flags & EAF_UNUSED)
3905 continue;
3907 /* As we compute ESCAPED context-insensitive we do not gain
3908 any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3909 set. The argument would still get clobbered through the
3910 escape solution. */
3911 if ((flags & EAF_NOCLOBBER)
3912 && (flags & EAF_NOESCAPE))
3914 varinfo_t uses = get_call_use_vi (stmt);
3915 varinfo_t tem = new_var_info (NULL_TREE, "callarg", true);
3916 make_constraint_to (tem->id, arg);
3917 make_any_offset_constraints (tem);
3918 if (!(flags & EAF_DIRECT))
3919 make_transitive_closure_constraints (tem);
3920 make_copy_constraint (uses, tem->id);
3921 returns_uses = true;
3923 else if (flags & EAF_NOESCAPE)
3925 struct constraint_expr lhs, rhs;
3926 varinfo_t uses = get_call_use_vi (stmt);
3927 varinfo_t clobbers = get_call_clobber_vi (stmt);
3928 varinfo_t tem = new_var_info (NULL_TREE, "callarg", true);
3929 make_constraint_to (tem->id, arg);
3930 make_any_offset_constraints (tem);
3931 if (!(flags & EAF_DIRECT))
3932 make_transitive_closure_constraints (tem);
3933 make_copy_constraint (uses, tem->id);
3934 make_copy_constraint (clobbers, tem->id);
3935 /* Add *tem = nonlocal, do not add *tem = callused as
3936 EAF_NOESCAPE parameters do not escape to other parameters
3937 and all other uses appear in NONLOCAL as well. */
3938 lhs.type = DEREF;
3939 lhs.var = tem->id;
3940 lhs.offset = 0;
3941 rhs.type = SCALAR;
3942 rhs.var = nonlocal_id;
3943 rhs.offset = 0;
3944 process_constraint (new_constraint (lhs, rhs));
3945 returns_uses = true;
3947 else
3948 make_escape_constraint (arg);
3951 /* If we added to the calls uses solution make sure we account for
3952 pointers to it to be returned. */
3953 if (returns_uses)
3955 rhsc.var = get_call_use_vi (stmt)->id;
3956 rhsc.offset = UNKNOWN_OFFSET;
3957 rhsc.type = SCALAR;
3958 results->safe_push (rhsc);
3961 /* The static chain escapes as well. */
3962 if (gimple_call_chain (stmt))
3963 make_escape_constraint (gimple_call_chain (stmt));
3965 /* And if we applied NRV the address of the return slot escapes as well. */
3966 if (gimple_call_return_slot_opt_p (stmt)
3967 && gimple_call_lhs (stmt) != NULL_TREE
3968 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3970 auto_vec<ce_s> tmpc;
3971 struct constraint_expr lhsc, *c;
3972 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3973 lhsc.var = escaped_id;
3974 lhsc.offset = 0;
3975 lhsc.type = SCALAR;
3976 FOR_EACH_VEC_ELT (tmpc, i, c)
3977 process_constraint (new_constraint (lhsc, *c));
3980 /* Regular functions return nonlocal memory. */
3981 rhsc.var = nonlocal_id;
3982 rhsc.offset = 0;
3983 rhsc.type = SCALAR;
3984 results->safe_push (rhsc);
3987 /* For non-IPA mode, generate constraints necessary for a call
3988 that returns a pointer and assigns it to LHS. This simply makes
3989 the LHS point to global and escaped variables. */
3991 static void
3992 handle_lhs_call (gcall *stmt, tree lhs, int flags, vec<ce_s> rhsc,
3993 tree fndecl)
3995 auto_vec<ce_s> lhsc;
3997 get_constraint_for (lhs, &lhsc);
3998 /* If the store is to a global decl make sure to
3999 add proper escape constraints. */
4000 lhs = get_base_address (lhs);
4001 if (lhs
4002 && DECL_P (lhs)
4003 && is_global_var (lhs))
4005 struct constraint_expr tmpc;
4006 tmpc.var = escaped_id;
4007 tmpc.offset = 0;
4008 tmpc.type = SCALAR;
4009 lhsc.safe_push (tmpc);
4012 /* If the call returns an argument unmodified override the rhs
4013 constraints. */
4014 if (flags & ERF_RETURNS_ARG
4015 && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
4017 tree arg;
4018 rhsc.create (0);
4019 arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
4020 get_constraint_for (arg, &rhsc);
4021 process_all_all_constraints (lhsc, rhsc);
4022 rhsc.release ();
4024 else if (flags & ERF_NOALIAS)
4026 varinfo_t vi;
4027 struct constraint_expr tmpc;
4028 rhsc.create (0);
4029 vi = make_heapvar ("HEAP", true);
4030 /* We are marking allocated storage local, we deal with it becoming
4031 global by escaping and setting of vars_contains_escaped_heap. */
4032 DECL_EXTERNAL (vi->decl) = 0;
4033 vi->is_global_var = 0;
4034 /* If this is not a real malloc call assume the memory was
4035 initialized and thus may point to global memory. All
4036 builtin functions with the malloc attribute behave in a sane way. */
4037 if (!fndecl
4038 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
4039 make_constraint_from (vi, nonlocal_id);
4040 tmpc.var = vi->id;
4041 tmpc.offset = 0;
4042 tmpc.type = ADDRESSOF;
4043 rhsc.safe_push (tmpc);
4044 process_all_all_constraints (lhsc, rhsc);
4045 rhsc.release ();
4047 else
4048 process_all_all_constraints (lhsc, rhsc);
4051 /* For non-IPA mode, generate constraints necessary for a call of a
4052 const function that returns a pointer in the statement STMT. */
4054 static void
4055 handle_const_call (gcall *stmt, vec<ce_s> *results)
4057 struct constraint_expr rhsc;
4058 unsigned int k;
4059 bool need_uses = false;
4061 /* Treat nested const functions the same as pure functions as far
4062 as the static chain is concerned. */
4063 if (gimple_call_chain (stmt))
4065 varinfo_t uses = get_call_use_vi (stmt);
4066 make_constraint_to (uses->id, gimple_call_chain (stmt));
4067 need_uses = true;
4070 /* And if we applied NRV the address of the return slot escapes as well. */
4071 if (gimple_call_return_slot_opt_p (stmt)
4072 && gimple_call_lhs (stmt) != NULL_TREE
4073 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
4075 varinfo_t uses = get_call_use_vi (stmt);
4076 auto_vec<ce_s> tmpc;
4077 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
4078 make_constraints_to (uses->id, tmpc);
4079 need_uses = true;
4082 if (need_uses)
4084 varinfo_t uses = get_call_use_vi (stmt);
4085 make_any_offset_constraints (uses);
4086 make_transitive_closure_constraints (uses);
4087 rhsc.var = uses->id;
4088 rhsc.offset = 0;
4089 rhsc.type = SCALAR;
4090 results->safe_push (rhsc);
4093 /* May return offsetted arguments. */
4094 varinfo_t tem = NULL;
4095 if (gimple_call_num_args (stmt) != 0)
4096 tem = new_var_info (NULL_TREE, "callarg", true);
4097 for (k = 0; k < gimple_call_num_args (stmt); ++k)
4099 tree arg = gimple_call_arg (stmt, k);
4100 auto_vec<ce_s> argc;
4101 get_constraint_for_rhs (arg, &argc);
4102 make_constraints_to (tem->id, argc);
4104 if (tem)
4106 ce_s ce;
4107 ce.type = SCALAR;
4108 ce.var = tem->id;
4109 ce.offset = UNKNOWN_OFFSET;
4110 results->safe_push (ce);
4113 /* May return addresses of globals. */
4114 rhsc.var = nonlocal_id;
4115 rhsc.offset = 0;
4116 rhsc.type = ADDRESSOF;
4117 results->safe_push (rhsc);
4120 /* For non-IPA mode, generate constraints necessary for a call to a
4121 pure function in statement STMT. */
4123 static void
4124 handle_pure_call (gcall *stmt, vec<ce_s> *results)
4126 struct constraint_expr rhsc;
4127 unsigned i;
4128 varinfo_t uses = NULL;
4130 /* Memory reached from pointer arguments is call-used. */
4131 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4133 tree arg = gimple_call_arg (stmt, i);
4134 if (!uses)
4136 uses = get_call_use_vi (stmt);
4137 make_any_offset_constraints (uses);
4138 make_transitive_closure_constraints (uses);
4140 make_constraint_to (uses->id, arg);
4143 /* The static chain is used as well. */
4144 if (gimple_call_chain (stmt))
4146 if (!uses)
4148 uses = get_call_use_vi (stmt);
4149 make_any_offset_constraints (uses);
4150 make_transitive_closure_constraints (uses);
4152 make_constraint_to (uses->id, gimple_call_chain (stmt));
4155 /* And if we applied NRV the address of the return slot. */
4156 if (gimple_call_return_slot_opt_p (stmt)
4157 && gimple_call_lhs (stmt) != NULL_TREE
4158 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
4160 if (!uses)
4162 uses = get_call_use_vi (stmt);
4163 make_any_offset_constraints (uses);
4164 make_transitive_closure_constraints (uses);
4166 auto_vec<ce_s> tmpc;
4167 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
4168 make_constraints_to (uses->id, tmpc);
4171 /* Pure functions may return call-used and nonlocal memory. */
4172 if (uses)
4174 rhsc.var = uses->id;
4175 rhsc.offset = 0;
4176 rhsc.type = SCALAR;
4177 results->safe_push (rhsc);
4179 rhsc.var = nonlocal_id;
4180 rhsc.offset = 0;
4181 rhsc.type = SCALAR;
4182 results->safe_push (rhsc);
4186 /* Return the varinfo for the callee of CALL. */
4188 static varinfo_t
4189 get_fi_for_callee (gcall *call)
4191 tree decl, fn = gimple_call_fn (call);
4193 if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
4194 fn = OBJ_TYPE_REF_EXPR (fn);
4196 /* If we can directly resolve the function being called, do so.
4197 Otherwise, it must be some sort of indirect expression that
4198 we should still be able to handle. */
4199 decl = gimple_call_addr_fndecl (fn);
4200 if (decl)
4201 return get_vi_for_tree (decl);
4203 /* If the function is anything other than a SSA name pointer we have no
4204 clue and should be getting ANYFN (well, ANYTHING for now). */
4205 if (!fn || TREE_CODE (fn) != SSA_NAME)
4206 return get_varinfo (anything_id);
4208 if (SSA_NAME_IS_DEFAULT_DEF (fn)
4209 && (TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
4210 || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL))
4211 fn = SSA_NAME_VAR (fn);
4213 return get_vi_for_tree (fn);
4216 /* Create constraints for assigning call argument ARG to the incoming parameter
4217 INDEX of function FI. */
4219 static void
4220 find_func_aliases_for_call_arg (varinfo_t fi, unsigned index, tree arg)
4222 struct constraint_expr lhs;
4223 lhs = get_function_part_constraint (fi, fi_parm_base + index);
4225 auto_vec<ce_s, 2> rhsc;
4226 get_constraint_for_rhs (arg, &rhsc);
4228 unsigned j;
4229 struct constraint_expr *rhsp;
4230 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4231 process_constraint (new_constraint (lhs, *rhsp));
4234 /* Return true if FNDECL may be part of another lto partition. */
4236 static bool
4237 fndecl_maybe_in_other_partition (tree fndecl)
4239 cgraph_node *fn_node = cgraph_node::get (fndecl);
4240 if (fn_node == NULL)
4241 return true;
4243 return fn_node->in_other_partition;
4246 /* Create constraints for the builtin call T. Return true if the call
4247 was handled, otherwise false. */
4249 static bool
4250 find_func_aliases_for_builtin_call (struct function *fn, gcall *t)
4252 tree fndecl = gimple_call_fndecl (t);
4253 auto_vec<ce_s, 2> lhsc;
4254 auto_vec<ce_s, 4> rhsc;
4255 varinfo_t fi;
4257 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4258 /* ??? All builtins that are handled here need to be handled
4259 in the alias-oracle query functions explicitly! */
4260 switch (DECL_FUNCTION_CODE (fndecl))
4262 /* All the following functions return a pointer to the same object
4263 as their first argument points to. The functions do not add
4264 to the ESCAPED solution. The functions make the first argument
4265 pointed to memory point to what the second argument pointed to
4266 memory points to. */
4267 case BUILT_IN_STRCPY:
4268 case BUILT_IN_STRNCPY:
4269 case BUILT_IN_BCOPY:
4270 case BUILT_IN_MEMCPY:
4271 case BUILT_IN_MEMMOVE:
4272 case BUILT_IN_MEMPCPY:
4273 case BUILT_IN_STPCPY:
4274 case BUILT_IN_STPNCPY:
4275 case BUILT_IN_STRCAT:
4276 case BUILT_IN_STRNCAT:
4277 case BUILT_IN_STRCPY_CHK:
4278 case BUILT_IN_STRNCPY_CHK:
4279 case BUILT_IN_MEMCPY_CHK:
4280 case BUILT_IN_MEMMOVE_CHK:
4281 case BUILT_IN_MEMPCPY_CHK:
4282 case BUILT_IN_STPCPY_CHK:
4283 case BUILT_IN_STPNCPY_CHK:
4284 case BUILT_IN_STRCAT_CHK:
4285 case BUILT_IN_STRNCAT_CHK:
4286 case BUILT_IN_TM_MEMCPY:
4287 case BUILT_IN_TM_MEMMOVE:
4289 tree res = gimple_call_lhs (t);
4290 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4291 == BUILT_IN_BCOPY ? 1 : 0));
4292 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4293 == BUILT_IN_BCOPY ? 0 : 1));
4294 if (res != NULL_TREE)
4296 get_constraint_for (res, &lhsc);
4297 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4298 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4299 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4300 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4301 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK
4302 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY_CHK)
4303 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4304 else
4305 get_constraint_for (dest, &rhsc);
4306 process_all_all_constraints (lhsc, rhsc);
4307 lhsc.truncate (0);
4308 rhsc.truncate (0);
4310 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4311 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4312 do_deref (&lhsc);
4313 do_deref (&rhsc);
4314 process_all_all_constraints (lhsc, rhsc);
4315 return true;
4317 case BUILT_IN_MEMSET:
4318 case BUILT_IN_MEMSET_CHK:
4319 case BUILT_IN_TM_MEMSET:
4321 tree res = gimple_call_lhs (t);
4322 tree dest = gimple_call_arg (t, 0);
4323 unsigned i;
4324 ce_s *lhsp;
4325 struct constraint_expr ac;
4326 if (res != NULL_TREE)
4328 get_constraint_for (res, &lhsc);
4329 get_constraint_for (dest, &rhsc);
4330 process_all_all_constraints (lhsc, rhsc);
4331 lhsc.truncate (0);
4333 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4334 do_deref (&lhsc);
4335 if (flag_delete_null_pointer_checks
4336 && integer_zerop (gimple_call_arg (t, 1)))
4338 ac.type = ADDRESSOF;
4339 ac.var = nothing_id;
4341 else
4343 ac.type = SCALAR;
4344 ac.var = integer_id;
4346 ac.offset = 0;
4347 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4348 process_constraint (new_constraint (*lhsp, ac));
4349 return true;
4351 case BUILT_IN_POSIX_MEMALIGN:
4353 tree ptrptr = gimple_call_arg (t, 0);
4354 get_constraint_for (ptrptr, &lhsc);
4355 do_deref (&lhsc);
4356 varinfo_t vi = make_heapvar ("HEAP", true);
4357 /* We are marking allocated storage local, we deal with it becoming
4358 global by escaping and setting of vars_contains_escaped_heap. */
4359 DECL_EXTERNAL (vi->decl) = 0;
4360 vi->is_global_var = 0;
4361 struct constraint_expr tmpc;
4362 tmpc.var = vi->id;
4363 tmpc.offset = 0;
4364 tmpc.type = ADDRESSOF;
4365 rhsc.safe_push (tmpc);
4366 process_all_all_constraints (lhsc, rhsc);
4367 return true;
4369 case BUILT_IN_ASSUME_ALIGNED:
4371 tree res = gimple_call_lhs (t);
4372 tree dest = gimple_call_arg (t, 0);
4373 if (res != NULL_TREE)
4375 get_constraint_for (res, &lhsc);
4376 get_constraint_for (dest, &rhsc);
4377 process_all_all_constraints (lhsc, rhsc);
4379 return true;
4381 /* All the following functions do not return pointers, do not
4382 modify the points-to sets of memory reachable from their
4383 arguments and do not add to the ESCAPED solution. */
4384 case BUILT_IN_SINCOS:
4385 case BUILT_IN_SINCOSF:
4386 case BUILT_IN_SINCOSL:
4387 case BUILT_IN_FREXP:
4388 case BUILT_IN_FREXPF:
4389 case BUILT_IN_FREXPL:
4390 case BUILT_IN_GAMMA_R:
4391 case BUILT_IN_GAMMAF_R:
4392 case BUILT_IN_GAMMAL_R:
4393 case BUILT_IN_LGAMMA_R:
4394 case BUILT_IN_LGAMMAF_R:
4395 case BUILT_IN_LGAMMAL_R:
4396 case BUILT_IN_MODF:
4397 case BUILT_IN_MODFF:
4398 case BUILT_IN_MODFL:
4399 case BUILT_IN_REMQUO:
4400 case BUILT_IN_REMQUOF:
4401 case BUILT_IN_REMQUOL:
4402 case BUILT_IN_FREE:
4403 return true;
4404 case BUILT_IN_STRDUP:
4405 case BUILT_IN_STRNDUP:
4406 case BUILT_IN_REALLOC:
4407 if (gimple_call_lhs (t))
4409 handle_lhs_call (t, gimple_call_lhs (t),
4410 gimple_call_return_flags (t) | ERF_NOALIAS,
4411 vNULL, fndecl);
4412 get_constraint_for_ptr_offset (gimple_call_lhs (t),
4413 NULL_TREE, &lhsc);
4414 get_constraint_for_ptr_offset (gimple_call_arg (t, 0),
4415 NULL_TREE, &rhsc);
4416 do_deref (&lhsc);
4417 do_deref (&rhsc);
4418 process_all_all_constraints (lhsc, rhsc);
4419 lhsc.truncate (0);
4420 rhsc.truncate (0);
4421 /* For realloc the resulting pointer can be equal to the
4422 argument as well. But only doing this wouldn't be
4423 correct because with ptr == 0 realloc behaves like malloc. */
4424 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_REALLOC)
4426 get_constraint_for (gimple_call_lhs (t), &lhsc);
4427 get_constraint_for (gimple_call_arg (t, 0), &rhsc);
4428 process_all_all_constraints (lhsc, rhsc);
4430 return true;
4432 break;
4433 /* String / character search functions return a pointer into the
4434 source string or NULL. */
4435 case BUILT_IN_INDEX:
4436 case BUILT_IN_STRCHR:
4437 case BUILT_IN_STRRCHR:
4438 case BUILT_IN_MEMCHR:
4439 case BUILT_IN_STRSTR:
4440 case BUILT_IN_STRPBRK:
4441 if (gimple_call_lhs (t))
4443 tree src = gimple_call_arg (t, 0);
4444 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4445 constraint_expr nul;
4446 nul.var = nothing_id;
4447 nul.offset = 0;
4448 nul.type = ADDRESSOF;
4449 rhsc.safe_push (nul);
4450 get_constraint_for (gimple_call_lhs (t), &lhsc);
4451 process_all_all_constraints (lhsc, rhsc);
4453 return true;
4454 /* Trampolines are special - they set up passing the static
4455 frame. */
4456 case BUILT_IN_INIT_TRAMPOLINE:
4458 tree tramp = gimple_call_arg (t, 0);
4459 tree nfunc = gimple_call_arg (t, 1);
4460 tree frame = gimple_call_arg (t, 2);
4461 unsigned i;
4462 struct constraint_expr lhs, *rhsp;
4463 if (in_ipa_mode)
4465 varinfo_t nfi = NULL;
4466 gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4467 nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4468 if (nfi)
4470 lhs = get_function_part_constraint (nfi, fi_static_chain);
4471 get_constraint_for (frame, &rhsc);
4472 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4473 process_constraint (new_constraint (lhs, *rhsp));
4474 rhsc.truncate (0);
4476 /* Make the frame point to the function for
4477 the trampoline adjustment call. */
4478 get_constraint_for (tramp, &lhsc);
4479 do_deref (&lhsc);
4480 get_constraint_for (nfunc, &rhsc);
4481 process_all_all_constraints (lhsc, rhsc);
4483 return true;
4486 /* Else fallthru to generic handling which will let
4487 the frame escape. */
4488 break;
4490 case BUILT_IN_ADJUST_TRAMPOLINE:
4492 tree tramp = gimple_call_arg (t, 0);
4493 tree res = gimple_call_lhs (t);
4494 if (in_ipa_mode && res)
4496 get_constraint_for (res, &lhsc);
4497 get_constraint_for (tramp, &rhsc);
4498 do_deref (&rhsc);
4499 process_all_all_constraints (lhsc, rhsc);
4501 return true;
4503 CASE_BUILT_IN_TM_STORE (1):
4504 CASE_BUILT_IN_TM_STORE (2):
4505 CASE_BUILT_IN_TM_STORE (4):
4506 CASE_BUILT_IN_TM_STORE (8):
4507 CASE_BUILT_IN_TM_STORE (FLOAT):
4508 CASE_BUILT_IN_TM_STORE (DOUBLE):
4509 CASE_BUILT_IN_TM_STORE (LDOUBLE):
4510 CASE_BUILT_IN_TM_STORE (M64):
4511 CASE_BUILT_IN_TM_STORE (M128):
4512 CASE_BUILT_IN_TM_STORE (M256):
4514 tree addr = gimple_call_arg (t, 0);
4515 tree src = gimple_call_arg (t, 1);
4517 get_constraint_for (addr, &lhsc);
4518 do_deref (&lhsc);
4519 get_constraint_for (src, &rhsc);
4520 process_all_all_constraints (lhsc, rhsc);
4521 return true;
4523 CASE_BUILT_IN_TM_LOAD (1):
4524 CASE_BUILT_IN_TM_LOAD (2):
4525 CASE_BUILT_IN_TM_LOAD (4):
4526 CASE_BUILT_IN_TM_LOAD (8):
4527 CASE_BUILT_IN_TM_LOAD (FLOAT):
4528 CASE_BUILT_IN_TM_LOAD (DOUBLE):
4529 CASE_BUILT_IN_TM_LOAD (LDOUBLE):
4530 CASE_BUILT_IN_TM_LOAD (M64):
4531 CASE_BUILT_IN_TM_LOAD (M128):
4532 CASE_BUILT_IN_TM_LOAD (M256):
4534 tree dest = gimple_call_lhs (t);
4535 tree addr = gimple_call_arg (t, 0);
4537 get_constraint_for (dest, &lhsc);
4538 get_constraint_for (addr, &rhsc);
4539 do_deref (&rhsc);
4540 process_all_all_constraints (lhsc, rhsc);
4541 return true;
4543 /* Variadic argument handling needs to be handled in IPA
4544 mode as well. */
4545 case BUILT_IN_VA_START:
4547 tree valist = gimple_call_arg (t, 0);
4548 struct constraint_expr rhs, *lhsp;
4549 unsigned i;
4550 get_constraint_for (valist, &lhsc);
4551 do_deref (&lhsc);
4552 /* The va_list gets access to pointers in variadic
4553 arguments. Which we know in the case of IPA analysis
4554 and otherwise are just all nonlocal variables. */
4555 if (in_ipa_mode)
4557 fi = lookup_vi_for_tree (fn->decl);
4558 rhs = get_function_part_constraint (fi, ~0);
4559 rhs.type = ADDRESSOF;
4561 else
4563 rhs.var = nonlocal_id;
4564 rhs.type = ADDRESSOF;
4565 rhs.offset = 0;
4567 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4568 process_constraint (new_constraint (*lhsp, rhs));
4569 /* va_list is clobbered. */
4570 make_constraint_to (get_call_clobber_vi (t)->id, valist);
4571 return true;
4573 /* va_end doesn't have any effect that matters. */
4574 case BUILT_IN_VA_END:
4575 return true;
4576 /* Alternate return. Simply give up for now. */
4577 case BUILT_IN_RETURN:
4579 fi = NULL;
4580 if (!in_ipa_mode
4581 || !(fi = get_vi_for_tree (fn->decl)))
4582 make_constraint_from (get_varinfo (escaped_id), anything_id);
4583 else if (in_ipa_mode
4584 && fi != NULL)
4586 struct constraint_expr lhs, rhs;
4587 lhs = get_function_part_constraint (fi, fi_result);
4588 rhs.var = anything_id;
4589 rhs.offset = 0;
4590 rhs.type = SCALAR;
4591 process_constraint (new_constraint (lhs, rhs));
4593 return true;
4595 case BUILT_IN_GOMP_PARALLEL:
4596 case BUILT_IN_GOACC_PARALLEL:
4598 if (in_ipa_mode)
4600 unsigned int fnpos, argpos;
4601 switch (DECL_FUNCTION_CODE (fndecl))
4603 case BUILT_IN_GOMP_PARALLEL:
4604 /* __builtin_GOMP_parallel (fn, data, num_threads, flags). */
4605 fnpos = 0;
4606 argpos = 1;
4607 break;
4608 case BUILT_IN_GOACC_PARALLEL:
4609 /* __builtin_GOACC_parallel (device, fn, mapnum, hostaddrs,
4610 sizes, kinds, ...). */
4611 fnpos = 1;
4612 argpos = 3;
4613 break;
4614 default:
4615 gcc_unreachable ();
4618 tree fnarg = gimple_call_arg (t, fnpos);
4619 gcc_assert (TREE_CODE (fnarg) == ADDR_EXPR);
4620 tree fndecl = TREE_OPERAND (fnarg, 0);
4621 if (fndecl_maybe_in_other_partition (fndecl))
4622 /* Fallthru to general call handling. */
4623 break;
4625 tree arg = gimple_call_arg (t, argpos);
4627 varinfo_t fi = get_vi_for_tree (fndecl);
4628 find_func_aliases_for_call_arg (fi, 0, arg);
4629 return true;
4631 /* Else fallthru to generic call handling. */
4632 break;
4634 /* printf-style functions may have hooks to set pointers to
4635 point to somewhere into the generated string. Leave them
4636 for a later exercise... */
4637 default:
4638 /* Fallthru to general call handling. */;
4641 return false;
4644 /* Create constraints for the call T. */
4646 static void
4647 find_func_aliases_for_call (struct function *fn, gcall *t)
4649 tree fndecl = gimple_call_fndecl (t);
4650 varinfo_t fi;
4652 if (fndecl != NULL_TREE
4653 && DECL_BUILT_IN (fndecl)
4654 && find_func_aliases_for_builtin_call (fn, t))
4655 return;
4657 fi = get_fi_for_callee (t);
4658 if (!in_ipa_mode
4659 || (fndecl && !fi->is_fn_info))
4661 auto_vec<ce_s, 16> rhsc;
4662 int flags = gimple_call_flags (t);
4664 /* Const functions can return their arguments and addresses
4665 of global memory but not of escaped memory. */
4666 if (flags & (ECF_CONST|ECF_NOVOPS))
4668 if (gimple_call_lhs (t))
4669 handle_const_call (t, &rhsc);
4671 /* Pure functions can return addresses in and of memory
4672 reachable from their arguments, but they are not an escape
4673 point for reachable memory of their arguments. */
4674 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4675 handle_pure_call (t, &rhsc);
4676 else
4677 handle_rhs_call (t, &rhsc);
4678 if (gimple_call_lhs (t))
4679 handle_lhs_call (t, gimple_call_lhs (t),
4680 gimple_call_return_flags (t), rhsc, fndecl);
4682 else
4684 auto_vec<ce_s, 2> rhsc;
4685 tree lhsop;
4686 unsigned j;
4688 /* Assign all the passed arguments to the appropriate incoming
4689 parameters of the function. */
4690 for (j = 0; j < gimple_call_num_args (t); j++)
4692 tree arg = gimple_call_arg (t, j);
4693 find_func_aliases_for_call_arg (fi, j, arg);
4696 /* If we are returning a value, assign it to the result. */
4697 lhsop = gimple_call_lhs (t);
4698 if (lhsop)
4700 auto_vec<ce_s, 2> lhsc;
4701 struct constraint_expr rhs;
4702 struct constraint_expr *lhsp;
4703 bool aggr_p = aggregate_value_p (lhsop, gimple_call_fntype (t));
4705 get_constraint_for (lhsop, &lhsc);
4706 rhs = get_function_part_constraint (fi, fi_result);
4707 if (aggr_p)
4709 auto_vec<ce_s, 2> tem;
4710 tem.quick_push (rhs);
4711 do_deref (&tem);
4712 gcc_checking_assert (tem.length () == 1);
4713 rhs = tem[0];
4715 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4716 process_constraint (new_constraint (*lhsp, rhs));
4718 /* If we pass the result decl by reference, honor that. */
4719 if (aggr_p)
4721 struct constraint_expr lhs;
4722 struct constraint_expr *rhsp;
4724 get_constraint_for_address_of (lhsop, &rhsc);
4725 lhs = get_function_part_constraint (fi, fi_result);
4726 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4727 process_constraint (new_constraint (lhs, *rhsp));
4728 rhsc.truncate (0);
4732 /* If we use a static chain, pass it along. */
4733 if (gimple_call_chain (t))
4735 struct constraint_expr lhs;
4736 struct constraint_expr *rhsp;
4738 get_constraint_for (gimple_call_chain (t), &rhsc);
4739 lhs = get_function_part_constraint (fi, fi_static_chain);
4740 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4741 process_constraint (new_constraint (lhs, *rhsp));
4746 /* Walk statement T setting up aliasing constraints according to the
4747 references found in T. This function is the main part of the
4748 constraint builder. AI points to auxiliary alias information used
4749 when building alias sets and computing alias grouping heuristics. */
4751 static void
4752 find_func_aliases (struct function *fn, gimple *origt)
4754 gimple *t = origt;
4755 auto_vec<ce_s, 16> lhsc;
4756 auto_vec<ce_s, 16> rhsc;
4757 struct constraint_expr *c;
4758 varinfo_t fi;
4760 /* Now build constraints expressions. */
4761 if (gimple_code (t) == GIMPLE_PHI)
4763 size_t i;
4764 unsigned int j;
4766 /* For a phi node, assign all the arguments to
4767 the result. */
4768 get_constraint_for (gimple_phi_result (t), &lhsc);
4769 for (i = 0; i < gimple_phi_num_args (t); i++)
4771 tree strippedrhs = PHI_ARG_DEF (t, i);
4773 STRIP_NOPS (strippedrhs);
4774 get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4776 FOR_EACH_VEC_ELT (lhsc, j, c)
4778 struct constraint_expr *c2;
4779 while (rhsc.length () > 0)
4781 c2 = &rhsc.last ();
4782 process_constraint (new_constraint (*c, *c2));
4783 rhsc.pop ();
4788 /* In IPA mode, we need to generate constraints to pass call
4789 arguments through their calls. There are two cases,
4790 either a GIMPLE_CALL returning a value, or just a plain
4791 GIMPLE_CALL when we are not.
4793 In non-ipa mode, we need to generate constraints for each
4794 pointer passed by address. */
4795 else if (is_gimple_call (t))
4796 find_func_aliases_for_call (fn, as_a <gcall *> (t));
4798 /* Otherwise, just a regular assignment statement. Only care about
4799 operations with pointer result, others are dealt with as escape
4800 points if they have pointer operands. */
4801 else if (is_gimple_assign (t))
4803 /* Otherwise, just a regular assignment statement. */
4804 tree lhsop = gimple_assign_lhs (t);
4805 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4807 if (rhsop && TREE_CLOBBER_P (rhsop))
4808 /* Ignore clobbers, they don't actually store anything into
4809 the LHS. */
4811 else if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4812 do_structure_copy (lhsop, rhsop);
4813 else
4815 enum tree_code code = gimple_assign_rhs_code (t);
4817 get_constraint_for (lhsop, &lhsc);
4819 if (code == POINTER_PLUS_EXPR)
4820 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4821 gimple_assign_rhs2 (t), &rhsc);
4822 else if (code == BIT_AND_EXPR
4823 && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4825 /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4826 the pointer. Handle it by offsetting it by UNKNOWN. */
4827 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4828 NULL_TREE, &rhsc);
4830 else if ((CONVERT_EXPR_CODE_P (code)
4831 && !(POINTER_TYPE_P (gimple_expr_type (t))
4832 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4833 || gimple_assign_single_p (t))
4834 get_constraint_for_rhs (rhsop, &rhsc);
4835 else if (code == COND_EXPR)
4837 /* The result is a merge of both COND_EXPR arms. */
4838 auto_vec<ce_s, 2> tmp;
4839 struct constraint_expr *rhsp;
4840 unsigned i;
4841 get_constraint_for_rhs (gimple_assign_rhs2 (t), &rhsc);
4842 get_constraint_for_rhs (gimple_assign_rhs3 (t), &tmp);
4843 FOR_EACH_VEC_ELT (tmp, i, rhsp)
4844 rhsc.safe_push (*rhsp);
4846 else if (truth_value_p (code))
4847 /* Truth value results are not pointer (parts). Or at least
4848 very unreasonable obfuscation of a part. */
4850 else
4852 /* All other operations are merges. */
4853 auto_vec<ce_s, 4> tmp;
4854 struct constraint_expr *rhsp;
4855 unsigned i, j;
4856 get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4857 for (i = 2; i < gimple_num_ops (t); ++i)
4859 get_constraint_for_rhs (gimple_op (t, i), &tmp);
4860 FOR_EACH_VEC_ELT (tmp, j, rhsp)
4861 rhsc.safe_push (*rhsp);
4862 tmp.truncate (0);
4865 process_all_all_constraints (lhsc, rhsc);
4867 /* If there is a store to a global variable the rhs escapes. */
4868 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4869 && DECL_P (lhsop))
4871 varinfo_t vi = get_vi_for_tree (lhsop);
4872 if ((! in_ipa_mode && vi->is_global_var)
4873 || vi->is_ipa_escape_point)
4874 make_escape_constraint (rhsop);
4877 /* Handle escapes through return. */
4878 else if (gimple_code (t) == GIMPLE_RETURN
4879 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE)
4881 greturn *return_stmt = as_a <greturn *> (t);
4882 fi = NULL;
4883 if (!in_ipa_mode
4884 || !(fi = get_vi_for_tree (fn->decl)))
4885 make_escape_constraint (gimple_return_retval (return_stmt));
4886 else if (in_ipa_mode)
4888 struct constraint_expr lhs ;
4889 struct constraint_expr *rhsp;
4890 unsigned i;
4892 lhs = get_function_part_constraint (fi, fi_result);
4893 get_constraint_for_rhs (gimple_return_retval (return_stmt), &rhsc);
4894 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4895 process_constraint (new_constraint (lhs, *rhsp));
4898 /* Handle asms conservatively by adding escape constraints to everything. */
4899 else if (gasm *asm_stmt = dyn_cast <gasm *> (t))
4901 unsigned i, noutputs;
4902 const char **oconstraints;
4903 const char *constraint;
4904 bool allows_mem, allows_reg, is_inout;
4906 noutputs = gimple_asm_noutputs (asm_stmt);
4907 oconstraints = XALLOCAVEC (const char *, noutputs);
4909 for (i = 0; i < noutputs; ++i)
4911 tree link = gimple_asm_output_op (asm_stmt, i);
4912 tree op = TREE_VALUE (link);
4914 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4915 oconstraints[i] = constraint;
4916 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4917 &allows_reg, &is_inout);
4919 /* A memory constraint makes the address of the operand escape. */
4920 if (!allows_reg && allows_mem)
4921 make_escape_constraint (build_fold_addr_expr (op));
4923 /* The asm may read global memory, so outputs may point to
4924 any global memory. */
4925 if (op)
4927 auto_vec<ce_s, 2> lhsc;
4928 struct constraint_expr rhsc, *lhsp;
4929 unsigned j;
4930 get_constraint_for (op, &lhsc);
4931 rhsc.var = nonlocal_id;
4932 rhsc.offset = 0;
4933 rhsc.type = SCALAR;
4934 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4935 process_constraint (new_constraint (*lhsp, rhsc));
4938 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4940 tree link = gimple_asm_input_op (asm_stmt, i);
4941 tree op = TREE_VALUE (link);
4943 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4945 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4946 &allows_mem, &allows_reg);
4948 /* A memory constraint makes the address of the operand escape. */
4949 if (!allows_reg && allows_mem)
4950 make_escape_constraint (build_fold_addr_expr (op));
4951 /* Strictly we'd only need the constraint to ESCAPED if
4952 the asm clobbers memory, otherwise using something
4953 along the lines of per-call clobbers/uses would be enough. */
4954 else if (op)
4955 make_escape_constraint (op);
4961 /* Create a constraint adding to the clobber set of FI the memory
4962 pointed to by PTR. */
4964 static void
4965 process_ipa_clobber (varinfo_t fi, tree ptr)
4967 vec<ce_s> ptrc = vNULL;
4968 struct constraint_expr *c, lhs;
4969 unsigned i;
4970 get_constraint_for_rhs (ptr, &ptrc);
4971 lhs = get_function_part_constraint (fi, fi_clobbers);
4972 FOR_EACH_VEC_ELT (ptrc, i, c)
4973 process_constraint (new_constraint (lhs, *c));
4974 ptrc.release ();
4977 /* Walk statement T setting up clobber and use constraints according to the
4978 references found in T. This function is a main part of the
4979 IPA constraint builder. */
4981 static void
4982 find_func_clobbers (struct function *fn, gimple *origt)
4984 gimple *t = origt;
4985 auto_vec<ce_s, 16> lhsc;
4986 auto_vec<ce_s, 16> rhsc;
4987 varinfo_t fi;
4989 /* Add constraints for clobbered/used in IPA mode.
4990 We are not interested in what automatic variables are clobbered
4991 or used as we only use the information in the caller to which
4992 they do not escape. */
4993 gcc_assert (in_ipa_mode);
4995 /* If the stmt refers to memory in any way it better had a VUSE. */
4996 if (gimple_vuse (t) == NULL_TREE)
4997 return;
4999 /* We'd better have function information for the current function. */
5000 fi = lookup_vi_for_tree (fn->decl);
5001 gcc_assert (fi != NULL);
5003 /* Account for stores in assignments and calls. */
5004 if (gimple_vdef (t) != NULL_TREE
5005 && gimple_has_lhs (t))
5007 tree lhs = gimple_get_lhs (t);
5008 tree tem = lhs;
5009 while (handled_component_p (tem))
5010 tem = TREE_OPERAND (tem, 0);
5011 if ((DECL_P (tem)
5012 && !auto_var_in_fn_p (tem, fn->decl))
5013 || INDIRECT_REF_P (tem)
5014 || (TREE_CODE (tem) == MEM_REF
5015 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
5016 && auto_var_in_fn_p
5017 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
5019 struct constraint_expr lhsc, *rhsp;
5020 unsigned i;
5021 lhsc = get_function_part_constraint (fi, fi_clobbers);
5022 get_constraint_for_address_of (lhs, &rhsc);
5023 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5024 process_constraint (new_constraint (lhsc, *rhsp));
5025 rhsc.truncate (0);
5029 /* Account for uses in assigments and returns. */
5030 if (gimple_assign_single_p (t)
5031 || (gimple_code (t) == GIMPLE_RETURN
5032 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE))
5034 tree rhs = (gimple_assign_single_p (t)
5035 ? gimple_assign_rhs1 (t)
5036 : gimple_return_retval (as_a <greturn *> (t)));
5037 tree tem = rhs;
5038 while (handled_component_p (tem))
5039 tem = TREE_OPERAND (tem, 0);
5040 if ((DECL_P (tem)
5041 && !auto_var_in_fn_p (tem, fn->decl))
5042 || INDIRECT_REF_P (tem)
5043 || (TREE_CODE (tem) == MEM_REF
5044 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
5045 && auto_var_in_fn_p
5046 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
5048 struct constraint_expr lhs, *rhsp;
5049 unsigned i;
5050 lhs = get_function_part_constraint (fi, fi_uses);
5051 get_constraint_for_address_of (rhs, &rhsc);
5052 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5053 process_constraint (new_constraint (lhs, *rhsp));
5054 rhsc.truncate (0);
5058 if (gcall *call_stmt = dyn_cast <gcall *> (t))
5060 varinfo_t cfi = NULL;
5061 tree decl = gimple_call_fndecl (t);
5062 struct constraint_expr lhs, rhs;
5063 unsigned i, j;
5065 /* For builtins we do not have separate function info. For those
5066 we do not generate escapes for we have to generate clobbers/uses. */
5067 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
5068 switch (DECL_FUNCTION_CODE (decl))
5070 /* The following functions use and clobber memory pointed to
5071 by their arguments. */
5072 case BUILT_IN_STRCPY:
5073 case BUILT_IN_STRNCPY:
5074 case BUILT_IN_BCOPY:
5075 case BUILT_IN_MEMCPY:
5076 case BUILT_IN_MEMMOVE:
5077 case BUILT_IN_MEMPCPY:
5078 case BUILT_IN_STPCPY:
5079 case BUILT_IN_STPNCPY:
5080 case BUILT_IN_STRCAT:
5081 case BUILT_IN_STRNCAT:
5082 case BUILT_IN_STRCPY_CHK:
5083 case BUILT_IN_STRNCPY_CHK:
5084 case BUILT_IN_MEMCPY_CHK:
5085 case BUILT_IN_MEMMOVE_CHK:
5086 case BUILT_IN_MEMPCPY_CHK:
5087 case BUILT_IN_STPCPY_CHK:
5088 case BUILT_IN_STPNCPY_CHK:
5089 case BUILT_IN_STRCAT_CHK:
5090 case BUILT_IN_STRNCAT_CHK:
5092 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
5093 == BUILT_IN_BCOPY ? 1 : 0));
5094 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
5095 == BUILT_IN_BCOPY ? 0 : 1));
5096 unsigned i;
5097 struct constraint_expr *rhsp, *lhsp;
5098 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
5099 lhs = get_function_part_constraint (fi, fi_clobbers);
5100 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5101 process_constraint (new_constraint (lhs, *lhsp));
5102 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
5103 lhs = get_function_part_constraint (fi, fi_uses);
5104 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5105 process_constraint (new_constraint (lhs, *rhsp));
5106 return;
5108 /* The following function clobbers memory pointed to by
5109 its argument. */
5110 case BUILT_IN_MEMSET:
5111 case BUILT_IN_MEMSET_CHK:
5112 case BUILT_IN_POSIX_MEMALIGN:
5114 tree dest = gimple_call_arg (t, 0);
5115 unsigned i;
5116 ce_s *lhsp;
5117 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
5118 lhs = get_function_part_constraint (fi, fi_clobbers);
5119 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5120 process_constraint (new_constraint (lhs, *lhsp));
5121 return;
5123 /* The following functions clobber their second and third
5124 arguments. */
5125 case BUILT_IN_SINCOS:
5126 case BUILT_IN_SINCOSF:
5127 case BUILT_IN_SINCOSL:
5129 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5130 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5131 return;
5133 /* The following functions clobber their second argument. */
5134 case BUILT_IN_FREXP:
5135 case BUILT_IN_FREXPF:
5136 case BUILT_IN_FREXPL:
5137 case BUILT_IN_LGAMMA_R:
5138 case BUILT_IN_LGAMMAF_R:
5139 case BUILT_IN_LGAMMAL_R:
5140 case BUILT_IN_GAMMA_R:
5141 case BUILT_IN_GAMMAF_R:
5142 case BUILT_IN_GAMMAL_R:
5143 case BUILT_IN_MODF:
5144 case BUILT_IN_MODFF:
5145 case BUILT_IN_MODFL:
5147 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5148 return;
5150 /* The following functions clobber their third argument. */
5151 case BUILT_IN_REMQUO:
5152 case BUILT_IN_REMQUOF:
5153 case BUILT_IN_REMQUOL:
5155 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5156 return;
5158 /* The following functions neither read nor clobber memory. */
5159 case BUILT_IN_ASSUME_ALIGNED:
5160 case BUILT_IN_FREE:
5161 return;
5162 /* Trampolines are of no interest to us. */
5163 case BUILT_IN_INIT_TRAMPOLINE:
5164 case BUILT_IN_ADJUST_TRAMPOLINE:
5165 return;
5166 case BUILT_IN_VA_START:
5167 case BUILT_IN_VA_END:
5168 return;
5169 case BUILT_IN_GOMP_PARALLEL:
5170 case BUILT_IN_GOACC_PARALLEL:
5172 unsigned int fnpos, argpos;
5173 unsigned int implicit_use_args[2];
5174 unsigned int num_implicit_use_args = 0;
5175 switch (DECL_FUNCTION_CODE (decl))
5177 case BUILT_IN_GOMP_PARALLEL:
5178 /* __builtin_GOMP_parallel (fn, data, num_threads, flags). */
5179 fnpos = 0;
5180 argpos = 1;
5181 break;
5182 case BUILT_IN_GOACC_PARALLEL:
5183 /* __builtin_GOACC_parallel (device, fn, mapnum, hostaddrs,
5184 sizes, kinds, ...). */
5185 fnpos = 1;
5186 argpos = 3;
5187 implicit_use_args[num_implicit_use_args++] = 4;
5188 implicit_use_args[num_implicit_use_args++] = 5;
5189 break;
5190 default:
5191 gcc_unreachable ();
5194 tree fnarg = gimple_call_arg (t, fnpos);
5195 gcc_assert (TREE_CODE (fnarg) == ADDR_EXPR);
5196 tree fndecl = TREE_OPERAND (fnarg, 0);
5197 if (fndecl_maybe_in_other_partition (fndecl))
5198 /* Fallthru to general call handling. */
5199 break;
5201 varinfo_t cfi = get_vi_for_tree (fndecl);
5203 tree arg = gimple_call_arg (t, argpos);
5205 /* Parameter passed by value is used. */
5206 lhs = get_function_part_constraint (fi, fi_uses);
5207 struct constraint_expr *rhsp;
5208 get_constraint_for (arg, &rhsc);
5209 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5210 process_constraint (new_constraint (lhs, *rhsp));
5211 rhsc.truncate (0);
5213 /* Handle parameters used by the call, but not used in cfi, as
5214 implicitly used by cfi. */
5215 lhs = get_function_part_constraint (cfi, fi_uses);
5216 for (unsigned i = 0; i < num_implicit_use_args; ++i)
5218 tree arg = gimple_call_arg (t, implicit_use_args[i]);
5219 get_constraint_for (arg, &rhsc);
5220 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5221 process_constraint (new_constraint (lhs, *rhsp));
5222 rhsc.truncate (0);
5225 /* The caller clobbers what the callee does. */
5226 lhs = get_function_part_constraint (fi, fi_clobbers);
5227 rhs = get_function_part_constraint (cfi, fi_clobbers);
5228 process_constraint (new_constraint (lhs, rhs));
5230 /* The caller uses what the callee does. */
5231 lhs = get_function_part_constraint (fi, fi_uses);
5232 rhs = get_function_part_constraint (cfi, fi_uses);
5233 process_constraint (new_constraint (lhs, rhs));
5235 return;
5237 /* printf-style functions may have hooks to set pointers to
5238 point to somewhere into the generated string. Leave them
5239 for a later exercise... */
5240 default:
5241 /* Fallthru to general call handling. */;
5244 /* Parameters passed by value are used. */
5245 lhs = get_function_part_constraint (fi, fi_uses);
5246 for (i = 0; i < gimple_call_num_args (t); i++)
5248 struct constraint_expr *rhsp;
5249 tree arg = gimple_call_arg (t, i);
5251 if (TREE_CODE (arg) == SSA_NAME
5252 || is_gimple_min_invariant (arg))
5253 continue;
5255 get_constraint_for_address_of (arg, &rhsc);
5256 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5257 process_constraint (new_constraint (lhs, *rhsp));
5258 rhsc.truncate (0);
5261 /* Build constraints for propagating clobbers/uses along the
5262 callgraph edges. */
5263 cfi = get_fi_for_callee (call_stmt);
5264 if (cfi->id == anything_id)
5266 if (gimple_vdef (t))
5267 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5268 anything_id);
5269 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5270 anything_id);
5271 return;
5274 /* For callees without function info (that's external functions),
5275 ESCAPED is clobbered and used. */
5276 if (gimple_call_fndecl (t)
5277 && !cfi->is_fn_info)
5279 varinfo_t vi;
5281 if (gimple_vdef (t))
5282 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5283 escaped_id);
5284 make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
5286 /* Also honor the call statement use/clobber info. */
5287 if ((vi = lookup_call_clobber_vi (call_stmt)) != NULL)
5288 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5289 vi->id);
5290 if ((vi = lookup_call_use_vi (call_stmt)) != NULL)
5291 make_copy_constraint (first_vi_for_offset (fi, fi_uses),
5292 vi->id);
5293 return;
5296 /* Otherwise the caller clobbers and uses what the callee does.
5297 ??? This should use a new complex constraint that filters
5298 local variables of the callee. */
5299 if (gimple_vdef (t))
5301 lhs = get_function_part_constraint (fi, fi_clobbers);
5302 rhs = get_function_part_constraint (cfi, fi_clobbers);
5303 process_constraint (new_constraint (lhs, rhs));
5305 lhs = get_function_part_constraint (fi, fi_uses);
5306 rhs = get_function_part_constraint (cfi, fi_uses);
5307 process_constraint (new_constraint (lhs, rhs));
5309 else if (gimple_code (t) == GIMPLE_ASM)
5311 /* ??? Ick. We can do better. */
5312 if (gimple_vdef (t))
5313 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5314 anything_id);
5315 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5316 anything_id);
5321 /* Find the first varinfo in the same variable as START that overlaps with
5322 OFFSET. Return NULL if we can't find one. */
5324 static varinfo_t
5325 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
5327 /* If the offset is outside of the variable, bail out. */
5328 if (offset >= start->fullsize)
5329 return NULL;
5331 /* If we cannot reach offset from start, lookup the first field
5332 and start from there. */
5333 if (start->offset > offset)
5334 start = get_varinfo (start->head);
5336 while (start)
5338 /* We may not find a variable in the field list with the actual
5339 offset when we have glommed a structure to a variable.
5340 In that case, however, offset should still be within the size
5341 of the variable. */
5342 if (offset >= start->offset
5343 && (offset - start->offset) < start->size)
5344 return start;
5346 start = vi_next (start);
5349 return NULL;
5352 /* Find the first varinfo in the same variable as START that overlaps with
5353 OFFSET. If there is no such varinfo the varinfo directly preceding
5354 OFFSET is returned. */
5356 static varinfo_t
5357 first_or_preceding_vi_for_offset (varinfo_t start,
5358 unsigned HOST_WIDE_INT offset)
5360 /* If we cannot reach offset from start, lookup the first field
5361 and start from there. */
5362 if (start->offset > offset)
5363 start = get_varinfo (start->head);
5365 /* We may not find a variable in the field list with the actual
5366 offset when we have glommed a structure to a variable.
5367 In that case, however, offset should still be within the size
5368 of the variable.
5369 If we got beyond the offset we look for return the field
5370 directly preceding offset which may be the last field. */
5371 while (start->next
5372 && offset >= start->offset
5373 && !((offset - start->offset) < start->size))
5374 start = vi_next (start);
5376 return start;
5380 /* This structure is used during pushing fields onto the fieldstack
5381 to track the offset of the field, since bitpos_of_field gives it
5382 relative to its immediate containing type, and we want it relative
5383 to the ultimate containing object. */
5385 struct fieldoff
5387 /* Offset from the base of the base containing object to this field. */
5388 HOST_WIDE_INT offset;
5390 /* Size, in bits, of the field. */
5391 unsigned HOST_WIDE_INT size;
5393 unsigned has_unknown_size : 1;
5395 unsigned must_have_pointers : 1;
5397 unsigned may_have_pointers : 1;
5399 unsigned only_restrict_pointers : 1;
5401 tree restrict_pointed_type;
5403 typedef struct fieldoff fieldoff_s;
5406 /* qsort comparison function for two fieldoff's PA and PB */
5408 static int
5409 fieldoff_compare (const void *pa, const void *pb)
5411 const fieldoff_s *foa = (const fieldoff_s *)pa;
5412 const fieldoff_s *fob = (const fieldoff_s *)pb;
5413 unsigned HOST_WIDE_INT foasize, fobsize;
5415 if (foa->offset < fob->offset)
5416 return -1;
5417 else if (foa->offset > fob->offset)
5418 return 1;
5420 foasize = foa->size;
5421 fobsize = fob->size;
5422 if (foasize < fobsize)
5423 return -1;
5424 else if (foasize > fobsize)
5425 return 1;
5426 return 0;
5429 /* Sort a fieldstack according to the field offset and sizes. */
5430 static void
5431 sort_fieldstack (vec<fieldoff_s> fieldstack)
5433 fieldstack.qsort (fieldoff_compare);
5436 /* Return true if T is a type that can have subvars. */
5438 static inline bool
5439 type_can_have_subvars (const_tree t)
5441 /* Aggregates without overlapping fields can have subvars. */
5442 return TREE_CODE (t) == RECORD_TYPE;
5445 /* Return true if V is a tree that we can have subvars for.
5446 Normally, this is any aggregate type. Also complex
5447 types which are not gimple registers can have subvars. */
5449 static inline bool
5450 var_can_have_subvars (const_tree v)
5452 /* Volatile variables should never have subvars. */
5453 if (TREE_THIS_VOLATILE (v))
5454 return false;
5456 /* Non decls or memory tags can never have subvars. */
5457 if (!DECL_P (v))
5458 return false;
5460 return type_can_have_subvars (TREE_TYPE (v));
5463 /* Return true if T is a type that does contain pointers. */
5465 static bool
5466 type_must_have_pointers (tree type)
5468 if (POINTER_TYPE_P (type))
5469 return true;
5471 if (TREE_CODE (type) == ARRAY_TYPE)
5472 return type_must_have_pointers (TREE_TYPE (type));
5474 /* A function or method can have pointers as arguments, so track
5475 those separately. */
5476 if (TREE_CODE (type) == FUNCTION_TYPE
5477 || TREE_CODE (type) == METHOD_TYPE)
5478 return true;
5480 return false;
5483 static bool
5484 field_must_have_pointers (tree t)
5486 return type_must_have_pointers (TREE_TYPE (t));
5489 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5490 the fields of TYPE onto fieldstack, recording their offsets along
5491 the way.
5493 OFFSET is used to keep track of the offset in this entire
5494 structure, rather than just the immediately containing structure.
5495 Returns false if the caller is supposed to handle the field we
5496 recursed for. */
5498 static bool
5499 push_fields_onto_fieldstack (tree type, vec<fieldoff_s> *fieldstack,
5500 HOST_WIDE_INT offset)
5502 tree field;
5503 bool empty_p = true;
5505 if (TREE_CODE (type) != RECORD_TYPE)
5506 return false;
5508 /* If the vector of fields is growing too big, bail out early.
5509 Callers check for vec::length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5510 sure this fails. */
5511 if (fieldstack->length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5512 return false;
5514 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5515 if (TREE_CODE (field) == FIELD_DECL)
5517 bool push = false;
5518 HOST_WIDE_INT foff = bitpos_of_field (field);
5519 tree field_type = TREE_TYPE (field);
5521 if (!var_can_have_subvars (field)
5522 || TREE_CODE (field_type) == QUAL_UNION_TYPE
5523 || TREE_CODE (field_type) == UNION_TYPE)
5524 push = true;
5525 else if (!push_fields_onto_fieldstack
5526 (field_type, fieldstack, offset + foff)
5527 && (DECL_SIZE (field)
5528 && !integer_zerop (DECL_SIZE (field))))
5529 /* Empty structures may have actual size, like in C++. So
5530 see if we didn't push any subfields and the size is
5531 nonzero, push the field onto the stack. */
5532 push = true;
5534 if (push)
5536 fieldoff_s *pair = NULL;
5537 bool has_unknown_size = false;
5538 bool must_have_pointers_p;
5540 if (!fieldstack->is_empty ())
5541 pair = &fieldstack->last ();
5543 /* If there isn't anything at offset zero, create sth. */
5544 if (!pair
5545 && offset + foff != 0)
5547 fieldoff_s e
5548 = {0, offset + foff, false, false, true, false, NULL_TREE};
5549 pair = fieldstack->safe_push (e);
5552 if (!DECL_SIZE (field)
5553 || !tree_fits_uhwi_p (DECL_SIZE (field)))
5554 has_unknown_size = true;
5556 /* If adjacent fields do not contain pointers merge them. */
5557 must_have_pointers_p = field_must_have_pointers (field);
5558 if (pair
5559 && !has_unknown_size
5560 && !must_have_pointers_p
5561 && !pair->must_have_pointers
5562 && !pair->has_unknown_size
5563 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5565 pair->size += tree_to_uhwi (DECL_SIZE (field));
5567 else
5569 fieldoff_s e;
5570 e.offset = offset + foff;
5571 e.has_unknown_size = has_unknown_size;
5572 if (!has_unknown_size)
5573 e.size = tree_to_uhwi (DECL_SIZE (field));
5574 else
5575 e.size = -1;
5576 e.must_have_pointers = must_have_pointers_p;
5577 e.may_have_pointers = true;
5578 e.only_restrict_pointers
5579 = (!has_unknown_size
5580 && POINTER_TYPE_P (field_type)
5581 && TYPE_RESTRICT (field_type));
5582 if (e.only_restrict_pointers)
5583 e.restrict_pointed_type = TREE_TYPE (field_type);
5584 fieldstack->safe_push (e);
5588 empty_p = false;
5591 return !empty_p;
5594 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5595 if it is a varargs function. */
5597 static unsigned int
5598 count_num_arguments (tree decl, bool *is_varargs)
5600 unsigned int num = 0;
5601 tree t;
5603 /* Capture named arguments for K&R functions. They do not
5604 have a prototype and thus no TYPE_ARG_TYPES. */
5605 for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5606 ++num;
5608 /* Check if the function has variadic arguments. */
5609 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5610 if (TREE_VALUE (t) == void_type_node)
5611 break;
5612 if (!t)
5613 *is_varargs = true;
5615 return num;
5618 /* Creation function node for DECL, using NAME, and return the index
5619 of the variable we've created for the function. If NONLOCAL_p, create
5620 initial constraints. */
5622 static varinfo_t
5623 create_function_info_for (tree decl, const char *name, bool add_id,
5624 bool nonlocal_p)
5626 struct function *fn = DECL_STRUCT_FUNCTION (decl);
5627 varinfo_t vi, prev_vi;
5628 tree arg;
5629 unsigned int i;
5630 bool is_varargs = false;
5631 unsigned int num_args = count_num_arguments (decl, &is_varargs);
5633 /* Create the variable info. */
5635 vi = new_var_info (decl, name, add_id);
5636 vi->offset = 0;
5637 vi->size = 1;
5638 vi->fullsize = fi_parm_base + num_args;
5639 vi->is_fn_info = 1;
5640 vi->may_have_pointers = false;
5641 if (is_varargs)
5642 vi->fullsize = ~0;
5643 insert_vi_for_tree (vi->decl, vi);
5645 prev_vi = vi;
5647 /* Create a variable for things the function clobbers and one for
5648 things the function uses. */
5650 varinfo_t clobbervi, usevi;
5651 const char *newname;
5652 char *tempname;
5654 tempname = xasprintf ("%s.clobber", name);
5655 newname = ggc_strdup (tempname);
5656 free (tempname);
5658 clobbervi = new_var_info (NULL, newname, false);
5659 clobbervi->offset = fi_clobbers;
5660 clobbervi->size = 1;
5661 clobbervi->fullsize = vi->fullsize;
5662 clobbervi->is_full_var = true;
5663 clobbervi->is_global_var = false;
5665 gcc_assert (prev_vi->offset < clobbervi->offset);
5666 prev_vi->next = clobbervi->id;
5667 prev_vi = clobbervi;
5669 tempname = xasprintf ("%s.use", name);
5670 newname = ggc_strdup (tempname);
5671 free (tempname);
5673 usevi = new_var_info (NULL, newname, false);
5674 usevi->offset = fi_uses;
5675 usevi->size = 1;
5676 usevi->fullsize = vi->fullsize;
5677 usevi->is_full_var = true;
5678 usevi->is_global_var = false;
5680 gcc_assert (prev_vi->offset < usevi->offset);
5681 prev_vi->next = usevi->id;
5682 prev_vi = usevi;
5685 /* And one for the static chain. */
5686 if (fn->static_chain_decl != NULL_TREE)
5688 varinfo_t chainvi;
5689 const char *newname;
5690 char *tempname;
5692 tempname = xasprintf ("%s.chain", name);
5693 newname = ggc_strdup (tempname);
5694 free (tempname);
5696 chainvi = new_var_info (fn->static_chain_decl, newname, false);
5697 chainvi->offset = fi_static_chain;
5698 chainvi->size = 1;
5699 chainvi->fullsize = vi->fullsize;
5700 chainvi->is_full_var = true;
5701 chainvi->is_global_var = false;
5703 insert_vi_for_tree (fn->static_chain_decl, chainvi);
5705 if (nonlocal_p
5706 && chainvi->may_have_pointers)
5707 make_constraint_from (chainvi, nonlocal_id);
5709 gcc_assert (prev_vi->offset < chainvi->offset);
5710 prev_vi->next = chainvi->id;
5711 prev_vi = chainvi;
5714 /* Create a variable for the return var. */
5715 if (DECL_RESULT (decl) != NULL
5716 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5718 varinfo_t resultvi;
5719 const char *newname;
5720 char *tempname;
5721 tree resultdecl = decl;
5723 if (DECL_RESULT (decl))
5724 resultdecl = DECL_RESULT (decl);
5726 tempname = xasprintf ("%s.result", name);
5727 newname = ggc_strdup (tempname);
5728 free (tempname);
5730 resultvi = new_var_info (resultdecl, newname, false);
5731 resultvi->offset = fi_result;
5732 resultvi->size = 1;
5733 resultvi->fullsize = vi->fullsize;
5734 resultvi->is_full_var = true;
5735 if (DECL_RESULT (decl))
5736 resultvi->may_have_pointers = true;
5738 if (DECL_RESULT (decl))
5739 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5741 if (nonlocal_p
5742 && DECL_RESULT (decl)
5743 && DECL_BY_REFERENCE (DECL_RESULT (decl)))
5744 make_constraint_from (resultvi, nonlocal_id);
5746 gcc_assert (prev_vi->offset < resultvi->offset);
5747 prev_vi->next = resultvi->id;
5748 prev_vi = resultvi;
5751 /* We also need to make function return values escape. Nothing
5752 escapes by returning from main though. */
5753 if (nonlocal_p
5754 && !MAIN_NAME_P (DECL_NAME (decl)))
5756 varinfo_t fi, rvi;
5757 fi = lookup_vi_for_tree (decl);
5758 rvi = first_vi_for_offset (fi, fi_result);
5759 if (rvi && rvi->offset == fi_result)
5760 make_copy_constraint (get_varinfo (escaped_id), rvi->id);
5763 /* Set up variables for each argument. */
5764 arg = DECL_ARGUMENTS (decl);
5765 for (i = 0; i < num_args; i++)
5767 varinfo_t argvi;
5768 const char *newname;
5769 char *tempname;
5770 tree argdecl = decl;
5772 if (arg)
5773 argdecl = arg;
5775 tempname = xasprintf ("%s.arg%d", name, i);
5776 newname = ggc_strdup (tempname);
5777 free (tempname);
5779 argvi = new_var_info (argdecl, newname, false);
5780 argvi->offset = fi_parm_base + i;
5781 argvi->size = 1;
5782 argvi->is_full_var = true;
5783 argvi->fullsize = vi->fullsize;
5784 if (arg)
5785 argvi->may_have_pointers = true;
5787 if (arg)
5788 insert_vi_for_tree (arg, argvi);
5790 if (nonlocal_p
5791 && argvi->may_have_pointers)
5792 make_constraint_from (argvi, nonlocal_id);
5794 gcc_assert (prev_vi->offset < argvi->offset);
5795 prev_vi->next = argvi->id;
5796 prev_vi = argvi;
5797 if (arg)
5798 arg = DECL_CHAIN (arg);
5801 /* Add one representative for all further args. */
5802 if (is_varargs)
5804 varinfo_t argvi;
5805 const char *newname;
5806 char *tempname;
5807 tree decl;
5809 tempname = xasprintf ("%s.varargs", name);
5810 newname = ggc_strdup (tempname);
5811 free (tempname);
5813 /* We need sth that can be pointed to for va_start. */
5814 decl = build_fake_var_decl (ptr_type_node);
5816 argvi = new_var_info (decl, newname, false);
5817 argvi->offset = fi_parm_base + num_args;
5818 argvi->size = ~0;
5819 argvi->is_full_var = true;
5820 argvi->is_heap_var = true;
5821 argvi->fullsize = vi->fullsize;
5823 if (nonlocal_p
5824 && argvi->may_have_pointers)
5825 make_constraint_from (argvi, nonlocal_id);
5827 gcc_assert (prev_vi->offset < argvi->offset);
5828 prev_vi->next = argvi->id;
5829 prev_vi = argvi;
5832 return vi;
5836 /* Return true if FIELDSTACK contains fields that overlap.
5837 FIELDSTACK is assumed to be sorted by offset. */
5839 static bool
5840 check_for_overlaps (vec<fieldoff_s> fieldstack)
5842 fieldoff_s *fo = NULL;
5843 unsigned int i;
5844 HOST_WIDE_INT lastoffset = -1;
5846 FOR_EACH_VEC_ELT (fieldstack, i, fo)
5848 if (fo->offset == lastoffset)
5849 return true;
5850 lastoffset = fo->offset;
5852 return false;
5855 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5856 This will also create any varinfo structures necessary for fields
5857 of DECL. DECL is a function parameter if HANDLE_PARAM is set.
5858 HANDLED_STRUCT_TYPE is used to register struct types reached by following
5859 restrict pointers. This is needed to prevent infinite recursion. */
5861 static varinfo_t
5862 create_variable_info_for_1 (tree decl, const char *name, bool add_id,
5863 bool handle_param, bitmap handled_struct_type)
5865 varinfo_t vi, newvi;
5866 tree decl_type = TREE_TYPE (decl);
5867 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5868 auto_vec<fieldoff_s> fieldstack;
5869 fieldoff_s *fo;
5870 unsigned int i;
5872 if (!declsize
5873 || !tree_fits_uhwi_p (declsize))
5875 vi = new_var_info (decl, name, add_id);
5876 vi->offset = 0;
5877 vi->size = ~0;
5878 vi->fullsize = ~0;
5879 vi->is_unknown_size_var = true;
5880 vi->is_full_var = true;
5881 vi->may_have_pointers = true;
5882 return vi;
5885 /* Collect field information. */
5886 if (use_field_sensitive
5887 && var_can_have_subvars (decl)
5888 /* ??? Force us to not use subfields for globals in IPA mode.
5889 Else we'd have to parse arbitrary initializers. */
5890 && !(in_ipa_mode
5891 && is_global_var (decl)))
5893 fieldoff_s *fo = NULL;
5894 bool notokay = false;
5895 unsigned int i;
5897 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5899 for (i = 0; !notokay && fieldstack.iterate (i, &fo); i++)
5900 if (fo->has_unknown_size
5901 || fo->offset < 0)
5903 notokay = true;
5904 break;
5907 /* We can't sort them if we have a field with a variable sized type,
5908 which will make notokay = true. In that case, we are going to return
5909 without creating varinfos for the fields anyway, so sorting them is a
5910 waste to boot. */
5911 if (!notokay)
5913 sort_fieldstack (fieldstack);
5914 /* Due to some C++ FE issues, like PR 22488, we might end up
5915 what appear to be overlapping fields even though they,
5916 in reality, do not overlap. Until the C++ FE is fixed,
5917 we will simply disable field-sensitivity for these cases. */
5918 notokay = check_for_overlaps (fieldstack);
5921 if (notokay)
5922 fieldstack.release ();
5925 /* If we didn't end up collecting sub-variables create a full
5926 variable for the decl. */
5927 if (fieldstack.length () == 0
5928 || fieldstack.length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5930 vi = new_var_info (decl, name, add_id);
5931 vi->offset = 0;
5932 vi->may_have_pointers = true;
5933 vi->fullsize = tree_to_uhwi (declsize);
5934 vi->size = vi->fullsize;
5935 vi->is_full_var = true;
5936 if (POINTER_TYPE_P (decl_type)
5937 && TYPE_RESTRICT (decl_type))
5938 vi->only_restrict_pointers = 1;
5939 if (vi->only_restrict_pointers
5940 && !type_contains_placeholder_p (TREE_TYPE (decl_type))
5941 && handle_param
5942 && !bitmap_bit_p (handled_struct_type,
5943 TYPE_UID (TREE_TYPE (decl_type))))
5945 varinfo_t rvi;
5946 tree heapvar = build_fake_var_decl (TREE_TYPE (decl_type));
5947 DECL_EXTERNAL (heapvar) = 1;
5948 if (var_can_have_subvars (heapvar))
5949 bitmap_set_bit (handled_struct_type,
5950 TYPE_UID (TREE_TYPE (decl_type)));
5951 rvi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS", true,
5952 true, handled_struct_type);
5953 if (var_can_have_subvars (heapvar))
5954 bitmap_clear_bit (handled_struct_type,
5955 TYPE_UID (TREE_TYPE (decl_type)));
5956 rvi->is_restrict_var = 1;
5957 insert_vi_for_tree (heapvar, rvi);
5958 make_constraint_from (vi, rvi->id);
5959 make_param_constraints (rvi);
5961 fieldstack.release ();
5962 return vi;
5965 vi = new_var_info (decl, name, add_id);
5966 vi->fullsize = tree_to_uhwi (declsize);
5967 if (fieldstack.length () == 1)
5968 vi->is_full_var = true;
5969 for (i = 0, newvi = vi;
5970 fieldstack.iterate (i, &fo);
5971 ++i, newvi = vi_next (newvi))
5973 const char *newname = NULL;
5974 char *tempname;
5976 if (dump_file)
5978 if (fieldstack.length () != 1)
5980 tempname
5981 = xasprintf ("%s." HOST_WIDE_INT_PRINT_DEC
5982 "+" HOST_WIDE_INT_PRINT_DEC, name,
5983 fo->offset, fo->size);
5984 newname = ggc_strdup (tempname);
5985 free (tempname);
5988 else
5989 newname = "NULL";
5991 if (newname)
5992 newvi->name = newname;
5993 newvi->offset = fo->offset;
5994 newvi->size = fo->size;
5995 newvi->fullsize = vi->fullsize;
5996 newvi->may_have_pointers = fo->may_have_pointers;
5997 newvi->only_restrict_pointers = fo->only_restrict_pointers;
5998 if (handle_param
5999 && newvi->only_restrict_pointers
6000 && !type_contains_placeholder_p (fo->restrict_pointed_type)
6001 && !bitmap_bit_p (handled_struct_type,
6002 TYPE_UID (fo->restrict_pointed_type)))
6004 varinfo_t rvi;
6005 tree heapvar = build_fake_var_decl (fo->restrict_pointed_type);
6006 DECL_EXTERNAL (heapvar) = 1;
6007 if (var_can_have_subvars (heapvar))
6008 bitmap_set_bit (handled_struct_type,
6009 TYPE_UID (fo->restrict_pointed_type));
6010 rvi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS", true,
6011 true, handled_struct_type);
6012 if (var_can_have_subvars (heapvar))
6013 bitmap_clear_bit (handled_struct_type,
6014 TYPE_UID (fo->restrict_pointed_type));
6015 rvi->is_restrict_var = 1;
6016 insert_vi_for_tree (heapvar, rvi);
6017 make_constraint_from (newvi, rvi->id);
6018 make_param_constraints (rvi);
6020 if (i + 1 < fieldstack.length ())
6022 varinfo_t tem = new_var_info (decl, name, false);
6023 newvi->next = tem->id;
6024 tem->head = vi->id;
6028 return vi;
6031 static unsigned int
6032 create_variable_info_for (tree decl, const char *name, bool add_id)
6034 varinfo_t vi = create_variable_info_for_1 (decl, name, add_id, false, NULL);
6035 unsigned int id = vi->id;
6037 insert_vi_for_tree (decl, vi);
6039 if (TREE_CODE (decl) != VAR_DECL)
6040 return id;
6042 /* Create initial constraints for globals. */
6043 for (; vi; vi = vi_next (vi))
6045 if (!vi->may_have_pointers
6046 || !vi->is_global_var)
6047 continue;
6049 /* Mark global restrict qualified pointers. */
6050 if ((POINTER_TYPE_P (TREE_TYPE (decl))
6051 && TYPE_RESTRICT (TREE_TYPE (decl)))
6052 || vi->only_restrict_pointers)
6054 varinfo_t rvi
6055 = make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT",
6056 true);
6057 /* ??? For now exclude reads from globals as restrict sources
6058 if those are not (indirectly) from incoming parameters. */
6059 rvi->is_restrict_var = false;
6060 continue;
6063 /* In non-IPA mode the initializer from nonlocal is all we need. */
6064 if (!in_ipa_mode
6065 || DECL_HARD_REGISTER (decl))
6066 make_copy_constraint (vi, nonlocal_id);
6068 /* In IPA mode parse the initializer and generate proper constraints
6069 for it. */
6070 else
6072 varpool_node *vnode = varpool_node::get (decl);
6074 /* For escaped variables initialize them from nonlocal. */
6075 if (!vnode->all_refs_explicit_p ())
6076 make_copy_constraint (vi, nonlocal_id);
6078 /* If this is a global variable with an initializer and we are in
6079 IPA mode generate constraints for it. */
6080 ipa_ref *ref;
6081 for (unsigned idx = 0; vnode->iterate_reference (idx, ref); ++idx)
6083 auto_vec<ce_s> rhsc;
6084 struct constraint_expr lhs, *rhsp;
6085 unsigned i;
6086 get_constraint_for_address_of (ref->referred->decl, &rhsc);
6087 lhs.var = vi->id;
6088 lhs.offset = 0;
6089 lhs.type = SCALAR;
6090 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
6091 process_constraint (new_constraint (lhs, *rhsp));
6092 /* If this is a variable that escapes from the unit
6093 the initializer escapes as well. */
6094 if (!vnode->all_refs_explicit_p ())
6096 lhs.var = escaped_id;
6097 lhs.offset = 0;
6098 lhs.type = SCALAR;
6099 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
6100 process_constraint (new_constraint (lhs, *rhsp));
6106 return id;
6109 /* Print out the points-to solution for VAR to FILE. */
6111 static void
6112 dump_solution_for_var (FILE *file, unsigned int var)
6114 varinfo_t vi = get_varinfo (var);
6115 unsigned int i;
6116 bitmap_iterator bi;
6118 /* Dump the solution for unified vars anyway, this avoids difficulties
6119 in scanning dumps in the testsuite. */
6120 fprintf (file, "%s = { ", vi->name);
6121 vi = get_varinfo (find (var));
6122 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6123 fprintf (file, "%s ", get_varinfo (i)->name);
6124 fprintf (file, "}");
6126 /* But note when the variable was unified. */
6127 if (vi->id != var)
6128 fprintf (file, " same as %s", vi->name);
6130 fprintf (file, "\n");
6133 /* Print the points-to solution for VAR to stderr. */
6135 DEBUG_FUNCTION void
6136 debug_solution_for_var (unsigned int var)
6138 dump_solution_for_var (stderr, var);
6141 /* Register the constraints for function parameter related VI. */
6143 static void
6144 make_param_constraints (varinfo_t vi)
6146 for (; vi; vi = vi_next (vi))
6148 if (vi->only_restrict_pointers)
6150 else if (vi->may_have_pointers)
6151 make_constraint_from (vi, nonlocal_id);
6153 if (vi->is_full_var)
6154 break;
6158 /* Create varinfo structures for all of the variables in the
6159 function for intraprocedural mode. */
6161 static void
6162 intra_create_variable_infos (struct function *fn)
6164 tree t;
6165 bitmap handled_struct_type = NULL;
6167 /* For each incoming pointer argument arg, create the constraint ARG
6168 = NONLOCAL or a dummy variable if it is a restrict qualified
6169 passed-by-reference argument. */
6170 for (t = DECL_ARGUMENTS (fn->decl); t; t = DECL_CHAIN (t))
6172 if (handled_struct_type == NULL)
6173 handled_struct_type = BITMAP_ALLOC (NULL);
6175 varinfo_t p
6176 = create_variable_info_for_1 (t, alias_get_name (t), false, true,
6177 handled_struct_type);
6178 insert_vi_for_tree (t, p);
6180 make_param_constraints (p);
6183 if (handled_struct_type != NULL)
6184 BITMAP_FREE (handled_struct_type);
6186 /* Add a constraint for a result decl that is passed by reference. */
6187 if (DECL_RESULT (fn->decl)
6188 && DECL_BY_REFERENCE (DECL_RESULT (fn->decl)))
6190 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (fn->decl));
6192 for (p = result_vi; p; p = vi_next (p))
6193 make_constraint_from (p, nonlocal_id);
6196 /* Add a constraint for the incoming static chain parameter. */
6197 if (fn->static_chain_decl != NULL_TREE)
6199 varinfo_t p, chain_vi = get_vi_for_tree (fn->static_chain_decl);
6201 for (p = chain_vi; p; p = vi_next (p))
6202 make_constraint_from (p, nonlocal_id);
6206 /* Structure used to put solution bitmaps in a hashtable so they can
6207 be shared among variables with the same points-to set. */
6209 typedef struct shared_bitmap_info
6211 bitmap pt_vars;
6212 hashval_t hashcode;
6213 } *shared_bitmap_info_t;
6214 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
6216 /* Shared_bitmap hashtable helpers. */
6218 struct shared_bitmap_hasher : free_ptr_hash <shared_bitmap_info>
6220 static inline hashval_t hash (const shared_bitmap_info *);
6221 static inline bool equal (const shared_bitmap_info *,
6222 const shared_bitmap_info *);
6225 /* Hash function for a shared_bitmap_info_t */
6227 inline hashval_t
6228 shared_bitmap_hasher::hash (const shared_bitmap_info *bi)
6230 return bi->hashcode;
6233 /* Equality function for two shared_bitmap_info_t's. */
6235 inline bool
6236 shared_bitmap_hasher::equal (const shared_bitmap_info *sbi1,
6237 const shared_bitmap_info *sbi2)
6239 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
6242 /* Shared_bitmap hashtable. */
6244 static hash_table<shared_bitmap_hasher> *shared_bitmap_table;
6246 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
6247 existing instance if there is one, NULL otherwise. */
6249 static bitmap
6250 shared_bitmap_lookup (bitmap pt_vars)
6252 shared_bitmap_info **slot;
6253 struct shared_bitmap_info sbi;
6255 sbi.pt_vars = pt_vars;
6256 sbi.hashcode = bitmap_hash (pt_vars);
6258 slot = shared_bitmap_table->find_slot (&sbi, NO_INSERT);
6259 if (!slot)
6260 return NULL;
6261 else
6262 return (*slot)->pt_vars;
6266 /* Add a bitmap to the shared bitmap hashtable. */
6268 static void
6269 shared_bitmap_add (bitmap pt_vars)
6271 shared_bitmap_info **slot;
6272 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
6274 sbi->pt_vars = pt_vars;
6275 sbi->hashcode = bitmap_hash (pt_vars);
6277 slot = shared_bitmap_table->find_slot (sbi, INSERT);
6278 gcc_assert (!*slot);
6279 *slot = sbi;
6283 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
6285 static void
6286 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt,
6287 tree fndecl)
6289 unsigned int i;
6290 bitmap_iterator bi;
6291 varinfo_t escaped_vi = get_varinfo (find (escaped_id));
6292 bool everything_escaped
6293 = escaped_vi->solution && bitmap_bit_p (escaped_vi->solution, anything_id);
6295 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
6297 varinfo_t vi = get_varinfo (i);
6299 /* The only artificial variables that are allowed in a may-alias
6300 set are heap variables. */
6301 if (vi->is_artificial_var && !vi->is_heap_var)
6302 continue;
6304 if (everything_escaped
6305 || (escaped_vi->solution
6306 && bitmap_bit_p (escaped_vi->solution, i)))
6308 pt->vars_contains_escaped = true;
6309 pt->vars_contains_escaped_heap = vi->is_heap_var;
6312 if (TREE_CODE (vi->decl) == VAR_DECL
6313 || TREE_CODE (vi->decl) == PARM_DECL
6314 || TREE_CODE (vi->decl) == RESULT_DECL)
6316 /* If we are in IPA mode we will not recompute points-to
6317 sets after inlining so make sure they stay valid. */
6318 if (in_ipa_mode
6319 && !DECL_PT_UID_SET_P (vi->decl))
6320 SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
6322 /* Add the decl to the points-to set. Note that the points-to
6323 set contains global variables. */
6324 bitmap_set_bit (into, DECL_PT_UID (vi->decl));
6325 if (vi->is_global_var
6326 /* In IPA mode the escaped_heap trick doesn't work as
6327 ESCAPED is escaped from the unit but
6328 pt_solution_includes_global needs to answer true for
6329 all variables not automatic within a function.
6330 For the same reason is_global_var is not the
6331 correct flag to track - local variables from other
6332 functions also need to be considered global.
6333 Conveniently all HEAP vars are not put in function
6334 scope. */
6335 || (in_ipa_mode
6336 && fndecl
6337 && ! auto_var_in_fn_p (vi->decl, fndecl)))
6338 pt->vars_contains_nonlocal = true;
6341 else if (TREE_CODE (vi->decl) == FUNCTION_DECL
6342 || TREE_CODE (vi->decl) == LABEL_DECL)
6344 /* Nothing should read/write from/to code so we can
6345 save bits by not including them in the points-to bitmaps.
6346 Still mark the points-to set as containing global memory
6347 to make code-patching possible - see PR70128. */
6348 pt->vars_contains_nonlocal = true;
6354 /* Compute the points-to solution *PT for the variable VI. */
6356 static struct pt_solution
6357 find_what_var_points_to (tree fndecl, varinfo_t orig_vi)
6359 unsigned int i;
6360 bitmap_iterator bi;
6361 bitmap finished_solution;
6362 bitmap result;
6363 varinfo_t vi;
6364 struct pt_solution *pt;
6366 /* This variable may have been collapsed, let's get the real
6367 variable. */
6368 vi = get_varinfo (find (orig_vi->id));
6370 /* See if we have already computed the solution and return it. */
6371 pt_solution **slot = &final_solutions->get_or_insert (vi);
6372 if (*slot != NULL)
6373 return **slot;
6375 *slot = pt = XOBNEW (&final_solutions_obstack, struct pt_solution);
6376 memset (pt, 0, sizeof (struct pt_solution));
6378 /* Translate artificial variables into SSA_NAME_PTR_INFO
6379 attributes. */
6380 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6382 varinfo_t vi = get_varinfo (i);
6384 if (vi->is_artificial_var)
6386 if (vi->id == nothing_id)
6387 pt->null = 1;
6388 else if (vi->id == escaped_id)
6390 if (in_ipa_mode)
6391 pt->ipa_escaped = 1;
6392 else
6393 pt->escaped = 1;
6394 /* Expand some special vars of ESCAPED in-place here. */
6395 varinfo_t evi = get_varinfo (find (escaped_id));
6396 if (bitmap_bit_p (evi->solution, nonlocal_id))
6397 pt->nonlocal = 1;
6399 else if (vi->id == nonlocal_id)
6400 pt->nonlocal = 1;
6401 else if (vi->is_heap_var)
6402 /* We represent heapvars in the points-to set properly. */
6404 else if (vi->id == string_id)
6405 /* Nobody cares - STRING_CSTs are read-only entities. */
6407 else if (vi->id == anything_id
6408 || vi->id == integer_id)
6409 pt->anything = 1;
6413 /* Instead of doing extra work, simply do not create
6414 elaborate points-to information for pt_anything pointers. */
6415 if (pt->anything)
6416 return *pt;
6418 /* Share the final set of variables when possible. */
6419 finished_solution = BITMAP_GGC_ALLOC ();
6420 stats.points_to_sets_created++;
6422 set_uids_in_ptset (finished_solution, vi->solution, pt, fndecl);
6423 result = shared_bitmap_lookup (finished_solution);
6424 if (!result)
6426 shared_bitmap_add (finished_solution);
6427 pt->vars = finished_solution;
6429 else
6431 pt->vars = result;
6432 bitmap_clear (finished_solution);
6435 return *pt;
6438 /* Given a pointer variable P, fill in its points-to set. */
6440 static void
6441 find_what_p_points_to (tree fndecl, tree p)
6443 struct ptr_info_def *pi;
6444 tree lookup_p = p;
6445 varinfo_t vi;
6447 /* For parameters, get at the points-to set for the actual parm
6448 decl. */
6449 if (TREE_CODE (p) == SSA_NAME
6450 && SSA_NAME_IS_DEFAULT_DEF (p)
6451 && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
6452 || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL))
6453 lookup_p = SSA_NAME_VAR (p);
6455 vi = lookup_vi_for_tree (lookup_p);
6456 if (!vi)
6457 return;
6459 pi = get_ptr_info (p);
6460 pi->pt = find_what_var_points_to (fndecl, vi);
6464 /* Query statistics for points-to solutions. */
6466 static struct {
6467 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
6468 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
6469 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
6470 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
6471 } pta_stats;
6473 void
6474 dump_pta_stats (FILE *s)
6476 fprintf (s, "\nPTA query stats:\n");
6477 fprintf (s, " pt_solution_includes: "
6478 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6479 HOST_WIDE_INT_PRINT_DEC" queries\n",
6480 pta_stats.pt_solution_includes_no_alias,
6481 pta_stats.pt_solution_includes_no_alias
6482 + pta_stats.pt_solution_includes_may_alias);
6483 fprintf (s, " pt_solutions_intersect: "
6484 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6485 HOST_WIDE_INT_PRINT_DEC" queries\n",
6486 pta_stats.pt_solutions_intersect_no_alias,
6487 pta_stats.pt_solutions_intersect_no_alias
6488 + pta_stats.pt_solutions_intersect_may_alias);
6492 /* Reset the points-to solution *PT to a conservative default
6493 (point to anything). */
6495 void
6496 pt_solution_reset (struct pt_solution *pt)
6498 memset (pt, 0, sizeof (struct pt_solution));
6499 pt->anything = true;
6502 /* Set the points-to solution *PT to point only to the variables
6503 in VARS. VARS_CONTAINS_GLOBAL specifies whether that contains
6504 global variables and VARS_CONTAINS_RESTRICT specifies whether
6505 it contains restrict tag variables. */
6507 void
6508 pt_solution_set (struct pt_solution *pt, bitmap vars,
6509 bool vars_contains_nonlocal)
6511 memset (pt, 0, sizeof (struct pt_solution));
6512 pt->vars = vars;
6513 pt->vars_contains_nonlocal = vars_contains_nonlocal;
6514 pt->vars_contains_escaped
6515 = (cfun->gimple_df->escaped.anything
6516 || bitmap_intersect_p (cfun->gimple_df->escaped.vars, vars));
6519 /* Set the points-to solution *PT to point only to the variable VAR. */
6521 void
6522 pt_solution_set_var (struct pt_solution *pt, tree var)
6524 memset (pt, 0, sizeof (struct pt_solution));
6525 pt->vars = BITMAP_GGC_ALLOC ();
6526 bitmap_set_bit (pt->vars, DECL_PT_UID (var));
6527 pt->vars_contains_nonlocal = is_global_var (var);
6528 pt->vars_contains_escaped
6529 = (cfun->gimple_df->escaped.anything
6530 || bitmap_bit_p (cfun->gimple_df->escaped.vars, DECL_PT_UID (var)));
6533 /* Computes the union of the points-to solutions *DEST and *SRC and
6534 stores the result in *DEST. This changes the points-to bitmap
6535 of *DEST and thus may not be used if that might be shared.
6536 The points-to bitmap of *SRC and *DEST will not be shared after
6537 this function if they were not before. */
6539 static void
6540 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
6542 dest->anything |= src->anything;
6543 if (dest->anything)
6545 pt_solution_reset (dest);
6546 return;
6549 dest->nonlocal |= src->nonlocal;
6550 dest->escaped |= src->escaped;
6551 dest->ipa_escaped |= src->ipa_escaped;
6552 dest->null |= src->null;
6553 dest->vars_contains_nonlocal |= src->vars_contains_nonlocal;
6554 dest->vars_contains_escaped |= src->vars_contains_escaped;
6555 dest->vars_contains_escaped_heap |= src->vars_contains_escaped_heap;
6556 if (!src->vars)
6557 return;
6559 if (!dest->vars)
6560 dest->vars = BITMAP_GGC_ALLOC ();
6561 bitmap_ior_into (dest->vars, src->vars);
6564 /* Return true if the points-to solution *PT is empty. */
6566 bool
6567 pt_solution_empty_p (struct pt_solution *pt)
6569 if (pt->anything
6570 || pt->nonlocal)
6571 return false;
6573 if (pt->vars
6574 && !bitmap_empty_p (pt->vars))
6575 return false;
6577 /* If the solution includes ESCAPED, check if that is empty. */
6578 if (pt->escaped
6579 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6580 return false;
6582 /* If the solution includes ESCAPED, check if that is empty. */
6583 if (pt->ipa_escaped
6584 && !pt_solution_empty_p (&ipa_escaped_pt))
6585 return false;
6587 return true;
6590 /* Return true if the points-to solution *PT only point to a single var, and
6591 return the var uid in *UID. */
6593 bool
6594 pt_solution_singleton_p (struct pt_solution *pt, unsigned *uid)
6596 if (pt->anything || pt->nonlocal || pt->escaped || pt->ipa_escaped
6597 || pt->null || pt->vars == NULL
6598 || !bitmap_single_bit_set_p (pt->vars))
6599 return false;
6601 *uid = bitmap_first_set_bit (pt->vars);
6602 return true;
6605 /* Return true if the points-to solution *PT includes global memory. */
6607 bool
6608 pt_solution_includes_global (struct pt_solution *pt)
6610 if (pt->anything
6611 || pt->nonlocal
6612 || pt->vars_contains_nonlocal
6613 /* The following is a hack to make the malloc escape hack work.
6614 In reality we'd need different sets for escaped-through-return
6615 and escaped-to-callees and passes would need to be updated. */
6616 || pt->vars_contains_escaped_heap)
6617 return true;
6619 /* 'escaped' is also a placeholder so we have to look into it. */
6620 if (pt->escaped)
6621 return pt_solution_includes_global (&cfun->gimple_df->escaped);
6623 if (pt->ipa_escaped)
6624 return pt_solution_includes_global (&ipa_escaped_pt);
6626 return false;
6629 /* Return true if the points-to solution *PT includes the variable
6630 declaration DECL. */
6632 static bool
6633 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6635 if (pt->anything)
6636 return true;
6638 if (pt->nonlocal
6639 && is_global_var (decl))
6640 return true;
6642 if (pt->vars
6643 && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6644 return true;
6646 /* If the solution includes ESCAPED, check it. */
6647 if (pt->escaped
6648 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6649 return true;
6651 /* If the solution includes ESCAPED, check it. */
6652 if (pt->ipa_escaped
6653 && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6654 return true;
6656 return false;
6659 bool
6660 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6662 bool res = pt_solution_includes_1 (pt, decl);
6663 if (res)
6664 ++pta_stats.pt_solution_includes_may_alias;
6665 else
6666 ++pta_stats.pt_solution_includes_no_alias;
6667 return res;
6670 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6671 intersection. */
6673 static bool
6674 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6676 if (pt1->anything || pt2->anything)
6677 return true;
6679 /* If either points to unknown global memory and the other points to
6680 any global memory they alias. */
6681 if ((pt1->nonlocal
6682 && (pt2->nonlocal
6683 || pt2->vars_contains_nonlocal))
6684 || (pt2->nonlocal
6685 && pt1->vars_contains_nonlocal))
6686 return true;
6688 /* If either points to all escaped memory and the other points to
6689 any escaped memory they alias. */
6690 if ((pt1->escaped
6691 && (pt2->escaped
6692 || pt2->vars_contains_escaped))
6693 || (pt2->escaped
6694 && pt1->vars_contains_escaped))
6695 return true;
6697 /* Check the escaped solution if required.
6698 ??? Do we need to check the local against the IPA escaped sets? */
6699 if ((pt1->ipa_escaped || pt2->ipa_escaped)
6700 && !pt_solution_empty_p (&ipa_escaped_pt))
6702 /* If both point to escaped memory and that solution
6703 is not empty they alias. */
6704 if (pt1->ipa_escaped && pt2->ipa_escaped)
6705 return true;
6707 /* If either points to escaped memory see if the escaped solution
6708 intersects with the other. */
6709 if ((pt1->ipa_escaped
6710 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6711 || (pt2->ipa_escaped
6712 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6713 return true;
6716 /* Now both pointers alias if their points-to solution intersects. */
6717 return (pt1->vars
6718 && pt2->vars
6719 && bitmap_intersect_p (pt1->vars, pt2->vars));
6722 bool
6723 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6725 bool res = pt_solutions_intersect_1 (pt1, pt2);
6726 if (res)
6727 ++pta_stats.pt_solutions_intersect_may_alias;
6728 else
6729 ++pta_stats.pt_solutions_intersect_no_alias;
6730 return res;
6734 /* Dump points-to information to OUTFILE. */
6736 static void
6737 dump_sa_points_to_info (FILE *outfile)
6739 unsigned int i;
6741 fprintf (outfile, "\nPoints-to sets\n\n");
6743 if (dump_flags & TDF_STATS)
6745 fprintf (outfile, "Stats:\n");
6746 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
6747 fprintf (outfile, "Non-pointer vars: %d\n",
6748 stats.nonpointer_vars);
6749 fprintf (outfile, "Statically unified vars: %d\n",
6750 stats.unified_vars_static);
6751 fprintf (outfile, "Dynamically unified vars: %d\n",
6752 stats.unified_vars_dynamic);
6753 fprintf (outfile, "Iterations: %d\n", stats.iterations);
6754 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
6755 fprintf (outfile, "Number of implicit edges: %d\n",
6756 stats.num_implicit_edges);
6759 for (i = 1; i < varmap.length (); i++)
6761 varinfo_t vi = get_varinfo (i);
6762 if (!vi->may_have_pointers)
6763 continue;
6764 dump_solution_for_var (outfile, i);
6769 /* Debug points-to information to stderr. */
6771 DEBUG_FUNCTION void
6772 debug_sa_points_to_info (void)
6774 dump_sa_points_to_info (stderr);
6778 /* Initialize the always-existing constraint variables for NULL
6779 ANYTHING, READONLY, and INTEGER */
6781 static void
6782 init_base_vars (void)
6784 struct constraint_expr lhs, rhs;
6785 varinfo_t var_anything;
6786 varinfo_t var_nothing;
6787 varinfo_t var_string;
6788 varinfo_t var_escaped;
6789 varinfo_t var_nonlocal;
6790 varinfo_t var_storedanything;
6791 varinfo_t var_integer;
6793 /* Variable ID zero is reserved and should be NULL. */
6794 varmap.safe_push (NULL);
6796 /* Create the NULL variable, used to represent that a variable points
6797 to NULL. */
6798 var_nothing = new_var_info (NULL_TREE, "NULL", false);
6799 gcc_assert (var_nothing->id == nothing_id);
6800 var_nothing->is_artificial_var = 1;
6801 var_nothing->offset = 0;
6802 var_nothing->size = ~0;
6803 var_nothing->fullsize = ~0;
6804 var_nothing->is_special_var = 1;
6805 var_nothing->may_have_pointers = 0;
6806 var_nothing->is_global_var = 0;
6808 /* Create the ANYTHING variable, used to represent that a variable
6809 points to some unknown piece of memory. */
6810 var_anything = new_var_info (NULL_TREE, "ANYTHING", false);
6811 gcc_assert (var_anything->id == anything_id);
6812 var_anything->is_artificial_var = 1;
6813 var_anything->size = ~0;
6814 var_anything->offset = 0;
6815 var_anything->fullsize = ~0;
6816 var_anything->is_special_var = 1;
6818 /* Anything points to anything. This makes deref constraints just
6819 work in the presence of linked list and other p = *p type loops,
6820 by saying that *ANYTHING = ANYTHING. */
6821 lhs.type = SCALAR;
6822 lhs.var = anything_id;
6823 lhs.offset = 0;
6824 rhs.type = ADDRESSOF;
6825 rhs.var = anything_id;
6826 rhs.offset = 0;
6828 /* This specifically does not use process_constraint because
6829 process_constraint ignores all anything = anything constraints, since all
6830 but this one are redundant. */
6831 constraints.safe_push (new_constraint (lhs, rhs));
6833 /* Create the STRING variable, used to represent that a variable
6834 points to a string literal. String literals don't contain
6835 pointers so STRING doesn't point to anything. */
6836 var_string = new_var_info (NULL_TREE, "STRING", false);
6837 gcc_assert (var_string->id == string_id);
6838 var_string->is_artificial_var = 1;
6839 var_string->offset = 0;
6840 var_string->size = ~0;
6841 var_string->fullsize = ~0;
6842 var_string->is_special_var = 1;
6843 var_string->may_have_pointers = 0;
6845 /* Create the ESCAPED variable, used to represent the set of escaped
6846 memory. */
6847 var_escaped = new_var_info (NULL_TREE, "ESCAPED", false);
6848 gcc_assert (var_escaped->id == escaped_id);
6849 var_escaped->is_artificial_var = 1;
6850 var_escaped->offset = 0;
6851 var_escaped->size = ~0;
6852 var_escaped->fullsize = ~0;
6853 var_escaped->is_special_var = 0;
6855 /* Create the NONLOCAL variable, used to represent the set of nonlocal
6856 memory. */
6857 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL", false);
6858 gcc_assert (var_nonlocal->id == nonlocal_id);
6859 var_nonlocal->is_artificial_var = 1;
6860 var_nonlocal->offset = 0;
6861 var_nonlocal->size = ~0;
6862 var_nonlocal->fullsize = ~0;
6863 var_nonlocal->is_special_var = 1;
6865 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
6866 lhs.type = SCALAR;
6867 lhs.var = escaped_id;
6868 lhs.offset = 0;
6869 rhs.type = DEREF;
6870 rhs.var = escaped_id;
6871 rhs.offset = 0;
6872 process_constraint (new_constraint (lhs, rhs));
6874 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6875 whole variable escapes. */
6876 lhs.type = SCALAR;
6877 lhs.var = escaped_id;
6878 lhs.offset = 0;
6879 rhs.type = SCALAR;
6880 rhs.var = escaped_id;
6881 rhs.offset = UNKNOWN_OFFSET;
6882 process_constraint (new_constraint (lhs, rhs));
6884 /* *ESCAPED = NONLOCAL. This is true because we have to assume
6885 everything pointed to by escaped points to what global memory can
6886 point to. */
6887 lhs.type = DEREF;
6888 lhs.var = escaped_id;
6889 lhs.offset = 0;
6890 rhs.type = SCALAR;
6891 rhs.var = nonlocal_id;
6892 rhs.offset = 0;
6893 process_constraint (new_constraint (lhs, rhs));
6895 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
6896 global memory may point to global memory and escaped memory. */
6897 lhs.type = SCALAR;
6898 lhs.var = nonlocal_id;
6899 lhs.offset = 0;
6900 rhs.type = ADDRESSOF;
6901 rhs.var = nonlocal_id;
6902 rhs.offset = 0;
6903 process_constraint (new_constraint (lhs, rhs));
6904 rhs.type = ADDRESSOF;
6905 rhs.var = escaped_id;
6906 rhs.offset = 0;
6907 process_constraint (new_constraint (lhs, rhs));
6909 /* Create the STOREDANYTHING variable, used to represent the set of
6910 variables stored to *ANYTHING. */
6911 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING", false);
6912 gcc_assert (var_storedanything->id == storedanything_id);
6913 var_storedanything->is_artificial_var = 1;
6914 var_storedanything->offset = 0;
6915 var_storedanything->size = ~0;
6916 var_storedanything->fullsize = ~0;
6917 var_storedanything->is_special_var = 0;
6919 /* Create the INTEGER variable, used to represent that a variable points
6920 to what an INTEGER "points to". */
6921 var_integer = new_var_info (NULL_TREE, "INTEGER", false);
6922 gcc_assert (var_integer->id == integer_id);
6923 var_integer->is_artificial_var = 1;
6924 var_integer->size = ~0;
6925 var_integer->fullsize = ~0;
6926 var_integer->offset = 0;
6927 var_integer->is_special_var = 1;
6929 /* INTEGER = ANYTHING, because we don't know where a dereference of
6930 a random integer will point to. */
6931 lhs.type = SCALAR;
6932 lhs.var = integer_id;
6933 lhs.offset = 0;
6934 rhs.type = ADDRESSOF;
6935 rhs.var = anything_id;
6936 rhs.offset = 0;
6937 process_constraint (new_constraint (lhs, rhs));
6940 /* Initialize things necessary to perform PTA */
6942 static void
6943 init_alias_vars (void)
6945 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6947 bitmap_obstack_initialize (&pta_obstack);
6948 bitmap_obstack_initialize (&oldpta_obstack);
6949 bitmap_obstack_initialize (&predbitmap_obstack);
6951 constraints.create (8);
6952 varmap.create (8);
6953 vi_for_tree = new hash_map<tree, varinfo_t>;
6954 call_stmt_vars = new hash_map<gimple *, varinfo_t>;
6956 memset (&stats, 0, sizeof (stats));
6957 shared_bitmap_table = new hash_table<shared_bitmap_hasher> (511);
6958 init_base_vars ();
6960 gcc_obstack_init (&fake_var_decl_obstack);
6962 final_solutions = new hash_map<varinfo_t, pt_solution *>;
6963 gcc_obstack_init (&final_solutions_obstack);
6966 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6967 predecessor edges. */
6969 static void
6970 remove_preds_and_fake_succs (constraint_graph_t graph)
6972 unsigned int i;
6974 /* Clear the implicit ref and address nodes from the successor
6975 lists. */
6976 for (i = 1; i < FIRST_REF_NODE; i++)
6978 if (graph->succs[i])
6979 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6980 FIRST_REF_NODE * 2);
6983 /* Free the successor list for the non-ref nodes. */
6984 for (i = FIRST_REF_NODE + 1; i < graph->size; i++)
6986 if (graph->succs[i])
6987 BITMAP_FREE (graph->succs[i]);
6990 /* Now reallocate the size of the successor list as, and blow away
6991 the predecessor bitmaps. */
6992 graph->size = varmap.length ();
6993 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6995 free (graph->implicit_preds);
6996 graph->implicit_preds = NULL;
6997 free (graph->preds);
6998 graph->preds = NULL;
6999 bitmap_obstack_release (&predbitmap_obstack);
7002 /* Solve the constraint set. */
7004 static void
7005 solve_constraints (void)
7007 struct scc_info *si;
7009 if (dump_file)
7010 fprintf (dump_file,
7011 "\nCollapsing static cycles and doing variable "
7012 "substitution\n");
7014 init_graph (varmap.length () * 2);
7016 if (dump_file)
7017 fprintf (dump_file, "Building predecessor graph\n");
7018 build_pred_graph ();
7020 if (dump_file)
7021 fprintf (dump_file, "Detecting pointer and location "
7022 "equivalences\n");
7023 si = perform_var_substitution (graph);
7025 if (dump_file)
7026 fprintf (dump_file, "Rewriting constraints and unifying "
7027 "variables\n");
7028 rewrite_constraints (graph, si);
7030 build_succ_graph ();
7032 free_var_substitution_info (si);
7034 /* Attach complex constraints to graph nodes. */
7035 move_complex_constraints (graph);
7037 if (dump_file)
7038 fprintf (dump_file, "Uniting pointer but not location equivalent "
7039 "variables\n");
7040 unite_pointer_equivalences (graph);
7042 if (dump_file)
7043 fprintf (dump_file, "Finding indirect cycles\n");
7044 find_indirect_cycles (graph);
7046 /* Implicit nodes and predecessors are no longer necessary at this
7047 point. */
7048 remove_preds_and_fake_succs (graph);
7050 if (dump_file && (dump_flags & TDF_GRAPH))
7052 fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
7053 "in dot format:\n");
7054 dump_constraint_graph (dump_file);
7055 fprintf (dump_file, "\n\n");
7058 if (dump_file)
7059 fprintf (dump_file, "Solving graph\n");
7061 solve_graph (graph);
7063 if (dump_file && (dump_flags & TDF_GRAPH))
7065 fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
7066 "in dot format:\n");
7067 dump_constraint_graph (dump_file);
7068 fprintf (dump_file, "\n\n");
7071 if (dump_file)
7072 dump_sa_points_to_info (dump_file);
7075 /* Create points-to sets for the current function. See the comments
7076 at the start of the file for an algorithmic overview. */
7078 static void
7079 compute_points_to_sets (void)
7081 basic_block bb;
7082 unsigned i;
7083 varinfo_t vi;
7085 timevar_push (TV_TREE_PTA);
7087 init_alias_vars ();
7089 intra_create_variable_infos (cfun);
7091 /* Now walk all statements and build the constraint set. */
7092 FOR_EACH_BB_FN (bb, cfun)
7094 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7095 gsi_next (&gsi))
7097 gphi *phi = gsi.phi ();
7099 if (! virtual_operand_p (gimple_phi_result (phi)))
7100 find_func_aliases (cfun, phi);
7103 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7104 gsi_next (&gsi))
7106 gimple *stmt = gsi_stmt (gsi);
7108 find_func_aliases (cfun, stmt);
7112 if (dump_file)
7114 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
7115 dump_constraints (dump_file, 0);
7118 /* From the constraints compute the points-to sets. */
7119 solve_constraints ();
7121 /* Compute the points-to set for ESCAPED used for call-clobber analysis. */
7122 cfun->gimple_df->escaped = find_what_var_points_to (cfun->decl,
7123 get_varinfo (escaped_id));
7125 /* Make sure the ESCAPED solution (which is used as placeholder in
7126 other solutions) does not reference itself. This simplifies
7127 points-to solution queries. */
7128 cfun->gimple_df->escaped.escaped = 0;
7130 /* Compute the points-to sets for pointer SSA_NAMEs. */
7131 for (i = 0; i < num_ssa_names; ++i)
7133 tree ptr = ssa_name (i);
7134 if (ptr
7135 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7136 find_what_p_points_to (cfun->decl, ptr);
7139 /* Compute the call-used/clobbered sets. */
7140 FOR_EACH_BB_FN (bb, cfun)
7142 gimple_stmt_iterator gsi;
7144 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7146 gcall *stmt;
7147 struct pt_solution *pt;
7149 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7150 if (!stmt)
7151 continue;
7153 pt = gimple_call_use_set (stmt);
7154 if (gimple_call_flags (stmt) & ECF_CONST)
7155 memset (pt, 0, sizeof (struct pt_solution));
7156 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7158 *pt = find_what_var_points_to (cfun->decl, vi);
7159 /* Escaped (and thus nonlocal) variables are always
7160 implicitly used by calls. */
7161 /* ??? ESCAPED can be empty even though NONLOCAL
7162 always escaped. */
7163 pt->nonlocal = 1;
7164 pt->escaped = 1;
7166 else
7168 /* If there is nothing special about this call then
7169 we have made everything that is used also escape. */
7170 *pt = cfun->gimple_df->escaped;
7171 pt->nonlocal = 1;
7174 pt = gimple_call_clobber_set (stmt);
7175 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7176 memset (pt, 0, sizeof (struct pt_solution));
7177 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7179 *pt = find_what_var_points_to (cfun->decl, vi);
7180 /* Escaped (and thus nonlocal) variables are always
7181 implicitly clobbered by calls. */
7182 /* ??? ESCAPED can be empty even though NONLOCAL
7183 always escaped. */
7184 pt->nonlocal = 1;
7185 pt->escaped = 1;
7187 else
7189 /* If there is nothing special about this call then
7190 we have made everything that is used also escape. */
7191 *pt = cfun->gimple_df->escaped;
7192 pt->nonlocal = 1;
7197 timevar_pop (TV_TREE_PTA);
7201 /* Delete created points-to sets. */
7203 static void
7204 delete_points_to_sets (void)
7206 unsigned int i;
7208 delete shared_bitmap_table;
7209 shared_bitmap_table = NULL;
7210 if (dump_file && (dump_flags & TDF_STATS))
7211 fprintf (dump_file, "Points to sets created:%d\n",
7212 stats.points_to_sets_created);
7214 delete vi_for_tree;
7215 delete call_stmt_vars;
7216 bitmap_obstack_release (&pta_obstack);
7217 constraints.release ();
7219 for (i = 0; i < graph->size; i++)
7220 graph->complex[i].release ();
7221 free (graph->complex);
7223 free (graph->rep);
7224 free (graph->succs);
7225 free (graph->pe);
7226 free (graph->pe_rep);
7227 free (graph->indirect_cycles);
7228 free (graph);
7230 varmap.release ();
7231 variable_info_pool.release ();
7232 constraint_pool.release ();
7234 obstack_free (&fake_var_decl_obstack, NULL);
7236 delete final_solutions;
7237 obstack_free (&final_solutions_obstack, NULL);
7240 /* Mark "other" loads and stores as belonging to CLIQUE and with
7241 base zero. */
7243 static bool
7244 visit_loadstore (gimple *, tree base, tree ref, void *clique_)
7246 unsigned short clique = (uintptr_t)clique_;
7247 if (TREE_CODE (base) == MEM_REF
7248 || TREE_CODE (base) == TARGET_MEM_REF)
7250 tree ptr = TREE_OPERAND (base, 0);
7251 if (TREE_CODE (ptr) == SSA_NAME
7252 && ! SSA_NAME_IS_DEFAULT_DEF (ptr))
7254 /* ??? We need to make sure 'ptr' doesn't include any of
7255 the restrict tags we added bases for in its points-to set. */
7256 return false;
7259 /* For now let decls through. */
7261 /* Do not overwrite existing cliques (that includes clique, base
7262 pairs we just set). */
7263 if (MR_DEPENDENCE_CLIQUE (base) == 0)
7265 MR_DEPENDENCE_CLIQUE (base) = clique;
7266 MR_DEPENDENCE_BASE (base) = 0;
7270 /* For plain decl accesses see whether they are accesses to globals
7271 and rewrite them to MEM_REFs with { clique, 0 }. */
7272 if (TREE_CODE (base) == VAR_DECL
7273 && is_global_var (base)
7274 /* ??? We can't rewrite a plain decl with the walk_stmt_load_store
7275 ops callback. */
7276 && base != ref)
7278 tree *basep = &ref;
7279 while (handled_component_p (*basep))
7280 basep = &TREE_OPERAND (*basep, 0);
7281 gcc_assert (TREE_CODE (*basep) == VAR_DECL);
7282 tree ptr = build_fold_addr_expr (*basep);
7283 tree zero = build_int_cst (TREE_TYPE (ptr), 0);
7284 *basep = build2 (MEM_REF, TREE_TYPE (*basep), ptr, zero);
7285 MR_DEPENDENCE_CLIQUE (*basep) = clique;
7286 MR_DEPENDENCE_BASE (*basep) = 0;
7289 return false;
7292 /* If REF is a MEM_REF then assign a clique, base pair to it, updating
7293 CLIQUE, *RESTRICT_VAR and LAST_RUID. Return whether dependence info
7294 was assigned to REF. */
7296 static bool
7297 maybe_set_dependence_info (tree ref, tree ptr,
7298 unsigned short &clique, varinfo_t restrict_var,
7299 unsigned short &last_ruid)
7301 while (handled_component_p (ref))
7302 ref = TREE_OPERAND (ref, 0);
7303 if ((TREE_CODE (ref) == MEM_REF
7304 || TREE_CODE (ref) == TARGET_MEM_REF)
7305 && TREE_OPERAND (ref, 0) == ptr)
7307 /* Do not overwrite existing cliques. This avoids overwriting dependence
7308 info inlined from a function with restrict parameters inlined
7309 into a function with restrict parameters. This usually means we
7310 prefer to be precise in innermost loops. */
7311 if (MR_DEPENDENCE_CLIQUE (ref) == 0)
7313 if (clique == 0)
7314 clique = ++cfun->last_clique;
7315 if (restrict_var->ruid == 0)
7316 restrict_var->ruid = ++last_ruid;
7317 MR_DEPENDENCE_CLIQUE (ref) = clique;
7318 MR_DEPENDENCE_BASE (ref) = restrict_var->ruid;
7319 return true;
7322 return false;
7325 /* Compute the set of independend memory references based on restrict
7326 tags and their conservative propagation to the points-to sets. */
7328 static void
7329 compute_dependence_clique (void)
7331 unsigned short clique = 0;
7332 unsigned short last_ruid = 0;
7333 for (unsigned i = 0; i < num_ssa_names; ++i)
7335 tree ptr = ssa_name (i);
7336 if (!ptr || !POINTER_TYPE_P (TREE_TYPE (ptr)))
7337 continue;
7339 /* Avoid all this when ptr is not dereferenced? */
7340 tree p = ptr;
7341 if (SSA_NAME_IS_DEFAULT_DEF (ptr)
7342 && (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
7343 || TREE_CODE (SSA_NAME_VAR (ptr)) == RESULT_DECL))
7344 p = SSA_NAME_VAR (ptr);
7345 varinfo_t vi = lookup_vi_for_tree (p);
7346 if (!vi)
7347 continue;
7348 vi = get_varinfo (find (vi->id));
7349 bitmap_iterator bi;
7350 unsigned j;
7351 varinfo_t restrict_var = NULL;
7352 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, j, bi)
7354 varinfo_t oi = get_varinfo (j);
7355 if (oi->is_restrict_var)
7357 if (restrict_var)
7359 if (dump_file && (dump_flags & TDF_DETAILS))
7361 fprintf (dump_file, "found restrict pointed-to "
7362 "for ");
7363 print_generic_expr (dump_file, ptr, 0);
7364 fprintf (dump_file, " but not exclusively\n");
7366 restrict_var = NULL;
7367 break;
7369 restrict_var = oi;
7371 /* NULL is the only other valid points-to entry. */
7372 else if (oi->id != nothing_id)
7374 restrict_var = NULL;
7375 break;
7378 /* Ok, found that ptr must(!) point to a single(!) restrict
7379 variable. */
7380 /* ??? PTA isn't really a proper propagation engine to compute
7381 this property.
7382 ??? We could handle merging of two restricts by unifying them. */
7383 if (restrict_var)
7385 /* Now look at possible dereferences of ptr. */
7386 imm_use_iterator ui;
7387 gimple *use_stmt;
7388 FOR_EACH_IMM_USE_STMT (use_stmt, ui, ptr)
7390 /* ??? Calls and asms. */
7391 if (!gimple_assign_single_p (use_stmt))
7392 continue;
7393 maybe_set_dependence_info (gimple_assign_lhs (use_stmt), ptr,
7394 clique, restrict_var, last_ruid);
7395 maybe_set_dependence_info (gimple_assign_rhs1 (use_stmt), ptr,
7396 clique, restrict_var, last_ruid);
7401 if (clique == 0)
7402 return;
7404 /* Assign the BASE id zero to all accesses not based on a restrict
7405 pointer. That way they get disabiguated against restrict
7406 accesses but not against each other. */
7407 /* ??? For restricts derived from globals (thus not incoming
7408 parameters) we can't restrict scoping properly thus the following
7409 is too aggressive there. For now we have excluded those globals from
7410 getting into the MR_DEPENDENCE machinery. */
7411 basic_block bb;
7412 FOR_EACH_BB_FN (bb, cfun)
7413 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7414 !gsi_end_p (gsi); gsi_next (&gsi))
7416 gimple *stmt = gsi_stmt (gsi);
7417 walk_stmt_load_store_ops (stmt, (void *)(uintptr_t)clique,
7418 visit_loadstore, visit_loadstore);
7422 /* Compute points-to information for every SSA_NAME pointer in the
7423 current function and compute the transitive closure of escaped
7424 variables to re-initialize the call-clobber states of local variables. */
7426 unsigned int
7427 compute_may_aliases (void)
7429 if (cfun->gimple_df->ipa_pta)
7431 if (dump_file)
7433 fprintf (dump_file, "\nNot re-computing points-to information "
7434 "because IPA points-to information is available.\n\n");
7436 /* But still dump what we have remaining it. */
7437 dump_alias_info (dump_file);
7440 return 0;
7443 /* For each pointer P_i, determine the sets of variables that P_i may
7444 point-to. Compute the reachability set of escaped and call-used
7445 variables. */
7446 compute_points_to_sets ();
7448 /* Debugging dumps. */
7449 if (dump_file)
7450 dump_alias_info (dump_file);
7452 /* Compute restrict-based memory disambiguations. */
7453 compute_dependence_clique ();
7455 /* Deallocate memory used by aliasing data structures and the internal
7456 points-to solution. */
7457 delete_points_to_sets ();
7459 gcc_assert (!need_ssa_update_p (cfun));
7461 return 0;
7464 /* A dummy pass to cause points-to information to be computed via
7465 TODO_rebuild_alias. */
7467 namespace {
7469 const pass_data pass_data_build_alias =
7471 GIMPLE_PASS, /* type */
7472 "alias", /* name */
7473 OPTGROUP_NONE, /* optinfo_flags */
7474 TV_NONE, /* tv_id */
7475 ( PROP_cfg | PROP_ssa ), /* properties_required */
7476 0, /* properties_provided */
7477 0, /* properties_destroyed */
7478 0, /* todo_flags_start */
7479 TODO_rebuild_alias, /* todo_flags_finish */
7482 class pass_build_alias : public gimple_opt_pass
7484 public:
7485 pass_build_alias (gcc::context *ctxt)
7486 : gimple_opt_pass (pass_data_build_alias, ctxt)
7489 /* opt_pass methods: */
7490 virtual bool gate (function *) { return flag_tree_pta; }
7492 }; // class pass_build_alias
7494 } // anon namespace
7496 gimple_opt_pass *
7497 make_pass_build_alias (gcc::context *ctxt)
7499 return new pass_build_alias (ctxt);
7502 /* A dummy pass to cause points-to information to be computed via
7503 TODO_rebuild_alias. */
7505 namespace {
7507 const pass_data pass_data_build_ealias =
7509 GIMPLE_PASS, /* type */
7510 "ealias", /* name */
7511 OPTGROUP_NONE, /* optinfo_flags */
7512 TV_NONE, /* tv_id */
7513 ( PROP_cfg | PROP_ssa ), /* properties_required */
7514 0, /* properties_provided */
7515 0, /* properties_destroyed */
7516 0, /* todo_flags_start */
7517 TODO_rebuild_alias, /* todo_flags_finish */
7520 class pass_build_ealias : public gimple_opt_pass
7522 public:
7523 pass_build_ealias (gcc::context *ctxt)
7524 : gimple_opt_pass (pass_data_build_ealias, ctxt)
7527 /* opt_pass methods: */
7528 virtual bool gate (function *) { return flag_tree_pta; }
7530 }; // class pass_build_ealias
7532 } // anon namespace
7534 gimple_opt_pass *
7535 make_pass_build_ealias (gcc::context *ctxt)
7537 return new pass_build_ealias (ctxt);
7541 /* IPA PTA solutions for ESCAPED. */
7542 struct pt_solution ipa_escaped_pt
7543 = { true, false, false, false, false, false, false, false, NULL };
7545 /* Associate node with varinfo DATA. Worker for
7546 cgraph_for_symbol_thunks_and_aliases. */
7547 static bool
7548 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
7550 if ((node->alias || node->thunk.thunk_p)
7551 && node->analyzed)
7552 insert_vi_for_tree (node->decl, (varinfo_t)data);
7553 return false;
7556 /* Compute whether node is refered to non-locally. Worker for
7557 cgraph_for_symbol_thunks_and_aliases. */
7558 static bool
7559 refered_from_nonlocal_fn (struct cgraph_node *node, void *data)
7561 bool *nonlocal_p = (bool *)data;
7562 *nonlocal_p |= (node->used_from_other_partition
7563 || node->externally_visible
7564 || node->force_output);
7565 return false;
7568 /* Same for varpool nodes. */
7569 static bool
7570 refered_from_nonlocal_var (struct varpool_node *node, void *data)
7572 bool *nonlocal_p = (bool *)data;
7573 *nonlocal_p |= (node->used_from_other_partition
7574 || node->externally_visible
7575 || node->force_output);
7576 return false;
7579 /* Execute the driver for IPA PTA. */
7580 static unsigned int
7581 ipa_pta_execute (void)
7583 struct cgraph_node *node;
7584 varpool_node *var;
7585 unsigned int from = 0;
7587 in_ipa_mode = 1;
7589 init_alias_vars ();
7591 if (dump_file && (dump_flags & TDF_DETAILS))
7593 symtab_node::dump_table (dump_file);
7594 fprintf (dump_file, "\n");
7597 if (dump_file)
7599 fprintf (dump_file, "Generating generic constraints\n\n");
7600 dump_constraints (dump_file, from);
7601 fprintf (dump_file, "\n");
7602 from = constraints.length ();
7605 /* Build the constraints. */
7606 FOR_EACH_DEFINED_FUNCTION (node)
7608 varinfo_t vi;
7609 /* Nodes without a body are not interesting. Especially do not
7610 visit clones at this point for now - we get duplicate decls
7611 there for inline clones at least. */
7612 if (!node->has_gimple_body_p () || node->global.inlined_to)
7613 continue;
7614 node->get_body ();
7616 gcc_assert (!node->clone_of);
7618 /* When parallelizing a code region, we split the region off into a
7619 separate function, to be run by several threads in parallel. So for a
7620 function foo, we split off a region into a function
7621 foo._0 (void *foodata), and replace the region with some variant of a
7622 function call run_on_threads (&foo._0, data). The '&foo._0' sets the
7623 address_taken bit for function foo._0, which would make it non-local.
7624 But for the purpose of ipa-pta, we can regard the run_on_threads call
7625 as a local call foo._0 (data), so we ignore address_taken on nodes
7626 with parallelized_function set.
7627 Note: this is only safe, if foo and foo._0 are in the same lto
7628 partition. */
7629 bool node_address_taken = ((node->parallelized_function
7630 && !node->used_from_other_partition)
7631 ? false
7632 : node->address_taken);
7634 /* For externally visible or attribute used annotated functions use
7635 local constraints for their arguments.
7636 For local functions we see all callers and thus do not need initial
7637 constraints for parameters. */
7638 bool nonlocal_p = (node->used_from_other_partition
7639 || node->externally_visible
7640 || node->force_output
7641 || node_address_taken);
7642 node->call_for_symbol_thunks_and_aliases (refered_from_nonlocal_fn,
7643 &nonlocal_p, true);
7645 vi = create_function_info_for (node->decl,
7646 alias_get_name (node->decl), false,
7647 nonlocal_p);
7648 if (dump_file
7649 && from != constraints.length ())
7651 fprintf (dump_file,
7652 "Generating intial constraints for %s", node->name ());
7653 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7654 fprintf (dump_file, " (%s)",
7655 IDENTIFIER_POINTER
7656 (DECL_ASSEMBLER_NAME (node->decl)));
7657 fprintf (dump_file, "\n\n");
7658 dump_constraints (dump_file, from);
7659 fprintf (dump_file, "\n");
7661 from = constraints.length ();
7664 node->call_for_symbol_thunks_and_aliases
7665 (associate_varinfo_to_alias, vi, true);
7668 /* Create constraints for global variables and their initializers. */
7669 FOR_EACH_VARIABLE (var)
7671 if (var->alias && var->analyzed)
7672 continue;
7674 varinfo_t vi = get_vi_for_tree (var->decl);
7676 /* For the purpose of IPA PTA unit-local globals are not
7677 escape points. */
7678 bool nonlocal_p = (var->used_from_other_partition
7679 || var->externally_visible
7680 || var->force_output);
7681 var->call_for_symbol_and_aliases (refered_from_nonlocal_var,
7682 &nonlocal_p, true);
7683 if (nonlocal_p)
7684 vi->is_ipa_escape_point = true;
7687 if (dump_file
7688 && from != constraints.length ())
7690 fprintf (dump_file,
7691 "Generating constraints for global initializers\n\n");
7692 dump_constraints (dump_file, from);
7693 fprintf (dump_file, "\n");
7694 from = constraints.length ();
7697 FOR_EACH_DEFINED_FUNCTION (node)
7699 struct function *func;
7700 basic_block bb;
7702 /* Nodes without a body are not interesting. */
7703 if (!node->has_gimple_body_p () || node->clone_of)
7704 continue;
7706 if (dump_file)
7708 fprintf (dump_file,
7709 "Generating constraints for %s", node->name ());
7710 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7711 fprintf (dump_file, " (%s)",
7712 IDENTIFIER_POINTER
7713 (DECL_ASSEMBLER_NAME (node->decl)));
7714 fprintf (dump_file, "\n");
7717 func = DECL_STRUCT_FUNCTION (node->decl);
7718 gcc_assert (cfun == NULL);
7720 /* Build constriants for the function body. */
7721 FOR_EACH_BB_FN (bb, func)
7723 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7724 gsi_next (&gsi))
7726 gphi *phi = gsi.phi ();
7728 if (! virtual_operand_p (gimple_phi_result (phi)))
7729 find_func_aliases (func, phi);
7732 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7733 gsi_next (&gsi))
7735 gimple *stmt = gsi_stmt (gsi);
7737 find_func_aliases (func, stmt);
7738 find_func_clobbers (func, stmt);
7742 if (dump_file)
7744 fprintf (dump_file, "\n");
7745 dump_constraints (dump_file, from);
7746 fprintf (dump_file, "\n");
7747 from = constraints.length ();
7751 /* From the constraints compute the points-to sets. */
7752 solve_constraints ();
7754 /* Compute the global points-to sets for ESCAPED.
7755 ??? Note that the computed escape set is not correct
7756 for the whole unit as we fail to consider graph edges to
7757 externally visible functions. */
7758 ipa_escaped_pt = find_what_var_points_to (NULL, get_varinfo (escaped_id));
7760 /* Make sure the ESCAPED solution (which is used as placeholder in
7761 other solutions) does not reference itself. This simplifies
7762 points-to solution queries. */
7763 ipa_escaped_pt.ipa_escaped = 0;
7765 /* Assign the points-to sets to the SSA names in the unit. */
7766 FOR_EACH_DEFINED_FUNCTION (node)
7768 tree ptr;
7769 struct function *fn;
7770 unsigned i;
7771 basic_block bb;
7773 /* Nodes without a body are not interesting. */
7774 if (!node->has_gimple_body_p () || node->clone_of)
7775 continue;
7777 fn = DECL_STRUCT_FUNCTION (node->decl);
7779 /* Compute the points-to sets for pointer SSA_NAMEs. */
7780 FOR_EACH_VEC_ELT (*fn->gimple_df->ssa_names, i, ptr)
7782 if (ptr
7783 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7784 find_what_p_points_to (node->decl, ptr);
7787 /* Compute the call-use and call-clobber sets for indirect calls
7788 and calls to external functions. */
7789 FOR_EACH_BB_FN (bb, fn)
7791 gimple_stmt_iterator gsi;
7793 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7795 gcall *stmt;
7796 struct pt_solution *pt;
7797 varinfo_t vi, fi;
7798 tree decl;
7800 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7801 if (!stmt)
7802 continue;
7804 /* Handle direct calls to functions with body. */
7805 decl = gimple_call_fndecl (stmt);
7808 tree called_decl = NULL_TREE;
7809 if (gimple_call_builtin_p (stmt, BUILT_IN_GOMP_PARALLEL))
7810 called_decl = TREE_OPERAND (gimple_call_arg (stmt, 0), 0);
7811 else if (gimple_call_builtin_p (stmt, BUILT_IN_GOACC_PARALLEL))
7812 called_decl = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
7814 if (called_decl != NULL_TREE
7815 && !fndecl_maybe_in_other_partition (called_decl))
7816 decl = called_decl;
7819 if (decl
7820 && (fi = lookup_vi_for_tree (decl))
7821 && fi->is_fn_info)
7823 *gimple_call_clobber_set (stmt)
7824 = find_what_var_points_to
7825 (node->decl, first_vi_for_offset (fi, fi_clobbers));
7826 *gimple_call_use_set (stmt)
7827 = find_what_var_points_to
7828 (node->decl, first_vi_for_offset (fi, fi_uses));
7830 /* Handle direct calls to external functions. */
7831 else if (decl)
7833 pt = gimple_call_use_set (stmt);
7834 if (gimple_call_flags (stmt) & ECF_CONST)
7835 memset (pt, 0, sizeof (struct pt_solution));
7836 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7838 *pt = find_what_var_points_to (node->decl, vi);
7839 /* Escaped (and thus nonlocal) variables are always
7840 implicitly used by calls. */
7841 /* ??? ESCAPED can be empty even though NONLOCAL
7842 always escaped. */
7843 pt->nonlocal = 1;
7844 pt->ipa_escaped = 1;
7846 else
7848 /* If there is nothing special about this call then
7849 we have made everything that is used also escape. */
7850 *pt = ipa_escaped_pt;
7851 pt->nonlocal = 1;
7854 pt = gimple_call_clobber_set (stmt);
7855 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7856 memset (pt, 0, sizeof (struct pt_solution));
7857 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7859 *pt = find_what_var_points_to (node->decl, vi);
7860 /* Escaped (and thus nonlocal) variables are always
7861 implicitly clobbered by calls. */
7862 /* ??? ESCAPED can be empty even though NONLOCAL
7863 always escaped. */
7864 pt->nonlocal = 1;
7865 pt->ipa_escaped = 1;
7867 else
7869 /* If there is nothing special about this call then
7870 we have made everything that is used also escape. */
7871 *pt = ipa_escaped_pt;
7872 pt->nonlocal = 1;
7875 /* Handle indirect calls. */
7876 else if (!decl
7877 && (fi = get_fi_for_callee (stmt)))
7879 /* We need to accumulate all clobbers/uses of all possible
7880 callees. */
7881 fi = get_varinfo (find (fi->id));
7882 /* If we cannot constrain the set of functions we'll end up
7883 calling we end up using/clobbering everything. */
7884 if (bitmap_bit_p (fi->solution, anything_id)
7885 || bitmap_bit_p (fi->solution, nonlocal_id)
7886 || bitmap_bit_p (fi->solution, escaped_id))
7888 pt_solution_reset (gimple_call_clobber_set (stmt));
7889 pt_solution_reset (gimple_call_use_set (stmt));
7891 else
7893 bitmap_iterator bi;
7894 unsigned i;
7895 struct pt_solution *uses, *clobbers;
7897 uses = gimple_call_use_set (stmt);
7898 clobbers = gimple_call_clobber_set (stmt);
7899 memset (uses, 0, sizeof (struct pt_solution));
7900 memset (clobbers, 0, sizeof (struct pt_solution));
7901 EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7903 struct pt_solution sol;
7905 vi = get_varinfo (i);
7906 if (!vi->is_fn_info)
7908 /* ??? We could be more precise here? */
7909 uses->nonlocal = 1;
7910 uses->ipa_escaped = 1;
7911 clobbers->nonlocal = 1;
7912 clobbers->ipa_escaped = 1;
7913 continue;
7916 if (!uses->anything)
7918 sol = find_what_var_points_to
7919 (node->decl,
7920 first_vi_for_offset (vi, fi_uses));
7921 pt_solution_ior_into (uses, &sol);
7923 if (!clobbers->anything)
7925 sol = find_what_var_points_to
7926 (node->decl,
7927 first_vi_for_offset (vi, fi_clobbers));
7928 pt_solution_ior_into (clobbers, &sol);
7936 fn->gimple_df->ipa_pta = true;
7938 /* We have to re-set the final-solution cache after each function
7939 because what is a "global" is dependent on function context. */
7940 final_solutions->empty ();
7941 obstack_free (&final_solutions_obstack, NULL);
7942 gcc_obstack_init (&final_solutions_obstack);
7945 delete_points_to_sets ();
7947 in_ipa_mode = 0;
7949 return 0;
7952 namespace {
7954 const pass_data pass_data_ipa_pta =
7956 SIMPLE_IPA_PASS, /* type */
7957 "pta", /* name */
7958 OPTGROUP_NONE, /* optinfo_flags */
7959 TV_IPA_PTA, /* tv_id */
7960 0, /* properties_required */
7961 0, /* properties_provided */
7962 0, /* properties_destroyed */
7963 0, /* todo_flags_start */
7964 0, /* todo_flags_finish */
7967 class pass_ipa_pta : public simple_ipa_opt_pass
7969 public:
7970 pass_ipa_pta (gcc::context *ctxt)
7971 : simple_ipa_opt_pass (pass_data_ipa_pta, ctxt)
7974 /* opt_pass methods: */
7975 virtual bool gate (function *)
7977 return (optimize
7978 && flag_ipa_pta
7979 /* Don't bother doing anything if the program has errors. */
7980 && !seen_error ());
7983 opt_pass * clone () { return new pass_ipa_pta (m_ctxt); }
7985 virtual unsigned int execute (function *) { return ipa_pta_execute (); }
7987 }; // class pass_ipa_pta
7989 } // anon namespace
7991 simple_ipa_opt_pass *
7992 make_pass_ipa_pta (gcc::context *ctxt)
7994 return new pass_ipa_pta (ctxt);