Algorithmadvanced
Offline variable substitution
Also called pointer equivalence detection.
Finds variables with surely equal points-to sets before solving and merges them, which shrinks the constraint graph.
- Solves
- Points-to analysis
- Time
- O(n^3 + m) worst
- Space
- O(n^2 + m) extra
- Where
- m = the number of pointer statements; n = the number of variables (each variable is also a location)
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Atanas Rountev, Satish Chandra, 2000
Offline variable substitution makes Andersen's analysis faster without a change to its result. Before the solver starts, it looks only at the statements and finds groups of variables whose least points-to sets must be equal. It then rewrites the statements so that each group is one variable, solves the smaller system, and gives each variable the set of its group. The test is simple: a variable that gets values only by copies from other variables, and from nothing else, has the union of their sets. Rountev and Chandra (2000) gave the method and found that many variables of C programs, most of them temporaries, are of this kind.
In plain words
Many pointer variables in a program only receive copies of other pointers. A temporary that holds a copy of one pointer and nothing else will always hold the same addresses as that pointer. Pointers that copy each other in a circle also hold the same addresses. The method finds these groups before the real analysis starts, with one pass over the copy statements. It must be careful with any pointer that can get a value in another way: from an address, from a read through a pointer, or by a write through a pointer to it. Such a pointer starts a group of its own. The analysis then treats each group as one pointer, so it has less to do, and each pointer gets the result of its group.
The problem
The input is a set of statements in the four basic forms p = &a, p = q, p = *q and *p = q over variables, and the output is the least solution of the subset constraints of Andersen's analysis, as on the page of the points-to analysis problem. The order is the subset order on each set, with the empty sets at the bottom, in the direction of Cousot. The analysis is flow-insensitive: it ignores the order of the statements, but not the statements that the control flow gives.
The copy graph has an edge for each copy p = q. A variable is indirect if it can get a value other than by a copy: it is the left side of p = &a or of p = *q, or its address is taken in some x = &p, so that a store *x = q can write into it. All other variables are direct. The key fact: a direct variable gets values only through the edges of the copy graph, so its least set is the union of the sets of its sources.
The algorithm
Each strongly connected component of the copy graph gets a label, and components with one label must have one least set. The labels go out in topological order, so the sources of a component have their labels first.
OVS(S)- 1
G <- the graph with an edge q -> p for each p = q in S - 2
X <- the variables p with p = &a or p = *q in S, and the a with p = &a in S - 3
for each strongly connected component C of G, in topological order do - 4
if C has a variable in X then label[C] <- a fresh label - 5
else P <- the labels of the components with an edge into C, without EMPTY - 6
if P is empty then label[C] <- EMPTY - 7
else if P has one label l then label[C] <- l - 8
else label[C] <- a fresh label - 9
rep[v] <- the first variable with the label of v, for each variable v - 10
S' <- S with each variable v replaced by rep[v], except the a of p = &a; drop the copies r = r and repeats - 11
M <- the result of Andersen's solver on S', with the set of a location a kept at rep[a] - 12
return M[rep[v]] for each variable v
The label EMPTY marks the direct components that nothing flows into: their sets are surely empty. The addresses in the sets stay the original locations (line L10): if and are in one group, a pointer to does not point to . The implementation finds the components with an iterative form of Tarjan's algorithm, which gives them in reverse topological order.
Example
The program, in the toy IR:
entry:
p = &a
a = &b
q = p
r = q
s = r
r = s
u = q
u = s
t = *u
ret 0
The copy graph has the edges , , , , and . The set is : and are the left sides of p = &a and a = &b, and have their addresses taken, and is the left side of a load.
| component | in | labels of the sources | label |
|---|---|---|---|
| yes | 1 (fresh) | ||
| , , | yes | a fresh label each | |
| no | from | 1 | |
| no | from | 1 | |
| no | from and | 1 |
So , , , and form one group with the representative . The variable has two sources, but both carry the label 1, so it joins too. The nine statements become three:
p = &a
a = &b
t = *p
The solver gives , and on four nodes instead of eight variables. Line L12 gives , which is the result of Andersen's analysis on the original program.
If the program also had w = &q and *w = c with c = &d, then would have its address taken. It would be in and get a fresh label, since the store writes into its set but not into the set of .
Correctness
The full proof is in the proof file. Its steps:
- A direct component gets only what its sources give. If no variable of a component is in , its least set is the union of the least sets of the variables with an edge into it. The proof makes the set of the component equal to that union, checks that the result is still a solution, and uses the fact that is the least one. A store cannot write into a direct variable, since every address in a least set is the address of a variable in .
- Equal labels mean equal sets. By induction in topological order: a fresh label belongs to one component, whose members share a set because they copy each other in a cycle; EMPTY components get a union of empty sets; a component that takes the label of all its sources gets their common set.
- The rewritten system has the same least solution. The original least solution, read on the representatives, solves the rewritten system, so the rewritten least solution is no larger. The rewritten least solution, read back on all variables, solves the original system, so it is no smaller.
So any correct solver for the rewritten system gives Andersen's result after the map back.
Proof: Offline variable substitution keeps the least solution of the subset constraintsfull
Setting. The program is a set of statements in the four forms over variables, each variable also a location. is the least solution of the subset constraints of Andersen's analysis: p = &a gives , p = q gives , p = *q gives for , and *p = q gives for . lies inside every solution. The copy graph has an edge for each copy p = q with . The set of line L2 holds every with a statement p = &a or p = *q, and every with a statement p = &a. A variable not in is direct.
Every element of is a location with a statement x = &a, since the set of such locations, given to every variable, is a solution. So for all , and a store *p = q adds only to the sets of variables in .
Lemma 1 (a direct component gets only what its sources give). Let be a strongly connected component of with no variable of , and let be the union of over the edges with and . Then for every .
Proof. Each such edge is a copy, so for some , and since the members of lie on cycles of copies, is the same on all of and contains . For the other direction, let be with every set of replaced by , so . We show that is a solution; then by minimality, and on . Take the constraints that involve a member of .
- On the left. is direct, so the only statements with on the left are copies
x = q. If , then . If not, . No store adds to , since and the sets of hold only locations in . - On the right. For
p = x, , and if then too. Forp = *xand*x = q, each is in , so , and the constraints of for give what is needed. For*p = x, each has , since . - is never a location in a set, since .
Lemma 2 (equal labels mean equal sets). If two variables get the same label in lines L3 to L8, they have the same least set. Every variable with the label EMPTY has an empty least set.
Proof. By induction over the components in topological order, which puts each component after all components with an edge into it. All members of a component have the same , since they lie on cycles of copies. A component that gets a fresh label (lines L4 and L8) is the only one with that label. A component with the label EMPTY (line L6) is direct and every component with an edge into it has the label EMPTY, so by Lemma 1 and the induction hypothesis its set is a union of empty sets. A component that takes the label in line L7 is direct, and every component with an edge into it has the label or EMPTY; by the induction hypothesis these have one common set or the empty set, and by Lemma 1 the component has the set .
Theorem 1 (correctness). Let be the statements of rewritten by line L10, and let be the least solution of with the set of a location kept at the node . Then for every variable .
Proof. In each statement p = &a becomes rep(p) = &a, p = q becomes rep(p) = rep(q), p = *q gives for , and *p = q gives for .
First, read on the nodes, for each representative , is a solution of . By Lemma 2, for every , so each rewritten constraint for is the original constraint for , with each variable replaced by and the same sets. So , that is, .
Second, is a solution of , since each original constraint for is exactly the rewritten constraint for . So , that is, .
So the substitution keeps the least solution, and any correct solver for the smaller system, such as Andersen's worklist solver, gives Andersen's result after the map back in line L12.
Theorem 2 (time). Lines L1 to L10 take time and space, with hashing to drop repeated statements. With the worklist solver of Andersen's analysis on the rewritten system, the total time is , where is the number of representatives. This is within the bound of Andersen's analysis.
Proof. The copy graph has at most edges. Tarjan's algorithm finds its components in time. Line L5 looks at each edge into each component once, so all labels cost . Lines L9 and L10 take . The rewritten system has nodes, and its sets hold at most locations. After the repeats are dropped, each node has at most loads, stores and successors. Each of the at most edges is added once, and its first transfer of a set costs . Each location enters the set of each node once, so each of the pairs of a node and a location is handled once, at a cost of for the loads, the stores and the successors of the node. The total is for the solver.
The substitution does not lower the worst case of Andersen's analysis. Its gain is that real programs have many direct variables, often temporaries, and the solver then works on far fewer nodes and edges.
Complexity
Proved. Lines L1 to L10 take time and space: Tarjan's algorithm is linear, and each edge into a component is looked at once for its label. The solver then runs on nodes, with sets of at most locations, in time with difference propagation. The total is within Andersen's bound of time and space. The substitution does not lower the worst case.
Stated in the paper, not proved here. Rountev and Chandra report that on C programs the substitution removes a large part of the variables before solving and makes the analysis much faster. Hardekopf and Lin (2007) use it as a first step before their solvers for programs of millions of lines.
Measured, not proved. On the 400 seeded random programs of the test file, of up to 12 variables and 30 statements, the 2460 variables become 1853 nodes and the 5630 distinct statements become 4154. On 200 random programs of 20 variables and 30 statements with mostly copies, the 3823 variables become 1611 nodes and the 5895 statements become 3113. The result equals Andersen's least solution in every case.
Properties
- Same result as Andersen's analysis. The substitution changes the system, not its least solution.
- Offline. It looks only at the statements, before any solving, and costs linear time.
- Weaker than the truth. It finds only some of the variables with equal least sets. Variables that become equal through loads and stores, or through cycles that loads and stores close, are left to the solver or to online cycle elimination.
- Works with any solver. The rewritten system is an ordinary system of the four forms, plus the map from locations to nodes.
- Locations stay apart. Only the pointers are merged; the addresses in the sets are the original ones.
Variants and improvements
- Hash-based value numbering. Hardekopf and Lin (SAS 2007) gave each variable a set of labels and merged variables with equal label sets, with ideas from value numbering. This finds more equal variables, including some that receive values from loads, and also finds locations that are equal.
- Cycles in the solver. Online and lazy or hybrid cycle detection merge the cycles that only appear while the solver runs. The hybrid method uses an offline pass over the same graph, with extra nodes for the loads and stores.
- Unification. Steensgaard's analysis merges every pair of variables joined by a copy, which is much more than this method and loses precision.
When to use it
Use it as a cheap first step before any inclusion-based solver for large programs, especially for code produced by a compiler front end, such as three-address code, which has many temporaries that only copy another value. It costs linear time and never changes the answer. It helps less when most pointers are written through other pointers, as in code with many heap structures.
Pitfalls
- Forgetting the stores. A variable whose address is taken can be written by a store
*x = q. If it is merged with its copy source, the facts from the store spread to the source, or are lost. Treat every variable whose address is taken as indirect. - Merging the locations. The rewritten
p = &amust keep as it is, and the solver must read the set of at . Replacing by in the sets makes a pointer to seem to point to its whole group. - Two sources with different labels. The union of two different sets is not equal to either one. Such a component needs a fresh label, unless one of the sources is surely empty.
- The wrong order. Labels must go out in topological order; a component whose sources have no labels yet cannot take one.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/offline-variable-substitution/. The authors are listed in prov/Q7GZTS.jsonl.
"""Offline variable substitution for Andersen's analysis.
substitute(stmts) looks at the statements before any solving and gives
each variable a representative, rep[v], such that variables with the same
representative surely have the same least points-to set. It works on the
copy graph, with an edge q -> p for each p = q:
* the variables on one cycle of copies have equal sets;
* a variable that gets values only through copies, not through p = &a,
p = *q, or a store into it (which needs its address to be taken), has
the union of the sets of its copy sources; if all its sources carry one
label, it has the same set as them.
ovs(stmts) rewrites the statements over the representatives, solves the
smaller system with a worklist solver, and maps the result back. The
result is exactly Andersen's least solution. The addresses in the sets
stay the original locations: the set of a location a is stored at rep[a].
"""
from collections import deque
import ptsgen
EMPTY = 0 # the label of variables whose least set is surely empty
def sccs(names, succ):
"""Tarjan's algorithm, without recursion. Returns the strongly
connected components in reverse topological order."""
index, low, on_stack = {}, {}, set()
stack, out = [], []
counter = 0
for root in names:
if root in index:
continue
work = [(root, iter(succ[root]))]
index[root] = low[root] = counter
counter += 1
stack.append(root)
on_stack.add(root)
while work:
v, it = work[-1]
for w in it:
if w not in index:
index[w] = low[w] = counter
counter += 1
stack.append(w)
on_stack.add(w)
work.append((w, iter(succ[w])))
break
if w in on_stack:
low[v] = min(low[v], index[w])
else:
work.pop()
if work:
u = work[-1][0]
low[u] = min(low[u], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on_stack.discard(w)
comp.append(w)
if w == v:
break
out.append(comp)
return out
def substitute(stmts):
names = ptsgen.variables(stmts)
succ = {v: [] for v in names}
pred = {v: [] for v in names}
for kind, x, y in stmts:
if kind == "copy" and x != y:
succ[y].append(x) # @line L1
pred[x].append(y)
indirect = set()
for kind, x, y in stmts:
if kind == "addr":
indirect.add(x) # @line L2
indirect.add(y)
elif kind == "load":
indirect.add(x)
comp_of = {}
comps = sccs(names, succ)
for i, comp in enumerate(comps):
for v in comp:
comp_of[v] = i
label = {}
fresh = 0
for i in reversed(range(len(comps))): # @line L3
comp = comps[i]
if any(v in indirect for v in comp):
fresh += 1
label[i] = fresh # @line L4
continue
incoming = {label[comp_of[q]] for v in comp for q in pred[v] # @line L5
if comp_of[q] != i} - {EMPTY}
if not incoming:
label[i] = EMPTY # @line L6
elif len(incoming) == 1:
label[i] = incoming.pop() # @line L7
else:
fresh += 1
label[i] = fresh # @line L8
first = {}
for v in names:
first.setdefault(label[comp_of[v]], v)
return {v: first[label[comp_of[v]]] for v in names} # @line L9
def rewrite(stmts, rep):
out = []
seen = set()
for kind, x, y in stmts:
if kind == "addr":
s = (kind, rep[x], y) # @line L10
else:
s = (kind, rep[x], rep[y])
if (kind == "copy" and s[1] == s[2]) or s in seen:
continue
seen.add(s)
out.append(s)
return out
def solve(reduced, rep):
"""Andersen's worklist solver with difference propagation, where the
set of the location a lives at the node rep[a]."""
nodes = set(rep.values())
pts = {r: set() for r in nodes}
delta = {r: set() for r in nodes}
succ = {r: set() for r in nodes}
loads = {r: [] for r in nodes}
stores = {r: [] for r in nodes}
work = deque()
def propagate(s, v):
new = s - pts[v]
if new:
pts[v] |= new
if not delta[v]:
work.append(v)
delta[v] |= new
def add_edge(u, v):
if u != v and v not in succ[u]:
succ[u].add(v)
propagate(pts[u], v)
for kind, x, y in reduced:
if kind == "addr":
propagate({y}, x)
elif kind == "copy":
add_edge(y, x)
elif kind == "load":
loads[y].append(x)
else:
stores[x].append(y)
while work:
n = work.popleft()
d, delta[n] = delta[n], set()
for a in d:
for p in loads[n]:
add_edge(rep[a], p) # @line L11
for q in stores[n]:
add_edge(q, rep[a])
for w in list(succ[n]):
propagate(d, w)
return pts
def ovs(stmts):
rep = substitute(stmts)
reduced = rewrite(stmts, rep)
m = solve(reduced, rep)
stats = {"variables": len(rep), "nodes": len(set(rep.values())),
"statements": len(set(stmts)), "reduced": len(reduced)}
return {v: set(m[rep[v]]) for v in rep}, stats # @line L12
def points_to(text):
return ovs(ptsgen.parse(text))[0]
ptsgen.py 177 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Points-to constraints in the four basic forms, for the pointer analysis pages.
A program is a list of statements. Each statement is a tuple with the same
shape as the pointer instructions of the toy IR (toyir.py):
("addr", p, a) p = &a
("copy", p, q) p = q
("load", p, q) p = *q
("store", p, q) *p = q
Every name is a pointer variable, and every variable is also a memory
location whose address the program may take. A points-to solution is a dict
from each variable to a set of variables. The order of the statements does
not matter to a flow-insensitive analysis.
parse(text) and show(stmts) convert to and from the toy IR notation.
random_program(rng, nvars, nstmts) builds a random program.
least_solution(stmts) is a slow reference: it applies the four rules to
every statement, round after round, until nothing changes.
is_solution(stmts, pts) checks that pts meets every constraint.
concrete_facts(stmts, rng, runs, steps) runs the program concretely, with
the statements in random order, and returns the facts (p, a) that some run
saw: p held the address of a.
"""
import re
_NAME = r"[A-Za-z_][A-Za-z0-9_]*"
_FORMS = [
("addr", re.compile(r"(%s) = &(%s)" % (_NAME, _NAME))),
("load", re.compile(r"(%s) = \*(%s)" % (_NAME, _NAME))),
("store", re.compile(r"\*(%s) = (%s)" % (_NAME, _NAME))),
("copy", re.compile(r"(%s) = (%s)" % (_NAME, _NAME))),
]
def parse(text):
"""Parse lines such as "p = &a", "p = q", "p = *q" and "*p = q".
The k-th "p = alloc" becomes "p = &hk", one location per allocation
site. Blank lines, lines that start with #, block labels and the
terminators jump, br and ret are skipped, so a toy IR program with only
pointer instructions can be read as it is. A flow-insensitive analysis
ignores the order of the statements, so the blocks do not matter."""
stmts = []
sites = 0
for raw in text.splitlines():
line = " ".join(raw.split())
if not line or line.startswith("#") or line.endswith(":"):
continue
if line.split()[0] in ("jump", "br", "ret"):
continue
m = re.fullmatch(r"(%s) = alloc" % _NAME, line)
if m:
sites += 1
stmts.append(("addr", m.group(1), "h%d" % sites))
continue
for kind, rx in _FORMS:
m = rx.fullmatch(line)
if m:
stmts.append((kind, m.group(1), m.group(2)))
break
else:
raise ValueError("not a pointer statement: %r" % raw)
return stmts
def show(stmts):
out = []
for kind, x, y in stmts:
if kind == "addr":
out.append("%s = &%s" % (x, y))
elif kind == "copy":
out.append("%s = %s" % (x, y))
elif kind == "load":
out.append("%s = *%s" % (x, y))
else:
out.append("*%s = %s" % (x, y))
return "\n".join(out)
def variables(stmts):
"""All names, in the order of their first use."""
seen = {}
for _, x, y in stmts:
seen.setdefault(x, None)
seen.setdefault(y, None)
return list(seen)
def random_program(rng, nvars=8, nstmts=30, weights=(3, 4, 2, 2)):
"""A random list of nstmts statements over the names v0 .. v(nvars-1).
weights gives the relative number of addr, copy, load and store forms."""
names = ["v%d" % i for i in range(nvars)]
kinds = ["addr", "copy", "load", "store"]
return [
(rng.choices(kinds, weights)[0], rng.choice(names), rng.choice(names))
for _ in range(nstmts)
]
def least_solution(stmts):
"""The least solution of the inclusion constraints, by plain iteration."""
pts = {v: set() for v in variables(stmts)}
changed = True
while changed:
changed = False
for kind, x, y in stmts:
if kind == "addr":
new = {y}
targets = [x]
elif kind == "copy":
new = pts[y]
targets = [x]
elif kind == "load":
new = set()
for a in pts[y]:
new |= pts[a]
targets = [x]
else:
new = pts[y]
targets = list(pts[x])
for t in targets:
if not new <= pts[t]:
pts[t] |= new
changed = True
return pts
def is_solution(stmts, pts):
"""True if pts satisfies every constraint of stmts."""
for kind, x, y in stmts:
if kind == "addr" and y not in pts[x]:
return False
if kind == "copy" and not pts[y] <= pts[x]:
return False
if kind == "load" and any(not pts[a] <= pts[x] for a in pts[y]):
return False
if kind == "store" and any(not pts[y] <= pts[a] for a in pts[x]):
return False
return True
def concrete_facts(stmts, rng, runs=20, steps=120):
"""Run the program concretely. Each variable holds no value at the start.
A run is a sequence of statements in any order, with repeats, which is the
semantics that a flow-insensitive analysis must cover; every path of a
real control flow graph over these statements is such a sequence. A
statement that reads a variable with no value, or goes through one,
cannot run, so the run picks another. Returns the set of pairs (p, a)
such that p held the address of a at some moment of some run."""
seen = set()
for _ in range(runs):
val = {v: None for v in variables(stmts)}
for _ in range(steps):
kind, x, y = stmts[rng.randrange(len(stmts))]
if kind == "addr":
val[x] = y
dst = x
elif kind == "copy":
if val[y] is None:
continue
val[x] = val[y]
dst = x
elif kind == "load":
if val[y] is None or val[val[y]] is None:
continue
val[x] = val[val[y]]
dst = x
else:
if val[x] is None or val[y] is None:
continue
dst = val[x]
val[dst] = val[y]
seen.add((dst, val[dst]))
return seen
test_offline_variable_substitution.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/offline-variable-substitution/. The authors are listed in prov/Q7GZTS.jsonl.
import random
import ptsgen
from offline_variable_substitution import ovs, points_to, rewrite, substitute
PAGE = """
entry:
p = &a
a = &b
q = p
r = q
s = r
r = s
u = q
u = s
t = *u
ret 0
"""
def test_page_example():
stmts = ptsgen.parse(PAGE)
rep = substitute(stmts)
assert {v for v in rep if rep[v] == "p"} == {"p", "q", "r", "s", "u"}
assert rep["a"] == "a" and rep["b"] == "b" and rep["t"] == "t"
assert ptsgen.show(rewrite(stmts, rep)) == "p = &a\na = &b\nt = *p"
pts, stats = ovs(stmts)
assert pts == ptsgen.least_solution(stmts)
assert pts["u"] == {"a"} and pts["t"] == {"b"}
assert stats == {"variables": 8, "nodes": 4, "statements": 9, "reduced": 3}
def test_address_taken_variable_keeps_its_own_label():
# q gets b through the store *w = s, since w points to q. Merging q
# with its only copy source p would lose that fact.
stmts = ptsgen.parse("p = &a\nq = p\nw = &q\ns = &b\n*w = s")
rep = substitute(stmts)
assert rep["q"] != rep["p"]
pts = ovs(stmts)[0]
assert pts["q"] == {"a", "b"} and pts["p"] == {"a"}
assert pts == ptsgen.least_solution(stmts)
def test_load_target_keeps_its_own_label():
stmts = ptsgen.parse("p = &a\nq = p\nr = &x\nx = &c\nq = *r")
rep = substitute(stmts)
assert rep["q"] != rep["p"]
assert ovs(stmts)[0] == ptsgen.least_solution(stmts)
def test_two_sources_with_different_labels_stay_apart():
stmts = ptsgen.parse("p = &a\nq = &b\nr = p\nr = q\ns = r")
rep = substitute(stmts)
assert rep["r"] not in (rep["p"], rep["q"])
assert rep["s"] == rep["r"]
assert ovs(stmts)[0] == ptsgen.least_solution(stmts)
def test_variables_with_no_source_share_the_empty_label():
stmts = ptsgen.parse("x = y\nz = x\nw = *z\nu = v")
rep = substitute(stmts)
assert rep["x"] == rep["y"] == rep["z"] == rep["u"] == rep["v"]
assert rep["w"] != rep["x"]
assert all(s == set() for s in ovs(stmts)[0].values())
def test_equal_labels_mean_equal_least_sets():
rng = random.Random(5100)
for trial in range(400):
stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
rep = substitute(stmts)
least = ptsgen.least_solution(stmts)
for v in rep:
assert least[v] == least[rep[v]], ptsgen.show(stmts)
def test_equals_andersen_on_random_programs():
rng = random.Random(5200)
for trial in range(400):
stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
assert ovs(stmts)[0] == ptsgen.least_solution(stmts), ptsgen.show(stmts)
def test_copy_heavy_programs_shrink():
rng = random.Random(5300)
before = after = 0
for trial in range(200):
stmts = ptsgen.random_program(rng, 20, 30, (1, 8, 1, 1))
pts, stats = ovs(stmts)
assert pts == ptsgen.least_solution(stmts)
before += stats["variables"]
after += stats["nodes"]
assert after < before * 0.7
def test_sound_against_concrete_runs():
rng = random.Random(5400)
for trial in range(150):
stmts = ptsgen.random_program(rng, rng.randint(3, 10), 30)
pts = points_to(ptsgen.show(stmts))
for p, a in ptsgen.concrete_facts(stmts, rng, runs=10, steps=150):
assert a in pts[p]
def test_long_chain_without_recursion():
n = 3000
text = "\n".join(["v0 = &a"] + ["v%d = v%d" % (i + 1, i) for i in range(n)])
stmts = ptsgen.parse(text)
pts, stats = ovs(stmts)
assert stats["nodes"] == 2 # v0 and its chain, and a
assert pts["v%d" % n] == {"a"}
History
Andersen's analysis (1994) was too slow for large C programs, and much of its work went into variables that were only copies of others. Rountev and Chandra (2000) found these variables with a linear pass over the copy graph, before solving, and reported large savings on C programs. Fähndrich, Foster, Su and Aiken (1998) had merged cycles during solving; the two methods work together. Hardekopf and Lin (2007) used offline substitution with their lazy and hybrid cycle detection, and in a second paper the same year extended it with hash-based value numbering, which finds more equal pointers and also equal locations.
References
- Atanas Rountev and Satish Chandra, Off-line variable substitution for scaling points-to analysis, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2000), 47 to 56, 2000, whole paper (the copy graph, the variables that receive values only through copies, the substitution and its measurements on C programs)
- Ben Hardekopf and Calvin Lin, The ant and the grasshopper, fast and accurate pointer analysis for millions of lines of code, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '07), 290 to 299, 2007, the section on offline variable substitution as a step before the solver
- Lars Ole Andersen, Program Analysis and Specialization for the C Programming Language, PhD thesis, DIKU, University of Copenhagen, 1994 (DIKU report 94/19), the chapter on pointer analysis (the inclusion constraints that the substitution rewrites)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Q7GZTS Edit this page History Report an error Markdown