Algorithm Search⌘K

Algorithmresearch

Demand-driven points-to analysis

Also called refinement-based points-to analysis.

Answers points-to queries for chosen variables only, by searching backward in the constraint graph, often as CFL reachability.

Time
O(m^3 + m s) worst
Space
O(m^2 + s) extra
Where
m = the number of variables and queries; s = the number of statements
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
Nevin Heintze, Olivier Tardieu, 2001

A demand-driven points-to analysis answers a question such as "what may pp point to?" for a few chosen variables, without solving the whole program. It gives the same answer as the exhaustive Andersen analysis for each queried variable, but it only builds the part of the constraint graph that the query depends on. The algorithm on this page starts from the queried variables and works backward: a variable is demanded when the set of a demanded variable depends on its set, and only demanded variables get sets, edges and work. In the language of Datalog it is the magic-sets form of Andersen's rules. Heintze and Tardieu (2001) made the approach fast in practice for C, and Sridharan and Bodík (2006) recast it as CFL reachability for Java, with contexts and fields refined on demand.

In plain words

A full pointer analysis works out where every pointer may point, even when a tool only needs to know about one of them. A demand-driven analysis starts from the one pointer it is asked about. To know what it points to, it must know the pointers it was copied from, and the pointers it was loaded through. So it asks about those next, and so on. Pointers that the answer does not depend on are never looked at. For a debugger, an editor or a check on one line of code, this is often a small part of the program. The answer is exactly the one the full analysis would give for that pointer.

The problem

The input is a list of statements of the four forms of the Andersen page: v=&av = \&a, v=yv = y, v=∗yv = {*}y and ∗p=q{*}p = q, and a set QQ of query variables. The output is A(q)A(q) for each q∈Qq \in Q, where AA is the least solution of Andersen's inclusion constraints. A variable is taken if some statement takes its address.

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain maps from the demanded variables to sets of variables, a set of demanded variables and a set of edges
order inclusion in all parts (bottom is precise)
join union
bottom and top everything empty, and every variable demanded with the set of all variables
boundary value the queries are demanded
initial value only the queries are demanded, with empty sets
transfer Andersen's four rules, each applied only for a demanded left side

The algorithm

  1. DEMAND-POINTS-TO(S, Q)
  2. 1for each q in Q do DEMAND(q)
  3. 2while some variable waits to start or the worklist is not empty do
  4. 3if a variable v waits to start then START(v)
  5. 4else take n from the worklist, with its new part d
  6. 5for each a in d and each load x = *n with x demanded do EDGE(a, x)
  7. 6for each a in d that is demanded and each store *n = q do EDGE(q, a)
  8. 7for each edge n -> w do ADD(d, w)
  9. 8return pts(q) for each q in Q
  10. START(v)
  11. 9ADD({a : v = &a is in S}, v)
  12. 10for each v = y in S do EDGE(y, v)
  13. 11for each v = *y in S do DEMAND(y); for each b in pts(y) do EDGE(b, v)
  14. 12if v is taken then for each *p = q in S do DEMAND(p); if v is in pts(p) then EDGE(q, v)
  15. EDGE(u, v)
  16. 13DEMAND(u); if u -> v is new then add it and ADD(pts(u), v)
  17. DEMAND(v)
  18. 14if v is not demanded then demand it with an empty set and let it wait to start
  19. ADD(s, v)
  20. 15if s has elements not in pts(v) then add them to pts(v) and to its new part, and put v on the worklist

The four rules of Andersen's analysis are read backward. Line L10 says that the set of vv needs the set of yy for a copy. Line L11 says that a load v=∗yv = {*}y needs the set of yy, and then the set of every bb that yy may point to. Line L12 is the hard case: a store ∗p=q{*}p = q writes to vv when pp may point to vv, so for a taken vv the run must know the sets of all store pointers pp. Lines L5 and L6 handle the same two cases when a set grows after the variable has started. The edges and the worklist with new parts are those of Andersen's solver, with difference propagation.

Example

p = &a
q = &b
r = &p
s = q
*r = s
t = *r
u = &c
v = u
w = *v

The query is tt. Line L11 demands rr for the load t=∗rt = {*}r. Then pts(r)={p}pts(r) = \{p\}, so pp is demanded with the edge p→tp \to t. The variable pp is taken, so line L12 demands the store pointer rr (already demanded) and, since p∈pts(r)p \in pts(r), adds the edge s→ps \to p for the store ∗r=s{*}r = s. Then ss demands qq through the copy s=qs = q.

variable demanded because set
tt it is the query {a,b}\{a, b\}
rr t=∗rt = {*}r {p}\{p\}
pp rr points to pp {a,b}\{a, b\}
ss ∗r=s{*}r = s with p∈pts(r)p \in pts(r) {b}\{b\}
qq s=qs = q {b}\{b\}

The run never looks at aa, bb, uu, vv, ww or cc, and pts(t)={a,b}pts(t) = \{a, b\} is the Andersen answer. A query for qq demands only qq. A query for ww demands ww, vv, uu and cc, and, since cc is taken, the store pointer rr. It finds c∉pts(r)c \notin pts(r) and stops with pts(w)=∅pts(w) = \emptyset.

Correctness

Soundness. Every edge u→vu \to v is created only when Andersen's least solution AA has A(u)⊆A(v)A(u) \subseteq A(v): for a copy, for a load through a pointer that may point to uu, or for a store through a pointer that may point to vv. So by induction every set stays inside AA.

Completeness for demanded variables. When the run stops, the demanded part is closed. Every demanded variable has its own facts from line L9, an edge from each copy source, the edges of each load, and, if it is taken, the edges of every store whose pointer may point to it, with the store pointers demanded. Edges carry every element, by the worklist argument of Andersen's solver. Now take a fact (v,a)(v, a) of AA with vv demanded and do induction on the height of its derivation by Andersen's rules. Each rule has premises about variables that the closure forces to be demanded, so by induction they hold, and the edge carries aa into pts(v)pts(v). So pts(v)=A(v)pts(v) = A(v) for every demanded vv, and in particular for every query. The full proofs are in the proof file.

Proof: The demand-driven solver stops, and for every demanded variable it computes exactly the set of the exhaustive Andersen analysisfull

Setting. A program is a finite list SS of statements of the forms v=&av = \&a, v=yv = y, v=∗yv = {*}y and ∗p=q{*}p = q over a finite set VV of variables. A variable is taken if it is the aa of some statement v=&av = \&a. Andersen's analysis is the least map A:V→2VA : V \to 2^V such that

  1. v=&av = \&a gives a∈A(v)a \in A(v);
  2. v=yv = y gives A(y)⊆A(v)A(y) \subseteq A(v);
  3. v=∗yv = {*}y and b∈A(y)b \in A(y) give A(b)⊆A(v)A(b) \subseteq A(v);
  4. ∗p=q{*}p = q and b∈A(p)b \in A(p) give A(q)⊆A(b)A(q) \subseteq A(b).

The least map exists because the rules are monotone, and it is the set of facts (v,a)(v, a) that have a finite derivation by the rules. The rank of a fact is the height of its shortest derivation. Every fact (v,a)∈A(v, a) \in A has aa taken, by induction on the rank.

The algorithm keeps a set DD of demanded variables (the keys of pts), a set pts(v)pts(v) for each v∈Dv \in D, a set of edges u→vu \to v between demanded variables, a queue of variables that wait to start, and a worklist of variables whose sets have grown, with the new part in delta(v)delta(v). The line numbers refer to the pseudocode of the page.

Lemma 1 (soundness). At all times, pts(v)⊆A(v)pts(v) \subseteq A(v) for every v∈Dv \in D, and every edge u→vu \to v has A(u)⊆A(v)A(u) \subseteq A(v).

Proof. By induction over the steps. A set grows only at line L15, called from line L9 or along an edge. Line L9 adds aa for v=&av = \&a, and a∈A(v)a \in A(v) by rule 1. Along an edge u→vu \to v the added elements come from pts(u)⊆A(u)⊆A(v)pts(u) \subseteq A(u) \subseteq A(v). Edges are created at four places. Line L10 adds y→vy \to v for v=yv = y, and A(y)⊆A(v)A(y) \subseteq A(v) by rule 2. Lines L11 and L5 add b→vb \to v for v=∗yv = {*}y with b∈pts(y)⊆A(y)b \in pts(y) \subseteq A(y), and rule 3 gives A(b)⊆A(v)A(b) \subseteq A(v). Lines L12 and L6 add q→bq \to b for ∗p=q{*}p = q with b∈pts(p)⊆A(p)b \in pts(p) \subseteq A(p), and rule 4 gives A(q)⊆A(b)A(q) \subseteq A(b). □\square

Lemma 2 (termination). The run stops.

Proof. A variable enters DD at most once (line L14), so at most ∣V∣+∣Q∣|V| + |Q| variables start, where QQ is the set of queries. A variable joins the worklist only when its set grows, and a set is a subset of VV that never shrinks, so there are at most ∣V∣|V| growths per variable. Each step of the main loop either starts a variable or removes one entry of the worklist. □\square

Lemma 3 (edges carry everything). When the run stops, pts(u)⊆pts(v)pts(u) \subseteq pts(v) for every edge u→vu \to v.

Proof. Let a∈pts(u)a \in pts(u). If aa entered pts(u)pts(u) before the edge was created, line L13 added the whole of pts(u)pts(u) to pts(v)pts(v) at that moment. Otherwise aa entered pts(u)pts(u) later, together with delta(u)delta(u), and uu was put on the worklist. The worklist is empty at the end, so uu was removed afterwards, with aa in the removed delta(u)delta(u), and line L7 sent it along every edge of uu, including u→vu \to v. □\square

Lemma 4 (closure of the demanded part). When the run stops, for every v∈Dv \in D:

  • (a) if v=&av = \&a is in SS, then a∈pts(v)a \in pts(v);
  • (b) if v=yv = y is in SS, then y∈Dy \in D and y→vy \to v is an edge;
  • (c) if v=∗yv = {*}y is in SS, then y∈Dy \in D, and every b∈pts(y)b \in pts(y) is in DD with an edge b→vb \to v;
  • (d) if vv is taken and ∗p=q{*}p = q is in SS, then p∈Dp \in D, and if v∈pts(p)v \in pts(p), then q∈Dq \in D with an edge q→vq \to v.

Proof. The queue of waiting variables is empty at the end, so vv has started. (a) and (b) come from lines L9 and L10, and line L13 demands the source of each edge. For (c), line L11 demands yy and adds b→vb \to v for every bb that is in pts(y)pts(y) when vv starts. A bb that enters pts(y)pts(y) later is in delta(y)delta(y) when yy is removed from the worklist, and since v∈Dv \in D already, line L5 adds b→vb \to v. For (d), line L12 demands pp and adds q→vq \to v if v∈pts(p)v \in pts(p) when vv starts. If vv enters pts(p)pts(p) later, it is in delta(p)delta(p) when pp is removed, v∈Dv \in D, and line L6 adds q→vq \to v. □\square

Theorem 1 (exact answers). When the run stops, pts(v)=A(v)pts(v) = A(v) for every v∈Dv \in D. In particular every query gets the answer of the exhaustive analysis.

Proof. pts(v)⊆A(v)pts(v) \subseteq A(v) is Lemma 1. For the other direction, we show by induction on the rank rr that every fact (v,a)∈A(v, a) \in A with v∈Dv \in D has a∈pts(v)a \in pts(v). Take the last rule of a shortest derivation of (v,a)(v, a).

  • Rule 1: v=&av = \&a, and Lemma 4(a) gives a∈pts(v)a \in pts(v).
  • Rule 2: v=yv = y and (y,a)(y, a) has a smaller rank. By Lemma 4(b), y∈Dy \in D with an edge y→vy \to v. By induction a∈pts(y)a \in pts(y), and by Lemma 3 a∈pts(v)a \in pts(v).
  • Rule 3: v=∗yv = {*}y, and (y,b)(y, b) and (b,a)(b, a) have smaller ranks. By Lemma 4(c), y∈Dy \in D, so by induction b∈pts(y)b \in pts(y). Then Lemma 4(c) gives b∈Db \in D and an edge b→vb \to v. By induction a∈pts(b)a \in pts(b), and by Lemma 3 a∈pts(v)a \in pts(v).
  • Rule 4: ∗p=q{*}p = q, and (p,v)(p, v) and (q,a)(q, a) have smaller ranks. The fact (p,v)∈A(p, v) \in A shows that vv is taken, so Lemma 4(d) gives p∈Dp \in D. By induction v∈pts(p)v \in pts(p). Then Lemma 4(d) gives q∈Dq \in D and an edge q→vq \to v. By induction a∈pts(q)a \in pts(q), and by Lemma 3 a∈pts(v)a \in pts(v).

So A(v)⊆pts(v)A(v) \subseteq pts(v). Queries are in DD from line L1. □\square

Theorem 2 (cost). Let m=∣V∣+∣Q∣m = |V| + |Q| and s=∣S∣s = |S|. With hash sets and unit-cost set operations per element, the run takes O(m3+ms)O(m^3 + m s) time and O(m2+s)O(m^2 + s) space. Only demanded variables cost anything beyond the O(s)O(s) indexing.

Proof. Each demanded variable starts once. A start scans the statements into vv and, for a taken vv, all stores, so all starts cost O(ms)O(m s). There are at most m2m^2 edges, and creating one copies a set of at most mm elements, so edge creation costs O(m3)O(m^3). Each of the at most mm elements of a set is in exactly one removed delta of that variable. When it is removed, it is sent along at most mm edges and checked against the loads and stores of the variable, so the delta work is O(m⋅(m2+s))O(m \cdot (m^2 + s)) in total. The sets, edges and indexes take O(m2+s)O(m^2 + s) space. ■\blacksquare

Complexity

Proved. With mm variables and queries and ss statements, the run takes O(m3+ms)O(m^3 + m s) time and O(m2+s)O(m^2 + s) space, the same worst case as Andersen's solver. Only demanded variables get starts, edges and propagation, so the actual work is that of Andersen's solver on the demanded part, plus a scan of all stores for each demanded taken variable.

Stated in the literature. Heintze and Tardieu report that demand-driven queries on large C programs are answered much faster than the exhaustive analysis, with caching of the results of earlier queries. Sridharan and Bodík report that refinement-based queries for Java answer most client questions within a small budget.

Measured, not proved. On 400 random programs (seed 2001), each answer equals the exhaustive Andersen set, also computed by plain iteration. On 200 programs (seed 2006), answering all variables at once gives the full Andersen solution, and the union of the demanded sets of single queries equals the demanded set of all of them. On 200 random programs with 60 statements over 60 variables (seed 2005), one query demanded 23% of the variables on average, and 98 of the 200 queries demanded at most 5 variables. On 300 programs (seed 1990), every fact of a concrete run is in the answer.

Properties

  • Exact with respect to the exhaustive analysis. It is not an approximation of Andersen's analysis: each answer is the same set.
  • Monotone in the queries. More queries demand more variables, never fewer, and the answers do not change.
  • Stores are the expensive part. A taken variable needs the sets of all store pointers, because any of them may point to it. In C code with many stores through pointers, the demanded part can grow to most of the program.
  • Reusable. The demanded sets are final, so a later query can reuse them.

Variants and improvements

  • Pointed-by queries. Heintze and Tardieu avoid demanding every store pointer: for a taken vv they ask a second kind of query, "which pointers may point to vv?", and only follow the stores whose pointers are in its answer. They also cache answers between queries.
  • CFL reachability. For Java, where pointers come from fields and not from address-of, a points-to query is a search for paths in a graph of assignments whose field stores and loads match, like balanced parentheses. Sridharan and Bodík add matching calls and returns for context sensitivity, and a refinement loop that starts with cheap, imprecise matching and refines only the parts that affect the client's question, within a budget.
  • Magic sets. Writing Andersen's rules in Datalog and applying the magic-sets rewriting to the query gives this algorithm automatically.
  • Incremental and demand-driven alias queries. The same backward search answers alias questions for two pointers, and can stop as soon as a common target is found.

When to use it

Use it when a client needs points-to facts for a small part of a large program: an IDE that shows the targets of a call, a bug checker that asks about a few dereferences, or a just-in-time compiler with a time limit. When the client needs facts for most variables, for example a whole-program optimizer, the exhaustive Andersen analysis with cycle elimination is faster, because it shares work between all variables.

Pitfalls

  • Forgetting stores into a taken variable. A version of START without line L12 only follows copies and loads. It misses every value written through a pointer, so in the example it returns pts(t)={a}pts(t) = \{a\} instead of {a,b}\{a, b\}. Line L12 must demand every store pointer for a taken variable and add the store edge when that pointer may point to it.
  • Handling only the sets present at the start. A version of START that adds the load and store edges only for the elements present when the variable starts is incomplete. Lines L5 and L6 must also add the edges for elements that arrive later.
  • Answering before the worklist is empty. A query answer is final only when no variable waits to start and the worklist is empty, as in line L2. Partial answers are under-approximations.
  • Calling it sound with reflection or native code. Like the exhaustive analysis, it only covers the statements it sees. Code that is loaded, generated or called through native interfaces needs a model.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

demand_driven_points_to.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/demand-driven-points-to/. The authors are listed in prov/MGQX2W.jsonl.
"""Demand-driven inclusion-based points-to analysis.

demand_points_to(stmts, queries) 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 a list of query variables. It returns
(answer, demanded): answer maps each query to its set in the least solution
of Andersen's subset constraints, and demanded is the set of variables whose
sets the run had to compute.

The run only builds the part of Andersen's constraint graph that the
queries need. A variable is demanded when a query names it, or when the set
of a demanded variable depends on it: the source of a copy, the pointer of a
load and the targets of that pointer, and, for a demanded variable whose
address is taken, the pointer and the source of every store that may write
to it. This is the magic-sets form of Andersen's rules with the first
argument bound. Each demanded variable keeps delta, the part of its set that
it has not yet sent along its edges or used for loads and stores.
"""

from collections import deque


def demand_points_to(stmts, queries):
    addr_into, copy_into, load_into = {}, {}, {}
    loads_of, stores_of = {}, {}
    stores, taken = [], set()
    for kind, x, y in stmts:
        if kind == "addr":
            addr_into.setdefault(x, []).append(y)
            taken.add(y)
        elif kind == "copy":
            copy_into.setdefault(x, []).append(y)
        elif kind == "load":
            load_into.setdefault(x, []).append(y)
            loads_of.setdefault(y, []).append(x)
        else:
            stores_of.setdefault(x, []).append(y)
            stores.append((x, y))

    pts, delta, succ = {}, {}, {}
    starting = deque()
    work = deque()
    queued = set()

    def demand(v):
        if v not in pts:  # @line L14
            pts[v], delta[v], succ[v] = set(), set(), set()
            starting.append(v)

    def add(s, v):
        new = s - pts[v]  # @line L15
        if new:
            pts[v] |= new
            delta[v] |= new
            if v not in queued:
                queued.add(v)
                work.append(v)

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

    def start(v):
        add(set(addr_into.get(v, ())), v)  # @line L9
        for y in copy_into.get(v, ()):
            edge(y, v)  # @line L10
        for y in load_into.get(v, ()):
            demand(y)  # @line L11
            for b in list(pts[y]):
                edge(b, v)
        if v in taken:
            for p, q in stores:
                demand(p)  # @line L12
                if v in pts[p]:
                    edge(q, v)

    for q in queries:
        demand(q)  # @line L1
    while starting or work:  # @line L2
        if starting:
            start(starting.popleft())  # @line L3
            continue
        n = work.popleft()  # @line L4
        queued.discard(n)
        d = delta[n]
        delta[n] = set()
        for a in d:
            for x in loads_of.get(n, ()):
                if x in pts:
                    edge(a, x)  # @line L5
            if a in pts:
                for q in stores_of.get(n, ()):
                    edge(q, a)  # @line L6
        for w in list(succ[n]):
            add(d, w)  # @line L7
    return {q: pts[q] for q in queries}, set(pts)  # @line L8
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_demand_driven_points_to.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/demand-driven-points-to/. The authors are listed in prov/MGQX2W.jsonl.

import random
from collections import deque

import ptsgen
from demand_driven_points_to import demand_points_to

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


def andersen(stmts):
    """The exhaustive analysis, a copy of the solver of the Andersen page:
    a constraint graph with difference propagation over all variables."""
    names = ptsgen.variables(stmts)
    pts = {v: set() for v in names}
    succ = {v: set() for v in names}
    delta = {v: set() for v in names}
    loads = {v: set() for v in names}
    stores = {v: set() for v in names}
    work = deque()
    queued = set()

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

    def propagate(s, v):
        new = s - pts[v]
        if new:
            pts[v] |= new
            delta[v] |= new
            push(v)

    def add_edge(u, v):
        if v not in succ[u]:
            succ[u].add(v)
            propagate(pts[u], v)

    for kind, x, y in stmts:
        if kind == "addr":
            pts[x].add(y)
            delta[x].add(y)
            push(x)
        elif kind == "load":
            loads[y].add(x)
        elif kind == "store":
            stores[x].add(y)
    for kind, x, y in stmts:
        if kind == "copy":
            add_edge(y, x)
    while work:
        n = work.popleft()
        queued.discard(n)
        d = delta[n]
        delta[n] = set()
        for a in d:
            for p in loads[n]:
                add_edge(a, p)
            for q in stores[n]:
                add_edge(q, a)
        for w in list(succ[n]):
            propagate(d, w)
    return pts


def test_page_example():
    stmts = ptsgen.parse(PAGE)
    answer, demanded = demand_points_to(stmts, ["t"])
    assert answer == {"t": {"a", "b"}}
    assert demanded == {"t", "r", "p", "s", "q"}
    answer, demanded = demand_points_to(stmts, ["q"])
    assert answer == {"q": {"b"}}
    assert demanded == {"q"}
    answer, demanded = demand_points_to(stmts, ["w"])
    assert answer == {"w": set()}
    assert demanded == {"w", "v", "u", "c", "r"}


def test_empty_and_unknown_queries():
    assert demand_points_to([], ["x"]) == ({"x": set()}, {"x"})
    assert demand_points_to([("addr", "p", "a")], []) == ({}, set())


def test_store_through_self():
    stmts = [("addr", "p", "p"), ("store", "p", "p")]
    answer, _ = demand_points_to(stmts, ["p"])
    assert answer == {"p": {"p"}}


def programs(seed, count):
    rng = random.Random(seed)
    for _ in range(count):
        nvars = rng.randint(2, 12)
        yield rng, ptsgen.random_program(rng, nvars, rng.randint(1, 40))


def test_same_as_exhaustive_analysis_for_every_query():
    for rng, stmts in programs(2001, 400):
        full = andersen(stmts)
        assert full == ptsgen.least_solution(stmts)
        names = ptsgen.variables(stmts)
        for _ in range(3):
            q = rng.choice(names)
            answer, demanded = demand_points_to(stmts, [q])
            assert answer == {q: full[q]}, ptsgen.show(stmts)
            assert q in demanded <= set(names) | {q}
        some = rng.sample(names, rng.randint(1, len(names)))
        answer, _ = demand_points_to(stmts, some)
        assert answer == {q: full[q] for q in some}


def test_queries_together_or_alone():
    for rng, stmts in programs(2006, 200):
        names = ptsgen.variables(stmts)
        together, both = demand_points_to(stmts, names)
        assert together == andersen(stmts)
        alone = set()
        for q in names:
            answer, demanded = demand_points_to(stmts, [q])
            assert answer[q] == together[q]
            alone |= demanded
        assert alone == both


def test_sound_against_concrete_runs():
    for rng, stmts in programs(1990, 300):
        facts = ptsgen.concrete_facts(stmts, rng, runs=10, steps=80)
        names = ptsgen.variables(stmts)
        answer, _ = demand_points_to(stmts, names[: len(names) // 2 + 1])
        for p, a in facts:
            if p in answer:
                assert a in answer[p], ptsgen.show(stmts)


def test_demand_skips_unrelated_variables():
    rng = random.Random(2005)
    total, part = 0, 0
    for _ in range(200):
        stmts = ptsgen.random_program(rng, 60, 60)
        names = ptsgen.variables(stmts)
        q = rng.choice(names)
        _, demanded = demand_points_to(stmts, [q])
        total += len(names)
        part += len(demanded)
    assert part < 0.5 * total

History

Andersen's inclusion-based analysis dates from 1994, and exhaustive solvers for it were made fast in the following years. Heintze and Tardieu (2001) showed that a demand-driven version could answer queries on very large C programs quickly. Sridharan, Gopan, Shan and Bodík (2005) formulated demand-driven points-to analysis for Java as CFL reachability, and Sridharan and Bodík (2006) added refinement and context sensitivity. The link to Datalog and magic sets made the idea a standard part of declarative program analysis.

References

  1. Nevin Heintze and Olivier Tardieu, Demand-driven pointer analysis, Proceedings of PLDI 2001, the demand-driven form of Andersen's analysis for C, with points-to and pointed-by queries and caching between queries
  2. Manu Sridharan and Rastislav Bodík, Refinement-based context-sensitive points-to analysis for Java, Proceedings of PLDI 2006, points-to queries as CFL reachability with balanced fields and calls, refined on demand within a budget

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/MGQX2W/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
  • at least three sources
  • a scene preset for the example