Algorithmcore
Class hierarchy analysis
Also called CHA.
Build a call graph from declared types. A virtual call y.m() may reach the method m of every class at or below the declared class of y.
- Solves
- Call graph construction
- Time
- O(n + S K + K M) worst
- Space
- O(S K + K M) extra
- Where
- K = the number of classes; M = the number of method names; S = the number of call sites; n = the size of the program
- Model
- Word RAM
- Properties
- not context sensitivedeterministicnot flow sensitiveofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Jeffrey Dean, David Grove, Craig Chambers, 1995
Class hierarchy analysis (CHA) solves call graph construction for object-oriented programs from the class tree and the declared types alone. At a virtual call y.m(z), the object in y has a class at or below the declared class of y, so the call may reach the method that m dispatches to on any of those classes. The analysis starts at main, adds these targets as edges, and scans each newly reached method once. It runs in time close to linear in the size of the program, it is sound for any type-safe program without reflection, and it is the base that rapid type analysis and variable type analysis refine.
In plain words
When a program calls shape.area(), the variable shape is declared as a Shape. The language promises that the object in it is a Shape or an object of a class below Shape in the class tree. So the call can only run one of the area methods that those classes use. Class hierarchy analysis lists exactly those methods. It does this for each call in each method that main can reach, and it adds each new method it finds to a to-do list. When the list is empty, the result is a call graph. It never misses a real call, as long as the program does not use tricks such as reflection. It may list calls that never happen, because it does not ask which objects the program creates.
The problem
The input is a program in the model of the call graph construction page: a set of classes with single inheritance, where means that is or a class below it; for each method name the class that introduces it; method bodies with the statements x = new C(), x = y, x = y.f, y.f = z and the virtual call x = y.m(z) at a site ; a declared class for each variable; and the root main. The program is well typed: an assignment puts a value of class into a variable or field of declared class only if , and a call y.m(z) has .
is the method that runs when is called on an object of class : the definition of in or in the nearest class above that defines it. The CHA targets of a site : x = y.m(z) are
The output is the least pair such that , and for each site in a method of and each , and .
| item | value |
|---|---|
| direction | none: flow-insensitive, one answer for the whole program |
| may or must | may |
| domain | pairs of reachable methods and call edges |
| order | inclusion of both parts (bottom is precise) |
| join | union of both parts |
| bottom and top | and all methods with all edges |
| boundary value | |
| initial value | , |
| transfer | the closure rule above; monotone, and distributive since does not depend on |
The algorithm
CHA(P)- 1
R <- {main}; W <- [main]; E <- {} - 2
while W is not empty do - 3
take a method M from W - 4
for each call site s: x = y.m(z) in M do - 5
for each class C with C <= decl(y) do - 6
T <- LOOKUP(C, m) - 7
add (s, T) to E - 8
if T is not in R then add T to R and to W - 9
return (R, E) LOOKUP(C, m)- 10
while C does not define m do C <- parent(C) - 11
return the method m of C
Each method enters once, when it first enters (line L8), so each body is scanned once. Line L5 needs the set of classes below each class. The implementation builds it once, together with a table of for every class below , so lines L5 and L6 cost per class. The loop of line L10 always stops, because and defines .
Example
The program of the call graph construction page:
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
}
The classes at or below Shape are Shape, Circle, Square and Oval. walks up to Circle.grow. So for all three sites, since all three receivers are declared as Shape.
| step | method taken | what happens | after the step |
|---|---|---|---|
| 1 | main | s1, s2 and s3 each get the 3 edges; the 3 grow methods enter |
Shape.grow, Circle.grow, Square.grow |
| 2 | Square.grow | no call sites | Shape.grow, Circle.grow |
| 3 | Circle.grow | no call sites | Shape.grow |
| 4 | Shape.grow | no call sites | empty |
The result has 4 reachable methods and 9 edges. The only run makes 3 calls: s1 to Circle.grow, and s2 and s3 to Square.grow. Shape.grow is in although no code creates a Shape. Rapid type analysis removes it.
Correctness
Soundness. In a well-typed program without reflection, native callbacks or classes loaded at run time, every method that a run enters is in , and every call that a run makes is in . The key fact is type safety: at every moment of a run, each variable and field of declared class holds null or an object of a class . So when site : x = y.m(z) runs in a method of , the receiver has a class , and the method that runs is . By induction over the calls of the run, the caller is in , so the edge is in and the callee is in .
Least solution. The algorithm adds only edges that the closure rule forces, and when is empty, every method of has been scanned, so the rule holds. So the result is the least closed pair. The full proof is in the proof file.
Proof: Class hierarchy analysis computes the least closed call graph, and it is sound for well-typed programsfull
Setting. The program has a finite set of classes with a parent function; means that is or below it. Each method name has a class that defines it, and is the definition of in the nearest class at or above that has one. Each variable of a method body has a declared class . A call site : x = y.m(z) has the target set . A pair is closed if and, for every site in a method of and every , and .
The program is well typed: x = new C() has ; x = y has ; a load x = y.f and a store y.f = z have for the class that declares , for the load and for the store; a call x = y.m(z) has , and ; in the body of the definition of in class , , and . The program has no reflection, no native code that calls back and no classes loaded at run time: every call of a run is the execution of a call site of the text.
Lemma 1 (LOOKUP stops). For a site y.m(z) and , the loop of line L10 stops at a class that defines .
Proof. , so is on the path from to the root, and it defines . The loop stops at the first class on this path that defines , at the latest at .
Lemma 2 (termination and the invariant). The loop of line L2 runs at most times, where is the set of methods. At each test of line L2: (a) every method is in at most once, and ; (b) for every method , every site of and every , and .
Proof. A method enters only in line L1 or line L8, and line L8 adds it to at the same time, only if it was not in . Methods never leave . So each method enters at most once, and the loop runs at most times. This gives (a). For (b): at the start, . A method leaves in line L3, and lines L4 to L8 add to and to for every site of and every , by Lemma 1. Sets only grow, so (b) stays true for the methods that left before.
Lemma 3 (every fact is forced). Let be any closed pair. At all times, and .
Proof. At the start, and . Line L7 adds for a site of a method taken from and a , so and because is closed. Line L8 adds the same to .
Theorem 1 (least closed pair). The algorithm stops and returns the least closed pair.
Proof. It stops by Lemma 2. At the end is empty, so by Lemma 2(b) the pair is closed. By Lemma 3 it is inside every closed pair. The intersection of all closed pairs is closed (each rule instance holds in each of them), so a least closed pair exists, and is it.
Lemma 4 (type safety). In every run of a well-typed program, at every moment, every variable of a live frame holds null or an object of a class , and every field of every object holds null or an object of a class .
Proof. By induction over the steps of the run. At the start, all variables and fields hold null. x = new C() stores an object of class . x = y stores the value of , of a class . A load stores a field value, of a class . A store puts a value of class in a field. A call x = y.m(z) on a receiver of class runs the body of , defined in a class with ; it binds this to the receiver, of class , and p to a value of class at most . The return stores the value of ret, of a class at most , in .
Theorem 2 (soundness). In every run, every method that the run enters is in , and for every execution of a site that enters a method , .
Proof. By induction over the calls of the run, in the order in which they happen. The run starts in . Take a call at site : x = y.m(z) in a frame of method . That frame was entered earlier, so by the induction hypothesis. The receiver is an object of a class by Lemma 4 (a null receiver makes no call). The method that runs is . Since is closed by Theorem 1, and .
Theorem 3 (cost). With a dispatch table and the sets of classes below each class built first, the algorithm takes time after the table, where is the size of the program, the number of sites and the number of classes. The table takes time for method names when it is filled from the root down.
Proof. By Lemma 2, each method is taken from once, so lines L3 and L4 read each body once, in in total. For each site, line L5 visits at most classes, and lines L6 to L8 take each with the table and with hashing or direct indexing for and . That is . The table: for each name , visit the classes below from the top; the entry of a class is its own definition of if it has one, and else the entry of its parent. Each of the at most entries takes . The sets of classes below each class have elements in total for a tree of height , and the program reads one of them per site.
Complexity
Proved. Let be the height of the class tree. The table of LOOKUP has at most entries. Filled top-down, each entry copies the entry of the parent or takes the class's own method, so it takes time; the implementation calls LOOKUP for each entry, which takes . Each method is scanned once, which costs over the program. Each call site loops over at most classes with work each, which costs . So the time is , with hash sets for and (in expectation) or arrays indexed by method and site (worst case). The space is for the table and for the edges.
Measured, not proved. On 500 random well-typed programs with up to 7 classes, the result equals that of a plain round-robin iteration of the closure rule. On 300 random programs with 5 concrete runs each (seed 77), every call that a run makes is in .
Properties
- Sound under type safety. The proof uses only the declared types. A language with unchecked casts, such as C++ with
static_caston a wrong type, breaks it. - Independent of the values. depends on the text of the site, not on what the program creates or assigns. So the transfer is distributive, and the answer for a site does not change when other code changes, as long as the class tree is the same.
- Least precise of the classic three. For every program, the call graph of rapid type analysis and that of variable type analysis are subsets of the CHA graph. The proofs are on their pages.
- Single target. If has one method, the call can become a direct call (devirtualization) with no run-time test.
Variants and improvements
- Name-based resolution. Keep every method called , whatever the class. This needs no class tree and is weaker than CHA.
- Rapid type analysis. Keep only the classes that some reachable method creates (rapid type analysis).
- Type propagation. Track the classes that reach each variable (variable type analysis), or the abstract objects of a points-to analysis.
- Interfaces and multiple inheritance. For a Java interface, the classes below it are the classes that implement it and their subclasses. For C++ with multiple inheritance, LOOKUP must search several paths and report an ambiguity.
- Specialization. A compiler can make a copy of a method for a group of receiver classes. Inside the copy,
thishas a smaller set of classes below it, so more calls onthishave one CHA target. - Guarded inlining in a JIT. A just-in-time compiler can use CHA on the classes loaded so far, inline the single target, and record a dependency. When a new subclass is loaded, it throws the code away. See inline caching for the run-time alternative.
When to use it
Use CHA when you need a sound call graph fast, for example as the first step of a whole-program optimizer, as the initial graph of variable type analysis, or in a tool that must answer at once. It needs no fixed point over values and scales to any program size. When the program creates few of the classes in its hierarchy, as with large libraries, use rapid type analysis, which costs almost the same. When the call graph feeds a precise analysis, such as an alias analysis, use a points-to based graph.
Pitfalls
- Missing inherited methods. A version that, in line L5, loops only over the classes that define
mmisses calls of a method inherited from above . WithOval oand a callo.grow(), no class at or belowOvaldefinesgrow, but the call runsCircle.grow. Line L5 must loop over all classes below , and line L6 must walk up. - Scanning unreachable code. Taking every method of the program as a root, instead of
mainin line L1, makes a sound graph with more edges. That is right for a library, whose public methods are all roots, and wrong for a whole program. - Claiming soundness with reflection. A call through
Method.invokeor a class loaded by name is not a call site of the text. The result of line L9 does not cover it. Treat such programs as unsound for CHA, or add the reflective targets by hand. - An open hierarchy. If code that the analysis did not see can add subclasses, the set in line L5 is not complete. A compiler that devirtualizes on CHA must then guard the call or recompile when a class is loaded.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/class-hierarchy-analysis/. The authors are listed in prov/M6WV8Z.jsonl.
"""Class hierarchy analysis (CHA): a call graph from declared types.
class_hierarchy_analysis(prog) takes a program of the oomodel form and
returns (R, E): the methods reachable from the root, and the call edges as
pairs (site, method id). A virtual call y.m(z) may call LOOKUP(C, m) for
every class C at or below the declared class of y. The worklist holds the
methods that are reachable but not yet scanned.
Precondition: the program is well typed, so a variable of declared class D
only holds objects of a class C <= D. Cost: O(K * M) for the dispatch table
of K classes and M method names, plus O(n + S * K) for a program of size n
with S call sites.
"""
from oomodel import MAIN, call_sites, lookup, subclasses
def class_hierarchy_analysis(prog: dict) -> tuple[set, set]:
below = subclasses(prog)
table = {} # (C, m) -> LOOKUP(C, m), built once
for m, (mdecl, _, _) in prog["methods"].items():
for c in below[mdecl]:
table[(c, m)] = lookup(prog, c, m) # @line L10 @line L11
reach, work, edges = {MAIN}, [MAIN], set() # @line L1
while work: # @line L2
mid = work.pop() # @line L3
local = prog["bodies"][mid][0]
for _, s, _, y, m, _ in call_sites(prog, mid): # @line L4
for c in below[local[y]]: # @line L5
t = table[(c, m)] # @line L6
edges.add((s, t)) # @line L7
if t not in reach: # @line L8
reach.add(t)
work.append(t)
return reach, edges # @line L9
oomodel.py 305 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/.
"""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)
test_class_hierarchy_analysis.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/class-hierarchy-analysis/. The authors are listed in prov/M6WV8Z.jsonl.
import random
import oomodel
from class_hierarchy_analysis import class_hierarchy_analysis
from oomodel import MAIN
def test_page_example():
reach, edges = class_hierarchy_analysis(oomodel.shapes())
grows = {("Shape", "grow"), ("Circle", "grow"), ("Square", "grow")}
assert reach == {MAIN} | grows
assert edges == {(s, t) for s in ("s1", "s2", "s3") for t in grows}
def test_lookup_walks_up_the_tree():
prog = oomodel.shapes()
assert oomodel.lookup(prog, "Oval", "grow") == ("Circle", "grow")
assert oomodel.lookup(prog, "Square", "grow") == ("Square", "grow")
def test_no_calls():
prog = {
"classes": {"A": None},
"methods": {},
"fields": {},
"bodies": {MAIN: ({"x": "A"}, [("new", "x", "A")])},
}
assert class_hierarchy_analysis(prog) == ({MAIN}, set())
def test_declared_type_limits_the_targets():
# A receiver declared as Square cannot reach Circle.grow or Shape.grow.
prog = oomodel.shapes()
local, stmts = prog["bodies"][MAIN]
local = dict(local, q="Square")
prog["bodies"][MAIN] = (local, [("new", "q", "Square"), ("call", "s9", None, "q", "grow", None)])
reach, edges = class_hierarchy_analysis(prog)
assert edges == {("s9", ("Square", "grow"))}
assert reach == {MAIN, ("Square", "grow")}
def test_unreachable_method_adds_no_edges():
# The call in Shape.grow is never scanned when no site reaches Shape.grow.
prog = oomodel.shapes()
local, _ = prog["bodies"][MAIN]
prog["bodies"][MAIN] = (local, [])
prog["bodies"][("Shape", "grow")][1].append(("call", "s7", None, "this", "grow", None))
assert class_hierarchy_analysis(prog) == ({MAIN}, set())
def test_same_as_plain_iteration():
rng = random.Random(1995)
for _ in range(500):
prog = oomodel.random_program(rng, rng.randint(1, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
assert class_hierarchy_analysis(prog) == oomodel.cha_spec(prog), oomodel.show(prog)
def test_sound_against_concrete_runs():
rng = random.Random(77)
for _ in range(300):
prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
reach, edges = class_hierarchy_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_contains_rapid_type_analysis():
rng = random.Random(5)
for _ in range(300):
prog = oomodel.random_program(rng, rng.randint(2, 7), rng.randint(1, 4), rng.randint(0, 2), 8)
reach, edges = class_hierarchy_analysis(prog)
rta_reach, rta_edges = oomodel.rta_spec(prog)
assert rta_reach <= reach and rta_edges <= edges
History
Dean, Grove and Chambers described class hierarchy analysis in 1995, in their work on optimizing compilers for object-oriented languages, and used it to replace message sends with direct calls. Bacon and Sweeney (1996) measured it on C++ programs and showed that rapid type analysis removes many more virtual calls at almost the same cost. Grove, DeFouw, Dean and Chambers (1997), and Grove and Chambers (2001), placed CHA at the bottom of a lattice of call graph algorithms and measured the whole family on Cecil and Java programs. Sundaresan and others (2000) used CHA as the conservative initial call graph of the Soot framework for Java, on which variable type analysis builds.
References
- Jeffrey Dean, David Grove and Craig Chambers, Optimization of object-oriented programs using static class hierarchy analysis, ECOOP '95, LNCS 952, 77 to 101, 1995, the definition of class hierarchy analysis and its use to bind message sends statically
- David F. Bacon and Peter F. Sweeney, Fast static analysis of C++ virtual function calls, Proceedings of OOPSLA '96, 324 to 341, 1996, class hierarchy analysis for C++ and its measured comparison with rapid type analysis
- 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, class hierarchy analysis as the cheapest point of the framework, and its measured precision
- 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, class hierarchy analysis as the conservative initial call graph of the Soot framework
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M6WV8Z Edit this page History Report an error Markdown