Algorithm Search⌘K

Algorithmadvanced

Online cycle elimination

Also called cycle elimination in inclusion constraints.

Detects cycles in an inclusion constraint graph while solving and merges their nodes, since all nodes on a cycle have equal sets.

Time
O(n^4 + n^2 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 sensitiveonlineiterative
Origin
Manuel Fähndrich, Jeffrey S. Foster, Zhendong Su, Alexander Aiken, 1998

Online cycle elimination speeds up Andersen's analysis without a change to its result. Andersen's analysis keeps a graph with an edge u→vu \to v for each subset constraint pts(u)⊆pts(v)pts(u) \subseteq pts(v). If the edges form a cycle, every node on it must end with the same set, so the solver can merge the nodes into one and keep one set for all of them. The online method checks for a new cycle each time it adds an edge, while the solver runs, and merges the nodes at once with a disjoint-set forest. Fähndrich, Foster, Su and Aiken (1998) showed that a cheap, partial search for these cycles makes the analysis of large C programs much faster. This page gives a version with a full search, which finds every cycle.

In plain words

Andersen's analysis draws arrows between pointers. An arrow from one pointer to another says that the second can hold every address that the first can hold. If arrows go around a circle, each pointer on the circle can hold the addresses of all the others, so all of them end with the same list. Then there is no need to keep a separate list for each one and to send each new address around the circle again and again. The method looks for a circle each time it draws a new arrow. When it finds one, it joins all the pointers on the circle into one group with one shared list. The final lists are the same as those of Andersen's analysis. Only the work to find them is less.

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 analysis uses the subset order on each set, with the empty sets as bottom, in the direction of Cousot: smaller is more precise. It is flow-insensitive: it ignores the order of the statements, but the statements themselves come from the control flow of the program.

The fact that makes the method work: if the constraint graph has a path u→∗vu \to^* v, then L(u)⊆L(v)L(u) \subseteq L(v), because inclusion is transitive. So on a cycle, LL is the same at every node. Merging the nodes of a cycle into one node, with one set, gives a smaller system with the same least solution. The nodes are merged; the locations stay distinct. If q and r are merged, a pointer that holds the address of q does not also hold the address of r.

The algorithm

The solver is Andersen's worklist solver over the roots of a union-find forest. FIND gives the root of the class of a variable. ADD-EDGE adds the edge, then searches for the roots on a path back from the new target to the new source.

  1. OCE(S)
  2. 1for each variable v do parent[v] <- v; pts[v] <- {}; succ[v] <- {}
  3. 2for each p = &a in S do add a to pts[p]; add p to W
  4. 3for each p = q in S do ADD-EDGE(q, p)
  5. 4while W is not empty do
  6. 5take n from W; if FIND(n) is not n then go to the next n
  7. 6for each a in pts[n] do
  8. 7for each p = *y in S with FIND(y) = n do ADD-EDGE(a, p)
  9. 8for each *y = q in S with FIND(y) = n do ADD-EDGE(q, a)
  10. 9for each w in succ[n] do copy pts[n] into pts[FIND(w)]; if it grew, add FIND(w) to W
  11. 10return pts[FIND(v)] for each variable v
  12. ADD-EDGE(u, v)
  13. 11u <- FIND(u); v <- FIND(v); if u = v or v is in succ[u] then return
  14. 12add v to succ[u]
  15. 13C <- the roots on some path from v to u
  16. 14if C is not empty then COLLAPSE(C, u); return
  17. 15copy pts[u] into pts[v]; if it grew, add v to W
  18. COLLAPSE(C, r)
  19. 16for each x in C other than r do
  20. 17parent[x] <- r; add pts[x], succ[x] and the loads and stores of x to those of r
  21. 18succ[r] <- {FIND(w) : w in succ[r]} without r; add r to W

Line L13 is two depth-first searches: one forward from vv, and one backward from uu inside the part that the first reached. The roots on some path from vv to uu are the roots that both searches visit. The merged root is pushed on the worklist in line L18, so its loads and stores are processed for the union of the sets. The implementation keeps the loads and stores of each root in tables, so lines L7 and L8 look only at the statements of the class nn.

Example

The program, in the toy IR:

entry:
  p = &a
  a = &x
  q = *p
  r = q
  a = r
  s = &b
  r = s
  ret 0

The copies give the edges q→rq \to r, r→ar \to a and s→rs \to r. The load q = *p gives the edge a→qa \to q once aa is in the set of pp, and that edge closes the cycle a→q→r→aa \to q \to r \to a.

step line what happens
1 L2 pts(p)={a}pts(p) = \{a\}, pts(a)={x}pts(a) = \{x\}, pts(s)={b}pts(s) = \{b\}; the worklist is p,a,sp, a, s
2 L3 r = q: edge q→rq \to r; no path from rr to qq
3 L3 a = r: edge r→ar \to a; no path from aa to rr
4 L3 r = s: edge s→rs \to r; no path back; pts(r)={b}pts(r) = \{b\}; rr joins the worklist
5 L7 take pp: a∈pts(p)a \in pts(p) and q = *p give ADD-EDGE(a,q)(a, q); the search from qq finds q→r→aq \to r \to a, so C={a,q,r}C = \{a, q, r\}
6 L16 to L18 qq and rr merge into aa: pts(a)={x}∪{b}={x,b}pts(a) = \{x\} \cup \{b\} = \{x, b\}; the edges inside CC disappear
7 L9 take aa: no loads, stores or edges
8 L9 take ss: the edge s→rs \to r is now s→as \to a, and bb is already in the set
9 L5 take rr: not a root, so skip it

The result is pts(a)=pts(q)=pts(r)={x,b}pts(a) = pts(q) = pts(r) = \{x, b\}, pts(p)={a}pts(p) = \{a\}, pts(s)={b}pts(s) = \{b\}, and empty sets for xx and bb. This is the result of Andersen's analysis. There were two merges. The set of pp is {a}\{a\} and not {a,q,r}\{a, q, r\}: the three variables share one set as pointers, but they are still three locations.

Correctness

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

  1. Every step is forced. Every edge u→vu \to v that the solver adds has L(u)⊆L(v)L(u) \subseteq L(v), and every set stays inside LL. A merged set CC lies on the cycle u→v→∗x→∗uu \to v \to^* x \to^* u, and LL cannot shrink along an edge, so LL is the same at every node of CC, and the union of their sets is still inside it.
  2. The graph stays acyclic. If the graph has no cycle before an edge u→vu \to v is added, every new cycle goes through the path from vv to uu, and all its nodes are merged. A cycle through the merged node would need a node outside CC on a path from vv to uu, which cannot be.
  3. What is done stays done. A root that is not on the worklist has the edges for the loads and stores of all its elements, and its set is inside the set of each successor. A merge or a growing set puts the root back on the worklist.
  4. At the end, the sets are LL. With the worklist empty, the sets meet every constraint, so they contain LL, and with step 1 they equal LL.

The proof uses only the fact that the merged nodes lie on a cycle. So a partial search, which can miss some cycles, gives the same result.

Proof: Collapsing cycles online keeps the least solution of the subset constraints, and the graph of classes stays acyclicfull

Setting. The program is a set 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 algorithm keeps a union-find forest over the variables. For a variable vv, [v][v] is the root of its class. Each root rr has a set pts(r)pts(r), a set of successors succ(r)succ(r), and the loads and stores of all members of its class. An edge r→wr \to w is read on the roots, as [r]→[w][r] \to [w]. The result is S(v)=pts([v])S(v) = pts([v]). For a class cc we write L(c)=L(v)L(c) = L(v) for a member vv; Lemma 1 shows that this does not depend on the member.

Lemma 1 (every step is forced). At every moment:

  1. all members of a class have the same LL;
  2. pts(r)⊆L(r)pts(r) \subseteq L(r) for every root rr;
  3. every edge r→wr \to w has L(r)⊆L(w)L(r) \subseteq L(w).

Proof. At the start every class has one member, all sets are empty and there are no edges. Take each step.

  • Line L2 puts aa into pts(p)pts(p) for a statement p = &a, and a∈L(p)a \in L(p).
  • Line L3 adds the edge [q]→[p][q] \to [p] for p = q, and L(q)⊆L(p)L(q) \subseteq L(p).
  • Line L7 adds [a]→[p][a] \to [p], where a∈pts(r)a \in pts(r) and p = *y is a statement with yy in the class rr. By part 2, a∈L(r)=L(y)a \in L(r) = L(y), so the load constraint gives L(a)⊆L(p)L(a) \subseteq L(p).
  • Line L8 adds [q]→[a][q] \to [a] for *y = q with yy in the class rr and a∈pts(r)⊆L(y)a \in pts(r) \subseteq L(y), so the store constraint gives L(q)⊆L(a)L(q) \subseteq L(a).
  • Lines L9 and L15 copy pts(u)pts(u) into pts(v)pts(v) along an edge u→vu \to v. By parts 2 and 3, pts(u)⊆L(u)⊆L(v)pts(u) \subseteq L(u) \subseteq L(v).
  • Line L14 merges the set CC of roots that lie on some path from vv to uu, just after line L12 added the edge u→vu \to v. Every x∈Cx \in C lies on the cycle u→v→∗x→∗uu \to v \to^* x \to^* u. By part 3, LL cannot shrink along an edge, so it is the same on the whole cycle: L(x)=L(u)L(x) = L(u) for every x∈Cx \in C. So part 1 holds for the new class, the union of the old sets is inside this common LL, and the edges keep their ends' LL. □\square

Lemma 2 (the graph of classes has no cycle). After every call of ADD-EDGE, the graph of roots and edges has no cycle, other than edges from a root to itself, which are dropped.

Proof. By induction. Suppose the graph has no cycle before ADD-EDGE adds u→vu \to v. A cycle in the new graph must use the new edge, so it is a path from vv to uu, and all its nodes are in CC. If there is no such path, there is no cycle. Otherwise line L14 merges CC into one root rr. Suppose the merged graph has a cycle. It must go through rr, since every other cycle was there before. So there are x,y∈Cx, y \in C and roots a,ba, b outside CC with x→a→∗b→yx \to a \to^* b \to y. Now v→∗xv \to^* x and y→∗uy \to^* u, because xx and yy are on paths from vv to uu. So v→∗a→∗uv \to^* a \to^* u, and aa is on a path from vv to uu, which means a∈Ca \in C, a contradiction. A merge does not add other edges: the successors of rr are the successors of the members of CC, read on the roots. □\square

Lemma 3 (what is done stays done). Call a root rr finished if (A) for every a∈pts(r)a \in pts(r), the edges [a]→[p][a] \to [p] for the loads p = *y and [q]→[a][q] \to [a] for the stores *y = q with yy in the class rr are in the graph, and (B) pts(r)⊆pts(w)pts(r) \subseteq pts(w) for every edge r→wr \to w. Every root that is not on the worklist is finished.

Proof. A root that is not finished got that way in one of these steps: its set grew, it became the root of a merge, or an edge left it. When its set grows (lines L9, L15), it is pushed. When it becomes the root of a merge, line L14 pushes it. When ADD-EDGE adds u→vu \to v and no cycle forms, line L15 makes pts(u)⊆pts(v)pts(u) \subseteq pts(v) at once; when a cycle forms, the edge disappears into the merged root, which is pushed. The set of a successor only grows, so (B) cannot break that way. Each root is taken off the worklist before lines L6 to L9 run for it, and those lines make (A) and (B) true for the set it has then. If the set grows during those lines, the root is pushed again. □\square

Theorem 1 (correctness). The algorithm stops, and S=LS = L.

Proof. Each push comes from a set that grew or from a merge. A set can grow at most nn times per root and there are at most n−1n - 1 merges, so there are at most n2+nn^2 + n pushes, and the loop stops. When it stops, the worklist is empty, so every root is finished by Lemma 3. Take each statement form. For p = &a, a∈pts([p])a \in pts([p]) since sets only grow and merges take the union. For p = q, the edge [q]→[p][q] \to [p] is in the graph, or [q]=[p][q] = [p], and (B) gives S(q)⊆S(p)S(q) \subseteq S(p). For p = *y and a∈S(y)a \in S(y), (A) gives the edge [a]→[p][a] \to [p], so S(a)⊆S(p)S(a) \subseteq S(p). For *y = q and a∈S(y)a \in S(y), (A) gives [q]→[a][q] \to [a], so S(q)⊆S(a)S(q) \subseteq S(a). So SS is a solution and L⊆SL \subseteq S. By Lemma 1, S(v)=pts([v])⊆L([v])=L(v)S(v) = pts([v]) \subseteq L([v]) = L(v). So S=LS = L. □\square

So merging a cycle never changes the answer. It is only a way to store fewer sets and to move each fact along fewer edges.

Theorem 2 (time). With a full search for each new edge, and with each find of the union-find forest counted as one step, the algorithm runs in O(n4+n2m)O(n^4 + n^2 m) time and O(n2+m)O(n^2 + m) space. The finds add at most a factor of O(log⁡n)O(\log n), since the forest uses path compression.

Proof. There are at most n2n^2 distinct edges. Each new edge starts one search, which visits each root and each edge once, in O(n+n2)O(n + n^2) time, so the searches cost O(n4)O(n^4). A merge of CC costs O(∣C∣(n+m))O(|C| (n + m)) for the unions of the sets, the edges and the tables, and each variable stops being a root once, so the merges cost O(n(n+m))O(n (n + m)). Each root is processed once per push, and by the proof of Theorem 1 each variable is pushed O(n)O(n) times as a root. One processing of rr makes ∣pts(r)∣⋅(lr+sr)≤n(lr+sr)|pts(r)| \cdot (l_r + s_r) \le n (l_r + s_r) calls of ADD-EDGE, where lrl_r and srs_r count the loads and stores of the class, and copies pts(r)pts(r) along at most nn edges in O(n2)O(n^2) time. A call of ADD-EDGE that finds the edge already there costs O(1)O(1); the others are the new edges, counted above. Summed over all processings, this is O(n⋅(nm+n3))=O(n2m+n4)O(n \cdot (n m + n^3)) = O(n^2 m + n^4). The sets, the edges and the tables need O(n2+m)O(n^2 + m) space. □\square

The bound is weaker than the O(n3)O(n^3) bound of plain Andersen's analysis with difference propagation, because this version moves full sets and searches the whole graph for every new edge. Online cycle elimination is a practical method: it pays when the graph has large cycles, as the graphs of real C programs do. The partial search of Fähndrich, Foster, Su and Aiken looks at much less of the graph per edge and may miss some cycles; Theorem 1 still holds for it, since it merges only nodes that are on a cycle, and Lemma 1 needs nothing more.

Complexity

Proved. With a full search for each new edge, the time is O(n4+n2m)O(n^4 + n^2 m) and the space is O(n2+m)O(n^2 + m), with each find counted as one step. There are at most n2n^2 edges, and each new one starts a search of O(n2)O(n^2) time. Each root goes back on the worklist O(n)O(n) times, and each visit makes O(n)O(n) calls of ADD-EDGE per load or store of its class and copies its set along O(n)O(n) edges. The bound is worse than the O(n3)O(n^3) bound of Andersen's analysis with difference propagation, because this version moves full sets and searches the whole graph. Cycle elimination does not lower the worst case; its gain is on the graphs of real programs.

Stated in the paper, not proved here. Fähndrich, Foster, Su and Aiken keep the constraint graph in an inductive form: the variables have a fixed order, and each edge is stored at only one of its ends. Their search follows only chains of edges in that order, so it costs little, and it finds only some of the cycles. They report that this partial search finds most of the variables that are on cycles, and that it makes their solver much faster on C programs, by large factors on the larger ones. Hardekopf and Lin (2007) report that full online searches cost too much on large programs, which led them to lazy and hybrid detection.

Measured, not proved. On the 400 seeded random programs of the test file, of up to 12 variables and 30 statements, the result equals Andersen's least solution in every case, and 817 of the 2519 variables are merged into another. On 200 random programs of 40 variables and 120 statements, 6262 of 7980 variables are merged.

Properties

  • Same result as Andersen's analysis. The merges change the work, not the answer.
  • Online. The search happens while the solver runs, so it also finds the cycles that the edges from loads and stores close, which no analysis before the solver can see.
  • Acyclic graph. With a full search, the graph of classes never has a cycle.
  • Not every equal pair. Two variables with equal sets but no cycle between them stay apart. Offline variable substitution finds some of those before solving.
  • Nodes, not locations. Merging joins the sets of pointers. The addresses in the sets stay the original locations.

Variants and improvements

  • Partial search. The original method of Fähndrich, Foster, Su and Aiken searches only a chain of edges in a fixed order of the variables. It misses some cycles and costs much less per edge.
  • Lazy and hybrid detection. Lazy cycle detection searches only when an edge carries a set that is already equal to the set at its target, which is a hint of a cycle. Hybrid cycle detection plans some merges with an offline pass over the statements and does them while the solver runs, with no search.
  • Dynamic topological order. Pearce, Kelly and Hankin keep a topological order of the graph and update it when an edge is added; an edge that goes against the order shows a possible cycle.
  • Offline merges. Offline variable substitution merges variables before the solver starts, with the strongly connected components of the copy graph and more.
  • Unification. Steensgaard's analysis merges every pair of nodes joined by an edge, not only nodes on a cycle, and loses precision.

When to use it

Use cycle elimination in any inclusion-based points-to solver for large programs. Real C programs give constraint graphs with large cycles, many of them closed only by the edges from loads and stores, and without merges the solver moves the same facts around them many times. For the fastest solvers, use the cheaper lazy or hybrid detection, or the partial search, instead of a full search for every edge.

Pitfalls

  • Merging the locations too. Only the sets are shared. If the merge renames the addresses in the sets, the pointers to a merged variable seem to point to all of its class, and the result is wrong.
  • Merging only the two ends. All the nodes on every path from vv back to uu must be merged; merging only uu and vv leaves a cycle in the graph.
  • Forgetting the tables. The loads and stores of a merged node move to the root, and the root goes back on the worklist; without this, the new elements of the merged set never add their edges.
  • Stale names. After merges, an edge can name a variable that is no longer a root. Every use of a node must go through FIND.
  • A full search for every edge. It is correct, but it can cost more than it saves. Bound the search, or search only when there is a hint of a cycle.

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.

online_cycle_elimination.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/online-cycle-elimination/. The authors are listed in prov/DDXZCS.jsonl.
"""Andersen's analysis with online cycle elimination.

oce(stmts) takes statements in the four forms of ptsgen and returns
(pts, stats). pts is the least solution of the subset constraints, the same
result as Andersen's analysis. Each time an edge u -> v is added to the
constraint graph, a search looks for a path from v back to u. If there is
one, every node on such a path is merged with u and v into one node of a
union-find forest, since they must all have the same set. The graph of the
merged nodes then has no cycle. The locations stay distinct: only the nodes
that hold the sets are merged. stats counts the searches and the merges, and
gives the merged classes and the edges between them at the end.

This version searches the whole graph for each new edge. Fahndrich, Foster,
Su and Aiken search only part of it, so they can miss cycles; see the page.
"""

from collections import deque

import ptsgen


def oce(stmts):
    names = ptsgen.variables(stmts)
    parent = {v: v for v in names}  # @line L1
    pts = {v: set() for v in names}
    succ = {v: set() for v in names}
    loads = {v: set() for v in names}  # loads[x]: the p with p = *x
    stores = {v: set() for v in names}  # stores[x]: the q with *x = q
    stats = {"searches": 0, "merged": 0}
    work = deque()
    queued = set()

    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 push(v):
        if v not in queued:
            queued.add(v)
            work.append(v)

    def on_paths(src, dst):
        """The nodes on some path from src to dst, or an empty set."""
        stats["searches"] += 1
        seen = {src}
        stack = [src]
        while stack:
            x = stack.pop()
            for w in succ[x]:
                w = find(w)
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        if dst not in seen:
            return set()
        pred = {x: [] for x in seen}
        for x in seen:
            for w in succ[x]:
                pred[find(w)].append(x)
        back = {dst}
        stack = [dst]
        while stack:
            x = stack.pop()
            for w in pred[x]:
                if w not in back:
                    back.add(w)
                    stack.append(w)
        return back

    def collapse(nodes, r):
        for x in sorted(nodes):  # @line L16
            if x != r:
                parent[x] = r  # @line L17
                pts[r] |= pts[x]
                succ[r] |= succ[x]
                loads[r] |= loads[x]
                stores[r] |= stores[x]
                stats["merged"] += 1
        succ[r] = {find(w) for w in succ[r]} - {r}  # @line L18
        push(r)

    def add_edge(u, v):
        u, v = find(u), find(v)  # @line L11
        if u == v or v in succ[u]:
            return
        succ[u].add(v)  # @line L12
        cycle = on_paths(v, u)  # @line L13
        if cycle:
            collapse(cycle, u)  # @line L14
            return
        if not pts[u] <= pts[v]:  # @line L15
            pts[v] |= pts[u]
            push(v)

    for kind, x, y in stmts:
        if kind == "addr":
            pts[x].add(y)  # @line L2
            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)  # @line L3
    while work:  # @line L4
        n = work.popleft()
        queued.discard(n)
        if find(n) != n:  # @line L5
            continue
        for a in list(pts[n]):  # @line L6
            for p in list(loads[n]):
                add_edge(a, p)  # @line L7
            for q in list(stores[n]):
                add_edge(q, a)  # @line L8
        n = find(n)
        for w in list(succ[n]):  # @line L9
            w = find(w)
            if w != n and not pts[n] <= pts[w]:
                pts[w] |= pts[n]
                push(w)
    stats["classes"] = {}
    for v in names:
        stats["classes"].setdefault(find(v), []).append(v)
    stats["edges"] = {(find(u), find(w)) for u in names if find(u) == u
                      for w in succ[u] if find(w) != u}
    return {v: set(pts[find(v)]) for v in names}, stats  # @line L10


def points_to(text):
    return oce(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_online_cycle_elimination.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/online-cycle-elimination/. The authors are listed in prov/DDXZCS.jsonl.

import random

import ptsgen
from online_cycle_elimination import oce, points_to

PAGE = """
entry:
  p = &a
  a = &x
  q = *p
  r = q
  a = r
  s = &b
  r = s
  ret 0
"""


def acyclic(edges):
    succ = {}
    for u, v in edges:
        succ.setdefault(u, []).append(v)
    state = {}
    for start in succ:
        if start in state:
            continue
        state[start] = 1
        stack = [(start, iter(succ.get(start, [])))]
        while stack:
            node, it = stack[-1]
            for w in it:
                if state.get(w) == 1:
                    return False
                if w not in state:
                    state[w] = 1
                    stack.append((w, iter(succ.get(w, []))))
                    break
            else:
                state[node] = 2
                stack.pop()
    return True


def test_page_example():
    stmts = ptsgen.parse(PAGE)
    pts, stats = oce(stmts)
    assert pts["p"] == {"a"} and pts["s"] == {"b"}
    assert pts["a"] == pts["q"] == pts["r"] == {"x", "b"}
    # The load adds the edge a -> q, which closes the cycle a -> q -> r -> a.
    assert sorted(stats["classes"]["a"]) == ["a", "q", "r"]
    assert stats["merged"] == 2
    assert pts == ptsgen.least_solution(stmts)


def test_copy_cycle():
    pts, stats = oce(ptsgen.parse("p = &a\nq = p\nr = q\np = r"))
    assert pts["p"] == pts["q"] == pts["r"] == {"a"}
    assert stats["merged"] == 2


def test_no_cycle_no_merge():
    pts, stats = oce(ptsgen.parse("p = &a\nq = p\nr = q\nt = *r\n*q = p"))
    assert stats["merged"] == 0
    assert pts == ptsgen.least_solution(ptsgen.parse("p = &a\nq = p\nr = q\nt = *r\n*q = p"))


def test_self_store_and_load():
    stmts = ptsgen.parse("p = &p\n*p = p\nq = *p")
    assert oce(stmts)[0] == ptsgen.least_solution(stmts)


def test_equals_andersen_on_random_programs():
    rng = random.Random(4100)
    merges = 0
    for trial in range(400):
        stmts = ptsgen.random_program(rng, rng.randint(2, 12), rng.randint(1, 30))
        pts, stats = oce(stmts)
        assert pts == ptsgen.least_solution(stmts), ptsgen.show(stmts)
        merges += stats["merged"]
    assert merges > 100  # the random programs do have cycles


def test_graph_of_classes_has_no_cycle():
    rng = random.Random(4200)
    for trial in range(300):
        stmts = ptsgen.random_program(rng, rng.randint(2, 12), 30, (2, 6, 2, 2))
        pts, stats = oce(stmts)
        assert acyclic(stats["edges"]), ptsgen.show(stmts)
        # Every class holds variables with one and the same least set.
        least = ptsgen.least_solution(stmts)
        for members in stats["classes"].values():
            assert all(least[v] == least[members[0]] for v in members)


def test_order_of_statements_does_not_change_the_result():
    rng = random.Random(4300)
    for trial in range(200):
        stmts = ptsgen.random_program(rng, rng.randint(2, 10), 30)
        first = oce(stmts)[0]
        shuffled = stmts[:]
        rng.shuffle(shuffled)
        assert oce(shuffled)[0] == first


def test_sound_against_concrete_runs():
    rng = random.Random(4400)
    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_copy_cycle():
    n = 2000
    text = "\n".join(["v0 = &a"] + ["v%d = v%d" % ((i + 1) % n, i) for i in range(n)])
    pts, stats = oce(ptsgen.parse(text))
    assert all(pts["v%d" % i] == {"a"} for i in range(n))
    assert stats["merged"] == n - 1

History

The cubic cost of Andersen's analysis (1994) was the main obstacle to its use on large programs, and the constraint graphs of real programs have many cycles. Fähndrich, Foster, Su and Aiken (1998) showed that a partial online search for cycles in an inductive form of the graph removes most of the repeated work. Rountev and Chandra (2000) found many equal variables before solving. Heintze and Tardieu (2001) and Pearce, Kelly and Hankin (2003) gave other ways to detect cycles while solving. Hardekopf and Lin (2007) compared these methods and gave lazy and hybrid cycle detection, which analyse millions of lines of C.

References

  1. Manuel Fähndrich, Jeffrey S. Foster, Zhendong Su and Alexander Aiken, Partial online cycle elimination in inclusion constraint graphs, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '98), 85 to 96, 1998, whole paper (the inductive form of the constraint graph, the partial search for cycles along chains of variables in index order, and the 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 earlier cycle detection methods and the comparison of online and lazy detection
  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 solver works on)

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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/DDXZCS/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