Copy-and-patch

From HandWiki
Revision as of 17:28, 6 February 2024 by Dennis Ross (talk | contribs) (update)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Short description: Compiler technique

Copy-and-patch compilation is a simple compiler technique intended for just-in-time compilation that uses pattern matching to match pre-generated templates to parts of an abstract syntax tree or bytecode stream, and emit corresponding pre-written machine code fragments that are then patched to insert memory addresses, register addresses, constants and other parameters to produce executable code. Code not matched by templates can be either be interpreted in the normal way, or code created to directly call interpreter code.

While copy-and-patch is a "quick-and-dirty" approach to compilation that is orders of magnitude faster than more rigorous techniques, it often yields code that can in many cases approach the performance of unoptimized code produced by those techniques.

Copy-and-patch was first described by Fredrik Kjolstad and Haoran Xu in a 2021 paper.[1] A bytecode-based copy-and-patch implementation is used for the Python 3.13 JIT compiler.[2][3]

(As of 2023), Xu was working on an implementation that generates templates automatically, based on high-level language descriptions of the interpreter primitives.[4]

References