Algorithm Search⌘K

Algorithmcore

Andersen's analysis

Also called inclusion-based points-to analysis, subset-based pointer analysis.

Flow-insensitive points-to analysis that turns each assignment into a subset constraint and solves the constraint graph in cubic time.

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
Lars Ole Andersen, 1994

Andersen's analysis solves the points-to analysis problem for a whole program, without regard to the order of its statements. Each pointer assignment becomes one subset constraint between points-to sets: after p = q, the set of p must contain the set of q. The analysis finds the least sets that meet all the constraints. It keeps a constraint graph with an edge for each subset constraint and moves new facts along the edges with a worklist. Loads and stores add new edges while it runs, because the target of *p is known only when the set of p is known. On nn variables it runs in O(n3)O(n^3) time in the worst case, and much faster on real programs.

In plain words

Each pointer in a program holds the address of some memory cell. We want to know, for each pointer, all the cells it could ever hold, for any run of the program. Andersen's analysis reads each assignment as a rule. If one pointer is copied into another, then everything the first could hold, the second could hold too. Copies through a pointer give rules that depend on what that pointer holds, so new rules appear as the answer grows. The analysis draws an arrow from each source to each target and pushes facts along the arrows until nothing new arrives. The result is the smallest answer that obeys every rule. It never misses a cell that a real run can use. It can list a cell that no real run uses, because it ignores the order of the statements.

The problem

The input is a set of statements in the four basic forms over a set VV of nn variables, and the output is a points-to set pts(v)⊆Vpts(v) \subseteq V for each variable. Every variable is also a memory location, so it can be a target. In the toy IR, p = alloc at site kk is treated as p = &h_k, with one location hkh_k per site. Each statement gives one constraint:

statement constraint
p = &a a∈pts(p)a \in pts(p)
p = q pts(q)⊆pts(p)pts(q) \subseteq pts(p)
p = *q pts(a)⊆pts(p)pts(a) \subseteq pts(p) for every a∈pts(q)a \in pts(q)
*p = q pts(q)⊆pts(a)pts(q) \subseteq pts(a) for every a∈pts(p)a \in pts(p)

The result is the least solution of these constraints, in the order of ⊆\subseteq on each set, with union as the join. This is the order of abstract interpretation in the direction of Cousot: bottom is the most precise answer, where every set is empty, and larger answers are less precise. The least solution exists because the solutions are closed under intersection. The analysis in the terms of a data-flow framework:

item value
direction none: the analysis is flow-insensitive and has one answer for the whole program
may or must may
domain maps from VV to subsets of VV
order ⊆\subseteq on each set (bottom is precise)
join union on each set
bottom and top all sets empty, and all sets equal to VV
boundary value none, there is no entry or exit point
initial value all sets empty
transfer monotone, not distributive: the load and store rules combine two facts, a∈pts(q)a \in pts(q) and b∈pts(a)b \in pts(a)

Flow-insensitive means that the order of the statements is ignored: the answer covers every run that executes the statements in any order, any number of times. It does not mean that control flow is ignored entirely. Every real path is one of those orders, so the answer is sound for the program, and statements that the program never reaches can still be dropped first. Two expressions *p and *q may alias if pts(p)∩pts(q)≠∅pts(p) \cap pts(q) \neq \emptyset, which gives an alias analysis.

The algorithm

The constraint graph has a node for each variable and an edge u→vu \to v for each known constraint pts(u)⊆pts(v)pts(u) \subseteq pts(v). Copies give edges at the start. A load p = *q gives the edge a→pa \to p for each aa that enters pts(q)pts(q), and a store *q = r gives r→ar \to a. Each node keeps deltadelta, the part of its set that it has not yet sent on. This is difference propagation: each fact moves along each edge once.

  1. ANDERSEN(S)
  2. 1for each variable v do pts[v] <- {}; succ[v] <- {}; delta[v] <- {}
  3. 2W <- an empty worklist
  4. 3for each p = &a in S do add a to pts[p] and to delta[p]; add p to W
  5. 4for each p = q in S do ADD-EDGE(q, p)
  6. 5while W is not empty do
  7. 6take n from W; d <- delta[n]; delta[n] <- {}
  8. 7for each a in d do
  9. 8for each p = *n in S do ADD-EDGE(a, p)
  10. 9for each *n = r in S do ADD-EDGE(r, a)
  11. 10for each w in succ[n] do PROPAGATE(d, w)
  12. 11return pts
  13. ADD-EDGE(u, v)
  14. 12if v is not in succ[u] then
  15. 13add v to succ[u]; PROPAGATE(pts[u], v)
  16. PROPAGATE(s, v)
  17. 14new <- s minus pts[v]
  18. 15if new is not empty then
  19. 16add new to pts[v] and to delta[v]; add v to W if it is not there

A new edge must carry the whole set of its source at once (line L13), since the facts that the source already sent on did not go along this edge. After that, only the differences move (line L10). The implementation keeps the loads and stores of each node in tables, so lines L8 and L9 look only at the statements of nn, and it uses a first-in first-out worklist. The order of the worklist changes the running time, not the result.

Example

The program, in the toy IR:

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

Lines L3 and L4 give pts(p)={a}pts(p) = \{a\}, pts(q)={b}pts(q) = \{b\}, pts(r)={p}pts(r) = \{p\}, the edge q→sq \to s and pts(s)={b}pts(s) = \{b\}. The worklist is p,q,r,sp, q, r, s.

step node dd what happens
1 pp {a}\{a\} pp has no edges, loads or stores yet
2 qq {b}\{b\} bb is already in pts(s)pts(s)
3 rr {p}\{p\} load t = *r: edge p→tp \to t, pts(t)={a}pts(t) = \{a\}; store *r = s: edge s→ps \to p, pts(p)={a,b}pts(p) = \{a, b\}
4 ss {b}\{b\} bb is already in pts(p)pts(p)
5 tt {a}\{a\} no edges
6 pp {b}\{b\} along p→tp \to t: pts(t)={a,b}pts(t) = \{a, b\}
7 tt {b}\{b\} no edges; the worklist is empty

The result is pts(p)={a,b}pts(p) = \{a, b\}, pts(q)={b}pts(q) = \{b\}, pts(r)={p}pts(r) = \{p\}, pts(s)={b}pts(s) = \{b\}, pts(t)={a,b}pts(t) = \{a, b\}, and pts(a)=pts(b)=∅pts(a) = pts(b) = \emptyset. The fact b∈pts(p)b \in pts(p) comes from the store *r = s, which writes into pp because rr points to pp. The set of qq stays {b}\{b\}: the edge q→sq \to s goes one way only. The Steensgaard analysis of the same program unifies the targets of qq and ss with those of pp and gives pts(q)={a,b}pts(q) = \{a, b\}.

Correctness

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

  1. The least solution exists. The intersection of solutions is a solution, and the assignment where every set is VV is one. So the intersection LL of all solutions is the least one. It is also the least fixed point of a monotone map, by the Knaster-Tarski theorem.
  2. Every fact is forced. By induction over the steps, pts(v)⊆L(v)pts(v) \subseteq L(v), and every edge u→vu \to v has L(u)⊆L(v)L(u) \subseteq L(v): each new edge comes from a statement and from a fact that is already in LL.
  3. What is sent stays sent. With done(v)=pts(v)done(v) = pts(v) minus delta(v)delta(v), every edge u→vu \to v has done(u)⊆pts(v)done(u) \subseteq pts(v), and the edges for loads and stores exist for every element of donedone. A node with a non-empty deltadelta is on the worklist.
  4. At the end, the sets are a solution. When the worklist is empty, done=ptsdone = pts, so all four constraints hold. With step 2, pts=Lpts = L.
  5. Soundness for the program. In any run that executes the statements in any order, the cell that vv points to is always in L(v)L(v). Each statement keeps this true because LL meets its constraint.
Proof: Andersen's worklist algorithm computes the least solution of the subset constraints in O(n^3 + m) timefull

Setting. The program is a set SS of mm statements over a set VV of nn variables. Every variable is also a location, so a points-to assignment is a map P:V→2VP : V \to 2^V. The statements give the constraints

  • p=&ap = \&a: a∈P(p)a \in P(p);
  • p=qp = q: P(q)⊆P(p)P(q) \subseteq P(p);
  • p=∗qp = {*q}: P(a)⊆P(p)P(a) \subseteq P(p) for every a∈P(q)a \in P(q);
  • ∗p=q{*p} = q: P(q)⊆P(a)P(q) \subseteq P(a) for every a∈P(p)a \in P(p).

A solution is an assignment that meets all of them. Assignments are ordered pointwise by ⊆\subseteq, with the pointwise union as join and the empty sets as bottom. This is the order of abstract interpretation in the direction of Cousot: a larger assignment says more pointers may point to more places, so it is less precise and safer. "Least" below means least in this order.

Lemma 1 (the least solution exists). The pointwise intersection of any family of solutions is a solution. So there is a least solution LL, the intersection of all solutions.

Proof. Let PiP_i be solutions and Q(v)=⋂iPi(v)Q(v) = \bigcap_i P_i(v). For p=&ap = \&a, aa is in every Pi(p)P_i(p). For p=qp = q, Q(q)⊆Pi(q)⊆Pi(p)Q(q) \subseteq P_i(q) \subseteq P_i(p) for each ii. For p=∗qp = {*q} and a∈Q(q)a \in Q(q), a∈Pi(q)a \in P_i(q), so Q(a)⊆Pi(a)⊆Pi(p)Q(a) \subseteq P_i(a) \subseteq P_i(p) for each ii. The store case is the same. The full assignment P(v)=VP(v) = V is a solution, so the family is not empty. □\square

The same LL is the least fixed point of the monotone map FF that adds to PP every fact one rule forces from PP, by the Knaster-Tarski theorem; Lemma 1 is the direct form of this.

The algorithm. Write EE for the set of edges, ptspts and deltadelta for the arrays of the pseudocode and WW for the worklist. An edge u→vu \to v stands for pts(u)⊆pts(v)pts(u) \subseteq pts(v). Line L3 puts the addresses in, line L4 adds the copy edges, and lines L8 and L9 add the edges that a load or a store needs for each new element of the set of its pointer. PROPAGATE adds to pts(v)pts(v) the part of a set that is new and records it in delta(v)delta(v).

Lemma 2 (every fact is forced). At all times, pts(v)⊆L(v)pts(v) \subseteq L(v) for every vv, and L(u)⊆L(v)L(u) \subseteq L(v) for every edge u→vu \to v.

Proof. Both hold at the start, when all sets and EE are empty. Line L3 adds aa to pts(p)pts(p) only for a statement p=&ap = \&a, and a∈L(p)a \in L(p). Line L4 adds q→pq \to p for a statement p=qp = q, and L(q)⊆L(p)L(q) \subseteq L(p). Line L8 adds a→pa \to p for a statement p=∗np = {*n} and an a∈pts(n)⊆L(n)a \in pts(n) \subseteq L(n), so L(a)⊆L(p)L(a) \subseteq L(p) because LL is a solution. Line L9 is the same for a store. PROPAGATE along an edge u→wu \to w adds only elements of pts(u)⊆L(u)⊆L(w)pts(u) \subseteq L(u) \subseteq L(w). In line L10, d⊆pts(n)d \subseteq pts(n) and the edges are those of EE. □\square

Lemma 3 (what is done is done). Call done(v)=pts(v)∖delta(v)done(v) = pts(v) \setminus delta(v). The following hold each time line L5 tests the loop condition:

  1. If delta(v)≠∅delta(v) \neq \emptyset, then v∈Wv \in W.
  2. Every statement p=&ap = \&a has a∈pts(p)a \in pts(p), and every statement p=qp = q has the edge q→pq \to p.
  3. For every edge u→vu \to v, done(u)⊆pts(v)done(u) \subseteq pts(v).
  4. For every statement p=∗qp = {*q} and every a∈done(q)a \in done(q), the edge a→pa \to p is in EE; for every statement ∗p=q{*p} = q and every a∈done(p)a \in done(p), the edge q→aq \to a is in EE.

Proof. Parts 1 and 2 are clear: every write to delta(v)delta(v) comes with push(v)push(v), vv leaves WW only in line L6 where delta(v)delta(v) is emptied, and lines L3 and L4 run before the loop. Before the loop, done(v)=∅done(v) = \emptyset for every vv: line L3 puts aa into both pts(p)pts(p) and delta(p)delta(p), and PROPAGATE does the same with the new elements. So parts 3 and 4 hold then. Consider one pass of lines L6 to L10 at node nn, with d=delta(n)d = delta(n). Sets only grow, and an element enters done(v)done(v) only when v=nv = n and it is in dd, because elsewhere new elements go into pts(v)pts(v) and delta(v)delta(v) together. So in this pass the new part of done(u)done(u) is empty if u≠nu \neq n and is dd if u=nu = n. Part 3 for an edge u→vu \to v: if the edge was added in this pass, ADD-EDGE sent all of pts(u)pts(u) to vv at that moment, and that set already held the old done(u)done(u) and dd. If the edge was there before, the old done(u)done(u) was already in pts(v)pts(v), and for u=nu = n line L10 sends dd along every edge of nn. Part 4: the new part of done(n)done(n) is dd, and lines L8 and L9 add the needed edges for each element of dd. For v≠nv \neq n, done(v)done(v) does not grow. □\square

Theorem 1 (correctness). The loop stops, and then pts=Lpts = L.

Proof. Each pass of the loop body takes a node out of WW, and a node is put back only when some pts(v)pts(v) grows. By Lemma 2, ∑v∣pts(v)∣≤n2\sum_v |pts(v)| \le n^2, so there are at most n2n^2 pushes after line L4, plus at most nn before, and the loop stops. Then WW is empty, so every delta(v)delta(v) is empty by part 1 of Lemma 3, and done=ptsdone = pts. Parts 2 to 4 now say that ptspts meets every constraint: for p=∗qp = {*q} and a∈pts(q)a \in pts(q) the edge a→pa \to p is in EE, so pts(a)⊆pts(p)pts(a) \subseteq pts(p) by part 3, and the other forms are the same. So ptspts is a solution, L⊆ptsL \subseteq pts by Lemma 1, and pts⊆Lpts \subseteq L by Lemma 2. □\square

Soundness for the program. A flow-insensitive analysis must cover every run that executes the statements of SS in any order, any number of times. Let val(v)val(v) be the location whose address vv holds in such a run, or none. Then val(v)∈L(v)val(v) \in L(v) whenever val(v)val(v) is defined, at every moment. This holds at the start, when nothing is defined. A step p=&ap = \&a sets val(p)=a∈L(p)val(p) = a \in L(p). A step p=qp = q sets val(p)=val(q)∈L(q)⊆L(p)val(p) = val(q) \in L(q) \subseteq L(p). A step p=∗qp = {*q} with val(q)=bval(q) = b sets val(p)=val(b)∈L(b)⊆L(p)val(p) = val(b) \in L(b) \subseteq L(p), since b∈L(q)b \in L(q). A step ∗p=q{*p} = q with val(p)=bval(p) = b sets val(b)=val(q)∈L(q)⊆L(b)val(b) = val(q) \in L(q) \subseteq L(b). Every path through a control flow graph made of these statements is such a run, so the result holds for the program under any control flow.

Theorem 2 (time). With hash sets, the algorithm takes O(n3+m)O(n^3 + m) expected time and O(n2+m)O(n^2 + m) space. With an n×nn \times n bit matrix for EE and bit vectors for the sets, the same bound holds in the worst case, counting word operations on vectors of nn bits as O(n)O(n).

Proof. Reading the statements and filling the tables of loads and stores, without repeats, costs O(m)O(m); after that there are at most n2n^2 distinct loads and n2n^2 distinct stores. Count the rest.

  • Edges. There are at most n2n^2 distinct edges. Each one is added once, and its call of PROPAGATE costs O(∣pts(u)∣)=O(n)O(|pts(u)|) = O(n). Total O(n3)O(n^3).
  • Elements taken from delta. An element aa enters pts(v)pts(v) once, so it is in the dd of line L6 for vv at most once. The n2n^2 pairs (v,a)(v, a) each cost, in lines L8 and L9, one test of ADD-EDGE per load and per store of vv. The distinct loads and stores of all nodes number at most 2n22n^2 in total, and each is met at most nn times, once per aa, so these tests cost O(n3)O(n^3).
  • Line L10. The pass at vv sends dd along at most nn edges at cost O(∣d∣)O(|d|) each. Since each element is in the dd of vv at most once, the total over all passes at vv is O(n⋅n)O(n \cdot n), and over all vv it is O(n3)O(n^3).
  • Worklist. At most n2+nn^2 + n pushes and pops, O(1)O(1) each.

The space is the O(n2)O(n^2) edges and set elements plus the O(m)O(m) statements. □\square

The bound is for the worklist with difference propagation. A plain round-robin iteration, which applies every constraint in each round until no set changes, also reaches LL, but each of up to n2n^2 rounds can cost Θ(mn)\Theta(m n).

Complexity

Proved. Each of the at most n2n^2 edges is added once, and its first PROPAGATE costs O(n)O(n). Each element enters each set once, so it is in some dd once per node; for that pair, lines L8 and L9 touch the loads and stores of the node, and line L10 touches at most nn edges. After the statements are read and their repeats dropped in O(m)O(m) time, there are at most n2n^2 loads and n2n^2 stores, and the total is O(n3+m)O(n^3 + m) time with O(n2+m)O(n^2 + m) space. With hash sets the bound is in expectation; with an n×nn \times n bit matrix for the edges and bit vectors for the sets it is a worst-case bound.

Stated in the literature, not proved here. Heintze and McAllester (1997) relate the cubic time of inclusion-based flow analysis to the reachability problem of two-way nondeterministic pushdown automata (2NPDA), for which no subcubic algorithm is known; this is the "cubic bottleneck". Sridharan and Fink (2009) show that the worklist algorithm runs in O(n2)O(n^2) time on k-sparse programs, where, roughly, each variable and each location gets its values from at most a constant number of statements, and they argue that real programs are close to this case.

Measured, not proved. On random programs of 30 statements, the result of the implementation equals that of a plain round-robin iteration of the four rules in all 400 seeded trials of its test file.

Properties

  • Least solution. The result does not depend on the worklist order or on the order of the statements.
  • Directional. An edge u→vu \to v moves facts only from uu to vv. This is the source of its precision over unification.
  • Not distributive. The load and store rules join two facts, so the analysis is not a bit-vector problem, and the solver must add edges while it runs.
  • Whole program. The answer for one variable can depend on any statement. Demand-driven methods answer one query with less work.
  • One location per name. Every variable and allocation site is one location. A loop that allocates many objects at one site gives one location for all of them.

Variants and improvements

When to use it

Use it when a flow-insensitive answer is enough and the program is up to a few million lines, as in most whole-program analyses of C and Java. It is the usual base for call graph construction, for mod-ref analysis and for alias queries in an optimizer. With cycle elimination and difference propagation, it handles programs of millions of lines. When time must be near linear and precision can drop, use Steensgaard's analysis. When the order of the statements matters, such as for strong updates of a pointer that is assigned twice, use a flow-sensitive analysis.

Pitfalls

  • New edges need the full set. If ADD-EDGE sends only the current deltadelta of the source, the facts the source sent earlier never reach the new target, and the result misses facts.
  • Stores write into the target, not the pointer. The store *p = q adds edges q→aq \to a for a∈pts(p)a \in pts(p). Adding q→pq \to p instead is a common mistake that gives wrong sets for both pp and its targets.
  • The order of statements. Flow-insensitive answers include facts that no single order makes true together. The answer is not "what pp points to at this line".
  • Precision of the abstraction. All objects from one allocation site are one location, so a store into one of them is a store into all. Do not use the result to prove that two objects from one site are different.
  • Self-loops and repeats. Edges u→uu \to u and repeated statements are harmless, but without a test for repeated edges, ADD-EDGE can run PROPAGATE over the full set many times.

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.

andersen_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/andersen-analysis/. The authors are listed in prov/MBB0JP.jsonl.
"""Andersen's inclusion-based points-to analysis.

andersen(stmts) takes statements in the four forms of ptsgen
(("addr", p, a), ("copy", p, q), ("load", p, q) for p = *q and
("store", p, q) for *p = q) and returns the least solution of the subset
constraints, as a dict from each variable to the set of variables it may
point to. It keeps a constraint graph with an edge u -> v for each
inclusion pts(u) <= pts(v), and a worklist of nodes whose sets have grown.
Each node also keeps delta, the part of its set that it has not yet sent
along its edges or used for its loads and stores (difference propagation).

may_alias(pts, p, q) tells if *p and *q may be the same location.
"""

from collections import deque

import ptsgen


def andersen(stmts):
    names = ptsgen.variables(stmts)
    pts = {v: set() for v in names}  # @line L1
    succ = {v: set() for v in names}
    delta = {v: set() for v in names}
    loads = {v: set() for v in names}  # loads[q]: the p with p = *q
    stores = {v: set() for v in names}  # stores[p]: the q with *p = q
    work = deque()  # @line L2
    queued = set()

    def push(v):
        if v not in queued:
            queued.add(v)
            work.append(v)

    def propagate(s, v):
        new = s - pts[v]  # @line L14
        if new:  # @line L15
            pts[v] |= new  # @line L16
            delta[v] |= new
            push(v)

    def add_edge(u, v):
        if v not in succ[u]:  # @line L12
            succ[u].add(v)  # @line L13
            propagate(pts[u], v)

    for kind, x, y in stmts:
        if kind == "addr":
            pts[x].add(y)  # @line L3
            delta[x].add(y)
            push(x)
        elif kind == "load":
            loads[y].add(x)
        elif kind == "store":
            stores[x].add(y)
    for kind, x, y in stmts:
        if kind == "copy":
            add_edge(y, x)  # @line L4
    while work:  # @line L5
        n = work.popleft()  # @line L6
        queued.discard(n)
        d = delta[n]
        delta[n] = set()
        for a in d:  # @line L7
            for p in loads[n]:
                add_edge(a, p)  # @line L8
            for q in stores[n]:
                add_edge(q, a)  # @line L9
        for w in list(succ[n]):
            propagate(d, w)  # @line L10
    return pts  # @line L11


def may_alias(pts, p, q):
    """True if the locations *p and *q may be the same."""
    return bool(pts.get(p, set()) & pts.get(q, set()))


def points_to(text):
    """Run the analysis on a program written in toy IR notation."""
    return andersen(ptsgen.parse(text))
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_andersen_analysis.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/andersen-analysis/. The authors are listed in prov/MBB0JP.jsonl.

import random

import ptsgen
from andersen_analysis import andersen, may_alias, points_to

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


def test_page_example():
    pts = points_to(PAGE)
    assert pts == {
        "p": {"a", "b"},
        "a": set(),
        "q": {"b"},
        "b": set(),
        "r": {"p"},
        "s": {"b"},
        "t": {"a", "b"},
    }
    assert may_alias(pts, "p", "t")
    assert may_alias(pts, "q", "s")
    assert may_alias(pts, "p", "q")
    assert not may_alias(pts, "r", "p")


def test_parse_and_show():
    stmts = ptsgen.parse(PAGE)
    assert [k for k, _, _ in stmts] == ["addr", "addr", "addr", "copy", "store", "load"]
    assert ptsgen.parse(ptsgen.show(stmts)) == stmts


def test_allocation_sites():
    # Each alloc instruction is one abstract location.
    pts = points_to("p = alloc\nq = alloc\nr = p\n*r = q\ns = *p")
    assert pts["p"] == {"h1"} and pts["q"] == {"h2"}
    assert pts["h1"] == {"h2"} and pts["s"] == {"h2"}


def test_empty_and_trivial():
    assert andersen([]) == {}
    assert points_to("p = p") == {"p": set()}
    assert points_to("p = &p\nq = *p") == {"p": {"p"}, "q": {"p"}}


def test_store_through_self():
    # *p = p with p = &a writes the address of a into a.
    assert points_to("p = &a\n*p = p") == {"p": {"a"}, "a": {"a"}}


def test_same_as_least_solution_on_random_programs():
    rng = random.Random(1994)
    for trial in range(400):
        nvars = rng.randint(2, 12)
        stmts = ptsgen.random_program(rng, nvars, rng.randint(1, 30))
        pts = andersen(stmts)
        assert pts == ptsgen.least_solution(stmts), ptsgen.show(stmts)
        assert ptsgen.is_solution(stmts, pts)


def test_every_fact_is_needed():
    # The result is the least solution, so no smaller assignment is a
    # solution: removing any one fact breaks some constraint.
    rng = random.Random(7)
    for trial in range(100):
        stmts = ptsgen.random_program(rng, 6, 20)
        pts = andersen(stmts)
        for v in pts:
            for a in pts[v]:
                smaller = {w: set(s) for w, s in pts.items()}
                smaller[v].discard(a)
                assert not ptsgen.is_solution(stmts, smaller)


def test_sound_against_concrete_runs():
    rng = random.Random(2024)
    for trial in range(150):
        stmts = ptsgen.random_program(rng, rng.randint(3, 10), 30)
        pts = andersen(stmts)
        facts = ptsgen.concrete_facts(stmts, rng, runs=10, steps=150)
        for p, a in facts:
            assert a in pts[p], (p, a, ptsgen.show(stmts))


def test_concrete_runs_reach_most_facts():
    # The analysis is the least solution, and with enough runs the concrete
    # program shows nearly every fact of it. The check uses programs without
    # loads and stores, where every fact must show up.
    rng = random.Random(5)
    for trial in range(50):
        stmts = ptsgen.random_program(rng, 6, 15, weights=(1, 2, 0, 0))
        pts = andersen(stmts)
        facts = ptsgen.concrete_facts(stmts, rng, runs=40, steps=200)
        assert facts == {(p, a) for p in pts for a in pts[p]}

History

Lars Ole Andersen defined the inclusion-based analysis in his 1994 PhD thesis at DIKU, as part of a partial evaluator for C. Steensgaard's 1996 unification analysis was a faster and less precise answer to its cubic cost. Heintze and McAllester (1997) placed the cubic time among the problems equivalent to 2NPDA reachability. Fähndrich, Foster, Su and Aiken (1998) made the solver much faster by merging cycles online, Rountev and Chandra (2000) by finding equal variables offline, and Hardekopf and Lin (2007) by lazy and hybrid cycle detection, which made Andersen's analysis of millions of lines of C practical. Hind (2001) surveyed the field and its open questions. Sridharan and Fink (2009) explained its speed on real code with the k-sparse bound. Many current tools write the analysis as Datalog rules; Smaragdakis and Balatsouras (2015) survey this style.

References

  1. 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, with the inclusion constraints for the assignments of C and their solution
  2. Nevin Heintze and David McAllester, On the cubic bottleneck in subtyping and flow analysis, Proceedings of the 12th IEEE Symposium on Logic in Computer Science (LICS), 342 to 351, 1997, whole paper (the cubic bound of inclusion-based flow analysis and its relation to 2NPDA reachability)
  3. Manu Sridharan and Stephen J. Fink, The complexity of Andersen's analysis in practice, Static Analysis Symposium (SAS 2009), LNCS 5673, 205 to 221, whole paper (a quadratic bound for k-sparse programs, which explains why the analysis is fast on real code)
  4. 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 survey of flow-insensitive analyses and their scalability
  5. Yannis Smaragdakis and George Balatsouras, Pointer Analysis, Foundations and Trends in Programming Languages 2(1), 1 to 69, 2015, the inclusion-based model of the analysis, written as rules over input relations
  6. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 12.4 (a simple pointer-analysis algorithm, flow-insensitive, written in Datalog)

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/MBB0JP/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