@fraczak/k 8.8.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +902 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +0 -16
  25. package/backends/wasm/README.md +2 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
@@ -85,8 +85,9 @@ context for referenced functions.
85
85
  arena in linear memory.
86
86
  - [LLVM](../backends/llvm/README.md) emits target functions and uses the C
87
87
  runtime.
88
- - [PKIR](POLYMORPHIC_IR.md) has a separate layout-oriented instruction set
89
- and a lowering adapter to kVM.
88
+ - [kTVM](KTVM_SPEC.md) is an alternative packed-wire transducer VM that lowers
89
+ KIR-P directly to bit-stream transducers with its own interpreter, Wasm, and
90
+ LLVM targets.
90
91
 
91
92
  The representation preserves branch order and partial failure across these
92
93
  paths. It does not specify a universal pointer layout for every backend.
@@ -0,0 +1,127 @@
1
+ # KVM vs. kTVM: A High-Level Comparative Study
2
+
3
+ This study compares K's two compiled execution architectures across both **WebAssembly (Wasm)** and **Native C/LLVM (`-O3`)** targets:
4
+
5
+ - **KVM** (`backends/wasm`, `backends/llvm`): the heap-allocated, pointer-linked structural value machine executing compiled K relations directly on the host/Wasm call stack.
6
+ - **kTVM** (`ktvm/`, `ktvm/wasm`, `ktvm/llvm`): the packed-wire, demand-driven streaming transducer virtual machine operating directly on prefix-free `k-wire` bitstreams via single-producer single-consumer (SPSC) channels and L1-budgeted lookup-table kernels.
7
+
8
+ All measurements below reflect a single uncontended run on the current tree across 19 representative workloads spanning four behavioral regimes: deep linear bitstreams, polymorphic list operations, deep divide-and-conquer Karatsuba arithmetic, and speculative RFC 8259 JSON parsing.
9
+
10
+ ---
11
+
12
+ ## 1. Architectural Contrast
13
+
14
+ | Dimension | KVM (Wasm & LLVM) | kTVM (Wasm & LLVM) |
15
+ |---|---|---|
16
+ | **Value Representation** | Pointer-linked algebraic heap trees (`Value` / tagged heap objects) | Packed, prefix-free `k-wire` bitstreams in ring-buffered SPSC channels (`BitDeque`) |
17
+ | **I/O Boundary** | Must decode `k-wire` → heap tree on entry and encode heap tree → `k-wire` on exit | Operates directly on raw `k-wire` bitstreams (zero serialization boundary) |
18
+ | **Control Flow & Recursion** | Direct host/Wasm function recursion on the native call stack | Strictly iterative demand-driven pull scheduler (`dstack`); bounded call stack |
19
+ | **Memory Lifecycle** | Bump allocation during evaluation (no incremental reclamation within a run) | Immediate channel release on consumption + slab freelist recycling + strict accumulator settlement |
20
+ | **Non-Linearity & Projection** | $O(1)$ pointer sharing and $O(1)$ field pointer dereference | Linear SPSC channels; fanout (`tee`) and non-tail product fields (`demux`) copy/scan bits via a resumable schema DPDA |
21
+ | **Hot-Loop Acceleration** | Direct compiled code per relation step (1 symbol per call) | Verified multi-bit `chunk_table` / `stack_table` kernels (4–8 bits per lookup) under a 64 KiB L1 budget + bounded short-bit unfolding |
22
+ | **Speculation & Partiality** | Native backtracking / branch rollback over shared heap pointers | Scoped speculative replay (`spec` / `tap`), compiled away into deterministic multi-column `switch`es whenever entry-guard analysis proves disjointness |
23
+
24
+ ---
25
+
26
+ ## 2. Empirical Results
27
+
28
+ ### 2.1 End-to-End Timing & Memory Across All Four Workload Families
29
+
30
+ - **Wasm memory** reports committed Wasm linear memory (`memKB`) for KVM, and peak live `BitDeque` buffer bytes (`buf`) + live nodes inside kTVM's reusable 16 MiB initial linear-memory pool (`19 MiB` on `s^9`).
31
+ - **LLVM timing & memory** report single-invocation process wall time (`wallMs`) and OS Peak Resident Set Size (`RSS`, via `/usr/bin/time -v`), plus kTVM's peak live `BitDeque` bytes and peak live graph nodes.
32
+
33
+ #### A. Deep Streaming Bitstreams (`lsb_add`, `lsb_trim`)
34
+
35
+ | Workload (`in → out`) | KVM Wasm (Mem) | kTVM Wasm (Live Buf / Nodes) | KVM LLVM (Peak RSS) | kTVM LLVM (Peak RSS / Live Buf / Nodes) |
36
+ |---|---:|---:|---:|---:|
37
+ | `lsb_add` 512b (`270 → 136 B`) | `10.12 ms` (`256 KiB`) | **`1.83 ms`** (`1.0 KiB` / 4) | `4.85 ms` (`5.32 MiB`) | **`4.15 ms`** (**`1.20 MiB`** / `1.0 KiB` / 2) |
38
+ | `lsb_add` 4,096b (`2.0 → 1.0 KiB`) | *Stack overflow* | **`1.23 ms`** (`8.0 KiB` / 4) | `5.55 ms` (`10.59 MiB`) | **`4.71 ms`** (**`1.34 MiB`** / `8.0 KiB` / 2) |
39
+ | `lsb_add` 16,384b (`8.0 → 4.0 KiB`) | *Stack overflow* | **`4.17 ms`** (`32.0 KiB` / 4) | `11.10 ms` (`35.27 MiB`) | **`4.50 ms`** (**`1.34 MiB`** / `32.0 KiB` / 2) |
40
+ | `lsb_add` 65,536b (`32 → 16 KiB`) | *Stack overflow* | **`12.69 ms`** (`128 KiB` / 4) | *SIGSEGV* (`108.9 MiB`) | **`5.34 ms`** (**`1.47 MiB`** / `128 KiB` / 2) |
41
+ | `lsb_trim` 500b (`133 → 71 B`) | `4.31 ms` (`128 KiB`) | **`2.61 ms`** (`256 B` / 5) | `3.96 ms` (`5.35 MiB`) | `4.78 ms` (**`1.22 MiB`** / `256 B` / 1) |
42
+ | `lsb_trim` 2,000b (`508 → 258 B`) | *Stack overflow* | **`0.42 ms`** (`1.0 KiB` / 5) | `3.50 ms` (`5.46 MiB`) | `4.20 ms` (**`1.22 MiB`** / `1.0 KiB` / 1) |
43
+ | `lsb_trim` 16,000b (`4.0 → 2.0 KiB`) | *Stack overflow* | **`2.13 ms`** (`8.0 KiB` / 5) | `6.54 ms` (`16.71 MiB`) | **`3.98 ms`** (**`1.34 MiB`** / `8.0 KiB` / 1) |
44
+
45
+ #### B. Polymorphic Structural Lists (`Examples/poly.k`)
46
+
47
+ | Workload (`in → out`) | KVM Wasm (Mem) | kTVM Wasm (Live Buf / Nodes) | KVM LLVM (Peak RSS) | kTVM LLVM (Peak RSS / Live Buf / Nodes) |
48
+ |---|---:|---:|---:|---:|
49
+ | `poly.length` $L=200$ (`476 → 16 B`) | `11.67 ms` (`448 KiB`) | **`9.18 ms`** (`1.3 KiB` / 44) | `5.23 ms` (`7.35 MiB`) | `5.55 ms` (**`1.47 MiB`** / `1.1 KiB` / 26) |
50
+ | `poly.length` $L=1000$ (`2.7 KiB → 16 B`) | `37.08 ms` (`1.25 MiB`) | **`22.89 ms`** (`8.0 KiB` / 44) | **`6.28 ms`** (`11.96 MiB`) | `8.90 ms` (**`1.47 MiB`** / `8.0 KiB` / 26) |
51
+ | `poly.reverse` $L=200$ (`476 → 476 B`) | `17.17 ms` (`64 KiB`)* | **`2.44 ms`** (`10.0 KiB` / 407) | **`3.60 ms`** (`5.32 MiB`) | `4.35 ms` (**`1.34 MiB`** / `9.2 KiB` / 355) |
52
+ | `poly.reverse` $L=1000$ (`2.7 → 2.7 KiB`) | `63.75 ms` (`320 KiB`)* | **`3.81 ms`** (`51.0 KiB` / 2,007) | **`3.90 ms`** (`7.38 MiB`) | `5.09 ms` (**`1.97 MiB`** / `47.1 KiB` / 1,755) |
53
+ | `poly.split_by` $L=200$ (`485 → 494 B`) | `24.50 ms` (`320 KiB`)* | **`9.41 ms`** (`6.2 KiB` / 248) | **`5.55 ms`** (`7.37 MiB`) | `6.68 ms` (**`1.47 MiB`** / `6.1 KiB` / 234) |
54
+ | `poly.split_by` $L=1000$ (`2.7 → 2.7 KiB`) | `74.95 ms` (`1.25 MiB`)* | **`27.73 ms`** (`29.7 KiB` / 1,048) | **`5.43 ms`** (`10.31 MiB`) | `15.59 ms` (**`1.72 MiB`** / `31.6 KiB` / 1,034) |
55
+
56
+ *\*Note: KVM Wasm's serialized output wire on polymorphic `reverse` / `split_by` is `9,904 B` at $L=1000$ vs. `2,784 B` for kTVM (`3.56×` smaller wire payload) due to KVM emitting unspecialized open-schema envelopes.*
57
+
58
+ #### C. Deep Divide-and-Conquer Karatsuba Arithmetic (`lib/integer.k`)
59
+
60
+ | Workload (`in → out`) | KVM Wasm (Mem) | kTVM Wasm (Live Buf / Nodes) | KVM LLVM (Peak RSS) | kTVM LLVM (Peak RSS / Live Buf / Nodes) |
61
+ |---|---:|---:|---:|---:|
62
+ | `times` 64b×64b (`51 → 45 B`) | **`5.88 ms`** (`1.13 MiB`) | `7.36 ms` (`3.3 KiB` / 137) | `5.20 ms` (`7.68 MiB`) | **`4.90 ms`** (**`1.65 MiB`** / `2.9 KiB` / 92) |
63
+ | `times` 256b×256b (`147 → 141 B`) | **`11.41 ms`** (`1.50 MiB`) | `26.66 ms` (`5.9 KiB` / 204) | `12.81 ms` (`10.05 MiB`) | **`8.66 ms`** (**`1.65 MiB`** / `5.4 KiB` / 136) |
64
+ | `times` 1024b×1024b (`531 → 525 B`) | **`103.01 ms`** (`3.88 MiB`) | `177.26 ms` (`12.2 KiB` / 285) | `91.33 ms` (`15.73 MiB`) | **`46.73 ms`** (**`1.65 MiB`** / `11.5 KiB` / 192) |
65
+ | `s^9` (`987654321^512`, `21 → 3,838 B`) | **`2,021 ms`** (`41.75 MiB`) | `4,665 ms` (`55.2 KiB` / 361) | `3,629 ms` (`48.48 MiB`) | **`1,136 ms`** (**`1.72 MiB`** / `53.4 KiB` / 242) |
66
+
67
+ #### D. Speculative RFC 8259 JSON Parsing (`lib/djson.k` `parse_json`)
68
+
69
+ | Workload (`in → out`) | KVM Wasm (Mem) | kTVM Wasm (Live Buf / Rollbacks) | KVM LLVM (Peak RSS) | kTVM LLVM (Peak RSS / Live Buf / Nodes) |
70
+ |---|---:|---:|---:|---:|
71
+ | `djson` 29 B (`471 → 817 B`) | `66.06 ms` (`320 KiB`) | **`17.38 ms`** (`4.7 KiB` / 1) | *Runtime error (exit 3)* | **`6.18 ms`** (**`3.22 MiB`** / `4.5 KiB` / 149) |
72
+ | `djson` 60 objs (`4.3 → 3.9 KiB`) | `626.40 ms` (`2.63 MiB`) | **`499.10 ms`** (`21.6 KiB` / 60) | *Runtime error (exit 3)* | **`89.83 ms`** (**`3.22 MiB`** / `21.3 KiB` / 170) |
73
+
74
+ ---
75
+
76
+ ### 2.2 Persistent Multi-Op `poly` Harness (`harness/cli.mjs`)
77
+
78
+ Comparing warm persistent execution across all 5 polymorphic list operations (`reverse`, `concat`, `split_by`, `get_nth`, `length`) separates boundary marshaling cost from pure evaluation time:
79
+
80
+ | Suite Size | Backend | Total Mean (ms/iter) | Pure Eval (ms/iter) | Min (ms) | Relative Total Speed |
81
+ |---|---|---:|---:|---:|---:|
82
+ | **$L = 200$** | `wasm-in-process` (KVM Wasm) | `47.344` | `0.655` | `41.609` | 1.00× |
83
+ | **$L = 200$** | `ktvm-wasm-opt` (kTVM Wasm) | **`10.985`** | `10.722` | `10.499` | **4.31× faster vs. KVM Wasm** |
84
+ | **$L = 200$** | `llvm` (KVM LLVM persistent) | **`1.614`** | **`1.382`** | `1.259` | **2.04× faster vs. kTVM LLVM** |
85
+ | **$L = 200$** | `ktvm-llvm-opt` (kTVM LLVM persistent) | `3.298` | `2.707` | `3.101` | 1.00× |
86
+ | **$L = 1,000$** | `wasm-in-process` (KVM Wasm) | `271.819` | `2.955` | `251.680` | 1.00× |
87
+ | **$L = 1,000$** | `ktvm-wasm-opt` (kTVM Wasm) | **`56.307`** | `54.738` | `54.423` | **4.83× faster vs. KVM Wasm** |
88
+ | **$L = 1,000$** | `llvm` (KVM LLVM persistent) | **`5.567`** | **`3.321`** | `5.215` | **3.10× faster vs. kTVM LLVM** |
89
+ | **$L = 1,000$** | `ktvm-llvm-opt` (kTVM LLVM persistent) | `17.252` | `17.320` | `16.999` | 1.00× |
90
+
91
+ ---
92
+
93
+ ## 3. Hypotheses Explaining the Observed Differences
94
+
95
+ Four structural hypotheses explain every sign flip across the matrix above — why **kTVM wins decisively on memory, deep streaming, native Karatsuba, and end-to-end Wasm structural/JSON workloads**, while **KVM still leads on persistent native list manipulation and Wasm Karatsuba**.
96
+
97
+ ### H1 — Boundary Marshaling Dominance in Wasm vs. Direct Pointer Traversal in Persistent Native LLVM
98
+ - **Observation:** On the 5-op `poly` harness ($L=1,000$), `ktvm-wasm-opt` is **4.83× faster end-to-end** than `wasm-in-process` (`56.3 ms` vs. `271.8 ms`), yet `wasm-in-process` spends only `2.96 ms` in pure Wasm evaluation. In persistent native LLVM, the ranking reverses: KVM LLVM (`5.57 ms` total / `3.32 ms` eval) is **3.10× faster** than kTVM LLVM (`17.25 ms`).
99
+ - **Explanation:** Over **98%** of KVM Wasm's end-to-end time on list workloads is spent crossing the JS↔Wasm boundary to materialize and re-serialize pointer trees. kTVM eliminates this boundary entirely by computing directly over the wire representation (where `54.7 ms` of `56.3 ms` is actual evaluation). Once marshaling is amortized in a persistent native binary, however, KVM's pointer-chasing list operations (`reverse`, `split_by`, `concat`) execute as direct compiled function calls with $O(1)$ cons-cell relinking, whereas kTVM traverses the scheduler and sequentially moves packed bit sequences.
100
+
101
+ ### H2 — Call-Stack Depth & Non-Reclaiming Bump Heap vs. Iterative Slab Reclamation
102
+ - **Observation:** KVM Wasm overflows the host/Wasm call stack on every streaming input $\ge 2,000$ bits, and KVM LLVM segfaults at `65,536` bits after allocating `108.9 MiB` RSS. Even where KVM completes (`s^9`, `times 1024b`, `poly.length 1000`), KVM LLVM consumes **8×–28× more physical RAM** than kTVM LLVM (`48.5 MiB` vs. `1.72 MiB` on `s^9`; `15.7 MiB` vs. `1.65 MiB` on `times 1024b`), and KVM Wasm grows to `41.8 MiB` on `s^9`.
103
+ - **Explanation:** KVM lowers structural recursion directly to native/Wasm stack frames and bump-allocates every intermediate algebraic node without freeing dead intermediates within an invocation. On `s^9` (9 sequential squarings culminating in a 15,300-bit Karatsuba tree), KVM leaves tens of megabytes of dead bit-lists resident in memory. kTVM runs strictly iteratively on a heap-backed demand stack, enforces strict accumulator settlement (`after %tok`) to prevent lazy thunk buildup, immediately frees consumed channel buffers, and recycles graph nodes and channels through fixed-size slab freelists — keeping peak live state at **`53 KiB` / 242 nodes** (`1.72 MiB` RSS) on `s^9` and **`1–2` nodes** (`1.2–1.5 MiB` RSS) on 65,536-bit streaming passes.
104
+
105
+ ### H3 — L1-Resident Multi-Bit Table Acceleration & Cache Locality vs. Wasm Dispatch Overhead on Karatsuba
106
+ - **Observation:** On `s^9` and `times (1024b×1024b)`, **kTVM LLVM beats KVM LLVM by 3.20× (`1.14 s` vs. `3.63 s`) and 1.95× (`46.7 ms` vs. `91.3 ms`)**, while in Wasm the relationship flips: **KVM Wasm beats kTVM Wasm by 2.31× (`2.02 s` vs. `4.66 s`) and 1.72× (`103 ms` vs. `177 ms`)**.
107
+ - **Explanation:** Two opposing forces govern Karatsuba performance:
108
+ 1. **Why kTVM wins in Native LLVM:** kTVM compiles inner arithmetic loops (`lsb_add`, `lsb_sub`, `rev_bits`, `trim_bits`, `lsb_shl`) into bisimulation-verified `chunk_table` and `stack_table` kernels that process multiple bits per lookup while fitting completely inside a 64 KiB L1 cache budget. Combined with `1.7 MiB` RSS (L2-resident working set vs. KVM's `48.5 MiB` L3-thrashing heap) and native C optimizations (eager constant/wrap lowering, zero-`memset` inline-channel slab allocation, self-looping `bits[]` DPDA), kTVM LLVM overtakes KVM LLVM decisively once operands grow past ~128 bits.
109
+ 2. **Why KVM still leads in Wasm:** Even with table-accelerated inner loops, Karatsuba's outer divide-and-conquer scaffolding (`lsb_split`, `lsb_mul_small`, channel wiring, `tee`, `switch`, `demux`) still executes ~33.4M kTVM scheduler steps on `s^9`. In native `-O3` C, Clang inlines the node steppers into the pull loop and eliminates most constant/wrap nodes at instantiation time; in Wasm, each non-kernel step still pays interpreted-graph dispatch and `call_indirect` overhead, making KVM Wasm's direct Wasm function calls faster on CPU-bound Wasm Karatsuba despite using `41.8 MiB` of memory.
110
+
111
+ ### H4 — Cost of Bitstream Linearity & Schema Scanning on Non-Linear / Composite Workloads
112
+ - **Observation:** Native `perf` hardware sampling on the two hardest real-world workloads (`s^9` and `djson 60 objs`) shows that after eliminating speculative backtracking (`60` rollbacks across 60 JSON objects) and redundant copies, bit-level copying (`push`/`peek`/`splice`) is no longer the dominant cost. Instead, native runtime splits across three remaining structural overheads:
113
+ - **`s^9` (`1.14 s`):** node/channel lifecycle & batched slab reclamation (`~34%`), pull-scheduler + stepper dispatch (`~13%`), DPDA scanning of `bits[]` (`~11%`), and actual multi-bit table arithmetic (`~7%`).
114
+ - **`djson 60 objs` (`89.8 ms`):** DPDA scanning/copying of composite variable-width schemas (`btrie`, Unicode strings: `~25%`), node/channel lifecycle (`~29%`), and pull-scheduler dispatch (`~14%`).
115
+ - **Explanation:** Because kTVM represents values as flat prefix-free bitstreams without internal length prefixes or pointers, projecting non-tail fields from composite products (`demux` over `btrie` or `cons` lists) or draining discarded branches requires walking the schema DPDA to locate value boundaries. Fixed-width and tail-recursive list schemas (`unit`, `bit`, `ascii`, `float64`, `bits[]`) collapse into tight register loops, while branching recursive products (`btrie`) and variable-width encodings (Unicode codepoints) still pay per-symbol DPDA transitions. Meanwhile, `djson` runs reliably and 1.26× faster in kTVM Wasm than KVM Wasm (`499 ms` vs. `626 ms`) and completes cleanly in `89.8 ms` / `3.22 MiB` RSS in kTVM LLVM (where KVM LLVM currently fails with exit code 3).
116
+
117
+ ---
118
+
119
+ ## 4. Summary Takeaways
120
+
121
+ | Regime | Winner (Wasm) | Winner (Native LLVM) | Primary Driver |
122
+ |---|---|---|---|
123
+ | **Deep bitstreams ($\ge 2\text{k}$ bits)** | **kTVM** *(KVM overflows stack)* | **kTVM** *(up to 2.5× faster; KVM crashes at 64k bits)* | Iterative execution + multi-bit tables + $O(1)$ nodes |
124
+ | **Polymorphic lists (end-to-end)** | **kTVM** *(1.6×–16.7× faster; 4.8× on 5-op harness)* | **KVM** *(1.2×–3.1× faster)* | Wasm JS marshaling tax vs. native $O(1)$ pointer manipulation |
125
+ | **Deep Karatsuba (`times 1024b`, `s^9`)** | **KVM** *(1.7×–2.3× faster, 42 MiB mem)* | **kTVM** *(1.95×–3.20× faster, 28× less RAM)* | Multi-bit L1 tables + L2 cache residency vs. Wasm step dispatch |
126
+ | **RFC 8259 JSON (`djson.parse_json`)** | **kTVM** *(1.26×–3.8× faster)* | **kTVM** *(`89.8 ms`, 3.2 MiB; KVM LLVM errors)* | Entry-guard `spec→switch` compilation + bounded slab memory |
127
+ | **Memory footprint (all workloads)** | **kTVM** *(55 KiB live buf vs. 42 MiB on `s^9`)* | **kTVM** *(1.2–3.2 MiB RSS: 4×–28× less RAM)* | Immediate channel release + slab recycling + strict accumulators |
@@ -1,13 +1,13 @@
1
1
  # Profiling and benchmarks
2
2
 
3
- Benchmarks compare reference JavaScript, kVM, Wasm, LLVM, and PKIR execution.
3
+ Benchmarks compare reference JavaScript, kVM, Wasm, LLVM, and kTVM execution.
4
4
  Run commands from the repository root; LLVM lanes need Clang.
5
5
 
6
6
  ## Entry points
7
7
 
8
8
  | Command | Workload |
9
9
  | --- | --- |
10
- | `npm run compare` | Shared harness for polymorphic list operations |
10
+ | `npm run compare` | Shared harness for polymorphic list operations (JS, kVM, Wasm, LLVM, kTVM) |
11
11
  | `npm run perf:poly` | List operations across execution lanes |
12
12
  | `npm run perf:poly:trace` | List timing phases and call profiles |
13
13
  | `npm run perf:int` | Integer arithmetic |
@@ -66,5 +66,7 @@ The kVM interpreter increments `context.profile` counters, and backend
66
66
  performance helpers collect profiles and phase timings.
67
67
 
68
68
  Generated benchmark reports are measurements of a particular run, not language
69
- or performance guarantees. Use the [test suites](../tests/README.md) for
70
- regression verification.
69
+ or performance guarantees. For an in-depth architectural comparison of kVM and
70
+ kTVM across arithmetic, list, IEEE 754, and JSON workloads, see the
71
+ [kVM vs. kTVM comparative study](KVM_VS_KTVM_COMPARATIVE_STUDY.md). Use the
72
+ [test suites](../tests/README.md) for regression verification.
package/DOCS/README.md CHANGED
@@ -9,7 +9,7 @@ or [try the browser REPL](https://fraczak.github.io/k/).
9
9
  | --- | --- |
10
10
  | [Patterns and relations](PATTERNS.md) | Core syntax, filters, named patterns, scope, and canonical identity |
11
11
  | [REPL](REPL.md) | Session state, loading, codecs, engines, and exports |
12
- | [File formats and tools](FILE_FORMATS.md) | Source, objects, libraries, kVM, PKIR, and CLI workflows |
12
+ | [File formats and tools](FILE_FORMATS.md) | Source, objects, libraries, kVM, and CLI workflows |
13
13
  | [Textual values](TEXTUAL_VALUES.md) | Boundary notation and singleton product/variant ambiguity |
14
14
  | [Writing codecs](CODECS.md) | Codec module contract and a complete example |
15
15
  | [Wire format](../codecs/WIRE_FORMAT.md) | Pattern framing and binary payload encoding |
@@ -24,7 +24,8 @@ The published [paper](https://zenodo.org/records/23652382) has a
24
24
  - [Contract derivation](TYPE_DERIVATION.md)
25
25
  - [KIR-P export](KIR_V1.md)
26
26
  - [kVM execution](KVM_EXECUTION_MODEL.md)
27
- - [PKIR and layout witnesses](POLYMORPHIC_IR.md)
27
+ - [kTVM packed-wire transducer VM](KTVM_SPEC.md)
28
+ - [kVM vs. kTVM comparative study](KVM_VS_KTVM_COMPARATIVE_STUDY.md)
28
29
  - [Profiling and benchmarks](PROFILING_AND_TRACING.md)
29
30
  - [WebAssembly backend](../backends/wasm/README.md)
30
31
  - [LLVM backend](../backends/llvm/README.md)
package/DOCS/REPL.md CHANGED
@@ -34,9 +34,9 @@ shows compilation and execution costs for the selected engine.
34
34
  | `:codec unload name` | Remove a codec |
35
35
  | `:codec list` / `:codecs` | List registered codecs |
36
36
  | `:input codec.mjs [text]` | Parse inline text, or prompt for the next input line |
37
- | `:engine [wasm\|pkir\|js]` | Show or select the evaluation engine |
38
- | `:wasm` / `:pkir` / `:js` | Engine shortcuts |
39
- | `:limit [number\|none]` | Show or change the output limit (default: 4096 characters) |
37
+ | `:engine [wasm\|ktvm\|js]` | Show or select the evaluation engine |
38
+ | `:wasm` / `:ktvm` / `:js` | Engine shortcuts |
39
+ | `:limit [number\|none]` | Show or change the output limit (default: `none`) |
40
40
  | `:max-pat-length [number\|none]` | Show or change max inline pattern length in `:rel` (default: 45, alias `:maxPatLength`) |
41
41
  | `:klib file` | Export the current library |
42
42
  | `:ko file expression` | Export an executable object |
@@ -111,18 +111,20 @@ See [writing codecs](CODECS.md) for the module contract.
111
111
 
112
112
  The terminal REPL provides:
113
113
 
114
- - `wasm` (default): compile and execute through WebAssembly;
115
- - `pkir`: execute through the experimental polymorphic IR;
114
+ - `wasm` (default): compile and execute through the kVM WebAssembly backend;
115
+ - `ktvm`: compile and execute through the packed-wire kTVM WebAssembly backend;
116
116
  - `js`: use the envelope-aware JavaScript reference evaluator.
117
117
 
118
118
  Choose an engine or output limit at startup:
119
119
 
120
120
  ```sh
121
121
  node repl.mjs --engine=js
122
- node repl.mjs --engine=pkir
122
+ node repl.mjs --engine=ktvm
123
123
  node repl.mjs --engine=wasm --limit=8192
124
124
  ```
125
125
 
126
+ Shortcuts `--wasm`, `--ktvm`, and `--js` are equivalent to `--engine=...`.
127
+
126
128
  Large values are rendered iteratively and truncated at the configured limit.
127
129
  Use `:limit none` to disable truncation.
128
130
 
@@ -143,10 +145,12 @@ See [file formats](FILE_FORMATS.md) for inspection, validation, and CLI executio
143
145
 
144
146
  ## Browser REPL
145
147
 
146
- `npm run build:repl-html` creates a self-contained `repl.html` with an
147
- in-process WebAssembly backend, bundled libraries/codecs, and a virtual
148
- filesystem. It is also [hosted online](https://fraczak.github.io/k/).
148
+ `npm run build:repl-html` creates a self-contained `repl.html` with in-process
149
+ WebAssembly (`wasm`), kTVM-Wasm (`ktvm`), and JavaScript (`js`) engines, bundled
150
+ libraries/codecs, and a virtual filesystem. It is also
151
+ [hosted online](https://fraczak.github.io/k/).
149
152
 
150
- The browser adds file loading, codec management, interactive input dialogs, and
151
- value-tree inspection. Uploaded and exported files use the virtual filesystem
152
- and browser downloads rather than the terminal's filesystem access.
153
+ The browser adds an interactive engine-switcher badge, file loading, codec
154
+ management, interactive input dialogs, and value-tree inspection. Uploaded and
155
+ exported files use the virtual filesystem and browser downloads rather than the
156
+ terminal's filesystem access.
package/README.md CHANGED
@@ -80,6 +80,136 @@ content hash (`@<hash>`), while `--use` explicitly brings requested friendly
80
80
  names or aliases into compilation scope. See
81
81
  [file formats and tools](DOCS/FILE_FORMATS.md).
82
82
 
83
+ ## Execution backends
84
+
85
+ All backends implement the same k semantics over the binary
86
+ [wire format](codecs/WIRE_FORMAT.md) and are fully polymorphic (supporting
87
+ parameterized schemas and open patterns).
88
+
89
+ | Backend | Target(s) | Execution model | How to invoke |
90
+ | --- | --- | --- | --- |
91
+ | **JS reference** | JavaScript | Tree-walking interpreter over enveloped `Value` objects | `k` (`k.mjs`), `k.compile()`, REPL `:js` |
92
+ | **kVM interpreter** | JavaScript | Register bytecode over structural heap values | `k-vm` (`kvm.mjs`), `executeKVM()` |
93
+ | **kVM Wasm** | WebAssembly | Register VM compiled to `.wasm` with a bump arena | `k-wasm`, `k-wasm-compile`, `k-wasm-run`, REPL `:wasm` *(default)* |
94
+ | **kVM LLVM** | Native (Clang/LLVM) | Register VM lowered to LLVM IR + C runtime (`krt.c`) | `k-llvm`, `k-llvm-compile`, `k-llvm-build` |
95
+ | **kTVM ref VM** | JavaScript | Iterative packed-wire streaming transducer VM | `@fraczak/k/ktvm/index.mjs` (`executeObjectWithKTVM`) |
96
+ | **kTVM Wasm** | WebAssembly | Packed-wire transducer + verified bit-chunk tables in `.wasm` | REPL `:ktvm` (`--ktvm`), `compileObjectToKTVMWasm()` |
97
+ | **kTVM LLVM** | Native (Clang/LLVM) | Packed-wire transducer lowered to C99 + `clang -O3` | `compileObjectToKTVMExecutable()` / `executeKTVMExecutable()` |
98
+
99
+ ### 1. JavaScript reference evaluator
100
+
101
+ The reference interpreter (`run.mjs`, `k.mjs`) evaluates relations directly
102
+ over in-memory `Value` trees with runtime envelope propagation (plus an
103
+ envelope-free `run_converged` path for converged relations). It supports all
104
+ language features, including non-converged relations.
105
+
106
+ ```sh
107
+ node codecs/unit.mjs --parse | node k.mjs '{} |ok' | node codecs/k-print.mjs
108
+ node repl.mjs --js # or type :js inside the REPL
109
+ ```
110
+
111
+ ### 2. kVM backends (interpreter, WebAssembly, LLVM)
112
+
113
+ [kVM](DOCS/KVM_EXECUTION_MODEL.md) lowers portable [KIR-P](DOCS/KIR_V1.md) into
114
+ polymorphic register-bytecode templates (`KVM-P`), specializes them for
115
+ incoming envelopes (`KVM`), and evaluates pointer-linked algebraic trees on the
116
+ host/Wasm call stack.
117
+
118
+ - **kVM bytecode interpreter** (`kvm.mjs` / `k-vm`):
119
+ ```sh
120
+ node codecs/unit.mjs --parse | node kvm.mjs '{} |ok' | node codecs/k-print.mjs
121
+ ```
122
+ - **kVM WebAssembly** ([backends/wasm/README.md](backends/wasm/README.md) —
123
+ default engine in both the terminal and browser REPLs):
124
+ ```sh
125
+ # Compile and run in one step
126
+ node codecs/unit.mjs --parse |
127
+ node backends/wasm/bin/k-wasm.mjs '|ok' |
128
+ node codecs/k-print.mjs
129
+
130
+ # Compile ahead-of-time to .wasm and run
131
+ node backends/wasm/bin/k-wasm-compile.mjs '?{} {} |ok' /tmp/k-ok.wasm
132
+ node codecs/unit.mjs --parse |
133
+ node backends/wasm/bin/k-wasm-run.mjs /tmp/k-ok.wasm |
134
+ node codecs/k-print.mjs
135
+ ```
136
+ - **kVM LLVM** ([backends/llvm/README.md](backends/llvm/README.md) — requires
137
+ Clang):
138
+ ```sh
139
+ # Compile, cache, and run directly over a wire stream
140
+ node codecs/unit.mjs --parse |
141
+ node backends/llvm/bin/k-llvm.mjs '|ok' |
142
+ node codecs/k-print.mjs
143
+
144
+ # Build a standalone native executable (or emit .ll IR with k-llvm-compile.mjs)
145
+ node backends/llvm/bin/k-llvm-build.mjs '?{} {} |ok' /tmp/k-ok.exe
146
+ node codecs/unit.mjs --parse | /tmp/k-ok.exe | node codecs/k-print.mjs
147
+ ```
148
+
149
+ ### 3. kTVM backends (packed-wire transducer VM: JS, WebAssembly, LLVM)
150
+
151
+ [kTVM](DOCS/KTVM_SPEC.md) is an iterative, demand-driven streaming transducer
152
+ VM (`ktvm/`) that executes relations **directly over raw `k-wire` bitstreams**
153
+ without materializing heap value trees. At the wire boundary it specializes
154
+ polymorphic `kTVM-P` modules into closed `kTVM` modules, compiles inner
155
+ streaming loops into bisimulation-verified, L1-budgeted multi-bit lookup tables
156
+ (selected via Howard's MWTR criterion), and recycles channels and nodes through
157
+ slab freelists — avoiding call-stack overflows on deep bitstreams and using
158
+ dramatically less memory than heap-allocated execution.
159
+
160
+ - **In the terminal and browser REPLs (kTVM WebAssembly):**
161
+ ```sh
162
+ node repl.mjs --ktvm # or type :ktvm inside the REPL
163
+ ```
164
+ In `repl.html`, click the engine badge (`wasm-in-process → ktvm-wasm → js-in-process`) or run `:engine ktvm`.
165
+ - **Via the JavaScript API** (`ktvm/index.mjs`, also re-exported from
166
+ `backend-api.mjs`):
167
+ ```js
168
+ import { compileObjectBuffer, decodeObject } from "@fraczak/k/object.mjs";
169
+ import { encodeToWire, decodeWire } from "@fraczak/k/codecs/runtime/prefix-codec.mjs";
170
+ import { Value } from "@fraczak/k/Value.mjs";
171
+ import {
172
+ executeObjectWithKTVM,
173
+ compileObjectToKTVMWasm,
174
+ instantiateKTVMWasm,
175
+ compileObjectToKTVMExecutable,
176
+ executeKTVMExecutable
177
+ } from "@fraczak/k/ktvm/index.mjs";
178
+
179
+ const unitPattern = [["closed-product", []]];
180
+ const obj = decodeObject(compileObjectBuffer("?{} {} |ok"));
181
+ const inWire = encodeToWire(Value.product({}, unitPattern), unitPattern);
182
+
183
+ // 1. kTVM iterative JS reference VM
184
+ const ref = executeObjectWithKTVM(obj, "__main__", inWire);
185
+ console.log(ref.value.tag); // "ok"
186
+
187
+ // 2. kTVM WebAssembly (zero JS tree marshaling at the wire boundary)
188
+ const wasmArtifact = await compileObjectToKTVMWasm(obj, "__main__", unitPattern);
189
+ const wasmRunner = await instantiateKTVMWasm(wasmArtifact);
190
+ console.log(wasmRunner.executeWire(inWire, { decodeValue: true }).value.tag); // "ok"
191
+
192
+ // 3. kTVM Native C/LLVM executable (requires Clang; binary reads/writes k-wire on stdio)
193
+ compileObjectToKTVMExecutable(obj, "__main__", unitPattern, "/tmp/k-ok-ktvm.exe");
194
+ const native = executeKTVMExecutable("/tmp/k-ok-ktvm.exe", inWire);
195
+ console.log(decodeWire(native.wire).value.tag); // "ok"
196
+ ```
197
+
198
+ A standalone binary produced by `compileObjectToKTVMExecutable` also works
199
+ directly in shell pipelines:
200
+
201
+ ```sh
202
+ node codecs/unit.mjs --parse | /tmp/k-ok-ktvm.exe | node codecs/k-print.mjs
203
+ ```
204
+
205
+ ### Comparing backends
206
+
207
+ Compare backends on conformance and speed with `npm run compare`
208
+ (`node harness/cli.mjs --help`). See the
209
+ [kVM vs. kTVM comparative study](DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md) and
210
+ [profiling guide](DOCS/PROFILING_AND_TRACING.md) for trade-offs across deep
211
+ bitstreams, polymorphic lists, Karatsuba arithmetic, and RFC 8259 JSON parsing.
212
+
83
213
  ## JavaScript API
84
214
 
85
215
  ```js
@@ -107,8 +237,8 @@ by hand.
107
237
 
108
238
  The [compiler guide](DOCS/ARCHITECTURE.md) maps the implementation and execution
109
239
  layers. [WebAssembly](backends/wasm/README.md),
110
- [LLVM](backends/llvm/README.md), and the [VS Code extension](k-vscode/README.md)
111
- have their own usage instructions.
240
+ [LLVM](backends/llvm/README.md), [kTVM](DOCS/KTVM_SPEC.md), and the
241
+ [VS Code extension](k-vscode/README.md) have their own usage instructions.
112
242
 
113
243
  k is experimental: syntax, diagnostics, libraries, and artifact formats may
114
244
  change. Release history is in [CHANGELOG.md](CHANGELOG.md).
package/backend-api.mjs CHANGED
@@ -36,21 +36,36 @@ export {
36
36
  isIdentityIntrinsic,
37
37
  unsupportedIntrinsic
38
38
  } from "./intrinsics.mjs";
39
- export { buildAccessTable, AccessTable } from "./access-table.mjs";
40
39
  export {
41
- PKIR_FORMAT,
42
- PKIR_VERSION,
43
- compileRelationToPKIR,
44
- executePKIR,
45
- specializePKIR,
46
- valueToKVal,
47
- kvalToValue,
48
- lowerPKIRToKVM
49
- } from "./pkir.mjs";
50
- export {
51
- compileWasmArtifactFromPKIR
52
- } from "./backends/wasm/src/wasm.mjs";
53
- export {
54
- compileLLVMArtifactFromPKIR
55
- } from "./backends/llvm/src/llvm.mjs";
40
+ KTVM_FORMAT,
41
+ KTVM_VERSION,
42
+ KTVMSyntaxError,
43
+ KTVMValidationError,
44
+ KTVMSchemaError,
45
+ KTVMQuotaError,
46
+ parseModule as parseKTVMModule,
47
+ printModule as printKTVMModule,
48
+ moduleToJSON as ktvmModuleToJSON,
49
+ moduleFromJSON as ktvmModuleFromJSON,
50
+ validateModule as validateKTVMModule,
51
+ specializeKTVM,
52
+ lowerKIRToKTVMP,
53
+ compileKIRToKTVM,
54
+ compileObjectToKTVM,
55
+ executeKTVM,
56
+ executeKTVMWire,
57
+ executeObjectWithKTVM,
58
+ optimizeKTVM,
59
+ computeMWTR,
60
+ compileKTVMToWat,
61
+ compileKTVMToWasm,
62
+ instantiateKTVMWasm,
63
+ compileObjectToKTVMWasm,
64
+ isClangAvailable,
65
+ compileKTVMToC,
66
+ compileCToExecutable,
67
+ compileKTVMToExecutable,
68
+ compileObjectToKTVMExecutable,
69
+ executeKTVMExecutable
70
+ } from "./ktvm/index.mjs";
56
71
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  The experimental LLVM backend lowers k programs to LLVM IR and links them with
4
4
  the C runtime. It supports source/object execution, compiled native executables,
5
- kVM input, and the experimental PKIR path.
5
+ and kVM input.
6
6
 
7
7
  Commands belong to the root package. Install dependencies from the repository
8
8
  root and ensure Clang is available:
@@ -46,8 +46,8 @@ node backends/llvm/bin/k-llvm-compile.mjs '?{} {} |ok' /tmp/k-ok.ll
46
46
  | `k-llvm-compile` | Emit textual LLVM IR |
47
47
  | `k-llvm-build` | Link a standalone executable that reads/writes k wire values |
48
48
 
49
- Compile/build commands accept inline source or a source, `.ko`, `.kvm`, or
50
- `.pkir` input. A `.klib` needs a selected relation, supplied through the
49
+ Compile/build commands accept inline source or a source, `.ko`, or `.kvm`
50
+ input. A `.klib` needs a selected relation, supplied through the
51
51
  tool's `--retype` option or linked into source with a terminal expression.
52
52
  Source is read from stdin when omitted. The execution command instead requires
53
53
  a program argument and reads binary input from stdin or an optional filename.
@@ -57,7 +57,6 @@ Common compile options:
57
57
  - `-o` / `--output path`: output path instead of a positional output.
58
58
  - `--lib file`: one `.k` or `.klib` dependency.
59
59
  - `--use name` or `--use libraryName:localName`: repeatable alias imports.
60
- - `--pkir`: compile source through PKIR.
61
60
  - `--retype relation`: select the relation for envelope specialization.
62
61
  - `--opt flag`: Clang optimization flag.
63
62
 
@@ -93,7 +92,7 @@ k_result k_main(k_rt *rt, k_value *input);
93
92
  [runtime/krt.h](runtime/krt.h) defines helpers and ownership through the runtime;
94
93
  [runtime/krt.c](runtime/krt.c) implements values, arenas, and wire support.
95
94
  [kvm2llvm.mjs](src/kvm2llvm.mjs) lowers kVM functions;
96
- [llvm.mjs](src/llvm.mjs) coordinates object and PKIR paths.
95
+ [llvm.mjs](src/llvm.mjs) coordinates object and kVM compilation paths.
97
96
 
98
97
  Unsupported operations must produce diagnostics rather than silently change
99
98
  semantics. Backend coverage and artifact formats remain experimental.
@@ -9,14 +9,13 @@ import {
9
9
  } from "../src/cli.mjs";
10
10
  import {
11
11
  compileKVMToExecutable,
12
- compileObjectToExecutable,
13
- compilePKIRToExecutable
12
+ compileObjectToExecutable
14
13
  } from "../src/executable.mjs";
15
14
 
16
15
  function helpText() {
17
16
  const prog = argv[1] || "k-llvm-build.mjs";
18
17
  return [
19
- "Compile k source, .ko, .klib, .kvm, or .pkir into a native",
18
+ "Compile k source, .ko, .klib, or .kvm into a native",
20
19
  "standalone executable.",
21
20
  "",
22
21
  `Usage: ${prog} [options]`,
@@ -24,7 +23,7 @@ function helpText() {
24
23
  "",
25
24
  "Arguments:",
26
25
  " source-snippet Inline k source snippet (in the style of k.mjs).",
27
- " input-file Source .k, .ko, .klib, .kvm, or .pkir file.",
26
+ " input-file Source .k, .ko, .klib, or .kvm file.",
28
27
  " Reads UTF-8 source from stdin when omitted.",
29
28
  " output-exe Output executable path.",
30
29
  "",
@@ -35,7 +34,6 @@ function helpText() {
35
34
  "",
36
35
  "Options:",
37
36
  " -o, --output path Specify output file path explicitly.",
38
- " --pkir Lower via Polymorphic K IR (PKIR).",
39
37
  " --input-pattern pattern Input pattern JSON or file for spec.",
40
38
  " --retype rel Relation to specialize (default: main).",
41
39
  " --lib file Load .klib or .k library before build.",
@@ -119,7 +117,7 @@ try {
119
117
 
120
118
  const inputPattern = readPattern(rawInputPattern);
121
119
 
122
- const { libraries, useSpecs, usePKIR } =
120
+ const { libraries, useSpecs } =
123
121
  parseCompileOptions(remainingArgs);
124
122
  const input = resolveProgramInput(remainingArgs, {
125
123
  allowStdinSource: true
@@ -134,22 +132,13 @@ try {
134
132
  );
135
133
  }
136
134
 
137
- if (input.kind === "pkir") {
138
- const pkir = JSON.parse(fs.readFileSync(input.path, "utf8"));
139
- compilePKIRToExecutable(pkir, outputPath, {
140
- entry: relation,
141
- inputPattern,
142
- clangOpt,
143
- runtimeMode
144
- });
145
- } else if (input.kind === "kvm") {
135
+ if (input.kind === "kvm") {
146
136
  const kvm = JSON.parse(fs.readFileSync(input.path, "utf8"));
147
137
  compileKVMToExecutable(kvm, outputPath, {
148
138
  entry: relation,
149
139
  inputPattern,
150
140
  clangOpt,
151
- runtimeMode,
152
- usePKIR
141
+ runtimeMode
153
142
  });
154
143
  } else {
155
144
  const object = await compileProgramInputToObject(input, {
@@ -162,8 +151,7 @@ try {
162
151
  relation: relation || object.main,
163
152
  inputPattern,
164
153
  clangOpt,
165
- runtimeMode,
166
- usePKIR
154
+ runtimeMode
167
155
  });
168
156
  }
169
157
  } catch (error) {
@@ -9,28 +9,26 @@ import {
9
9
  } from "../src/cli.mjs";
10
10
  import {
11
11
  compileObjectToLLVM,
12
- compileLLVMArtifactFromKVM,
13
- compileLLVMArtifactFromPKIR
12
+ compileLLVMArtifactFromKVM
14
13
  } from "../src/llvm.mjs";
15
14
  import { inputPatternForObjectRelation } from "../src/executable.mjs";
16
15
 
17
16
  function helpText() {
18
17
  const prog = argv[1] || "k-llvm-compile.mjs";
19
18
  return [
20
- "Compile a k .ko/.klib object, source, .kvm, or .pkir into LLVM IR.",
19
+ "Compile a k .ko/.klib object, source, or .kvm into LLVM IR.",
21
20
  "",
22
21
  `Usage: ${prog} [options]`,
23
22
  " [source-snippet | input-file [output.ll]]",
24
23
  "",
25
24
  "Arguments:",
26
25
  " source-snippet Inline k source snippet (in the style of k.mjs).",
27
- " input-file Source .k, .ko, .klib, .kvm, or .pkir file.",
26
+ " input-file Source .k, .ko, .klib, or .kvm file.",
28
27
  " Reads UTF-8 source from stdin when omitted.",
29
28
  " output.ll Output LLVM IR path (default: stdout).",
30
29
  "",
31
30
  "Options:",
32
31
  " -o, --output path Specify output file path explicitly.",
33
- " --pkir Lower via Polymorphic K IR (PKIR).",
34
32
  " --retype rel Relation to compile (default: object main).",
35
33
  " --lib file Load one .klib or .k library before compiling.",
36
34
  " --use spec Use library alias in scope (repeatable).",
@@ -40,7 +38,6 @@ function helpText() {
40
38
  "Examples:",
41
39
  ` ${prog} 'x = |x; x x' program.ll`,
42
40
  ` ${prog} program.k -o program.ll`,
43
- ` ${prog} --pkir program.k -o program.ll`,
44
41
  ` ${prog} --lib core.klib --use add program.k program.ll`
45
42
  ].join("\n");
46
43
  }
@@ -78,7 +75,7 @@ try {
78
75
  }
79
76
  }
80
77
 
81
- const { libraries, useSpecs, usePKIR } =
78
+ const { libraries, useSpecs } =
82
79
  parseCompileOptions(remainingArgs);
83
80
  const input = resolveProgramInput(remainingArgs, {
84
81
  allowStdinSource: true
@@ -89,15 +86,7 @@ try {
89
86
  const outputPath = explicitOutput || positionalOutput || null;
90
87
 
91
88
  let llvm;
92
- if (input.kind === "pkir") {
93
- const pkir = JSON.parse(fs.readFileSync(input.path, "utf8"));
94
- const entry = relation || pkir.entry || pkir.name || "__main__";
95
- llvm = compileLLVMArtifactFromPKIR(pkir, {
96
- relation: entry,
97
- inputPattern: pkir.inputPattern,
98
- outputPattern: pkir.outputPattern
99
- });
100
- } else if (input.kind === "kvm") {
89
+ if (input.kind === "kvm") {
101
90
  const kvm = JSON.parse(fs.readFileSync(input.path, "utf8"));
102
91
  const entry = relation || kvm.entry || kvm.relation || "__main__";
103
92
  const mainFunc = kvm.functions?.[entry];
@@ -117,8 +106,7 @@ try {
117
106
  const targetRel = relation || object.main;
118
107
  const res = compileObjectToLLVM(object, {
119
108
  relation: targetRel,
120
- inputPattern: inputPatternForObjectRelation(object, targetRel),
121
- usePKIR
109
+ inputPattern: inputPatternForObjectRelation(object, targetRel)
122
110
  });
123
111
  llvm = res.llvm;
124
112
  }