Algorithm Search⌘K

Algorithmadvanced

Escape analysis

Also called escape analysis for objects.

Finds objects that do not outlive their method or thread, so they can be put on the stack and their locks removed.

Time
O(n^2 h + s h) worst
Space
O(n^2 + n h + s) extra
Where
h = the number of allocation sites; n = the number of nodes of the constraint graph; s = the total size of the statements
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
Jong Deok Choi, Manish Gupta, Mauricio Serrano, Vugranam C. Sreedhar, Samuel Midkiff, Bruno Blanchet, John Whaley, Martin Rinard, 1999

Escape analysis finds the objects that cannot outlive the method that creates them, and the objects that only one thread can ever see. An object escapes its method when some path of references from outside the method's activation can reach it: through a global, a parameter object of the caller, or the return value. An object escapes its thread when another thread can reach it, through a global or through the arguments of a thread start. The first fact lets a compiler put the object in the method's stack frame, or break it into local variables with scalar replacement. The second lets it remove the locks on the object. The algorithm on this page follows Choi and colleagues (1999): it gives each allocation site one of three states, NONE, ARG or GLOBAL, from a points-to graph of the whole program. Here the graph comes from a field-sensitive Andersen analysis.

In plain words

Many objects in object-oriented code live only for a moment: an iterator in a loop, a small result object, a temporary string builder. If no one outside the method can ever get a reference to such an object, the method can keep it in its own stack frame, and the garbage collector never sees it. Escape analysis checks this. It follows every way a reference can leave a method: it can be stored in a global, written into an object that the caller gave, returned, or handed to a new thread. If none of these ways can reach the object, it stays inside. If only the thread start and global ways are closed, the object stays in one thread, so locking it is not needed. The check is safe: when it says an object stays inside, that is true for every run.

The problem

The input is a program of methods with the statements $x = $ new at site ss, x=yx = y, x=y.fx = y.f, x.f=yx.f = y, x=gx = g and g=yg = y for a global gg, x=m(a1,…)x = m(a_1, \ldots), start m(a1,…)m(a_1, \ldots) in a new thread, and ret y. The output is a state for each allocation site ss in method mm: GLOBAL if an object of ss may be reachable from a global or from a thread other than the one that made it, ARG if not, but it may be reachable from a parameter or the return value of mm, and NONE otherwise.

item value
direction none: flow-insensitive, one answer for the whole program
may or must may: GLOBAL and ARG mean "may escape"
domain points-to sets of the locals, globals, return values and fields of sites, then one state for each site
order inclusion of sets, and NONE below ARG below GLOBAL (bottom is precise)
join union of sets, and maximum of states
bottom and top empty sets and every site NONE, and every set full and every site GLOBAL
boundary value the objects of globals and of thread start arguments are GLOBAL, and those of parameters and return values of mm are at least ARG for the sites of mm
initial value every set empty
transfer Andersen's inclusion rules for each statement, then reachability through the field sets

The algorithm

  1. ESCAPE(P)
  2. 1pts = ANDERSEN(P), with fields, globals, calls, returns and thread starts as copies
  3. 2roots = the sites in pts(g) for every global g, and in pts(a) for every argument a of every start
  4. 3shared = all sites reachable from roots through the field sets pts(s.f)
  5. 4for each method m do
  6. 5out = the sites in pts(p) for every parameter p of m, and in the return value of m
  7. 6out = all sites reachable from out through the field sets
  8. 7for each allocation site s in m do
  9. 8if s is in shared then state(s) = GLOBAL
  10. 9else if s is in out then state(s) = ARG
  11. 10else state(s) = NONE
  12. 11return state

Line L1 builds one points-to graph for the whole program. A call adds the copies pi⊇aip_i \supseteq a_i from each argument to the callee's parameter and x⊇retx \supseteq ret from the callee's return value. A start adds the parameter copies only. A field ff of the objects of site ss is one node s.fs.f, so a store x.f=yx.f = y adds yy to s.fs.f for every ss in pts(x)pts(x), and a load reads it.

Lines L2 and L3 find what other threads may see. Every object that a global may hold, or that is passed to a new thread, is shared, and so is everything reachable from it. Lines L5 and L6 do the same for one method: its parameter objects belong to its callers, and its return value goes to its caller. A site of mm in neither set is NONE. Its objects are reachable only from the activation that made them and from the methods that activation calls, and they are garbage when it returns.

Example

main():                    make():                  worker(p):
  a = new      // s1         d = new    // s4         q = new    // s7
  b = new      // s2         e = new    // s5         p.f = q
  a.f = b                    d.f = e                  r = new    // s8
  c = make()                 w = new    // s6         G = r
  t = new      // s3         w.f = d
  start worker(t)            ret d
site state why
s1s_1, s2s_2 NONE only locals of main reach them
s3s_3 GLOBAL it is the argument of a thread start
s4s_4 ARG make returns it
s5s_5 ARG it is reachable from the return value through s4.fs_4.f
s6s_6 NONE it points to s4s_4, but nothing points to it
s7s_7 GLOBAL it is stored into s3.fs_3.f, and s3s_3 is shared
s8s_8 GLOBAL it is stored in the global GG

So s1s_1, s2s_2 and s6s_6 can live in the stack frame of their method. The objects of s4s_4 and s5s_5 outlive make, but no other thread sees them, so their locks can go. If the compiler inlines make into main, they become NONE in main too. The other three need the heap and their locks. Note that s7s_7 is made by worker and never stored in a global, but the thread that started worker can reach it through tt.

Correctness

The proof file shows three facts. First, the points-to stage is sound for every run, including every interleaving of threads: each value that a local, a field, a global or a return slot holds has its site in the matching set. Second, a frontier lemma: split the frames into inside and outside. If every object that both sides reach has its site in a set BB that is closed under the field sets, and every way across the frontier, a global or a start argument, only carries sites of BB, then this stays true, and an object made inside with its site outside BB never becomes reachable from outside. Third, two uses of the lemma. With the frames of one thread inside and BB = shared, objects of non-GLOBAL sites are never seen by another thread. With one activation of mm and its callees inside and BB = shared plus out of mm, objects of NONE sites are never reachable from the caller, and when the activation returns, its return value does not reach them, so no root does.

Proof: An object of a NONE site is unreachable from outside its activation, and an object of a site that is not GLOBAL is never seen by another threadfull

Setting. A program is a set of methods. Each method mm has parameters, locals and a list of statements of the forms of the page: new, copy, load, store, global load, global store, call, start and ret. A run starts with one thread whose stack holds one frame of the main method. A frame is an activation of a method: it holds the values of its locals and parameters, and a return slot that ret y sets. A step picks a thread and either runs the next statement of its top frame, skips it, or pops the top frame when its body is done and puts the return slot into the destination local of the frame below. A call pushes a frame with the argument values as parameters. A start makes a new thread with one such frame. Skipping models branches, so the runs include every path of every control flow of the bodies. Each object oo has the site site(o)site(o) of the new that made it. An object o′o' is reachable from oo if a chain of fields leads from oo to o′o', and reachable from a frame or a global if it is reachable from a value it holds.

ptspts is the least solution of the inclusion constraints of the points-to stage (line L1): s∈pts(m.x)s \in pts(m.x) for $x = $ new at ss in mm; pts(m.y)⊆pts(m.x)pts(m.y) \subseteq pts(m.x) for a copy; for x=y.fx = y.f, pts(s.f)⊆pts(m.x)pts(s.f) \subseteq pts(m.x) for every s∈pts(m.y)s \in pts(m.y); for x.f=yx.f = y, pts(m.y)⊆pts(s.f)pts(m.y) \subseteq pts(s.f) for every s∈pts(m.x)s \in pts(m.x); pts(g)⊆pts(m.x)pts(g) \subseteq pts(m.x) and pts(m.y)⊆pts(g)pts(m.y) \subseteq pts(g) for the global forms; pts(m.ai)⊆pts(n.pi)pts(m.a_i) \subseteq pts(n.p_i) for each argument of a call or start of nn; pts(retn)⊆pts(m.x)pts(ret_n) \subseteq pts(m.x) for x=n(…)x = n(\ldots); and pts(m.y)⊆pts(retm)pts(m.y) \subseteq pts(ret_m) for ret y in mm. The heap closure cl(X)cl(X) of a set XX of sites is the least superset of XX that contains pts(s.f)pts(s.f) for every ss in it and every field ff. Let

G=cl(⋃gpts(g)∪⋃start n(a1,…) in mpts(m.ai)),Em=cl(pts(retm)∪⋃ipts(m.pi)).G = cl\Big(\bigcup_g pts(g) \cup \bigcup_{\text{start } n(a_1, \ldots)\text{ in } m} pts(m.a_i)\Big), \qquad E_m = cl\Big(pts(ret_m) \cup \bigcup_i pts(m.p_i)\Big).

Lines L2 to L10 set $state(s) = $ GLOBAL if s∈Gs \in G, ARG if s∈Em∖Gs \in E_m \setminus G for the method mm of ss, and NONE otherwise.

Lemma 1 (the points-to stage is sound). At every moment of every run: if a local xx of a frame of mm holds oo, then site(o)∈pts(m.x)site(o) \in pts(m.x); if field ff of oo holds o′o', then site(o′)∈pts(site(o).f)site(o') \in pts(site(o).f); if global gg holds oo, then site(o)∈pts(g)site(o) \in pts(g); and if the return slot of a frame of mm holds oo, then site(o)∈pts(retm)site(o) \in pts(ret_m). So if o′o' is reachable from oo, then site(o′)∈cl({site(o)})site(o') \in cl(\{site(o)\}).

Proof. By induction on the steps. At the start nothing holds an object. Each step writes one place, and the value written is covered by the constraint of its statement, using the induction hypothesis for the place it was read from: a call writes parameters, covered by the argument constraints; a pop writes the destination local, covered by the return constraint; a load reads o.fo.f with site(o)∈pts(m.y)site(o) \in pts(m.y), and a store writes o.fo.f with site(o)∈pts(m.x)site(o) \in pts(m.x). A skipped step writes nothing. The claim about reachability follows by induction on the length of the chain of fields. □\square

The frontier argument. Fix a run, a time interval [t0,t1][t_0, t_1], a set II of frames called inside, and a set BB of sites with cl(B)=Bcl(B) = B. At each moment let InIn be the objects reachable from inside frames, and OutOut the objects reachable from globals or from frames that are not inside. Assume:

  1. a frame joins II only when an inside frame calls, the new frame is the callee, and no frame leaves II except by its return;
  2. at t0t_0, every object in In∩OutIn \cap Out has its site in BB;
  3. pts(g)⊆Bpts(g) \subseteq B for every global gg, and pts(m.a)⊆Bpts(m.a) \subseteq B for every argument aa of every start in every method;
  4. no inside frame returns into a frame that is not inside before t1t_1.

Lemma 2 (frontier). Under these assumptions, at every moment of [t0,t1][t_0, t_1]: (P) every object in In∩OutIn \cap Out has its site in BB; and (Q) every object in OutOut that an inside frame made during the interval has its site in BB.

Proof. Both hold at t0t_0: (P) by assumption 2, and (Q) because nothing is made yet. Consider one step. A step that only removes references, such as a skip, a pop or the overwrite of a value, can only shrink InIn and OutOut, which keeps both claims, with one exception: a pop that writes the return value, treated below. For the other steps, note first that adding a reference from an object or root outside OutOut does not change OutOut.

A step of an inside frame. A new adds a fresh object to InIn only. A copy, a load or a ret writes into an inside frame a value that is already in InIn, so neither set changes. A call pushes an inside frame with values already in InIn (assumption 1). A pop of an inside frame into an inside frame writes a value of InIn into InIn (assumption 4 excludes the other case). A store x.f=yx.f = y writes into ox∈Ino_x \in In the object oy∈Ino_y \in In. If ox∉Outo_x \notin Out, OutOut does not change. If ox∈Outo_x \in Out, then site(ox)∈Bsite(o_x) \in B by (P), the new objects of OutOut are reachable from oxo_x after the step, and by Lemma 1 their sites are in cl(B)=Bcl(B) = B. A global load brings the object of gg, and the objects reachable from it, into InIn; they have sites in cl(pts(g))⊆Bcl(pts(g)) \subseteq B by Lemma 1 and assumption 3. A global store and a start make the objects reachable from the value or the arguments reachable from a global or from a new frame that is not inside, and their sites are in cl(pts(g))cl(pts(g)) or cl(pts(m.a))⊆Bcl(pts(m.a)) \subseteq B by assumption 3. In every case each object that joins OutOut or In∩OutIn \cap Out has its site in BB.

A step of a frame that is not inside. It is a frame of another thread, or a frame below the inside frames that is not on top, and only top frames run. A new adds a fresh object to OutOut, not made by an inside frame. A copy, a load, a global load or a global store moves values that are already in OutOut, so OutOut does not grow, and InIn does not change. A call, a start or a pop puts values of OutOut into frames that are not inside. A store x.f=yx.f = y with ox,oy∈Outo_x, o_y \in Out does not grow OutOut, and if ox∈Ino_x \in In, the new objects of InIn are reachable from oxo_x, whose site is in BB by (P), so their sites are in BB by Lemma 1. □\square

Theorem 1 (threads). If state(s)≠state(s) \neq GLOBAL, then no object of site ss is ever reachable from a global or from a frame of a thread other than the thread that made it.

Proof. Let thread TT make oo with site(o)=s∉Gsite(o) = s \notin G. Take II = all frames of TT, from the start of TT to the end of the run, and B=GB = G, which is closed. Assumption 1 holds, since frames of TT come only from calls in TT. Assumption 3 holds by the definition of GG. Assumption 4 holds, since the first frame of TT has no frame below it. For assumption 2, at the start of TT the inside objects are those reachable from the start arguments, whose sites are in GG. By (Q) of Lemma 2, o∉Outo \notin Out at every moment, and OutOut is exactly the set of objects reachable from globals or from other threads. □\square

Theorem 2 (activations). If state(s)=state(s) = NONE for a site ss of method mm, then each object oo of site ss, made by an activation AA of mm, is reachable only from AA and the frames that AA calls while AA runs, and from no root at all after AA returns. So oo can be allocated in the frame of AA.

Proof. Here s∉G∪Ems \notin G \cup E_m. Let t0t_0 be the push of AA and t1t_1 the moment just before its pop. Take II = AA and every frame pushed above AA while AA is on the stack, and B=G∪EmB = G \cup E_m, which is closed as a union of closed sets. Assumption 1 holds because only the top frame of TT calls. Assumption 3 holds since G⊆BG \subseteq B. Assumption 4 holds since only AA returns into a frame below AA, and that happens after t1t_1. For assumption 2, at t0t_0 the inside objects are those reachable from the parameters of AA, with sites in cl(⋃ipts(m.pi))⊆Emcl(\bigcup_i pts(m.p_i)) \subseteq E_m by Lemma 1. Every object of site ss is made by a frame of mm, and AA is inside, so by (Q), o∉Outo \notin Out during [t0,t1][t_0, t_1]: no global, no other thread and no frame below AA reaches it.

At the pop of AA, the return slot holds an object rr with site(r)∈pts(retm)site(r) \in pts(ret_m), and the objects reachable from rr have sites in EmE_m by Lemma 1, so oo is not among them. After the pop, every root is a root that was outside before, or the destination local that now holds rr. So no root reaches oo. A step can only create a reference to an object that some root reaches, so oo stays unreachable for the rest of the run. □\square

Theorem 3 (termination and cost). Let nn be the number of nodes of the constraint graph (locals, return values, globals and pairs of a site and a field), hh the number of sites and ss the total size of the statements, counting each argument. The analysis stops and takes O(n2h+sh)O(n^2 h + s h) time and O(n2+nh+s)O(n^2 + n h + s) space.

Proof. Each node's set only grows inside the hh sites, so there are at most nhn h insertions, and the worklist stops. With difference propagation each pair of a node and a site is sent along each out-edge of the node once, and there are at most n2n^2 distinct edges, so propagation costs O(n2h)O(n^2 h). Each new edge first sends the whole set of its source, O(h)O(h), for O(n2h)O(n^2 h) in total. Each pair of a load or store statement and a site of its base pointer is handled once, for O(sh)O(s h) edge requests. The heap closure of a set of sites visits each site once and each element of each set pts(s.f)pts(s.f) once, which is O(nh)O(n h). It runs once for GG and once for each method, and there are at most nn methods, since each has a return node, so this part is O(n2h)O(n^2 h). The space holds the edges, the sets and the statements. ■\blacksquare

Complexity

Proved. Let nn be the number of nodes of the constraint graph (locals, return values, globals and pairs of a site and a field), hh the number of sites and ss the total size of the statements. The Andersen stage with difference propagation takes O(n2h+sh)O(n^2 h + s h) time. Each closure of lines L3 and L6 takes O(nh)O(n h), once for the shared set and once per method, and there are at most nn methods. So the whole analysis takes O(n2h+sh)O(n^2 h + s h) time and O(n2+nh+s)O(n^2 + n h + s) space.

Stated in the literature. Choi and colleagues report, for a set of Java benchmarks in a static compiler, that a large share of the objects could be allocated on the stack in some programs and that many lock operations could be removed, with a measurable speedup. Stadler, Würthinger and Mössenböck report that a partial escape analysis in a just-in-time compiler removes more allocations and locks than an analysis that decides once per method.

Measured, not proved. On 250 random programs with up to 4 methods, threads, globals, recursion and two fields (seed 2024), the 2608 sites got 1608 NONE, 431 ARG and 569 GLOBAL states. Three random interleaved runs of each program, with each statement skipped with probability 0.2 to model branches, checked the claims of both theorems after every step, 575103 checks in all, with no failure. Dropping the globals, the start arguments, the return values or the parameters from lines L2 and L5 made the same check fail in 138, 33, 99 and 17 of the 750 runs.

Properties

  • Sound, not exact. A NONE object never escapes in any run, but an object marked ARG or GLOBAL may never escape in a real run.
  • Context-insensitive. All activations of a method share one set per variable, so a method that sometimes receives an escaping object makes its parameter objects escape for all callers. Object sensitivity or method summaries reduce this.
  • Flow-insensitive. An object that escapes only on one branch, or only at the end of a method, escapes everywhere.
  • Thread-aware. Thread starts are roots of escape, like globals. An analysis that ignores them would remove locks from objects that two threads share.
  • Whole program. The answer for one method depends on its callers and callees, so loading a new class can change it. A just-in-time compiler that uses the result must be able to undo it.

Variants and improvements

  • Connection graphs. Choi and colleagues build a summary graph for each method that records which parameter fields may reach which objects, and combine summaries at call sites, without a whole-program points-to analysis. This gives some context sensitivity, since each call site maps the summary to its own arguments.
  • Escape by types. Blanchet's analysis abstracts each value by an integer that says how much of its type may escape, and computes it by abstract interpretation. It is fast and handles recursion over lists and trees.
  • Points-to escape graphs. Whaley and Rinard separate inside edges, made by the method, from outside edges, which stand for unknown objects of the caller. A method's summary can then be reused, and objects captured by a method or a thread are found compositionally.
  • Partial escape analysis. In a just-in-time compiler, Stadler, Würthinger and Mössenböck decide escape per control flow branch. An object that escapes only on a rare path is created only on that path, and is replaced by local values on the others.
  • Regions. Region-based memory management generalizes stack allocation: an object goes into the region of the outermost activation that it cannot escape.

When to use it

Use it in a compiler for a language where every object is on the heap and every object can be locked, such as Java. The common clients are stack allocation, scalar replacement after inlining, and removing locks from thread-local objects. A just-in-time compiler runs it per compiled method after inlining, where most temporary objects become NONE. For languages that already let the programmer choose stack allocation, the same analysis checks that a pointer to a stack object does not outlive the frame.

Pitfalls

  • Forgetting threads. A version of line L2 that uses only the globals as roots treats s3s_3 and s7s_7 in the example as thread-local and removes locks that two threads need. The right line L2 also adds every argument of every thread start.
  • Forgetting the return value. A version of line L5 with only the parameters marks s4s_4 and s5s_5 as NONE, and stack allocation would leave main with a pointer into a dead frame. The right line L5 adds the return value.
  • Forgetting the parameters. A version of line L5 without the parameters misses an object stored into a field of a parameter object, which the caller can then reach. The right line L5 adds the sites of every parameter.
  • Stopping at direct references. A version of lines L3 and L6 that takes only the sets themselves, without the closure, marks s7s_7 as NONE, although it is reachable from the shared s3s_3 through a field. The right lines close over the field sets.
  • Allocation in a loop. A NONE site in a loop makes one object per iteration. One fixed slot in the frame is enough only if the object of the last iteration is dead when the next one is made. Otherwise the frame needs space per iteration, or the object stays on the heap.
  • Claiming soundness with reflection or native code. Reflection, native methods and serialization can store a reference where the analysis does not see it. Such calls must be treated as making their arguments GLOBAL.

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.

escape_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/escape-analysis/. The authors are listed in prov/JVVDBX.jsonl.
"""Escape analysis with threads, on top of a field-sensitive Andersen analysis.

A program is a dict from method names to (params, body). params is a list of
parameter names, and body is a list of statements in these forms:

    ("new", x, s)            x = new object at allocation site s
    ("copy", x, y)           x = y
    ("load", x, y, f)        x = y.f
    ("store", x, f, y)       x.f = y
    ("gload", x, g)          x = global g
    ("gstore", g, y)         global g = y
    ("call", x, m, args)     x = m(args), args is a list of local names
    ("start", m, args)       start a new thread that runs m(args)
    ("ret", y)               the method will return the value of y

Each allocation site appears in one "new" statement. Names are local to their
method; globals have their own name space.

escape(program) returns a dict from each allocation site to one of
    GLOBAL  an object from the site may be reachable from a global or from a
            thread other than the one that made it;
    ARG     not GLOBAL, but an object may be reachable from a parameter or
            the return value of the method that made it, so it may outlive
            the activation that made it;
    NONE    an object never leaves the activation that made it and the
            methods it calls: it can live on the stack, and its locks can go.
"""

from collections import deque

NONE, ARG, GLOBAL = "none", "arg", "global"


def points_to(program):
    """Andersen's analysis with fields, globals, calls, returns and thread
    starts, by a constraint graph with difference propagation. The nodes are
    ("v", m, x) for a local, ("r", m) for the return value of m, ("g", g) for
    a global and ("f", s, f) for field f of the objects of site s."""
    pts, succ, delta, loads, stores = {}, {}, {}, {}, {}
    work = deque()
    queued = set()

    def node(n):
        if n not in pts:
            pts[n], succ[n], delta[n] = set(), set(), set()
            loads[n], stores[n] = [], []
        return n

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

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

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

    def var(m, x):
        return node(("v", m, x))

    for m, (params, body) in program.items():
        node(("r", m))
        for p in params:
            var(m, p)
        for st in body:
            kind = st[0]
            if kind == "new":
                propagate({st[2]}, var(m, st[1]))
            elif kind == "copy":
                add_edge(var(m, st[2]), var(m, st[1]))
            elif kind == "load":
                loads[var(m, st[2])].append((st[3], var(m, st[1])))
            elif kind == "store":
                stores[var(m, st[1])].append((st[2], var(m, st[3])))
            elif kind == "gload":
                add_edge(node(("g", st[2])), var(m, st[1]))
            elif kind == "gstore":
                add_edge(var(m, st[2]), node(("g", st[1])))
            elif kind in ("call", "start"):
                callee, args = (st[2], st[3]) if kind == "call" else (st[1], st[2])
                for p, a in zip(program[callee][0], args):
                    add_edge(var(m, a), var(callee, p))
                if kind == "call":
                    add_edge(node(("r", callee)), var(m, st[1]))
            elif kind == "ret":
                add_edge(var(m, st[1]), node(("r", m)))
    while work:
        n = work.popleft()
        queued.discard(n)
        d = delta[n]
        delta[n] = set()
        for a in d:
            for f, x in loads[n]:
                add_edge(node(("f", a, f)), x)
            for f, y in stores[n]:
                add_edge(y, node(("f", a, f)))
        for w in list(succ[n]):
            propagate(d, w)
    return pts


def heap_graph(pts):
    """Site s -> the sites that some field of an object of s may point to."""
    heap = {}
    for n, s in pts.items():
        if n[0] == "f":
            heap.setdefault(n[1], set()).update(s)
    return heap


def closure(heap, start):
    seen = set(start)
    stack = list(start)
    while stack:
        s = stack.pop()
        for t in heap.get(s, ()):
            if t not in seen:
                seen.add(t)
                stack.append(t)
    return seen


def escape(program):
    pts = points_to(program)  # @line L1
    heap = heap_graph(pts)
    roots = set()
    for n, s in pts.items():
        if n[0] == "g":
            roots |= s
    for m, (_, body) in program.items():
        for st in body:
            if st[0] == "start":
                for a in st[2]:
                    roots |= pts[("v", m, a)]  # @line L2
    shared = closure(heap, roots)  # @line L3
    state = {}
    for m, (params, body) in program.items():  # @line L4
        out = set(pts[("r", m)])
        for p in params:
            out |= pts[("v", m, p)]  # @line L5
        out = closure(heap, out)  # @line L6
        for st in body:
            if st[0] == "new":  # @line L7
                s = st[2]
                if s in shared:
                    state[s] = GLOBAL  # @line L8
                elif s in out:
                    state[s] = ARG  # @line L9
                else:
                    state[s] = NONE  # @line L10
    return state  # @line L11
test_escape_analysis.py 257 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/escape-analysis/. The authors are listed in prov/JVVDBX.jsonl.

import random

from escape_analysis import ARG, GLOBAL, NONE, escape, points_to

PAGE = {
    "main": ([], [
        ("new", "a", "s1"),
        ("new", "b", "s2"),
        ("store", "a", "f", "b"),
        ("call", "c", "make", []),
        ("new", "t", "s3"),
        ("start", "worker", ["t"]),
    ]),
    "make": ([], [
        ("new", "d", "s4"),
        ("new", "e", "s5"),
        ("store", "d", "f", "e"),
        ("new", "w", "s6"),
        ("store", "w", "f", "d"),
        ("ret", "d"),
    ]),
    "worker": (["p"], [
        ("new", "q", "s7"),
        ("store", "p", "f", "q"),
        ("new", "r", "s8"),
        ("gstore", "G", "r"),
    ]),
}


def test_page_example():
    assert escape(PAGE) == {
        "s1": NONE, "s2": NONE, "s3": GLOBAL, "s4": ARG,
        "s5": ARG, "s6": NONE, "s7": GLOBAL, "s8": GLOBAL,
    }


def test_storing_into_a_parameter_escapes_to_the_caller():
    prog = {
        "main": ([], [("new", "a", "s1"), ("call", "x", "fill", ["a"])]),
        "fill": (["p"], [("new", "q", "s2"), ("store", "p", "f", "q")]),
    }
    assert escape(prog) == {"s1": NONE, "s2": ARG}


def test_passing_to_a_callee_that_keeps_it_local_does_not_escape():
    prog = {
        "main": ([], [("new", "a", "s1"), ("call", "x", "use", ["a"])]),
        "use": (["p"], [("load", "y", "p", "f")]),
    }
    assert escape(prog) == {"s1": NONE}


def test_reading_a_global_and_writing_into_it():
    prog = {
        "main": ([], [("gload", "x", "G"), ("new", "a", "s1"), ("store", "x", "f", "a")]),
        "init": ([], [("new", "b", "s2"), ("gstore", "G", "b")]),
    }
    assert escape(prog) == {"s1": GLOBAL, "s2": GLOBAL}


def test_recursion_that_passes_its_object_on():
    prog = {"main": (["p"], [("new", "a", "s1"), ("call", "x", "main", ["a"])])}
    assert escape(prog) == {"s1": ARG}


# Random programs and a concrete interpreter with threads.

FIELDS = ["f0", "f1"]
GLOBALS = ["G0", "G1"]
LOCALS = ["l0", "l1", "l2"]


def random_program(rng, nmethods, nstmts):
    methods = ["m%d" % i for i in range(nmethods)]
    params = {m: ["p%d" % j for j in range(0 if m == "m0" else rng.randint(0, 2))] for m in methods}
    kinds = ["new", "copy", "load", "store", "gload", "gstore", "call", "start", "ret"]
    weights = [4, 2, 2, 3, 1, 1, 3, 1, 2]
    site = 0
    prog = {}
    for m in methods:
        names = params[m] + LOCALS
        body = []
        for x in LOCALS:
            site += 1
            body.append(("new", x, "s%d" % site))
        for _ in range(nstmts):
            kind = rng.choices(kinds, weights)[0]
            if kind == "new":
                site += 1
                body.append(("new", rng.choice(LOCALS), "s%d" % site))
            elif kind == "copy":
                body.append(("copy", rng.choice(LOCALS), rng.choice(names)))
            elif kind == "load":
                body.append(("load", rng.choice(LOCALS), rng.choice(names), rng.choice(FIELDS)))
            elif kind == "store":
                x = rng.choice(params[m] if params[m] and rng.random() < 0.5 else names)
                body.append(("store", x, rng.choice(FIELDS), rng.choice(names)))
            elif kind == "gload":
                body.append(("gload", rng.choice(LOCALS), rng.choice(GLOBALS)))
            elif kind == "gstore":
                body.append(("gstore", rng.choice(GLOBALS), rng.choice(names)))
            elif kind in ("call", "start"):
                callee = rng.choice(methods)
                args = [rng.choice(names) for _ in params[callee]]
                if kind == "call":
                    body.append(("call", rng.choice(LOCALS), callee, args))
                else:
                    body.append(("start", callee, args))
            else:
                body.append(("ret", rng.choice(names)))
        prog[m] = (params[m], body)
    return prog


class Frame:
    def __init__(self, method, env, dest, ident):
        self.method, self.env, self.dest, self.ident = method, env, dest, ident
        self.pc = 0
        self.ret = None


def reach(heap, start):
    seen = set()
    stack = [o for o in start if o is not None]
    while stack:
        o = stack.pop()
        if o in seen:
            continue
        seen.add(o)
        stack.extend(v for v in heap[o].values() if v is not None)
    return seen


def frame_roots(fr):
    return list(fr.env.values()) + [fr.ret]


def run_and_check(prog, state, pts, rng, steps=120, max_depth=4, max_threads=3):
    """Run the program from m0 with random interleaving of threads, and skip
    each statement with probability 0.2, which models a branch. After every
    step, check the escape claims and that the heap matches pts."""
    heap, glob, made = {}, {}, {}
    threads = [[Frame("m0", {}, None, 0)]]
    idents = 1
    checked = 0
    for _ in range(steps):
        live = [t for t in range(len(threads)) if threads[t]]
        if not live:
            break
        t = rng.choice(live)
        stack = threads[t]
        fr = stack[-1]
        params, body = prog[fr.method]
        if fr.pc == len(body):
            stack.pop()
            if stack and fr.dest is not None:
                stack[-1].env[fr.dest] = fr.ret
        else:
            st = body[fr.pc]
            fr.pc += 1
            env = fr.env
            kind = st[0]
            if rng.random() < 0.2:
                pass
            elif kind == "new":
                o = len(heap)
                heap[o] = {}
                made[o] = (st[2], t, fr.ident)
                env[st[1]] = o
            elif kind == "copy":
                env[st[1]] = env.get(st[2])
            elif kind == "load":
                if env.get(st[2]) is not None:
                    env[st[1]] = heap[env[st[2]]].get(st[3])
            elif kind == "store":
                if env.get(st[1]) is not None:
                    heap[env[st[1]]][st[2]] = env.get(st[3])
            elif kind == "gload":
                env[st[1]] = glob.get(st[2])
            elif kind == "gstore":
                glob[st[1]] = env.get(st[2])
            elif kind == "call":
                if len(stack) < max_depth:
                    cparams = prog[st[2]][0]
                    stack.append(Frame(st[2], {p: env.get(a) for p, a in zip(cparams, st[3])}, st[1], idents))
                    idents += 1
            elif kind == "start":
                if len(threads) < max_threads:
                    cparams = prog[st[1]][0]
                    threads.append([Frame(st[1], {p: env.get(a) for p, a in zip(cparams, st[2])}, None, idents)])
                    idents += 1
            else:
                fr.ret = env.get(st[1])
        checked += check(prog, state, pts, heap, glob, made, threads)
    return checked


def check(prog, state, pts, heap, glob, made, threads):
    from_globals = reach(heap, glob.values())
    per_frame = [[reach(heap, frame_roots(fr)) for fr in stack] for stack in threads]
    # The heap and the variables are inside the points-to result.
    for o, fields in heap.items():
        for f, v in fields.items():
            if v is not None:
                assert made[v][0] in pts[("f", made[o][0], f)]
    for stack in threads:
        for fr in stack:
            for x, v in fr.env.items():
                if v is not None:
                    assert made[v][0] in pts[("v", fr.method, x)]
    count = 0
    for o, (site, t, ident) in made.items():
        if state[site] != GLOBAL:
            assert o not in from_globals, site
            for u, frames in enumerate(per_frame):
                if u != t:
                    assert all(o not in r for r in frames), site
            count += 1
        if state[site] == NONE:
            idents = [fr.ident for fr in threads[t]]
            below = idents.index(ident) if ident in idents else len(idents)
            assert all(o not in r for r in per_frame[t][:below]), site
            count += 1
    return count


def test_escape_claims_hold_on_concrete_runs():
    rng = random.Random(2024)
    checked = 0
    kinds = {NONE: 0, ARG: 0, GLOBAL: 0}
    for _ in range(250):
        prog = random_program(rng, rng.randint(1, 4), rng.randint(2, 9))
        state = escape(prog)
        pts = points_to(prog)
        for s in state.values():
            kinds[s] += 1
        for _ in range(3):
            checked += run_and_check(prog, state, pts, rng)
    assert checked > 5000
    assert min(kinds.values()) > 50


def test_a_returned_none_object_is_garbage():
    """After the activation that made a NONE object returns, no root reaches
    the object, so it could have lived in that activation's stack frame."""
    prog = {
        "m0": ([], [("call", "x", "m1", []), ("new", "y", "s9")]),
        "m1": ([], [("new", "a", "s1"), ("new", "b", "s2"), ("store", "a", "f0", "b"), ("ret", "b")]),
    }
    state = escape(prog)
    assert state["s1"] == NONE and state["s2"] == ARG
    rng = random.Random(7)
    assert run_and_check(prog, state, points_to(prog), rng, steps=30) > 0

History

Escape analysis began in functional languages. Park and Goldberg (1992) found lists that do not escape a function, so that they could be allocated on the stack. For Java, three papers at OOPSLA 1999 appeared together: Choi, Gupta, Serrano, Sreedhar and Midkiff with connection graphs and the three escape states, Blanchet with an analysis by abstract interpretation over types, and Whaley and Rinard with compositional points-to escape graphs. All three used the result to allocate on the stack and to remove locks. Escape analysis then moved into just-in-time compilers for Java, where it drives scalar replacement and lock removal after inlining, and Stadler, Würthinger and Mössenböck (2014) made it partial, per control flow branch.

References

  1. Jong-Deok Choi, Manish Gupta, Mauricio Serrano, Vugranam C. Sreedhar and Samuel Midkiff, Escape analysis for Java, Proceedings of OOPSLA 1999, 1 to 19, the connection graph, the three escape states NoEscape, ArgEscape and GlobalEscape, objects reachable from threads as escaping, stack allocation and lock removal
  2. Bruno Blanchet, Escape analysis for object-oriented languages, application to Java, Proceedings of OOPSLA 1999, 20 to 34, escape analysis as an abstract interpretation over types, with stack allocation and synchronization elimination
  3. John Whaley and Martin Rinard, Compositional pointer and escape analysis for Java programs, Proceedings of OOPSLA 1999, 187 to 206, points-to escape graphs with inside and outside edges, method summaries, and objects captured by a method or a thread
  4. Lukas Stadler, Thomas Würthinger and Hanspeter Mössenböck, Partial escape analysis and scalar replacement for Java, Proceedings of CGO 2014, escape decided per control flow branch in a just-in-time compiler, with objects created only on the branches where they escape

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