Update gcc-50 to SVN version 231263 (gcc-5-branch)
[dragonfly.git] / contrib / gcc-5.0 / gcc / tree-ssa-structalias.c
blobc12128a923b0e8f8384d066f58a8627cab0636d6
1 /* Tree based points-to analysis
2 Copyright (C) 2005-2015 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dberlin@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "obstack.h"
26 #include "bitmap.h"
27 #include "sbitmap.h"
28 #include "flags.h"
29 #include "predict.h"
30 #include "vec.h"
31 #include "hashtab.h"
32 #include "hash-set.h"
33 #include "machmode.h"
34 #include "hard-reg-set.h"
35 #include "input.h"
36 #include "function.h"
37 #include "dominance.h"
38 #include "cfg.h"
39 #include "basic-block.h"
40 #include "double-int.h"
41 #include "alias.h"
42 #include "symtab.h"
43 #include "wide-int.h"
44 #include "inchash.h"
45 #include "tree.h"
46 #include "fold-const.h"
47 #include "stor-layout.h"
48 #include "stmt.h"
49 #include "hash-table.h"
50 #include "tree-ssa-alias.h"
51 #include "internal-fn.h"
52 #include "gimple-expr.h"
53 #include "is-a.h"
54 #include "gimple.h"
55 #include "gimple-iterator.h"
56 #include "gimple-ssa.h"
57 #include "hash-map.h"
58 #include "plugin-api.h"
59 #include "ipa-ref.h"
60 #include "cgraph.h"
61 #include "stringpool.h"
62 #include "tree-ssanames.h"
63 #include "tree-into-ssa.h"
64 #include "rtl.h"
65 #include "statistics.h"
66 #include "real.h"
67 #include "fixed-value.h"
68 #include "insn-config.h"
69 #include "expmed.h"
70 #include "dojump.h"
71 #include "explow.h"
72 #include "calls.h"
73 #include "emit-rtl.h"
74 #include "varasm.h"
75 #include "expr.h"
76 #include "tree-dfa.h"
77 #include "tree-inline.h"
78 #include "diagnostic-core.h"
79 #include "tree-pass.h"
80 #include "alloc-pool.h"
81 #include "splay-tree.h"
82 #include "params.h"
83 #include "tree-phinodes.h"
84 #include "ssa-iterators.h"
85 #include "tree-pretty-print.h"
86 #include "gimple-walk.h"
88 /* The idea behind this analyzer is to generate set constraints from the
89 program, then solve the resulting constraints in order to generate the
90 points-to sets.
92 Set constraints are a way of modeling program analysis problems that
93 involve sets. They consist of an inclusion constraint language,
94 describing the variables (each variable is a set) and operations that
95 are involved on the variables, and a set of rules that derive facts
96 from these operations. To solve a system of set constraints, you derive
97 all possible facts under the rules, which gives you the correct sets
98 as a consequence.
100 See "Efficient Field-sensitive pointer analysis for C" by "David
101 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
102 http://citeseer.ist.psu.edu/pearce04efficient.html
104 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
105 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
106 http://citeseer.ist.psu.edu/heintze01ultrafast.html
108 There are three types of real constraint expressions, DEREF,
109 ADDRESSOF, and SCALAR. Each constraint expression consists
110 of a constraint type, a variable, and an offset.
112 SCALAR is a constraint expression type used to represent x, whether
113 it appears on the LHS or the RHS of a statement.
114 DEREF is a constraint expression type used to represent *x, whether
115 it appears on the LHS or the RHS of a statement.
116 ADDRESSOF is a constraint expression used to represent &x, whether
117 it appears on the LHS or the RHS of a statement.
119 Each pointer variable in the program is assigned an integer id, and
120 each field of a structure variable is assigned an integer id as well.
122 Structure variables are linked to their list of fields through a "next
123 field" in each variable that points to the next field in offset
124 order.
125 Each variable for a structure field has
127 1. "size", that tells the size in bits of that field.
128 2. "fullsize, that tells the size in bits of the entire structure.
129 3. "offset", that tells the offset in bits from the beginning of the
130 structure to this field.
132 Thus,
133 struct f
135 int a;
136 int b;
137 } foo;
138 int *bar;
140 looks like
142 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
143 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
144 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
147 In order to solve the system of set constraints, the following is
148 done:
150 1. Each constraint variable x has a solution set associated with it,
151 Sol(x).
153 2. Constraints are separated into direct, copy, and complex.
154 Direct constraints are ADDRESSOF constraints that require no extra
155 processing, such as P = &Q
156 Copy constraints are those of the form P = Q.
157 Complex constraints are all the constraints involving dereferences
158 and offsets (including offsetted copies).
160 3. All direct constraints of the form P = &Q are processed, such
161 that Q is added to Sol(P)
163 4. All complex constraints for a given constraint variable are stored in a
164 linked list attached to that variable's node.
166 5. A directed graph is built out of the copy constraints. Each
167 constraint variable is a node in the graph, and an edge from
168 Q to P is added for each copy constraint of the form P = Q
170 6. The graph is then walked, and solution sets are
171 propagated along the copy edges, such that an edge from Q to P
172 causes Sol(P) <- Sol(P) union Sol(Q).
174 7. As we visit each node, all complex constraints associated with
175 that node are processed by adding appropriate copy edges to the graph, or the
176 appropriate variables to the solution set.
178 8. The process of walking the graph is iterated until no solution
179 sets change.
181 Prior to walking the graph in steps 6 and 7, We perform static
182 cycle elimination on the constraint graph, as well
183 as off-line variable substitution.
185 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
186 on and turned into anything), but isn't. You can just see what offset
187 inside the pointed-to struct it's going to access.
189 TODO: Constant bounded arrays can be handled as if they were structs of the
190 same number of elements.
192 TODO: Modeling heap and incoming pointers becomes much better if we
193 add fields to them as we discover them, which we could do.
195 TODO: We could handle unions, but to be honest, it's probably not
196 worth the pain or slowdown. */
198 /* IPA-PTA optimizations possible.
200 When the indirect function called is ANYTHING we can add disambiguation
201 based on the function signatures (or simply the parameter count which
202 is the varinfo size). We also do not need to consider functions that
203 do not have their address taken.
205 The is_global_var bit which marks escape points is overly conservative
206 in IPA mode. Split it to is_escape_point and is_global_var - only
207 externally visible globals are escape points in IPA mode. This is
208 also needed to fix the pt_solution_includes_global predicate
209 (and thus ptr_deref_may_alias_global_p).
211 The way we introduce DECL_PT_UID to avoid fixing up all points-to
212 sets in the translation unit when we copy a DECL during inlining
213 pessimizes precision. The advantage is that the DECL_PT_UID keeps
214 compile-time and memory usage overhead low - the points-to sets
215 do not grow or get unshared as they would during a fixup phase.
216 An alternative solution is to delay IPA PTA until after all
217 inlining transformations have been applied.
219 The way we propagate clobber/use information isn't optimized.
220 It should use a new complex constraint that properly filters
221 out local variables of the callee (though that would make
222 the sets invalid after inlining). OTOH we might as well
223 admit defeat to WHOPR and simply do all the clobber/use analysis
224 and propagation after PTA finished but before we threw away
225 points-to information for memory variables. WHOPR and PTA
226 do not play along well anyway - the whole constraint solving
227 would need to be done in WPA phase and it will be very interesting
228 to apply the results to local SSA names during LTRANS phase.
230 We probably should compute a per-function unit-ESCAPE solution
231 propagating it simply like the clobber / uses solutions. The
232 solution can go alongside the non-IPA espaced solution and be
233 used to query which vars escape the unit through a function.
235 We never put function decls in points-to sets so we do not
236 keep the set of called functions for indirect calls.
238 And probably more. */
240 static bool use_field_sensitive = true;
241 static int in_ipa_mode = 0;
243 /* Used for predecessor bitmaps. */
244 static bitmap_obstack predbitmap_obstack;
246 /* Used for points-to sets. */
247 static bitmap_obstack pta_obstack;
249 /* Used for oldsolution members of variables. */
250 static bitmap_obstack oldpta_obstack;
252 /* Used for per-solver-iteration bitmaps. */
253 static bitmap_obstack iteration_obstack;
255 static unsigned int create_variable_info_for (tree, const char *);
256 typedef struct constraint_graph *constraint_graph_t;
257 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
259 struct constraint;
260 typedef struct constraint *constraint_t;
263 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
264 if (a) \
265 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
267 static struct constraint_stats
269 unsigned int total_vars;
270 unsigned int nonpointer_vars;
271 unsigned int unified_vars_static;
272 unsigned int unified_vars_dynamic;
273 unsigned int iterations;
274 unsigned int num_edges;
275 unsigned int num_implicit_edges;
276 unsigned int points_to_sets_created;
277 } stats;
279 struct variable_info
281 /* ID of this variable */
282 unsigned int id;
284 /* True if this is a variable created by the constraint analysis, such as
285 heap variables and constraints we had to break up. */
286 unsigned int is_artificial_var : 1;
288 /* True if this is a special variable whose solution set should not be
289 changed. */
290 unsigned int is_special_var : 1;
292 /* True for variables whose size is not known or variable. */
293 unsigned int is_unknown_size_var : 1;
295 /* True for (sub-)fields that represent a whole variable. */
296 unsigned int is_full_var : 1;
298 /* True if this is a heap variable. */
299 unsigned int is_heap_var : 1;
301 /* True if this field may contain pointers. */
302 unsigned int may_have_pointers : 1;
304 /* True if this field has only restrict qualified pointers. */
305 unsigned int only_restrict_pointers : 1;
307 /* True if this represents a heap var created for a restrict qualified
308 pointer. */
309 unsigned int is_restrict_var : 1;
311 /* True if this represents a global variable. */
312 unsigned int is_global_var : 1;
314 /* True if this represents a IPA function info. */
315 unsigned int is_fn_info : 1;
317 /* ??? Store somewhere better. */
318 unsigned short ruid;
320 /* The ID of the variable for the next field in this structure
321 or zero for the last field in this structure. */
322 unsigned next;
324 /* The ID of the variable for the first field in this structure. */
325 unsigned head;
327 /* Offset of this variable, in bits, from the base variable */
328 unsigned HOST_WIDE_INT offset;
330 /* Size of the variable, in bits. */
331 unsigned HOST_WIDE_INT size;
333 /* Full size of the base variable, in bits. */
334 unsigned HOST_WIDE_INT fullsize;
336 /* Name of this variable */
337 const char *name;
339 /* Tree that this variable is associated with. */
340 tree decl;
342 /* Points-to set for this variable. */
343 bitmap solution;
345 /* Old points-to set for this variable. */
346 bitmap oldsolution;
348 typedef struct variable_info *varinfo_t;
350 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
351 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
352 unsigned HOST_WIDE_INT);
353 static varinfo_t lookup_vi_for_tree (tree);
354 static inline bool type_can_have_subvars (const_tree);
356 /* Pool of variable info structures. */
357 static alloc_pool variable_info_pool;
359 /* Map varinfo to final pt_solution. */
360 static hash_map<varinfo_t, pt_solution *> *final_solutions;
361 struct obstack final_solutions_obstack;
363 /* Table of variable info structures for constraint variables.
364 Indexed directly by variable info id. */
365 static vec<varinfo_t> varmap;
367 /* Return the varmap element N */
369 static inline varinfo_t
370 get_varinfo (unsigned int n)
372 return varmap[n];
375 /* Return the next variable in the list of sub-variables of VI
376 or NULL if VI is the last sub-variable. */
378 static inline varinfo_t
379 vi_next (varinfo_t vi)
381 return get_varinfo (vi->next);
384 /* Static IDs for the special variables. Variable ID zero is unused
385 and used as terminator for the sub-variable chain. */
386 enum { nothing_id = 1, anything_id = 2, string_id = 3,
387 escaped_id = 4, nonlocal_id = 5,
388 storedanything_id = 6, integer_id = 7 };
390 /* Return a new variable info structure consisting for a variable
391 named NAME, and using constraint graph node NODE. Append it
392 to the vector of variable info structures. */
394 static varinfo_t
395 new_var_info (tree t, const char *name)
397 unsigned index = varmap.length ();
398 varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
400 ret->id = index;
401 ret->name = name;
402 ret->decl = t;
403 /* Vars without decl are artificial and do not have sub-variables. */
404 ret->is_artificial_var = (t == NULL_TREE);
405 ret->is_special_var = false;
406 ret->is_unknown_size_var = false;
407 ret->is_full_var = (t == NULL_TREE);
408 ret->is_heap_var = false;
409 ret->may_have_pointers = true;
410 ret->only_restrict_pointers = false;
411 ret->is_restrict_var = false;
412 ret->ruid = 0;
413 ret->is_global_var = (t == NULL_TREE);
414 ret->is_fn_info = false;
415 if (t && DECL_P (t))
416 ret->is_global_var = (is_global_var (t)
417 /* We have to treat even local register variables
418 as escape points. */
419 || (TREE_CODE (t) == VAR_DECL
420 && DECL_HARD_REGISTER (t)));
421 ret->solution = BITMAP_ALLOC (&pta_obstack);
422 ret->oldsolution = NULL;
423 ret->next = 0;
424 ret->head = ret->id;
426 stats.total_vars++;
428 varmap.safe_push (ret);
430 return ret;
434 /* A map mapping call statements to per-stmt variables for uses
435 and clobbers specific to the call. */
436 static hash_map<gimple, varinfo_t> *call_stmt_vars;
438 /* Lookup or create the variable for the call statement CALL. */
440 static varinfo_t
441 get_call_vi (gcall *call)
443 varinfo_t vi, vi2;
445 bool existed;
446 varinfo_t *slot_p = &call_stmt_vars->get_or_insert (call, &existed);
447 if (existed)
448 return *slot_p;
450 vi = new_var_info (NULL_TREE, "CALLUSED");
451 vi->offset = 0;
452 vi->size = 1;
453 vi->fullsize = 2;
454 vi->is_full_var = true;
456 vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED");
457 vi2->offset = 1;
458 vi2->size = 1;
459 vi2->fullsize = 2;
460 vi2->is_full_var = true;
462 vi->next = vi2->id;
464 *slot_p = vi;
465 return vi;
468 /* Lookup the variable for the call statement CALL representing
469 the uses. Returns NULL if there is nothing special about this call. */
471 static varinfo_t
472 lookup_call_use_vi (gcall *call)
474 varinfo_t *slot_p = call_stmt_vars->get (call);
475 if (slot_p)
476 return *slot_p;
478 return NULL;
481 /* Lookup the variable for the call statement CALL representing
482 the clobbers. Returns NULL if there is nothing special about this call. */
484 static varinfo_t
485 lookup_call_clobber_vi (gcall *call)
487 varinfo_t uses = lookup_call_use_vi (call);
488 if (!uses)
489 return NULL;
491 return vi_next (uses);
494 /* Lookup or create the variable for the call statement CALL representing
495 the uses. */
497 static varinfo_t
498 get_call_use_vi (gcall *call)
500 return get_call_vi (call);
503 /* Lookup or create the variable for the call statement CALL representing
504 the clobbers. */
506 static varinfo_t ATTRIBUTE_UNUSED
507 get_call_clobber_vi (gcall *call)
509 return vi_next (get_call_vi (call));
513 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
515 /* An expression that appears in a constraint. */
517 struct constraint_expr
519 /* Constraint type. */
520 constraint_expr_type type;
522 /* Variable we are referring to in the constraint. */
523 unsigned int var;
525 /* Offset, in bits, of this constraint from the beginning of
526 variables it ends up referring to.
528 IOW, in a deref constraint, we would deref, get the result set,
529 then add OFFSET to each member. */
530 HOST_WIDE_INT offset;
533 /* Use 0x8000... as special unknown offset. */
534 #define UNKNOWN_OFFSET HOST_WIDE_INT_MIN
536 typedef struct constraint_expr ce_s;
537 static void get_constraint_for_1 (tree, vec<ce_s> *, bool, bool);
538 static void get_constraint_for (tree, vec<ce_s> *);
539 static void get_constraint_for_rhs (tree, vec<ce_s> *);
540 static void do_deref (vec<ce_s> *);
542 /* Our set constraints are made up of two constraint expressions, one
543 LHS, and one RHS.
545 As described in the introduction, our set constraints each represent an
546 operation between set valued variables.
548 struct constraint
550 struct constraint_expr lhs;
551 struct constraint_expr rhs;
554 /* List of constraints that we use to build the constraint graph from. */
556 static vec<constraint_t> constraints;
557 static alloc_pool constraint_pool;
559 /* The constraint graph is represented as an array of bitmaps
560 containing successor nodes. */
562 struct constraint_graph
564 /* Size of this graph, which may be different than the number of
565 nodes in the variable map. */
566 unsigned int size;
568 /* Explicit successors of each node. */
569 bitmap *succs;
571 /* Implicit predecessors of each node (Used for variable
572 substitution). */
573 bitmap *implicit_preds;
575 /* Explicit predecessors of each node (Used for variable substitution). */
576 bitmap *preds;
578 /* Indirect cycle representatives, or -1 if the node has no indirect
579 cycles. */
580 int *indirect_cycles;
582 /* Representative node for a node. rep[a] == a unless the node has
583 been unified. */
584 unsigned int *rep;
586 /* Equivalence class representative for a label. This is used for
587 variable substitution. */
588 int *eq_rep;
590 /* Pointer equivalence label for a node. All nodes with the same
591 pointer equivalence label can be unified together at some point
592 (either during constraint optimization or after the constraint
593 graph is built). */
594 unsigned int *pe;
596 /* Pointer equivalence representative for a label. This is used to
597 handle nodes that are pointer equivalent but not location
598 equivalent. We can unite these once the addressof constraints
599 are transformed into initial points-to sets. */
600 int *pe_rep;
602 /* Pointer equivalence label for each node, used during variable
603 substitution. */
604 unsigned int *pointer_label;
606 /* Location equivalence label for each node, used during location
607 equivalence finding. */
608 unsigned int *loc_label;
610 /* Pointed-by set for each node, used during location equivalence
611 finding. This is pointed-by rather than pointed-to, because it
612 is constructed using the predecessor graph. */
613 bitmap *pointed_by;
615 /* Points to sets for pointer equivalence. This is *not* the actual
616 points-to sets for nodes. */
617 bitmap *points_to;
619 /* Bitmap of nodes where the bit is set if the node is a direct
620 node. Used for variable substitution. */
621 sbitmap direct_nodes;
623 /* Bitmap of nodes where the bit is set if the node is address
624 taken. Used for variable substitution. */
625 bitmap address_taken;
627 /* Vector of complex constraints for each graph node. Complex
628 constraints are those involving dereferences or offsets that are
629 not 0. */
630 vec<constraint_t> *complex;
633 static constraint_graph_t graph;
635 /* During variable substitution and the offline version of indirect
636 cycle finding, we create nodes to represent dereferences and
637 address taken constraints. These represent where these start and
638 end. */
639 #define FIRST_REF_NODE (varmap).length ()
640 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
642 /* Return the representative node for NODE, if NODE has been unioned
643 with another NODE.
644 This function performs path compression along the way to finding
645 the representative. */
647 static unsigned int
648 find (unsigned int node)
650 gcc_checking_assert (node < graph->size);
651 if (graph->rep[node] != node)
652 return graph->rep[node] = find (graph->rep[node]);
653 return node;
656 /* Union the TO and FROM nodes to the TO nodes.
657 Note that at some point in the future, we may want to do
658 union-by-rank, in which case we are going to have to return the
659 node we unified to. */
661 static bool
662 unite (unsigned int to, unsigned int from)
664 gcc_checking_assert (to < graph->size && from < graph->size);
665 if (to != from && graph->rep[from] != to)
667 graph->rep[from] = to;
668 return true;
670 return false;
673 /* Create a new constraint consisting of LHS and RHS expressions. */
675 static constraint_t
676 new_constraint (const struct constraint_expr lhs,
677 const struct constraint_expr rhs)
679 constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
680 ret->lhs = lhs;
681 ret->rhs = rhs;
682 return ret;
685 /* Print out constraint C to FILE. */
687 static void
688 dump_constraint (FILE *file, constraint_t c)
690 if (c->lhs.type == ADDRESSOF)
691 fprintf (file, "&");
692 else if (c->lhs.type == DEREF)
693 fprintf (file, "*");
694 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
695 if (c->lhs.offset == UNKNOWN_OFFSET)
696 fprintf (file, " + UNKNOWN");
697 else if (c->lhs.offset != 0)
698 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
699 fprintf (file, " = ");
700 if (c->rhs.type == ADDRESSOF)
701 fprintf (file, "&");
702 else if (c->rhs.type == DEREF)
703 fprintf (file, "*");
704 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
705 if (c->rhs.offset == UNKNOWN_OFFSET)
706 fprintf (file, " + UNKNOWN");
707 else if (c->rhs.offset != 0)
708 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
712 void debug_constraint (constraint_t);
713 void debug_constraints (void);
714 void debug_constraint_graph (void);
715 void debug_solution_for_var (unsigned int);
716 void debug_sa_points_to_info (void);
718 /* Print out constraint C to stderr. */
720 DEBUG_FUNCTION void
721 debug_constraint (constraint_t c)
723 dump_constraint (stderr, c);
724 fprintf (stderr, "\n");
727 /* Print out all constraints to FILE */
729 static void
730 dump_constraints (FILE *file, int from)
732 int i;
733 constraint_t c;
734 for (i = from; constraints.iterate (i, &c); i++)
735 if (c)
737 dump_constraint (file, c);
738 fprintf (file, "\n");
742 /* Print out all constraints to stderr. */
744 DEBUG_FUNCTION void
745 debug_constraints (void)
747 dump_constraints (stderr, 0);
750 /* Print the constraint graph in dot format. */
752 static void
753 dump_constraint_graph (FILE *file)
755 unsigned int i;
757 /* Only print the graph if it has already been initialized: */
758 if (!graph)
759 return;
761 /* Prints the header of the dot file: */
762 fprintf (file, "strict digraph {\n");
763 fprintf (file, " node [\n shape = box\n ]\n");
764 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
765 fprintf (file, "\n // List of nodes and complex constraints in "
766 "the constraint graph:\n");
768 /* The next lines print the nodes in the graph together with the
769 complex constraints attached to them. */
770 for (i = 1; i < graph->size; i++)
772 if (i == FIRST_REF_NODE)
773 continue;
774 if (find (i) != i)
775 continue;
776 if (i < FIRST_REF_NODE)
777 fprintf (file, "\"%s\"", get_varinfo (i)->name);
778 else
779 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
780 if (graph->complex[i].exists ())
782 unsigned j;
783 constraint_t c;
784 fprintf (file, " [label=\"\\N\\n");
785 for (j = 0; graph->complex[i].iterate (j, &c); ++j)
787 dump_constraint (file, c);
788 fprintf (file, "\\l");
790 fprintf (file, "\"]");
792 fprintf (file, ";\n");
795 /* Go over the edges. */
796 fprintf (file, "\n // Edges in the constraint graph:\n");
797 for (i = 1; i < graph->size; i++)
799 unsigned j;
800 bitmap_iterator bi;
801 if (find (i) != i)
802 continue;
803 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
805 unsigned to = find (j);
806 if (i == to)
807 continue;
808 if (i < FIRST_REF_NODE)
809 fprintf (file, "\"%s\"", get_varinfo (i)->name);
810 else
811 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
812 fprintf (file, " -> ");
813 if (to < FIRST_REF_NODE)
814 fprintf (file, "\"%s\"", get_varinfo (to)->name);
815 else
816 fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
817 fprintf (file, ";\n");
821 /* Prints the tail of the dot file. */
822 fprintf (file, "}\n");
825 /* Print out the constraint graph to stderr. */
827 DEBUG_FUNCTION void
828 debug_constraint_graph (void)
830 dump_constraint_graph (stderr);
833 /* SOLVER FUNCTIONS
835 The solver is a simple worklist solver, that works on the following
836 algorithm:
838 sbitmap changed_nodes = all zeroes;
839 changed_count = 0;
840 For each node that is not already collapsed:
841 changed_count++;
842 set bit in changed nodes
844 while (changed_count > 0)
846 compute topological ordering for constraint graph
848 find and collapse cycles in the constraint graph (updating
849 changed if necessary)
851 for each node (n) in the graph in topological order:
852 changed_count--;
854 Process each complex constraint associated with the node,
855 updating changed if necessary.
857 For each outgoing edge from n, propagate the solution from n to
858 the destination of the edge, updating changed as necessary.
860 } */
862 /* Return true if two constraint expressions A and B are equal. */
864 static bool
865 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
867 return a.type == b.type && a.var == b.var && a.offset == b.offset;
870 /* Return true if constraint expression A is less than constraint expression
871 B. This is just arbitrary, but consistent, in order to give them an
872 ordering. */
874 static bool
875 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
877 if (a.type == b.type)
879 if (a.var == b.var)
880 return a.offset < b.offset;
881 else
882 return a.var < b.var;
884 else
885 return a.type < b.type;
888 /* Return true if constraint A is less than constraint B. This is just
889 arbitrary, but consistent, in order to give them an ordering. */
891 static bool
892 constraint_less (const constraint_t &a, const constraint_t &b)
894 if (constraint_expr_less (a->lhs, b->lhs))
895 return true;
896 else if (constraint_expr_less (b->lhs, a->lhs))
897 return false;
898 else
899 return constraint_expr_less (a->rhs, b->rhs);
902 /* Return true if two constraints A and B are equal. */
904 static bool
905 constraint_equal (struct constraint a, struct constraint b)
907 return constraint_expr_equal (a.lhs, b.lhs)
908 && constraint_expr_equal (a.rhs, b.rhs);
912 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
914 static constraint_t
915 constraint_vec_find (vec<constraint_t> vec,
916 struct constraint lookfor)
918 unsigned int place;
919 constraint_t found;
921 if (!vec.exists ())
922 return NULL;
924 place = vec.lower_bound (&lookfor, constraint_less);
925 if (place >= vec.length ())
926 return NULL;
927 found = vec[place];
928 if (!constraint_equal (*found, lookfor))
929 return NULL;
930 return found;
933 /* Union two constraint vectors, TO and FROM. Put the result in TO.
934 Returns true of TO set is changed. */
936 static bool
937 constraint_set_union (vec<constraint_t> *to,
938 vec<constraint_t> *from)
940 int i;
941 constraint_t c;
942 bool any_change = false;
944 FOR_EACH_VEC_ELT (*from, i, c)
946 if (constraint_vec_find (*to, *c) == NULL)
948 unsigned int place = to->lower_bound (c, constraint_less);
949 to->safe_insert (place, c);
950 any_change = true;
953 return any_change;
956 /* Expands the solution in SET to all sub-fields of variables included. */
958 static bitmap
959 solution_set_expand (bitmap set, bitmap *expanded)
961 bitmap_iterator bi;
962 unsigned j;
964 if (*expanded)
965 return *expanded;
967 *expanded = BITMAP_ALLOC (&iteration_obstack);
969 /* In a first pass expand to the head of the variables we need to
970 add all sub-fields off. This avoids quadratic behavior. */
971 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
973 varinfo_t v = get_varinfo (j);
974 if (v->is_artificial_var
975 || v->is_full_var)
976 continue;
977 bitmap_set_bit (*expanded, v->head);
980 /* In the second pass now expand all head variables with subfields. */
981 EXECUTE_IF_SET_IN_BITMAP (*expanded, 0, j, bi)
983 varinfo_t v = get_varinfo (j);
984 if (v->head != j)
985 continue;
986 for (v = vi_next (v); v != NULL; v = vi_next (v))
987 bitmap_set_bit (*expanded, v->id);
990 /* And finally set the rest of the bits from SET. */
991 bitmap_ior_into (*expanded, set);
993 return *expanded;
996 /* Union solution sets TO and DELTA, and add INC to each member of DELTA in the
997 process. */
999 static bool
1000 set_union_with_increment (bitmap to, bitmap delta, HOST_WIDE_INT inc,
1001 bitmap *expanded_delta)
1003 bool changed = false;
1004 bitmap_iterator bi;
1005 unsigned int i;
1007 /* If the solution of DELTA contains anything it is good enough to transfer
1008 this to TO. */
1009 if (bitmap_bit_p (delta, anything_id))
1010 return bitmap_set_bit (to, anything_id);
1012 /* If the offset is unknown we have to expand the solution to
1013 all subfields. */
1014 if (inc == UNKNOWN_OFFSET)
1016 delta = solution_set_expand (delta, expanded_delta);
1017 changed |= bitmap_ior_into (to, delta);
1018 return changed;
1021 /* For non-zero offset union the offsetted solution into the destination. */
1022 EXECUTE_IF_SET_IN_BITMAP (delta, 0, i, bi)
1024 varinfo_t vi = get_varinfo (i);
1026 /* If this is a variable with just one field just set its bit
1027 in the result. */
1028 if (vi->is_artificial_var
1029 || vi->is_unknown_size_var
1030 || vi->is_full_var)
1031 changed |= bitmap_set_bit (to, i);
1032 else
1034 HOST_WIDE_INT fieldoffset = vi->offset + inc;
1035 unsigned HOST_WIDE_INT size = vi->size;
1037 /* If the offset makes the pointer point to before the
1038 variable use offset zero for the field lookup. */
1039 if (fieldoffset < 0)
1040 vi = get_varinfo (vi->head);
1041 else
1042 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1046 changed |= bitmap_set_bit (to, vi->id);
1047 if (vi->is_full_var
1048 || vi->next == 0)
1049 break;
1051 /* We have to include all fields that overlap the current field
1052 shifted by inc. */
1053 vi = vi_next (vi);
1055 while (vi->offset < fieldoffset + size);
1059 return changed;
1062 /* Insert constraint C into the list of complex constraints for graph
1063 node VAR. */
1065 static void
1066 insert_into_complex (constraint_graph_t graph,
1067 unsigned int var, constraint_t c)
1069 vec<constraint_t> complex = graph->complex[var];
1070 unsigned int place = complex.lower_bound (c, constraint_less);
1072 /* Only insert constraints that do not already exist. */
1073 if (place >= complex.length ()
1074 || !constraint_equal (*c, *complex[place]))
1075 graph->complex[var].safe_insert (place, c);
1079 /* Condense two variable nodes into a single variable node, by moving
1080 all associated info from FROM to TO. Returns true if TO node's
1081 constraint set changes after the merge. */
1083 static bool
1084 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1085 unsigned int from)
1087 unsigned int i;
1088 constraint_t c;
1089 bool any_change = false;
1091 gcc_checking_assert (find (from) == to);
1093 /* Move all complex constraints from src node into to node */
1094 FOR_EACH_VEC_ELT (graph->complex[from], i, c)
1096 /* In complex constraints for node FROM, we may have either
1097 a = *FROM, and *FROM = a, or an offseted constraint which are
1098 always added to the rhs node's constraints. */
1100 if (c->rhs.type == DEREF)
1101 c->rhs.var = to;
1102 else if (c->lhs.type == DEREF)
1103 c->lhs.var = to;
1104 else
1105 c->rhs.var = to;
1108 any_change = constraint_set_union (&graph->complex[to],
1109 &graph->complex[from]);
1110 graph->complex[from].release ();
1111 return any_change;
1115 /* Remove edges involving NODE from GRAPH. */
1117 static void
1118 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1120 if (graph->succs[node])
1121 BITMAP_FREE (graph->succs[node]);
1124 /* Merge GRAPH nodes FROM and TO into node TO. */
1126 static void
1127 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1128 unsigned int from)
1130 if (graph->indirect_cycles[from] != -1)
1132 /* If we have indirect cycles with the from node, and we have
1133 none on the to node, the to node has indirect cycles from the
1134 from node now that they are unified.
1135 If indirect cycles exist on both, unify the nodes that they
1136 are in a cycle with, since we know they are in a cycle with
1137 each other. */
1138 if (graph->indirect_cycles[to] == -1)
1139 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1142 /* Merge all the successor edges. */
1143 if (graph->succs[from])
1145 if (!graph->succs[to])
1146 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1147 bitmap_ior_into (graph->succs[to],
1148 graph->succs[from]);
1151 clear_edges_for_node (graph, from);
1155 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1156 it doesn't exist in the graph already. */
1158 static void
1159 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1160 unsigned int from)
1162 if (to == from)
1163 return;
1165 if (!graph->implicit_preds[to])
1166 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1168 if (bitmap_set_bit (graph->implicit_preds[to], from))
1169 stats.num_implicit_edges++;
1172 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1173 it doesn't exist in the graph already.
1174 Return false if the edge already existed, true otherwise. */
1176 static void
1177 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1178 unsigned int from)
1180 if (!graph->preds[to])
1181 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1182 bitmap_set_bit (graph->preds[to], from);
1185 /* Add a graph edge to GRAPH, going from FROM to TO if
1186 it doesn't exist in the graph already.
1187 Return false if the edge already existed, true otherwise. */
1189 static bool
1190 add_graph_edge (constraint_graph_t graph, unsigned int to,
1191 unsigned int from)
1193 if (to == from)
1195 return false;
1197 else
1199 bool r = false;
1201 if (!graph->succs[from])
1202 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1203 if (bitmap_set_bit (graph->succs[from], to))
1205 r = true;
1206 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1207 stats.num_edges++;
1209 return r;
1214 /* Initialize the constraint graph structure to contain SIZE nodes. */
1216 static void
1217 init_graph (unsigned int size)
1219 unsigned int j;
1221 graph = XCNEW (struct constraint_graph);
1222 graph->size = size;
1223 graph->succs = XCNEWVEC (bitmap, graph->size);
1224 graph->indirect_cycles = XNEWVEC (int, graph->size);
1225 graph->rep = XNEWVEC (unsigned int, graph->size);
1226 /* ??? Macros do not support template types with multiple arguments,
1227 so we use a typedef to work around it. */
1228 typedef vec<constraint_t> vec_constraint_t_heap;
1229 graph->complex = XCNEWVEC (vec_constraint_t_heap, size);
1230 graph->pe = XCNEWVEC (unsigned int, graph->size);
1231 graph->pe_rep = XNEWVEC (int, graph->size);
1233 for (j = 0; j < graph->size; j++)
1235 graph->rep[j] = j;
1236 graph->pe_rep[j] = -1;
1237 graph->indirect_cycles[j] = -1;
1241 /* Build the constraint graph, adding only predecessor edges right now. */
1243 static void
1244 build_pred_graph (void)
1246 int i;
1247 constraint_t c;
1248 unsigned int j;
1250 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1251 graph->preds = XCNEWVEC (bitmap, graph->size);
1252 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1253 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1254 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1255 graph->points_to = XCNEWVEC (bitmap, graph->size);
1256 graph->eq_rep = XNEWVEC (int, graph->size);
1257 graph->direct_nodes = sbitmap_alloc (graph->size);
1258 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1259 bitmap_clear (graph->direct_nodes);
1261 for (j = 1; j < FIRST_REF_NODE; j++)
1263 if (!get_varinfo (j)->is_special_var)
1264 bitmap_set_bit (graph->direct_nodes, j);
1267 for (j = 0; j < graph->size; j++)
1268 graph->eq_rep[j] = -1;
1270 for (j = 0; j < varmap.length (); j++)
1271 graph->indirect_cycles[j] = -1;
1273 FOR_EACH_VEC_ELT (constraints, i, c)
1275 struct constraint_expr lhs = c->lhs;
1276 struct constraint_expr rhs = c->rhs;
1277 unsigned int lhsvar = lhs.var;
1278 unsigned int rhsvar = rhs.var;
1280 if (lhs.type == DEREF)
1282 /* *x = y. */
1283 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1284 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1286 else if (rhs.type == DEREF)
1288 /* x = *y */
1289 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1290 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1291 else
1292 bitmap_clear_bit (graph->direct_nodes, lhsvar);
1294 else if (rhs.type == ADDRESSOF)
1296 varinfo_t v;
1298 /* x = &y */
1299 if (graph->points_to[lhsvar] == NULL)
1300 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1301 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1303 if (graph->pointed_by[rhsvar] == NULL)
1304 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1305 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1307 /* Implicitly, *x = y */
1308 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1310 /* All related variables are no longer direct nodes. */
1311 bitmap_clear_bit (graph->direct_nodes, rhsvar);
1312 v = get_varinfo (rhsvar);
1313 if (!v->is_full_var)
1315 v = get_varinfo (v->head);
1318 bitmap_clear_bit (graph->direct_nodes, v->id);
1319 v = vi_next (v);
1321 while (v != NULL);
1323 bitmap_set_bit (graph->address_taken, rhsvar);
1325 else if (lhsvar > anything_id
1326 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1328 /* x = y */
1329 add_pred_graph_edge (graph, lhsvar, rhsvar);
1330 /* Implicitly, *x = *y */
1331 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1332 FIRST_REF_NODE + rhsvar);
1334 else if (lhs.offset != 0 || rhs.offset != 0)
1336 if (rhs.offset != 0)
1337 bitmap_clear_bit (graph->direct_nodes, lhs.var);
1338 else if (lhs.offset != 0)
1339 bitmap_clear_bit (graph->direct_nodes, rhs.var);
1344 /* Build the constraint graph, adding successor edges. */
1346 static void
1347 build_succ_graph (void)
1349 unsigned i, t;
1350 constraint_t c;
1352 FOR_EACH_VEC_ELT (constraints, i, c)
1354 struct constraint_expr lhs;
1355 struct constraint_expr rhs;
1356 unsigned int lhsvar;
1357 unsigned int rhsvar;
1359 if (!c)
1360 continue;
1362 lhs = c->lhs;
1363 rhs = c->rhs;
1364 lhsvar = find (lhs.var);
1365 rhsvar = find (rhs.var);
1367 if (lhs.type == DEREF)
1369 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1370 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1372 else if (rhs.type == DEREF)
1374 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1375 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1377 else if (rhs.type == ADDRESSOF)
1379 /* x = &y */
1380 gcc_checking_assert (find (rhs.var) == rhs.var);
1381 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1383 else if (lhsvar > anything_id
1384 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1386 add_graph_edge (graph, lhsvar, rhsvar);
1390 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1391 receive pointers. */
1392 t = find (storedanything_id);
1393 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1395 if (!bitmap_bit_p (graph->direct_nodes, i)
1396 && get_varinfo (i)->may_have_pointers)
1397 add_graph_edge (graph, find (i), t);
1400 /* Everything stored to ANYTHING also potentially escapes. */
1401 add_graph_edge (graph, find (escaped_id), t);
1405 /* Changed variables on the last iteration. */
1406 static bitmap changed;
1408 /* Strongly Connected Component visitation info. */
1410 struct scc_info
1412 sbitmap visited;
1413 sbitmap deleted;
1414 unsigned int *dfs;
1415 unsigned int *node_mapping;
1416 int current_index;
1417 vec<unsigned> scc_stack;
1421 /* Recursive routine to find strongly connected components in GRAPH.
1422 SI is the SCC info to store the information in, and N is the id of current
1423 graph node we are processing.
1425 This is Tarjan's strongly connected component finding algorithm, as
1426 modified by Nuutila to keep only non-root nodes on the stack.
1427 The algorithm can be found in "On finding the strongly connected
1428 connected components in a directed graph" by Esko Nuutila and Eljas
1429 Soisalon-Soininen, in Information Processing Letters volume 49,
1430 number 1, pages 9-14. */
1432 static void
1433 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1435 unsigned int i;
1436 bitmap_iterator bi;
1437 unsigned int my_dfs;
1439 bitmap_set_bit (si->visited, n);
1440 si->dfs[n] = si->current_index ++;
1441 my_dfs = si->dfs[n];
1443 /* Visit all the successors. */
1444 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1446 unsigned int w;
1448 if (i > LAST_REF_NODE)
1449 break;
1451 w = find (i);
1452 if (bitmap_bit_p (si->deleted, w))
1453 continue;
1455 if (!bitmap_bit_p (si->visited, w))
1456 scc_visit (graph, si, w);
1458 unsigned int t = find (w);
1459 gcc_checking_assert (find (n) == n);
1460 if (si->dfs[t] < si->dfs[n])
1461 si->dfs[n] = si->dfs[t];
1464 /* See if any components have been identified. */
1465 if (si->dfs[n] == my_dfs)
1467 if (si->scc_stack.length () > 0
1468 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1470 bitmap scc = BITMAP_ALLOC (NULL);
1471 unsigned int lowest_node;
1472 bitmap_iterator bi;
1474 bitmap_set_bit (scc, n);
1476 while (si->scc_stack.length () != 0
1477 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1479 unsigned int w = si->scc_stack.pop ();
1481 bitmap_set_bit (scc, w);
1484 lowest_node = bitmap_first_set_bit (scc);
1485 gcc_assert (lowest_node < FIRST_REF_NODE);
1487 /* Collapse the SCC nodes into a single node, and mark the
1488 indirect cycles. */
1489 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1491 if (i < FIRST_REF_NODE)
1493 if (unite (lowest_node, i))
1494 unify_nodes (graph, lowest_node, i, false);
1496 else
1498 unite (lowest_node, i);
1499 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1503 bitmap_set_bit (si->deleted, n);
1505 else
1506 si->scc_stack.safe_push (n);
1509 /* Unify node FROM into node TO, updating the changed count if
1510 necessary when UPDATE_CHANGED is true. */
1512 static void
1513 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1514 bool update_changed)
1516 gcc_checking_assert (to != from && find (to) == to);
1518 if (dump_file && (dump_flags & TDF_DETAILS))
1519 fprintf (dump_file, "Unifying %s to %s\n",
1520 get_varinfo (from)->name,
1521 get_varinfo (to)->name);
1523 if (update_changed)
1524 stats.unified_vars_dynamic++;
1525 else
1526 stats.unified_vars_static++;
1528 merge_graph_nodes (graph, to, from);
1529 if (merge_node_constraints (graph, to, from))
1531 if (update_changed)
1532 bitmap_set_bit (changed, to);
1535 /* Mark TO as changed if FROM was changed. If TO was already marked
1536 as changed, decrease the changed count. */
1538 if (update_changed
1539 && bitmap_clear_bit (changed, from))
1540 bitmap_set_bit (changed, to);
1541 varinfo_t fromvi = get_varinfo (from);
1542 if (fromvi->solution)
1544 /* If the solution changes because of the merging, we need to mark
1545 the variable as changed. */
1546 varinfo_t tovi = get_varinfo (to);
1547 if (bitmap_ior_into (tovi->solution, fromvi->solution))
1549 if (update_changed)
1550 bitmap_set_bit (changed, to);
1553 BITMAP_FREE (fromvi->solution);
1554 if (fromvi->oldsolution)
1555 BITMAP_FREE (fromvi->oldsolution);
1557 if (stats.iterations > 0
1558 && tovi->oldsolution)
1559 BITMAP_FREE (tovi->oldsolution);
1561 if (graph->succs[to])
1562 bitmap_clear_bit (graph->succs[to], to);
1565 /* Information needed to compute the topological ordering of a graph. */
1567 struct topo_info
1569 /* sbitmap of visited nodes. */
1570 sbitmap visited;
1571 /* Array that stores the topological order of the graph, *in
1572 reverse*. */
1573 vec<unsigned> topo_order;
1577 /* Initialize and return a topological info structure. */
1579 static struct topo_info *
1580 init_topo_info (void)
1582 size_t size = graph->size;
1583 struct topo_info *ti = XNEW (struct topo_info);
1584 ti->visited = sbitmap_alloc (size);
1585 bitmap_clear (ti->visited);
1586 ti->topo_order.create (1);
1587 return ti;
1591 /* Free the topological sort info pointed to by TI. */
1593 static void
1594 free_topo_info (struct topo_info *ti)
1596 sbitmap_free (ti->visited);
1597 ti->topo_order.release ();
1598 free (ti);
1601 /* Visit the graph in topological order, and store the order in the
1602 topo_info structure. */
1604 static void
1605 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1606 unsigned int n)
1608 bitmap_iterator bi;
1609 unsigned int j;
1611 bitmap_set_bit (ti->visited, n);
1613 if (graph->succs[n])
1614 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1616 if (!bitmap_bit_p (ti->visited, j))
1617 topo_visit (graph, ti, j);
1620 ti->topo_order.safe_push (n);
1623 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1624 starting solution for y. */
1626 static void
1627 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1628 bitmap delta, bitmap *expanded_delta)
1630 unsigned int lhs = c->lhs.var;
1631 bool flag = false;
1632 bitmap sol = get_varinfo (lhs)->solution;
1633 unsigned int j;
1634 bitmap_iterator bi;
1635 HOST_WIDE_INT roffset = c->rhs.offset;
1637 /* Our IL does not allow this. */
1638 gcc_checking_assert (c->lhs.offset == 0);
1640 /* If the solution of Y contains anything it is good enough to transfer
1641 this to the LHS. */
1642 if (bitmap_bit_p (delta, anything_id))
1644 flag |= bitmap_set_bit (sol, anything_id);
1645 goto done;
1648 /* If we do not know at with offset the rhs is dereferenced compute
1649 the reachability set of DELTA, conservatively assuming it is
1650 dereferenced at all valid offsets. */
1651 if (roffset == UNKNOWN_OFFSET)
1653 delta = solution_set_expand (delta, expanded_delta);
1654 /* No further offset processing is necessary. */
1655 roffset = 0;
1658 /* For each variable j in delta (Sol(y)), add
1659 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1660 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1662 varinfo_t v = get_varinfo (j);
1663 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1664 unsigned HOST_WIDE_INT size = v->size;
1665 unsigned int t;
1667 if (v->is_full_var)
1669 else if (roffset != 0)
1671 if (fieldoffset < 0)
1672 v = get_varinfo (v->head);
1673 else
1674 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1677 /* We have to include all fields that overlap the current field
1678 shifted by roffset. */
1681 t = find (v->id);
1683 /* Adding edges from the special vars is pointless.
1684 They don't have sets that can change. */
1685 if (get_varinfo (t)->is_special_var)
1686 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1687 /* Merging the solution from ESCAPED needlessly increases
1688 the set. Use ESCAPED as representative instead. */
1689 else if (v->id == escaped_id)
1690 flag |= bitmap_set_bit (sol, escaped_id);
1691 else if (v->may_have_pointers
1692 && add_graph_edge (graph, lhs, t))
1693 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1695 if (v->is_full_var
1696 || v->next == 0)
1697 break;
1699 v = vi_next (v);
1701 while (v->offset < fieldoffset + size);
1704 done:
1705 /* If the LHS solution changed, mark the var as changed. */
1706 if (flag)
1708 get_varinfo (lhs)->solution = sol;
1709 bitmap_set_bit (changed, lhs);
1713 /* Process a constraint C that represents *(x + off) = y using DELTA
1714 as the starting solution for x. */
1716 static void
1717 do_ds_constraint (constraint_t c, bitmap delta, bitmap *expanded_delta)
1719 unsigned int rhs = c->rhs.var;
1720 bitmap sol = get_varinfo (rhs)->solution;
1721 unsigned int j;
1722 bitmap_iterator bi;
1723 HOST_WIDE_INT loff = c->lhs.offset;
1724 bool escaped_p = false;
1726 /* Our IL does not allow this. */
1727 gcc_checking_assert (c->rhs.offset == 0);
1729 /* If the solution of y contains ANYTHING simply use the ANYTHING
1730 solution. This avoids needlessly increasing the points-to sets. */
1731 if (bitmap_bit_p (sol, anything_id))
1732 sol = get_varinfo (find (anything_id))->solution;
1734 /* If the solution for x contains ANYTHING we have to merge the
1735 solution of y into all pointer variables which we do via
1736 STOREDANYTHING. */
1737 if (bitmap_bit_p (delta, anything_id))
1739 unsigned t = find (storedanything_id);
1740 if (add_graph_edge (graph, t, rhs))
1742 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1743 bitmap_set_bit (changed, t);
1745 return;
1748 /* If we do not know at with offset the rhs is dereferenced compute
1749 the reachability set of DELTA, conservatively assuming it is
1750 dereferenced at all valid offsets. */
1751 if (loff == UNKNOWN_OFFSET)
1753 delta = solution_set_expand (delta, expanded_delta);
1754 loff = 0;
1757 /* For each member j of delta (Sol(x)), add an edge from y to j and
1758 union Sol(y) into Sol(j) */
1759 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1761 varinfo_t v = get_varinfo (j);
1762 unsigned int t;
1763 HOST_WIDE_INT fieldoffset = v->offset + loff;
1764 unsigned HOST_WIDE_INT size = v->size;
1766 if (v->is_full_var)
1768 else if (loff != 0)
1770 if (fieldoffset < 0)
1771 v = get_varinfo (v->head);
1772 else
1773 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1776 /* We have to include all fields that overlap the current field
1777 shifted by loff. */
1780 if (v->may_have_pointers)
1782 /* If v is a global variable then this is an escape point. */
1783 if (v->is_global_var
1784 && !escaped_p)
1786 t = find (escaped_id);
1787 if (add_graph_edge (graph, t, rhs)
1788 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1789 bitmap_set_bit (changed, t);
1790 /* Enough to let rhs escape once. */
1791 escaped_p = true;
1794 if (v->is_special_var)
1795 break;
1797 t = find (v->id);
1798 if (add_graph_edge (graph, t, rhs)
1799 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1800 bitmap_set_bit (changed, t);
1803 if (v->is_full_var
1804 || v->next == 0)
1805 break;
1807 v = vi_next (v);
1809 while (v->offset < fieldoffset + size);
1813 /* Handle a non-simple (simple meaning requires no iteration),
1814 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1816 static void
1817 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta,
1818 bitmap *expanded_delta)
1820 if (c->lhs.type == DEREF)
1822 if (c->rhs.type == ADDRESSOF)
1824 gcc_unreachable ();
1826 else
1828 /* *x = y */
1829 do_ds_constraint (c, delta, expanded_delta);
1832 else if (c->rhs.type == DEREF)
1834 /* x = *y */
1835 if (!(get_varinfo (c->lhs.var)->is_special_var))
1836 do_sd_constraint (graph, c, delta, expanded_delta);
1838 else
1840 bitmap tmp;
1841 bool flag = false;
1843 gcc_checking_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR
1844 && c->rhs.offset != 0 && c->lhs.offset == 0);
1845 tmp = get_varinfo (c->lhs.var)->solution;
1847 flag = set_union_with_increment (tmp, delta, c->rhs.offset,
1848 expanded_delta);
1850 if (flag)
1851 bitmap_set_bit (changed, c->lhs.var);
1855 /* Initialize and return a new SCC info structure. */
1857 static struct scc_info *
1858 init_scc_info (size_t size)
1860 struct scc_info *si = XNEW (struct scc_info);
1861 size_t i;
1863 si->current_index = 0;
1864 si->visited = sbitmap_alloc (size);
1865 bitmap_clear (si->visited);
1866 si->deleted = sbitmap_alloc (size);
1867 bitmap_clear (si->deleted);
1868 si->node_mapping = XNEWVEC (unsigned int, size);
1869 si->dfs = XCNEWVEC (unsigned int, size);
1871 for (i = 0; i < size; i++)
1872 si->node_mapping[i] = i;
1874 si->scc_stack.create (1);
1875 return si;
1878 /* Free an SCC info structure pointed to by SI */
1880 static void
1881 free_scc_info (struct scc_info *si)
1883 sbitmap_free (si->visited);
1884 sbitmap_free (si->deleted);
1885 free (si->node_mapping);
1886 free (si->dfs);
1887 si->scc_stack.release ();
1888 free (si);
1892 /* Find indirect cycles in GRAPH that occur, using strongly connected
1893 components, and note them in the indirect cycles map.
1895 This technique comes from Ben Hardekopf and Calvin Lin,
1896 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1897 Lines of Code", submitted to PLDI 2007. */
1899 static void
1900 find_indirect_cycles (constraint_graph_t graph)
1902 unsigned int i;
1903 unsigned int size = graph->size;
1904 struct scc_info *si = init_scc_info (size);
1906 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1907 if (!bitmap_bit_p (si->visited, i) && find (i) == i)
1908 scc_visit (graph, si, i);
1910 free_scc_info (si);
1913 /* Compute a topological ordering for GRAPH, and store the result in the
1914 topo_info structure TI. */
1916 static void
1917 compute_topo_order (constraint_graph_t graph,
1918 struct topo_info *ti)
1920 unsigned int i;
1921 unsigned int size = graph->size;
1923 for (i = 0; i != size; ++i)
1924 if (!bitmap_bit_p (ti->visited, i) && find (i) == i)
1925 topo_visit (graph, ti, i);
1928 /* Structure used to for hash value numbering of pointer equivalence
1929 classes. */
1931 typedef struct equiv_class_label
1933 hashval_t hashcode;
1934 unsigned int equivalence_class;
1935 bitmap labels;
1936 } *equiv_class_label_t;
1937 typedef const struct equiv_class_label *const_equiv_class_label_t;
1939 /* Equiv_class_label hashtable helpers. */
1941 struct equiv_class_hasher : typed_free_remove <equiv_class_label>
1943 typedef equiv_class_label value_type;
1944 typedef equiv_class_label compare_type;
1945 static inline hashval_t hash (const value_type *);
1946 static inline bool equal (const value_type *, const compare_type *);
1949 /* Hash function for a equiv_class_label_t */
1951 inline hashval_t
1952 equiv_class_hasher::hash (const value_type *ecl)
1954 return ecl->hashcode;
1957 /* Equality function for two equiv_class_label_t's. */
1959 inline bool
1960 equiv_class_hasher::equal (const value_type *eql1, const compare_type *eql2)
1962 return (eql1->hashcode == eql2->hashcode
1963 && bitmap_equal_p (eql1->labels, eql2->labels));
1966 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1967 classes. */
1968 static hash_table<equiv_class_hasher> *pointer_equiv_class_table;
1970 /* A hashtable for mapping a bitmap of labels->location equivalence
1971 classes. */
1972 static hash_table<equiv_class_hasher> *location_equiv_class_table;
1974 /* Lookup a equivalence class in TABLE by the bitmap of LABELS with
1975 hash HAS it contains. Sets *REF_LABELS to the bitmap LABELS
1976 is equivalent to. */
1978 static equiv_class_label *
1979 equiv_class_lookup_or_add (hash_table<equiv_class_hasher> *table,
1980 bitmap labels)
1982 equiv_class_label **slot;
1983 equiv_class_label ecl;
1985 ecl.labels = labels;
1986 ecl.hashcode = bitmap_hash (labels);
1987 slot = table->find_slot (&ecl, INSERT);
1988 if (!*slot)
1990 *slot = XNEW (struct equiv_class_label);
1991 (*slot)->labels = labels;
1992 (*slot)->hashcode = ecl.hashcode;
1993 (*slot)->equivalence_class = 0;
1996 return *slot;
1999 /* Perform offline variable substitution.
2001 This is a worst case quadratic time way of identifying variables
2002 that must have equivalent points-to sets, including those caused by
2003 static cycles, and single entry subgraphs, in the constraint graph.
2005 The technique is described in "Exploiting Pointer and Location
2006 Equivalence to Optimize Pointer Analysis. In the 14th International
2007 Static Analysis Symposium (SAS), August 2007." It is known as the
2008 "HU" algorithm, and is equivalent to value numbering the collapsed
2009 constraint graph including evaluating unions.
2011 The general method of finding equivalence classes is as follows:
2012 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
2013 Initialize all non-REF nodes to be direct nodes.
2014 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
2015 variable}
2016 For each constraint containing the dereference, we also do the same
2017 thing.
2019 We then compute SCC's in the graph and unify nodes in the same SCC,
2020 including pts sets.
2022 For each non-collapsed node x:
2023 Visit all unvisited explicit incoming edges.
2024 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
2025 where y->x.
2026 Lookup the equivalence class for pts(x).
2027 If we found one, equivalence_class(x) = found class.
2028 Otherwise, equivalence_class(x) = new class, and new_class is
2029 added to the lookup table.
2031 All direct nodes with the same equivalence class can be replaced
2032 with a single representative node.
2033 All unlabeled nodes (label == 0) are not pointers and all edges
2034 involving them can be eliminated.
2035 We perform these optimizations during rewrite_constraints
2037 In addition to pointer equivalence class finding, we also perform
2038 location equivalence class finding. This is the set of variables
2039 that always appear together in points-to sets. We use this to
2040 compress the size of the points-to sets. */
2042 /* Current maximum pointer equivalence class id. */
2043 static int pointer_equiv_class;
2045 /* Current maximum location equivalence class id. */
2046 static int location_equiv_class;
2048 /* Recursive routine to find strongly connected components in GRAPH,
2049 and label it's nodes with DFS numbers. */
2051 static void
2052 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2054 unsigned int i;
2055 bitmap_iterator bi;
2056 unsigned int my_dfs;
2058 gcc_checking_assert (si->node_mapping[n] == n);
2059 bitmap_set_bit (si->visited, n);
2060 si->dfs[n] = si->current_index ++;
2061 my_dfs = si->dfs[n];
2063 /* Visit all the successors. */
2064 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2066 unsigned int w = si->node_mapping[i];
2068 if (bitmap_bit_p (si->deleted, w))
2069 continue;
2071 if (!bitmap_bit_p (si->visited, w))
2072 condense_visit (graph, si, w);
2074 unsigned int t = si->node_mapping[w];
2075 gcc_checking_assert (si->node_mapping[n] == n);
2076 if (si->dfs[t] < si->dfs[n])
2077 si->dfs[n] = si->dfs[t];
2080 /* Visit all the implicit predecessors. */
2081 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2083 unsigned int w = si->node_mapping[i];
2085 if (bitmap_bit_p (si->deleted, w))
2086 continue;
2088 if (!bitmap_bit_p (si->visited, w))
2089 condense_visit (graph, si, w);
2091 unsigned int t = si->node_mapping[w];
2092 gcc_assert (si->node_mapping[n] == n);
2093 if (si->dfs[t] < si->dfs[n])
2094 si->dfs[n] = si->dfs[t];
2097 /* See if any components have been identified. */
2098 if (si->dfs[n] == my_dfs)
2100 while (si->scc_stack.length () != 0
2101 && si->dfs[si->scc_stack.last ()] >= my_dfs)
2103 unsigned int w = si->scc_stack.pop ();
2104 si->node_mapping[w] = n;
2106 if (!bitmap_bit_p (graph->direct_nodes, w))
2107 bitmap_clear_bit (graph->direct_nodes, n);
2109 /* Unify our nodes. */
2110 if (graph->preds[w])
2112 if (!graph->preds[n])
2113 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2114 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2116 if (graph->implicit_preds[w])
2118 if (!graph->implicit_preds[n])
2119 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2120 bitmap_ior_into (graph->implicit_preds[n],
2121 graph->implicit_preds[w]);
2123 if (graph->points_to[w])
2125 if (!graph->points_to[n])
2126 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2127 bitmap_ior_into (graph->points_to[n],
2128 graph->points_to[w]);
2131 bitmap_set_bit (si->deleted, n);
2133 else
2134 si->scc_stack.safe_push (n);
2137 /* Label pointer equivalences.
2139 This performs a value numbering of the constraint graph to
2140 discover which variables will always have the same points-to sets
2141 under the current set of constraints.
2143 The way it value numbers is to store the set of points-to bits
2144 generated by the constraints and graph edges. This is just used as a
2145 hash and equality comparison. The *actual set of points-to bits* is
2146 completely irrelevant, in that we don't care about being able to
2147 extract them later.
2149 The equality values (currently bitmaps) just have to satisfy a few
2150 constraints, the main ones being:
2151 1. The combining operation must be order independent.
2152 2. The end result of a given set of operations must be unique iff the
2153 combination of input values is unique
2154 3. Hashable. */
2156 static void
2157 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2159 unsigned int i, first_pred;
2160 bitmap_iterator bi;
2162 bitmap_set_bit (si->visited, n);
2164 /* Label and union our incoming edges's points to sets. */
2165 first_pred = -1U;
2166 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2168 unsigned int w = si->node_mapping[i];
2169 if (!bitmap_bit_p (si->visited, w))
2170 label_visit (graph, si, w);
2172 /* Skip unused edges */
2173 if (w == n || graph->pointer_label[w] == 0)
2174 continue;
2176 if (graph->points_to[w])
2178 if (!graph->points_to[n])
2180 if (first_pred == -1U)
2181 first_pred = w;
2182 else
2184 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2185 bitmap_ior (graph->points_to[n],
2186 graph->points_to[first_pred],
2187 graph->points_to[w]);
2190 else
2191 bitmap_ior_into (graph->points_to[n], graph->points_to[w]);
2195 /* Indirect nodes get fresh variables and a new pointer equiv class. */
2196 if (!bitmap_bit_p (graph->direct_nodes, n))
2198 if (!graph->points_to[n])
2200 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2201 if (first_pred != -1U)
2202 bitmap_copy (graph->points_to[n], graph->points_to[first_pred]);
2204 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2205 graph->pointer_label[n] = pointer_equiv_class++;
2206 equiv_class_label_t ecl;
2207 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2208 graph->points_to[n]);
2209 ecl->equivalence_class = graph->pointer_label[n];
2210 return;
2213 /* If there was only a single non-empty predecessor the pointer equiv
2214 class is the same. */
2215 if (!graph->points_to[n])
2217 if (first_pred != -1U)
2219 graph->pointer_label[n] = graph->pointer_label[first_pred];
2220 graph->points_to[n] = graph->points_to[first_pred];
2222 return;
2225 if (!bitmap_empty_p (graph->points_to[n]))
2227 equiv_class_label_t ecl;
2228 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2229 graph->points_to[n]);
2230 if (ecl->equivalence_class == 0)
2231 ecl->equivalence_class = pointer_equiv_class++;
2232 else
2234 BITMAP_FREE (graph->points_to[n]);
2235 graph->points_to[n] = ecl->labels;
2237 graph->pointer_label[n] = ecl->equivalence_class;
2241 /* Print the pred graph in dot format. */
2243 static void
2244 dump_pred_graph (struct scc_info *si, FILE *file)
2246 unsigned int i;
2248 /* Only print the graph if it has already been initialized: */
2249 if (!graph)
2250 return;
2252 /* Prints the header of the dot file: */
2253 fprintf (file, "strict digraph {\n");
2254 fprintf (file, " node [\n shape = box\n ]\n");
2255 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
2256 fprintf (file, "\n // List of nodes and complex constraints in "
2257 "the constraint graph:\n");
2259 /* The next lines print the nodes in the graph together with the
2260 complex constraints attached to them. */
2261 for (i = 1; i < graph->size; i++)
2263 if (i == FIRST_REF_NODE)
2264 continue;
2265 if (si->node_mapping[i] != i)
2266 continue;
2267 if (i < FIRST_REF_NODE)
2268 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2269 else
2270 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2271 if (graph->points_to[i]
2272 && !bitmap_empty_p (graph->points_to[i]))
2274 fprintf (file, "[label=\"%s = {", get_varinfo (i)->name);
2275 unsigned j;
2276 bitmap_iterator bi;
2277 EXECUTE_IF_SET_IN_BITMAP (graph->points_to[i], 0, j, bi)
2278 fprintf (file, " %d", j);
2279 fprintf (file, " }\"]");
2281 fprintf (file, ";\n");
2284 /* Go over the edges. */
2285 fprintf (file, "\n // Edges in the constraint graph:\n");
2286 for (i = 1; i < graph->size; i++)
2288 unsigned j;
2289 bitmap_iterator bi;
2290 if (si->node_mapping[i] != i)
2291 continue;
2292 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[i], 0, j, bi)
2294 unsigned from = si->node_mapping[j];
2295 if (from < FIRST_REF_NODE)
2296 fprintf (file, "\"%s\"", get_varinfo (from)->name);
2297 else
2298 fprintf (file, "\"*%s\"", get_varinfo (from - FIRST_REF_NODE)->name);
2299 fprintf (file, " -> ");
2300 if (i < FIRST_REF_NODE)
2301 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2302 else
2303 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2304 fprintf (file, ";\n");
2308 /* Prints the tail of the dot file. */
2309 fprintf (file, "}\n");
2312 /* Perform offline variable substitution, discovering equivalence
2313 classes, and eliminating non-pointer variables. */
2315 static struct scc_info *
2316 perform_var_substitution (constraint_graph_t graph)
2318 unsigned int i;
2319 unsigned int size = graph->size;
2320 struct scc_info *si = init_scc_info (size);
2322 bitmap_obstack_initialize (&iteration_obstack);
2323 pointer_equiv_class_table = new hash_table<equiv_class_hasher> (511);
2324 location_equiv_class_table
2325 = new hash_table<equiv_class_hasher> (511);
2326 pointer_equiv_class = 1;
2327 location_equiv_class = 1;
2329 /* Condense the nodes, which means to find SCC's, count incoming
2330 predecessors, and unite nodes in SCC's. */
2331 for (i = 1; i < FIRST_REF_NODE; i++)
2332 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2333 condense_visit (graph, si, si->node_mapping[i]);
2335 if (dump_file && (dump_flags & TDF_GRAPH))
2337 fprintf (dump_file, "\n\n// The constraint graph before var-substitution "
2338 "in dot format:\n");
2339 dump_pred_graph (si, dump_file);
2340 fprintf (dump_file, "\n\n");
2343 bitmap_clear (si->visited);
2344 /* Actually the label the nodes for pointer equivalences */
2345 for (i = 1; i < FIRST_REF_NODE; i++)
2346 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2347 label_visit (graph, si, si->node_mapping[i]);
2349 /* Calculate location equivalence labels. */
2350 for (i = 1; i < FIRST_REF_NODE; i++)
2352 bitmap pointed_by;
2353 bitmap_iterator bi;
2354 unsigned int j;
2356 if (!graph->pointed_by[i])
2357 continue;
2358 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2360 /* Translate the pointed-by mapping for pointer equivalence
2361 labels. */
2362 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2364 bitmap_set_bit (pointed_by,
2365 graph->pointer_label[si->node_mapping[j]]);
2367 /* The original pointed_by is now dead. */
2368 BITMAP_FREE (graph->pointed_by[i]);
2370 /* Look up the location equivalence label if one exists, or make
2371 one otherwise. */
2372 equiv_class_label_t ecl;
2373 ecl = equiv_class_lookup_or_add (location_equiv_class_table, pointed_by);
2374 if (ecl->equivalence_class == 0)
2375 ecl->equivalence_class = location_equiv_class++;
2376 else
2378 if (dump_file && (dump_flags & TDF_DETAILS))
2379 fprintf (dump_file, "Found location equivalence for node %s\n",
2380 get_varinfo (i)->name);
2381 BITMAP_FREE (pointed_by);
2383 graph->loc_label[i] = ecl->equivalence_class;
2387 if (dump_file && (dump_flags & TDF_DETAILS))
2388 for (i = 1; i < FIRST_REF_NODE; i++)
2390 unsigned j = si->node_mapping[i];
2391 if (j != i)
2393 fprintf (dump_file, "%s node id %d ",
2394 bitmap_bit_p (graph->direct_nodes, i)
2395 ? "Direct" : "Indirect", i);
2396 if (i < FIRST_REF_NODE)
2397 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2398 else
2399 fprintf (dump_file, "\"*%s\"",
2400 get_varinfo (i - FIRST_REF_NODE)->name);
2401 fprintf (dump_file, " mapped to SCC leader node id %d ", j);
2402 if (j < FIRST_REF_NODE)
2403 fprintf (dump_file, "\"%s\"\n", get_varinfo (j)->name);
2404 else
2405 fprintf (dump_file, "\"*%s\"\n",
2406 get_varinfo (j - FIRST_REF_NODE)->name);
2408 else
2410 fprintf (dump_file,
2411 "Equivalence classes for %s node id %d ",
2412 bitmap_bit_p (graph->direct_nodes, i)
2413 ? "direct" : "indirect", i);
2414 if (i < FIRST_REF_NODE)
2415 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2416 else
2417 fprintf (dump_file, "\"*%s\"",
2418 get_varinfo (i - FIRST_REF_NODE)->name);
2419 fprintf (dump_file,
2420 ": pointer %d, location %d\n",
2421 graph->pointer_label[i], graph->loc_label[i]);
2425 /* Quickly eliminate our non-pointer variables. */
2427 for (i = 1; i < FIRST_REF_NODE; i++)
2429 unsigned int node = si->node_mapping[i];
2431 if (graph->pointer_label[node] == 0)
2433 if (dump_file && (dump_flags & TDF_DETAILS))
2434 fprintf (dump_file,
2435 "%s is a non-pointer variable, eliminating edges.\n",
2436 get_varinfo (node)->name);
2437 stats.nonpointer_vars++;
2438 clear_edges_for_node (graph, node);
2442 return si;
2445 /* Free information that was only necessary for variable
2446 substitution. */
2448 static void
2449 free_var_substitution_info (struct scc_info *si)
2451 free_scc_info (si);
2452 free (graph->pointer_label);
2453 free (graph->loc_label);
2454 free (graph->pointed_by);
2455 free (graph->points_to);
2456 free (graph->eq_rep);
2457 sbitmap_free (graph->direct_nodes);
2458 delete pointer_equiv_class_table;
2459 pointer_equiv_class_table = NULL;
2460 delete location_equiv_class_table;
2461 location_equiv_class_table = NULL;
2462 bitmap_obstack_release (&iteration_obstack);
2465 /* Return an existing node that is equivalent to NODE, which has
2466 equivalence class LABEL, if one exists. Return NODE otherwise. */
2468 static unsigned int
2469 find_equivalent_node (constraint_graph_t graph,
2470 unsigned int node, unsigned int label)
2472 /* If the address version of this variable is unused, we can
2473 substitute it for anything else with the same label.
2474 Otherwise, we know the pointers are equivalent, but not the
2475 locations, and we can unite them later. */
2477 if (!bitmap_bit_p (graph->address_taken, node))
2479 gcc_checking_assert (label < graph->size);
2481 if (graph->eq_rep[label] != -1)
2483 /* Unify the two variables since we know they are equivalent. */
2484 if (unite (graph->eq_rep[label], node))
2485 unify_nodes (graph, graph->eq_rep[label], node, false);
2486 return graph->eq_rep[label];
2488 else
2490 graph->eq_rep[label] = node;
2491 graph->pe_rep[label] = node;
2494 else
2496 gcc_checking_assert (label < graph->size);
2497 graph->pe[node] = label;
2498 if (graph->pe_rep[label] == -1)
2499 graph->pe_rep[label] = node;
2502 return node;
2505 /* Unite pointer equivalent but not location equivalent nodes in
2506 GRAPH. This may only be performed once variable substitution is
2507 finished. */
2509 static void
2510 unite_pointer_equivalences (constraint_graph_t graph)
2512 unsigned int i;
2514 /* Go through the pointer equivalences and unite them to their
2515 representative, if they aren't already. */
2516 for (i = 1; i < FIRST_REF_NODE; i++)
2518 unsigned int label = graph->pe[i];
2519 if (label)
2521 int label_rep = graph->pe_rep[label];
2523 if (label_rep == -1)
2524 continue;
2526 label_rep = find (label_rep);
2527 if (label_rep >= 0 && unite (label_rep, find (i)))
2528 unify_nodes (graph, label_rep, i, false);
2533 /* Move complex constraints to the GRAPH nodes they belong to. */
2535 static void
2536 move_complex_constraints (constraint_graph_t graph)
2538 int i;
2539 constraint_t c;
2541 FOR_EACH_VEC_ELT (constraints, i, c)
2543 if (c)
2545 struct constraint_expr lhs = c->lhs;
2546 struct constraint_expr rhs = c->rhs;
2548 if (lhs.type == DEREF)
2550 insert_into_complex (graph, lhs.var, c);
2552 else if (rhs.type == DEREF)
2554 if (!(get_varinfo (lhs.var)->is_special_var))
2555 insert_into_complex (graph, rhs.var, c);
2557 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2558 && (lhs.offset != 0 || rhs.offset != 0))
2560 insert_into_complex (graph, rhs.var, c);
2567 /* Optimize and rewrite complex constraints while performing
2568 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2569 result of perform_variable_substitution. */
2571 static void
2572 rewrite_constraints (constraint_graph_t graph,
2573 struct scc_info *si)
2575 int i;
2576 constraint_t c;
2578 #ifdef ENABLE_CHECKING
2579 for (unsigned int j = 0; j < graph->size; j++)
2580 gcc_assert (find (j) == j);
2581 #endif
2583 FOR_EACH_VEC_ELT (constraints, i, c)
2585 struct constraint_expr lhs = c->lhs;
2586 struct constraint_expr rhs = c->rhs;
2587 unsigned int lhsvar = find (lhs.var);
2588 unsigned int rhsvar = find (rhs.var);
2589 unsigned int lhsnode, rhsnode;
2590 unsigned int lhslabel, rhslabel;
2592 lhsnode = si->node_mapping[lhsvar];
2593 rhsnode = si->node_mapping[rhsvar];
2594 lhslabel = graph->pointer_label[lhsnode];
2595 rhslabel = graph->pointer_label[rhsnode];
2597 /* See if it is really a non-pointer variable, and if so, ignore
2598 the constraint. */
2599 if (lhslabel == 0)
2601 if (dump_file && (dump_flags & TDF_DETAILS))
2604 fprintf (dump_file, "%s is a non-pointer variable,"
2605 "ignoring constraint:",
2606 get_varinfo (lhs.var)->name);
2607 dump_constraint (dump_file, c);
2608 fprintf (dump_file, "\n");
2610 constraints[i] = NULL;
2611 continue;
2614 if (rhslabel == 0)
2616 if (dump_file && (dump_flags & TDF_DETAILS))
2619 fprintf (dump_file, "%s is a non-pointer variable,"
2620 "ignoring constraint:",
2621 get_varinfo (rhs.var)->name);
2622 dump_constraint (dump_file, c);
2623 fprintf (dump_file, "\n");
2625 constraints[i] = NULL;
2626 continue;
2629 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2630 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2631 c->lhs.var = lhsvar;
2632 c->rhs.var = rhsvar;
2636 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2637 part of an SCC, false otherwise. */
2639 static bool
2640 eliminate_indirect_cycles (unsigned int node)
2642 if (graph->indirect_cycles[node] != -1
2643 && !bitmap_empty_p (get_varinfo (node)->solution))
2645 unsigned int i;
2646 auto_vec<unsigned> queue;
2647 int queuepos;
2648 unsigned int to = find (graph->indirect_cycles[node]);
2649 bitmap_iterator bi;
2651 /* We can't touch the solution set and call unify_nodes
2652 at the same time, because unify_nodes is going to do
2653 bitmap unions into it. */
2655 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2657 if (find (i) == i && i != to)
2659 if (unite (to, i))
2660 queue.safe_push (i);
2664 for (queuepos = 0;
2665 queue.iterate (queuepos, &i);
2666 queuepos++)
2668 unify_nodes (graph, to, i, true);
2670 return true;
2672 return false;
2675 /* Solve the constraint graph GRAPH using our worklist solver.
2676 This is based on the PW* family of solvers from the "Efficient Field
2677 Sensitive Pointer Analysis for C" paper.
2678 It works by iterating over all the graph nodes, processing the complex
2679 constraints and propagating the copy constraints, until everything stops
2680 changed. This corresponds to steps 6-8 in the solving list given above. */
2682 static void
2683 solve_graph (constraint_graph_t graph)
2685 unsigned int size = graph->size;
2686 unsigned int i;
2687 bitmap pts;
2689 changed = BITMAP_ALLOC (NULL);
2691 /* Mark all initial non-collapsed nodes as changed. */
2692 for (i = 1; i < size; i++)
2694 varinfo_t ivi = get_varinfo (i);
2695 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2696 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2697 || graph->complex[i].length () > 0))
2698 bitmap_set_bit (changed, i);
2701 /* Allocate a bitmap to be used to store the changed bits. */
2702 pts = BITMAP_ALLOC (&pta_obstack);
2704 while (!bitmap_empty_p (changed))
2706 unsigned int i;
2707 struct topo_info *ti = init_topo_info ();
2708 stats.iterations++;
2710 bitmap_obstack_initialize (&iteration_obstack);
2712 compute_topo_order (graph, ti);
2714 while (ti->topo_order.length () != 0)
2717 i = ti->topo_order.pop ();
2719 /* If this variable is not a representative, skip it. */
2720 if (find (i) != i)
2721 continue;
2723 /* In certain indirect cycle cases, we may merge this
2724 variable to another. */
2725 if (eliminate_indirect_cycles (i) && find (i) != i)
2726 continue;
2728 /* If the node has changed, we need to process the
2729 complex constraints and outgoing edges again. */
2730 if (bitmap_clear_bit (changed, i))
2732 unsigned int j;
2733 constraint_t c;
2734 bitmap solution;
2735 vec<constraint_t> complex = graph->complex[i];
2736 varinfo_t vi = get_varinfo (i);
2737 bool solution_empty;
2739 /* Compute the changed set of solution bits. If anything
2740 is in the solution just propagate that. */
2741 if (bitmap_bit_p (vi->solution, anything_id))
2743 /* If anything is also in the old solution there is
2744 nothing to do.
2745 ??? But we shouldn't ended up with "changed" set ... */
2746 if (vi->oldsolution
2747 && bitmap_bit_p (vi->oldsolution, anything_id))
2748 continue;
2749 bitmap_copy (pts, get_varinfo (find (anything_id))->solution);
2751 else if (vi->oldsolution)
2752 bitmap_and_compl (pts, vi->solution, vi->oldsolution);
2753 else
2754 bitmap_copy (pts, vi->solution);
2756 if (bitmap_empty_p (pts))
2757 continue;
2759 if (vi->oldsolution)
2760 bitmap_ior_into (vi->oldsolution, pts);
2761 else
2763 vi->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
2764 bitmap_copy (vi->oldsolution, pts);
2767 solution = vi->solution;
2768 solution_empty = bitmap_empty_p (solution);
2770 /* Process the complex constraints */
2771 bitmap expanded_pts = NULL;
2772 FOR_EACH_VEC_ELT (complex, j, c)
2774 /* XXX: This is going to unsort the constraints in
2775 some cases, which will occasionally add duplicate
2776 constraints during unification. This does not
2777 affect correctness. */
2778 c->lhs.var = find (c->lhs.var);
2779 c->rhs.var = find (c->rhs.var);
2781 /* The only complex constraint that can change our
2782 solution to non-empty, given an empty solution,
2783 is a constraint where the lhs side is receiving
2784 some set from elsewhere. */
2785 if (!solution_empty || c->lhs.type != DEREF)
2786 do_complex_constraint (graph, c, pts, &expanded_pts);
2788 BITMAP_FREE (expanded_pts);
2790 solution_empty = bitmap_empty_p (solution);
2792 if (!solution_empty)
2794 bitmap_iterator bi;
2795 unsigned eff_escaped_id = find (escaped_id);
2797 /* Propagate solution to all successors. */
2798 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2799 0, j, bi)
2801 bitmap tmp;
2802 bool flag;
2804 unsigned int to = find (j);
2805 tmp = get_varinfo (to)->solution;
2806 flag = false;
2808 /* Don't try to propagate to ourselves. */
2809 if (to == i)
2810 continue;
2812 /* If we propagate from ESCAPED use ESCAPED as
2813 placeholder. */
2814 if (i == eff_escaped_id)
2815 flag = bitmap_set_bit (tmp, escaped_id);
2816 else
2817 flag = bitmap_ior_into (tmp, pts);
2819 if (flag)
2820 bitmap_set_bit (changed, to);
2825 free_topo_info (ti);
2826 bitmap_obstack_release (&iteration_obstack);
2829 BITMAP_FREE (pts);
2830 BITMAP_FREE (changed);
2831 bitmap_obstack_release (&oldpta_obstack);
2834 /* Map from trees to variable infos. */
2835 static hash_map<tree, varinfo_t> *vi_for_tree;
2838 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2840 static void
2841 insert_vi_for_tree (tree t, varinfo_t vi)
2843 gcc_assert (vi);
2844 gcc_assert (!vi_for_tree->put (t, vi));
2847 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2848 exist in the map, return NULL, otherwise, return the varinfo we found. */
2850 static varinfo_t
2851 lookup_vi_for_tree (tree t)
2853 varinfo_t *slot = vi_for_tree->get (t);
2854 if (slot == NULL)
2855 return NULL;
2857 return *slot;
2860 /* Return a printable name for DECL */
2862 static const char *
2863 alias_get_name (tree decl)
2865 const char *res = NULL;
2866 char *temp;
2867 int num_printed = 0;
2869 if (!dump_file)
2870 return "NULL";
2872 if (TREE_CODE (decl) == SSA_NAME)
2874 res = get_name (decl);
2875 if (res)
2876 num_printed = asprintf (&temp, "%s_%u", res, SSA_NAME_VERSION (decl));
2877 else
2878 num_printed = asprintf (&temp, "_%u", SSA_NAME_VERSION (decl));
2879 if (num_printed > 0)
2881 res = ggc_strdup (temp);
2882 free (temp);
2885 else if (DECL_P (decl))
2887 if (DECL_ASSEMBLER_NAME_SET_P (decl))
2888 res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2889 else
2891 res = get_name (decl);
2892 if (!res)
2894 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2895 if (num_printed > 0)
2897 res = ggc_strdup (temp);
2898 free (temp);
2903 if (res != NULL)
2904 return res;
2906 return "NULL";
2909 /* Find the variable id for tree T in the map.
2910 If T doesn't exist in the map, create an entry for it and return it. */
2912 static varinfo_t
2913 get_vi_for_tree (tree t)
2915 varinfo_t *slot = vi_for_tree->get (t);
2916 if (slot == NULL)
2917 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2919 return *slot;
2922 /* Get a scalar constraint expression for a new temporary variable. */
2924 static struct constraint_expr
2925 new_scalar_tmp_constraint_exp (const char *name)
2927 struct constraint_expr tmp;
2928 varinfo_t vi;
2930 vi = new_var_info (NULL_TREE, name);
2931 vi->offset = 0;
2932 vi->size = -1;
2933 vi->fullsize = -1;
2934 vi->is_full_var = 1;
2936 tmp.var = vi->id;
2937 tmp.type = SCALAR;
2938 tmp.offset = 0;
2940 return tmp;
2943 /* Get a constraint expression vector from an SSA_VAR_P node.
2944 If address_p is true, the result will be taken its address of. */
2946 static void
2947 get_constraint_for_ssa_var (tree t, vec<ce_s> *results, bool address_p)
2949 struct constraint_expr cexpr;
2950 varinfo_t vi;
2952 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2953 gcc_assert (TREE_CODE (t) == SSA_NAME || DECL_P (t));
2955 /* For parameters, get at the points-to set for the actual parm
2956 decl. */
2957 if (TREE_CODE (t) == SSA_NAME
2958 && SSA_NAME_IS_DEFAULT_DEF (t)
2959 && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2960 || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL))
2962 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2963 return;
2966 /* For global variables resort to the alias target. */
2967 if (TREE_CODE (t) == VAR_DECL
2968 && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2970 varpool_node *node = varpool_node::get (t);
2971 if (node && node->alias && node->analyzed)
2973 node = node->ultimate_alias_target ();
2974 t = node->decl;
2978 vi = get_vi_for_tree (t);
2979 cexpr.var = vi->id;
2980 cexpr.type = SCALAR;
2981 cexpr.offset = 0;
2983 /* If we are not taking the address of the constraint expr, add all
2984 sub-fiels of the variable as well. */
2985 if (!address_p
2986 && !vi->is_full_var)
2988 for (; vi; vi = vi_next (vi))
2990 cexpr.var = vi->id;
2991 results->safe_push (cexpr);
2993 return;
2996 results->safe_push (cexpr);
2999 /* Process constraint T, performing various simplifications and then
3000 adding it to our list of overall constraints. */
3002 static void
3003 process_constraint (constraint_t t)
3005 struct constraint_expr rhs = t->rhs;
3006 struct constraint_expr lhs = t->lhs;
3008 gcc_assert (rhs.var < varmap.length ());
3009 gcc_assert (lhs.var < varmap.length ());
3011 /* If we didn't get any useful constraint from the lhs we get
3012 &ANYTHING as fallback from get_constraint_for. Deal with
3013 it here by turning it into *ANYTHING. */
3014 if (lhs.type == ADDRESSOF
3015 && lhs.var == anything_id)
3016 lhs.type = DEREF;
3018 /* ADDRESSOF on the lhs is invalid. */
3019 gcc_assert (lhs.type != ADDRESSOF);
3021 /* We shouldn't add constraints from things that cannot have pointers.
3022 It's not completely trivial to avoid in the callers, so do it here. */
3023 if (rhs.type != ADDRESSOF
3024 && !get_varinfo (rhs.var)->may_have_pointers)
3025 return;
3027 /* Likewise adding to the solution of a non-pointer var isn't useful. */
3028 if (!get_varinfo (lhs.var)->may_have_pointers)
3029 return;
3031 /* This can happen in our IR with things like n->a = *p */
3032 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
3034 /* Split into tmp = *rhs, *lhs = tmp */
3035 struct constraint_expr tmplhs;
3036 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
3037 process_constraint (new_constraint (tmplhs, rhs));
3038 process_constraint (new_constraint (lhs, tmplhs));
3040 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
3042 /* Split into tmp = &rhs, *lhs = tmp */
3043 struct constraint_expr tmplhs;
3044 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
3045 process_constraint (new_constraint (tmplhs, rhs));
3046 process_constraint (new_constraint (lhs, tmplhs));
3048 else
3050 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
3051 constraints.safe_push (t);
3056 /* Return the position, in bits, of FIELD_DECL from the beginning of its
3057 structure. */
3059 static HOST_WIDE_INT
3060 bitpos_of_field (const tree fdecl)
3062 if (!tree_fits_shwi_p (DECL_FIELD_OFFSET (fdecl))
3063 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fdecl)))
3064 return -1;
3066 return (tree_to_shwi (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
3067 + tree_to_shwi (DECL_FIELD_BIT_OFFSET (fdecl)));
3071 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
3072 resulting constraint expressions in *RESULTS. */
3074 static void
3075 get_constraint_for_ptr_offset (tree ptr, tree offset,
3076 vec<ce_s> *results)
3078 struct constraint_expr c;
3079 unsigned int j, n;
3080 HOST_WIDE_INT rhsoffset;
3082 /* If we do not do field-sensitive PTA adding offsets to pointers
3083 does not change the points-to solution. */
3084 if (!use_field_sensitive)
3086 get_constraint_for_rhs (ptr, results);
3087 return;
3090 /* If the offset is not a non-negative integer constant that fits
3091 in a HOST_WIDE_INT, we have to fall back to a conservative
3092 solution which includes all sub-fields of all pointed-to
3093 variables of ptr. */
3094 if (offset == NULL_TREE
3095 || TREE_CODE (offset) != INTEGER_CST)
3096 rhsoffset = UNKNOWN_OFFSET;
3097 else
3099 /* Sign-extend the offset. */
3100 offset_int soffset = offset_int::from (offset, SIGNED);
3101 if (!wi::fits_shwi_p (soffset))
3102 rhsoffset = UNKNOWN_OFFSET;
3103 else
3105 /* Make sure the bit-offset also fits. */
3106 HOST_WIDE_INT rhsunitoffset = soffset.to_shwi ();
3107 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
3108 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
3109 rhsoffset = UNKNOWN_OFFSET;
3113 get_constraint_for_rhs (ptr, results);
3114 if (rhsoffset == 0)
3115 return;
3117 /* As we are eventually appending to the solution do not use
3118 vec::iterate here. */
3119 n = results->length ();
3120 for (j = 0; j < n; j++)
3122 varinfo_t curr;
3123 c = (*results)[j];
3124 curr = get_varinfo (c.var);
3126 if (c.type == ADDRESSOF
3127 /* If this varinfo represents a full variable just use it. */
3128 && curr->is_full_var)
3130 else if (c.type == ADDRESSOF
3131 /* If we do not know the offset add all subfields. */
3132 && rhsoffset == UNKNOWN_OFFSET)
3134 varinfo_t temp = get_varinfo (curr->head);
3137 struct constraint_expr c2;
3138 c2.var = temp->id;
3139 c2.type = ADDRESSOF;
3140 c2.offset = 0;
3141 if (c2.var != c.var)
3142 results->safe_push (c2);
3143 temp = vi_next (temp);
3145 while (temp);
3147 else if (c.type == ADDRESSOF)
3149 varinfo_t temp;
3150 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3152 /* If curr->offset + rhsoffset is less than zero adjust it. */
3153 if (rhsoffset < 0
3154 && curr->offset < offset)
3155 offset = 0;
3157 /* We have to include all fields that overlap the current
3158 field shifted by rhsoffset. And we include at least
3159 the last or the first field of the variable to represent
3160 reachability of off-bound addresses, in particular &object + 1,
3161 conservatively correct. */
3162 temp = first_or_preceding_vi_for_offset (curr, offset);
3163 c.var = temp->id;
3164 c.offset = 0;
3165 temp = vi_next (temp);
3166 while (temp
3167 && temp->offset < offset + curr->size)
3169 struct constraint_expr c2;
3170 c2.var = temp->id;
3171 c2.type = ADDRESSOF;
3172 c2.offset = 0;
3173 results->safe_push (c2);
3174 temp = vi_next (temp);
3177 else if (c.type == SCALAR)
3179 gcc_assert (c.offset == 0);
3180 c.offset = rhsoffset;
3182 else
3183 /* We shouldn't get any DEREFs here. */
3184 gcc_unreachable ();
3186 (*results)[j] = c;
3191 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3192 If address_p is true the result will be taken its address of.
3193 If lhs_p is true then the constraint expression is assumed to be used
3194 as the lhs. */
3196 static void
3197 get_constraint_for_component_ref (tree t, vec<ce_s> *results,
3198 bool address_p, bool lhs_p)
3200 tree orig_t = t;
3201 HOST_WIDE_INT bitsize = -1;
3202 HOST_WIDE_INT bitmaxsize = -1;
3203 HOST_WIDE_INT bitpos;
3204 tree forzero;
3206 /* Some people like to do cute things like take the address of
3207 &0->a.b */
3208 forzero = t;
3209 while (handled_component_p (forzero)
3210 || INDIRECT_REF_P (forzero)
3211 || TREE_CODE (forzero) == MEM_REF)
3212 forzero = TREE_OPERAND (forzero, 0);
3214 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3216 struct constraint_expr temp;
3218 temp.offset = 0;
3219 temp.var = integer_id;
3220 temp.type = SCALAR;
3221 results->safe_push (temp);
3222 return;
3225 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
3227 /* Pretend to take the address of the base, we'll take care of
3228 adding the required subset of sub-fields below. */
3229 get_constraint_for_1 (t, results, true, lhs_p);
3230 gcc_assert (results->length () == 1);
3231 struct constraint_expr &result = results->last ();
3233 if (result.type == SCALAR
3234 && get_varinfo (result.var)->is_full_var)
3235 /* For single-field vars do not bother about the offset. */
3236 result.offset = 0;
3237 else if (result.type == SCALAR)
3239 /* In languages like C, you can access one past the end of an
3240 array. You aren't allowed to dereference it, so we can
3241 ignore this constraint. When we handle pointer subtraction,
3242 we may have to do something cute here. */
3244 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result.var)->fullsize
3245 && bitmaxsize != 0)
3247 /* It's also not true that the constraint will actually start at the
3248 right offset, it may start in some padding. We only care about
3249 setting the constraint to the first actual field it touches, so
3250 walk to find it. */
3251 struct constraint_expr cexpr = result;
3252 varinfo_t curr;
3253 results->pop ();
3254 cexpr.offset = 0;
3255 for (curr = get_varinfo (cexpr.var); curr; curr = vi_next (curr))
3257 if (ranges_overlap_p (curr->offset, curr->size,
3258 bitpos, bitmaxsize))
3260 cexpr.var = curr->id;
3261 results->safe_push (cexpr);
3262 if (address_p)
3263 break;
3266 /* If we are going to take the address of this field then
3267 to be able to compute reachability correctly add at least
3268 the last field of the variable. */
3269 if (address_p && results->length () == 0)
3271 curr = get_varinfo (cexpr.var);
3272 while (curr->next != 0)
3273 curr = vi_next (curr);
3274 cexpr.var = curr->id;
3275 results->safe_push (cexpr);
3277 else if (results->length () == 0)
3278 /* Assert that we found *some* field there. The user couldn't be
3279 accessing *only* padding. */
3280 /* Still the user could access one past the end of an array
3281 embedded in a struct resulting in accessing *only* padding. */
3282 /* Or accessing only padding via type-punning to a type
3283 that has a filed just in padding space. */
3285 cexpr.type = SCALAR;
3286 cexpr.var = anything_id;
3287 cexpr.offset = 0;
3288 results->safe_push (cexpr);
3291 else if (bitmaxsize == 0)
3293 if (dump_file && (dump_flags & TDF_DETAILS))
3294 fprintf (dump_file, "Access to zero-sized part of variable,"
3295 "ignoring\n");
3297 else
3298 if (dump_file && (dump_flags & TDF_DETAILS))
3299 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3301 else if (result.type == DEREF)
3303 /* If we do not know exactly where the access goes say so. Note
3304 that only for non-structure accesses we know that we access
3305 at most one subfiled of any variable. */
3306 if (bitpos == -1
3307 || bitsize != bitmaxsize
3308 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3309 || result.offset == UNKNOWN_OFFSET)
3310 result.offset = UNKNOWN_OFFSET;
3311 else
3312 result.offset += bitpos;
3314 else if (result.type == ADDRESSOF)
3316 /* We can end up here for component references on a
3317 VIEW_CONVERT_EXPR <>(&foobar). */
3318 result.type = SCALAR;
3319 result.var = anything_id;
3320 result.offset = 0;
3322 else
3323 gcc_unreachable ();
3327 /* Dereference the constraint expression CONS, and return the result.
3328 DEREF (ADDRESSOF) = SCALAR
3329 DEREF (SCALAR) = DEREF
3330 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3331 This is needed so that we can handle dereferencing DEREF constraints. */
3333 static void
3334 do_deref (vec<ce_s> *constraints)
3336 struct constraint_expr *c;
3337 unsigned int i = 0;
3339 FOR_EACH_VEC_ELT (*constraints, i, c)
3341 if (c->type == SCALAR)
3342 c->type = DEREF;
3343 else if (c->type == ADDRESSOF)
3344 c->type = SCALAR;
3345 else if (c->type == DEREF)
3347 struct constraint_expr tmplhs;
3348 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3349 process_constraint (new_constraint (tmplhs, *c));
3350 c->var = tmplhs.var;
3352 else
3353 gcc_unreachable ();
3357 /* Given a tree T, return the constraint expression for taking the
3358 address of it. */
3360 static void
3361 get_constraint_for_address_of (tree t, vec<ce_s> *results)
3363 struct constraint_expr *c;
3364 unsigned int i;
3366 get_constraint_for_1 (t, results, true, true);
3368 FOR_EACH_VEC_ELT (*results, i, c)
3370 if (c->type == DEREF)
3371 c->type = SCALAR;
3372 else
3373 c->type = ADDRESSOF;
3377 /* Given a tree T, return the constraint expression for it. */
3379 static void
3380 get_constraint_for_1 (tree t, vec<ce_s> *results, bool address_p,
3381 bool lhs_p)
3383 struct constraint_expr temp;
3385 /* x = integer is all glommed to a single variable, which doesn't
3386 point to anything by itself. That is, of course, unless it is an
3387 integer constant being treated as a pointer, in which case, we
3388 will return that this is really the addressof anything. This
3389 happens below, since it will fall into the default case. The only
3390 case we know something about an integer treated like a pointer is
3391 when it is the NULL pointer, and then we just say it points to
3392 NULL.
3394 Do not do that if -fno-delete-null-pointer-checks though, because
3395 in that case *NULL does not fail, so it _should_ alias *anything.
3396 It is not worth adding a new option or renaming the existing one,
3397 since this case is relatively obscure. */
3398 if ((TREE_CODE (t) == INTEGER_CST
3399 && integer_zerop (t))
3400 /* The only valid CONSTRUCTORs in gimple with pointer typed
3401 elements are zero-initializer. But in IPA mode we also
3402 process global initializers, so verify at least. */
3403 || (TREE_CODE (t) == CONSTRUCTOR
3404 && CONSTRUCTOR_NELTS (t) == 0))
3406 if (flag_delete_null_pointer_checks)
3407 temp.var = nothing_id;
3408 else
3409 temp.var = nonlocal_id;
3410 temp.type = ADDRESSOF;
3411 temp.offset = 0;
3412 results->safe_push (temp);
3413 return;
3416 /* String constants are read-only, ideally we'd have a CONST_DECL
3417 for those. */
3418 if (TREE_CODE (t) == STRING_CST)
3420 temp.var = string_id;
3421 temp.type = SCALAR;
3422 temp.offset = 0;
3423 results->safe_push (temp);
3424 return;
3427 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3429 case tcc_expression:
3431 switch (TREE_CODE (t))
3433 case ADDR_EXPR:
3434 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3435 return;
3436 default:;
3438 break;
3440 case tcc_reference:
3442 switch (TREE_CODE (t))
3444 case MEM_REF:
3446 struct constraint_expr cs;
3447 varinfo_t vi, curr;
3448 get_constraint_for_ptr_offset (TREE_OPERAND (t, 0),
3449 TREE_OPERAND (t, 1), results);
3450 do_deref (results);
3452 /* If we are not taking the address then make sure to process
3453 all subvariables we might access. */
3454 if (address_p)
3455 return;
3457 cs = results->last ();
3458 if (cs.type == DEREF
3459 && type_can_have_subvars (TREE_TYPE (t)))
3461 /* For dereferences this means we have to defer it
3462 to solving time. */
3463 results->last ().offset = UNKNOWN_OFFSET;
3464 return;
3466 if (cs.type != SCALAR)
3467 return;
3469 vi = get_varinfo (cs.var);
3470 curr = vi_next (vi);
3471 if (!vi->is_full_var
3472 && curr)
3474 unsigned HOST_WIDE_INT size;
3475 if (tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (t))))
3476 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (t)));
3477 else
3478 size = -1;
3479 for (; curr; curr = vi_next (curr))
3481 if (curr->offset - vi->offset < size)
3483 cs.var = curr->id;
3484 results->safe_push (cs);
3486 else
3487 break;
3490 return;
3492 case ARRAY_REF:
3493 case ARRAY_RANGE_REF:
3494 case COMPONENT_REF:
3495 case IMAGPART_EXPR:
3496 case REALPART_EXPR:
3497 case BIT_FIELD_REF:
3498 get_constraint_for_component_ref (t, results, address_p, lhs_p);
3499 return;
3500 case VIEW_CONVERT_EXPR:
3501 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3502 lhs_p);
3503 return;
3504 /* We are missing handling for TARGET_MEM_REF here. */
3505 default:;
3507 break;
3509 case tcc_exceptional:
3511 switch (TREE_CODE (t))
3513 case SSA_NAME:
3515 get_constraint_for_ssa_var (t, results, address_p);
3516 return;
3518 case CONSTRUCTOR:
3520 unsigned int i;
3521 tree val;
3522 auto_vec<ce_s> tmp;
3523 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3525 struct constraint_expr *rhsp;
3526 unsigned j;
3527 get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3528 FOR_EACH_VEC_ELT (tmp, j, rhsp)
3529 results->safe_push (*rhsp);
3530 tmp.truncate (0);
3532 /* We do not know whether the constructor was complete,
3533 so technically we have to add &NOTHING or &ANYTHING
3534 like we do for an empty constructor as well. */
3535 return;
3537 default:;
3539 break;
3541 case tcc_declaration:
3543 get_constraint_for_ssa_var (t, results, address_p);
3544 return;
3546 case tcc_constant:
3548 /* We cannot refer to automatic variables through constants. */
3549 temp.type = ADDRESSOF;
3550 temp.var = nonlocal_id;
3551 temp.offset = 0;
3552 results->safe_push (temp);
3553 return;
3555 default:;
3558 /* The default fallback is a constraint from anything. */
3559 temp.type = ADDRESSOF;
3560 temp.var = anything_id;
3561 temp.offset = 0;
3562 results->safe_push (temp);
3565 /* Given a gimple tree T, return the constraint expression vector for it. */
3567 static void
3568 get_constraint_for (tree t, vec<ce_s> *results)
3570 gcc_assert (results->length () == 0);
3572 get_constraint_for_1 (t, results, false, true);
3575 /* Given a gimple tree T, return the constraint expression vector for it
3576 to be used as the rhs of a constraint. */
3578 static void
3579 get_constraint_for_rhs (tree t, vec<ce_s> *results)
3581 gcc_assert (results->length () == 0);
3583 get_constraint_for_1 (t, results, false, false);
3587 /* Efficiently generates constraints from all entries in *RHSC to all
3588 entries in *LHSC. */
3590 static void
3591 process_all_all_constraints (vec<ce_s> lhsc,
3592 vec<ce_s> rhsc)
3594 struct constraint_expr *lhsp, *rhsp;
3595 unsigned i, j;
3597 if (lhsc.length () <= 1 || rhsc.length () <= 1)
3599 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3600 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
3601 process_constraint (new_constraint (*lhsp, *rhsp));
3603 else
3605 struct constraint_expr tmp;
3606 tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3607 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
3608 process_constraint (new_constraint (tmp, *rhsp));
3609 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3610 process_constraint (new_constraint (*lhsp, tmp));
3614 /* Handle aggregate copies by expanding into copies of the respective
3615 fields of the structures. */
3617 static void
3618 do_structure_copy (tree lhsop, tree rhsop)
3620 struct constraint_expr *lhsp, *rhsp;
3621 auto_vec<ce_s> lhsc;
3622 auto_vec<ce_s> rhsc;
3623 unsigned j;
3625 get_constraint_for (lhsop, &lhsc);
3626 get_constraint_for_rhs (rhsop, &rhsc);
3627 lhsp = &lhsc[0];
3628 rhsp = &rhsc[0];
3629 if (lhsp->type == DEREF
3630 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3631 || rhsp->type == DEREF)
3633 if (lhsp->type == DEREF)
3635 gcc_assert (lhsc.length () == 1);
3636 lhsp->offset = UNKNOWN_OFFSET;
3638 if (rhsp->type == DEREF)
3640 gcc_assert (rhsc.length () == 1);
3641 rhsp->offset = UNKNOWN_OFFSET;
3643 process_all_all_constraints (lhsc, rhsc);
3645 else if (lhsp->type == SCALAR
3646 && (rhsp->type == SCALAR
3647 || rhsp->type == ADDRESSOF))
3649 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3650 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3651 unsigned k = 0;
3652 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3653 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3654 for (j = 0; lhsc.iterate (j, &lhsp);)
3656 varinfo_t lhsv, rhsv;
3657 rhsp = &rhsc[k];
3658 lhsv = get_varinfo (lhsp->var);
3659 rhsv = get_varinfo (rhsp->var);
3660 if (lhsv->may_have_pointers
3661 && (lhsv->is_full_var
3662 || rhsv->is_full_var
3663 || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3664 rhsv->offset + lhsoffset, rhsv->size)))
3665 process_constraint (new_constraint (*lhsp, *rhsp));
3666 if (!rhsv->is_full_var
3667 && (lhsv->is_full_var
3668 || (lhsv->offset + rhsoffset + lhsv->size
3669 > rhsv->offset + lhsoffset + rhsv->size)))
3671 ++k;
3672 if (k >= rhsc.length ())
3673 break;
3675 else
3676 ++j;
3679 else
3680 gcc_unreachable ();
3683 /* Create constraints ID = { rhsc }. */
3685 static void
3686 make_constraints_to (unsigned id, vec<ce_s> rhsc)
3688 struct constraint_expr *c;
3689 struct constraint_expr includes;
3690 unsigned int j;
3692 includes.var = id;
3693 includes.offset = 0;
3694 includes.type = SCALAR;
3696 FOR_EACH_VEC_ELT (rhsc, j, c)
3697 process_constraint (new_constraint (includes, *c));
3700 /* Create a constraint ID = OP. */
3702 static void
3703 make_constraint_to (unsigned id, tree op)
3705 auto_vec<ce_s> rhsc;
3706 get_constraint_for_rhs (op, &rhsc);
3707 make_constraints_to (id, rhsc);
3710 /* Create a constraint ID = &FROM. */
3712 static void
3713 make_constraint_from (varinfo_t vi, int from)
3715 struct constraint_expr lhs, rhs;
3717 lhs.var = vi->id;
3718 lhs.offset = 0;
3719 lhs.type = SCALAR;
3721 rhs.var = from;
3722 rhs.offset = 0;
3723 rhs.type = ADDRESSOF;
3724 process_constraint (new_constraint (lhs, rhs));
3727 /* Create a constraint ID = FROM. */
3729 static void
3730 make_copy_constraint (varinfo_t vi, int from)
3732 struct constraint_expr lhs, rhs;
3734 lhs.var = vi->id;
3735 lhs.offset = 0;
3736 lhs.type = SCALAR;
3738 rhs.var = from;
3739 rhs.offset = 0;
3740 rhs.type = SCALAR;
3741 process_constraint (new_constraint (lhs, rhs));
3744 /* Make constraints necessary to make OP escape. */
3746 static void
3747 make_escape_constraint (tree op)
3749 make_constraint_to (escaped_id, op);
3752 /* Add constraints to that the solution of VI is transitively closed. */
3754 static void
3755 make_transitive_closure_constraints (varinfo_t vi)
3757 struct constraint_expr lhs, rhs;
3759 /* VAR = *VAR; */
3760 lhs.type = SCALAR;
3761 lhs.var = vi->id;
3762 lhs.offset = 0;
3763 rhs.type = DEREF;
3764 rhs.var = vi->id;
3765 rhs.offset = UNKNOWN_OFFSET;
3766 process_constraint (new_constraint (lhs, rhs));
3769 /* Temporary storage for fake var decls. */
3770 struct obstack fake_var_decl_obstack;
3772 /* Build a fake VAR_DECL acting as referrer to a DECL_UID. */
3774 static tree
3775 build_fake_var_decl (tree type)
3777 tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3778 memset (decl, 0, sizeof (struct tree_var_decl));
3779 TREE_SET_CODE (decl, VAR_DECL);
3780 TREE_TYPE (decl) = type;
3781 DECL_UID (decl) = allocate_decl_uid ();
3782 SET_DECL_PT_UID (decl, -1);
3783 layout_decl (decl, 0);
3784 return decl;
3787 /* Create a new artificial heap variable with NAME.
3788 Return the created variable. */
3790 static varinfo_t
3791 make_heapvar (const char *name)
3793 varinfo_t vi;
3794 tree heapvar;
3796 heapvar = build_fake_var_decl (ptr_type_node);
3797 DECL_EXTERNAL (heapvar) = 1;
3799 vi = new_var_info (heapvar, name);
3800 vi->is_artificial_var = true;
3801 vi->is_heap_var = true;
3802 vi->is_unknown_size_var = true;
3803 vi->offset = 0;
3804 vi->fullsize = ~0;
3805 vi->size = ~0;
3806 vi->is_full_var = true;
3807 insert_vi_for_tree (heapvar, vi);
3809 return vi;
3812 /* Create a new artificial heap variable with NAME and make a
3813 constraint from it to LHS. Set flags according to a tag used
3814 for tracking restrict pointers. */
3816 static varinfo_t
3817 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3819 varinfo_t vi = make_heapvar (name);
3820 vi->is_restrict_var = 1;
3821 vi->is_global_var = 1;
3822 vi->may_have_pointers = 1;
3823 make_constraint_from (lhs, vi->id);
3824 return vi;
3827 /* Create a new artificial heap variable with NAME and make a
3828 constraint from it to LHS. Set flags according to a tag used
3829 for tracking restrict pointers and make the artificial heap
3830 point to global memory. */
3832 static varinfo_t
3833 make_constraint_from_global_restrict (varinfo_t lhs, const char *name)
3835 varinfo_t vi = make_constraint_from_restrict (lhs, name);
3836 make_copy_constraint (vi, nonlocal_id);
3837 return vi;
3840 /* In IPA mode there are varinfos for different aspects of reach
3841 function designator. One for the points-to set of the return
3842 value, one for the variables that are clobbered by the function,
3843 one for its uses and one for each parameter (including a single
3844 glob for remaining variadic arguments). */
3846 enum { fi_clobbers = 1, fi_uses = 2,
3847 fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3849 /* Get a constraint for the requested part of a function designator FI
3850 when operating in IPA mode. */
3852 static struct constraint_expr
3853 get_function_part_constraint (varinfo_t fi, unsigned part)
3855 struct constraint_expr c;
3857 gcc_assert (in_ipa_mode);
3859 if (fi->id == anything_id)
3861 /* ??? We probably should have a ANYFN special variable. */
3862 c.var = anything_id;
3863 c.offset = 0;
3864 c.type = SCALAR;
3866 else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3868 varinfo_t ai = first_vi_for_offset (fi, part);
3869 if (ai)
3870 c.var = ai->id;
3871 else
3872 c.var = anything_id;
3873 c.offset = 0;
3874 c.type = SCALAR;
3876 else
3878 c.var = fi->id;
3879 c.offset = part;
3880 c.type = DEREF;
3883 return c;
3886 /* For non-IPA mode, generate constraints necessary for a call on the
3887 RHS. */
3889 static void
3890 handle_rhs_call (gcall *stmt, vec<ce_s> *results)
3892 struct constraint_expr rhsc;
3893 unsigned i;
3894 bool returns_uses = false;
3896 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3898 tree arg = gimple_call_arg (stmt, i);
3899 int flags = gimple_call_arg_flags (stmt, i);
3901 /* If the argument is not used we can ignore it. */
3902 if (flags & EAF_UNUSED)
3903 continue;
3905 /* As we compute ESCAPED context-insensitive we do not gain
3906 any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3907 set. The argument would still get clobbered through the
3908 escape solution. */
3909 if ((flags & EAF_NOCLOBBER)
3910 && (flags & EAF_NOESCAPE))
3912 varinfo_t uses = get_call_use_vi (stmt);
3913 if (!(flags & EAF_DIRECT))
3915 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3916 make_constraint_to (tem->id, arg);
3917 make_transitive_closure_constraints (tem);
3918 make_copy_constraint (uses, tem->id);
3920 else
3921 make_constraint_to (uses->id, arg);
3922 returns_uses = true;
3924 else if (flags & EAF_NOESCAPE)
3926 struct constraint_expr lhs, rhs;
3927 varinfo_t uses = get_call_use_vi (stmt);
3928 varinfo_t clobbers = get_call_clobber_vi (stmt);
3929 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3930 make_constraint_to (tem->id, arg);
3931 if (!(flags & EAF_DIRECT))
3932 make_transitive_closure_constraints (tem);
3933 make_copy_constraint (uses, tem->id);
3934 make_copy_constraint (clobbers, tem->id);
3935 /* Add *tem = nonlocal, do not add *tem = callused as
3936 EAF_NOESCAPE parameters do not escape to other parameters
3937 and all other uses appear in NONLOCAL as well. */
3938 lhs.type = DEREF;
3939 lhs.var = tem->id;
3940 lhs.offset = 0;
3941 rhs.type = SCALAR;
3942 rhs.var = nonlocal_id;
3943 rhs.offset = 0;
3944 process_constraint (new_constraint (lhs, rhs));
3945 returns_uses = true;
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 = 0;
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");
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;
4060 /* Treat nested const functions the same as pure functions as far
4061 as the static chain is concerned. */
4062 if (gimple_call_chain (stmt))
4064 varinfo_t uses = get_call_use_vi (stmt);
4065 make_transitive_closure_constraints (uses);
4066 make_constraint_to (uses->id, gimple_call_chain (stmt));
4067 rhsc.var = uses->id;
4068 rhsc.offset = 0;
4069 rhsc.type = SCALAR;
4070 results->safe_push (rhsc);
4073 /* May return arguments. */
4074 for (k = 0; k < gimple_call_num_args (stmt); ++k)
4076 tree arg = gimple_call_arg (stmt, k);
4077 auto_vec<ce_s> argc;
4078 unsigned i;
4079 struct constraint_expr *argp;
4080 get_constraint_for_rhs (arg, &argc);
4081 FOR_EACH_VEC_ELT (argc, i, argp)
4082 results->safe_push (*argp);
4085 /* May return addresses of globals. */
4086 rhsc.var = nonlocal_id;
4087 rhsc.offset = 0;
4088 rhsc.type = ADDRESSOF;
4089 results->safe_push (rhsc);
4092 /* For non-IPA mode, generate constraints necessary for a call to a
4093 pure function in statement STMT. */
4095 static void
4096 handle_pure_call (gcall *stmt, vec<ce_s> *results)
4098 struct constraint_expr rhsc;
4099 unsigned i;
4100 varinfo_t uses = NULL;
4102 /* Memory reached from pointer arguments is call-used. */
4103 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4105 tree arg = gimple_call_arg (stmt, i);
4106 if (!uses)
4108 uses = get_call_use_vi (stmt);
4109 make_transitive_closure_constraints (uses);
4111 make_constraint_to (uses->id, arg);
4114 /* The static chain is used as well. */
4115 if (gimple_call_chain (stmt))
4117 if (!uses)
4119 uses = get_call_use_vi (stmt);
4120 make_transitive_closure_constraints (uses);
4122 make_constraint_to (uses->id, gimple_call_chain (stmt));
4125 /* Pure functions may return call-used and nonlocal memory. */
4126 if (uses)
4128 rhsc.var = uses->id;
4129 rhsc.offset = 0;
4130 rhsc.type = SCALAR;
4131 results->safe_push (rhsc);
4133 rhsc.var = nonlocal_id;
4134 rhsc.offset = 0;
4135 rhsc.type = SCALAR;
4136 results->safe_push (rhsc);
4140 /* Return the varinfo for the callee of CALL. */
4142 static varinfo_t
4143 get_fi_for_callee (gcall *call)
4145 tree decl, fn = gimple_call_fn (call);
4147 if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
4148 fn = OBJ_TYPE_REF_EXPR (fn);
4150 /* If we can directly resolve the function being called, do so.
4151 Otherwise, it must be some sort of indirect expression that
4152 we should still be able to handle. */
4153 decl = gimple_call_addr_fndecl (fn);
4154 if (decl)
4155 return get_vi_for_tree (decl);
4157 /* If the function is anything other than a SSA name pointer we have no
4158 clue and should be getting ANYFN (well, ANYTHING for now). */
4159 if (!fn || TREE_CODE (fn) != SSA_NAME)
4160 return get_varinfo (anything_id);
4162 if (SSA_NAME_IS_DEFAULT_DEF (fn)
4163 && (TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
4164 || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL))
4165 fn = SSA_NAME_VAR (fn);
4167 return get_vi_for_tree (fn);
4170 /* Create constraints for the builtin call T. Return true if the call
4171 was handled, otherwise false. */
4173 static bool
4174 find_func_aliases_for_builtin_call (struct function *fn, gcall *t)
4176 tree fndecl = gimple_call_fndecl (t);
4177 auto_vec<ce_s, 2> lhsc;
4178 auto_vec<ce_s, 4> rhsc;
4179 varinfo_t fi;
4181 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4182 /* ??? All builtins that are handled here need to be handled
4183 in the alias-oracle query functions explicitly! */
4184 switch (DECL_FUNCTION_CODE (fndecl))
4186 /* All the following functions return a pointer to the same object
4187 as their first argument points to. The functions do not add
4188 to the ESCAPED solution. The functions make the first argument
4189 pointed to memory point to what the second argument pointed to
4190 memory points to. */
4191 case BUILT_IN_STRCPY:
4192 case BUILT_IN_STRNCPY:
4193 case BUILT_IN_BCOPY:
4194 case BUILT_IN_MEMCPY:
4195 case BUILT_IN_MEMMOVE:
4196 case BUILT_IN_MEMPCPY:
4197 case BUILT_IN_STPCPY:
4198 case BUILT_IN_STPNCPY:
4199 case BUILT_IN_STRCAT:
4200 case BUILT_IN_STRNCAT:
4201 case BUILT_IN_STRCPY_CHK:
4202 case BUILT_IN_STRNCPY_CHK:
4203 case BUILT_IN_MEMCPY_CHK:
4204 case BUILT_IN_MEMMOVE_CHK:
4205 case BUILT_IN_MEMPCPY_CHK:
4206 case BUILT_IN_STPCPY_CHK:
4207 case BUILT_IN_STPNCPY_CHK:
4208 case BUILT_IN_STRCAT_CHK:
4209 case BUILT_IN_STRNCAT_CHK:
4210 case BUILT_IN_TM_MEMCPY:
4211 case BUILT_IN_TM_MEMMOVE:
4213 tree res = gimple_call_lhs (t);
4214 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4215 == BUILT_IN_BCOPY ? 1 : 0));
4216 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4217 == BUILT_IN_BCOPY ? 0 : 1));
4218 if (res != NULL_TREE)
4220 get_constraint_for (res, &lhsc);
4221 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4222 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4223 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4224 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4225 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK
4226 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY_CHK)
4227 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4228 else
4229 get_constraint_for (dest, &rhsc);
4230 process_all_all_constraints (lhsc, rhsc);
4231 lhsc.truncate (0);
4232 rhsc.truncate (0);
4234 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4235 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4236 do_deref (&lhsc);
4237 do_deref (&rhsc);
4238 process_all_all_constraints (lhsc, rhsc);
4239 return true;
4241 case BUILT_IN_MEMSET:
4242 case BUILT_IN_MEMSET_CHK:
4243 case BUILT_IN_TM_MEMSET:
4245 tree res = gimple_call_lhs (t);
4246 tree dest = gimple_call_arg (t, 0);
4247 unsigned i;
4248 ce_s *lhsp;
4249 struct constraint_expr ac;
4250 if (res != NULL_TREE)
4252 get_constraint_for (res, &lhsc);
4253 get_constraint_for (dest, &rhsc);
4254 process_all_all_constraints (lhsc, rhsc);
4255 lhsc.truncate (0);
4257 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4258 do_deref (&lhsc);
4259 if (flag_delete_null_pointer_checks
4260 && integer_zerop (gimple_call_arg (t, 1)))
4262 ac.type = ADDRESSOF;
4263 ac.var = nothing_id;
4265 else
4267 ac.type = SCALAR;
4268 ac.var = integer_id;
4270 ac.offset = 0;
4271 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4272 process_constraint (new_constraint (*lhsp, ac));
4273 return true;
4275 case BUILT_IN_POSIX_MEMALIGN:
4277 tree ptrptr = gimple_call_arg (t, 0);
4278 get_constraint_for (ptrptr, &lhsc);
4279 do_deref (&lhsc);
4280 varinfo_t vi = make_heapvar ("HEAP");
4281 /* We are marking allocated storage local, we deal with it becoming
4282 global by escaping and setting of vars_contains_escaped_heap. */
4283 DECL_EXTERNAL (vi->decl) = 0;
4284 vi->is_global_var = 0;
4285 struct constraint_expr tmpc;
4286 tmpc.var = vi->id;
4287 tmpc.offset = 0;
4288 tmpc.type = ADDRESSOF;
4289 rhsc.safe_push (tmpc);
4290 process_all_all_constraints (lhsc, rhsc);
4291 return true;
4293 case BUILT_IN_ASSUME_ALIGNED:
4295 tree res = gimple_call_lhs (t);
4296 tree dest = gimple_call_arg (t, 0);
4297 if (res != NULL_TREE)
4299 get_constraint_for (res, &lhsc);
4300 get_constraint_for (dest, &rhsc);
4301 process_all_all_constraints (lhsc, rhsc);
4303 return true;
4305 /* All the following functions do not return pointers, do not
4306 modify the points-to sets of memory reachable from their
4307 arguments and do not add to the ESCAPED solution. */
4308 case BUILT_IN_SINCOS:
4309 case BUILT_IN_SINCOSF:
4310 case BUILT_IN_SINCOSL:
4311 case BUILT_IN_FREXP:
4312 case BUILT_IN_FREXPF:
4313 case BUILT_IN_FREXPL:
4314 case BUILT_IN_GAMMA_R:
4315 case BUILT_IN_GAMMAF_R:
4316 case BUILT_IN_GAMMAL_R:
4317 case BUILT_IN_LGAMMA_R:
4318 case BUILT_IN_LGAMMAF_R:
4319 case BUILT_IN_LGAMMAL_R:
4320 case BUILT_IN_MODF:
4321 case BUILT_IN_MODFF:
4322 case BUILT_IN_MODFL:
4323 case BUILT_IN_REMQUO:
4324 case BUILT_IN_REMQUOF:
4325 case BUILT_IN_REMQUOL:
4326 case BUILT_IN_FREE:
4327 return true;
4328 case BUILT_IN_STRDUP:
4329 case BUILT_IN_STRNDUP:
4330 case BUILT_IN_REALLOC:
4331 if (gimple_call_lhs (t))
4333 handle_lhs_call (t, gimple_call_lhs (t),
4334 gimple_call_return_flags (t) | ERF_NOALIAS,
4335 vNULL, fndecl);
4336 get_constraint_for_ptr_offset (gimple_call_lhs (t),
4337 NULL_TREE, &lhsc);
4338 get_constraint_for_ptr_offset (gimple_call_arg (t, 0),
4339 NULL_TREE, &rhsc);
4340 do_deref (&lhsc);
4341 do_deref (&rhsc);
4342 process_all_all_constraints (lhsc, rhsc);
4343 lhsc.truncate (0);
4344 rhsc.truncate (0);
4345 /* For realloc the resulting pointer can be equal to the
4346 argument as well. But only doing this wouldn't be
4347 correct because with ptr == 0 realloc behaves like malloc. */
4348 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_REALLOC)
4350 get_constraint_for (gimple_call_lhs (t), &lhsc);
4351 get_constraint_for (gimple_call_arg (t, 0), &rhsc);
4352 process_all_all_constraints (lhsc, rhsc);
4354 return true;
4356 break;
4357 /* String / character search functions return a pointer into the
4358 source string or NULL. */
4359 case BUILT_IN_INDEX:
4360 case BUILT_IN_STRCHR:
4361 case BUILT_IN_STRRCHR:
4362 case BUILT_IN_MEMCHR:
4363 case BUILT_IN_STRSTR:
4364 case BUILT_IN_STRPBRK:
4365 if (gimple_call_lhs (t))
4367 tree src = gimple_call_arg (t, 0);
4368 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4369 constraint_expr nul;
4370 nul.var = nothing_id;
4371 nul.offset = 0;
4372 nul.type = ADDRESSOF;
4373 rhsc.safe_push (nul);
4374 get_constraint_for (gimple_call_lhs (t), &lhsc);
4375 process_all_all_constraints (lhsc, rhsc);
4377 return true;
4378 /* Trampolines are special - they set up passing the static
4379 frame. */
4380 case BUILT_IN_INIT_TRAMPOLINE:
4382 tree tramp = gimple_call_arg (t, 0);
4383 tree nfunc = gimple_call_arg (t, 1);
4384 tree frame = gimple_call_arg (t, 2);
4385 unsigned i;
4386 struct constraint_expr lhs, *rhsp;
4387 if (in_ipa_mode)
4389 varinfo_t nfi = NULL;
4390 gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4391 nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4392 if (nfi)
4394 lhs = get_function_part_constraint (nfi, fi_static_chain);
4395 get_constraint_for (frame, &rhsc);
4396 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4397 process_constraint (new_constraint (lhs, *rhsp));
4398 rhsc.truncate (0);
4400 /* Make the frame point to the function for
4401 the trampoline adjustment call. */
4402 get_constraint_for (tramp, &lhsc);
4403 do_deref (&lhsc);
4404 get_constraint_for (nfunc, &rhsc);
4405 process_all_all_constraints (lhsc, rhsc);
4407 return true;
4410 /* Else fallthru to generic handling which will let
4411 the frame escape. */
4412 break;
4414 case BUILT_IN_ADJUST_TRAMPOLINE:
4416 tree tramp = gimple_call_arg (t, 0);
4417 tree res = gimple_call_lhs (t);
4418 if (in_ipa_mode && res)
4420 get_constraint_for (res, &lhsc);
4421 get_constraint_for (tramp, &rhsc);
4422 do_deref (&rhsc);
4423 process_all_all_constraints (lhsc, rhsc);
4425 return true;
4427 CASE_BUILT_IN_TM_STORE (1):
4428 CASE_BUILT_IN_TM_STORE (2):
4429 CASE_BUILT_IN_TM_STORE (4):
4430 CASE_BUILT_IN_TM_STORE (8):
4431 CASE_BUILT_IN_TM_STORE (FLOAT):
4432 CASE_BUILT_IN_TM_STORE (DOUBLE):
4433 CASE_BUILT_IN_TM_STORE (LDOUBLE):
4434 CASE_BUILT_IN_TM_STORE (M64):
4435 CASE_BUILT_IN_TM_STORE (M128):
4436 CASE_BUILT_IN_TM_STORE (M256):
4438 tree addr = gimple_call_arg (t, 0);
4439 tree src = gimple_call_arg (t, 1);
4441 get_constraint_for (addr, &lhsc);
4442 do_deref (&lhsc);
4443 get_constraint_for (src, &rhsc);
4444 process_all_all_constraints (lhsc, rhsc);
4445 return true;
4447 CASE_BUILT_IN_TM_LOAD (1):
4448 CASE_BUILT_IN_TM_LOAD (2):
4449 CASE_BUILT_IN_TM_LOAD (4):
4450 CASE_BUILT_IN_TM_LOAD (8):
4451 CASE_BUILT_IN_TM_LOAD (FLOAT):
4452 CASE_BUILT_IN_TM_LOAD (DOUBLE):
4453 CASE_BUILT_IN_TM_LOAD (LDOUBLE):
4454 CASE_BUILT_IN_TM_LOAD (M64):
4455 CASE_BUILT_IN_TM_LOAD (M128):
4456 CASE_BUILT_IN_TM_LOAD (M256):
4458 tree dest = gimple_call_lhs (t);
4459 tree addr = gimple_call_arg (t, 0);
4461 get_constraint_for (dest, &lhsc);
4462 get_constraint_for (addr, &rhsc);
4463 do_deref (&rhsc);
4464 process_all_all_constraints (lhsc, rhsc);
4465 return true;
4467 /* Variadic argument handling needs to be handled in IPA
4468 mode as well. */
4469 case BUILT_IN_VA_START:
4471 tree valist = gimple_call_arg (t, 0);
4472 struct constraint_expr rhs, *lhsp;
4473 unsigned i;
4474 get_constraint_for (valist, &lhsc);
4475 do_deref (&lhsc);
4476 /* The va_list gets access to pointers in variadic
4477 arguments. Which we know in the case of IPA analysis
4478 and otherwise are just all nonlocal variables. */
4479 if (in_ipa_mode)
4481 fi = lookup_vi_for_tree (fn->decl);
4482 rhs = get_function_part_constraint (fi, ~0);
4483 rhs.type = ADDRESSOF;
4485 else
4487 rhs.var = nonlocal_id;
4488 rhs.type = ADDRESSOF;
4489 rhs.offset = 0;
4491 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4492 process_constraint (new_constraint (*lhsp, rhs));
4493 /* va_list is clobbered. */
4494 make_constraint_to (get_call_clobber_vi (t)->id, valist);
4495 return true;
4497 /* va_end doesn't have any effect that matters. */
4498 case BUILT_IN_VA_END:
4499 return true;
4500 /* Alternate return. Simply give up for now. */
4501 case BUILT_IN_RETURN:
4503 fi = NULL;
4504 if (!in_ipa_mode
4505 || !(fi = get_vi_for_tree (fn->decl)))
4506 make_constraint_from (get_varinfo (escaped_id), anything_id);
4507 else if (in_ipa_mode
4508 && fi != NULL)
4510 struct constraint_expr lhs, rhs;
4511 lhs = get_function_part_constraint (fi, fi_result);
4512 rhs.var = anything_id;
4513 rhs.offset = 0;
4514 rhs.type = SCALAR;
4515 process_constraint (new_constraint (lhs, rhs));
4517 return true;
4519 /* printf-style functions may have hooks to set pointers to
4520 point to somewhere into the generated string. Leave them
4521 for a later exercise... */
4522 default:
4523 /* Fallthru to general call handling. */;
4526 return false;
4529 /* Create constraints for the call T. */
4531 static void
4532 find_func_aliases_for_call (struct function *fn, gcall *t)
4534 tree fndecl = gimple_call_fndecl (t);
4535 varinfo_t fi;
4537 if (fndecl != NULL_TREE
4538 && DECL_BUILT_IN (fndecl)
4539 && find_func_aliases_for_builtin_call (fn, t))
4540 return;
4542 fi = get_fi_for_callee (t);
4543 if (!in_ipa_mode
4544 || (fndecl && !fi->is_fn_info))
4546 auto_vec<ce_s, 16> rhsc;
4547 int flags = gimple_call_flags (t);
4549 /* Const functions can return their arguments and addresses
4550 of global memory but not of escaped memory. */
4551 if (flags & (ECF_CONST|ECF_NOVOPS))
4553 if (gimple_call_lhs (t))
4554 handle_const_call (t, &rhsc);
4556 /* Pure functions can return addresses in and of memory
4557 reachable from their arguments, but they are not an escape
4558 point for reachable memory of their arguments. */
4559 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4560 handle_pure_call (t, &rhsc);
4561 else
4562 handle_rhs_call (t, &rhsc);
4563 if (gimple_call_lhs (t))
4564 handle_lhs_call (t, gimple_call_lhs (t),
4565 gimple_call_return_flags (t), rhsc, fndecl);
4567 else
4569 auto_vec<ce_s, 2> rhsc;
4570 tree lhsop;
4571 unsigned j;
4573 /* Assign all the passed arguments to the appropriate incoming
4574 parameters of the function. */
4575 for (j = 0; j < gimple_call_num_args (t); j++)
4577 struct constraint_expr lhs ;
4578 struct constraint_expr *rhsp;
4579 tree arg = gimple_call_arg (t, j);
4581 get_constraint_for_rhs (arg, &rhsc);
4582 lhs = get_function_part_constraint (fi, fi_parm_base + j);
4583 while (rhsc.length () != 0)
4585 rhsp = &rhsc.last ();
4586 process_constraint (new_constraint (lhs, *rhsp));
4587 rhsc.pop ();
4591 /* If we are returning a value, assign it to the result. */
4592 lhsop = gimple_call_lhs (t);
4593 if (lhsop)
4595 auto_vec<ce_s, 2> lhsc;
4596 struct constraint_expr rhs;
4597 struct constraint_expr *lhsp;
4599 get_constraint_for (lhsop, &lhsc);
4600 rhs = get_function_part_constraint (fi, fi_result);
4601 if (fndecl
4602 && DECL_RESULT (fndecl)
4603 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4605 auto_vec<ce_s, 2> tem;
4606 tem.quick_push (rhs);
4607 do_deref (&tem);
4608 gcc_checking_assert (tem.length () == 1);
4609 rhs = tem[0];
4611 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4612 process_constraint (new_constraint (*lhsp, rhs));
4615 /* If we pass the result decl by reference, honor that. */
4616 if (lhsop
4617 && fndecl
4618 && DECL_RESULT (fndecl)
4619 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4621 struct constraint_expr lhs;
4622 struct constraint_expr *rhsp;
4624 get_constraint_for_address_of (lhsop, &rhsc);
4625 lhs = get_function_part_constraint (fi, fi_result);
4626 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4627 process_constraint (new_constraint (lhs, *rhsp));
4628 rhsc.truncate (0);
4631 /* If we use a static chain, pass it along. */
4632 if (gimple_call_chain (t))
4634 struct constraint_expr lhs;
4635 struct constraint_expr *rhsp;
4637 get_constraint_for (gimple_call_chain (t), &rhsc);
4638 lhs = get_function_part_constraint (fi, fi_static_chain);
4639 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4640 process_constraint (new_constraint (lhs, *rhsp));
4645 /* Walk statement T setting up aliasing constraints according to the
4646 references found in T. This function is the main part of the
4647 constraint builder. AI points to auxiliary alias information used
4648 when building alias sets and computing alias grouping heuristics. */
4650 static void
4651 find_func_aliases (struct function *fn, gimple origt)
4653 gimple t = origt;
4654 auto_vec<ce_s, 16> lhsc;
4655 auto_vec<ce_s, 16> rhsc;
4656 struct constraint_expr *c;
4657 varinfo_t fi;
4659 /* Now build constraints expressions. */
4660 if (gimple_code (t) == GIMPLE_PHI)
4662 size_t i;
4663 unsigned int j;
4665 /* For a phi node, assign all the arguments to
4666 the result. */
4667 get_constraint_for (gimple_phi_result (t), &lhsc);
4668 for (i = 0; i < gimple_phi_num_args (t); i++)
4670 tree strippedrhs = PHI_ARG_DEF (t, i);
4672 STRIP_NOPS (strippedrhs);
4673 get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4675 FOR_EACH_VEC_ELT (lhsc, j, c)
4677 struct constraint_expr *c2;
4678 while (rhsc.length () > 0)
4680 c2 = &rhsc.last ();
4681 process_constraint (new_constraint (*c, *c2));
4682 rhsc.pop ();
4687 /* In IPA mode, we need to generate constraints to pass call
4688 arguments through their calls. There are two cases,
4689 either a GIMPLE_CALL returning a value, or just a plain
4690 GIMPLE_CALL when we are not.
4692 In non-ipa mode, we need to generate constraints for each
4693 pointer passed by address. */
4694 else if (is_gimple_call (t))
4695 find_func_aliases_for_call (fn, as_a <gcall *> (t));
4697 /* Otherwise, just a regular assignment statement. Only care about
4698 operations with pointer result, others are dealt with as escape
4699 points if they have pointer operands. */
4700 else if (is_gimple_assign (t))
4702 /* Otherwise, just a regular assignment statement. */
4703 tree lhsop = gimple_assign_lhs (t);
4704 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4706 if (rhsop && TREE_CLOBBER_P (rhsop))
4707 /* Ignore clobbers, they don't actually store anything into
4708 the LHS. */
4710 else if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4711 do_structure_copy (lhsop, rhsop);
4712 else
4714 enum tree_code code = gimple_assign_rhs_code (t);
4716 get_constraint_for (lhsop, &lhsc);
4718 if (code == POINTER_PLUS_EXPR)
4719 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4720 gimple_assign_rhs2 (t), &rhsc);
4721 else if (code == BIT_AND_EXPR
4722 && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4724 /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4725 the pointer. Handle it by offsetting it by UNKNOWN. */
4726 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4727 NULL_TREE, &rhsc);
4729 else if ((CONVERT_EXPR_CODE_P (code)
4730 && !(POINTER_TYPE_P (gimple_expr_type (t))
4731 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4732 || gimple_assign_single_p (t))
4733 get_constraint_for_rhs (rhsop, &rhsc);
4734 else if (code == COND_EXPR)
4736 /* The result is a merge of both COND_EXPR arms. */
4737 auto_vec<ce_s, 2> tmp;
4738 struct constraint_expr *rhsp;
4739 unsigned i;
4740 get_constraint_for_rhs (gimple_assign_rhs2 (t), &rhsc);
4741 get_constraint_for_rhs (gimple_assign_rhs3 (t), &tmp);
4742 FOR_EACH_VEC_ELT (tmp, i, rhsp)
4743 rhsc.safe_push (*rhsp);
4745 else if (truth_value_p (code))
4746 /* Truth value results are not pointer (parts). Or at least
4747 very very unreasonable obfuscation of a part. */
4749 else
4751 /* All other operations are merges. */
4752 auto_vec<ce_s, 4> tmp;
4753 struct constraint_expr *rhsp;
4754 unsigned i, j;
4755 get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4756 for (i = 2; i < gimple_num_ops (t); ++i)
4758 get_constraint_for_rhs (gimple_op (t, i), &tmp);
4759 FOR_EACH_VEC_ELT (tmp, j, rhsp)
4760 rhsc.safe_push (*rhsp);
4761 tmp.truncate (0);
4764 process_all_all_constraints (lhsc, rhsc);
4766 /* If there is a store to a global variable the rhs escapes. */
4767 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4768 && DECL_P (lhsop)
4769 && is_global_var (lhsop)
4770 && (!in_ipa_mode
4771 || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4772 make_escape_constraint (rhsop);
4774 /* Handle escapes through return. */
4775 else if (gimple_code (t) == GIMPLE_RETURN
4776 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE)
4778 greturn *return_stmt = as_a <greturn *> (t);
4779 fi = NULL;
4780 if (!in_ipa_mode
4781 || !(fi = get_vi_for_tree (fn->decl)))
4782 make_escape_constraint (gimple_return_retval (return_stmt));
4783 else if (in_ipa_mode
4784 && fi != NULL)
4786 struct constraint_expr lhs ;
4787 struct constraint_expr *rhsp;
4788 unsigned i;
4790 lhs = get_function_part_constraint (fi, fi_result);
4791 get_constraint_for_rhs (gimple_return_retval (return_stmt), &rhsc);
4792 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4793 process_constraint (new_constraint (lhs, *rhsp));
4796 /* Handle asms conservatively by adding escape constraints to everything. */
4797 else if (gasm *asm_stmt = dyn_cast <gasm *> (t))
4799 unsigned i, noutputs;
4800 const char **oconstraints;
4801 const char *constraint;
4802 bool allows_mem, allows_reg, is_inout;
4804 noutputs = gimple_asm_noutputs (asm_stmt);
4805 oconstraints = XALLOCAVEC (const char *, noutputs);
4807 for (i = 0; i < noutputs; ++i)
4809 tree link = gimple_asm_output_op (asm_stmt, i);
4810 tree op = TREE_VALUE (link);
4812 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4813 oconstraints[i] = constraint;
4814 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4815 &allows_reg, &is_inout);
4817 /* A memory constraint makes the address of the operand escape. */
4818 if (!allows_reg && allows_mem)
4819 make_escape_constraint (build_fold_addr_expr (op));
4821 /* The asm may read global memory, so outputs may point to
4822 any global memory. */
4823 if (op)
4825 auto_vec<ce_s, 2> lhsc;
4826 struct constraint_expr rhsc, *lhsp;
4827 unsigned j;
4828 get_constraint_for (op, &lhsc);
4829 rhsc.var = nonlocal_id;
4830 rhsc.offset = 0;
4831 rhsc.type = SCALAR;
4832 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4833 process_constraint (new_constraint (*lhsp, rhsc));
4836 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4838 tree link = gimple_asm_input_op (asm_stmt, i);
4839 tree op = TREE_VALUE (link);
4841 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4843 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4844 &allows_mem, &allows_reg);
4846 /* A memory constraint makes the address of the operand escape. */
4847 if (!allows_reg && allows_mem)
4848 make_escape_constraint (build_fold_addr_expr (op));
4849 /* Strictly we'd only need the constraint to ESCAPED if
4850 the asm clobbers memory, otherwise using something
4851 along the lines of per-call clobbers/uses would be enough. */
4852 else if (op)
4853 make_escape_constraint (op);
4859 /* Create a constraint adding to the clobber set of FI the memory
4860 pointed to by PTR. */
4862 static void
4863 process_ipa_clobber (varinfo_t fi, tree ptr)
4865 vec<ce_s> ptrc = vNULL;
4866 struct constraint_expr *c, lhs;
4867 unsigned i;
4868 get_constraint_for_rhs (ptr, &ptrc);
4869 lhs = get_function_part_constraint (fi, fi_clobbers);
4870 FOR_EACH_VEC_ELT (ptrc, i, c)
4871 process_constraint (new_constraint (lhs, *c));
4872 ptrc.release ();
4875 /* Walk statement T setting up clobber and use constraints according to the
4876 references found in T. This function is a main part of the
4877 IPA constraint builder. */
4879 static void
4880 find_func_clobbers (struct function *fn, gimple origt)
4882 gimple t = origt;
4883 auto_vec<ce_s, 16> lhsc;
4884 auto_vec<ce_s, 16> rhsc;
4885 varinfo_t fi;
4887 /* Add constraints for clobbered/used in IPA mode.
4888 We are not interested in what automatic variables are clobbered
4889 or used as we only use the information in the caller to which
4890 they do not escape. */
4891 gcc_assert (in_ipa_mode);
4893 /* If the stmt refers to memory in any way it better had a VUSE. */
4894 if (gimple_vuse (t) == NULL_TREE)
4895 return;
4897 /* We'd better have function information for the current function. */
4898 fi = lookup_vi_for_tree (fn->decl);
4899 gcc_assert (fi != NULL);
4901 /* Account for stores in assignments and calls. */
4902 if (gimple_vdef (t) != NULL_TREE
4903 && gimple_has_lhs (t))
4905 tree lhs = gimple_get_lhs (t);
4906 tree tem = lhs;
4907 while (handled_component_p (tem))
4908 tem = TREE_OPERAND (tem, 0);
4909 if ((DECL_P (tem)
4910 && !auto_var_in_fn_p (tem, fn->decl))
4911 || INDIRECT_REF_P (tem)
4912 || (TREE_CODE (tem) == MEM_REF
4913 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4914 && auto_var_in_fn_p
4915 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4917 struct constraint_expr lhsc, *rhsp;
4918 unsigned i;
4919 lhsc = get_function_part_constraint (fi, fi_clobbers);
4920 get_constraint_for_address_of (lhs, &rhsc);
4921 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4922 process_constraint (new_constraint (lhsc, *rhsp));
4923 rhsc.truncate (0);
4927 /* Account for uses in assigments and returns. */
4928 if (gimple_assign_single_p (t)
4929 || (gimple_code (t) == GIMPLE_RETURN
4930 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE))
4932 tree rhs = (gimple_assign_single_p (t)
4933 ? gimple_assign_rhs1 (t)
4934 : gimple_return_retval (as_a <greturn *> (t)));
4935 tree tem = rhs;
4936 while (handled_component_p (tem))
4937 tem = TREE_OPERAND (tem, 0);
4938 if ((DECL_P (tem)
4939 && !auto_var_in_fn_p (tem, fn->decl))
4940 || INDIRECT_REF_P (tem)
4941 || (TREE_CODE (tem) == MEM_REF
4942 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4943 && auto_var_in_fn_p
4944 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4946 struct constraint_expr lhs, *rhsp;
4947 unsigned i;
4948 lhs = get_function_part_constraint (fi, fi_uses);
4949 get_constraint_for_address_of (rhs, &rhsc);
4950 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4951 process_constraint (new_constraint (lhs, *rhsp));
4952 rhsc.truncate (0);
4956 if (gcall *call_stmt = dyn_cast <gcall *> (t))
4958 varinfo_t cfi = NULL;
4959 tree decl = gimple_call_fndecl (t);
4960 struct constraint_expr lhs, rhs;
4961 unsigned i, j;
4963 /* For builtins we do not have separate function info. For those
4964 we do not generate escapes for we have to generate clobbers/uses. */
4965 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4966 switch (DECL_FUNCTION_CODE (decl))
4968 /* The following functions use and clobber memory pointed to
4969 by their arguments. */
4970 case BUILT_IN_STRCPY:
4971 case BUILT_IN_STRNCPY:
4972 case BUILT_IN_BCOPY:
4973 case BUILT_IN_MEMCPY:
4974 case BUILT_IN_MEMMOVE:
4975 case BUILT_IN_MEMPCPY:
4976 case BUILT_IN_STPCPY:
4977 case BUILT_IN_STPNCPY:
4978 case BUILT_IN_STRCAT:
4979 case BUILT_IN_STRNCAT:
4980 case BUILT_IN_STRCPY_CHK:
4981 case BUILT_IN_STRNCPY_CHK:
4982 case BUILT_IN_MEMCPY_CHK:
4983 case BUILT_IN_MEMMOVE_CHK:
4984 case BUILT_IN_MEMPCPY_CHK:
4985 case BUILT_IN_STPCPY_CHK:
4986 case BUILT_IN_STPNCPY_CHK:
4987 case BUILT_IN_STRCAT_CHK:
4988 case BUILT_IN_STRNCAT_CHK:
4990 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4991 == BUILT_IN_BCOPY ? 1 : 0));
4992 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4993 == BUILT_IN_BCOPY ? 0 : 1));
4994 unsigned i;
4995 struct constraint_expr *rhsp, *lhsp;
4996 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4997 lhs = get_function_part_constraint (fi, fi_clobbers);
4998 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4999 process_constraint (new_constraint (lhs, *lhsp));
5000 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
5001 lhs = get_function_part_constraint (fi, fi_uses);
5002 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5003 process_constraint (new_constraint (lhs, *rhsp));
5004 return;
5006 /* The following function clobbers memory pointed to by
5007 its argument. */
5008 case BUILT_IN_MEMSET:
5009 case BUILT_IN_MEMSET_CHK:
5010 case BUILT_IN_POSIX_MEMALIGN:
5012 tree dest = gimple_call_arg (t, 0);
5013 unsigned i;
5014 ce_s *lhsp;
5015 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
5016 lhs = get_function_part_constraint (fi, fi_clobbers);
5017 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5018 process_constraint (new_constraint (lhs, *lhsp));
5019 return;
5021 /* The following functions clobber their second and third
5022 arguments. */
5023 case BUILT_IN_SINCOS:
5024 case BUILT_IN_SINCOSF:
5025 case BUILT_IN_SINCOSL:
5027 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5028 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5029 return;
5031 /* The following functions clobber their second argument. */
5032 case BUILT_IN_FREXP:
5033 case BUILT_IN_FREXPF:
5034 case BUILT_IN_FREXPL:
5035 case BUILT_IN_LGAMMA_R:
5036 case BUILT_IN_LGAMMAF_R:
5037 case BUILT_IN_LGAMMAL_R:
5038 case BUILT_IN_GAMMA_R:
5039 case BUILT_IN_GAMMAF_R:
5040 case BUILT_IN_GAMMAL_R:
5041 case BUILT_IN_MODF:
5042 case BUILT_IN_MODFF:
5043 case BUILT_IN_MODFL:
5045 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5046 return;
5048 /* The following functions clobber their third argument. */
5049 case BUILT_IN_REMQUO:
5050 case BUILT_IN_REMQUOF:
5051 case BUILT_IN_REMQUOL:
5053 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5054 return;
5056 /* The following functions neither read nor clobber memory. */
5057 case BUILT_IN_ASSUME_ALIGNED:
5058 case BUILT_IN_FREE:
5059 return;
5060 /* Trampolines are of no interest to us. */
5061 case BUILT_IN_INIT_TRAMPOLINE:
5062 case BUILT_IN_ADJUST_TRAMPOLINE:
5063 return;
5064 case BUILT_IN_VA_START:
5065 case BUILT_IN_VA_END:
5066 return;
5067 /* printf-style functions may have hooks to set pointers to
5068 point to somewhere into the generated string. Leave them
5069 for a later exercise... */
5070 default:
5071 /* Fallthru to general call handling. */;
5074 /* Parameters passed by value are used. */
5075 lhs = get_function_part_constraint (fi, fi_uses);
5076 for (i = 0; i < gimple_call_num_args (t); i++)
5078 struct constraint_expr *rhsp;
5079 tree arg = gimple_call_arg (t, i);
5081 if (TREE_CODE (arg) == SSA_NAME
5082 || is_gimple_min_invariant (arg))
5083 continue;
5085 get_constraint_for_address_of (arg, &rhsc);
5086 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5087 process_constraint (new_constraint (lhs, *rhsp));
5088 rhsc.truncate (0);
5091 /* Build constraints for propagating clobbers/uses along the
5092 callgraph edges. */
5093 cfi = get_fi_for_callee (call_stmt);
5094 if (cfi->id == anything_id)
5096 if (gimple_vdef (t))
5097 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5098 anything_id);
5099 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5100 anything_id);
5101 return;
5104 /* For callees without function info (that's external functions),
5105 ESCAPED is clobbered and used. */
5106 if (gimple_call_fndecl (t)
5107 && !cfi->is_fn_info)
5109 varinfo_t vi;
5111 if (gimple_vdef (t))
5112 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5113 escaped_id);
5114 make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
5116 /* Also honor the call statement use/clobber info. */
5117 if ((vi = lookup_call_clobber_vi (call_stmt)) != NULL)
5118 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5119 vi->id);
5120 if ((vi = lookup_call_use_vi (call_stmt)) != NULL)
5121 make_copy_constraint (first_vi_for_offset (fi, fi_uses),
5122 vi->id);
5123 return;
5126 /* Otherwise the caller clobbers and uses what the callee does.
5127 ??? This should use a new complex constraint that filters
5128 local variables of the callee. */
5129 if (gimple_vdef (t))
5131 lhs = get_function_part_constraint (fi, fi_clobbers);
5132 rhs = get_function_part_constraint (cfi, fi_clobbers);
5133 process_constraint (new_constraint (lhs, rhs));
5135 lhs = get_function_part_constraint (fi, fi_uses);
5136 rhs = get_function_part_constraint (cfi, fi_uses);
5137 process_constraint (new_constraint (lhs, rhs));
5139 else if (gimple_code (t) == GIMPLE_ASM)
5141 /* ??? Ick. We can do better. */
5142 if (gimple_vdef (t))
5143 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5144 anything_id);
5145 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5146 anything_id);
5151 /* Find the first varinfo in the same variable as START that overlaps with
5152 OFFSET. Return NULL if we can't find one. */
5154 static varinfo_t
5155 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
5157 /* If the offset is outside of the variable, bail out. */
5158 if (offset >= start->fullsize)
5159 return NULL;
5161 /* If we cannot reach offset from start, lookup the first field
5162 and start from there. */
5163 if (start->offset > offset)
5164 start = get_varinfo (start->head);
5166 while (start)
5168 /* We may not find a variable in the field list with the actual
5169 offset when when we have glommed a structure to a variable.
5170 In that case, however, offset should still be within the size
5171 of the variable. */
5172 if (offset >= start->offset
5173 && (offset - start->offset) < start->size)
5174 return start;
5176 start = vi_next (start);
5179 return NULL;
5182 /* Find the first varinfo in the same variable as START that overlaps with
5183 OFFSET. If there is no such varinfo the varinfo directly preceding
5184 OFFSET is returned. */
5186 static varinfo_t
5187 first_or_preceding_vi_for_offset (varinfo_t start,
5188 unsigned HOST_WIDE_INT offset)
5190 /* If we cannot reach offset from start, lookup the first field
5191 and start from there. */
5192 if (start->offset > offset)
5193 start = get_varinfo (start->head);
5195 /* We may not find a variable in the field list with the actual
5196 offset when when we have glommed a structure to a variable.
5197 In that case, however, offset should still be within the size
5198 of the variable.
5199 If we got beyond the offset we look for return the field
5200 directly preceding offset which may be the last field. */
5201 while (start->next
5202 && offset >= start->offset
5203 && !((offset - start->offset) < start->size))
5204 start = vi_next (start);
5206 return start;
5210 /* This structure is used during pushing fields onto the fieldstack
5211 to track the offset of the field, since bitpos_of_field gives it
5212 relative to its immediate containing type, and we want it relative
5213 to the ultimate containing object. */
5215 struct fieldoff
5217 /* Offset from the base of the base containing object to this field. */
5218 HOST_WIDE_INT offset;
5220 /* Size, in bits, of the field. */
5221 unsigned HOST_WIDE_INT size;
5223 unsigned has_unknown_size : 1;
5225 unsigned must_have_pointers : 1;
5227 unsigned may_have_pointers : 1;
5229 unsigned only_restrict_pointers : 1;
5231 typedef struct fieldoff fieldoff_s;
5234 /* qsort comparison function for two fieldoff's PA and PB */
5236 static int
5237 fieldoff_compare (const void *pa, const void *pb)
5239 const fieldoff_s *foa = (const fieldoff_s *)pa;
5240 const fieldoff_s *fob = (const fieldoff_s *)pb;
5241 unsigned HOST_WIDE_INT foasize, fobsize;
5243 if (foa->offset < fob->offset)
5244 return -1;
5245 else if (foa->offset > fob->offset)
5246 return 1;
5248 foasize = foa->size;
5249 fobsize = fob->size;
5250 if (foasize < fobsize)
5251 return -1;
5252 else if (foasize > fobsize)
5253 return 1;
5254 return 0;
5257 /* Sort a fieldstack according to the field offset and sizes. */
5258 static void
5259 sort_fieldstack (vec<fieldoff_s> fieldstack)
5261 fieldstack.qsort (fieldoff_compare);
5264 /* Return true if T is a type that can have subvars. */
5266 static inline bool
5267 type_can_have_subvars (const_tree t)
5269 /* Aggregates without overlapping fields can have subvars. */
5270 return TREE_CODE (t) == RECORD_TYPE;
5273 /* Return true if V is a tree that we can have subvars for.
5274 Normally, this is any aggregate type. Also complex
5275 types which are not gimple registers can have subvars. */
5277 static inline bool
5278 var_can_have_subvars (const_tree v)
5280 /* Volatile variables should never have subvars. */
5281 if (TREE_THIS_VOLATILE (v))
5282 return false;
5284 /* Non decls or memory tags can never have subvars. */
5285 if (!DECL_P (v))
5286 return false;
5288 return type_can_have_subvars (TREE_TYPE (v));
5291 /* Return true if T is a type that does contain pointers. */
5293 static bool
5294 type_must_have_pointers (tree type)
5296 if (POINTER_TYPE_P (type))
5297 return true;
5299 if (TREE_CODE (type) == ARRAY_TYPE)
5300 return type_must_have_pointers (TREE_TYPE (type));
5302 /* A function or method can have pointers as arguments, so track
5303 those separately. */
5304 if (TREE_CODE (type) == FUNCTION_TYPE
5305 || TREE_CODE (type) == METHOD_TYPE)
5306 return true;
5308 return false;
5311 static bool
5312 field_must_have_pointers (tree t)
5314 return type_must_have_pointers (TREE_TYPE (t));
5317 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5318 the fields of TYPE onto fieldstack, recording their offsets along
5319 the way.
5321 OFFSET is used to keep track of the offset in this entire
5322 structure, rather than just the immediately containing structure.
5323 Returns false if the caller is supposed to handle the field we
5324 recursed for. */
5326 static bool
5327 push_fields_onto_fieldstack (tree type, vec<fieldoff_s> *fieldstack,
5328 HOST_WIDE_INT offset)
5330 tree field;
5331 bool empty_p = true;
5333 if (TREE_CODE (type) != RECORD_TYPE)
5334 return false;
5336 /* If the vector of fields is growing too big, bail out early.
5337 Callers check for vec::length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5338 sure this fails. */
5339 if (fieldstack->length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5340 return false;
5342 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5343 if (TREE_CODE (field) == FIELD_DECL)
5345 bool push = false;
5346 HOST_WIDE_INT foff = bitpos_of_field (field);
5348 if (!var_can_have_subvars (field)
5349 || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
5350 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
5351 push = true;
5352 else if (!push_fields_onto_fieldstack
5353 (TREE_TYPE (field), fieldstack, offset + foff)
5354 && (DECL_SIZE (field)
5355 && !integer_zerop (DECL_SIZE (field))))
5356 /* Empty structures may have actual size, like in C++. So
5357 see if we didn't push any subfields and the size is
5358 nonzero, push the field onto the stack. */
5359 push = true;
5361 if (push)
5363 fieldoff_s *pair = NULL;
5364 bool has_unknown_size = false;
5365 bool must_have_pointers_p;
5367 if (!fieldstack->is_empty ())
5368 pair = &fieldstack->last ();
5370 /* If there isn't anything at offset zero, create sth. */
5371 if (!pair
5372 && offset + foff != 0)
5374 fieldoff_s e = {0, offset + foff, false, false, false, false};
5375 pair = fieldstack->safe_push (e);
5378 if (!DECL_SIZE (field)
5379 || !tree_fits_uhwi_p (DECL_SIZE (field)))
5380 has_unknown_size = true;
5382 /* If adjacent fields do not contain pointers merge them. */
5383 must_have_pointers_p = field_must_have_pointers (field);
5384 if (pair
5385 && !has_unknown_size
5386 && !must_have_pointers_p
5387 && !pair->must_have_pointers
5388 && !pair->has_unknown_size
5389 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5391 pair->size += tree_to_uhwi (DECL_SIZE (field));
5393 else
5395 fieldoff_s e;
5396 e.offset = offset + foff;
5397 e.has_unknown_size = has_unknown_size;
5398 if (!has_unknown_size)
5399 e.size = tree_to_uhwi (DECL_SIZE (field));
5400 else
5401 e.size = -1;
5402 e.must_have_pointers = must_have_pointers_p;
5403 e.may_have_pointers = true;
5404 e.only_restrict_pointers
5405 = (!has_unknown_size
5406 && POINTER_TYPE_P (TREE_TYPE (field))
5407 && TYPE_RESTRICT (TREE_TYPE (field)));
5408 fieldstack->safe_push (e);
5412 empty_p = false;
5415 return !empty_p;
5418 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5419 if it is a varargs function. */
5421 static unsigned int
5422 count_num_arguments (tree decl, bool *is_varargs)
5424 unsigned int num = 0;
5425 tree t;
5427 /* Capture named arguments for K&R functions. They do not
5428 have a prototype and thus no TYPE_ARG_TYPES. */
5429 for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5430 ++num;
5432 /* Check if the function has variadic arguments. */
5433 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5434 if (TREE_VALUE (t) == void_type_node)
5435 break;
5436 if (!t)
5437 *is_varargs = true;
5439 return num;
5442 /* Creation function node for DECL, using NAME, and return the index
5443 of the variable we've created for the function. */
5445 static varinfo_t
5446 create_function_info_for (tree decl, const char *name)
5448 struct function *fn = DECL_STRUCT_FUNCTION (decl);
5449 varinfo_t vi, prev_vi;
5450 tree arg;
5451 unsigned int i;
5452 bool is_varargs = false;
5453 unsigned int num_args = count_num_arguments (decl, &is_varargs);
5455 /* Create the variable info. */
5457 vi = new_var_info (decl, name);
5458 vi->offset = 0;
5459 vi->size = 1;
5460 vi->fullsize = fi_parm_base + num_args;
5461 vi->is_fn_info = 1;
5462 vi->may_have_pointers = false;
5463 if (is_varargs)
5464 vi->fullsize = ~0;
5465 insert_vi_for_tree (vi->decl, vi);
5467 prev_vi = vi;
5469 /* Create a variable for things the function clobbers and one for
5470 things the function uses. */
5472 varinfo_t clobbervi, usevi;
5473 const char *newname;
5474 char *tempname;
5476 tempname = xasprintf ("%s.clobber", name);
5477 newname = ggc_strdup (tempname);
5478 free (tempname);
5480 clobbervi = new_var_info (NULL, newname);
5481 clobbervi->offset = fi_clobbers;
5482 clobbervi->size = 1;
5483 clobbervi->fullsize = vi->fullsize;
5484 clobbervi->is_full_var = true;
5485 clobbervi->is_global_var = false;
5486 gcc_assert (prev_vi->offset < clobbervi->offset);
5487 prev_vi->next = clobbervi->id;
5488 prev_vi = clobbervi;
5490 tempname = xasprintf ("%s.use", name);
5491 newname = ggc_strdup (tempname);
5492 free (tempname);
5494 usevi = new_var_info (NULL, newname);
5495 usevi->offset = fi_uses;
5496 usevi->size = 1;
5497 usevi->fullsize = vi->fullsize;
5498 usevi->is_full_var = true;
5499 usevi->is_global_var = false;
5500 gcc_assert (prev_vi->offset < usevi->offset);
5501 prev_vi->next = usevi->id;
5502 prev_vi = usevi;
5505 /* And one for the static chain. */
5506 if (fn->static_chain_decl != NULL_TREE)
5508 varinfo_t chainvi;
5509 const char *newname;
5510 char *tempname;
5512 tempname = xasprintf ("%s.chain", name);
5513 newname = ggc_strdup (tempname);
5514 free (tempname);
5516 chainvi = new_var_info (fn->static_chain_decl, newname);
5517 chainvi->offset = fi_static_chain;
5518 chainvi->size = 1;
5519 chainvi->fullsize = vi->fullsize;
5520 chainvi->is_full_var = true;
5521 chainvi->is_global_var = false;
5522 gcc_assert (prev_vi->offset < chainvi->offset);
5523 prev_vi->next = chainvi->id;
5524 prev_vi = chainvi;
5525 insert_vi_for_tree (fn->static_chain_decl, chainvi);
5528 /* Create a variable for the return var. */
5529 if (DECL_RESULT (decl) != NULL
5530 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5532 varinfo_t resultvi;
5533 const char *newname;
5534 char *tempname;
5535 tree resultdecl = decl;
5537 if (DECL_RESULT (decl))
5538 resultdecl = DECL_RESULT (decl);
5540 tempname = xasprintf ("%s.result", name);
5541 newname = ggc_strdup (tempname);
5542 free (tempname);
5544 resultvi = new_var_info (resultdecl, newname);
5545 resultvi->offset = fi_result;
5546 resultvi->size = 1;
5547 resultvi->fullsize = vi->fullsize;
5548 resultvi->is_full_var = true;
5549 if (DECL_RESULT (decl))
5550 resultvi->may_have_pointers = true;
5551 gcc_assert (prev_vi->offset < resultvi->offset);
5552 prev_vi->next = resultvi->id;
5553 prev_vi = resultvi;
5554 if (DECL_RESULT (decl))
5555 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5558 /* Set up variables for each argument. */
5559 arg = DECL_ARGUMENTS (decl);
5560 for (i = 0; i < num_args; i++)
5562 varinfo_t argvi;
5563 const char *newname;
5564 char *tempname;
5565 tree argdecl = decl;
5567 if (arg)
5568 argdecl = arg;
5570 tempname = xasprintf ("%s.arg%d", name, i);
5571 newname = ggc_strdup (tempname);
5572 free (tempname);
5574 argvi = new_var_info (argdecl, newname);
5575 argvi->offset = fi_parm_base + i;
5576 argvi->size = 1;
5577 argvi->is_full_var = true;
5578 argvi->fullsize = vi->fullsize;
5579 if (arg)
5580 argvi->may_have_pointers = true;
5581 gcc_assert (prev_vi->offset < argvi->offset);
5582 prev_vi->next = argvi->id;
5583 prev_vi = argvi;
5584 if (arg)
5586 insert_vi_for_tree (arg, argvi);
5587 arg = DECL_CHAIN (arg);
5591 /* Add one representative for all further args. */
5592 if (is_varargs)
5594 varinfo_t argvi;
5595 const char *newname;
5596 char *tempname;
5597 tree decl;
5599 tempname = xasprintf ("%s.varargs", name);
5600 newname = ggc_strdup (tempname);
5601 free (tempname);
5603 /* We need sth that can be pointed to for va_start. */
5604 decl = build_fake_var_decl (ptr_type_node);
5606 argvi = new_var_info (decl, newname);
5607 argvi->offset = fi_parm_base + num_args;
5608 argvi->size = ~0;
5609 argvi->is_full_var = true;
5610 argvi->is_heap_var = true;
5611 argvi->fullsize = vi->fullsize;
5612 gcc_assert (prev_vi->offset < argvi->offset);
5613 prev_vi->next = argvi->id;
5614 prev_vi = argvi;
5617 return vi;
5621 /* Return true if FIELDSTACK contains fields that overlap.
5622 FIELDSTACK is assumed to be sorted by offset. */
5624 static bool
5625 check_for_overlaps (vec<fieldoff_s> fieldstack)
5627 fieldoff_s *fo = NULL;
5628 unsigned int i;
5629 HOST_WIDE_INT lastoffset = -1;
5631 FOR_EACH_VEC_ELT (fieldstack, i, fo)
5633 if (fo->offset == lastoffset)
5634 return true;
5635 lastoffset = fo->offset;
5637 return false;
5640 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5641 This will also create any varinfo structures necessary for fields
5642 of DECL. */
5644 static varinfo_t
5645 create_variable_info_for_1 (tree decl, const char *name)
5647 varinfo_t vi, newvi;
5648 tree decl_type = TREE_TYPE (decl);
5649 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5650 auto_vec<fieldoff_s> fieldstack;
5651 fieldoff_s *fo;
5652 unsigned int i;
5654 if (!declsize
5655 || !tree_fits_uhwi_p (declsize))
5657 vi = new_var_info (decl, name);
5658 vi->offset = 0;
5659 vi->size = ~0;
5660 vi->fullsize = ~0;
5661 vi->is_unknown_size_var = true;
5662 vi->is_full_var = true;
5663 vi->may_have_pointers = true;
5664 return vi;
5667 /* Collect field information. */
5668 if (use_field_sensitive
5669 && var_can_have_subvars (decl)
5670 /* ??? Force us to not use subfields for globals in IPA mode.
5671 Else we'd have to parse arbitrary initializers. */
5672 && !(in_ipa_mode
5673 && is_global_var (decl)))
5675 fieldoff_s *fo = NULL;
5676 bool notokay = false;
5677 unsigned int i;
5679 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5681 for (i = 0; !notokay && fieldstack.iterate (i, &fo); i++)
5682 if (fo->has_unknown_size
5683 || fo->offset < 0)
5685 notokay = true;
5686 break;
5689 /* We can't sort them if we have a field with a variable sized type,
5690 which will make notokay = true. In that case, we are going to return
5691 without creating varinfos for the fields anyway, so sorting them is a
5692 waste to boot. */
5693 if (!notokay)
5695 sort_fieldstack (fieldstack);
5696 /* Due to some C++ FE issues, like PR 22488, we might end up
5697 what appear to be overlapping fields even though they,
5698 in reality, do not overlap. Until the C++ FE is fixed,
5699 we will simply disable field-sensitivity for these cases. */
5700 notokay = check_for_overlaps (fieldstack);
5703 if (notokay)
5704 fieldstack.release ();
5707 /* If we didn't end up collecting sub-variables create a full
5708 variable for the decl. */
5709 if (fieldstack.length () <= 1
5710 || fieldstack.length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5712 vi = new_var_info (decl, name);
5713 vi->offset = 0;
5714 vi->may_have_pointers = true;
5715 vi->fullsize = tree_to_uhwi (declsize);
5716 vi->size = vi->fullsize;
5717 vi->is_full_var = true;
5718 fieldstack.release ();
5719 return vi;
5722 vi = new_var_info (decl, name);
5723 vi->fullsize = tree_to_uhwi (declsize);
5724 for (i = 0, newvi = vi;
5725 fieldstack.iterate (i, &fo);
5726 ++i, newvi = vi_next (newvi))
5728 const char *newname = "NULL";
5729 char *tempname;
5731 if (dump_file)
5733 tempname
5734 = xasprintf ("%s." HOST_WIDE_INT_PRINT_DEC
5735 "+" HOST_WIDE_INT_PRINT_DEC, name,
5736 fo->offset, fo->size);
5737 newname = ggc_strdup (tempname);
5738 free (tempname);
5740 newvi->name = newname;
5741 newvi->offset = fo->offset;
5742 newvi->size = fo->size;
5743 newvi->fullsize = vi->fullsize;
5744 newvi->may_have_pointers = fo->may_have_pointers;
5745 newvi->only_restrict_pointers = fo->only_restrict_pointers;
5746 if (i + 1 < fieldstack.length ())
5748 varinfo_t tem = new_var_info (decl, name);
5749 newvi->next = tem->id;
5750 tem->head = vi->id;
5754 return vi;
5757 static unsigned int
5758 create_variable_info_for (tree decl, const char *name)
5760 varinfo_t vi = create_variable_info_for_1 (decl, name);
5761 unsigned int id = vi->id;
5763 insert_vi_for_tree (decl, vi);
5765 if (TREE_CODE (decl) != VAR_DECL)
5766 return id;
5768 /* Create initial constraints for globals. */
5769 for (; vi; vi = vi_next (vi))
5771 if (!vi->may_have_pointers
5772 || !vi->is_global_var)
5773 continue;
5775 /* Mark global restrict qualified pointers. */
5776 if ((POINTER_TYPE_P (TREE_TYPE (decl))
5777 && TYPE_RESTRICT (TREE_TYPE (decl)))
5778 || vi->only_restrict_pointers)
5780 varinfo_t rvi
5781 = make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5782 /* ??? For now exclude reads from globals as restrict sources
5783 if those are not (indirectly) from incoming parameters. */
5784 rvi->is_restrict_var = false;
5785 continue;
5788 /* In non-IPA mode the initializer from nonlocal is all we need. */
5789 if (!in_ipa_mode
5790 || DECL_HARD_REGISTER (decl))
5791 make_copy_constraint (vi, nonlocal_id);
5793 /* In IPA mode parse the initializer and generate proper constraints
5794 for it. */
5795 else
5797 varpool_node *vnode = varpool_node::get (decl);
5799 /* For escaped variables initialize them from nonlocal. */
5800 if (!vnode->all_refs_explicit_p ())
5801 make_copy_constraint (vi, nonlocal_id);
5803 /* If this is a global variable with an initializer and we are in
5804 IPA mode generate constraints for it. */
5805 ipa_ref *ref;
5806 for (unsigned idx = 0; vnode->iterate_reference (idx, ref); ++idx)
5808 auto_vec<ce_s> rhsc;
5809 struct constraint_expr lhs, *rhsp;
5810 unsigned i;
5811 get_constraint_for_address_of (ref->referred->decl, &rhsc);
5812 lhs.var = vi->id;
5813 lhs.offset = 0;
5814 lhs.type = SCALAR;
5815 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5816 process_constraint (new_constraint (lhs, *rhsp));
5817 /* If this is a variable that escapes from the unit
5818 the initializer escapes as well. */
5819 if (!vnode->all_refs_explicit_p ())
5821 lhs.var = escaped_id;
5822 lhs.offset = 0;
5823 lhs.type = SCALAR;
5824 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5825 process_constraint (new_constraint (lhs, *rhsp));
5831 return id;
5834 /* Print out the points-to solution for VAR to FILE. */
5836 static void
5837 dump_solution_for_var (FILE *file, unsigned int var)
5839 varinfo_t vi = get_varinfo (var);
5840 unsigned int i;
5841 bitmap_iterator bi;
5843 /* Dump the solution for unified vars anyway, this avoids difficulties
5844 in scanning dumps in the testsuite. */
5845 fprintf (file, "%s = { ", vi->name);
5846 vi = get_varinfo (find (var));
5847 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5848 fprintf (file, "%s ", get_varinfo (i)->name);
5849 fprintf (file, "}");
5851 /* But note when the variable was unified. */
5852 if (vi->id != var)
5853 fprintf (file, " same as %s", vi->name);
5855 fprintf (file, "\n");
5858 /* Print the points-to solution for VAR to stderr. */
5860 DEBUG_FUNCTION void
5861 debug_solution_for_var (unsigned int var)
5863 dump_solution_for_var (stderr, var);
5866 /* Create varinfo structures for all of the variables in the
5867 function for intraprocedural mode. */
5869 static void
5870 intra_create_variable_infos (struct function *fn)
5872 tree t;
5874 /* For each incoming pointer argument arg, create the constraint ARG
5875 = NONLOCAL or a dummy variable if it is a restrict qualified
5876 passed-by-reference argument. */
5877 for (t = DECL_ARGUMENTS (fn->decl); t; t = DECL_CHAIN (t))
5879 varinfo_t p = get_vi_for_tree (t);
5881 /* For restrict qualified pointers to objects passed by
5882 reference build a real representative for the pointed-to object.
5883 Treat restrict qualified references the same. */
5884 if (TYPE_RESTRICT (TREE_TYPE (t))
5885 && ((DECL_BY_REFERENCE (t) && POINTER_TYPE_P (TREE_TYPE (t)))
5886 || TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
5887 && !type_contains_placeholder_p (TREE_TYPE (TREE_TYPE (t))))
5889 struct constraint_expr lhsc, rhsc;
5890 varinfo_t vi;
5891 tree heapvar = build_fake_var_decl (TREE_TYPE (TREE_TYPE (t)));
5892 DECL_EXTERNAL (heapvar) = 1;
5893 vi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS");
5894 vi->is_restrict_var = 1;
5895 insert_vi_for_tree (heapvar, vi);
5896 lhsc.var = p->id;
5897 lhsc.type = SCALAR;
5898 lhsc.offset = 0;
5899 rhsc.var = vi->id;
5900 rhsc.type = ADDRESSOF;
5901 rhsc.offset = 0;
5902 process_constraint (new_constraint (lhsc, rhsc));
5903 for (; vi; vi = vi_next (vi))
5904 if (vi->may_have_pointers)
5906 if (vi->only_restrict_pointers)
5907 make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5908 else
5909 make_copy_constraint (vi, nonlocal_id);
5911 continue;
5914 if (POINTER_TYPE_P (TREE_TYPE (t))
5915 && TYPE_RESTRICT (TREE_TYPE (t)))
5916 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5917 else
5919 for (; p; p = vi_next (p))
5921 if (p->only_restrict_pointers)
5922 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5923 else if (p->may_have_pointers)
5924 make_constraint_from (p, nonlocal_id);
5929 /* Add a constraint for a result decl that is passed by reference. */
5930 if (DECL_RESULT (fn->decl)
5931 && DECL_BY_REFERENCE (DECL_RESULT (fn->decl)))
5933 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (fn->decl));
5935 for (p = result_vi; p; p = vi_next (p))
5936 make_constraint_from (p, nonlocal_id);
5939 /* Add a constraint for the incoming static chain parameter. */
5940 if (fn->static_chain_decl != NULL_TREE)
5942 varinfo_t p, chain_vi = get_vi_for_tree (fn->static_chain_decl);
5944 for (p = chain_vi; p; p = vi_next (p))
5945 make_constraint_from (p, nonlocal_id);
5949 /* Structure used to put solution bitmaps in a hashtable so they can
5950 be shared among variables with the same points-to set. */
5952 typedef struct shared_bitmap_info
5954 bitmap pt_vars;
5955 hashval_t hashcode;
5956 } *shared_bitmap_info_t;
5957 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5959 /* Shared_bitmap hashtable helpers. */
5961 struct shared_bitmap_hasher : typed_free_remove <shared_bitmap_info>
5963 typedef shared_bitmap_info value_type;
5964 typedef shared_bitmap_info compare_type;
5965 static inline hashval_t hash (const value_type *);
5966 static inline bool equal (const value_type *, const compare_type *);
5969 /* Hash function for a shared_bitmap_info_t */
5971 inline hashval_t
5972 shared_bitmap_hasher::hash (const value_type *bi)
5974 return bi->hashcode;
5977 /* Equality function for two shared_bitmap_info_t's. */
5979 inline bool
5980 shared_bitmap_hasher::equal (const value_type *sbi1, const compare_type *sbi2)
5982 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
5985 /* Shared_bitmap hashtable. */
5987 static hash_table<shared_bitmap_hasher> *shared_bitmap_table;
5989 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
5990 existing instance if there is one, NULL otherwise. */
5992 static bitmap
5993 shared_bitmap_lookup (bitmap pt_vars)
5995 shared_bitmap_info **slot;
5996 struct shared_bitmap_info sbi;
5998 sbi.pt_vars = pt_vars;
5999 sbi.hashcode = bitmap_hash (pt_vars);
6001 slot = shared_bitmap_table->find_slot (&sbi, NO_INSERT);
6002 if (!slot)
6003 return NULL;
6004 else
6005 return (*slot)->pt_vars;
6009 /* Add a bitmap to the shared bitmap hashtable. */
6011 static void
6012 shared_bitmap_add (bitmap pt_vars)
6014 shared_bitmap_info **slot;
6015 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
6017 sbi->pt_vars = pt_vars;
6018 sbi->hashcode = bitmap_hash (pt_vars);
6020 slot = shared_bitmap_table->find_slot (sbi, INSERT);
6021 gcc_assert (!*slot);
6022 *slot = sbi;
6026 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
6028 static void
6029 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
6031 unsigned int i;
6032 bitmap_iterator bi;
6033 varinfo_t escaped_vi = get_varinfo (find (escaped_id));
6034 bool everything_escaped
6035 = escaped_vi->solution && bitmap_bit_p (escaped_vi->solution, anything_id);
6037 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
6039 varinfo_t vi = get_varinfo (i);
6041 /* The only artificial variables that are allowed in a may-alias
6042 set are heap variables. */
6043 if (vi->is_artificial_var && !vi->is_heap_var)
6044 continue;
6046 if (everything_escaped
6047 || (escaped_vi->solution
6048 && bitmap_bit_p (escaped_vi->solution, i)))
6050 pt->vars_contains_escaped = true;
6051 pt->vars_contains_escaped_heap = vi->is_heap_var;
6054 if (TREE_CODE (vi->decl) == VAR_DECL
6055 || TREE_CODE (vi->decl) == PARM_DECL
6056 || TREE_CODE (vi->decl) == RESULT_DECL)
6058 /* If we are in IPA mode we will not recompute points-to
6059 sets after inlining so make sure they stay valid. */
6060 if (in_ipa_mode
6061 && !DECL_PT_UID_SET_P (vi->decl))
6062 SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
6064 /* Add the decl to the points-to set. Note that the points-to
6065 set contains global variables. */
6066 bitmap_set_bit (into, DECL_PT_UID (vi->decl));
6067 if (vi->is_global_var)
6068 pt->vars_contains_nonlocal = true;
6074 /* Compute the points-to solution *PT for the variable VI. */
6076 static struct pt_solution
6077 find_what_var_points_to (varinfo_t orig_vi)
6079 unsigned int i;
6080 bitmap_iterator bi;
6081 bitmap finished_solution;
6082 bitmap result;
6083 varinfo_t vi;
6084 struct pt_solution *pt;
6086 /* This variable may have been collapsed, let's get the real
6087 variable. */
6088 vi = get_varinfo (find (orig_vi->id));
6090 /* See if we have already computed the solution and return it. */
6091 pt_solution **slot = &final_solutions->get_or_insert (vi);
6092 if (*slot != NULL)
6093 return **slot;
6095 *slot = pt = XOBNEW (&final_solutions_obstack, struct pt_solution);
6096 memset (pt, 0, sizeof (struct pt_solution));
6098 /* Translate artificial variables into SSA_NAME_PTR_INFO
6099 attributes. */
6100 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6102 varinfo_t vi = get_varinfo (i);
6104 if (vi->is_artificial_var)
6106 if (vi->id == nothing_id)
6107 pt->null = 1;
6108 else if (vi->id == escaped_id)
6110 if (in_ipa_mode)
6111 pt->ipa_escaped = 1;
6112 else
6113 pt->escaped = 1;
6114 /* Expand some special vars of ESCAPED in-place here. */
6115 varinfo_t evi = get_varinfo (find (escaped_id));
6116 if (bitmap_bit_p (evi->solution, nonlocal_id))
6117 pt->nonlocal = 1;
6119 else if (vi->id == nonlocal_id)
6120 pt->nonlocal = 1;
6121 else if (vi->is_heap_var)
6122 /* We represent heapvars in the points-to set properly. */
6124 else if (vi->id == string_id)
6125 /* Nobody cares - STRING_CSTs are read-only entities. */
6127 else if (vi->id == anything_id
6128 || vi->id == integer_id)
6129 pt->anything = 1;
6133 /* Instead of doing extra work, simply do not create
6134 elaborate points-to information for pt_anything pointers. */
6135 if (pt->anything)
6136 return *pt;
6138 /* Share the final set of variables when possible. */
6139 finished_solution = BITMAP_GGC_ALLOC ();
6140 stats.points_to_sets_created++;
6142 set_uids_in_ptset (finished_solution, vi->solution, pt);
6143 result = shared_bitmap_lookup (finished_solution);
6144 if (!result)
6146 shared_bitmap_add (finished_solution);
6147 pt->vars = finished_solution;
6149 else
6151 pt->vars = result;
6152 bitmap_clear (finished_solution);
6155 return *pt;
6158 /* Given a pointer variable P, fill in its points-to set. */
6160 static void
6161 find_what_p_points_to (tree p)
6163 struct ptr_info_def *pi;
6164 tree lookup_p = p;
6165 varinfo_t vi;
6167 /* For parameters, get at the points-to set for the actual parm
6168 decl. */
6169 if (TREE_CODE (p) == SSA_NAME
6170 && SSA_NAME_IS_DEFAULT_DEF (p)
6171 && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
6172 || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL))
6173 lookup_p = SSA_NAME_VAR (p);
6175 vi = lookup_vi_for_tree (lookup_p);
6176 if (!vi)
6177 return;
6179 pi = get_ptr_info (p);
6180 pi->pt = find_what_var_points_to (vi);
6184 /* Query statistics for points-to solutions. */
6186 static struct {
6187 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
6188 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
6189 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
6190 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
6191 } pta_stats;
6193 void
6194 dump_pta_stats (FILE *s)
6196 fprintf (s, "\nPTA query stats:\n");
6197 fprintf (s, " pt_solution_includes: "
6198 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6199 HOST_WIDE_INT_PRINT_DEC" queries\n",
6200 pta_stats.pt_solution_includes_no_alias,
6201 pta_stats.pt_solution_includes_no_alias
6202 + pta_stats.pt_solution_includes_may_alias);
6203 fprintf (s, " pt_solutions_intersect: "
6204 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6205 HOST_WIDE_INT_PRINT_DEC" queries\n",
6206 pta_stats.pt_solutions_intersect_no_alias,
6207 pta_stats.pt_solutions_intersect_no_alias
6208 + pta_stats.pt_solutions_intersect_may_alias);
6212 /* Reset the points-to solution *PT to a conservative default
6213 (point to anything). */
6215 void
6216 pt_solution_reset (struct pt_solution *pt)
6218 memset (pt, 0, sizeof (struct pt_solution));
6219 pt->anything = true;
6222 /* Set the points-to solution *PT to point only to the variables
6223 in VARS. VARS_CONTAINS_GLOBAL specifies whether that contains
6224 global variables and VARS_CONTAINS_RESTRICT specifies whether
6225 it contains restrict tag variables. */
6227 void
6228 pt_solution_set (struct pt_solution *pt, bitmap vars,
6229 bool vars_contains_nonlocal)
6231 memset (pt, 0, sizeof (struct pt_solution));
6232 pt->vars = vars;
6233 pt->vars_contains_nonlocal = vars_contains_nonlocal;
6234 pt->vars_contains_escaped
6235 = (cfun->gimple_df->escaped.anything
6236 || bitmap_intersect_p (cfun->gimple_df->escaped.vars, vars));
6239 /* Set the points-to solution *PT to point only to the variable VAR. */
6241 void
6242 pt_solution_set_var (struct pt_solution *pt, tree var)
6244 memset (pt, 0, sizeof (struct pt_solution));
6245 pt->vars = BITMAP_GGC_ALLOC ();
6246 bitmap_set_bit (pt->vars, DECL_PT_UID (var));
6247 pt->vars_contains_nonlocal = is_global_var (var);
6248 pt->vars_contains_escaped
6249 = (cfun->gimple_df->escaped.anything
6250 || bitmap_bit_p (cfun->gimple_df->escaped.vars, DECL_PT_UID (var)));
6253 /* Computes the union of the points-to solutions *DEST and *SRC and
6254 stores the result in *DEST. This changes the points-to bitmap
6255 of *DEST and thus may not be used if that might be shared.
6256 The points-to bitmap of *SRC and *DEST will not be shared after
6257 this function if they were not before. */
6259 static void
6260 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
6262 dest->anything |= src->anything;
6263 if (dest->anything)
6265 pt_solution_reset (dest);
6266 return;
6269 dest->nonlocal |= src->nonlocal;
6270 dest->escaped |= src->escaped;
6271 dest->ipa_escaped |= src->ipa_escaped;
6272 dest->null |= src->null;
6273 dest->vars_contains_nonlocal |= src->vars_contains_nonlocal;
6274 dest->vars_contains_escaped |= src->vars_contains_escaped;
6275 dest->vars_contains_escaped_heap |= src->vars_contains_escaped_heap;
6276 if (!src->vars)
6277 return;
6279 if (!dest->vars)
6280 dest->vars = BITMAP_GGC_ALLOC ();
6281 bitmap_ior_into (dest->vars, src->vars);
6284 /* Return true if the points-to solution *PT is empty. */
6286 bool
6287 pt_solution_empty_p (struct pt_solution *pt)
6289 if (pt->anything
6290 || pt->nonlocal)
6291 return false;
6293 if (pt->vars
6294 && !bitmap_empty_p (pt->vars))
6295 return false;
6297 /* If the solution includes ESCAPED, check if that is empty. */
6298 if (pt->escaped
6299 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6300 return false;
6302 /* If the solution includes ESCAPED, check if that is empty. */
6303 if (pt->ipa_escaped
6304 && !pt_solution_empty_p (&ipa_escaped_pt))
6305 return false;
6307 return true;
6310 /* Return true if the points-to solution *PT only point to a single var, and
6311 return the var uid in *UID. */
6313 bool
6314 pt_solution_singleton_p (struct pt_solution *pt, unsigned *uid)
6316 if (pt->anything || pt->nonlocal || pt->escaped || pt->ipa_escaped
6317 || pt->null || pt->vars == NULL
6318 || !bitmap_single_bit_set_p (pt->vars))
6319 return false;
6321 *uid = bitmap_first_set_bit (pt->vars);
6322 return true;
6325 /* Return true if the points-to solution *PT includes global memory. */
6327 bool
6328 pt_solution_includes_global (struct pt_solution *pt)
6330 if (pt->anything
6331 || pt->nonlocal
6332 || pt->vars_contains_nonlocal
6333 /* The following is a hack to make the malloc escape hack work.
6334 In reality we'd need different sets for escaped-through-return
6335 and escaped-to-callees and passes would need to be updated. */
6336 || pt->vars_contains_escaped_heap)
6337 return true;
6339 /* 'escaped' is also a placeholder so we have to look into it. */
6340 if (pt->escaped)
6341 return pt_solution_includes_global (&cfun->gimple_df->escaped);
6343 if (pt->ipa_escaped)
6344 return pt_solution_includes_global (&ipa_escaped_pt);
6346 /* ??? This predicate is not correct for the IPA-PTA solution
6347 as we do not properly distinguish between unit escape points
6348 and global variables. */
6349 if (cfun->gimple_df->ipa_pta)
6350 return true;
6352 return false;
6355 /* Return true if the points-to solution *PT includes the variable
6356 declaration DECL. */
6358 static bool
6359 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6361 if (pt->anything)
6362 return true;
6364 if (pt->nonlocal
6365 && is_global_var (decl))
6366 return true;
6368 if (pt->vars
6369 && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6370 return true;
6372 /* If the solution includes ESCAPED, check it. */
6373 if (pt->escaped
6374 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6375 return true;
6377 /* If the solution includes ESCAPED, check it. */
6378 if (pt->ipa_escaped
6379 && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6380 return true;
6382 return false;
6385 bool
6386 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6388 bool res = pt_solution_includes_1 (pt, decl);
6389 if (res)
6390 ++pta_stats.pt_solution_includes_may_alias;
6391 else
6392 ++pta_stats.pt_solution_includes_no_alias;
6393 return res;
6396 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6397 intersection. */
6399 static bool
6400 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6402 if (pt1->anything || pt2->anything)
6403 return true;
6405 /* If either points to unknown global memory and the other points to
6406 any global memory they alias. */
6407 if ((pt1->nonlocal
6408 && (pt2->nonlocal
6409 || pt2->vars_contains_nonlocal))
6410 || (pt2->nonlocal
6411 && pt1->vars_contains_nonlocal))
6412 return true;
6414 /* If either points to all escaped memory and the other points to
6415 any escaped memory they alias. */
6416 if ((pt1->escaped
6417 && (pt2->escaped
6418 || pt2->vars_contains_escaped))
6419 || (pt2->escaped
6420 && pt1->vars_contains_escaped))
6421 return true;
6423 /* Check the escaped solution if required.
6424 ??? Do we need to check the local against the IPA escaped sets? */
6425 if ((pt1->ipa_escaped || pt2->ipa_escaped)
6426 && !pt_solution_empty_p (&ipa_escaped_pt))
6428 /* If both point to escaped memory and that solution
6429 is not empty they alias. */
6430 if (pt1->ipa_escaped && pt2->ipa_escaped)
6431 return true;
6433 /* If either points to escaped memory see if the escaped solution
6434 intersects with the other. */
6435 if ((pt1->ipa_escaped
6436 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6437 || (pt2->ipa_escaped
6438 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6439 return true;
6442 /* Now both pointers alias if their points-to solution intersects. */
6443 return (pt1->vars
6444 && pt2->vars
6445 && bitmap_intersect_p (pt1->vars, pt2->vars));
6448 bool
6449 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6451 bool res = pt_solutions_intersect_1 (pt1, pt2);
6452 if (res)
6453 ++pta_stats.pt_solutions_intersect_may_alias;
6454 else
6455 ++pta_stats.pt_solutions_intersect_no_alias;
6456 return res;
6460 /* Dump points-to information to OUTFILE. */
6462 static void
6463 dump_sa_points_to_info (FILE *outfile)
6465 unsigned int i;
6467 fprintf (outfile, "\nPoints-to sets\n\n");
6469 if (dump_flags & TDF_STATS)
6471 fprintf (outfile, "Stats:\n");
6472 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
6473 fprintf (outfile, "Non-pointer vars: %d\n",
6474 stats.nonpointer_vars);
6475 fprintf (outfile, "Statically unified vars: %d\n",
6476 stats.unified_vars_static);
6477 fprintf (outfile, "Dynamically unified vars: %d\n",
6478 stats.unified_vars_dynamic);
6479 fprintf (outfile, "Iterations: %d\n", stats.iterations);
6480 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
6481 fprintf (outfile, "Number of implicit edges: %d\n",
6482 stats.num_implicit_edges);
6485 for (i = 1; i < varmap.length (); i++)
6487 varinfo_t vi = get_varinfo (i);
6488 if (!vi->may_have_pointers)
6489 continue;
6490 dump_solution_for_var (outfile, i);
6495 /* Debug points-to information to stderr. */
6497 DEBUG_FUNCTION void
6498 debug_sa_points_to_info (void)
6500 dump_sa_points_to_info (stderr);
6504 /* Initialize the always-existing constraint variables for NULL
6505 ANYTHING, READONLY, and INTEGER */
6507 static void
6508 init_base_vars (void)
6510 struct constraint_expr lhs, rhs;
6511 varinfo_t var_anything;
6512 varinfo_t var_nothing;
6513 varinfo_t var_string;
6514 varinfo_t var_escaped;
6515 varinfo_t var_nonlocal;
6516 varinfo_t var_storedanything;
6517 varinfo_t var_integer;
6519 /* Variable ID zero is reserved and should be NULL. */
6520 varmap.safe_push (NULL);
6522 /* Create the NULL variable, used to represent that a variable points
6523 to NULL. */
6524 var_nothing = new_var_info (NULL_TREE, "NULL");
6525 gcc_assert (var_nothing->id == nothing_id);
6526 var_nothing->is_artificial_var = 1;
6527 var_nothing->offset = 0;
6528 var_nothing->size = ~0;
6529 var_nothing->fullsize = ~0;
6530 var_nothing->is_special_var = 1;
6531 var_nothing->may_have_pointers = 0;
6532 var_nothing->is_global_var = 0;
6534 /* Create the ANYTHING variable, used to represent that a variable
6535 points to some unknown piece of memory. */
6536 var_anything = new_var_info (NULL_TREE, "ANYTHING");
6537 gcc_assert (var_anything->id == anything_id);
6538 var_anything->is_artificial_var = 1;
6539 var_anything->size = ~0;
6540 var_anything->offset = 0;
6541 var_anything->fullsize = ~0;
6542 var_anything->is_special_var = 1;
6544 /* Anything points to anything. This makes deref constraints just
6545 work in the presence of linked list and other p = *p type loops,
6546 by saying that *ANYTHING = ANYTHING. */
6547 lhs.type = SCALAR;
6548 lhs.var = anything_id;
6549 lhs.offset = 0;
6550 rhs.type = ADDRESSOF;
6551 rhs.var = anything_id;
6552 rhs.offset = 0;
6554 /* This specifically does not use process_constraint because
6555 process_constraint ignores all anything = anything constraints, since all
6556 but this one are redundant. */
6557 constraints.safe_push (new_constraint (lhs, rhs));
6559 /* Create the STRING variable, used to represent that a variable
6560 points to a string literal. String literals don't contain
6561 pointers so STRING doesn't point to anything. */
6562 var_string = new_var_info (NULL_TREE, "STRING");
6563 gcc_assert (var_string->id == string_id);
6564 var_string->is_artificial_var = 1;
6565 var_string->offset = 0;
6566 var_string->size = ~0;
6567 var_string->fullsize = ~0;
6568 var_string->is_special_var = 1;
6569 var_string->may_have_pointers = 0;
6571 /* Create the ESCAPED variable, used to represent the set of escaped
6572 memory. */
6573 var_escaped = new_var_info (NULL_TREE, "ESCAPED");
6574 gcc_assert (var_escaped->id == escaped_id);
6575 var_escaped->is_artificial_var = 1;
6576 var_escaped->offset = 0;
6577 var_escaped->size = ~0;
6578 var_escaped->fullsize = ~0;
6579 var_escaped->is_special_var = 0;
6581 /* Create the NONLOCAL variable, used to represent the set of nonlocal
6582 memory. */
6583 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
6584 gcc_assert (var_nonlocal->id == nonlocal_id);
6585 var_nonlocal->is_artificial_var = 1;
6586 var_nonlocal->offset = 0;
6587 var_nonlocal->size = ~0;
6588 var_nonlocal->fullsize = ~0;
6589 var_nonlocal->is_special_var = 1;
6591 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
6592 lhs.type = SCALAR;
6593 lhs.var = escaped_id;
6594 lhs.offset = 0;
6595 rhs.type = DEREF;
6596 rhs.var = escaped_id;
6597 rhs.offset = 0;
6598 process_constraint (new_constraint (lhs, rhs));
6600 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6601 whole variable escapes. */
6602 lhs.type = SCALAR;
6603 lhs.var = escaped_id;
6604 lhs.offset = 0;
6605 rhs.type = SCALAR;
6606 rhs.var = escaped_id;
6607 rhs.offset = UNKNOWN_OFFSET;
6608 process_constraint (new_constraint (lhs, rhs));
6610 /* *ESCAPED = NONLOCAL. This is true because we have to assume
6611 everything pointed to by escaped points to what global memory can
6612 point to. */
6613 lhs.type = DEREF;
6614 lhs.var = escaped_id;
6615 lhs.offset = 0;
6616 rhs.type = SCALAR;
6617 rhs.var = nonlocal_id;
6618 rhs.offset = 0;
6619 process_constraint (new_constraint (lhs, rhs));
6621 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
6622 global memory may point to global memory and escaped memory. */
6623 lhs.type = SCALAR;
6624 lhs.var = nonlocal_id;
6625 lhs.offset = 0;
6626 rhs.type = ADDRESSOF;
6627 rhs.var = nonlocal_id;
6628 rhs.offset = 0;
6629 process_constraint (new_constraint (lhs, rhs));
6630 rhs.type = ADDRESSOF;
6631 rhs.var = escaped_id;
6632 rhs.offset = 0;
6633 process_constraint (new_constraint (lhs, rhs));
6635 /* Create the STOREDANYTHING variable, used to represent the set of
6636 variables stored to *ANYTHING. */
6637 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
6638 gcc_assert (var_storedanything->id == storedanything_id);
6639 var_storedanything->is_artificial_var = 1;
6640 var_storedanything->offset = 0;
6641 var_storedanything->size = ~0;
6642 var_storedanything->fullsize = ~0;
6643 var_storedanything->is_special_var = 0;
6645 /* Create the INTEGER variable, used to represent that a variable points
6646 to what an INTEGER "points to". */
6647 var_integer = new_var_info (NULL_TREE, "INTEGER");
6648 gcc_assert (var_integer->id == integer_id);
6649 var_integer->is_artificial_var = 1;
6650 var_integer->size = ~0;
6651 var_integer->fullsize = ~0;
6652 var_integer->offset = 0;
6653 var_integer->is_special_var = 1;
6655 /* INTEGER = ANYTHING, because we don't know where a dereference of
6656 a random integer will point to. */
6657 lhs.type = SCALAR;
6658 lhs.var = integer_id;
6659 lhs.offset = 0;
6660 rhs.type = ADDRESSOF;
6661 rhs.var = anything_id;
6662 rhs.offset = 0;
6663 process_constraint (new_constraint (lhs, rhs));
6666 /* Initialize things necessary to perform PTA */
6668 static void
6669 init_alias_vars (void)
6671 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6673 bitmap_obstack_initialize (&pta_obstack);
6674 bitmap_obstack_initialize (&oldpta_obstack);
6675 bitmap_obstack_initialize (&predbitmap_obstack);
6677 constraint_pool = create_alloc_pool ("Constraint pool",
6678 sizeof (struct constraint), 30);
6679 variable_info_pool = create_alloc_pool ("Variable info pool",
6680 sizeof (struct variable_info), 30);
6681 constraints.create (8);
6682 varmap.create (8);
6683 vi_for_tree = new hash_map<tree, varinfo_t>;
6684 call_stmt_vars = new hash_map<gimple, varinfo_t>;
6686 memset (&stats, 0, sizeof (stats));
6687 shared_bitmap_table = new hash_table<shared_bitmap_hasher> (511);
6688 init_base_vars ();
6690 gcc_obstack_init (&fake_var_decl_obstack);
6692 final_solutions = new hash_map<varinfo_t, pt_solution *>;
6693 gcc_obstack_init (&final_solutions_obstack);
6696 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6697 predecessor edges. */
6699 static void
6700 remove_preds_and_fake_succs (constraint_graph_t graph)
6702 unsigned int i;
6704 /* Clear the implicit ref and address nodes from the successor
6705 lists. */
6706 for (i = 1; i < FIRST_REF_NODE; i++)
6708 if (graph->succs[i])
6709 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6710 FIRST_REF_NODE * 2);
6713 /* Free the successor list for the non-ref nodes. */
6714 for (i = FIRST_REF_NODE + 1; i < graph->size; i++)
6716 if (graph->succs[i])
6717 BITMAP_FREE (graph->succs[i]);
6720 /* Now reallocate the size of the successor list as, and blow away
6721 the predecessor bitmaps. */
6722 graph->size = varmap.length ();
6723 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6725 free (graph->implicit_preds);
6726 graph->implicit_preds = NULL;
6727 free (graph->preds);
6728 graph->preds = NULL;
6729 bitmap_obstack_release (&predbitmap_obstack);
6732 /* Solve the constraint set. */
6734 static void
6735 solve_constraints (void)
6737 struct scc_info *si;
6739 if (dump_file)
6740 fprintf (dump_file,
6741 "\nCollapsing static cycles and doing variable "
6742 "substitution\n");
6744 init_graph (varmap.length () * 2);
6746 if (dump_file)
6747 fprintf (dump_file, "Building predecessor graph\n");
6748 build_pred_graph ();
6750 if (dump_file)
6751 fprintf (dump_file, "Detecting pointer and location "
6752 "equivalences\n");
6753 si = perform_var_substitution (graph);
6755 if (dump_file)
6756 fprintf (dump_file, "Rewriting constraints and unifying "
6757 "variables\n");
6758 rewrite_constraints (graph, si);
6760 build_succ_graph ();
6762 free_var_substitution_info (si);
6764 /* Attach complex constraints to graph nodes. */
6765 move_complex_constraints (graph);
6767 if (dump_file)
6768 fprintf (dump_file, "Uniting pointer but not location equivalent "
6769 "variables\n");
6770 unite_pointer_equivalences (graph);
6772 if (dump_file)
6773 fprintf (dump_file, "Finding indirect cycles\n");
6774 find_indirect_cycles (graph);
6776 /* Implicit nodes and predecessors are no longer necessary at this
6777 point. */
6778 remove_preds_and_fake_succs (graph);
6780 if (dump_file && (dump_flags & TDF_GRAPH))
6782 fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
6783 "in dot format:\n");
6784 dump_constraint_graph (dump_file);
6785 fprintf (dump_file, "\n\n");
6788 if (dump_file)
6789 fprintf (dump_file, "Solving graph\n");
6791 solve_graph (graph);
6793 if (dump_file && (dump_flags & TDF_GRAPH))
6795 fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
6796 "in dot format:\n");
6797 dump_constraint_graph (dump_file);
6798 fprintf (dump_file, "\n\n");
6801 if (dump_file)
6802 dump_sa_points_to_info (dump_file);
6805 /* Create points-to sets for the current function. See the comments
6806 at the start of the file for an algorithmic overview. */
6808 static void
6809 compute_points_to_sets (void)
6811 basic_block bb;
6812 unsigned i;
6813 varinfo_t vi;
6815 timevar_push (TV_TREE_PTA);
6817 init_alias_vars ();
6819 intra_create_variable_infos (cfun);
6821 /* Now walk all statements and build the constraint set. */
6822 FOR_EACH_BB_FN (bb, cfun)
6824 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6825 gsi_next (&gsi))
6827 gphi *phi = gsi.phi ();
6829 if (! virtual_operand_p (gimple_phi_result (phi)))
6830 find_func_aliases (cfun, phi);
6833 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
6834 gsi_next (&gsi))
6836 gimple stmt = gsi_stmt (gsi);
6838 find_func_aliases (cfun, stmt);
6842 if (dump_file)
6844 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6845 dump_constraints (dump_file, 0);
6848 /* From the constraints compute the points-to sets. */
6849 solve_constraints ();
6851 /* Compute the points-to set for ESCAPED used for call-clobber analysis. */
6852 cfun->gimple_df->escaped = find_what_var_points_to (get_varinfo (escaped_id));
6854 /* Make sure the ESCAPED solution (which is used as placeholder in
6855 other solutions) does not reference itself. This simplifies
6856 points-to solution queries. */
6857 cfun->gimple_df->escaped.escaped = 0;
6859 /* Compute the points-to sets for pointer SSA_NAMEs. */
6860 for (i = 0; i < num_ssa_names; ++i)
6862 tree ptr = ssa_name (i);
6863 if (ptr
6864 && POINTER_TYPE_P (TREE_TYPE (ptr)))
6865 find_what_p_points_to (ptr);
6868 /* Compute the call-used/clobbered sets. */
6869 FOR_EACH_BB_FN (bb, cfun)
6871 gimple_stmt_iterator gsi;
6873 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6875 gcall *stmt;
6876 struct pt_solution *pt;
6878 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
6879 if (!stmt)
6880 continue;
6882 pt = gimple_call_use_set (stmt);
6883 if (gimple_call_flags (stmt) & ECF_CONST)
6884 memset (pt, 0, sizeof (struct pt_solution));
6885 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6887 *pt = find_what_var_points_to (vi);
6888 /* Escaped (and thus nonlocal) variables are always
6889 implicitly used by calls. */
6890 /* ??? ESCAPED can be empty even though NONLOCAL
6891 always escaped. */
6892 pt->nonlocal = 1;
6893 pt->escaped = 1;
6895 else
6897 /* If there is nothing special about this call then
6898 we have made everything that is used also escape. */
6899 *pt = cfun->gimple_df->escaped;
6900 pt->nonlocal = 1;
6903 pt = gimple_call_clobber_set (stmt);
6904 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6905 memset (pt, 0, sizeof (struct pt_solution));
6906 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6908 *pt = find_what_var_points_to (vi);
6909 /* Escaped (and thus nonlocal) variables are always
6910 implicitly clobbered by calls. */
6911 /* ??? ESCAPED can be empty even though NONLOCAL
6912 always escaped. */
6913 pt->nonlocal = 1;
6914 pt->escaped = 1;
6916 else
6918 /* If there is nothing special about this call then
6919 we have made everything that is used also escape. */
6920 *pt = cfun->gimple_df->escaped;
6921 pt->nonlocal = 1;
6926 timevar_pop (TV_TREE_PTA);
6930 /* Delete created points-to sets. */
6932 static void
6933 delete_points_to_sets (void)
6935 unsigned int i;
6937 delete shared_bitmap_table;
6938 shared_bitmap_table = NULL;
6939 if (dump_file && (dump_flags & TDF_STATS))
6940 fprintf (dump_file, "Points to sets created:%d\n",
6941 stats.points_to_sets_created);
6943 delete vi_for_tree;
6944 delete call_stmt_vars;
6945 bitmap_obstack_release (&pta_obstack);
6946 constraints.release ();
6948 for (i = 0; i < graph->size; i++)
6949 graph->complex[i].release ();
6950 free (graph->complex);
6952 free (graph->rep);
6953 free (graph->succs);
6954 free (graph->pe);
6955 free (graph->pe_rep);
6956 free (graph->indirect_cycles);
6957 free (graph);
6959 varmap.release ();
6960 free_alloc_pool (variable_info_pool);
6961 free_alloc_pool (constraint_pool);
6963 obstack_free (&fake_var_decl_obstack, NULL);
6965 delete final_solutions;
6966 obstack_free (&final_solutions_obstack, NULL);
6969 /* Mark "other" loads and stores as belonging to CLIQUE and with
6970 base zero. */
6972 static bool
6973 visit_loadstore (gimple, tree base, tree ref, void *clique_)
6975 unsigned short clique = (uintptr_t)clique_;
6976 if (TREE_CODE (base) == MEM_REF
6977 || TREE_CODE (base) == TARGET_MEM_REF)
6979 tree ptr = TREE_OPERAND (base, 0);
6980 if (TREE_CODE (ptr) == SSA_NAME)
6982 /* ??? We need to make sure 'ptr' doesn't include any of
6983 the restrict tags in its points-to set. */
6984 return false;
6987 /* For now let decls through. */
6989 /* Do not overwrite existing cliques (that includes clique, base
6990 pairs we just set). */
6991 if (MR_DEPENDENCE_CLIQUE (base) == 0)
6993 MR_DEPENDENCE_CLIQUE (base) = clique;
6994 MR_DEPENDENCE_BASE (base) = 0;
6998 /* For plain decl accesses see whether they are accesses to globals
6999 and rewrite them to MEM_REFs with { clique, 0 }. */
7000 if (TREE_CODE (base) == VAR_DECL
7001 && is_global_var (base)
7002 /* ??? We can't rewrite a plain decl with the walk_stmt_load_store
7003 ops callback. */
7004 && base != ref)
7006 tree *basep = &ref;
7007 while (handled_component_p (*basep))
7008 basep = &TREE_OPERAND (*basep, 0);
7009 gcc_assert (TREE_CODE (*basep) == VAR_DECL);
7010 tree ptr = build_fold_addr_expr (*basep);
7011 tree zero = build_int_cst (TREE_TYPE (ptr), 0);
7012 *basep = build2 (MEM_REF, TREE_TYPE (*basep), ptr, zero);
7013 MR_DEPENDENCE_CLIQUE (*basep) = clique;
7014 MR_DEPENDENCE_BASE (*basep) = 0;
7017 return false;
7020 /* If REF is a MEM_REF then assign a clique, base pair to it, updating
7021 CLIQUE, *RESTRICT_VAR and LAST_RUID. Return whether dependence info
7022 was assigned to REF. */
7024 static bool
7025 maybe_set_dependence_info (tree ref, tree ptr,
7026 unsigned short &clique, varinfo_t restrict_var,
7027 unsigned short &last_ruid)
7029 while (handled_component_p (ref))
7030 ref = TREE_OPERAND (ref, 0);
7031 if ((TREE_CODE (ref) == MEM_REF
7032 || TREE_CODE (ref) == TARGET_MEM_REF)
7033 && TREE_OPERAND (ref, 0) == ptr)
7035 /* Do not overwrite existing cliques. This avoids overwriting dependence
7036 info inlined from a function with restrict parameters inlined
7037 into a function with restrict parameters. This usually means we
7038 prefer to be precise in innermost loops. */
7039 if (MR_DEPENDENCE_CLIQUE (ref) == 0)
7041 if (clique == 0)
7042 clique = ++cfun->last_clique;
7043 if (restrict_var->ruid == 0)
7044 restrict_var->ruid = ++last_ruid;
7045 MR_DEPENDENCE_CLIQUE (ref) = clique;
7046 MR_DEPENDENCE_BASE (ref) = restrict_var->ruid;
7047 return true;
7050 return false;
7053 /* Compute the set of independend memory references based on restrict
7054 tags and their conservative propagation to the points-to sets. */
7056 static void
7057 compute_dependence_clique (void)
7059 unsigned short clique = 0;
7060 unsigned short last_ruid = 0;
7061 for (unsigned i = 0; i < num_ssa_names; ++i)
7063 tree ptr = ssa_name (i);
7064 if (!ptr || !POINTER_TYPE_P (TREE_TYPE (ptr)))
7065 continue;
7067 /* Avoid all this when ptr is not dereferenced? */
7068 tree p = ptr;
7069 if (SSA_NAME_IS_DEFAULT_DEF (ptr)
7070 && (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
7071 || TREE_CODE (SSA_NAME_VAR (ptr)) == RESULT_DECL))
7072 p = SSA_NAME_VAR (ptr);
7073 varinfo_t vi = lookup_vi_for_tree (p);
7074 if (!vi)
7075 continue;
7076 vi = get_varinfo (find (vi->id));
7077 bitmap_iterator bi;
7078 unsigned j;
7079 varinfo_t restrict_var = NULL;
7080 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, j, bi)
7082 varinfo_t oi = get_varinfo (j);
7083 if (oi->is_restrict_var)
7085 if (restrict_var)
7087 if (dump_file && (dump_flags & TDF_DETAILS))
7089 fprintf (dump_file, "found restrict pointed-to "
7090 "for ");
7091 print_generic_expr (dump_file, ptr, 0);
7092 fprintf (dump_file, " but not exclusively\n");
7094 restrict_var = NULL;
7095 break;
7097 restrict_var = oi;
7099 /* NULL is the only other valid points-to entry. */
7100 else if (oi->id != nothing_id)
7102 restrict_var = NULL;
7103 break;
7106 /* Ok, found that ptr must(!) point to a single(!) restrict
7107 variable. */
7108 /* ??? PTA isn't really a proper propagation engine to compute
7109 this property.
7110 ??? We could handle merging of two restricts by unifying them. */
7111 if (restrict_var)
7113 /* Now look at possible dereferences of ptr. */
7114 imm_use_iterator ui;
7115 gimple use_stmt;
7116 FOR_EACH_IMM_USE_STMT (use_stmt, ui, ptr)
7118 /* ??? Calls and asms. */
7119 if (!gimple_assign_single_p (use_stmt))
7120 continue;
7121 maybe_set_dependence_info (gimple_assign_lhs (use_stmt), ptr,
7122 clique, restrict_var, last_ruid);
7123 maybe_set_dependence_info (gimple_assign_rhs1 (use_stmt), ptr,
7124 clique, restrict_var, last_ruid);
7129 if (clique == 0)
7130 return;
7132 /* Assign the BASE id zero to all accesses not based on a restrict
7133 pointer. That way they get disabiguated against restrict
7134 accesses but not against each other. */
7135 /* ??? For restricts derived from globals (thus not incoming
7136 parameters) we can't restrict scoping properly thus the following
7137 is too aggressive there. For now we have excluded those globals from
7138 getting into the MR_DEPENDENCE machinery. */
7139 basic_block bb;
7140 FOR_EACH_BB_FN (bb, cfun)
7141 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7142 !gsi_end_p (gsi); gsi_next (&gsi))
7144 gimple stmt = gsi_stmt (gsi);
7145 walk_stmt_load_store_ops (stmt, (void *)(uintptr_t)clique,
7146 visit_loadstore, visit_loadstore);
7150 /* Compute points-to information for every SSA_NAME pointer in the
7151 current function and compute the transitive closure of escaped
7152 variables to re-initialize the call-clobber states of local variables. */
7154 unsigned int
7155 compute_may_aliases (void)
7157 if (cfun->gimple_df->ipa_pta)
7159 if (dump_file)
7161 fprintf (dump_file, "\nNot re-computing points-to information "
7162 "because IPA points-to information is available.\n\n");
7164 /* But still dump what we have remaining it. */
7165 dump_alias_info (dump_file);
7168 return 0;
7171 /* For each pointer P_i, determine the sets of variables that P_i may
7172 point-to. Compute the reachability set of escaped and call-used
7173 variables. */
7174 compute_points_to_sets ();
7176 /* Debugging dumps. */
7177 if (dump_file)
7178 dump_alias_info (dump_file);
7180 /* Compute restrict-based memory disambiguations. */
7181 compute_dependence_clique ();
7183 /* Deallocate memory used by aliasing data structures and the internal
7184 points-to solution. */
7185 delete_points_to_sets ();
7187 gcc_assert (!need_ssa_update_p (cfun));
7189 return 0;
7192 /* A dummy pass to cause points-to information to be computed via
7193 TODO_rebuild_alias. */
7195 namespace {
7197 const pass_data pass_data_build_alias =
7199 GIMPLE_PASS, /* type */
7200 "alias", /* name */
7201 OPTGROUP_NONE, /* optinfo_flags */
7202 TV_NONE, /* tv_id */
7203 ( PROP_cfg | PROP_ssa ), /* properties_required */
7204 0, /* properties_provided */
7205 0, /* properties_destroyed */
7206 0, /* todo_flags_start */
7207 TODO_rebuild_alias, /* todo_flags_finish */
7210 class pass_build_alias : public gimple_opt_pass
7212 public:
7213 pass_build_alias (gcc::context *ctxt)
7214 : gimple_opt_pass (pass_data_build_alias, ctxt)
7217 /* opt_pass methods: */
7218 virtual bool gate (function *) { return flag_tree_pta; }
7220 }; // class pass_build_alias
7222 } // anon namespace
7224 gimple_opt_pass *
7225 make_pass_build_alias (gcc::context *ctxt)
7227 return new pass_build_alias (ctxt);
7230 /* A dummy pass to cause points-to information to be computed via
7231 TODO_rebuild_alias. */
7233 namespace {
7235 const pass_data pass_data_build_ealias =
7237 GIMPLE_PASS, /* type */
7238 "ealias", /* name */
7239 OPTGROUP_NONE, /* optinfo_flags */
7240 TV_NONE, /* tv_id */
7241 ( PROP_cfg | PROP_ssa ), /* properties_required */
7242 0, /* properties_provided */
7243 0, /* properties_destroyed */
7244 0, /* todo_flags_start */
7245 TODO_rebuild_alias, /* todo_flags_finish */
7248 class pass_build_ealias : public gimple_opt_pass
7250 public:
7251 pass_build_ealias (gcc::context *ctxt)
7252 : gimple_opt_pass (pass_data_build_ealias, ctxt)
7255 /* opt_pass methods: */
7256 virtual bool gate (function *) { return flag_tree_pta; }
7258 }; // class pass_build_ealias
7260 } // anon namespace
7262 gimple_opt_pass *
7263 make_pass_build_ealias (gcc::context *ctxt)
7265 return new pass_build_ealias (ctxt);
7269 /* IPA PTA solutions for ESCAPED. */
7270 struct pt_solution ipa_escaped_pt
7271 = { true, false, false, false, false, false, false, false, NULL };
7273 /* Associate node with varinfo DATA. Worker for
7274 cgraph_for_node_and_aliases. */
7275 static bool
7276 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
7278 if ((node->alias || node->thunk.thunk_p)
7279 && node->analyzed)
7280 insert_vi_for_tree (node->decl, (varinfo_t)data);
7281 return false;
7284 /* Execute the driver for IPA PTA. */
7285 static unsigned int
7286 ipa_pta_execute (void)
7288 struct cgraph_node *node;
7289 varpool_node *var;
7290 int from;
7292 in_ipa_mode = 1;
7294 init_alias_vars ();
7296 if (dump_file && (dump_flags & TDF_DETAILS))
7298 symtab_node::dump_table (dump_file);
7299 fprintf (dump_file, "\n");
7302 /* Build the constraints. */
7303 FOR_EACH_DEFINED_FUNCTION (node)
7305 varinfo_t vi;
7306 /* Nodes without a body are not interesting. Especially do not
7307 visit clones at this point for now - we get duplicate decls
7308 there for inline clones at least. */
7309 if (!node->has_gimple_body_p () || node->global.inlined_to)
7310 continue;
7311 node->get_body ();
7313 gcc_assert (!node->clone_of);
7315 vi = create_function_info_for (node->decl,
7316 alias_get_name (node->decl));
7317 node->call_for_symbol_thunks_and_aliases
7318 (associate_varinfo_to_alias, vi, true);
7321 /* Create constraints for global variables and their initializers. */
7322 FOR_EACH_VARIABLE (var)
7324 if (var->alias && var->analyzed)
7325 continue;
7327 get_vi_for_tree (var->decl);
7330 if (dump_file)
7332 fprintf (dump_file,
7333 "Generating constraints for global initializers\n\n");
7334 dump_constraints (dump_file, 0);
7335 fprintf (dump_file, "\n");
7337 from = constraints.length ();
7339 FOR_EACH_DEFINED_FUNCTION (node)
7341 struct function *func;
7342 basic_block bb;
7344 /* Nodes without a body are not interesting. */
7345 if (!node->has_gimple_body_p () || node->clone_of)
7346 continue;
7348 if (dump_file)
7350 fprintf (dump_file,
7351 "Generating constraints for %s", node->name ());
7352 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7353 fprintf (dump_file, " (%s)",
7354 IDENTIFIER_POINTER
7355 (DECL_ASSEMBLER_NAME (node->decl)));
7356 fprintf (dump_file, "\n");
7359 func = DECL_STRUCT_FUNCTION (node->decl);
7360 gcc_assert (cfun == NULL);
7362 /* For externally visible or attribute used annotated functions use
7363 local constraints for their arguments.
7364 For local functions we see all callers and thus do not need initial
7365 constraints for parameters. */
7366 if (node->used_from_other_partition
7367 || node->externally_visible
7368 || node->force_output)
7370 intra_create_variable_infos (func);
7372 /* We also need to make function return values escape. Nothing
7373 escapes by returning from main though. */
7374 if (!MAIN_NAME_P (DECL_NAME (node->decl)))
7376 varinfo_t fi, rvi;
7377 fi = lookup_vi_for_tree (node->decl);
7378 rvi = first_vi_for_offset (fi, fi_result);
7379 if (rvi && rvi->offset == fi_result)
7381 struct constraint_expr includes;
7382 struct constraint_expr var;
7383 includes.var = escaped_id;
7384 includes.offset = 0;
7385 includes.type = SCALAR;
7386 var.var = rvi->id;
7387 var.offset = 0;
7388 var.type = SCALAR;
7389 process_constraint (new_constraint (includes, var));
7394 /* Build constriants for the function body. */
7395 FOR_EACH_BB_FN (bb, func)
7397 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7398 gsi_next (&gsi))
7400 gphi *phi = gsi.phi ();
7402 if (! virtual_operand_p (gimple_phi_result (phi)))
7403 find_func_aliases (func, phi);
7406 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7407 gsi_next (&gsi))
7409 gimple stmt = gsi_stmt (gsi);
7411 find_func_aliases (func, stmt);
7412 find_func_clobbers (func, stmt);
7416 if (dump_file)
7418 fprintf (dump_file, "\n");
7419 dump_constraints (dump_file, from);
7420 fprintf (dump_file, "\n");
7422 from = constraints.length ();
7425 /* From the constraints compute the points-to sets. */
7426 solve_constraints ();
7428 /* Compute the global points-to sets for ESCAPED.
7429 ??? Note that the computed escape set is not correct
7430 for the whole unit as we fail to consider graph edges to
7431 externally visible functions. */
7432 ipa_escaped_pt = find_what_var_points_to (get_varinfo (escaped_id));
7434 /* Make sure the ESCAPED solution (which is used as placeholder in
7435 other solutions) does not reference itself. This simplifies
7436 points-to solution queries. */
7437 ipa_escaped_pt.ipa_escaped = 0;
7439 /* Assign the points-to sets to the SSA names in the unit. */
7440 FOR_EACH_DEFINED_FUNCTION (node)
7442 tree ptr;
7443 struct function *fn;
7444 unsigned i;
7445 basic_block bb;
7447 /* Nodes without a body are not interesting. */
7448 if (!node->has_gimple_body_p () || node->clone_of)
7449 continue;
7451 fn = DECL_STRUCT_FUNCTION (node->decl);
7453 /* Compute the points-to sets for pointer SSA_NAMEs. */
7454 FOR_EACH_VEC_ELT (*fn->gimple_df->ssa_names, i, ptr)
7456 if (ptr
7457 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7458 find_what_p_points_to (ptr);
7461 /* Compute the call-use and call-clobber sets for indirect calls
7462 and calls to external functions. */
7463 FOR_EACH_BB_FN (bb, fn)
7465 gimple_stmt_iterator gsi;
7467 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7469 gcall *stmt;
7470 struct pt_solution *pt;
7471 varinfo_t vi, fi;
7472 tree decl;
7474 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7475 if (!stmt)
7476 continue;
7478 /* Handle direct calls to functions with body. */
7479 decl = gimple_call_fndecl (stmt);
7480 if (decl
7481 && (fi = lookup_vi_for_tree (decl))
7482 && fi->is_fn_info)
7484 *gimple_call_clobber_set (stmt)
7485 = find_what_var_points_to
7486 (first_vi_for_offset (fi, fi_clobbers));
7487 *gimple_call_use_set (stmt)
7488 = find_what_var_points_to
7489 (first_vi_for_offset (fi, fi_uses));
7491 /* Handle direct calls to external functions. */
7492 else if (decl)
7494 pt = gimple_call_use_set (stmt);
7495 if (gimple_call_flags (stmt) & ECF_CONST)
7496 memset (pt, 0, sizeof (struct pt_solution));
7497 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7499 *pt = find_what_var_points_to (vi);
7500 /* Escaped (and thus nonlocal) variables are always
7501 implicitly used by calls. */
7502 /* ??? ESCAPED can be empty even though NONLOCAL
7503 always escaped. */
7504 pt->nonlocal = 1;
7505 pt->ipa_escaped = 1;
7507 else
7509 /* If there is nothing special about this call then
7510 we have made everything that is used also escape. */
7511 *pt = ipa_escaped_pt;
7512 pt->nonlocal = 1;
7515 pt = gimple_call_clobber_set (stmt);
7516 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7517 memset (pt, 0, sizeof (struct pt_solution));
7518 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7520 *pt = find_what_var_points_to (vi);
7521 /* Escaped (and thus nonlocal) variables are always
7522 implicitly clobbered by calls. */
7523 /* ??? ESCAPED can be empty even though NONLOCAL
7524 always escaped. */
7525 pt->nonlocal = 1;
7526 pt->ipa_escaped = 1;
7528 else
7530 /* If there is nothing special about this call then
7531 we have made everything that is used also escape. */
7532 *pt = ipa_escaped_pt;
7533 pt->nonlocal = 1;
7536 /* Handle indirect calls. */
7537 else if (!decl
7538 && (fi = get_fi_for_callee (stmt)))
7540 /* We need to accumulate all clobbers/uses of all possible
7541 callees. */
7542 fi = get_varinfo (find (fi->id));
7543 /* If we cannot constrain the set of functions we'll end up
7544 calling we end up using/clobbering everything. */
7545 if (bitmap_bit_p (fi->solution, anything_id)
7546 || bitmap_bit_p (fi->solution, nonlocal_id)
7547 || bitmap_bit_p (fi->solution, escaped_id))
7549 pt_solution_reset (gimple_call_clobber_set (stmt));
7550 pt_solution_reset (gimple_call_use_set (stmt));
7552 else
7554 bitmap_iterator bi;
7555 unsigned i;
7556 struct pt_solution *uses, *clobbers;
7558 uses = gimple_call_use_set (stmt);
7559 clobbers = gimple_call_clobber_set (stmt);
7560 memset (uses, 0, sizeof (struct pt_solution));
7561 memset (clobbers, 0, sizeof (struct pt_solution));
7562 EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7564 struct pt_solution sol;
7566 vi = get_varinfo (i);
7567 if (!vi->is_fn_info)
7569 /* ??? We could be more precise here? */
7570 uses->nonlocal = 1;
7571 uses->ipa_escaped = 1;
7572 clobbers->nonlocal = 1;
7573 clobbers->ipa_escaped = 1;
7574 continue;
7577 if (!uses->anything)
7579 sol = find_what_var_points_to
7580 (first_vi_for_offset (vi, fi_uses));
7581 pt_solution_ior_into (uses, &sol);
7583 if (!clobbers->anything)
7585 sol = find_what_var_points_to
7586 (first_vi_for_offset (vi, fi_clobbers));
7587 pt_solution_ior_into (clobbers, &sol);
7595 fn->gimple_df->ipa_pta = true;
7598 delete_points_to_sets ();
7600 in_ipa_mode = 0;
7602 return 0;
7605 namespace {
7607 const pass_data pass_data_ipa_pta =
7609 SIMPLE_IPA_PASS, /* type */
7610 "pta", /* name */
7611 OPTGROUP_NONE, /* optinfo_flags */
7612 TV_IPA_PTA, /* tv_id */
7613 0, /* properties_required */
7614 0, /* properties_provided */
7615 0, /* properties_destroyed */
7616 0, /* todo_flags_start */
7617 0, /* todo_flags_finish */
7620 class pass_ipa_pta : public simple_ipa_opt_pass
7622 public:
7623 pass_ipa_pta (gcc::context *ctxt)
7624 : simple_ipa_opt_pass (pass_data_ipa_pta, ctxt)
7627 /* opt_pass methods: */
7628 virtual bool gate (function *)
7630 return (optimize
7631 && flag_ipa_pta
7632 /* Don't bother doing anything if the program has errors. */
7633 && !seen_error ());
7636 virtual unsigned int execute (function *) { return ipa_pta_execute (); }
7638 }; // class pass_ipa_pta
7640 } // anon namespace
7642 simple_ipa_opt_pass *
7643 make_pass_ipa_pta (gcc::context *ctxt)
7645 return new pass_ipa_pta (ctxt);