Algorithm Search⌘K

Algorithmadvanced

Variable type analysis

Also called VTA.

Prune a sound call graph by pushing the classes of new along the assignments of a type propagation graph and keeping the targets that reach each receiver.

Time
O((n + P) K) worst
Space
O((n + P) K) extra
Where
K = the number of classes; P = the number of edges of the initial call graph; n = the size of the program
Properties
not context sensitivedeterministicnot flow sensitiveofflineiterative
Origin
Vijay Sundaresan, Laurie Hendren, Chrislain Razafimahefa, Raja Vallee Rai, Patrick Lam, Etienne Gagnon, Charles Godin, 2000

Variable type analysis (VTA) is a solution of call graph construction that tracks, for each variable and each field, the set of classes whose objects may reach it. It starts from a sound call graph, such as the one of rapid type analysis or class hierarchy analysis. It builds a graph with an edge for each assignment and for each argument and result passing along the initial call edges. It puts the class of each new into its variable, and pushes the classes along the edges after collapsing the cycles. A call y.m(z) then keeps only the initial edges that a class reaching y explains. The result is sound, and it is inside the initial graph.

In plain words

Rapid type analysis keeps one list of created classes for the whole program. So if the program creates a Circle in one place and a Square in another, every variable of type Shape may hold both. Variable type analysis keeps one list per variable. When the code says a = new Circle(), it writes Circle into the list of a. When the code says b = a, everything in the list of a also goes into the list of b. Calls pass lists into parameters and back out of results, along the calls that an earlier, rougher call graph found. When the lists stop growing, a call a.grow() keeps only the methods that the classes in the list of a really run.

The problem

The input is a program in the model of class hierarchy analysis, with the dispatch function LOOKUP(C,m)\mathrm{LOOKUP}(C, m), and a sound initial call graph (R0,E0)(R_0, E_0) whose edges start in methods of R0R_0 and end in methods of R0R_0. The type propagation graph GG has a node M.vM.v for each variable vv of each method M∈R0M \in R_0 and a node ff for each field name. Its edges are M.y→M.xM.y \to M.x for x = y, f→M.xf \to M.x for x = y.f, M.z→fM.z \to f for y.f = z, and for each (s,T)∈E0(s, T) \in E_0 with ss: x = y.m(z) in MM, the edges M.y→T.thisM.y \to T.this, M.z→T.pM.z \to T.p and T.ret→M.xT.ret \to M.x. The seed of M.xM.x is the set of classes CC with x = new C() in MM.

The types are the least τ\tau with seed(v)⊆τ(v)\mathrm{seed}(v) \subseteq \tau(v) and τ(v)⊆τ(w)\tau(v) \subseteq \tau(w) for every edge v→wv \to w. The output keeps the edges (s,T)∈E0(s, T) \in E_0, ss: x = y.m(z) in MM, for which some C∈τ(M.y)C \in \tau(M.y) has LOOKUP(C,m)=T\mathrm{LOOKUP}(C, m) = T, and then the part of them reachable from main.

item value
direction none: flow-insensitive, one answer for the whole program
may or must may
domain maps from the nodes of GG to sets of classes
order pointwise inclusion (bottom is precise)
join pointwise union
bottom and top every node maps to ∅\emptyset, and every node maps to all classes
boundary value the seeds from the new statements
initial value the seeds
transfer τ(w)⊇τ(v)\tau(w) \supseteq \tau(v) for each edge v→wv \to w; distributive, since it copies sets

The algorithm

  1. VTA(P, R0, E0)
  2. 1make a node M.v for each variable v of each method M in R0, and a node f for each field
  3. 2for each x = y in a method M of R0 do add the edge M.y -> M.x
  4. 3for each x = y.f do add f -> M.x; for each y.f = z do add M.z -> f
  5. 4for each (s, T) in E0 with s: x = y.m(z) in M do add M.y -> T.this, M.z -> T.p, T.ret -> M.x
  6. 5for each x = new C() in a method M of R0 do add C to types(M.x)
  7. 6find the strongly connected components of the graph with Tarjan's algorithm
  8. 7for each component c in topological order do
  9. 8for each edge from c to another component d do types(d) <- types(d) ∪ types(c)
  10. 9E <- {(s, T) in E0 : s: x = y.m(z) in M, and some C in types(M.y) has LOOKUP(C, m) = T}
  11. 10R <- the methods reachable from main along E; drop from E the edges of sites outside R
  12. 11return (R, E)

Line L6 uses Tarjan's algorithm. All nodes of one component get the same types, the union of their seeds. Line L7 visits the components so that every component comes after all components with an edge into it. So when line L8 pushes the types of a component, they are final, and each edge is used once. Line L10 removes the methods that only pruned edges reached.

Example

The program of the call graph construction page, with the initial graph of rapid type analysis:

class Shape          { Shape grow() { return this; } }
class Circle : Shape { Shape grow() { return new Square(); } }
class Square : Shape { Shape grow() { return this; } }
class Oval : Circle  { }

main() {
  Shape a = new Circle();
  Shape b = new Square();
  Shape c = a.grow();      // site s1
  Shape d = b.grow();      // site s2
  Shape e = c.grow();      // site s3
}

R0R_0 is main, Circle.grow and Square.grow, and E0E_0 links each of s1, s2 and s3 to both grow methods. The graph has these edges: from each receiver a, b and c to Circle.this and Square.this; from Circle.ret and Square.ret to each result c, d and e; and Square.this to Square.ret for return this. The seeds are {Circle}\{Circle\} for a, {Square}\{Square\} for b and {Square}\{Square\} for Circle.ret.

node types why
a Circle seed
b Square seed
Circle.ret Square seed
c, Square.this, Square.ret Circle, Square one component: c to Square.this to Square.ret to c; it gets Circle from a, and Square from b and Circle.ret
Circle.this Circle, Square from a, b and c
d, e Circle, Square from both results

Line L9 keeps s1 to Circle.grow (the types of a), s2 to Square.grow (the types of b), and s3 to both methods (the types of c). That is 4 edges, against 6 for RTA and 9 for CHA. The run makes 3 calls: s1 to Circle.grow, and s2 and s3 to Square.grow. The edge from s3 to Circle.grow is spurious. It comes from the spurious RTA edge from s1 to Square.grow: along it, the Circle of a flows into Square.this, then to Square.ret and back into c. Starting from the CHA graph gives the same 4 edges here.

Correctness

The types. The least solution maps each node ww to the union of the seeds of the nodes that reach ww. Nodes of one component reach each other, so they share their types. Taking the components in topological order, each component receives the final types of all components with an edge into it, so it ends with the union of the seeds of all nodes that reach it.

Soundness. Take a well-typed program without reflection or native code, and a sound initial graph. By induction over the steps of a run, if a variable vv of a frame of MM holds an object of class CC, then C∈τ(M.v)C \in \tau(M.v), and the same holds for fields. A new is a seed. A copy, a load and a store follow an edge of GG, because all objects share the one node of each field. A call from ss to TT is an edge of E0E_0, since E0E_0 is sound, so line L4 made the edges that carry the receiver, the argument and the result. So at a call, the class CC of the receiver is in τ(M.y)\tau(M.y), the target is LOOKUP(C,m)\mathrm{LOOKUP}(C, m), and line L9 keeps the edge. The caller is in RR by induction, so line L10 keeps it too.

Nesting. Line L9 keeps a subset of E0E_0, so VTA⊆RTA⊆CHA\mathrm{VTA} \subseteq \mathrm{RTA} \subseteq \mathrm{CHA} when the initial graph is the RTA graph. A larger initial graph gives a larger graph GG, larger types and a larger result. The full proofs are in the proof file.

Proof: Variable type analysis computes the least type assignment of its graph, and its pruned call graph is sound and inside the initial graphfull

Setting. The program, C≤DC \le D, decl\mathrm{decl}, LOOKUP\mathrm{LOOKUP} and well typed are as in the proof of class hierarchy analysis. The program has no reflection, no native code and no classes loaded at run time. The initial graph (R0,E0)(R_0, E_0) is sound: every method that a run enters is in R0R_0, and every call of a run from site ss to method TT has (s,T)∈E0(s, T) \in E_0. It is also closed under targets: main∈R0main \in R_0, every site of an edge of E0E_0 lies in a method of R0R_0, and every target of an edge of E0E_0 is in R0R_0. The results of class hierarchy analysis and of rapid type analysis have both properties.

The graph GG has a node M.vM.v for each variable vv of each method M∈R0M \in R_0, and a node ff for each field name. Its edges come from lines L2 to L4: M.y→M.xM.y \to M.x for x = y in MM; f→M.xf \to M.x for x = y.f; M.z→fM.z \to f for y.f = z; and for each edge (s,T)∈E0(s, T) \in E_0 with ss: x = y.m(z) in MM, the edges M.y→T.thisM.y \to T.this, M.z→T.pM.z \to T.p and T.ret→M.xT.ret \to M.x. The seed of a node M.xM.x is the set of classes CC with x = new C() in MM (line L5); other seeds are empty. A type assignment τ\tau maps each node to a set of classes. It is a solution if seed(v)⊆τ(v)\mathrm{seed}(v) \subseteq \tau(v) for every node and τ(v)⊆τ(w)\tau(v) \subseteq \tau(w) for every edge v→wv \to w.

Lemma 1 (the least solution). Let τ∗(w)=⋃{seed(v):v reaches w in G}\tau^*(w) = \bigcup \{\mathrm{seed}(v) : v \text{ reaches } w \text{ in } G\}, where every node reaches itself. Then τ∗\tau^* is the least solution.

Proof. τ∗\tau^* is a solution: seed(w)⊆τ∗(w)\mathrm{seed}(w) \subseteq \tau^*(w), and for an edge v→wv \to w, every node that reaches vv also reaches ww. Let τ\tau be any solution, and let vv reach ww along a path v=v0→v1→⋯→vk=wv = v_0 \to v_1 \to \dots \to v_k = w. Then seed(v)⊆τ(v0)⊆τ(v1)⊆⋯⊆τ(w)\mathrm{seed}(v) \subseteq \tau(v_0) \subseteq \tau(v_1) \subseteq \dots \subseteq \tau(w). So τ∗⊆τ\tau^* \subseteq \tau. □\square

Lemma 2 (lines L6 to L8 compute it). Lines L6 to L8 stop and give every node ww the set τ∗(w)\tau^*(w).

Proof. Tarjan's algorithm gives the strongly connected components, each as a list, in an order where a component comes after all components that it reaches. Line L7 takes them in the reverse order, which is a topological order of the component graph. Two nodes of one component reach each other, so they reach the same nodes and are reached by the same nodes, and τ∗\tau^* is the same on both. Let cc be a component and σ(c)\sigma(c) the union of the seeds of its nodes. We show by induction in the topological order that when line L7 reaches cc, the set of cc is ⋃{σ(c′):c′ reaches c}\bigcup \{\sigma(c') : c' \text{ reaches } c\}. Every component c′≠cc' \ne c that reaches cc reaches it through a last edge u→wu \to w with uu in a component c′′c'' that reaches cc and ww in cc. The component c′′c'' comes before cc, so line L8 has already added its set, which by induction holds σ(c′)\sigma(c'). Line L8 only adds sets of components that reach cc, so nothing more enters. The set of cc never changes after cc is processed, because no later component has an edge into cc. Each loop is over a finite list, so the lines stop. □\square

Lemma 3 (the run invariant). In every run, at every moment: if a variable vv of a live frame of method MM holds an object of class CC, then C∈τ∗(M.v)C \in \tau^*(M.v); and if the field ff of any object holds an object of class CC, then C∈τ∗(f)C \in \tau^*(f).

Proof. By induction over the steps of the run. At the start, all variables and fields hold null. Every frame belongs to a method that the run entered, which is in R0R_0 by soundness of the initial graph, so its nodes exist. x = new C() in MM puts CC into xx, and C∈seed(M.x)C \in \mathrm{seed}(M.x). x = y copies a value of yy, and the edge M.y→M.xM.y \to M.x carries its class. x = y.f reads the field ff of some object, whose class is in τ∗(f)\tau^*(f) by the induction hypothesis, and the edge f→M.xf \to M.x carries it. y.f = z writes the value of zz into a field ff, and the edge M.z→fM.z \to f carries its class. A call at ss: x = y.m(z) in MM that enters TT has (s,T)∈E0(s, T) \in E_0 by soundness. It binds thisthis in the new frame to the value of yy and pp to the value of zz, and the edges M.y→T.thisM.y \to T.this and M.z→T.pM.z \to T.p carry their classes. When it returns, it writes the value of T.retT.ret into xx, and the edge T.ret→M.xT.ret \to M.x carries its class. Since τ∗\tau^* is a solution, each class lands in the set of the node that receives it. □\square

Theorem 1 (soundness). Let (R,E)(R, E) be the result of lines L9 and L10. Every method that a run enters is in RR, and every call of a run from site ss to TT has (s,T)∈E(s, T) \in E.

Proof. By induction over the calls of the run. The run starts in main∈Rmain \in R. Take a call at site ss: x = y.m(z) in a frame of method MM, on a receiver of class CC, that enters T=LOOKUP(C,m)T = \mathrm{LOOKUP}(C, m). The frame of MM was entered earlier, so M∈RM \in R by the induction hypothesis. By soundness of the initial graph, (s,T)∈E0(s, T) \in E_0. By Lemma 3, C∈τ∗(M.y)C \in \tau^*(M.y), and by type safety (Lemma 4 of the proof of class hierarchy analysis), C≤decl(y)≤decl(m)C \le \mathrm{decl}(y) \le \mathrm{decl}(m). So line L9 keeps (s,T)(s, T). Line L10 searches from mainmain along the kept edges, and ss lies in M∈RM \in R, so the search adds (s,T)(s, T) to EE and TT to RR. □\square

Theorem 2 (inside the initial graph, and monotone). E⊆E0E \subseteq E_0 and R⊆R0R \subseteq R_0. If R0⊆R0′R_0 \subseteq R_0' and E0⊆E0′E_0 \subseteq E_0', then the result for (R0,E0)(R_0, E_0) is inside the result for (R0′,E0′)(R_0', E_0').

Proof. Line L9 keeps a subset of E0E_0. Line L10 starts at main∈R0main \in R_0 and follows edges of E0E_0, whose targets are in R0R_0. For the second part, the graph for (R0′,E0′)(R_0', E_0') contains every node, edge and seed of the graph for (R0,E0)(R_0, E_0), so by Lemma 1 its least solution is pointwise larger. Then line L9 keeps a superset, and the search of line L10 reaches a superset. With the initial graph of rapid type analysis, this gives VTA⊆RTA⊆CHA\mathrm{VTA} \subseteq \mathrm{RTA} \subseteq \mathrm{CHA}, where the second inclusion is Theorem 3 of the proof of rapid type analysis. □\square

Theorem 3 (cost). Let nn be the size of the program, KK the number of classes and P=∣E0∣P = |E_0|. The algorithm runs in O((n+P)K)O((n + P) K) time.

Proof. GG has at most n+Fn + F nodes, for F≤nF \le n field names, and at most n+3Pn + 3P edges, since each statement gives at most one edge and each edge of E0E_0 gives at most three. Lines L1 to L5 build it in O(n+P)O(n + P). Tarjan's algorithm takes O(n+P)O(n + P). Line L8 runs once per edge, and each union of sets of at most KK classes takes O(K)O(K) with bit vectors. Line L9 checks at most KK classes per edge of E0E_0, with a dispatch table, in O(PK)O(P K). Line L10 is a graph search over at most PP edges. The total is O((n+P)K)O((n + P) K). ■\blacksquare

Complexity

Proved. The graph has O(n)O(n) nodes and at most n+3Pn + 3P edges, for P=∣E0∣P = |E_0|. Building it and running Tarjan's algorithm take O(n+P)O(n + P). Line L8 takes one union of sets of at most KK classes per edge, in O(K)O(K) with bit vectors. Line L9 checks at most KK classes per edge of E0E_0. So the time is O((n+P)K)O((n + P) K), and the space for the types is O(nK)O(n K), plus O(n+P)O(n + P) for the graph.

Measured, not proved. On 400 random well-typed programs (seed 2000), the result equals that of a plain iteration of the edges until nothing changes. On 300 random programs with 5 concrete runs each (seed 79), every call that a run makes is in EE. On 300 random programs (seed 7), VTA⊆RTA⊆CHA\mathrm{VTA} \subseteq \mathrm{RTA} \subseteq \mathrm{CHA}, and VTA is strictly smaller than RTA on some of them. On 300 random programs (seed 8), the result from the RTA graph is inside the result from the CHA graph.

Properties

  • Sound only if the initial graph is sound. A call edge missing from E0E_0 means a missing parameter edge in line L4, so the types of the callee are too small.
  • Field-based. One node per field name merges the field ff of all objects. This is what makes stores and loads sound without any alias information.
  • Context-insensitive and flow-insensitive. All calls of a method share its parameter nodes, and the order of statements does not matter.
  • Monotone in the initial graph. A smaller sound initial graph never gives a larger result. So running VTA again with its own result as the initial graph is sound and may prune more.
  • Classes, not objects. The sets hold classes, so two objects of the same class are never told apart. A points-to analysis with allocation sites can tell them apart.

Variants and improvements

  • Declared type analysis. Sundaresan and others also describe a coarser variant with one node per declared type instead of one per variable. It is cheaper and less precise.
  • On-the-fly pruning. Pass a class CC along M.y→T.thisM.y \to T.this only if LOOKUP(C,m)=T\mathrm{LOOKUP}(C, m) = T, and add call edges as types arrive instead of starting from E0E_0. This is a type-based form of Andersen's analysis with an on-the-fly call graph. On the example it removes the spurious edge from s3 and gives the exact 3 edges.
  • Per-method and per-field sets. Tip and Palsberg propagate classes with one set per method, per field or per class. These lie between RTA and VTA.
  • Field-sensitive versions. One node per field of each abstract object needs alias information, which leads to field-sensitive points-to analysis.

When to use it

Use VTA when RTA leaves too many targets and you want a sound graph without a full points-to analysis. It costs one graph build, one pass of Tarjan's algorithm and one propagation pass, and it scales to large Java programs. It is a good input for devirtualization and for an interprocedural analysis that needs a tighter graph. When the precision of classes per variable is not enough, for example for collections that hold many classes, use a points-to analysis with context.

Pitfalls

  • A field node per base variable. Making a node for x.f instead of one node f in line L3 is unsound. With x.f = a; y = x; b = y.f, the class of a goes to x.f and never reaches b. Line L3 must use one node per field name, unless an alias analysis says which bases share objects.
  • Pruning with the declared type. A version of line L9 that keeps the targets of every class C≤decl(y)C \le \mathrm{decl}(y) is just CHA. Line L9 must test the classes in types(M.y)\mathrm{types}(M.y).
  • An unsound initial graph. If E0E_0 comes from a guess, such as the edges seen in a profile, line L4 misses parameter flows, and line L9 may drop real edges. E0E_0 must be sound, for example the result of line L12 of RTA.
  • Forgetting the result edge. A version of line L4 without T.ret→M.xT.ret \to M.x leaves c in the example with no types, and the real call from s3 to Square.grow is lost.
  • Claiming soundness with reflection. Objects from reflection, deserialization or native code do not come from a new of the text, so line L5 has no seed for them.

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.

oomodel.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small object-oriented program model, for the call graph pages.

A program is a dict with these keys:

    "classes"  dict from each class name to its parent, None for the root.
    "methods"  dict from each method name m to (decl, ptype, rtype): the
               class that introduces m, the declared type of its parameter
               p and the declared type of its result.
    "fields"   dict from each field name f to (decl, ftype): the class that
               declares f and the declared type of f.
    "bodies"   dict from each method id (C, m), the method m as class C
               defines it, to (locals, stmts). The root is MAIN, a static
               method with no this, p or ret. locals maps each variable to
               its declared class. Every other body has the variables
               "this" (of type C), "p" and "ret" among its locals.

The statements are tuples:

    ("new", x, C)              x = new C()
    ("copy", x, y)             x = y
    ("load", x, y, f)          x = y.f
    ("store", y, f, z)         y.f = z
    ("call", s, x, y, m, z)    x = y.m(z) at call site s; x or z may be None

A method returns the value of its variable ret. The programs of
random_program are well typed in the sense of Java: a variable or field only
receives objects of its declared class or of a subclass, and a call y.m(z)
has decl(y) <= decl(m), so the dispatch always finds a method.

lookup(prog, C, m) is the method that runs for m on an object of class C.
run(prog, rng) runs the program concretely and returns the call edges and
the methods that the run saw. cha_spec and rta_spec are slow reference
versions of class hierarchy analysis and rapid type analysis: they apply
their rules to every reachable method, round after round, until nothing
changes.
"""

MAIN = ("Main", "main")


def is_sub(prog, c, d):
    """True if class c is d or a subclass of d."""
    while c is not None:
        if c == d:
            return True
        c = prog["classes"][c]
    return False


def subclasses(prog):
    """A dict from each class d to the set of classes c with c <= d."""
    below = {d: set() for d in prog["classes"]}
    for c in prog["classes"]:
        a = c
        while a is not None:
            below[a].add(c)
            a = prog["classes"][a]
    return below


def lookup(prog, c, m):
    """The method id that runs when m is called on an object of class c."""
    while c is not None:
        if (c, m) in prog["bodies"]:
            return (c, m)
        c = prog["classes"][c]
    raise KeyError(f"no method {m} above the class")


def call_sites(prog, mid):
    """The call statements of the body of mid."""
    return [st for st in prog["bodies"][mid][1] if st[0] == "call"]


def all_sites(prog):
    """A dict from each call site to (method id, statement)."""
    out = {}
    for mid, (_, stmts) in prog["bodies"].items():
        for st in stmts:
            if st[0] == "call":
                out[st[1]] = (mid, st)
    return out


def shapes():
    """The example of the call graph pages: Shape, Circle, Square, Oval."""
    S = "Shape"
    return {
        "classes": {S: None, "Circle": S, "Square": S, "Oval": "Circle"},
        "methods": {"grow": (S, S, S)},
        "fields": {},
        "bodies": {
            (S, "grow"): ({"this": S, "p": S, "ret": S}, [("copy", "ret", "this")]),
            ("Circle", "grow"): ({"this": "Circle", "p": S, "ret": S}, [("new", "ret", "Square")]),
            ("Square", "grow"): ({"this": "Square", "p": S, "ret": S}, [("copy", "ret", "this")]),
            MAIN: (
                {"a": S, "b": S, "c": S, "d": S, "e": S},
                [
                    ("new", "a", "Circle"),
                    ("new", "b", "Square"),
                    ("call", "s1", "c", "a", "grow", None),
                    ("call", "s2", "d", "b", "grow", None),
                    ("call", "s3", "e", "c", "grow", None),
                ],
            ),
        },
    }


def random_program(rng, nclasses=5, nmethods=3, nfields=2, nstmts=6):
    """A random well-typed program. rng is a random.Random."""
    names = ["K%d" % i for i in range(nclasses)]
    classes = {names[0]: None}
    for i in range(1, nclasses):
        classes[names[i]] = names[rng.randrange(i)]
    prog = {"classes": classes, "methods": {}, "fields": {}, "bodies": {}}
    below = subclasses(prog)
    for i in range(nmethods):
        prog["methods"]["m%d" % i] = (rng.choice(names), rng.choice(names), rng.choice(names))
    for i in range(nfields):
        prog["fields"]["f%d" % i] = (rng.choice(names), rng.choice(names))
    sites = [0]

    def body(this, ptype, rtype, count):
        local = {"v%d" % i: rng.choice(names) for i in range(3)}
        if this is not None:
            local.update({"this": this, "p": ptype, "ret": rtype})
        allv = list(local)
        dest = [v for v in allv if v != "this"]

        def sub_vars(t):
            return [v for v in allv if is_sub(prog, local[v], t)]

        def super_vars(t):
            return [v for v in dest if is_sub(prog, t, local[v])]

        stmts = []
        if this is None:  # main starts by making objects for two variables
            stmts = [("new", x, rng.choice(sorted(below[local[x]]))) for x in rng.sample(dest, 2)]
        while len(stmts) < count:
            kind = rng.choices(["new", "copy", "load", "store", "call"], (3, 3, 2, 2, 4))[0]
            if kind == "new":
                x = rng.choice(dest)
                stmts.append(("new", x, rng.choice(sorted(below[local[x]]))))
            elif kind == "copy":
                x = rng.choice(dest)
                ys = sub_vars(local[x])
                if ys:
                    stmts.append(("copy", x, rng.choice(ys)))
            elif kind in ("load", "store"):
                if not prog["fields"]:
                    continue
                f = rng.choice(sorted(prog["fields"]))
                fdecl, ftype = prog["fields"][f]
                ys = sub_vars(fdecl)
                if not ys:
                    continue
                if kind == "load":
                    xs = super_vars(ftype)
                    if xs:
                        stmts.append(("load", rng.choice(xs), rng.choice(ys), f))
                else:
                    zs = sub_vars(ftype)
                    if zs:
                        stmts.append(("store", rng.choice(ys), f, rng.choice(zs)))
            else:
                m = rng.choice(sorted(prog["methods"]))
                mdecl, pt, rt = prog["methods"][m]
                ys = sub_vars(mdecl)
                if not ys:
                    continue
                zs = sub_vars(pt)
                xs = super_vars(rt)
                z = rng.choice(zs) if zs and rng.random() < 0.8 else None
                x = rng.choice(xs) if xs and rng.random() < 0.8 else None
                sites[0] += 1
                stmts.append(("call", "s%d" % sites[0], x, rng.choice(ys), m, z))
        return local, stmts

    for m, (mdecl, pt, rt) in sorted(prog["methods"].items()):
        for c in sorted(below[mdecl]):
            if c == mdecl or rng.random() < 0.4:
                prog["bodies"][(c, m)] = body(c, pt, rt, rng.randint(1, nstmts))
    prog["bodies"][MAIN] = body(None, None, None, nstmts + 2)
    return prog


class _Stop(Exception):
    pass


def run(prog, rng, steps=300, depth=6, skip=0.25):
    """One concrete run from MAIN. Variables start as null. Each statement is
    skipped with probability skip, and each body runs once or twice, which
    stands for branches and loops. A call on null or a field access on null
    is skipped, as if the program caught the exception. Returns (edges,
    entered): the pairs (site, method id) that the run executed and the
    methods it entered."""
    heap = []
    edges, entered = set(), {MAIN}
    budget = [steps]

    def execute(mid, env, level):
        stmts = prog["bodies"][mid][1]
        for _ in range(rng.randint(1, 2)):
            for st in stmts:
                budget[0] -= 1
                if budget[0] < 0:
                    raise _Stop
                if rng.random() < skip:
                    continue
                kind = st[0]
                if kind == "new":
                    heap.append((st[2], {}))
                    env[st[1]] = len(heap) - 1
                elif kind == "copy":
                    env[st[1]] = env.get(st[2])
                elif kind == "load":
                    o = env.get(st[2])
                    if o is None:
                        continue
                    env[st[1]] = heap[o][1].get(st[3])
                elif kind == "store":
                    o = env.get(st[1])
                    if o is None:
                        continue
                    heap[o][1][st[2]] = env.get(st[3])
                else:
                    _, s, x, y, m, z = st
                    o = env.get(y)
                    if o is None:
                        continue
                    target = lookup(prog, heap[o][0], m)
                    edges.add((s, target))
                    entered.add(target)
                    result = None
                    if level < depth:
                        callee = {"this": o, "p": env.get(z) if z is not None else None}
                        execute(target, callee, level + 1)
                        result = callee.get("ret")
                    if x is not None:
                        env[x] = result

    try:
        execute(MAIN, {}, 0)
    except _Stop:
        pass
    return edges, entered


def _fixpoint(prog, targets):
    """The least (R, E) closed under: MAIN in R, and for each site s of a
    method of R and each T in targets(s, R), (s, T) in E and T in R."""
    reach, edges = {MAIN}, set()
    changed = True
    while changed:
        changed = False
        for mid in sorted(reach):
            for st in call_sites(prog, mid):
                for t in targets(mid, st, reach):
                    if (st[1], t) not in edges:
                        edges.add((st[1], t))
                        changed = True
                    if t not in reach:
                        reach.add(t)
                        changed = True
    return reach, edges


def cha_spec(prog):
    """Class hierarchy analysis by plain iteration."""

    def targets(mid, st, reach):
        decl = prog["bodies"][mid][0][st[3]]
        return {lookup(prog, c, st[4]) for c in prog["classes"] if is_sub(prog, c, decl)}

    return _fixpoint(prog, targets)


def rta_spec(prog):
    """Rapid type analysis by plain iteration."""

    def targets(mid, st, reach):
        made = {s[2] for r in reach for s in prog["bodies"][r][1] if s[0] == "new"}
        decl = prog["bodies"][mid][0][st[3]]
        return {lookup(prog, c, st[4]) for c in made if is_sub(prog, c, decl)}

    return _fixpoint(prog, targets)


def show(prog):
    """The program in a short text form, for messages of failed tests."""
    out = []
    for c, p in prog["classes"].items():
        out.append(f"class {c}" + (f" : {p}" if p else ""))
    for m, sig in prog["methods"].items():
        out.append(f"method {m} {sig}")
    for f, sig in prog["fields"].items():
        out.append(f"field {f} {sig}")
    for mid, (local, stmts) in prog["bodies"].items():
        out.append(f"{mid[0]}.{mid[1]} {local}")
        out.extend(f"  {st}" for st in stmts)
    return "\n".join(out)
variable_type_analysis.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-type-analysis/. The authors are listed in prov/5D67PN.jsonl.
"""Variable type analysis (VTA): prune a call graph with the classes that
reach each variable.

variable_type_analysis(prog, initial) takes a program of the oomodel form and
a sound initial call graph initial = (R0, E0), by default the one of rapid
type analysis. It builds the type propagation graph: one node per variable
of each method of R0 and one node per field name, with an edge for each
assignment and for each parameter and result passing along E0. It seeds the
nodes with the classes of the new statements, collapses the strongly
connected components, and propagates the classes in topological order. A
call y.m(z) keeps the edges of E0 to LOOKUP(C, m) for the classes C that
reach y. Returns (R, E), with R the methods reachable from the root along E.

graph_and_seeds and prune are shared with the plain iteration of the tests.
Cost: O((n + |E0|) * K) for a program of size n and K classes.
"""

from oomodel import MAIN, lookup, subclasses


def graph_and_seeds(prog: dict, initial: tuple) -> tuple[dict, dict]:
    """The type propagation graph as successor sets, and the seed classes."""
    reach0, edges0 = initial
    succ, seed = {}, {}

    def edge(a, b):
        succ.setdefault(a, set()).add(b)
        succ.setdefault(b, set())

    by_site = {}
    for s, t in edges0:
        by_site.setdefault(s, []).append(t)
    for mid in reach0:  # @line L1
        local, stmts = prog["bodies"][mid]
        for v in local:
            succ.setdefault((mid, v), set())
        for st in stmts:
            kind = st[0]
            if kind == "new":
                seed.setdefault((mid, st[1]), set()).add(st[2])  # @line L5
            elif kind == "copy":
                edge((mid, st[2]), (mid, st[1]))  # @line L2
            elif kind == "load":
                edge(("field", st[3]), (mid, st[1]))  # @line L3
            elif kind == "store":
                edge((mid, st[3]), ("field", st[2]))  # @line L3
            else:
                _, s, x, y, m, z = st
                for t in by_site.get(s, []):  # @line L4
                    edge((mid, y), (t, "this"))
                    if z is not None:
                        edge((mid, z), (t, "p"))
                    if x is not None:
                        edge((t, "ret"), (mid, x))
    return succ, seed


def prune(prog: dict, initial: tuple, types: dict) -> tuple[set, set]:
    """Keep the edges of E0 that some class reaching the receiver explains,
    then keep what is reachable from the root."""
    below = subclasses(prog)
    reach0, edges0 = initial
    sites = {}
    for mid in reach0:
        for st in prog["bodies"][mid][1]:
            if st[0] == "call":
                sites[st[1]] = (mid, st)
    keep = {}
    for s, t in edges0:  # @line L9
        mid, (_, _, _, y, m, _) = sites[s]
        mdecl = prog["methods"][m][0]
        if any(c in below[mdecl] and lookup(prog, c, m) == t for c in types.get((mid, y), ())):
            keep.setdefault(mid, set()).add((s, t))
    reach, stack, edges = {MAIN}, [MAIN], set()  # @line L10
    while stack:
        mid = stack.pop()
        for s, t in keep.get(mid, ()):
            edges.add((s, t))
            if t not in reach:
                reach.add(t)
                stack.append(t)
    return reach, edges


def components(succ: dict) -> list[list]:
    """Tarjan's strongly connected components, without recursion. The list
    comes in reverse topological order: sinks first."""
    index, low, on, stack, out = {}, {}, set(), [], []
    counter = 0
    for root in succ:
        if root in index:
            continue
        index[root] = low[root] = counter
        counter += 1
        stack.append(root)
        on.add(root)
        work = [(root, iter(succ[root]))]
        while work:
            v, it = work[-1]
            pushed = False
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter
                    counter += 1
                    stack.append(w)
                    on.add(w)
                    work.append((w, iter(succ[w])))
                    pushed = True
                    break
                if w in on:
                    low[v] = min(low[v], index[w])
            if pushed:
                continue
            work.pop()
            if work:
                u = work[-1][0]
                low[u] = min(low[u], low[v])
            if low[v] == index[v]:
                comp = []
                while True:
                    w = stack.pop()
                    on.discard(w)
                    comp.append(w)
                    if w == v:
                        break
                out.append(comp)
    return out


def variable_type_analysis(prog: dict, initial: tuple | None = None) -> tuple[set, set]:
    if initial is None:
        from oomodel import rta_spec

        initial = rta_spec(prog)
    succ, seed = graph_and_seeds(prog, initial)
    comps = components(succ)  # @line L6
    rep = {v: i for i, comp in enumerate(comps) for v in comp}
    ctypes = [set() for _ in comps]
    for v, cs in seed.items():
        ctypes[rep[v]] |= cs
    for i in range(len(comps) - 1, -1, -1):  # @line L7
        for v in comps[i]:
            for w in succ[v]:  # @line L8
                if rep[w] != i:
                    ctypes[rep[w]] |= ctypes[i]
    types = {v: ctypes[rep[v]] for v in succ}
    return prune(prog, initial, types)  # @line L11
test_variable_type_analysis.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variable-type-analysis/. The authors are listed in prov/5D67PN.jsonl.

import random

import oomodel
from oomodel import MAIN
from variable_type_analysis import components, graph_and_seeds, prune, variable_type_analysis


def plain_vta(prog, initial):
    """The same graph, solved by pushing classes along every edge until
    nothing changes."""
    succ, seed = graph_and_seeds(prog, initial)
    types = {v: set(seed.get(v, ())) for v in succ}
    changed = True
    while changed:
        changed = False
        for v in succ:
            for w in succ[v]:
                if not types[v] <= types[w]:
                    types[w] |= types[v]
                    changed = True
    return prune(prog, initial, types)


def programs(seed, count):
    rng = random.Random(seed)
    for _ in range(count):
        yield rng, oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)


def test_page_example():
    reach, edges = variable_type_analysis(oomodel.shapes())
    circle, square = ("Circle", "grow"), ("Square", "grow")
    assert reach == {MAIN, circle, square}
    assert edges == {("s1", circle), ("s2", square), ("s3", circle), ("s3", square)}


def test_page_example_from_cha_graph():
    prog = oomodel.shapes()
    assert variable_type_analysis(prog, oomodel.cha_spec(prog)) == variable_type_analysis(prog)


def test_class_flows_through_a_field():
    prog = {
        "classes": {"A": None, "B": "A", "H": None},
        "methods": {"m": ("A", "A", "A")},
        "fields": {"f": ("H", "A")},
        "bodies": {
            ("A", "m"): ({"this": "A", "p": "A", "ret": "A"}, []),
            ("B", "m"): ({"this": "B", "p": "A", "ret": "A"}, []),
            MAIN: (
                {"a": "A", "o": "A", "h": "H", "x": "A"},
                [
                    ("new", "a", "B"),
                    ("new", "o", "A"),
                    ("new", "h", "H"),
                    ("store", "h", "f", "a"),
                    ("load", "x", "h", "f"),
                    ("call", "s1", None, "x", "m", None),
                    ("call", "s2", None, "o", "m", None),
                ],
            ),
        },
    }
    reach, edges = variable_type_analysis(prog)
    assert edges == {("s1", ("B", "m")), ("s2", ("A", "m"))}
    assert len(oomodel.rta_spec(prog)[1]) == 4


def test_components_match_mutual_reachability():
    rng = random.Random(3)
    for _ in range(200):
        n = rng.randint(1, 12)
        succ = {v: {w for w in range(n) if rng.random() < 0.15} for v in range(n)}
        comps = components(succ)
        assert sorted(v for c in comps for v in c) == list(range(n))
        reach = {}
        for v in range(n):
            seen, stack = {v}, [v]
            while stack:
                for w in succ[stack.pop()]:
                    if w not in seen:
                        seen.add(w)
                        stack.append(w)
            reach[v] = seen
        where = {v: i for i, c in enumerate(comps) for v in c}
        for v in range(n):
            for w in range(n):
                assert (where[v] == where[w]) == (w in reach[v] and v in reach[w])
                if w in succ[v] and where[v] != where[w]:
                    assert where[w] < where[v]  # sinks come first


def test_same_as_plain_iteration():
    for _, prog in programs(2000, 400):
        initial = oomodel.rta_spec(prog)
        assert variable_type_analysis(prog, initial) == plain_vta(prog, initial), oomodel.show(prog)


def test_sound_against_concrete_runs():
    for rng, prog in programs(79, 300):
        reach, edges = variable_type_analysis(prog)
        for _ in range(5):
            seen_edges, entered = oomodel.run(prog, rng)
            assert seen_edges <= edges, oomodel.show(prog)
            assert entered <= reach


def test_nested_inside_rta_inside_cha():
    smaller = 0
    for _, prog in programs(7, 300):
        cha = oomodel.cha_spec(prog)
        rta = oomodel.rta_spec(prog)
        vta = variable_type_analysis(prog, rta)
        assert vta[0] <= rta[0] <= cha[0]
        assert vta[1] <= rta[1] <= cha[1]
        smaller += vta[1] != rta[1]
    assert smaller > 0


def test_monotone_in_the_initial_graph():
    for _, prog in programs(8, 300):
        from_rta = variable_type_analysis(prog, oomodel.rta_spec(prog))
        from_cha = variable_type_analysis(prog, oomodel.cha_spec(prog))
        assert from_rta[0] <= from_cha[0] and from_rta[1] <= from_cha[1]

History

Sundaresan, Hendren, Razafimahefa, Vallee-Rai, Lam, Gagnon and Godin introduced variable type analysis and declared type analysis in 2000, as part of the Soot framework for Java. They built the type propagation graph on a conservative initial call graph, collapsed its strongly connected components, and used the result to resolve virtual calls. In the same year, Tip and Palsberg described a family of propagation-based algorithms that keep fewer sets. Grove and Chambers (2001) placed such algorithms in a general framework of call graph construction.

References

  1. Vijay Sundaresan, Laurie Hendren, Chrislain Razafimahefa, Raja Vallee-Rai, Patrick Lam, Etienne Gagnon and Charles Godin, Practical virtual method call resolution for Java, Proceedings of OOPSLA 2000, 264 to 280, the type propagation graph, the collapse of strongly connected components, and the pruning of a conservative initial call graph
  2. Frank Tip and Jens Palsberg, Scalable propagation-based call graph construction algorithms, Proceedings of OOPSLA 2000, 281 to 293, the related propagation-based algorithms with one set of classes per method, per field or per class
  3. David Grove and Craig Chambers, A framework for call graph construction algorithms, ACM Transactions on Programming Languages and Systems 23(6), 685 to 746, 2001, the lattice of call graph algorithms and the place of flow-insensitive type propagation in it

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/5D67PN/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