Algorithmcore
Steensgaard's analysis
Also called unification-based points-to analysis.
Flow-insensitive points-to analysis that unifies the targets of both sides of each assignment, with union-find, in almost linear time.
- Solves
- Points-to analysis
- Time
- O((n + m) α(n + m)) worst
- Space
- O(n + m) extra
- Where
- m = the number of pointer statements; n = the number of variables; α = the inverse Ackermann function
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveonlineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Bjarne Steensgaard, 1996
Steensgaard's analysis solves the points-to analysis problem by unification. Where Andersen's analysis reads p = q as "the set of p contains the set of q", Steensgaard's analysis reads it as "p and q point into the same class of locations". The locations are kept in classes with union-find, each class points to at most one class, and every statement merges a few classes. One pass over the statements is enough, and the total time is almost linear in the size of the program. The sets are larger than Andersen's, and the proof file shows that they always contain them.
In plain words
Think of the memory cells of a program as grouped into boxes, where every box has at most one arrow to another box. A pointer in a box can point to any cell in the box at the end of the arrow. When the program copies one pointer into another, the analysis makes them use the same target box: if the two boxes they point to are different, it pours one into the other. Pouring two boxes together also pours together the boxes that they point to. Each statement is read once, and each pour is quick with the union-find structure. The answer is safe, because every cell a real run can use ends up in the right box. It is coarse, because cells that were only copied in one direction still share a box.
The problem
The input is a set of statements over variables in the forms p = &a, p = q, p = *q and *p = q; p = alloc at site is treated as p = &h_k. The output is a set for each variable that meets the subset constraints of Andersen's analysis. Steensgaard's analysis computes more: a partition of the locations into classes and, for each class, at most one target class, such that:
- for
p = &a, the class of is the target of the class of ; - for
p = q, if the class of has a target, the class of has the same target; - for
p = *qand*p = q, the same rule applies between and the target class of , or between the target class of and .
Then is the set of variables in the target class of the class of . Steensgaard wrote these rules as a type system: the type of a location is a reference to the class of its targets, and the analysis is type inference. The analysis in the terms of a data-flow framework:
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | partitions of the locations, with at most one target class per class |
| order | the partition is coarser and the target map follows it (bottom is precise) |
| join | merging classes (union-find) |
| bottom and top | all classes single, with no targets; one class that points to itself |
| boundary value | none |
| initial value | each location in its own class, with no target |
| transfer | monotone, not distributive |
The algorithm
Each root of the union-find forest has a target , or none, and a list . A copy p = q when has no target yet must not invent one: that would merge the classes of and for nothing. So ASSIGN puts on the pending list of , and the join happens only if gets a target later. Steensgaard calls this a conditional join. JOIN merges two classes and then their targets.
STEENSGAARD(S)- 1
make a class for each variable, with no target and an empty pending list - 2
for each statement of S, in any order do - 3
p = &a: if class(p) has no target then SET-TARGET(class(p), class(a)) - 4
else queue JOIN(pt(class(p)), class(a)) - 5
p = q: ASSIGN(class(p), class(q)) - 6
p = *q: ASSIGN(class(p), DEREF(class(q))) - 7
*p = q: ASSIGN(DEREF(class(p)), class(q)) - 8
run the queued operations until the queue is empty - 9
return S(v) = the variables in the class pt(class(v)), for each v DEREF(c)- 10
if c has no target then SET-TARGET(c, a new class) - 11
return pt(c) ASSIGN(x, y) the targets of x must include those of yif x = y then return- 12
if y has no target then add x to pending(y) - 13
else if x has no target then SET-TARGET(x, pt(y)) - 14
else queue JOIN(pt(x), pt(y)) JOIN(c1, c2)if c1 = c2 then return- 15
c <- UNION(c1, c2) - 16
if neither had a target then pending(c) <- pending(c1) + pending(c2) - 17
else if one had no target then pt(c) <- the other target; queue ASSIGN(d, c) for each d pending on the one with no target - 18
else pt(c) <- pt(c1); queue JOIN(pt(c1), pt(c2)) SET-TARGET(c, t)- 19
pt(c) <- t - 20
queue ASSIGN(d, c) for each d in pending(c); pending(c) <- empty
The paper writes JOIN and the conditional join as recursive procedures. The implementation uses one queue of operations instead, so long chains of joins do not use the call stack. The union-find forest uses union by rank and path compression, as in a disjoint-set forest.
Example
The same program as on the Andersen page:
entry:
p = &a
q = &b
r = &p
s = q
*r = s
t = *r
ret 0
| statement | what happens | classes and targets after it |
|---|---|---|
p = &a |
had no target | |
q = &b |
had no target | |
r = &p |
had no target | |
s = q |
ASSIGN: has a target, has none, so gets it | |
*r = s |
DEREF is ; ASSIGN: both and have targets, so JOIN | is one class; |
t = *r |
DEREF is ; ASSIGN gives the target of |
The result is and . Andersen's analysis gives for and : here the store *r = s merged and , and since and already shared the class , the merge reached them too.
The pending lists matter for statements in the other order. In p = q followed by q = &b, the first statement finds that has no target and puts on its pending list; the second gives the target , and SET-TARGET then runs ASSIGN for , so . A version without pending lists would make a placeholder target for at the first statement, which gives the same sets here, but in larger programs it merges classes that never needed to meet.
Correctness
The full proof is in the proof file. Its steps:
- A target, once set, stays. A class with a target keeps one when it merges, and the old and the new targets end up in one class, because the JOIN of line L18 runs before the end.
- A pending copy is not lost. If ASSIGN runs and the class of has a target at the end, then the classes of and have the same target at the end. The pending entry moves with the class until the class gets a target, and then it becomes an ASSIGN again.
- The result is a solution. With steps 1 and 2, each of the four statement forms meets its subset constraint. For a load
p = *q, every in is in the target class of , which is the class that DEREF returned, and its target is the target of . - It contains Andersen's result. Andersen's sets are the least solution, so they are inside every solution, and in particular inside .
The sets have one more property: two sets are equal or disjoint, because each is a whole class.
Proof: Steensgaard's analysis gives a solution of the subset constraints, so its sets contain Andersen's, in almost linear timefull
Setting. The program is a set of statements in the four forms p = &a, p = q, p = *q and *p = q over variables, and each variable is also a location. The constraints of a statement are those of Andersen's analysis, and is their least solution in the order on each set. The proof of the Andersen page shows that for every solution .
The algorithm keeps a union-find forest over the variables and the fresh classes made in line L10. For a root , is a class or none, and is a list of classes. At the end, is the root of , is the root of when is set, and
or the empty set when has no target. All operations queued while a statement is read run in line L8 before the next statement, so no operation is left in the queue at the end. We write if and are in the same class at the end. Classes only merge, so two elements in one class at some moment are in one class at the end.
Lemma 1 (a target, once set, stays). If at some moment the root of the class of has the target , then at the end has a target and .
Proof. A target is written only in line L19, which is called only for a root with no target, and in lines L17 and L18, when two roots merge. So a root with a target keeps it until its class merges with another. We use induction on the number of later merges of the class of . With none, the root of at the end still has . At the next merge, the class of , with target , merges with a class with target or with none. If the other class has none, line L17 gives the new root the target . If it has , line L18 gives the new root one of and and queues JOIN, which runs before the end, so . In both cases the new root has a target with , and the induction hypothesis for the remaining merges gives .
Lemma 2 (a pending copy is not lost). If ASSIGN runs, then at the end either has no target, or both and have targets and .
Proof. Let and be the roots when ASSIGN runs. If , there is nothing to show. If is set and is not, line L13 sets the target of to , and Lemma 1, used for and for , gives . If both are set, line L14 queues JOIN, and Lemma 1 again gives the claim. If is not set, line L12 puts on . As long as the class of has no target, a merge with another class with no target keeps the entry on the joined list (line L16). The class of gets a target only in line L19 or line L17, and both queue ASSIGN for every on its list, with the root of the class of . That ASSIGN runs with set, so it falls in one of the cases above. If the class of never gets a target, then has none at the end.
Theorem 1 (the result is a solution). meets every constraint of the program.
Proof. Take each statement form.
p = &a. Line L3 sets the target of to the class of , or line L4 queues JOIN. By Lemma 1, , so .p = q. Line L5 runs ASSIGN. If has no target, . Otherwise, by Lemma 2, and .p = *q. Line L6 gets from DEREF, so by Lemma 1, and then runs ASSIGN. Let . Then . If this class has no target, . Otherwise Lemma 2 gives , so .*p = q. Line L7 gets , with , and runs ASSIGN. Let , so . If has no target, . Otherwise Lemma 2 gives , so .
Corollary (containment). for every variable : Steensgaard's sets contain Andersen's. This is the least-solution property of applied to the solution . In particular is sound for every run that executes the statements in any order, by the soundness argument of the Andersen page.
Unification. For any and , and are equal or disjoint, since each is one whole class of variables or empty. So two pointers whose sets meet always have the same set. This is the loss of precision against Andersen.
Theorem 2 (time). With linked lists for the pending lists, and union by rank with path compression, the algorithm takes time and space to compute the classes and their targets. Listing the sets costs their total size more.
Proof. There are at most classes: one per variable, and at most one fresh class per load or store, made in line L10. Count the operations.
- Each statement runs one of lines L3 to L7: at most one SET-TARGET, one queued JOIN, one ASSIGN and two DEREF.
- An ASSIGN puts an entry on a pending list at most once, and an entry is taken off once, when its class gets a target, and then gives one ASSIGN that cannot add to a pending list again, because the class it reads now has a target. So there are at most ASSIGN operations, and each queues at most one JOIN.
- A JOIN that merges two classes lowers the number of classes by one, so at most JOINs merge. Each queues at most one more JOIN in line L18. A JOIN that finds both arguments in one class does nothing else.
- So the number of JOINs is at most from line L4, plus from line L14, plus from line L18. The ASSIGNs queued by lines L17 and L20 number at most the pending entries, at most .
Every operation does finds and unions plus other work, since joining two linked lists is . In total there are operations on the union-find forest, which cost by the bound of Tarjan for union by rank with path compression. The space is one record per class and one per pending entry.
The implementation joins two pending lists by appending the shorter Python list to the longer one. An entry then moves only when its list at least doubles, so it moves times, and this part costs in the worst case instead of .
Complexity
Proved. There are at most classes, one per variable and one fresh class per load or store at most. Each statement queues operations; each pending entry is added once and fired once; each JOIN that merges removes a class and queues at most one more JOIN. So there are operations, each with finds and unions. With union by rank and path compression the total time is , where is the inverse Ackermann function, and the space is . This assumes pending lists that join in , such as linked lists; the implementation appends the shorter list to the longer, which costs for that part. Writing out all the sets costs their total size, up to , so a client should query the classes instead.
Stated in the paper, not proved here. Steensgaard states the bound in the size of the program, for full C with structures and function pointers, and reports that the analysis of a C program of about 75,000 lines took about 27 seconds on an SGI Indigo2 workstation of the time.
Measured, not proved. In the seeded tests of the implementation, on 400 random programs of up to 30 statements, the sets of every variable contained Andersen's sets, and on 200 programs, three random orders of the statements each gave the same result.
Properties
- Online. Each statement is read once, in any order, and the classes after a prefix of the statements are already correct for that prefix. The analysis can run while a compiler reads the program.
- Sets are equal or disjoint. Two pointers that may point to one common location have the same set. This is what makes the result so small to store: one target per class.
- Bidirectional loss. A copy
p = qmakes the targets of visible to and also the targets of visible to . - Not recursive in the code. The queue replaces the recursion of JOIN.
- Result independent of the order. The tests found no case where the order of the statements changed the result.
Variants and improvements
- One-level flow. Das's one-level flow keeps the subset direction for top-level copies, which are most of the copies in C, and unifies below that. Its precision is close to Andersen's at a cost close to Steensgaard's.
- Fields. Steensgaard's paper treats a structure as one location. Later work gives each field its own class; see field sensitivity.
- Context sensitivity. Unification works well with context sensitivity by cloning: the classes of a function are copied at each call, as the type of a polymorphic function is copied at each use.
- Andersen's analysis. Andersen's analysis keeps the subset direction everywhere, for more precision and up to cubic time.
- Type inference. The same union-find method solves the unification problem for first-order terms and the type equations of the Hindley-Milner type system.
When to use it
Use it when the program is very large or the analysis must run in a compile pass, and coarse sets are acceptable. It is a good first pass that tells which pointers can never alias, and it can split a program into parts that a more precise analysis then studies apart. When the clients need precise sets, such as call graphs through function pointers or alias queries for an optimizer, use Andersen's analysis or one-level flow.
Pitfalls
- Joining on copies from pointers with no target. If
p = qmerges the targets of and even when has none yet, a placeholder target is made and later joined with real targets; the result is still sound but coarser. The pending lists avoid this. - Forgetting to join targets. When two classes merge, their targets must merge too. Without line L18 the classes no longer have one target each, and the result misses facts.
- Reading sets as precise. Equal sets do not mean the two pointers were copied into each other. Unification merges along the whole chain of statements, as in the example, where gets .
- Recursion depth. A program with a long chain of pointers to pointers gives a long chain of JOINs. A recursive JOIN can overflow the stack on such input.
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
steensgaard_analysis.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/steensgaard-analysis/. The authors are listed in prov/EFB787.jsonl.
"""Steensgaard's unification-based points-to analysis.
steensgaard(stmts) takes statements in the four forms of ptsgen and returns
a dict from each variable to the set of variables it may point to. The
locations are split into classes kept in a union-find forest. Each class
has at most one target class, pt, or none (bottom). A copy p = q is a
conditional join: if q has no target yet, p is put on the pending list of
q, and the join waits until q gets a target. Joining two classes also joins
their targets. All the work goes through one queue of operations, so the
code has no recursion.
classes(stmts) returns the classes of the program variables and the target
class of each, for display.
"""
from collections import deque
import ptsgen
def _solve(stmts):
names = ptsgen.variables(stmts)
parent = {}
rank = {}
pt = {} # target class of a root, or None for bottom
pending = {} # roots waiting for this root to get a target
ops = deque()
def make(key):
parent[key] = key
rank[key] = 0
pt[key] = None
pending[key] = []
return key
def find(x):
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
parent[x], x = root, parent[x]
return root
def set_target(c, t):
pt[c] = t # @line L19
for d in pending[c]:
ops.append(("assign", d, c)) # @line L20
pending[c] = []
def deref(c):
"""The target class of c; a fresh class if c has none."""
c = find(c)
if pt[c] is None:
set_target(c, make(("fresh", len(parent)))) # @line L10
return find(pt[c]) # @line L11
def assign(cx, cy):
"""The targets of cx must include those of cy."""
cx, cy = find(cx), find(cy)
if cx == cy:
return
if pt[cy] is None:
pending[cy].append(cx) # @line L12
elif pt[cx] is None:
set_target(cx, pt[cy]) # @line L13
else:
ops.append(("join", pt[cx], pt[cy])) # @line L14
def join(c1, c2):
c1, c2 = find(c1), find(c2)
if c1 == c2:
return
t1, t2, p1, p2 = pt[c1], pt[c2], pending[c1], pending[c2]
if rank[c1] < rank[c2]:
c1, c2 = c2, c1
parent[c2] = c1 # @line L15
if rank[c1] == rank[c2]:
rank[c1] += 1
c = c1
pt[c], pending[c] = None, []
if t1 is None and t2 is None: # @line L16
# Append the shorter list to the longer one; a linked list
# would do this in O(1).
longer, shorter = (p1, p2) if len(p1) >= len(p2) else (p2, p1)
longer.extend(shorter)
pending[c] = longer
elif t1 is None or t2 is None: # @line L17
set_target(c, t1 if t1 is not None else t2)
for d in p1 if t1 is None else p2:
ops.append(("assign", d, c))
else:
pt[c] = t1 # @line L18
ops.append(("join", t1, t2))
for v in names:
make(v) # @line L1
for kind, x, y in stmts: # @line L2
if kind == "addr":
cx = find(x)
if pt[cx] is None:
set_target(cx, find(y)) # @line L3
else:
ops.append(("join", pt[cx], y)) # @line L4
elif kind == "copy":
assign(x, y) # @line L5
elif kind == "load":
assign(x, deref(y)) # @line L6
else:
assign(deref(x), y) # @line L7
while ops: # @line L8
op, a, b = ops.popleft()
if op == "assign":
assign(a, b)
else:
join(a, b)
return names, find, pt
def steensgaard(stmts):
names, find, pt = _solve(stmts)
members = {}
for a in names:
members.setdefault(find(a), set()).add(a)
pts = {}
for v in names:
t = pt[find(v)]
pts[v] = set() if t is None else set(members.get(find(t), ())) # @line L9
return pts
def classes(stmts):
"""The classes of the program variables, each a sorted list, and a dict
from the index of each class to the index of its target class, if the
target holds a program variable."""
names, find, pt = _solve(stmts)
by_root = {}
for v in names:
by_root.setdefault(find(v), []).append(v)
roots = sorted(by_root, key=lambda r: sorted(by_root[r]))
groups = [sorted(by_root[r]) for r in roots]
index = {r: i for i, r in enumerate(roots)}
target = {}
for r in roots:
t = pt[r]
if t is not None and find(t) in index:
target[index[r]] = index[find(t)]
return groups, target
def points_to(text):
return steensgaard(ptsgen.parse(text))
test_steensgaard_analysis.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/steensgaard-analysis/. The authors are listed in prov/EFB787.jsonl.
import random
import ptsgen
from steensgaard_analysis import classes, points_to, steensgaard
PAGE = """
entry:
p = &a
q = &b
r = &p
s = q
*r = s
t = *r
ret 0
"""
def test_page_example():
pts = points_to(PAGE)
ab = {"a", "b"}
assert pts == {"p": ab, "a": set(), "q": ab, "b": set(), "r": {"p"}, "s": ab, "t": ab}
groups, target = classes(ptsgen.parse(PAGE))
assert groups == [["a", "b"], ["p"], ["q"], ["r"], ["s"], ["t"]]
assert target == {1: 0, 2: 0, 3: 1, 4: 0, 5: 0}
def test_copy_from_a_pointer_with_no_target_waits():
# q has no target when p = q is seen; the join waits on the pending list
# and happens when q = &b arrives. No placeholder is joined with b.
pts = points_to("p = q\nq = &b")
assert pts == {"p": {"b"}, "q": {"b"}, "b": set()}
# A copy between two pointers that never get targets merges nothing.
assert points_to("p = q\nr = &a") == {"p": set(), "q": set(), "r": {"a"}, "a": set()}
def test_unification_merges_targets():
# Two different targets of one pointer end up in one class.
pts = points_to("p = &a\np = &b\nq = &a")
assert pts["q"] == {"a", "b"}
def test_store_and_load_through_unknown_targets():
# *p = q before p has a target makes a placeholder class; p = &a later
# joins a with it, so a gets the target of q.
pts = points_to("*p = q\nq = &x\np = &a\nr = *p")
assert pts["a"] == {"x"} and pts["r"] == {"x"}
def is_unification(pts):
# Two sets are equal or disjoint, as in a storage graph where each
# class points to at most one class.
sets = [frozenset(s) for s in pts.values() if s]
return all(a == b or not (a & b) for a in sets for b in sets)
def test_contains_andersen_on_random_programs():
rng = random.Random(1996)
for trial in range(400):
stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
pts = steensgaard(stmts)
least = ptsgen.least_solution(stmts)
for v in least:
assert least[v] <= pts[v], ptsgen.show(stmts)
assert ptsgen.is_solution(stmts, pts)
assert is_unification(pts)
def test_order_of_statements_does_not_change_the_result():
rng = random.Random(11)
for trial in range(200):
stmts = ptsgen.random_program(rng, rng.randint(2, 10), 30)
first = steensgaard(stmts)
for _ in range(3):
shuffled = stmts[:]
rng.shuffle(shuffled)
assert steensgaard(shuffled) == first, ptsgen.show(stmts)
def test_sound_against_concrete_runs():
rng = random.Random(42)
for trial in range(150):
stmts = ptsgen.random_program(rng, rng.randint(3, 10), 30)
pts = steensgaard(stmts)
for p, a in ptsgen.concrete_facts(stmts, rng, runs=10, steps=150):
assert a in pts[p]
def test_long_chain_needs_no_recursion():
# p0 = &p1, p1 = &p2, ..., and a copy that joins the two ends of the
# chain; the joins run through the queue, not the call stack.
n = 3000
lines = ["p%d = &p%d" % (i, i + 1) for i in range(n)]
lines += ["q%d = &p%d" % (i, i) for i in range(1, n, 2)]
lines += ["x = q1", "x = q%d" % (n - 1)]
pts = points_to("\n".join(lines))
assert pts["x"] == pts["q1"] and "p1" in pts["x"] and "p%d" % (n - 1) in pts["x"]
History
Bjarne Steensgaard presented the analysis at POPL 1996, as an answer to the cubic cost of Andersen's analysis. He described it as type inference with a non-standard type system for C and solved it with union-find, the method of type inference for ML-like languages. The conditional join with pending sets was his device to avoid merging classes for copies of pointers that never point anywhere. Das (2000) showed that keeping the direction at the top level gives most of Andersen's precision at almost the same cost. Unification remains the basis of fast analyses in compilers and of context-sensitive analyses by cloning.
References
- Bjarne Steensgaard, Points-to analysis in almost linear time, Proceedings of the 23rd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '96), 32 to 41, 1996, the non-standard type system for C, the equivalence class representatives with fast union-find, the conditional join with pending sets, the O(N α(N, N)) bound and the timings on C programs
- Manuvir Das, Unification-based pointer analysis with directional assignments, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2000), 35 to 46, the comparison of the precision of Steensgaard's analysis, one-level flow and Andersen's analysis on C programs
- Michael Hind, Pointer analysis, haven't we solved this problem yet?, Proceedings of the ACM SIGPLAN-SIGSOFT Workshop on Program Analysis for Software Tools and Engineering (PASTE '01), 54 to 61, 2001, the place of unification-based analyses among the flow-insensitive analyses
- Yannis Smaragdakis and George Balatsouras, Pointer Analysis, Foundations and Trends in Programming Languages 2(1), 1 to 69, 2015, the comparison of unification-based and inclusion-based analyses
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, fourth edition, Chapter 19 (data structures for disjoint sets, union by rank with path compression)
Where this leads
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 EFB787 Edit this page History Report an error Markdown