Algorithm Search⌘K

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.

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)
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
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 nn variables, and the output is the least solution LL 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 q→pq \to p 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.

  1. OVS(S)
  2. 1G <- the graph with an edge q -> p for each p = q in S
  3. 2X <- the variables p with p = &a or p = *q in S, and the a with p = &a in S
  4. 3for each strongly connected component C of G, in topological order do
  5. 4if C has a variable in X then label[C] <- a fresh label
  6. 5else P <- the labels of the components with an edge into C, without EMPTY
  7. 6if P is empty then label[C] <- EMPTY
  8. 7else if P has one label l then label[C] <- l
  9. 8else label[C] <- a fresh label
  10. 9rep[v] <- the first variable with the label of v, for each variable v
  11. 10S' <- S with each variable v replaced by rep[v], except the a of p = &a; drop the copies r = r and repeats
  12. 11M <- the result of Andersen's solver on S', with the set of a location a kept at rep[a]
  13. 12return 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 qq and rr are in one group, a pointer to qq does not point to rr. 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 p→qp \to q, q→rq \to r, r→sr \to s, s→rs \to r, q→uq \to u and s→us \to u. The set XX is {p,a,b,t}\{p, a, b, t\}: pp and aa are the left sides of p = &a and a = &b, aa and bb have their addresses taken, and tt is the left side of a load.

component in XX labels of the sources label
{p}\{p\} yes 1 (fresh)
{a}\{a\}, {b}\{b\}, {t}\{t\} yes a fresh label each
{q}\{q\} no {1}\{1\} from pp 1
{r,s}\{r, s\} no {1}\{1\} from qq 1
{u}\{u\} no {1}\{1\} from qq and ss 1

So pp, qq, rr, ss and uu form one group with the representative pp. The variable uu 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 M(p)={a}M(p) = \{a\}, M(a)={b}M(a) = \{b\} and M(t)={b}M(t) = \{b\} on four nodes instead of eight variables. Line L12 gives pts(q)=pts(r)=pts(s)=pts(u)={a}pts(q) = pts(r) = pts(s) = pts(u) = \{a\}, 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 qq would have its address taken. It would be in XX and get a fresh label, since the store writes dd into its set but not into the set of pp.

Correctness

The full proof is in the proof file. Its steps:

  1. A direct component gets only what its sources give. If no variable of a component is in XX, 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 LL 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 XX.
  2. 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.
  3. 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 SS of mm statements in the four forms over nn variables, each variable also a location. LL is the least solution of the subset constraints of Andersen's analysis: p = &a gives a∈L(p)a \in L(p), p = q gives L(q)⊆L(p)L(q) \subseteq L(p), p = *q gives L(a)⊆L(p)L(a) \subseteq L(p) for a∈L(q)a \in L(q), and *p = q gives L(q)⊆L(a)L(q) \subseteq L(a) for a∈L(p)a \in L(p). LL lies inside every solution. The copy graph GG has an edge q→pq \to p for each copy p = q with p≠qp \ne q. The set XX of line L2 holds every pp with a statement p = &a or p = *q, and every aa with a statement p = &a. A variable not in XX is direct.

Every element of L(p)L(p) is a location aa with a statement x = &a, since the set of such locations, given to every variable, is a solution. So L(p)⊆XL(p) \subseteq X for all pp, and a store *p = q adds only to the sets of variables in XX.

Lemma 1 (a direct component gets only what its sources give). Let CC be a strongly connected component of GG with no variable of XX, and let UU be the union of L(q)L(q) over the edges q→xq \to x with x∈Cx \in C and q∉Cq \notin C. Then L(x)=UL(x) = U for every x∈Cx \in C.

Proof. Each such edge is a copy, so U⊆L(x)U \subseteq L(x) for some x∈Cx \in C, and since the members of CC lie on cycles of copies, LL is the same on all of CC and contains UU. For the other direction, let TT be LL with every set of CC replaced by UU, so T≤LT \le L. We show that TT is a solution; then L≤TL \le T by minimality, and L=TL = T on CC. Take the constraints that involve a member xx of CC.

  • On the left. xx is direct, so the only statements with xx on the left are copies x = q. If q∈Cq \in C, then T(q)=U=T(x)T(q) = U = T(x). If not, T(q)=L(q)⊆UT(q) = L(q) \subseteq U. No store adds to T(x)T(x), since x∉Xx \notin X and the sets of TT hold only locations in XX.
  • On the right. For p = x, T(x)=U⊆L(x)⊆L(p)T(x) = U \subseteq L(x) \subseteq L(p), and if p∈Cp \in C then T(p)=UT(p) = U too. For p = *x and *x = q, each a∈T(x)⊆L(x)a \in T(x) \subseteq L(x) is in XX, so a∉Ca \notin C, and the constraints of LL for aa give what is needed. For *p = x, each a∈T(p)a \in T(p) has T(x)⊆L(x)⊆L(a)=T(a)T(x) \subseteq L(x) \subseteq L(a) = T(a), since a∈Xa \in X.
  • xx is never a location in a set, since x∉Xx \notin X. □\square

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 LL, 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 ll in line L7 is direct, and every component with an edge into it has the label ll or EMPTY; by the induction hypothesis these have one common set LlL_l or the empty set, and by Lemma 1 the component has the set LlL_l. □\square

Theorem 1 (correctness). Let S′S' be the statements of SS rewritten by line L10, and let MM be the least solution of S′S' with the set of a location aa kept at the node rep(a)rep(a). Then M(rep(v))=L(v)M(rep(v)) = L(v) for every variable vv.

Proof. In S′S' each statement p = &a becomes rep(p) = &a, p = q becomes rep(p) = rep(q), p = *q gives M(rep(a))⊆M(rep(p))M(rep(a)) \subseteq M(rep(p)) for a∈M(rep(q))a \in M(rep(q)), and *p = q gives M(rep(q))⊆M(rep(a))M(rep(q)) \subseteq M(rep(a)) for a∈M(rep(p))a \in M(rep(p)).

First, LL read on the nodes, N(r)=L(r)N(r) = L(r) for each representative rr, is a solution of S′S'. By Lemma 2, L(rep(v))=L(v)L(rep(v)) = L(v) for every vv, so each rewritten constraint for NN is the original constraint for LL, with each variable vv replaced by rep(v)rep(v) and the same sets. So M≤NM \le N, that is, M(rep(v))⊆L(v)M(rep(v)) \subseteq L(v).

Second, T(v)=M(rep(v))T(v) = M(rep(v)) is a solution of SS, since each original constraint for TT is exactly the rewritten constraint for MM. So L≤TL \le T, that is, L(v)⊆M(rep(v))L(v) \subseteq M(rep(v)). □\square

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 O(n+m)O(n + m) 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 O(n′2n+n+m)O(n'^2 n + n + m), where n′≤nn' \le n is the number of representatives. This is within the O(n3+m)O(n^3 + m) bound of Andersen's analysis.

Proof. The copy graph has at most mm edges. Tarjan's algorithm finds its components in O(n+m)O(n + m) time. Line L5 looks at each edge into each component once, so all labels cost O(n+m)O(n + m). Lines L9 and L10 take O(n+m)O(n + m). The rewritten system has n′n' nodes, and its sets hold at most nn locations. After the repeats are dropped, each node has at most n′n' loads, n′n' stores and n′n' successors. Each of the at most n′2n'^2 edges is added once, and its first transfer of a set costs O(n)O(n). Each location enters the set of each node once, so each of the n′nn' n pairs of a node and a location is handled once, at a cost of O(n′)O(n') for the loads, the stores and the successors of the node. The total is O(n′2n)O(n'^2 n) for the solver. □\square

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 O(n+m)O(n + m) 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 n′≤nn' \le n nodes, with sets of at most nn locations, in O(n′2n)O(n'^2 n) time with difference propagation. The total is within Andersen's bound of O(n3+m)O(n^3 + m) time and O(n2+m)O(n^2 + m) 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 = &a must keep aa as it is, and the solver must read the set of aa at rep(a)rep(a). Replacing aa by rep(a)rep(a) in the sets makes a pointer to aa 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.

offline_variable_substitution.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/Q7GZTS/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example