Algorithmresearch
Sparse flow-sensitive pointer analysis
Also called staged flow-sensitive pointer analysis.
Makes flow-sensitive points-to analysis scale by propagating facts only along def-use chains found by a cheaper pre-analysis.
- Solves
- Points-to analysis
- Time
- O(n^3 m^4) worst
- Space
- O(n^2 m + n m^2) extra
- Where
- m = the number of names; n = the number of nodes and edges of the control flow graph
- Model
- Word RAM
- Properties
- not context sensitivedeterministicflow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Ben Hardekopf, Calvin Lin, 2011
A sparse flow-sensitive pointer analysis computes a points-to set for each variable at each program point, like the dense flow-sensitive analysis, but it moves a set only from the node that defines it to the nodes that use it. For top-level variables these def-use chains are easy to find. For memory reached through pointers they depend on the result being computed. The staged analysis of Hardekopf and Lin (2011) breaks this cycle with a cheap first stage: Andersen's analysis gives a sound over-approximation of what each store may write and each load may read, and that gives def-use chains that are safe to use. The second stage then runs the flow-sensitive transfer functions, with strong updates, along those chains only. The result is exactly the dense result at every place where a variable is used.
In plain words
A flow-sensitive analysis knows that a pointer pointed to one thing before a line and to another thing after it. The plain way to do this keeps a full table of every pointer at every line and copies the table from line to line. Most entries never change on the way, so most of that copying is wasted. The sparse way sends each new fact straight from the line that makes it to the lines that read it. The hard part is knowing which lines read a fact written through a pointer. A fast first pass that ignores the order of statements answers that safely, because it can only say "maybe" too often, never too rarely. The second pass then follows those links and gets the same answers as the full table.
The problem
The input is a control flow graph whose nodes hold statements of four forms: , , and , with node as the entry. A name of the form is a heap location that stands for every object made at one allocation site. The output is, for each reachable node and each name that may read, the set of names that may point to just before , and the set just after each node for each name that may define. Here is Andersen's result, and and are the names that may define and read according to .
| item | value |
|---|---|
| direction | forward |
| may or must | may |
| domain | maps from pairs (node, name) on def-use edges to subsets of the names, each inside the Andersen set of the name |
| order | pointwise inclusion (bottom is precise) |
| join | union over the def-use edges into a node |
| bottom and top | every set empty, and every name mapped to its Andersen set |
| boundary value | at the entry no name points to anything |
| initial value | every is empty |
| transfer | gives , a copy and a load give the usual sets, and a store gives a strong update to a single target that is not a heap name and a weak update otherwise |
The algorithm
SPARSE-FS(S, G)- 1
A = ANDERSEN(S) - 2
for each node n reachable from the entry, compute DEF(n) and USE(n) with A - 3
for each reachable node d and each v in DEF(d) do - 4
add an edge d -v-> u for each node u with v in USE(u) that some path reaches from d with no node strictly between them that may define v - 5
set every out(d, v) to the empty set and put every reachable node on the worklist W - 6
while W is not empty do - 7
take a node n from W - 8
for each w in USE(n), in(w) = the union of out(d, w) over the edges d -w-> n - 9
for each v in DEF(n), new = TRANSFER(n, v, in) - 10
if new differs from out(n, v) then out(n, v) = new and put every u with an edge n -v-> u on W - 11
return out, and in(w) at each node for each w in USE of the node TRANSFER(n, v, in)- 12
x = &a gives {a}; x = y gives in(y); x = *y gives the union of in(b) for b in in(y) for a store *x = y:- 13
if in(x) is empty then return the empty set - 14
if in(x) = {v} and v is not a heap name then return in(y) - 15
if v is in in(x) then return in(v) ∪ in(y) else return in(v)
For a node , is for the first three forms and for a store . is empty for , for a copy, for a load and for a store. The search of line L4 is a depth-first search from the successors of that records each node using and stops at each node that may define . A store defines every name that its pointer may point to by Andersen's result, so a weak update at a store passes the old value on through line L15.
Line L14 is the strong update. When the pointer points to exactly one name, and that name is one concrete location, the store overwrites it, so the old value is dropped. Line L13 handles a store whose pointer points to nothing yet. Such a store cannot run, so its output is empty. This keeps TRANSFER monotone: if line L13 kept the old value, a later strong update could make the output smaller, and the result would depend on the order of the worklist.
Example
0: p = &a
1: x = &p
2: t = *x
3: q = &b
4: *x = q
5: r = *x
6: s = p
The nodes form one straight path. Andersen's analysis gives , and . So the store at node 4 may define only , and the loads at nodes 2 and 5 may read and .
| def-use edge | why |
|---|---|
| , | node 4 may define , so the search stops there |
| , , | no other node defines |
| the store reads | |
| , | the store gives the new value of |
The worklist gives and , so node 2 gets . At node 4, is one name and not a heap name, so line L14 gives . Node 5 reads through the edge from node 4 and gets , and node 6 gets . Andersen's analysis alone gives for , and . If pointed to a heap name instead, line L15 would keep the old value, and a later load would see both the old and the new value.
Correctness
The proof file shows four facts. First, TRANSFER keeps every set inside the Andersen set of its name and is monotone, because a store with an empty pointer set gives the empty set. Second, a node changes only names in its DEF set and reads only names in its USE set, both computed from the sound Andersen result. Third, the least solution of the sparse equations is equal to the dense flow-sensitive least solution on every def-use pair. One direction restricts the dense solution to the def-use pairs and shows that it satisfies the sparse equations. The other direction extends the sparse solution to every node by the reaching definitions and shows that it satisfies the dense equations. Fourth, every concrete run is covered: a strong update is applied only when the pointer can hold one location, and a heap name, which stands for many objects, gets only weak updates.
Proof: The sparse analysis computes exactly the sets of the dense flow-sensitive analysis on its def-use pairs, and both are inside Andersen's resultfull
Setting. The program is a control flow graph whose nodes are the nodes reachable from the entry . Each node holds one statement , , or . is the set of all names, and a name that matches h<digits> is a heap name. is Andersen's least solution of the four inclusion rules for all statements (the Andersen page). A state maps every name to a set of names. is the set of states with for every . Ordered by pointwise inclusion, is a finite complete lattice.
The dense analysis. For a node and a state , is with these changes:
- : ;
- : ;
- : ;
- , with : if , every maps to ; if and is not a heap name, ; otherwise every maps to .
The dense equations are , and , where maps every name to . The dense result is their least solution in .
DEF, USE and def-use edges. is for the first three forms and for a store. is , , and for the four forms. A node reaches for if there is a path with and for . The edge exists when , and reaches for . The search of lines L3 and L4 finds exactly these: it starts at the successors of , records a visited when , and goes on past only when .
The sparse analysis. Its unknowns are for and . For a node and , . The sparse equations are , where is extended to a state by outside . The sparse result is their least solution with every .
Lemma 1 (closure and monotonicity). Each maps into and is monotone on .
Proof. Let . Rule 1 gives . Rule 2 gives . In rule 3, , so by Andersen's load rule. In rule 4, , so every written is in , and by Andersen's store rule. So .
For monotonicity, only rule 4 needs care. Let in , with , and fix a name . If , then and is unchanged in both. Let . The value of is if , if with not a heap name, if otherwise, and if . Going from to the larger moves only from the empty case to any case, from the second case to the third, or from the fourth case to the third, and each of these moves gives a superset. With the sets and only grow.
Lemma 2 (locality). For , for , and for depends only on restricted to .
Proof. The first three rules change only . They read , and rule 3 also reads . Rule 4 changes only names in or in , and it reads , and . All of these are in .
Lemma 3 (both results exist and are computed). and exist. The round-robin iteration of the dense equations from reaches , and the worklist of lines L5 to L10 stops with .
Proof. By Lemma 1 the dense equations define a monotone map on the finite lattice , so its least fixed point exists and is the limit of the iteration from the bottom (Kleene). The sparse map is monotone by Lemma 1 and keeps every , so the same holds for it. The worklist starts with every node, so each equation is evaluated at least once. A value only changes to a larger set, by induction with monotonicity, so there are finitely many changes, and each change puts every user of that value on the worklist. When the worklist is empty, each node was last evaluated after its last input changed, so every equation holds. Every value it computes is inside every solution, by induction over the steps, so the result is the least one.
Lemma 4 (paths carry values). If reaches for and , then in .
Proof. Along the path , by the join, and for by Lemma 2, since .
Theorem 1 (sparse equals dense). For every and , in . For every and , computed from equals in .
Proof. Sparse inside dense. Let from . Then for , by Lemma 4. By Lemmas 1 and 2, . So satisfies every sparse equation with , and since the least fixed point of a monotone map is below every such point (Knaster and Tarski), .
Dense inside sparse. Build the state from : is the union of over all that reach for with , and is for and otherwise. All its sets are inside . Check the dense equations with . For the join at , take a predecessor . If , then reaches for by the path , so . If not, , and every that reaches for also reaches for , through . For the transfer at and , by Lemma 2. For , agrees with on , because the edges into are exactly the reaching definitions of the names in . So by Lemma 2, . So satisfies the dense equations with , and .
Now for : . For : , and by the first part and Lemma 4.
Theorem 2 (inside Andersen, and sound). Every set of , and so every set of , is inside Andersen's set for the same name. For every run that starts at the entry with no values and follows the graph, the state before each node is covered by : if location holds a pointer to , then the name of is in .
Proof. The first part is . For soundness, use induction on the length of the run. At the entry nothing holds a value. For one step through node , the cases of rules 1 to 3 follow the concrete step. For a store that runs, holds a location whose name is in , so . If and is not a heap name, then is the only location with that name, the store overwrites it, and the new value is covered by . Otherwise the written location keeps a value covered by . Other locations do not change. The empty case never runs, so its value does not matter for soundness. A heap name stands for every object created at its allocation statement, so it only gets weak updates.
Theorem 3 (cost). Let be the number of nodes and edges of the graph and the number of names. Building the def-use edges takes time after Andersen's analysis, there are at most of them, and the worklist runs in time. The space is .
Proof. There are at most pairs , and each search visits each node and edge once, so the edges cost and number at most . Each is a subset of and only grows, so it changes at most times, and each change queues at most users. So there are at most visits. A visit computes at most values, and each reads at most inputs, each a union over at most sources of sets of size at most , so it costs . The product is . The space holds the edges and at most sets of size at most .
Complexity
Proved. Let be the number of nodes and edges and the number of names. After Andersen's analysis, building the def-use edges takes time, with at most edges. Each value only grows inside , so it changes at most times, and the worklist makes at most visits of each. That gives time and space. This bound is loose. The point of the method is that real programs have far fewer def-use edges than the worst case.
Stated in the literature. Hardekopf and Lin report that the staged analysis handles C programs of up to millions of lines of code, as the title of their paper says, and that it is much faster and uses much less memory than their earlier semi-sparse analysis.
Measured, not proved. On 400 random programs with up to 25 nodes and 8 names (seed 2011), the sparse result equals the dense result at every def-use pair. The sparse analysis stored 7936 points-to facts where the dense tables stored 33568, which is 24%. Of the 525 reachable stores, 81 got a strong update. On 300 programs (seed 2004), every dense set is inside the Andersen set, and some are strictly smaller. On 300 programs (seed 2003), every fact of a random concrete run is in the result.
Properties
- Exact with respect to the dense analysis. The sparse result is not an approximation of the dense flow-sensitive result: at each use the sets are the same.
- As precise as its strong updates allow. It is more precise than Andersen's analysis only because of the order of statements and the strong updates of line L14.
- The first stage limits the cost, not the result. A less precise first stage gives larger DEF and USE sets and more def-use edges, so more work, but the answers stay the same as long as the first stage is sound.
- Flow-sensitive, not context-sensitive. Calls are handled through the call graph, with one set per variable and node for all contexts.
Variants and improvements
- Semi-sparse analysis. Hardekopf and Lin's earlier analysis (2009) puts only the top-level variables, whose address is never taken, in SSA form and still propagates the address-taken variables densely.
- Memory SSA. The def-use edges of line L4 for address-taken variables are usually built by putting the program in SSA form for memory, with a may-definition at each store and a may-use at each load for the names that Andersen's result gives. This gives fewer edges than one edge from each definition to each use.
- Access equivalence. Names whose def-use chains are the same can share one set of edges, which saves memory on large programs.
- A cheaper first stage. Steensgaard's analysis can replace Andersen's analysis as the first stage. It is faster but gives more def-use edges.
- Fields and contexts. The same staging works with field-sensitive names and with a context-sensitive first stage.
When to use it
Use it when a client needs flow-sensitive precision, for example strong updates for a bug checker or for proving that a pointer is not null at a point, on a program that is too large for the dense analysis. When flow-insensitive precision is enough, Andersen's analysis alone is cheaper. When only a few variables matter, a demand-driven analysis may be cheaper still.
Pitfalls
- Strong updates on heap names. A version of line L14 without the test "v is not a heap name" overwrites a heap location that stands for many objects. For , , , , , it gives instead of , which misses a real value. The right line L14 updates strongly only a name for one concrete location.
- Keeping the old value at a store that cannot run. A version of line L13 that returns when is empty makes TRANSFER non-monotone, because a later strong update gives a smaller set. The result then depends on the order of the worklist. The right line L13 returns the empty set.
- Stopping the search at a use. A version of line L4 that stops at the first node that uses misses later uses on the same path. The right search records a node that uses and goes on past it, and stops only at a node that may define .
- An unsound first stage. If the first stage misses a target of a store, the store does not appear in DEF for that name and the def-use edges skip it. The first stage must be sound for every statement of the program.
- Calling it sound with reflection or native code. Like every whole-program pointer analysis, it covers only the statements it sees. Code loaded, generated or called through native interfaces needs a model.
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
# 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
sparse_flow_sensitive_pointer_analysis.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-flow-sensitive-pointer-analysis/. The authors are listed in prov/9J9RX5.jsonl.
"""Staged sparse flow-sensitive points-to analysis, after Hardekopf and Lin.
A program is (stmts, succ): stmts[i] is the statement of node i in the four
forms of ptsgen (("addr", p, a), ("copy", p, q), ("load", p, q) for p = *q
and ("store", p, q) for *p = q), and succ[i] lists the successors of node i
in the control flow graph. Node 0 is the entry. A name that matches h<digits>
is a heap location that stands for many objects, so it never gets a strong
update. At the entry every pointer points to nothing.
sparse_fs(stmts, succ) runs three stages:
1. andersen(stmts), the flow-insensitive auxiliary analysis;
2. DEF and USE sets for each node, computed with the auxiliary result, and
the def-use edges: d -v-> u when d may define v, u may use v, and some
path of the graph goes from d to u with no node strictly between them
that may define v;
3. a worklist that recomputes a node only when one of its inputs changed,
and sends a changed value along the def-use edges of that variable only.
It returns (ins, outs, users): ins[(u, v)] is the points-to set of v just
before node u, for every reachable u and v in USE(u); outs[(d, v)] is the set
of v just after node d, for v in DEF(d); users[(d, v)] lists the nodes u of
the def-use edges d -v-> u.
"""
import re
from collections import deque
HEAP = re.compile(r"h\d+")
def is_heap(a):
return HEAP.fullmatch(a) is not None
def andersen(stmts):
"""Andersen's analysis by a constraint graph with difference propagation,
the solver of the Andersen page."""
names = {}
for _, x, y in stmts:
names.setdefault(x, None)
names.setdefault(y, None)
pts = {v: set() for v in names}
succ = {v: set() for v in names}
delta = {v: set() for v in names}
loads = {v: set() for v in names}
stores = {v: set() for v in names}
work = deque()
queued = set()
def push(v):
if v not in queued:
queued.add(v)
work.append(v)
def propagate(s, v):
new = s - pts[v]
if new:
pts[v] |= new
delta[v] |= new
push(v)
def add_edge(u, v):
if v not in succ[u]:
succ[u].add(v)
propagate(pts[u], v)
for kind, x, y in stmts:
if kind == "addr":
pts[x].add(y)
delta[x].add(y)
push(x)
elif kind == "load":
loads[y].add(x)
elif kind == "store":
stores[x].add(y)
for kind, x, y in stmts:
if kind == "copy":
add_edge(y, x)
while work:
n = work.popleft()
queued.discard(n)
d = delta[n]
delta[n] = set()
for a in d:
for p in loads[n]:
add_edge(a, p)
for q in stores[n]:
add_edge(q, a)
for w in list(succ[n]):
propagate(d, w)
return pts
def reachable(succ):
seen = {0}
stack = [0]
while stack:
n = stack.pop()
for m in succ[n]:
if m not in seen:
seen.add(m)
stack.append(m)
return sorted(seen)
def def_use(stmt, aux):
"""The locations that the statement may define and may read."""
kind, x, y = stmt
if kind == "addr":
return {x}, set()
if kind == "copy":
return {x}, {y}
if kind == "load":
return {x}, {y} | aux.get(y, set())
return set(aux.get(x, ())), {x, y} | aux.get(x, set())
def transfer(stmt, v, get):
"""The new set of v after the statement, for v in DEF; get(w) gives the
set of w before it."""
kind, x, y = stmt
if kind == "addr":
return frozenset([y]) # @line L12
if kind == "copy":
return get(y)
if kind == "load":
out = set()
for b in get(y):
out |= get(b)
return frozenset(out)
targets = get(x)
if not targets:
return frozenset() # @line L13
if targets == {v} and not is_heap(v):
return get(y) # @line L14
if v in targets:
return get(v) | get(y) # @line L15
return get(v)
def sparse_fs(stmts, succ):
aux = andersen(stmts) # @line L1
nodes = reachable(succ)
defs, uses = {}, {}
for n in nodes:
defs[n], uses[n] = def_use(stmts[n], aux) # @line L2
users, sources = {}, {}
for d in nodes:
for v in defs[d]: # @line L3
found = []
seen = set()
stack = list(succ[d])
while stack:
u = stack.pop()
if u in seen:
continue
seen.add(u)
if v in uses[u]:
found.append(u) # @line L4
if v not in defs[u]:
stack.extend(succ[u])
users[(d, v)] = sorted(found)
for u in found:
sources.setdefault((u, v), []).append(d)
outs = {(d, v): frozenset() for d in nodes for v in defs[d]}
def read(n):
def get(w):
s = set()
for d in sources.get((n, w), ()):
s |= outs[(d, w)]
return frozenset(s)
return get
work = deque(nodes) # @line L5
queued = set(nodes)
while work: # @line L6
n = work.popleft() # @line L7
queued.discard(n)
get = read(n) # @line L8
for v in sorted(defs[n]):
new = transfer(stmts[n], v, get) # @line L9
if new != outs[(n, v)]:
outs[(n, v)] = new # @line L10
for u in users[(n, v)]:
if u not in queued:
queued.add(u)
work.append(u)
ins = {(u, w): read(u)(w) for u in nodes for w in uses[u]}
return ins, outs, users # @line L11
test_sparse_flow_sensitive_pointer_analysis.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-flow-sensitive-pointer-analysis/. The authors are listed in prov/9J9RX5.jsonl.
import random
import ptsgen
from sparse_flow_sensitive_pointer_analysis import andersen, is_heap, reachable, sparse_fs
EMPTY = frozenset()
def dense(stmts, succ, aux):
"""The dense flow-sensitive reference: a full map from every name to its
set before and after every reachable node, by round-robin iteration. A
store writes the locations that its pointer may point to here, with a
strong update for one location that is not a heap name. A store whose
pointer points to nothing cannot run; it gives the empty set to the
locations it may write by the auxiliary analysis aux."""
nodes = reachable(succ)
names = ptsgen.variables(stmts)
preds = {n: [] for n in nodes}
for n in nodes:
for m in succ[n]:
preds[m].append(n)
IN = {n: {v: EMPTY for v in names} for n in nodes}
OUT = {n: {v: EMPTY for v in names} for n in nodes}
changed = True
while changed:
changed = False
for n in nodes:
inn = {v: frozenset().union(*(OUT[p][v] for p in preds[n])) for v in names}
out = dict(inn)
kind, x, y = stmts[n]
if kind == "addr":
out[x] = frozenset([y])
elif kind == "copy":
out[x] = inn[y]
elif kind == "load":
out[x] = frozenset().union(*(inn[b] for b in inn[y]))
elif not inn[x]:
for b in aux[x]:
out[b] = EMPTY
elif len(inn[x]) == 1 and not is_heap(next(iter(inn[x]))):
out[next(iter(inn[x]))] = inn[y]
else:
for b in inn[x]:
out[b] = inn[b] | inn[y]
if inn != IN[n] or out != OUT[n]:
IN[n], OUT[n] = inn, out
changed = True
return IN, OUT
def line(succ_count):
return [[i + 1] for i in range(succ_count - 1)] + [[]]
PAGE = [
("addr", "p", "a"),
("addr", "x", "p"),
("load", "t", "x"),
("addr", "q", "b"),
("store", "x", "q"),
("load", "r", "x"),
("copy", "s", "p"),
]
def test_page_example_strong_update():
succ = line(len(PAGE))
ins, outs, users = sparse_fs(PAGE, succ)
assert outs[(2, "t")] == {"a"}
assert outs[(4, "p")] == {"b"}
assert outs[(5, "r")] == {"b"}
assert outs[(6, "s")] == {"b"}
assert users[(0, "p")] == [2, 4]
assert users[(4, "p")] == [5, 6]
aux = andersen(PAGE)
assert aux["t"] == aux["r"] == {"a", "b"}
def test_heap_location_gets_a_weak_update():
stmts = [("addr", "q0", "a"), ("addr", "x", "h1"), ("store", "x", "q0"), ("addr", "q", "b"), ("store", "x", "q"), ("load", "r", "x")]
_, outs, _ = sparse_fs(stmts, line(len(stmts)))
assert outs[(5, "r")] == {"a", "b"}
def test_branches_join():
stmts = [("addr", "x", "p"), ("addr", "q", "a"), ("addr", "q", "b"), ("store", "x", "q"), ("load", "r", "x")]
succ = [[1, 2], [3], [3], [4], []]
ins, outs, _ = sparse_fs(stmts, succ)
assert ins[(3, "q")] == {"a", "b"}
assert outs[(4, "r")] == {"a", "b"}
def test_unreachable_nodes_are_ignored():
stmts = [("addr", "p", "a"), ("addr", "p", "b"), ("copy", "r", "p")]
succ = [[2], [2], []]
ins, outs, _ = sparse_fs(stmts, succ)
assert ins[(2, "p")] == {"a"}
assert (1, "p") not in outs
def random_cfg(rng, nvars, nnodes):
stmts = []
for kind, x, y in ptsgen.random_program(rng, nvars, nnodes):
if kind == "addr" and rng.random() < 0.35:
y = "h%d" % rng.randint(1, 2)
stmts.append((kind, x, y))
succ = []
for i in range(nnodes):
out = []
if i + 1 < nnodes and rng.random() < 0.85:
out.append(i + 1)
if rng.random() < 0.3:
out.append(rng.randrange(nnodes))
succ.append(sorted(set(out)))
return stmts, succ
def programs(seed, count, nvars=(2, 8), nnodes=(1, 25)):
rng = random.Random(seed)
for _ in range(count):
yield rng, random_cfg(rng, rng.randint(*nvars), rng.randint(*nnodes))
def test_sparse_equals_dense():
for _, (stmts, succ) in programs(2011, 400):
aux = andersen(stmts)
IN, OUT = dense(stmts, succ, aux)
ins, outs, _ = sparse_fs(stmts, succ)
for (u, w), s in ins.items():
assert s == IN[u][w], (ptsgen.show(stmts), succ, u, w)
for (d, v), s in outs.items():
assert s == OUT[d][v], (ptsgen.show(stmts), succ, d, v)
def test_dense_is_inside_andersen():
strict = 0
for _, (stmts, succ) in programs(2004, 300):
aux = andersen(stmts)
assert aux == ptsgen.least_solution(stmts)
IN, OUT = dense(stmts, succ, aux)
for n in IN:
for w, s in IN[n].items():
assert s <= aux[w]
strict += s < aux[w]
assert strict > 0
def run(stmts, succ, rng, steps=60):
"""One random walk from the entry. Each execution of x = &h with a heap
name h makes a fresh object (h, k). Yields (node, memory) before each
node. A load or store through a pointer with no value stops the walk."""
mem = {}
n, fresh = 0, 0
for _ in range(steps):
yield n, dict(mem)
kind, x, y = stmts[n]
if kind == "addr":
if is_heap(y):
fresh += 1
mem[x] = (y, fresh)
else:
mem[x] = y
elif kind == "copy":
mem[x] = mem.get(y)
elif kind == "load":
if mem.get(y) is None:
return
mem[x] = mem.get(mem[y])
else:
if mem.get(x) is None:
return
mem[mem[x]] = mem.get(y)
if not succ[n]:
return
n = rng.choice(succ[n])
def name(loc):
return loc if isinstance(loc, str) else loc[0]
def test_sound_against_concrete_runs():
checked = 0
for rng, (stmts, succ) in programs(2003, 300):
aux = andersen(stmts)
IN, _ = dense(stmts, succ, aux)
ins, _, _ = sparse_fs(stmts, succ)
for _ in range(5):
for n, mem in run(stmts, succ, rng):
for loc, val in mem.items():
if val is not None:
assert name(val) in IN[n][name(loc)], (ptsgen.show(stmts), succ)
if (n, name(loc)) in ins:
assert name(val) in ins[(n, name(loc))]
checked += 1
assert checked > 500
History
Sparse evaluation of dataflow problems along def-use chains is older than pointer analysis on SSA form. For pointer analysis the difficulty was that the def-use chains of memory depend on the points-to result itself. Hardekopf and Lin (2009) first made the top-level variables sparse in a semi-sparse analysis. In 2011 they added the staging: a flow-insensitive analysis first gives safe def-use chains for memory, and the flow-sensitive analysis then runs only along them. Later frameworks for LLVM build a sparse value-flow graph in the same way.
References
- Ben Hardekopf and Calvin Lin, Flow-sensitive pointer analysis for millions of lines of code, Proceedings of CGO 2011, the staged analysis with an auxiliary flow-insensitive analysis, def-use chains for address-taken variables and strong updates on singleton targets
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 9J9RX5 Edit this page History Report an error Markdown