Algorithm Search⌘K

Data structureadvanced

Polymorphic inline cache

An inline cache that holds several receiver types and their targets at a call site, and records the types seen for later optimization.

Time
O(k) hitO(S k h) invalidateO(k + h) miss
Space
O(S k) extra
Where
S = the number of send sites; h = the length of the longest chain of parent classes; k = the bound on the number of entries of one cache

A polymorphic inline cache (PIC) is the cache of one send site in a dynamically typed language. It holds a short list of pairs, each a receiver class and the method that a full lookup found for it, up to a fixed bound. A send compares the class of the receiver with the cached classes in turn and calls the method of the first match. On a miss it does the full lookup and adds a pair. When a site has seen more classes than the bound, the cache marks it megamorphic and from then on uses a slower general lookup. Hölzle, Chambers and Ungar introduced PICs in SELF in 1991. They fix the weak point of the one-entry inline cache, which misses on every change of class at a site that sees two or more classes. They also have a second use: the list of classes is a record of the receiver types that the site has seen, which an optimizing compiler reads as type feedback.

In plain words

A call such as shape.draw() must find the right draw for the kind of object in shape. A one-entry cache remembers only the last kind. If the kinds alternate, circle, square, circle, square, the cache is wrong every time.

A polymorphic inline cache remembers a few kinds, for example up to four, each with its method. On each call it checks the list, and if the kind is there it calls the method at once. If not, it does the slow search and adds the new kind to the list. If a call place sees too many kinds, the list is no help, so the cache stops trying and always does a general search. The list has one more use: it tells the optimizing compiler which kinds really occur at that place.

The abstract type

A runtime has classes, each with a method table and an optional parent, and a set of send sites. Each site has a selector ss and a bound k≥1k \ge 1. LOOKUP(K,s)\mathrm{LOOKUP}(K, s) is the full lookup: the method of the first class in the chain K,parent(K),…K, \mathit{parent}(K), \dots that defines ss, or a "not understood" marker.

  • SEND(site, KK). The method that a send of ss to a receiver of class KK runs. It must equal LOOKUP(K,s)\mathrm{LOOKUP}(K, s) under the current classes.
  • SETMETHOD(DD, ss), REMOVEMETHOD(DD, ss), SETPARENT(DD, PP). Change a class at run time.
  • STATE(site). One of uninitialized, monomorphic, polymorphic and megamorphic.
  • TYPES(site). The classes in the cache, in the order in which they were added.

Representation

Each site holds:

  • entries\mathit{entries}: a list of at most kk pairs (Ki,mi)(K_i, m_i) with distinct classes KiK_i;
  • mega\mathit{mega}: a flag, true when the site is megamorphic, and then entries\mathit{entries} is empty;
  • counters of hits and misses, for the profiler.

The state is a function of these fields, not a separate variable:

mega\mathit{mega} number of entries state
false 0 uninitialized
false 1 monomorphic
false 2 to kk polymorphic
true 0 megamorphic

The runtime holds the list of all sites and a global lookup cache, a hash table from (class, selector) to method, which only megamorphic sites use.

In SELF the entries are not a list in memory but machine code: a stub that the call instruction of the site jumps to, which compares the class of the receiver with each KiK_i and jumps to mim_i on a match. On a miss the stub calls the lookup routine, which writes a new stub with one more case and points the call instruction at it. The list form here has the same behaviour.

Operations

SEND(site, K)
L1  if site.mega then return GLOBALLOOKUP(K, s)
L2  for each (Ki, mi) in site.entries, in order
L3      if Ki = K then return mi                      ▷ hit
L4  m ← LOOKUP(K, s)                                  ▷ miss
L5  if |site.entries| < k then append (K, m) to site.entries
L6  else site.entries ← empty; site.mega ← true
L7  return m

GLOBALLOOKUP(K, s)
L8  if (K, s) is not in the global cache then global[(K, s)] ← LOOKUP(K, s)
L9  return global[(K, s)]

CHANGED(D)                                            ▷ called before D changes
L10 empty the global cache
L11 for each site: remove from site.entries each (Ki, mi) such that D is in the chain of Ki

SETMETHOD, REMOVEMETHOD and SETPARENT call CHANGED(DD) and then change DD. SETPARENT first refuses a parent that would make a cycle, that is, a PP whose chain holds DD. CHANGED does not reset the megamorphic flag: a megamorphic site is correct in every state of the classes, so there is no need to.

From these operations the state of a site moves only along these transitions:

from event to
uninitialized miss monomorphic
monomorphic miss, k≥2k \ge 2 polymorphic
polymorphic with j<kj < k entries miss polymorphic with j+1j + 1 entries
any state with kk entries miss megamorphic
any state that is not megamorphic CHANGED the same or a state with fewer entries
any state hit the same
megamorphic anything megamorphic

Example

Take five classes. Object defines print and hash. Point, child of Object, defines x and print. ColorPoint, child of Point, defines color. Circle, child of Object, defines print and area. Square, child of Object, defines area. One site sends print with bound k=3k = 3.

send receiver class result method run state after entries after
1 Point miss Point.print monomorphic Point
2 Circle miss Circle.print polymorphic Point, Circle
3 Point hit, 1 test Point.print polymorphic Point, Circle
4 ColorPoint miss Point.print polymorphic Point, Circle, ColorPoint
5 Circle hit, 2 tests Circle.print polymorphic same
6 Square miss Object.print megamorphic none
7 Point global cache Point.print megamorphic none

Send 6 finds three entries, the bound, so the site turns megamorphic. Send 7 would have been a hit before, but now it goes to the global cache, whose first look-up of (Point, print) is a full lookup.

Now take the same site after send 4, with entries Point, Circle and ColorPoint, and add a method print to ColorPoint. CHANGED(ColorPoint) removes only the entry for ColorPoint, because the chains of Point (Point, Object) and of Circle (Circle, Object) do not hold ColorPoint. The next send to a ColorPoint misses and adds (ColorPoint, ColorPoint.print). If the program then adds a method print to Point, the entry for Point goes, and the entry for ColorPoint goes too, because Point is in the chain of ColorPoint. Only Circle is left, and the site is monomorphic again. The implementation's tests replay both runs.

Simple cases: a site that never runs stays uninitialized. With k=1k = 1 the PIC is the one-entry inline cache plus a megamorphic state, and the states go uninitialized, monomorphic, megamorphic. A site that sees exactly j≤kj \le k classes, each several times, without changes to the classes, ends with jj entries after jj misses.

Correctness

The full proof is in the proof file. It rests on one invariant and one fact about lookups.

  • Invariant. At each site, the classes in the entries are distinct, there are at most kk of them, and each pair satisfies mi=LOOKUP(Ki,s)m_i = \mathrm{LOOKUP}(K_i, s) under the current classes. Each pair in the global cache satisfies the same equation.
  • Locality of lookup. LOOKUP(K,s)\mathrm{LOOKUP}(K, s) reads only the parent links and method tables of the classes in the chain of KK. So if a class DD is not in the chain of KK, a change of DD does not change the chain of KK or the result of the lookup.

A hit at line L3 returns mi=LOOKUP(Ki,s)=LOOKUP(K,s)m_i = \mathrm{LOOKUP}(K_i, s) = \mathrm{LOOKUP}(K, s), because the guard Ki=KK_i = K holds. A miss returns LOOKUP(K,s)\mathrm{LOOKUP}(K, s) directly, and the pair it adds satisfies the invariant. It is added only if KK is not in the list yet, since the loop found no match. A megamorphic send returns a global cache entry, which is right by the invariant. Line L10 empties the global cache, and line L11 removes exactly the entries whose result can change, by locality. So every send returns the result of the full lookup, in every state, for every sequence of sends and changes. The transitions in the table above follow from lines L5 and L6 and from the fact that CHANGED only removes entries.

Proof: A polymorphic inline cache returns the result of the full lookupfull

We use the operations SEND, GLOBALLOOKUP and CHANGED with lines L1 to L11 from the page. A class state is the set of classes with their parent links and method tables. The parent links have no cycle: SETPARENT refuses a parent PP whose chain holds DD, and a new class gets an existing class as parent, so following parent links from any class ends after finitely many steps. The chain of KK is the list K,parent(K),…K, \mathit{parent}(K), \dots up to a class with no parent. LOOKUP(K,s)\mathrm{LOOKUP}(K, s) returns the method table entry for ss of the first class in the chain of KK that defines ss, or the marker "not understood" if none does. We write LOOKUPΣ\mathrm{LOOKUP}_\Sigma when we need to name the class state Σ\Sigma.

A run is a sequence of steps. Each step is a SEND at some site, or a change SETMETHOD, REMOVEMETHOD or SETPARENT of one class DD, which first calls CHANGED(DD) and then changes DD.

Invariant II. In the current class state Σ\Sigma:

  1. at each site with selector ss and bound kk, the classes KiK_i in entries\mathit{entries} are distinct, ∣entries∣≤k|\mathit{entries}| \le k, and mi=LOOKUPΣ(Ki,s)m_i = \mathrm{LOOKUP}_\Sigma(K_i, s) for each pair;
  2. if mega\mathit{mega} is true, then entries\mathit{entries} is empty;
  3. each pair ((K,s),m)((K, s), m) in the global cache satisfies m=LOOKUPΣ(K,s)m = \mathrm{LOOKUP}_\Sigma(K, s).

Initially every site is empty with mega\mathit{mega} false, and the global cache is empty, so II holds.

Lemma 1 (locality). Let Σ\Sigma and Σ′\Sigma' differ only in the parent link and the method table of one class DD. If DD is not in the chain of KK in Σ\Sigma, then the chain of KK is the same in Σ\Sigma and Σ′\Sigma', and LOOKUPΣ(K,s)=LOOKUPΣ′(K,s)\mathrm{LOOKUP}_\Sigma(K, s) = \mathrm{LOOKUP}_{\Sigma'}(K, s) for every selector ss.

Proof. Let the chain of KK in Σ\Sigma be C0=K,C1,…,CtC_0 = K, C_1, \dots, C_t, where CtC_t has no parent. By induction on ii, the chain in Σ′\Sigma' starts with C0,…,CiC_0, \dots, C_i: for i=0i = 0 both start with KK; and if both start with C0,…,CiC_0, \dots, C_i with i<ti < t, then Ci≠DC_i \ne D, so parent(Ci)\mathit{parent}(C_i) is the same in both states, and it is Ci+1C_{i+1}. Also Ct≠DC_t \ne D, so CtC_t has no parent in Σ′\Sigma' either. So the chains are equal. LOOKUP reads only the method tables of C0,…,CtC_0, \dots, C_t, which are equal in the two states because none of them is DD. So the results are equal. □\square

Lemma 2 (send). If II holds before SEND(site, KK) in class state Σ\Sigma, then the send returns LOOKUPΣ(K,s)\mathrm{LOOKUP}_\Sigma(K, s), and II holds after it.

Proof. SEND does not change the class state. There are three cases.

Megamorphic (line L1). GLOBALLOOKUP returns the cached method for (K,s)(K, s) if there is one, which equals LOOKUPΣ(K,s)\mathrm{LOOKUP}_\Sigma(K, s) by part 3 of II. Otherwise line L8 stores LOOKUPΣ(K,s)\mathrm{LOOKUP}_\Sigma(K, s) and line L9 returns it, and the new pair satisfies part 3. Parts 1 and 2 are unchanged.

Hit (line L3). The loop returns mim_i for the first ii with Ki=KK_i = K. By part 1, mi=LOOKUPΣ(Ki,s)=LOOKUPΣ(K,s)m_i = \mathrm{LOOKUP}_\Sigma(K_i, s) = \mathrm{LOOKUP}_\Sigma(K, s). Nothing changes.

Miss (lines L4 to L7). The loop found no ii with Ki=KK_i = K, so KK is not among the cached classes. Line L4 computes m=LOOKUPΣ(K,s)m = \mathrm{LOOKUP}_\Sigma(K, s) and line L7 returns it. If ∣entries∣<k|\mathit{entries}| < k, line L5 appends (K,m)(K, m): the classes stay distinct because KK was not in the list, the length is at most kk, and the new pair satisfies the equation. Otherwise line L6 empties the list and sets mega\mathit{mega}, which satisfies parts 1 and 2. Part 3 is unchanged. □\square

Lemma 3 (change). If II holds in class state Σ\Sigma, and a step changes the class DD to give Σ′\Sigma', then II holds in Σ′\Sigma' after the step.

Proof. The step runs CHANGED(DD) in Σ\Sigma and then changes DD. Line L10 empties the global cache, so part 3 holds in Σ′\Sigma'. Line L11 only removes pairs and does not touch mega\mathit{mega}, so the classes stay distinct, the length stays at most kk, and part 2 still holds. Take a pair (Ki,mi)(K_i, m_i) that is still in a list. Line L11 kept it, so DD is not in the chain of KiK_i in Σ\Sigma. By part 1 in Σ\Sigma, mi=LOOKUPΣ(Ki,s)m_i = \mathrm{LOOKUP}_\Sigma(K_i, s), and by Lemma 1 this equals LOOKUPΣ′(Ki,s)\mathrm{LOOKUP}_{\Sigma'}(K_i, s). So part 1 holds in Σ′\Sigma'. □\square

Theorem 1 (correctness). In every run, every SEND(site, KK) returns LOOKUP(K,s)\mathrm{LOOKUP}(K, s) in the class state at the time of the send.

Proof. By induction on the steps of the run, II holds before each step: it holds at the start, Lemma 2 keeps it over a send, and Lemma 3 keeps it over a change. Lemma 2 then gives the result of each send. □\square

Theorem 2 (state machine). Let the state of a site be uninitialized, monomorphic or polymorphic when mega\mathit{mega} is false and the list has 0, 1, or at least 2 entries, and megamorphic when mega\mathit{mega} is true. Then in every run:

  1. a hit and every step at another site leave the state and the entries of the site unchanged, except that a change of a class can remove entries;
  2. a miss at a site that is not megamorphic with j<kj < k entries leads to j+1j + 1 entries, and a miss with j=kj = k entries leads to the megamorphic state;
  3. a change of a class leaves mega\mathit{mega} unchanged and does not add entries;
  4. once megamorphic, a site stays megamorphic.

In particular, in a run without changes, the states that a site goes through are a prefix of uninitialized, monomorphic, polymorphic, megamorphic, with polymorphic left out when k=1k = 1. If the site sees exactly jj distinct classes and j≤kj \le k, it ends with jj entries after exactly jj misses. If it sees more than kk distinct classes, it ends megamorphic.

Proof. Parts 1 to 4 are read off lines L1 to L11: only lines L5 and L6 add entries or set mega\mathit{mega}, only line L11 removes entries, and no line clears mega\mathit{mega}. Without changes, the number of entries starts at 0, grows by 1 at each miss while it is below kk, and the site turns megamorphic at the first miss with kk entries, so the sequence of states is as stated. With k=1k = 1 the count goes from 1 directly to the megamorphic state. If the site sees exactly j≤kj \le k distinct classes, the first send of each class misses, because by part 1 of II the list holds only classes seen before, and every later send of it hits, because the class was added and nothing removes it. So there are jj misses and jj entries. If it sees more than kk distinct classes and is not megamorphic before the first send of the (k+1)(k+1)-th class, then the list holds the kk earlier classes, and that send misses with kk entries and makes the site megamorphic. □\square

Complexity

A hit costs one comparison per entry up to the match, so O(k)O(k), and O(1)O(1) for the first entry. A miss costs the kk comparisons plus a full lookup, which visits at most hh classes, each with a hash-table look-up of expected O(1)O(1) time, so O(k+h)O(k + h) expected. A megamorphic send costs one global hash-table look-up, plus a full lookup the first time a pair is seen. CHANGED walks all sites and, for each entry, the chain of its class, so it costs O(Skh)O(S k h). That is acceptable because classes change rarely, and a system can trade precision for speed by emptying every site with the selector.

A site uses O(k)O(k) space. Bounds in practice are small: SELF marked a site megamorphic after more than 10 cases (Hölzle 1994, Section 3.5.1), and JavaScript engines use a bound of a few entries.

Variants

  • Order of the tests. The list keeps the order of first use. A system can move the most frequent class to the front, or sort by the counts that the stub keeps. SELF tried a move-to-front scheme and dropped it (Hölzle 1994, Section 3.5.1).
  • What happens at the bound. The variant here switches to a global cache and stays megamorphic. SELF instead kept the stub and replaced a random case. Some systems clear the cache and start again from uninitialized.
  • Keys. The key can be a class, a SELF map, or a hidden class, and the stored answer can be a field offset instead of a method, as in property-access caches of JavaScript engines.
  • Caches in an interpreter. A bytecode interpreter can keep the entries next to the send instruction instead of in a stub of machine code.
  • Counts for type feedback. Each entry can count its hits, so that the compiler knows not only which classes occur but how often. The optimizing compiler of SELF-93 inlines the frequent cases behind type tests and keeps a dynamic send for the rest, which is type feedback.

When to use it

Use a PIC at send sites of a language with dynamic dispatch, when most sites see one class and a minority see a few, which is what Hölzle measured in SELF programs. Use it together with a profiler, because the PICs are a cheap source of type information for an optimizing compiler. If class hierarchy analysis proves that a site has one possible target, a direct call is better, and if the language has a static type for the receiver, a virtual method table gives dispatch in constant time without a cache.

Pitfalls

  • Testing a superclass. Each entry must test the exact class. A test "is a subclass of KiK_i" returns the wrong method when a subclass overrides it.
  • Forgetting invalidation. Without CHANGED, a site keeps calling an old method after the program redefines it. The removal must use the chain as it was before the change, so CHANGED runs before the change.
  • Resetting the megamorphic flag on every change. It is not wrong, but a site that is truly megamorphic then climbs the states again and pays for several misses each time.
  • A bound that is too large. A long chain of tests can be slower than a global hash-table look-up, and a large stub uses code memory.
  • Reading the types as complete. TYPES(site) holds only the classes seen so far, and is empty after a megamorphic switch. A compiler that inlines from it must keep a fallback send for other classes.

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.

polymorphic_inline_cache.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polymorphic-inline-cache/. The authors are listed in prov/WAS1H3.jsonl.

"""A small class-based object model with polymorphic inline caches.

Classes have a method table and an optional parent. A full lookup walks the
chain of parents. Each send site has a polymorphic inline cache (PIC) with the
states uninitialized, monomorphic, polymorphic and megamorphic. The runtime
keeps a list of all sites and empties the stale entries when a method table or
a parent link changes.
"""

from __future__ import annotations

from dataclasses import dataclass, field

UNINITIALIZED = "uninitialized"
MONOMORPHIC = "monomorphic"
POLYMORPHIC = "polymorphic"
MEGAMORPHIC = "megamorphic"

NOT_UNDERSTOOD = ("not understood",)


@dataclass(frozen=True)
class Method:
    """A method body. The id makes two definitions with the same name differ."""

    owner: str
    selector: str
    ident: int


@dataclass(eq=False)
class Klass:
    name: str
    parent: Klass | None = None
    methods: dict[str, Method] = field(default_factory=dict)

    def chain(self) -> list[Klass]:
        out: list[Klass] = []
        k: Klass | None = self
        while k is not None:
            out.append(k)
            k = k.parent
        return out


class Runtime:
    """Classes, the send sites, and the global lookup cache used by megamorphic sites."""

    def __init__(self) -> None:
        self.classes: dict[str, Klass] = {}
        self.sites: list[PIC] = []
        self.global_cache: dict[tuple[int, str], Method | tuple[str]] = {}
        self.full_lookups = 0
        self._next_ident = 0

    def define_class(self, name: str, parent: str | None = None) -> Klass:
        if name in self.classes:
            raise ValueError("class already defined: " + name)
        k = Klass(name, self.classes[parent] if parent is not None else None)
        self.classes[name] = k
        return k

    def lookup(self, k: Klass, selector: str) -> Method | tuple[str]:
        """The full lookup: the first class in the chain of k that defines selector."""
        self.full_lookups += 1
        for d in k.chain():
            m = d.methods.get(selector)
            if m is not None:
                return m
        return NOT_UNDERSTOOD

    def global_lookup(self, k: Klass, selector: str) -> Method | tuple[str]:
        key = (id(k), selector)
        m = self.global_cache.get(key)
        if m is None:
            m = self.lookup(k, selector)
            self.global_cache[key] = m
        return m

    def _changed(self, d: Klass) -> None:
        """Called before a change of d. Empties every entry whose class has d in its chain."""
        self.global_cache.clear()
        for site in self.sites:
            site.invalidate(d)

    def set_method(self, cls: str, selector: str) -> Method:
        d = self.classes[cls]
        self._changed(d)
        self._next_ident += 1
        m = Method(cls, selector, self._next_ident)
        d.methods[selector] = m
        return m

    def remove_method(self, cls: str, selector: str) -> None:
        d = self.classes[cls]
        if selector in d.methods:
            self._changed(d)
            del d.methods[selector]

    def set_parent(self, cls: str, parent: str | None) -> None:
        d = self.classes[cls]
        p = self.classes[parent] if parent is not None else None
        if p is not None and d in p.chain():
            raise ValueError("the new parent link would make a cycle")
        self._changed(d)
        d.parent = p

    def site(self, selector: str, bound: int = 4) -> PIC:
        s = PIC(self, selector, bound)
        self.sites.append(s)
        return s


class PIC:
    """A polymorphic inline cache for one send site.

    entries is a list of (class, method) pairs with distinct classes, in the
    order in which they were added, of length at most bound. A megamorphic
    site has no entries and uses the global lookup cache.
    """

    def __init__(self, rt: Runtime, selector: str, bound: int = 4) -> None:
        if bound < 1:
            raise ValueError("bound must be at least 1")
        self.rt = rt
        self.selector = selector
        self.bound = bound
        self.entries: list[tuple[Klass, Method | tuple[str]]] = []
        self.megamorphic = False
        self.hits = 0
        self.misses = 0
        self.history: list[str] = [UNINITIALIZED]

    @property
    def state(self) -> str:
        if self.megamorphic:
            return MEGAMORPHIC
        if not self.entries:
            return UNINITIALIZED
        if len(self.entries) == 1:
            return MONOMORPHIC
        return POLYMORPHIC

    def _record(self) -> None:
        if self.history[-1] != self.state:
            self.history.append(self.state)

    def send(self, k: Klass) -> Method | tuple[str]:
        """The method that a send of the selector to a receiver of class k runs."""
        if self.megamorphic:
            self.misses += 1
            return self.rt.global_lookup(k, self.selector)
        for ck, m in self.entries:
            if ck is k:
                self.hits += 1
                return m
        self.misses += 1
        m = self.rt.lookup(k, self.selector)
        if len(self.entries) < self.bound:
            self.entries.append((k, m))
        else:
            self.entries = []
            self.megamorphic = True
        self._record()
        return m

    def invalidate(self, d: Klass) -> None:
        kept = [(k, m) for k, m in self.entries if d not in k.chain()]
        if len(kept) != len(self.entries):
            self.entries = kept
            self._record()

    def types_seen(self) -> list[str]:
        """The receiver classes in the cache, the data that type feedback reads."""
        return [k.name for k, _ in self.entries]


def example() -> list[tuple[str, str, str, str]]:
    """The worked example of the page: one print site with bound 3."""
    rt = Runtime()
    for name, parent in [("Object", None), ("Point", "Object"), ("ColorPoint", "Point"), ("Circle", "Object"), ("Square", "Object")]:
        rt.define_class(name, parent)
    rt.set_method("Object", "print")
    rt.set_method("Object", "hash")
    rt.set_method("Point", "x")
    rt.set_method("Point", "print")
    rt.set_method("ColorPoint", "color")
    rt.set_method("Circle", "print")
    rt.set_method("Circle", "area")
    rt.set_method("Square", "area")
    site = rt.site("print", bound=3)
    rows = []
    for name in ["Point", "Circle", "Point", "ColorPoint", "Circle", "Square", "Point"]:
        hits = site.hits
        m = site.send(rt.classes[name])
        assert isinstance(m, Method)
        rows.append((name, "hit" if site.hits > hits else "miss", m.owner + "." + m.selector, site.state))
    return rows


if __name__ == "__main__":
    for row in example():
        print(*row)
test_polymorphic_inline_cache.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polymorphic-inline-cache/. The authors are listed in prov/WAS1H3.jsonl.

import random

import pytest

from polymorphic_inline_cache import (
    MEGAMORPHIC,
    MONOMORPHIC,
    NOT_UNDERSTOOD,
    POLYMORPHIC,
    UNINITIALIZED,
    Runtime,
    example,
)


class Shadow:
    """An independent copy of the class table, used as the reference lookup."""

    def __init__(self) -> None:
        self.parent: dict[str, str | None] = {}
        self.methods: dict[str, dict[str, object]] = {}

    def lookup(self, name: str | None, selector: str) -> object:
        while name is not None:
            if selector in self.methods[name]:
                return self.methods[name][selector]
            name = self.parent[name]
        return NOT_UNDERSTOOD

    def ancestors(self, name: str | None) -> set[str]:
        out = set()
        while name is not None:
            out.add(name)
            name = self.parent[name]
        return out


def test_example_table():
    assert example() == [
        ("Point", "miss", "Point.print", MONOMORPHIC),
        ("Circle", "miss", "Circle.print", POLYMORPHIC),
        ("Point", "hit", "Point.print", POLYMORPHIC),
        ("ColorPoint", "miss", "Point.print", POLYMORPHIC),
        ("Circle", "hit", "Circle.print", POLYMORPHIC),
        ("Square", "miss", "Object.print", MEGAMORPHIC),
        ("Point", "miss", "Point.print", MEGAMORPHIC),
    ]


def test_example_invalidation():
    rt = Runtime()
    for name, parent in [("Object", None), ("Point", "Object"), ("ColorPoint", "Point"), ("Circle", "Object")]:
        rt.define_class(name, parent)
    rt.set_method("Object", "print")
    rt.set_method("Point", "print")
    circle_print = rt.set_method("Circle", "print")
    site = rt.site("print", bound=3)
    for name in ["Point", "Circle", "ColorPoint"]:
        site.send(rt.classes[name])
    assert site.types_seen() == ["Point", "Circle", "ColorPoint"]
    new = rt.set_method("ColorPoint", "print")
    assert site.types_seen() == ["Point", "Circle"]
    assert site.send(rt.classes["ColorPoint"]) == new
    assert site.state == POLYMORPHIC and len(site.entries) == 3
    rt.set_method("Point", "print")
    assert site.types_seen() == ["Circle"] and site.state == MONOMORPHIC
    assert site.send(rt.classes["Circle"]) == circle_print


@pytest.mark.parametrize("bound", [1, 2, 3, 4, 10])
def test_state_machine_without_changes(bound):
    rt = Runtime()
    rt.define_class("Object")
    rt.set_method("Object", "m")
    names = ["C%d" % i for i in range(bound + 3)]
    for n in names:
        rt.define_class(n, "Object")
    for j in range(1, bound + 3):
        site = rt.site("m", bound)
        for n in names[:j] * 3:
            site.send(rt.classes[n])
        if j <= bound:
            assert len(site.entries) == j
            assert site.state == (MONOMORPHIC if j == 1 else POLYMORPHIC)
            assert site.misses == j and site.hits == 2 * j
        else:
            assert site.state == MEGAMORPHIC and site.entries == []
        expected = [UNINITIALIZED, MONOMORPHIC, POLYMORPHIC, MEGAMORPHIC]
        if bound == 1:
            expected = [UNINITIALIZED, MONOMORPHIC, MEGAMORPHIC]
        assert site.history == expected[: len(site.history)]


def check_site(site, shadow):
    classes = [k.name for k, _ in site.entries]
    assert len(classes) == len(set(classes))
    assert len(classes) <= site.bound
    for k, m in site.entries:
        assert m == shadow.lookup(k.name, site.selector)
    if site.megamorphic:
        assert site.state == MEGAMORPHIC and not site.entries
    elif not classes:
        assert site.state == UNINITIALIZED
    elif len(classes) == 1:
        assert site.state == MONOMORPHIC
    else:
        assert site.state == POLYMORPHIC


def random_run(seed):
    rng = random.Random(seed)
    rt = Runtime()
    shadow = Shadow()
    nclasses = rng.randint(3, 9)
    names = ["K%d" % i for i in range(nclasses)]
    for i, n in enumerate(names):
        p = rng.choice(names[:i]) if i > 0 and rng.random() < 0.85 else None
        rt.define_class(n, p)
        shadow.parent[n] = p
        shadow.methods[n] = {}
    selectors = ["a", "b", "c", "d"]
    for _ in range(rng.randint(2, 12)):
        n, s = rng.choice(names), rng.choice(selectors)
        shadow.methods[n][s] = rt.set_method(n, s)
    sites = [rt.site(rng.choice(selectors), rng.randint(1, 5)) for _ in range(6)]
    weights = {id(s): [rng.random() ** 3 for _ in names] for s in sites}
    sends = 0
    for _ in range(300):
        before = [(s.megamorphic, len(s.entries)) for s in sites]
        r = rng.random()
        if r < 0.88:
            i = rng.randrange(len(sites))
            site = sites[i]
            name = rng.choices(names, weights[id(site)])[0]
            hits = site.hits
            got = site.send(rt.classes[name])
            sends += 1
            assert got == shadow.lookup(name, site.selector)
            mega, n = before[i]
            if mega:
                assert site.megamorphic
            elif site.hits > hits:
                assert (site.megamorphic, len(site.entries)) == (mega, n)
            elif n < site.bound:
                assert not site.megamorphic and len(site.entries) == n + 1
            else:
                assert site.megamorphic and not site.entries
        else:
            n = rng.choice(names)
            kind = rng.randrange(3)
            if kind == 0:
                s = rng.choice(selectors)
                shadow.methods[n][s] = rt.set_method(n, s)
            elif kind == 1:
                s = rng.choice(selectors)
                rt.remove_method(n, s)
                shadow.methods[n].pop(s, None)
            else:
                p = rng.choice(names + [None])
                if p is not None and n in shadow.ancestors(p):
                    with pytest.raises(ValueError):
                        rt.set_parent(n, p)
                else:
                    rt.set_parent(n, p)
                    shadow.parent[n] = p
            for site, (mega, cnt) in zip(sites, before):
                assert site.megamorphic == mega
                assert len(site.entries) <= cnt
        for site in sites:
            check_site(site, shadow)
    return sends


def test_random_programs_match_full_lookup():
    total = 0
    for seed in range(150):
        total += random_run(seed)
    assert total > 30000


def test_invalidation_keeps_unrelated_entries():
    rt = Runtime()
    rt.define_class("A")
    rt.define_class("B", "A")
    rt.define_class("C", "A")
    rt.set_method("A", "f")
    site = rt.site("f", bound=4)
    for n in "ABC":
        site.send(rt.classes[n])
    rt.set_method("B", "g")
    assert site.types_seen() == ["A", "C"]
    rt.set_method("A", "g")
    assert site.types_seen() == []
    assert site.state == UNINITIALIZED


def test_parent_cycle_rejected():
    rt = Runtime()
    rt.define_class("A")
    rt.define_class("B", "A")
    with pytest.raises(ValueError):
        rt.set_parent("A", "B")
    with pytest.raises(ValueError):
        rt.set_parent("A", "A")


def test_not_understood_is_cached_and_invalidated():
    rt = Runtime()
    rt.define_class("A")
    site = rt.site("f", bound=2)
    assert site.send(rt.classes["A"]) == NOT_UNDERSTOOD
    assert site.send(rt.classes["A"]) == NOT_UNDERSTOOD and site.hits == 1
    m = rt.set_method("A", "f")
    assert site.send(rt.classes["A"]) == m

History

Deutsch and Schiffman introduced the one-entry inline cache in their Smalltalk-80 system in 1984. Hölzle, Chambers and Ungar introduced the polymorphic inline cache for SELF in 1991, at ECOOP, and reported a median speedup of 11% on their SELF programs, a measured result on the machines and programs of that paper. They also noted that the cached types are information for the compiler. Hölzle and Ungar built on that in 1994 with type feedback, where the optimizing compiler of SELF-93 reads the PICs to inline the common cases. Hölzle's 1994 thesis gives the design in full, with megamorphic sends and measurements of the number of types per site.

References

  1. Urs Hölzle, Craig Chambers and David Ungar, Optimizing dynamically-typed object-oriented languages with polymorphic inline caches, ECOOP 1991, LNCS 512, 21-38, the polymorphic inline cache as a stub that tests the receiver type against each cached case and is extended on a miss, and the use of the cached types by the compiler; the abstract reports a median speedup of 11% on SELF programs
  2. Urs Hölzle, Adaptive optimization for SELF: reconciling high performance with exploratory programming, PhD thesis, Stanford University, 1994 (report STAN-CS-TR-94-1520), Chapter 3, Section 3.4 with Figure 3-4 (receiver types per send site), Section 3.5 (polymorphic inline caches) and Section 3.5.1 (megamorphic sends, marked after more than 10 cases)
  3. Urs Hölzle and David Ungar, Optimizing dynamically-dispatched calls with run-time type feedback, PLDI 1994, 326-336, the use of the receiver types stored in polymorphic inline caches as type feedback for the optimizing compiler
  4. L. Peter Deutsch and Allan M. Schiffman, Efficient implementation of the Smalltalk-80 system, POPL 1984, 297-302, the monomorphic inline cache that the polymorphic inline cache extends

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.hit
  • a full proof of time.invalidate
  • a full proof of time.miss
  • a full proof of space.extra
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)
WritingW4 complete
  • a review of the text: no review record reviews/WAS1H3/text.yaml