@fraczak/k 8.9.0 → 9.1.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.
- package/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +907 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +13 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +138 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -7
- package/backends/llvm/src/llvm.mjs +4 -113
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +2 -16
- package/backends/wasm/README.md +7 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +60 -57
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/runtime/prefix-codec.mjs +67 -1
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +497 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +130 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +1134 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1805 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4404 -0
- package/ktvm/wasm/test-wasm.mjs +429 -0
- package/ktvm/wire.mjs +679 -0
- package/package.json +1 -9
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +14 -232
- package/scripts/perf-int.mjs +16 -274
- package/scripts/perf-multiplication.mjs +116 -121
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,2111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CPS Symbolic `proc -> kernel` Fusion, TMC Streaming, Finite-Enum Register
|
|
3
|
+
* Promotion, and Virtual LIFO Bit-Stack Promotion (`kTVM -> kTVM`).
|
|
4
|
+
*
|
|
5
|
+
* Operates purely on validated concrete `mono` kTVM modules:
|
|
6
|
+
* 1. Flattens product ports into flat leaf streams (replacing the proc body
|
|
7
|
+
* with a thin `demux -> exec @kernel -> mux` wrapper).
|
|
8
|
+
* 2. Symbolically executes the SPSC proc DAG (inlining acyclic helpers,
|
|
9
|
+
* eliminating `mux`/`demux`/`tee`/`spec` overhead) into a compact
|
|
10
|
+
* deterministic Decision DAG.
|
|
11
|
+
* 3. Recognizes both strict self-tail loops and Tail-Modulo-Constructor (TMC)
|
|
12
|
+
* forward-streaming loops (`wrap |tag` around direct self-`spawn`).
|
|
13
|
+
* 4. Promotes finite unit-enum loop ports (`bit[]`, `order[]`, carry/borrow/mode)
|
|
14
|
+
* to in-register `reg r : enum(K)`.
|
|
15
|
+
* 5. Promotes LIFO `bits[]`-like accumulator ports (e.g. `_lsb_trim`'s `z` or
|
|
16
|
+
* `_rev_bits`'s `acc`) to kernel-local `stack s : bits`.
|
|
17
|
+
* 6. Gracefully skips wide-alphabet unions (`> maxUnionTags`, e.g. `ascii[]`
|
|
18
|
+
* in `djson.k`) and branching-recursive orchestrators, leaving them intact.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { S, cloneAst, createModule } from "../ast.mjs";
|
|
22
|
+
import {
|
|
23
|
+
compileSchemaExprToPlist,
|
|
24
|
+
isUnitSchema,
|
|
25
|
+
mooreMinimize,
|
|
26
|
+
plistToSchemaAst,
|
|
27
|
+
productFields,
|
|
28
|
+
schemasEquivalent,
|
|
29
|
+
subPlist,
|
|
30
|
+
unionTagInfo
|
|
31
|
+
} from "../schema.mjs";
|
|
32
|
+
import { choiceWidth } from "../../codecs/runtime/prefix-codec.mjs";
|
|
33
|
+
|
|
34
|
+
const BAIL = Symbol("BAIL");
|
|
35
|
+
|
|
36
|
+
function bail(reason = "bail") {
|
|
37
|
+
const err = new Error(reason);
|
|
38
|
+
err[BAIL] = true;
|
|
39
|
+
throw err;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function toBitsLit(val, width) {
|
|
43
|
+
return (val >>> 0).toString(2).padStart(width, "0");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function sanitize(raw) {
|
|
47
|
+
const s = String(raw || "").replace(/^[@$%]/, "").replace(/[^A-Za-z0-9_]/g, "_");
|
|
48
|
+
return /^[A-Za-z_]/.test(s) ? s : `k_${s}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Flatten a concrete closed schema into leaf streams (splitting nested closed-products).
|
|
53
|
+
* Empty `closed-product` (`unit`) is kept as a single unit leaf.
|
|
54
|
+
*/
|
|
55
|
+
function flattenLeaves(plist, nodeId = 0, path = []) {
|
|
56
|
+
const [kind, edges] = plist[nodeId];
|
|
57
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
58
|
+
const out = [];
|
|
59
|
+
for (const [label, target] of edges) {
|
|
60
|
+
out.push(...flattenLeaves(plist, target, [...path, label]));
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
return [{
|
|
65
|
+
path,
|
|
66
|
+
pathKey: path.join("."),
|
|
67
|
+
nodeId,
|
|
68
|
+
plist: subPlist(plist, nodeId),
|
|
69
|
+
isUnit: kind === "closed-product" && edges.length === 0
|
|
70
|
+
}];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function buildInitialInSVal(plist, nodeId, box) {
|
|
74
|
+
const [kind, edges] = plist[nodeId];
|
|
75
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
76
|
+
const fields = new Map();
|
|
77
|
+
for (const [label, target] of edges) {
|
|
78
|
+
fields.set(label, buildInitialInSVal(plist, target, box));
|
|
79
|
+
}
|
|
80
|
+
return { kind: "bundle", fields, plist: subPlist(plist, nodeId) };
|
|
81
|
+
}
|
|
82
|
+
const p = box.next++;
|
|
83
|
+
const leafPl = subPlist(plist, nodeId);
|
|
84
|
+
if (kind === "closed-product" && edges.length === 0) {
|
|
85
|
+
return { kind: "port", p, depth: 0, plist: leafPl, nodeId: 0, isUnit: true };
|
|
86
|
+
}
|
|
87
|
+
return { kind: "port", p, depth: 0, plist: leafPl, nodeId: 0, isUnit: false };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function buildSelfOutSVal(plist, nodeId, box) {
|
|
91
|
+
const [kind, edges] = plist[nodeId];
|
|
92
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
93
|
+
const fields = new Map();
|
|
94
|
+
for (const [label, target] of edges) {
|
|
95
|
+
fields.set(label, buildSelfOutSVal(plist, target, box));
|
|
96
|
+
}
|
|
97
|
+
return { kind: "bundle", fields, plist: subPlist(plist, nodeId) };
|
|
98
|
+
}
|
|
99
|
+
const q = box.next++;
|
|
100
|
+
return { kind: "selfOut", q, plist: subPlist(plist, nodeId) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function svalToLeaves(v, out = []) {
|
|
104
|
+
if (v.kind === "bundle") {
|
|
105
|
+
for (const child of v.fields.values()) svalToLeaves(child, out);
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
out.push(v);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function containsSelfOut(v) {
|
|
113
|
+
if (!v) return false;
|
|
114
|
+
if (v.kind === "selfOut") return true;
|
|
115
|
+
if (v.kind === "cons") return containsSelfOut(v.tail);
|
|
116
|
+
if (v.kind === "bundle") {
|
|
117
|
+
for (const c of v.fields.values()) if (containsSelfOut(c)) return true;
|
|
118
|
+
}
|
|
119
|
+
if (v.kind === "cont") return v.args.some(containsSelfOut);
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function cloneSymState(st) {
|
|
124
|
+
return {
|
|
125
|
+
peeks: st.peeks.map((a) => a.slice()),
|
|
126
|
+
schemas: st.schemas.map((s) => ({ plist: s.plist, nodeId: s.nodeId })),
|
|
127
|
+
drained: st.drained.slice(),
|
|
128
|
+
mustDrainUnit: st.mustDrainUnit.slice(),
|
|
129
|
+
mustDrainFull: st.mustDrainFull.slice(),
|
|
130
|
+
selfCall: st.selfCall
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Compute call graph & finiteness (acyclicity) over all procs in a mono module.
|
|
136
|
+
*/
|
|
137
|
+
function analyzeProcCallGraph(mod) {
|
|
138
|
+
const callsOf = new Map();
|
|
139
|
+
const walkStmts = (stmts, set) => {
|
|
140
|
+
for (const s of stmts || []) {
|
|
141
|
+
if (s.op === "spawn") set.add(s.target);
|
|
142
|
+
else if (s.op === "switch") {
|
|
143
|
+
for (const a of s.arms) walkStmts(a.body, set);
|
|
144
|
+
if (s.defaultBody) walkStmts(s.defaultBody, set);
|
|
145
|
+
} else if (s.op === "spec") {
|
|
146
|
+
for (const b of s.branches) walkStmts(b.body, set);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
for (const p of mod.procs || []) {
|
|
151
|
+
const set = new Set();
|
|
152
|
+
walkStmts(p.body, set);
|
|
153
|
+
callsOf.set(p.name, set);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const finiteCache = new Map();
|
|
157
|
+
const isFinite = (name, visiting = new Set()) => {
|
|
158
|
+
if (finiteCache.has(name)) return finiteCache.get(name);
|
|
159
|
+
if (visiting.has(name)) return false;
|
|
160
|
+
if (!callsOf.has(name)) return false; // kernel or unknown
|
|
161
|
+
visiting.add(name);
|
|
162
|
+
let ok = true;
|
|
163
|
+
for (const callee of callsOf.get(name)) {
|
|
164
|
+
if (!isFinite(callee, visiting)) {
|
|
165
|
+
ok = false;
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
visiting.delete(name);
|
|
170
|
+
if (visiting.size === 0 || ok) finiteCache.set(name, ok);
|
|
171
|
+
return ok;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const hasDirectSelf = (name) => callsOf.get(name)?.has(name) || false;
|
|
175
|
+
|
|
176
|
+
// Count max self-calls along any single execution path (exclude branching recursion!)
|
|
177
|
+
const maxSelfCalls = (stmts, selfName) => {
|
|
178
|
+
let sum = 0;
|
|
179
|
+
for (const s of stmts || []) {
|
|
180
|
+
if (s.op === "spawn" && s.target === selfName) sum += 1;
|
|
181
|
+
else if (s.op === "switch") {
|
|
182
|
+
let best = 0;
|
|
183
|
+
for (const a of s.arms) best = Math.max(best, maxSelfCalls(a.body, selfName));
|
|
184
|
+
if (s.defaultBody) best = Math.max(best, maxSelfCalls(s.defaultBody, selfName));
|
|
185
|
+
sum += best;
|
|
186
|
+
} else if (s.op === "spec") {
|
|
187
|
+
let best = 0;
|
|
188
|
+
for (const b of s.branches) best = Math.max(best, maxSelfCalls(b.body, selfName));
|
|
189
|
+
sum += best;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return sum;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
return { callsOf, isFinite, hasDirectSelf, maxSelfCalls };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Check if a leaf schema is a finite unit-only union enum (2..8 states, all payloads unit).
|
|
200
|
+
*/
|
|
201
|
+
function getUnitEnumInfo(plist) {
|
|
202
|
+
const [kind, edges] = plist[0];
|
|
203
|
+
if (kind !== "closed-union" || edges.length < 2 || edges.length > 8) return null;
|
|
204
|
+
for (const [, target] of edges) {
|
|
205
|
+
if (!isUnitSchema(plist, target)) return null;
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
states: edges.length,
|
|
209
|
+
width: choiceWidth(edges.length),
|
|
210
|
+
tags: edges.map(([t]) => t),
|
|
211
|
+
tagToOrd: new Map(edges.map(([t], i) => [t, i]))
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Check if a leaf schema is a self-recursive LIFO bit-stackable union (e.g. `$bits = { 0: $bits, 1: $bits, _: unit }`),
|
|
217
|
+
* with 1 terminal `unit` tag and `2^k` (specifically 2) self-recursive tags!
|
|
218
|
+
*/
|
|
219
|
+
function getBitStackSchemaInfo(plist) {
|
|
220
|
+
const [kind, edges] = plist[0];
|
|
221
|
+
if (kind !== "closed-union" || edges.length < 2 || edges.length > 5) return null;
|
|
222
|
+
const termTags = [];
|
|
223
|
+
const recTags = [];
|
|
224
|
+
for (let i = 0; i < edges.length; i++) {
|
|
225
|
+
const [tag, target] = edges[i];
|
|
226
|
+
if (isUnitSchema(plist, target)) termTags.push({ tag, ord: i });
|
|
227
|
+
else if (schemasEquivalent(plist, 0, plist, target)) recTags.push({ tag, ord: i });
|
|
228
|
+
else return null;
|
|
229
|
+
}
|
|
230
|
+
if (termTags.length !== 1) return null;
|
|
231
|
+
if (recTags.length !== 1 && recTags.length !== 2) return null;
|
|
232
|
+
const tagWidth = choiceWidth(edges.length);
|
|
233
|
+
const stackBitWidth = recTags.length === 1 ? 1 : 1; // 1 bit per pushed recTag (0 or 1)
|
|
234
|
+
return {
|
|
235
|
+
tagWidth,
|
|
236
|
+
termTag: termTags[0].tag,
|
|
237
|
+
termOrd: termTags[0].ord,
|
|
238
|
+
recTags,
|
|
239
|
+
recTagToBit: new Map(recTags.map((r, i) => [r.tag, i])),
|
|
240
|
+
bitToRecTag: recTags.map((r) => r),
|
|
241
|
+
stackBitWidth
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Fuse eligible procedures in a concrete `mono` kTVM module into single-node
|
|
247
|
+
* compiled `kernel`s (FSM, tail-loop, TMC streaming, register-promoted, and
|
|
248
|
+
* virtual-stack kernels).
|
|
249
|
+
*/
|
|
250
|
+
export function fuseKernels(
|
|
251
|
+
mod,
|
|
252
|
+
{
|
|
253
|
+
maxDecisionNodes = 192,
|
|
254
|
+
maxEvalSteps = 3000,
|
|
255
|
+
maxInlineDepth = 16,
|
|
256
|
+
maxUnionTags = 12,
|
|
257
|
+
enableVirtualStack = true
|
|
258
|
+
} = {}
|
|
259
|
+
) {
|
|
260
|
+
if (mod.layer !== "mono") {
|
|
261
|
+
throw new Error("fuseKernels requires a concrete 'mono' kTVM module");
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const schemaDecls = new Map((mod.schemas || []).map((s) => [s.name, s]));
|
|
265
|
+
const procMap = new Map((mod.procs || []).map((p) => [p.name, p]));
|
|
266
|
+
const plistCache = new Map();
|
|
267
|
+
|
|
268
|
+
function resolvePlist(expr) {
|
|
269
|
+
const key = JSON.stringify(expr);
|
|
270
|
+
if (!plistCache.has(key)) {
|
|
271
|
+
plistCache.set(key, mooreMinimize(compileSchemaExprToPlist(expr, schemaDecls, { allowOpen: false }), 0).plist);
|
|
272
|
+
}
|
|
273
|
+
return plistCache.get(key);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Deduplicated schema interning for any new leaf schemas needed by kernel ports
|
|
277
|
+
const emittedSchemas = cloneAst(mod.schemas || []);
|
|
278
|
+
const schemaByMoore = new Map();
|
|
279
|
+
for (const s of emittedSchemas) {
|
|
280
|
+
const pl = resolvePlist(S.ref(s.name));
|
|
281
|
+
schemaByMoore.set(mooreMinimize(pl, 0).key, { expr: S.ref(s.name), plist: pl });
|
|
282
|
+
}
|
|
283
|
+
let schemaSeq = 0;
|
|
284
|
+
|
|
285
|
+
function internSchemaExpr(plist, hint = "K") {
|
|
286
|
+
const min = mooreMinimize(plist, 0);
|
|
287
|
+
if (isUnitSchema(min.plist, 0)) return S.unit();
|
|
288
|
+
if (schemaByMoore.has(min.key)) return schemaByMoore.get(min.key).expr;
|
|
289
|
+
const prefix = `$${sanitize(hint)}_k${schemaSeq++}`;
|
|
290
|
+
const { decls, rootExpr } = plistToSchemaAst(min.plist, prefix);
|
|
291
|
+
for (const d of decls) {
|
|
292
|
+
emittedSchemas.push(d);
|
|
293
|
+
schemaDecls.set(d.name, d);
|
|
294
|
+
}
|
|
295
|
+
schemaByMoore.set(min.key, { expr: rootExpr, plist: min.plist });
|
|
296
|
+
return rootExpr;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const cg = analyzeProcCallGraph(mod);
|
|
300
|
+
const emittedKernels = cloneAst(mod.kernels || []);
|
|
301
|
+
const existingKernelNames = new Set(emittedKernels.map((k) => k.name));
|
|
302
|
+
const newProcs = [];
|
|
303
|
+
const helperProcs = [];
|
|
304
|
+
|
|
305
|
+
const stats = {
|
|
306
|
+
fusedFSMs: 0,
|
|
307
|
+
fusedLoops: 0,
|
|
308
|
+
tmcLoops: 0,
|
|
309
|
+
registerPromotions: 0,
|
|
310
|
+
stackKernels: 0,
|
|
311
|
+
skippedWideOrComplex: 0
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
let helperSeq = 0;
|
|
315
|
+
|
|
316
|
+
// Attempt to fuse each eligible procedure
|
|
317
|
+
for (const proc of mod.procs || []) {
|
|
318
|
+
// Only fuse single-input single-output procs (or multi-port procs with <= 4 leaves)
|
|
319
|
+
const isFin = cg.isFinite(proc.name);
|
|
320
|
+
const hasSelf = cg.hasDirectSelf(proc.name);
|
|
321
|
+
if (!isFin && !hasSelf) {
|
|
322
|
+
newProcs.push(cloneAst(proc));
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (hasSelf && (proc.attrs?.includes("branching") || cg.maxSelfCalls(proc.body, proc.name) > 1)) {
|
|
326
|
+
newProcs.push(cloneAst(proc));
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
// Don't fuse trivial 1-statement `splice`/`exec` wrappers
|
|
330
|
+
if (proc.body.length <= 2 && proc.body.every((s) => s.op === "splice" || s.op === "exec" || s.op === "const_unit")) {
|
|
331
|
+
newProcs.push(cloneAst(proc));
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const compiled = trySymbolicFuseProc(proc, isFin, hasSelf);
|
|
336
|
+
if (!compiled) {
|
|
337
|
+
stats.skippedWideOrComplex += 1;
|
|
338
|
+
newProcs.push(cloneAst(proc));
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const emitted = emitKernelFromDecisionDag(proc, compiled);
|
|
343
|
+
if (!emitted) {
|
|
344
|
+
stats.skippedWideOrComplex += 1;
|
|
345
|
+
newProcs.push(cloneAst(proc));
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
emittedKernels.push(emitted.kernel);
|
|
350
|
+
newProcs.push(emitted.wrapperProc);
|
|
351
|
+
if (emitted.fallbackProc) helperProcs.push(emitted.fallbackProc);
|
|
352
|
+
|
|
353
|
+
if (compiled.isLoop) {
|
|
354
|
+
stats.fusedLoops += 1;
|
|
355
|
+
if (compiled.hasTmcEmit) stats.tmcLoops += 1;
|
|
356
|
+
stats.registerPromotions += emitted.promotedRegCount;
|
|
357
|
+
if (emitted.hasVirtualStack) stats.stackKernels += 1;
|
|
358
|
+
} else {
|
|
359
|
+
stats.fusedFSMs += 1;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// --- Core Symbolic Evaluator over Concrete `kTVM` `proc` DAG ---
|
|
364
|
+
|
|
365
|
+
function trySymbolicFuseProc(proc, isFinite, hasSelf) {
|
|
366
|
+
const inPortPlists = proc.inputs.map((p) => resolvePlist(p.schema));
|
|
367
|
+
const outPortPlists = proc.outputs.map((p) => resolvePlist(p.schema));
|
|
368
|
+
|
|
369
|
+
const inLeaves = [];
|
|
370
|
+
const inPortLeafRanges = [];
|
|
371
|
+
for (let i = 0; i < proc.inputs.length; i++) {
|
|
372
|
+
const start = inLeaves.length;
|
|
373
|
+
const leaves = flattenLeaves(inPortPlists[i], 0, proc.inputs.length === 1 ? [] : [proc.inputs[i].name.slice(1)]);
|
|
374
|
+
inLeaves.push(...leaves);
|
|
375
|
+
inPortLeafRanges.push({ start, count: leaves.length });
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const outLeaves = [];
|
|
379
|
+
for (let i = 0; i < proc.outputs.length; i++) {
|
|
380
|
+
outLeaves.push(...flattenLeaves(outPortPlists[i], 0, proc.outputs.length === 1 ? [] : [proc.outputs[i].name.slice(1)]));
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const P = inLeaves.length;
|
|
384
|
+
const Q = outLeaves.length;
|
|
385
|
+
if (P === 0 || Q === 0 || P > 6 || Q > 4) return null;
|
|
386
|
+
|
|
387
|
+
// Bail early on wide-alphabet schemas (`ascii[]`/`unicode[]`)
|
|
388
|
+
for (const l of inLeaves) {
|
|
389
|
+
if (l.plist[0][0] === "closed-union" && l.plist[0][1].length > maxUnionTags) {
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
let nodeIdSeq = 0;
|
|
395
|
+
let evalSteps = 0;
|
|
396
|
+
const dnodeById = new Map();
|
|
397
|
+
const dnodeByKey = new Map();
|
|
398
|
+
const plistKeyCache = new WeakMap();
|
|
399
|
+
const FAIL_NODE = { id: -1, kind: "fail" };
|
|
400
|
+
let hasLoopLeaf = false;
|
|
401
|
+
let hasTmcEmit = false;
|
|
402
|
+
let hasFail = false;
|
|
403
|
+
|
|
404
|
+
const getPlKey = (pl) => {
|
|
405
|
+
if (!pl) return "null";
|
|
406
|
+
let k = plistKeyCache.get(pl);
|
|
407
|
+
if (k === undefined) {
|
|
408
|
+
k = mooreMinimize(pl, 0).key;
|
|
409
|
+
plistKeyCache.set(pl, k);
|
|
410
|
+
}
|
|
411
|
+
return k;
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
const allocDNode = (obj, canonicalKey = null) => {
|
|
415
|
+
if (canonicalKey && dnodeByKey.has(canonicalKey)) {
|
|
416
|
+
return dnodeByKey.get(canonicalKey);
|
|
417
|
+
}
|
|
418
|
+
if (nodeIdSeq >= maxDecisionNodes) bail("maxDecisionNodes");
|
|
419
|
+
const n = { id: nodeIdSeq++, ...obj };
|
|
420
|
+
dnodeById.set(n.id, n);
|
|
421
|
+
if (canonicalKey) dnodeByKey.set(canonicalKey, n);
|
|
422
|
+
return n;
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const tick = () => {
|
|
426
|
+
if (++evalSteps > maxEvalSteps) bail("maxEvalSteps");
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const inLeafIsUnitEnum = inLeaves.map((l) => Boolean(getUnitEnumInfo(l.plist)));
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Compile an output leaf SVal into:
|
|
433
|
+
* - `{ kind: "const", tokens: [{ tag, ord, width }] }`
|
|
434
|
+
* - `{ kind: "splice", prefix: [{ tag, ord, width }], p, consumeCount, tailPlist }`
|
|
435
|
+
*
|
|
436
|
+
* When `forLoop === true`, `port(p, depth)` shifts ONLY `depth` actually consumed
|
|
437
|
+
* tokens (leaving peeked-but-unconsumed tokens untouched in `%p`) and keeps `prefix`
|
|
438
|
+
* strictly equal to explicitly `wrap`ped tags.
|
|
439
|
+
*/
|
|
440
|
+
function compileLeafOutExpr(v, st, expectedPlist, { forLoop = false } = {}) {
|
|
441
|
+
const prefix = [];
|
|
442
|
+
let cur = v;
|
|
443
|
+
while (cur.kind === "cons") {
|
|
444
|
+
const info = unionTagInfo(cur.plist, cur.nodeId, cur.tag);
|
|
445
|
+
if (!info) bail("cons-tag-info");
|
|
446
|
+
prefix.push({ tag: cur.tag, ord: info.ordinal, width: info.width, nextPlist: subPlist(cur.plist, info.targetId) });
|
|
447
|
+
cur = cur.tail;
|
|
448
|
+
}
|
|
449
|
+
if (cur.kind === "unit") {
|
|
450
|
+
return { kind: "const", tokens: prefix };
|
|
451
|
+
}
|
|
452
|
+
if (cur.kind === "port") {
|
|
453
|
+
const { p, depth } = cur;
|
|
454
|
+
if (forLoop) {
|
|
455
|
+
// Leave any unconsumed peeked tags `st.peeks[p].slice(depth)` in `%p`!
|
|
456
|
+
let checkPl = expectedPlist;
|
|
457
|
+
let checkNid = 0;
|
|
458
|
+
for (const tok of prefix) {
|
|
459
|
+
const info = unionTagInfo(checkPl, checkNid, tok.tag);
|
|
460
|
+
if (!info) bail("loop-prefix-schema");
|
|
461
|
+
checkNid = info.targetId;
|
|
462
|
+
}
|
|
463
|
+
const curTailPl = subPlist(cur.plist, cur.nodeId);
|
|
464
|
+
if (!schemasEquivalent(curTailPl, 0, checkPl, checkNid)) bail("loop-tail-schema");
|
|
465
|
+
return {
|
|
466
|
+
kind: "splice",
|
|
467
|
+
prefix,
|
|
468
|
+
p,
|
|
469
|
+
consumeCount: depth,
|
|
470
|
+
tailPlist: curTailPl
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Emit leaf: re-emit unconsumed peeked tags in order so all `st.peeks[p]` can be shifted cleanly.
|
|
475
|
+
const unconsumed = [];
|
|
476
|
+
let curPl = cur.plist;
|
|
477
|
+
let curNid = cur.nodeId;
|
|
478
|
+
for (let d = depth; d < st.peeks[p].length; d++) {
|
|
479
|
+
const t = st.peeks[p][d];
|
|
480
|
+
const info = unionTagInfo(curPl, curNid, t);
|
|
481
|
+
if (!info) bail("emit-unconsumed-info");
|
|
482
|
+
unconsumed.push({ tag: t, ord: info.ordinal, width: info.width, nextPlist: subPlist(curPl, info.targetId) });
|
|
483
|
+
curNid = info.targetId;
|
|
484
|
+
}
|
|
485
|
+
const tailPlist = subPlist(curPl, curNid);
|
|
486
|
+
if (st.drained[p] || isUnitSchema(tailPlist, 0)) {
|
|
487
|
+
// Port p has already reached `unit` -> mark for unit drain and emit constant!
|
|
488
|
+
st.mustDrainUnit[p] = true;
|
|
489
|
+
return { kind: "const", tokens: [...prefix, ...unconsumed] };
|
|
490
|
+
}
|
|
491
|
+
// Verify tail schema matches expected suffix schema (after prefix + unconsumed)
|
|
492
|
+
const allPrefix = [...prefix, ...unconsumed];
|
|
493
|
+
let checkPl = expectedPlist;
|
|
494
|
+
let checkNid = 0;
|
|
495
|
+
for (const tok of allPrefix) {
|
|
496
|
+
const info = unionTagInfo(checkPl, checkNid, tok.tag);
|
|
497
|
+
if (!info) bail("emit-prefix-schema");
|
|
498
|
+
checkNid = info.targetId;
|
|
499
|
+
}
|
|
500
|
+
if (!schemasEquivalent(tailPlist, 0, checkPl, checkNid)) bail("emit-tail-schema");
|
|
501
|
+
// Kernel `push_bits` does not advance `dst.prodSchema`, so `splice` after non-empty prefix
|
|
502
|
+
// requires `tailPlist` to remain schema-equivalent to `expectedPlist` (true for all recursive streams!).
|
|
503
|
+
if (allPrefix.length > 0 && !schemasEquivalent(tailPlist, 0, expectedPlist, 0)) {
|
|
504
|
+
bail("emit-nonrec-splice");
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
kind: "splice",
|
|
508
|
+
prefix: allPrefix,
|
|
509
|
+
p,
|
|
510
|
+
consumeCount: st.peeks[p].length,
|
|
511
|
+
tailPlist
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
bail("leaf-out-expr");
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function markSValDrained(v, st) {
|
|
518
|
+
if (!v || v.kind === "unit") return;
|
|
519
|
+
if (v.kind === "cons") {
|
|
520
|
+
markSValDrained(v.tail, st);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
if (v.kind === "bundle") {
|
|
524
|
+
for (const c of v.fields.values()) markSValDrained(c, st);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if (v.kind === "port") {
|
|
528
|
+
const { p, depth } = v;
|
|
529
|
+
let curPl = v.plist;
|
|
530
|
+
let curNid = v.nodeId;
|
|
531
|
+
for (let d = depth; d < st.peeks[p].length; d++) {
|
|
532
|
+
const info = unionTagInfo(curPl, curNid, st.peeks[p][d]);
|
|
533
|
+
if (!info) bail();
|
|
534
|
+
curNid = info.targetId;
|
|
535
|
+
}
|
|
536
|
+
const remPl = subPlist(curPl, curNid);
|
|
537
|
+
if (isUnitSchema(remPl, 0)) {
|
|
538
|
+
st.mustDrainUnit[p] = true;
|
|
539
|
+
} else {
|
|
540
|
+
st.mustDrainFull[p] = remPl;
|
|
541
|
+
}
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
bail();
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function makeEmitLeaf(outVals, st) {
|
|
548
|
+
const outLeafVals = [];
|
|
549
|
+
for (const ov of outVals) svalToLeaves(ov, outLeafVals);
|
|
550
|
+
if (outLeafVals.length !== Q) bail();
|
|
551
|
+
|
|
552
|
+
const stCopy = cloneSymState(st);
|
|
553
|
+
const outExprs = outLeafVals.map((lv, q) => compileLeafOutExpr(lv, stCopy, outLeaves[q].plist));
|
|
554
|
+
|
|
555
|
+
// Verify no input port is spliced twice across outputs (SPSC linearity!)
|
|
556
|
+
const splicedPorts = new Set();
|
|
557
|
+
for (const e of outExprs) {
|
|
558
|
+
if (e.kind === "splice") {
|
|
559
|
+
if (splicedPorts.has(e.p)) bail();
|
|
560
|
+
splicedPorts.add(e.p);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Compute exact shifts and remaining drains per input port
|
|
565
|
+
const shifts = new Array(P).fill(0);
|
|
566
|
+
const shiftTokens = Array.from({ length: P }, () => []);
|
|
567
|
+
const drainGuards = new Array(P).fill(null);
|
|
568
|
+
|
|
569
|
+
for (let p = 0; p < P; p++) {
|
|
570
|
+
let curPl = inLeaves[p].plist;
|
|
571
|
+
let curNid = 0;
|
|
572
|
+
for (const t of stCopy.peeks[p]) {
|
|
573
|
+
const info = unionTagInfo(curPl, curNid, t);
|
|
574
|
+
if (!info) bail();
|
|
575
|
+
shifts[p] += info.width;
|
|
576
|
+
shiftTokens[p].push({ width: info.width, nextPlist: subPlist(curPl, info.targetId) });
|
|
577
|
+
curNid = info.targetId;
|
|
578
|
+
}
|
|
579
|
+
const remPl = subPlist(curPl, curNid);
|
|
580
|
+
if (!splicedPorts.has(p)) {
|
|
581
|
+
if (stCopy.mustDrainFull[p]) drainGuards[p] = stCopy.mustDrainFull[p];
|
|
582
|
+
else if (stCopy.mustDrainUnit[p] || isUnitSchema(remPl, 0)) drainGuards[p] = remPl;
|
|
583
|
+
else drainGuards[p] = remPl; // Ensure every unspliced input port is drained cleanly!
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const emitKey = `E|${outExprs.map((e) =>
|
|
588
|
+
e.kind === "const"
|
|
589
|
+
? `C:${e.tokens.map((t) => `${t.ord}/${t.width}`).join(",")}`
|
|
590
|
+
: `S:${e.p}:${e.prefix.map((t) => `${t.ord}/${t.width}`).join(",")}`
|
|
591
|
+
).join(";")}|${shiftTokens.map((ts) => ts.map((t) => `${t.width}:${getPlKey(t.nextPlist)}`).join(",")).join(";")}|${drainGuards.map((d) => getPlKey(d)).join(",")}`;
|
|
592
|
+
|
|
593
|
+
return allocDNode({
|
|
594
|
+
kind: "emit",
|
|
595
|
+
outExprs,
|
|
596
|
+
shifts,
|
|
597
|
+
shiftTokens,
|
|
598
|
+
drainGuards
|
|
599
|
+
}, emitKey);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function makeLoopLeaf(outVals, st) {
|
|
603
|
+
if (!st.selfCall) bail("no-self-call");
|
|
604
|
+
const nextInLeafVals = [];
|
|
605
|
+
for (const nv of st.selfCall.nextArgs) svalToLeaves(nv, nextInLeafVals);
|
|
606
|
+
if (nextInLeafVals.length !== P) bail("self-arity");
|
|
607
|
+
|
|
608
|
+
// Check TMC output wrapping around `selfOut(q)`
|
|
609
|
+
const outLeafVals = [];
|
|
610
|
+
for (const ov of outVals) svalToLeaves(ov, outLeafVals);
|
|
611
|
+
if (outLeafVals.length !== Q) bail("loop-out-arity");
|
|
612
|
+
|
|
613
|
+
const outEmitPrefixes = new Array(Q).fill(null);
|
|
614
|
+
for (let q = 0; q < Q; q++) {
|
|
615
|
+
const prefix = [];
|
|
616
|
+
let cur = outLeafVals[q];
|
|
617
|
+
while (cur.kind === "cons") {
|
|
618
|
+
const info = unionTagInfo(cur.plist, cur.nodeId, cur.tag);
|
|
619
|
+
if (!info) bail("tmc-prefix-info");
|
|
620
|
+
prefix.push({ tag: cur.tag, ord: info.ordinal, width: info.width });
|
|
621
|
+
cur = cur.tail;
|
|
622
|
+
}
|
|
623
|
+
if (cur.kind !== "selfOut" || cur.q !== q) bail("not-tmc-selfout");
|
|
624
|
+
if (prefix.length > 0) hasTmcEmit = true;
|
|
625
|
+
outEmitPrefixes[q] = prefix;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const stCopy = cloneSymState(st);
|
|
629
|
+
const nextExprs = nextInLeafVals.map((nv, p) =>
|
|
630
|
+
compileLeafOutExpr(nv, stCopy, inLeaves[p].plist, { forLoop: true })
|
|
631
|
+
);
|
|
632
|
+
|
|
633
|
+
// Terminal-keep equivalence: on non-unit-enum ports (e.g. `$bits`), if `p` was peeked
|
|
634
|
+
// all the way to terminal tag `t` (`st.drained[p] === true`, last peek === `t`) and the
|
|
635
|
+
// recursive call passes `const([t])` (e.g. `pop_lsb_bit` or `drop2` clamping at `_`),
|
|
636
|
+
// leaving `t` unshifted on `%p` (`consumeCount = st.peeks[p].length - 1`) is bit-exact!
|
|
637
|
+
for (let p = 0; p < P; p++) {
|
|
638
|
+
if (inLeafIsUnitEnum[p]) continue;
|
|
639
|
+
const ne = nextExprs[p];
|
|
640
|
+
if (
|
|
641
|
+
ne.kind === "const" &&
|
|
642
|
+
ne.tokens.length === 1 &&
|
|
643
|
+
stCopy.drained[p] &&
|
|
644
|
+
stCopy.peeks[p].length >= 1 &&
|
|
645
|
+
stCopy.peeks[p][stCopy.peeks[p].length - 1] === ne.tokens[0].tag
|
|
646
|
+
) {
|
|
647
|
+
const keepDepth = stCopy.peeks[p].length - 1;
|
|
648
|
+
let curPl = inLeaves[p].plist;
|
|
649
|
+
let curNid = 0;
|
|
650
|
+
let ok = true;
|
|
651
|
+
for (let d = 0; d < keepDepth; d++) {
|
|
652
|
+
const info = unionTagInfo(curPl, curNid, stCopy.peeks[p][d]);
|
|
653
|
+
if (!info) { ok = false; break; }
|
|
654
|
+
curNid = info.targetId;
|
|
655
|
+
}
|
|
656
|
+
if (ok && schemasEquivalent(curPl, curNid, inLeaves[p].plist, 0)) {
|
|
657
|
+
nextExprs[p] = {
|
|
658
|
+
kind: "splice",
|
|
659
|
+
prefix: [],
|
|
660
|
+
p,
|
|
661
|
+
consumeCount: keepDepth,
|
|
662
|
+
tailPlist: inLeaves[p].plist
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// Verify every non-constant port maps to itself (no port permutation in-place)
|
|
669
|
+
for (let p = 0; p < P; p++) {
|
|
670
|
+
const ne = nextExprs[p];
|
|
671
|
+
if (ne.kind === "splice" && ne.p !== p) bail("port-permute");
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Record any non-unit `mustDrainFull[p]` where port `p` is NOT kept live in `nextExprs[p]`
|
|
675
|
+
// (a `drain` on a `tee`'d copy of a still-live port `p` is redundant because `p` remains owned!).
|
|
676
|
+
const droppedDrainFull = new Array(P).fill(false);
|
|
677
|
+
for (let p = 0; p < P; p++) {
|
|
678
|
+
if (st.mustDrainFull[p]) {
|
|
679
|
+
const ne = nextExprs[p];
|
|
680
|
+
const keptLive = ne.kind === "splice" && ne.p === p;
|
|
681
|
+
if (!keptLive) droppedDrainFull[p] = true;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// Compute exact bit shifts per port (ONLY `consumeCount` tokens for splice ports!)
|
|
686
|
+
const shifts = new Array(P).fill(0);
|
|
687
|
+
const shiftTokens = Array.from({ length: P }, () => []);
|
|
688
|
+
for (let p = 0; p < P; p++) {
|
|
689
|
+
const ne = nextExprs[p];
|
|
690
|
+
const count = ne.kind === "splice" ? ne.consumeCount : 0;
|
|
691
|
+
let curPl = inLeaves[p].plist;
|
|
692
|
+
let curNid = 0;
|
|
693
|
+
for (let d = 0; d < count; d++) {
|
|
694
|
+
const t = stCopy.peeks[p][d];
|
|
695
|
+
const info = unionTagInfo(curPl, curNid, t);
|
|
696
|
+
if (!info) bail("loop-shift-info");
|
|
697
|
+
shifts[p] += info.width;
|
|
698
|
+
shiftTokens[p].push({ width: info.width, nextPlist: subPlist(curPl, info.targetId) });
|
|
699
|
+
curNid = info.targetId;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const loopKey = `L|${nextExprs.map((e) =>
|
|
704
|
+
e.kind === "const"
|
|
705
|
+
? `C:${e.tokens.map((t) => `${t.ord}/${t.width}`).join(",")}`
|
|
706
|
+
: `S:${e.p}:${e.consumeCount}:${e.prefix.map((t) => `${t.ord}/${t.width}`).join(",")}`
|
|
707
|
+
).join(";")}|${outEmitPrefixes.map((ps) => ps.map((t) => `${t.ord}/${t.width}`).join(",")).join(";")}|${shiftTokens.map((ts) => ts.map((t) => `${t.width}:${getPlKey(t.nextPlist)}`).join(",")).join(";")}|${droppedDrainFull.map((b) => (b ? "1" : "0")).join("")}`;
|
|
708
|
+
|
|
709
|
+
hasLoopLeaf = true;
|
|
710
|
+
return allocDNode({
|
|
711
|
+
kind: "loop",
|
|
712
|
+
nextExprs,
|
|
713
|
+
outEmitPrefixes,
|
|
714
|
+
shifts,
|
|
715
|
+
shiftTokens,
|
|
716
|
+
droppedDrainFull
|
|
717
|
+
}, loopKey);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Symbolically inspect a single union SVal `val`, calling `onTag(tag, payloadVal, nextSt)`
|
|
722
|
+
* or `onFail(st)` if impossible.
|
|
723
|
+
*/
|
|
724
|
+
function inspectUnion(val, st, onTag, onFail) {
|
|
725
|
+
tick();
|
|
726
|
+
if (val.kind === "cons") {
|
|
727
|
+
return onTag(val.tag, val.tail, st);
|
|
728
|
+
}
|
|
729
|
+
if (val.kind === "port") {
|
|
730
|
+
const { p, depth, plist, nodeId } = val;
|
|
731
|
+
const [kind, edges] = plist[nodeId];
|
|
732
|
+
if (kind !== "closed-union") bail();
|
|
733
|
+
if (edges.length > maxUnionTags) bail();
|
|
734
|
+
|
|
735
|
+
if (depth < st.peeks[p].length) {
|
|
736
|
+
const tag = st.peeks[p][depth];
|
|
737
|
+
const info = unionTagInfo(plist, nodeId, tag);
|
|
738
|
+
if (!info) return onFail(st);
|
|
739
|
+
const nextPl = subPlist(plist, info.targetId);
|
|
740
|
+
const payload = isUnitSchema(nextPl, 0)
|
|
741
|
+
? { kind: "unit" }
|
|
742
|
+
: { kind: "port", p, depth: depth + 1, plist: nextPl, nodeId: 0 };
|
|
743
|
+
return onTag(tag, payload, st);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// Singleton 1-tag union (`width === 0`): no peek bits needed, step deterministically!
|
|
747
|
+
if (edges.length === 1) {
|
|
748
|
+
const [tag, targetId] = edges[0];
|
|
749
|
+
const nextSt = cloneSymState(st);
|
|
750
|
+
nextSt.peeks[p].push(tag);
|
|
751
|
+
const nextPl = subPlist(plist, targetId);
|
|
752
|
+
if (isUnitSchema(nextPl, 0)) nextSt.drained[p] = true;
|
|
753
|
+
const payload = isUnitSchema(nextPl, 0)
|
|
754
|
+
? { kind: "unit" }
|
|
755
|
+
: { kind: "port", p, depth: depth + 1, plist: nextPl, nodeId: 0 };
|
|
756
|
+
return onTag(tag, payload, nextSt);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// Branch decision node `peek(p, depth)`!
|
|
760
|
+
const cases = {};
|
|
761
|
+
let offsetBits = 0;
|
|
762
|
+
{
|
|
763
|
+
let cPl = inLeaves[p].plist;
|
|
764
|
+
let cNid = 0;
|
|
765
|
+
for (const t of st.peeks[p]) {
|
|
766
|
+
const inf = unionTagInfo(cPl, cNid, t);
|
|
767
|
+
offsetBits += inf.width;
|
|
768
|
+
cNid = inf.targetId;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
const width = choiceWidth(edges.length);
|
|
772
|
+
for (let ord = 0; ord < edges.length; ord++) {
|
|
773
|
+
const [tag, targetId] = edges[ord];
|
|
774
|
+
const nextSt = cloneSymState(st);
|
|
775
|
+
nextSt.peeks[p].push(tag);
|
|
776
|
+
const nextPl = subPlist(plist, targetId);
|
|
777
|
+
if (isUnitSchema(nextPl, 0)) nextSt.drained[p] = true;
|
|
778
|
+
const payload = isUnitSchema(nextPl, 0)
|
|
779
|
+
? { kind: "unit" }
|
|
780
|
+
: { kind: "port", p, depth: depth + 1, plist: nextPl, nodeId: 0 };
|
|
781
|
+
cases[tag] = {
|
|
782
|
+
ord,
|
|
783
|
+
bits: toBitsLit(ord, width),
|
|
784
|
+
node: onTag(tag, payload, nextSt)
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
// Redundant-peek elimination: if all tags lead to the exact same canonical DNode,
|
|
788
|
+
// collapse this peek node directly (only skip bit-validation when the alphabet fills
|
|
789
|
+
// all `2^width` codes OR when the collapsed sub-DAG never shifts `p` past `depth`!).
|
|
790
|
+
const caseVals = Object.values(cases);
|
|
791
|
+
const firstTarget = caseVals[0]?.node;
|
|
792
|
+
if (firstTarget && caseVals.every((c) => c.node === firstTarget)) {
|
|
793
|
+
const isFullPowerOf2 = edges.length === (1 << width);
|
|
794
|
+
const shiftsAtOrPastDepth = (n, seen = new Set()) => {
|
|
795
|
+
if (!n || n === FAIL_NODE || seen.has(n.id)) return false;
|
|
796
|
+
seen.add(n.id);
|
|
797
|
+
if (n.kind === "peek") {
|
|
798
|
+
if (n.p === p && n.depth >= depth) return true;
|
|
799
|
+
return Object.values(n.cases).some((c) => shiftsAtOrPastDepth(c.node, seen));
|
|
800
|
+
}
|
|
801
|
+
return (n.shiftTokens && n.shiftTokens[p] && n.shiftTokens[p].length > depth);
|
|
802
|
+
};
|
|
803
|
+
if (isFullPowerOf2 || !shiftsAtOrPastDepth(firstTarget)) {
|
|
804
|
+
return firstTarget;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const peekKey = `P|${p}|${depth}|${offsetBits}|${width}|${caseVals.map((c) => `${c.bits}:${c.node.id}`).join(",")}`;
|
|
809
|
+
return allocDNode({
|
|
810
|
+
kind: "peek",
|
|
811
|
+
p,
|
|
812
|
+
depth,
|
|
813
|
+
offsetBits,
|
|
814
|
+
width,
|
|
815
|
+
plist,
|
|
816
|
+
nodeId,
|
|
817
|
+
cases
|
|
818
|
+
}, peekKey);
|
|
819
|
+
}
|
|
820
|
+
bail();
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Symbolically execute a block of kTVM statements in `env` with explicit CPS
|
|
825
|
+
* `(onDone(finalEnv, finalSt), onFail(st))`.
|
|
826
|
+
*/
|
|
827
|
+
function symExecBlock(stmts, idx, env, st, inlineDepth, onDone, onFail) {
|
|
828
|
+
tick();
|
|
829
|
+
if (idx >= stmts.length) {
|
|
830
|
+
return onDone(env, st);
|
|
831
|
+
}
|
|
832
|
+
const s = stmts[idx];
|
|
833
|
+
const cont = (nextEnv, nextSt) => symExecBlock(stmts, idx + 1, nextEnv, nextSt, inlineDepth, onDone, onFail);
|
|
834
|
+
|
|
835
|
+
switch (s.op) {
|
|
836
|
+
case "chan": {
|
|
837
|
+
const nextEnv = new Map(env);
|
|
838
|
+
nextEnv.set(s.name, { __schema: resolvePlist(s.schema) });
|
|
839
|
+
return cont(nextEnv, st);
|
|
840
|
+
}
|
|
841
|
+
case "barrier":
|
|
842
|
+
return cont(env, st);
|
|
843
|
+
case "const_unit": {
|
|
844
|
+
const nextEnv = new Map(env);
|
|
845
|
+
nextEnv.set(s.dst, { kind: "unit" });
|
|
846
|
+
return cont(nextEnv, st);
|
|
847
|
+
}
|
|
848
|
+
case "splice": {
|
|
849
|
+
const nextEnv = new Map(env);
|
|
850
|
+
nextEnv.set(s.dst, env.get(s.src));
|
|
851
|
+
return cont(nextEnv, st);
|
|
852
|
+
}
|
|
853
|
+
case "gate": {
|
|
854
|
+
const nextEnv = new Map(env);
|
|
855
|
+
nextEnv.set(s.dst, env.get(s.src));
|
|
856
|
+
return cont(nextEnv, st);
|
|
857
|
+
}
|
|
858
|
+
case "drain": {
|
|
859
|
+
const nextSt = cloneSymState(st);
|
|
860
|
+
markSValDrained(env.get(s.src), nextSt);
|
|
861
|
+
return cont(env, nextSt);
|
|
862
|
+
}
|
|
863
|
+
case "tee": {
|
|
864
|
+
const val = env.get(s.src);
|
|
865
|
+
const nextEnv = new Map(env);
|
|
866
|
+
for (const d of s.dsts) nextEnv.set(d, val);
|
|
867
|
+
return cont(nextEnv, st);
|
|
868
|
+
}
|
|
869
|
+
case "mux": {
|
|
870
|
+
const pl = resolvePlist(s.schema);
|
|
871
|
+
const fields = new Map();
|
|
872
|
+
const pf = productFields(pl, 0);
|
|
873
|
+
const byLbl = new Map(s.fields.map((f) => [f.label, env.get(f.name)]));
|
|
874
|
+
for (const f of pf) fields.set(f.label, byLbl.get(f.label));
|
|
875
|
+
const nextEnv = new Map(env);
|
|
876
|
+
nextEnv.set(s.dst, { kind: "bundle", fields, plist: pl });
|
|
877
|
+
return cont(nextEnv, st);
|
|
878
|
+
}
|
|
879
|
+
case "demux": {
|
|
880
|
+
const val = env.get(s.src);
|
|
881
|
+
if (!val || val.kind !== "bundle") bail();
|
|
882
|
+
const nextEnv = new Map(env);
|
|
883
|
+
for (const f of s.fields) nextEnv.set(f.name, val.fields.get(f.label));
|
|
884
|
+
return cont(nextEnv, st);
|
|
885
|
+
}
|
|
886
|
+
case "wrap": {
|
|
887
|
+
const dstMeta = env.get(s.dst);
|
|
888
|
+
const dstPl = dstMeta?.__schema || env.get(`__port_schema__${s.dst}`);
|
|
889
|
+
if (!dstPl) bail();
|
|
890
|
+
const nextEnv = new Map(env);
|
|
891
|
+
nextEnv.set(s.dst, { kind: "cons", tag: s.tag, tail: env.get(s.src), plist: dstPl, nodeId: 0 });
|
|
892
|
+
return cont(nextEnv, st);
|
|
893
|
+
}
|
|
894
|
+
case "match": {
|
|
895
|
+
const val = env.get(s.src);
|
|
896
|
+
return inspectUnion(
|
|
897
|
+
val,
|
|
898
|
+
st,
|
|
899
|
+
(tag, payload, nextSt) => {
|
|
900
|
+
if (tag !== s.tag) return onFail(nextSt);
|
|
901
|
+
const nextEnv = new Map(env);
|
|
902
|
+
nextEnv.set(s.dst, payload);
|
|
903
|
+
return cont(nextEnv, nextSt);
|
|
904
|
+
},
|
|
905
|
+
onFail
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
case "coerce": {
|
|
909
|
+
const sPl = resolvePlist(s.srcSchema);
|
|
910
|
+
const dPl = resolvePlist(s.dstSchema);
|
|
911
|
+
const val = env.get(s.src);
|
|
912
|
+
if (schemasEquivalent(sPl, 0, dPl, 0)) {
|
|
913
|
+
const nextEnv = new Map(env);
|
|
914
|
+
nextEnv.set(s.dst, val);
|
|
915
|
+
return cont(nextEnv, st);
|
|
916
|
+
}
|
|
917
|
+
// Re-tag known `cons` values (common in variant widening/narrowing!)
|
|
918
|
+
if (val.kind === "cons") {
|
|
919
|
+
const info = unionTagInfo(dPl, 0, val.tag);
|
|
920
|
+
if (!info) return onFail(st);
|
|
921
|
+
const nextEnv = new Map(env);
|
|
922
|
+
nextEnv.set(s.dst, { kind: "cons", tag: val.tag, tail: val.tail, plist: dPl, nodeId: 0 });
|
|
923
|
+
return cont(nextEnv, st);
|
|
924
|
+
}
|
|
925
|
+
bail();
|
|
926
|
+
}
|
|
927
|
+
case "switch": {
|
|
928
|
+
// Inspect all non-wildcard switch inputs sequentially!
|
|
929
|
+
const needed = [];
|
|
930
|
+
for (let j = 0; j < s.inputs.length; j++) {
|
|
931
|
+
if (s.arms.some((a) => a.patterns[j].kind === "tag")) needed.push(j);
|
|
932
|
+
}
|
|
933
|
+
const observedTags = new Array(s.inputs.length).fill(null);
|
|
934
|
+
|
|
935
|
+
const inspectNext = (k, curSt) => {
|
|
936
|
+
if (k >= needed.length) {
|
|
937
|
+
let chosen = null;
|
|
938
|
+
for (const arm of s.arms) {
|
|
939
|
+
let ok = true;
|
|
940
|
+
for (let j = 0; j < arm.patterns.length; j++) {
|
|
941
|
+
if (arm.patterns[j].kind === "tag" && observedTags[j] !== arm.patterns[j].tag) {
|
|
942
|
+
ok = false;
|
|
943
|
+
break;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (ok) {
|
|
947
|
+
chosen = arm.body;
|
|
948
|
+
break;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
if (!chosen) chosen = s.defaultBody;
|
|
952
|
+
if (!chosen) return onFail(curSt);
|
|
953
|
+
return symExecBlock(chosen, 0, env, curSt, inlineDepth, (armEnv, armSt) => cont(armEnv, armSt), onFail);
|
|
954
|
+
}
|
|
955
|
+
const j = needed[k];
|
|
956
|
+
return inspectUnion(
|
|
957
|
+
env.get(s.inputs[j]),
|
|
958
|
+
curSt,
|
|
959
|
+
(tag, _payload, nxtSt) => {
|
|
960
|
+
observedTags[j] = tag;
|
|
961
|
+
return inspectNext(k + 1, nxtSt);
|
|
962
|
+
},
|
|
963
|
+
onFail
|
|
964
|
+
);
|
|
965
|
+
};
|
|
966
|
+
return inspectNext(0, st);
|
|
967
|
+
}
|
|
968
|
+
case "spec": {
|
|
969
|
+
if (s.branches.length === 0) return onFail(st);
|
|
970
|
+
const tryBranch = (bIdx, curSt) => {
|
|
971
|
+
if (bIdx >= s.branches.length) return onFail(curSt);
|
|
972
|
+
const brEnv = new Map();
|
|
973
|
+
for (const v of s.inputs) brEnv.set(v, env.get(v));
|
|
974
|
+
for (const v of s.outputs) {
|
|
975
|
+
brEnv.set(v, env.get(v));
|
|
976
|
+
if (env.has(`__port_schema__${v}`)) brEnv.set(`__port_schema__${v}`, env.get(`__port_schema__${v}`));
|
|
977
|
+
}
|
|
978
|
+
return symExecBlock(
|
|
979
|
+
s.branches[bIdx].body,
|
|
980
|
+
0,
|
|
981
|
+
brEnv,
|
|
982
|
+
cloneSymState(curSt),
|
|
983
|
+
inlineDepth,
|
|
984
|
+
(outEnv, okSt) => {
|
|
985
|
+
const merged = new Map(env);
|
|
986
|
+
for (const v of s.outputs) merged.set(v, outEnv.get(v));
|
|
987
|
+
return cont(merged, okSt);
|
|
988
|
+
},
|
|
989
|
+
(failSt) => {
|
|
990
|
+
// Roll back local side effects of the failed speculative branch while preserving
|
|
991
|
+
// `peeks` and `drained` already committed by ancestor `peek` nodes along this path!
|
|
992
|
+
const rbSt = cloneSymState(curSt);
|
|
993
|
+
if (failSt) {
|
|
994
|
+
rbSt.peeks = failSt.peeks.map((a) => a.slice());
|
|
995
|
+
rbSt.drained = failSt.drained.slice();
|
|
996
|
+
}
|
|
997
|
+
return tryBranch(bIdx + 1, rbSt);
|
|
998
|
+
}
|
|
999
|
+
);
|
|
1000
|
+
};
|
|
1001
|
+
return tryBranch(0, st);
|
|
1002
|
+
}
|
|
1003
|
+
case "spawn": {
|
|
1004
|
+
// 1. Direct self-recursion -> tail-loop or TMC streaming loop!
|
|
1005
|
+
if (s.target === proc.name) {
|
|
1006
|
+
if (st.selfCall !== null || inlineDepth > 0) bail();
|
|
1007
|
+
const nextSt = cloneSymState(st);
|
|
1008
|
+
nextSt.selfCall = { nextArgs: s.inputs.map((v) => env.get(v)) };
|
|
1009
|
+
const nextEnv = new Map(env);
|
|
1010
|
+
const box = { next: 0 };
|
|
1011
|
+
for (let oi = 0; oi < s.outputs.length; oi++) {
|
|
1012
|
+
const outPl = outPortPlists[oi];
|
|
1013
|
+
nextEnv.set(s.outputs[oi], buildSelfOutSVal(outPl, 0, box));
|
|
1014
|
+
}
|
|
1015
|
+
return cont(nextEnv, nextSt);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// 2. Acyclic helper proc -> inline symbolically!
|
|
1019
|
+
const callee = procMap.get(s.target);
|
|
1020
|
+
if (callee && cg.isFinite(s.target) && inlineDepth < maxInlineDepth) {
|
|
1021
|
+
const subEnv = new Map();
|
|
1022
|
+
for (let i = 0; i < callee.inputs.length; i++) {
|
|
1023
|
+
subEnv.set(callee.inputs[i].name, env.get(s.inputs[i]));
|
|
1024
|
+
}
|
|
1025
|
+
for (let i = 0; i < callee.outputs.length; i++) {
|
|
1026
|
+
const oPl = resolvePlist(callee.outputs[i].schema);
|
|
1027
|
+
subEnv.set(callee.outputs[i].name, { __schema: oPl });
|
|
1028
|
+
subEnv.set(`__port_schema__${callee.outputs[i].name}`, oPl);
|
|
1029
|
+
}
|
|
1030
|
+
return symExecBlock(
|
|
1031
|
+
callee.body,
|
|
1032
|
+
0,
|
|
1033
|
+
subEnv,
|
|
1034
|
+
st,
|
|
1035
|
+
inlineDepth + 1,
|
|
1036
|
+
(doneEnv, doneSt) => {
|
|
1037
|
+
const nextEnv = new Map(env);
|
|
1038
|
+
for (let i = 0; i < s.outputs.length; i++) {
|
|
1039
|
+
nextEnv.set(s.outputs[i], doneEnv.get(callee.outputs[i].name));
|
|
1040
|
+
}
|
|
1041
|
+
return cont(nextEnv, doneSt);
|
|
1042
|
+
},
|
|
1043
|
+
onFail
|
|
1044
|
+
);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// External recursive call -> bail (keep as outer proc orchestrator)
|
|
1048
|
+
bail();
|
|
1049
|
+
}
|
|
1050
|
+
default:
|
|
1051
|
+
bail();
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
try {
|
|
1056
|
+
const initSt = {
|
|
1057
|
+
peeks: inLeaves.map(() => []),
|
|
1058
|
+
schemas: inLeaves.map((l) => ({ plist: l.plist, nodeId: 0 })),
|
|
1059
|
+
drained: inLeaves.map((l) => l.isUnit),
|
|
1060
|
+
mustDrainUnit: inLeaves.map(() => false),
|
|
1061
|
+
mustDrainFull: inLeaves.map(() => null),
|
|
1062
|
+
selfCall: null
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
const initEnv = new Map();
|
|
1066
|
+
const inBox = { next: 0 };
|
|
1067
|
+
for (let i = 0; i < proc.inputs.length; i++) {
|
|
1068
|
+
initEnv.set(proc.inputs[i].name, buildInitialInSVal(inPortPlists[i], 0, inBox));
|
|
1069
|
+
}
|
|
1070
|
+
for (let i = 0; i < proc.outputs.length; i++) {
|
|
1071
|
+
initEnv.set(proc.outputs[i].name, { __schema: outPortPlists[i] });
|
|
1072
|
+
initEnv.set(`__port_schema__${proc.outputs[i].name}`, outPortPlists[i]);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const root = symExecBlock(
|
|
1076
|
+
proc.body,
|
|
1077
|
+
0,
|
|
1078
|
+
initEnv,
|
|
1079
|
+
initSt,
|
|
1080
|
+
0,
|
|
1081
|
+
(finalEnv, finalSt) => {
|
|
1082
|
+
const outVals = proc.outputs.map((o) => finalEnv.get(o.name));
|
|
1083
|
+
return finalSt.selfCall ? makeLoopLeaf(outVals, finalSt) : makeEmitLeaf(outVals, finalSt);
|
|
1084
|
+
},
|
|
1085
|
+
() => {
|
|
1086
|
+
hasFail = true;
|
|
1087
|
+
return FAIL_NODE;
|
|
1088
|
+
}
|
|
1089
|
+
);
|
|
1090
|
+
|
|
1091
|
+
if (root === FAIL_NODE) return null;
|
|
1092
|
+
if (hasSelf && !hasLoopLeaf) return null;
|
|
1093
|
+
|
|
1094
|
+
// Collect actually reachable decision nodes
|
|
1095
|
+
const reachable = new Set();
|
|
1096
|
+
const visit = (n) => {
|
|
1097
|
+
if (!n || reachable.has(n.id)) return;
|
|
1098
|
+
reachable.add(n.id);
|
|
1099
|
+
if (n.kind === "peek") {
|
|
1100
|
+
for (const c of Object.values(n.cases)) visit(c.node);
|
|
1101
|
+
}
|
|
1102
|
+
};
|
|
1103
|
+
visit(root);
|
|
1104
|
+
|
|
1105
|
+
// Identify finite-enum register ports (e.g. `c`, `b`, `mode`, `ord`)!
|
|
1106
|
+
const regPorts = new Map(); // p -> enumInfo
|
|
1107
|
+
if (hasLoopLeaf) {
|
|
1108
|
+
for (let p = 0; p < P; p++) {
|
|
1109
|
+
const enumInfo = getUnitEnumInfo(inLeaves[p].plist);
|
|
1110
|
+
if (!enumInfo) continue;
|
|
1111
|
+
let valid = true;
|
|
1112
|
+
let hasConst = false;
|
|
1113
|
+
for (const id of reachable) {
|
|
1114
|
+
const n = dnodeById.get(id);
|
|
1115
|
+
if (!n || n.kind !== "loop") continue;
|
|
1116
|
+
const ne = n.nextExprs[p];
|
|
1117
|
+
if (ne.kind === "const" && ne.tokens.length === 1) {
|
|
1118
|
+
hasConst = true;
|
|
1119
|
+
} else if (ne.kind === "splice" && ne.p === p && ne.consumeCount === 0 && ne.prefix.length === 0) {
|
|
1120
|
+
// identity unchanged
|
|
1121
|
+
} else {
|
|
1122
|
+
valid = false;
|
|
1123
|
+
break;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
if (valid && hasConst) {
|
|
1127
|
+
regPorts.set(p, enumInfo);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// Identify write-only prepend accumulators -> `unshift_bits` directly onto output `q`!
|
|
1133
|
+
// (Handles `rev_bits`, `half_max_tally`, `f64_rev_step`, `f64_lsb_inc_step`, `f64_prepend_zeros`
|
|
1134
|
+
// with ZERO virtual stack overhead and full multi-input `chunk_table` + SWAR support!)
|
|
1135
|
+
const unshiftAccPorts = new Map(); // p -> { outIdx }
|
|
1136
|
+
const unshiftOutToPort = new Map(); // q -> p
|
|
1137
|
+
if (hasLoopLeaf) {
|
|
1138
|
+
const peekedPorts = new Set();
|
|
1139
|
+
for (const id of reachable) {
|
|
1140
|
+
const n = dnodeById.get(id);
|
|
1141
|
+
if (n && n.kind === "peek") peekedPorts.add(n.p);
|
|
1142
|
+
}
|
|
1143
|
+
for (let p = 0; p < P; p++) {
|
|
1144
|
+
if (regPorts.has(p) || peekedPorts.has(p)) continue;
|
|
1145
|
+
let okLoop = true;
|
|
1146
|
+
let hasPrepend = false;
|
|
1147
|
+
for (const id of reachable) {
|
|
1148
|
+
const n = dnodeById.get(id);
|
|
1149
|
+
if (!n || n.kind !== "loop") continue;
|
|
1150
|
+
const ne = n.nextExprs[p];
|
|
1151
|
+
if (ne.kind === "splice" && ne.p === p && ne.consumeCount === 0) {
|
|
1152
|
+
if (ne.prefix.length > 0) hasPrepend = true;
|
|
1153
|
+
} else {
|
|
1154
|
+
okLoop = false;
|
|
1155
|
+
break;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
if (!okLoop || !hasPrepend) continue;
|
|
1159
|
+
|
|
1160
|
+
// Every reachable `emit` leaf must splice `p` to the SAME output `q` with matching schema!
|
|
1161
|
+
let targetQ = -1;
|
|
1162
|
+
let okExit = true;
|
|
1163
|
+
for (const id of reachable) {
|
|
1164
|
+
const n = dnodeById.get(id);
|
|
1165
|
+
if (!n || n.kind !== "emit") continue;
|
|
1166
|
+
const idxQ = n.outExprs.findIndex((e) => e.kind === "splice" && e.p === p);
|
|
1167
|
+
if (idxQ < 0 || (targetQ >= 0 && targetQ !== idxQ)) {
|
|
1168
|
+
okExit = false;
|
|
1169
|
+
break;
|
|
1170
|
+
}
|
|
1171
|
+
targetQ = idxQ;
|
|
1172
|
+
}
|
|
1173
|
+
if (!okExit || targetQ < 0) continue;
|
|
1174
|
+
if (unshiftOutToPort.has(targetQ)) continue;
|
|
1175
|
+
if (!schemasEquivalent(inLeaves[p].plist, 0, outLeaves[targetQ].plist, 0)) continue;
|
|
1176
|
+
|
|
1177
|
+
// Output `targetQ` must NOT also emit forward TMC `push_bits` in any loop leaf!
|
|
1178
|
+
let conflictsTmc = false;
|
|
1179
|
+
for (const id of reachable) {
|
|
1180
|
+
const n = dnodeById.get(id);
|
|
1181
|
+
if (n && n.kind === "loop" && (n.outEmitPrefixes[targetQ] || []).length > 0) {
|
|
1182
|
+
conflictsTmc = true;
|
|
1183
|
+
break;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (conflictsTmc) continue;
|
|
1187
|
+
|
|
1188
|
+
unshiftAccPorts.set(p, { outIdx: targetQ });
|
|
1189
|
+
unshiftOutToPort.set(targetQ, p);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
// Identify read/write virtual LIFO bit-stack ports (e.g. `_lsb_trim`'s `z`)!
|
|
1194
|
+
const stackPorts = new Map(); // p -> { stackInfo, exitMode: "clear" | "flush_to_out", outIdx? }
|
|
1195
|
+
if (hasLoopLeaf && enableVirtualStack) {
|
|
1196
|
+
for (let p = 0; p < P; p++) {
|
|
1197
|
+
if (regPorts.has(p) || unshiftAccPorts.has(p)) continue;
|
|
1198
|
+
const sInfo = getBitStackSchemaInfo(inLeaves[p].plist);
|
|
1199
|
+
if (!sInfo) continue;
|
|
1200
|
+
|
|
1201
|
+
// Check loop updates: ONLY LIFO push, LIFO pop, identity, or clear/const(termTag)!
|
|
1202
|
+
let okLoop = true;
|
|
1203
|
+
let hasPush = false;
|
|
1204
|
+
for (const id of reachable) {
|
|
1205
|
+
const n = dnodeById.get(id);
|
|
1206
|
+
if (!n || n.kind !== "loop") continue;
|
|
1207
|
+
const ne = n.nextExprs[p];
|
|
1208
|
+
if (ne.kind === "splice" && ne.p === p) {
|
|
1209
|
+
if (ne.consumeCount === 0 && ne.prefix.length > 0) {
|
|
1210
|
+
// LIFO push of recTags!
|
|
1211
|
+
if (ne.prefix.every((tok) => sInfo.recTagToBit.has(tok.tag))) {
|
|
1212
|
+
hasPush = true;
|
|
1213
|
+
} else {
|
|
1214
|
+
okLoop = false;
|
|
1215
|
+
break;
|
|
1216
|
+
}
|
|
1217
|
+
} else if (ne.prefix.length === 0) {
|
|
1218
|
+
// Identity (`consumeCount === 0`) OR LIFO pop (`consumeCount >= 1`)!
|
|
1219
|
+
} else {
|
|
1220
|
+
okLoop = false;
|
|
1221
|
+
break;
|
|
1222
|
+
}
|
|
1223
|
+
} else if (ne.kind === "const" && ne.tokens.length === 1 && ne.tokens[0].tag === sInfo.termTag) {
|
|
1224
|
+
// Reset/clear to empty!
|
|
1225
|
+
} else {
|
|
1226
|
+
okLoop = false;
|
|
1227
|
+
break;
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
if (!okLoop || !hasPush) continue;
|
|
1231
|
+
|
|
1232
|
+
// Check exit leaves: must either discard (`drain`) OR splice cleanly to one output!
|
|
1233
|
+
let exitMode = null;
|
|
1234
|
+
let outIdx = -1;
|
|
1235
|
+
let okExit = true;
|
|
1236
|
+
for (const id of reachable) {
|
|
1237
|
+
const n = dnodeById.get(id);
|
|
1238
|
+
if (!n || n.kind !== "emit") continue;
|
|
1239
|
+
const splicedOut = n.outExprs.findIndex((e) => e.kind === "splice" && e.p === p);
|
|
1240
|
+
if (splicedOut >= 0) {
|
|
1241
|
+
if (exitMode === "clear" || (outIdx >= 0 && outIdx !== splicedOut)) {
|
|
1242
|
+
okExit = false;
|
|
1243
|
+
break;
|
|
1244
|
+
}
|
|
1245
|
+
exitMode = "flush_to_out";
|
|
1246
|
+
outIdx = splicedOut;
|
|
1247
|
+
} else {
|
|
1248
|
+
if (exitMode === "flush_to_out") {
|
|
1249
|
+
okExit = false;
|
|
1250
|
+
break;
|
|
1251
|
+
}
|
|
1252
|
+
exitMode = "clear";
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
if (okExit && exitMode) {
|
|
1256
|
+
stackPorts.set(p, { stackInfo: sInfo, exitMode, outIdx });
|
|
1257
|
+
break; // At most 1 virtual stack per kernel (matches stack_table_step!)
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// Validate loop-step invariants for all non-promoted ports & dropped drains!
|
|
1263
|
+
if (hasLoopLeaf) {
|
|
1264
|
+
for (const id of reachable) {
|
|
1265
|
+
const n = dnodeById.get(id);
|
|
1266
|
+
if (!n || n.kind !== "loop") continue;
|
|
1267
|
+
let makesProgress = false;
|
|
1268
|
+
for (let p = 0; p < P; p++) {
|
|
1269
|
+
const ne = n.nextExprs[p];
|
|
1270
|
+
if (n.droppedDrainFull[p] && !regPorts.has(p) && !stackPorts.has(p)) {
|
|
1271
|
+
bail("dropped-drain-in-loop");
|
|
1272
|
+
}
|
|
1273
|
+
if (regPorts.has(p)) {
|
|
1274
|
+
if (ne.kind === "const") makesProgress = true;
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
if (unshiftAccPorts.has(p)) continue;
|
|
1278
|
+
if (stackPorts.has(p)) {
|
|
1279
|
+
if (ne.kind === "splice" && ne.consumeCount > 0) makesProgress = true;
|
|
1280
|
+
if (ne.kind === "const") makesProgress = true;
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
if (ne.kind === "const") bail("const-stream-in-loop");
|
|
1284
|
+
if (ne.kind === "splice" && ne.prefix.length > 0) bail("prepend-stream-in-loop");
|
|
1285
|
+
if (n.shifts[p] > 0) makesProgress = true;
|
|
1286
|
+
}
|
|
1287
|
+
if (!makesProgress) bail("zero-progress-loop");
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// Must only have single-level peek (`depth === 0`) on stack ports, and every non-empty
|
|
1292
|
+
// branch of a `peek(sp)` MUST consume `sp` (since `stack_pop` pops 1 bit eagerly!).
|
|
1293
|
+
for (const [sp, spMeta] of stackPorts.entries()) {
|
|
1294
|
+
const sInfo = spMeta.stackInfo;
|
|
1295
|
+
const verifyConsumes = (node, seen = new Set()) => {
|
|
1296
|
+
if (!node || node === FAIL_NODE || seen.has(node.id)) return;
|
|
1297
|
+
seen.add(node.id);
|
|
1298
|
+
if (node.kind === "peek") {
|
|
1299
|
+
if (node.p === sp) bail("nested-stack-peek");
|
|
1300
|
+
for (const c of Object.values(node.cases)) verifyConsumes(c.node, seen);
|
|
1301
|
+
} else if (node.kind === "loop") {
|
|
1302
|
+
const ne = node.nextExprs[sp];
|
|
1303
|
+
if (ne.kind === "splice" && ne.consumeCount === 0) bail("unconsumed-stack-pop");
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
for (const id of reachable) {
|
|
1307
|
+
const n = dnodeById.get(id);
|
|
1308
|
+
if (n && n.kind === "peek" && n.p === sp) {
|
|
1309
|
+
if (n.depth > 0) bail("deep-stack-peek");
|
|
1310
|
+
for (const [tag, c] of Object.entries(n.cases)) {
|
|
1311
|
+
if (tag !== sInfo.termTag) verifyConsumes(c.node);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
return {
|
|
1318
|
+
isLoop: hasLoopLeaf,
|
|
1319
|
+
hasTmcEmit,
|
|
1320
|
+
inLeaves,
|
|
1321
|
+
outLeaves,
|
|
1322
|
+
inPortPlists,
|
|
1323
|
+
outPortPlists,
|
|
1324
|
+
inPortLeafRanges,
|
|
1325
|
+
root,
|
|
1326
|
+
reachable,
|
|
1327
|
+
dnodeById,
|
|
1328
|
+
regPorts,
|
|
1329
|
+
unshiftAccPorts,
|
|
1330
|
+
unshiftOutToPort,
|
|
1331
|
+
stackPorts,
|
|
1332
|
+
hasFail
|
|
1333
|
+
};
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
if (err && err[BAIL]) {
|
|
1336
|
+
if (process.env.KTVM_OPT_DEBUG) {
|
|
1337
|
+
console.error(`[fuse-kernel bail] ${proc.name}: ${err.message} (stack: ${err.stack?.split("\n")[2]?.trim()})`);
|
|
1338
|
+
}
|
|
1339
|
+
return null;
|
|
1340
|
+
}
|
|
1341
|
+
throw err;
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
// --- Emit Concrete `kTVM` `kernel` Basic-Block CFG from Decision DAG ---
|
|
1346
|
+
|
|
1347
|
+
function emitKernelFromDecisionDag(proc, c) {
|
|
1348
|
+
const { inLeaves, outLeaves, root, dnodeById, regPorts, unshiftAccPorts, unshiftOutToPort, stackPorts, isLoop, hasTmcEmit } = c;
|
|
1349
|
+
const P = inLeaves.length;
|
|
1350
|
+
const Q = outLeaves.length;
|
|
1351
|
+
|
|
1352
|
+
let kName = `@${sanitize(proc.name)}_k`;
|
|
1353
|
+
while (existingKernelNames.has(kName)) kName = `@${sanitize(proc.name)}_k${helperSeq++}`;
|
|
1354
|
+
existingKernelNames.add(kName);
|
|
1355
|
+
|
|
1356
|
+
const kInNames = inLeaves.map((l, i) => `%i${i}_${sanitize(l.pathKey || "in")}`);
|
|
1357
|
+
const kOutNames = outLeaves.map((l, i) => `%o${i}_${sanitize(l.pathKey || "out")}`);
|
|
1358
|
+
const kInputs = inLeaves.map((l, i) => ({ name: kInNames[i], schema: internSchemaExpr(l.plist, `ki${i}`) }));
|
|
1359
|
+
const kOutputs = outLeaves.map((l, i) => ({ name: kOutNames[i], schema: internSchemaExpr(l.plist, `ko${i}`) }));
|
|
1360
|
+
|
|
1361
|
+
const regs = [];
|
|
1362
|
+
const regNameOfPort = new Map();
|
|
1363
|
+
for (const [p, info] of regPorts.entries()) {
|
|
1364
|
+
const rName = `r${p}`;
|
|
1365
|
+
regNameOfPort.set(p, rName);
|
|
1366
|
+
regs.push({ name: rName, states: info.states, init: 0 });
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
const stacks = [];
|
|
1370
|
+
const stackNameOfPort = new Map();
|
|
1371
|
+
for (const [p] of stackPorts.entries()) {
|
|
1372
|
+
const sName = `s${p}`;
|
|
1373
|
+
stackNameOfPort.set(p, sName);
|
|
1374
|
+
stacks.push({ name: sName });
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
const blocks = [];
|
|
1378
|
+
let blkSeq = 0;
|
|
1379
|
+
const freshLbl = (p) => `${p}_${blkSeq++}`;
|
|
1380
|
+
|
|
1381
|
+
// If a stack port might receive a non-empty initial value at runtime, keep a fallback proc
|
|
1382
|
+
// so `entry_init` can handoff safely if initial stack != termTag!
|
|
1383
|
+
let fallbackProc = null;
|
|
1384
|
+
if (stackPorts.size > 0) {
|
|
1385
|
+
const fbName = `@${sanitize(proc.name)}_fb_${helperSeq++}`;
|
|
1386
|
+
const fbIn = kInputs.map((x) => cloneAst(x));
|
|
1387
|
+
const fbOut = kOutputs.map((x) => cloneAst(x));
|
|
1388
|
+
// Build a proc taking flat leaf ports -> muxing into original proc body -> demuxing!
|
|
1389
|
+
const fbBody = [];
|
|
1390
|
+
let fvSeq = 0;
|
|
1391
|
+
const fvar = (p) => `%fb_${p}_${fvSeq++}`;
|
|
1392
|
+
|
|
1393
|
+
const rebuildFromLeaves = (plist, nodeId, leafVars, idxBox, stmts) => {
|
|
1394
|
+
const [kind, edges] = plist[nodeId];
|
|
1395
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
1396
|
+
const mFields = edges.map(([lbl, t]) => ({
|
|
1397
|
+
label: lbl,
|
|
1398
|
+
name: rebuildFromLeaves(plist, t, leafVars, idxBox, stmts)
|
|
1399
|
+
}));
|
|
1400
|
+
const subPl = subPlist(plist, nodeId);
|
|
1401
|
+
const v = fvar("mux");
|
|
1402
|
+
stmts.push({ op: "chan", name: v, schema: internSchemaExpr(subPl, "fb") });
|
|
1403
|
+
stmts.push({ op: "mux", fields: mFields, dst: v, schema: internSchemaExpr(subPl, "fb") });
|
|
1404
|
+
return v;
|
|
1405
|
+
}
|
|
1406
|
+
return leafVars[idxBox.i++];
|
|
1407
|
+
};
|
|
1408
|
+
|
|
1409
|
+
const splitToLeaves = (srcVar, plist, nodeId, dstVars, idxBox, stmts) => {
|
|
1410
|
+
const [kind, edges] = plist[nodeId];
|
|
1411
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
1412
|
+
const subPl = subPlist(plist, nodeId);
|
|
1413
|
+
const dFields = [];
|
|
1414
|
+
const subPairs = [];
|
|
1415
|
+
for (const [lbl, t] of edges) {
|
|
1416
|
+
const tPl = subPlist(plist, t);
|
|
1417
|
+
const v = fvar(lbl);
|
|
1418
|
+
stmts.push({ op: "chan", name: v, schema: internSchemaExpr(tPl, lbl) });
|
|
1419
|
+
dFields.push({ label: lbl, name: v });
|
|
1420
|
+
subPairs.push({ v, t });
|
|
1421
|
+
}
|
|
1422
|
+
stmts.push({ op: "demux", src: srcVar, schema: internSchemaExpr(subPl, "fb"), fields: dFields });
|
|
1423
|
+
for (const sp of subPairs) splitToLeaves(sp.v, plist, sp.t, dstVars, idxBox, stmts);
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
stmts.push({ op: "splice", src: srcVar, dst: dstVars[idxBox.i++] });
|
|
1427
|
+
};
|
|
1428
|
+
|
|
1429
|
+
// Clone original proc as fallback helper and wrap it
|
|
1430
|
+
const origCopyName = `@${sanitize(proc.name)}_orig_${helperSeq++}`;
|
|
1431
|
+
const origCopy = cloneAst(proc);
|
|
1432
|
+
origCopy.name = origCopyName;
|
|
1433
|
+
// Rewrite self-spawns inside origCopy to origCopyName
|
|
1434
|
+
const rewriteSelf = (stmts) => {
|
|
1435
|
+
for (const s of stmts || []) {
|
|
1436
|
+
if (s.op === "spawn" && s.target === proc.name) s.target = origCopyName;
|
|
1437
|
+
else if (s.op === "switch") {
|
|
1438
|
+
for (const a of s.arms) rewriteSelf(a.body);
|
|
1439
|
+
if (s.defaultBody) rewriteSelf(s.defaultBody);
|
|
1440
|
+
} else if (s.op === "spec") {
|
|
1441
|
+
for (const b of s.branches) rewriteSelf(b.body);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
};
|
|
1445
|
+
rewriteSelf(origCopy.body);
|
|
1446
|
+
helperProcs.push(origCopy);
|
|
1447
|
+
|
|
1448
|
+
const boxIn = { i: 0 };
|
|
1449
|
+
const origArgs = c.inPortPlists.map((pl) => rebuildFromLeaves(pl, 0, kInNames, boxIn, fbBody));
|
|
1450
|
+
const origOuts = c.outPortPlists.map((pl, idx) => {
|
|
1451
|
+
const v = fvar(`out${idx}`);
|
|
1452
|
+
fbBody.push({ op: "chan", name: v, schema: internSchemaExpr(pl, "fbo") });
|
|
1453
|
+
return v;
|
|
1454
|
+
});
|
|
1455
|
+
fbBody.push({
|
|
1456
|
+
op: "spawn",
|
|
1457
|
+
target: origCopyName,
|
|
1458
|
+
schemaArgs: [],
|
|
1459
|
+
inputs: origArgs,
|
|
1460
|
+
outputs: origOuts,
|
|
1461
|
+
after: null,
|
|
1462
|
+
token: null
|
|
1463
|
+
});
|
|
1464
|
+
const boxOut = { i: 0 };
|
|
1465
|
+
for (let i = 0; i < origOuts.length; i++) {
|
|
1466
|
+
splitToLeaves(origOuts[i], c.outPortPlists[i], 0, kOutNames, boxOut, fbBody);
|
|
1467
|
+
}
|
|
1468
|
+
fallbackProc = {
|
|
1469
|
+
name: fbName,
|
|
1470
|
+
params: [],
|
|
1471
|
+
inputs: fbIn,
|
|
1472
|
+
outputs: fbOut,
|
|
1473
|
+
attrs: [],
|
|
1474
|
+
body: fbBody
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
const loopHeaderLabel = (regPorts.size > 0 || stackPorts.size > 0) ? "loop_hdr" : "entry";
|
|
1479
|
+
const slowStepLabel = "slow_step";
|
|
1480
|
+
|
|
1481
|
+
// Preamble `entry` initializing promoted `reg`s and checking `stack`s
|
|
1482
|
+
if (loopHeaderLabel !== "entry") {
|
|
1483
|
+
let curLbl = "entry";
|
|
1484
|
+
const initRegPorts = [...regPorts.entries()];
|
|
1485
|
+
const initStackPorts = [...stackPorts.entries()];
|
|
1486
|
+
|
|
1487
|
+
// Read initial enum values from promoted register ports & drain them to unit!
|
|
1488
|
+
for (let idx = 0; idx < initRegPorts.length; idx++) {
|
|
1489
|
+
const [p, info] = initRegPorts[idx];
|
|
1490
|
+
const nextLbl = (idx === initRegPorts.length - 1 && initStackPorts.length === 0)
|
|
1491
|
+
? loopHeaderLabel
|
|
1492
|
+
: freshLbl("init");
|
|
1493
|
+
const tmp = `%ir_${p}`;
|
|
1494
|
+
const cases = [];
|
|
1495
|
+
for (let ord = 0; ord < info.states; ord++) {
|
|
1496
|
+
const setLbl = freshLbl(`set_r${p}_${ord}`);
|
|
1497
|
+
cases.push({ bits: toBitsLit(ord, info.width), target: setLbl });
|
|
1498
|
+
blocks.push({
|
|
1499
|
+
label: setLbl,
|
|
1500
|
+
stmts: [
|
|
1501
|
+
{ op: "shift_tag", src: kInNames[p], width: info.width, nextSchema: S.unit() },
|
|
1502
|
+
{ op: "drain_guard", src: kInNames[p], schema: S.unit() },
|
|
1503
|
+
{ op: "set_reg", reg: regNameOfPort.get(p), value: ord }
|
|
1504
|
+
],
|
|
1505
|
+
term: { op: "goto", target: nextLbl }
|
|
1506
|
+
});
|
|
1507
|
+
}
|
|
1508
|
+
blocks.push({
|
|
1509
|
+
label: curLbl,
|
|
1510
|
+
stmts: [
|
|
1511
|
+
{ op: "peek_bits", dst: tmp, src: kInNames[p], offset: 0, width: info.width, onEof: "err" }
|
|
1512
|
+
],
|
|
1513
|
+
term: { op: "switch_bits", src: tmp, cases, defaultTarget: "err" }
|
|
1514
|
+
});
|
|
1515
|
+
curLbl = nextLbl;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
// Check initial stack port: if `exitMode === "clear"`, check empty (`termTag`),
|
|
1519
|
+
// else if `exitMode === "flush_to_out"`, keep `%in_p` untouched to splice after flushing stack!
|
|
1520
|
+
for (let idx = 0; idx < initStackPorts.length; idx++) {
|
|
1521
|
+
const [p, spMeta] = initStackPorts[idx];
|
|
1522
|
+
const nextLbl = idx === initStackPorts.length - 1 ? loopHeaderLabel : freshLbl("init");
|
|
1523
|
+
if (spMeta.exitMode === "flush_to_out") {
|
|
1524
|
+
// Don't even need `%in_p` to be empty: stack accumulates new prepended tags,
|
|
1525
|
+
// and on exit we pop stack then `splice %in_p -> %out`!
|
|
1526
|
+
if (curLbl !== nextLbl) {
|
|
1527
|
+
blocks.push({ label: curLbl, stmts: [], term: { op: "goto", target: nextLbl } });
|
|
1528
|
+
curLbl = nextLbl;
|
|
1529
|
+
}
|
|
1530
|
+
} else {
|
|
1531
|
+
// `exitMode === "clear"` (e.g. `_lsb_trim`): verify initial `%z` starts with `termTag`,
|
|
1532
|
+
// shift + drain it, otherwise handoff to fallbackProc!
|
|
1533
|
+
const sInfo = spMeta.stackInfo;
|
|
1534
|
+
const tmp = `%iz_${p}`;
|
|
1535
|
+
const emptyOkLbl = freshLbl("stack_init_ok");
|
|
1536
|
+
const fbLbl = freshLbl("stack_init_fb");
|
|
1537
|
+
blocks.push({
|
|
1538
|
+
label: curLbl,
|
|
1539
|
+
stmts: [
|
|
1540
|
+
{ op: "peek_bits", dst: tmp, src: kInNames[p], offset: 0, width: sInfo.tagWidth, onEof: "err" }
|
|
1541
|
+
],
|
|
1542
|
+
term: {
|
|
1543
|
+
op: "switch_bits",
|
|
1544
|
+
src: tmp,
|
|
1545
|
+
cases: [{ bits: toBitsLit(sInfo.termOrd, sInfo.tagWidth), target: emptyOkLbl }],
|
|
1546
|
+
defaultTarget: fbLbl
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
blocks.push({
|
|
1550
|
+
label: emptyOkLbl,
|
|
1551
|
+
stmts: [
|
|
1552
|
+
{ op: "shift_tag", src: kInNames[p], width: sInfo.tagWidth, nextSchema: S.unit() },
|
|
1553
|
+
{ op: "drain_guard", src: kInNames[p], schema: S.unit() }
|
|
1554
|
+
],
|
|
1555
|
+
term: { op: "goto", target: nextLbl }
|
|
1556
|
+
});
|
|
1557
|
+
blocks.push({
|
|
1558
|
+
label: fbLbl,
|
|
1559
|
+
stmts: [],
|
|
1560
|
+
term: { op: "handoff", target: fallbackProc.name, inputs: [...kInNames], outputs: [...kOutNames] }
|
|
1561
|
+
});
|
|
1562
|
+
curLbl = nextLbl;
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
// Loop header block (with cooperative `yield` ONLY for forward-push TMC outputs!)
|
|
1568
|
+
const hdrStmts = [];
|
|
1569
|
+
if (isLoop && hasTmcEmit && !unshiftOutToPort.has(0)) {
|
|
1570
|
+
hdrStmts.push({ op: "yield", dst: kOutNames[0], threshold: 64 });
|
|
1571
|
+
}
|
|
1572
|
+
blocks.push({
|
|
1573
|
+
label: loopHeaderLabel,
|
|
1574
|
+
stmts: hdrStmts,
|
|
1575
|
+
term: { op: "goto", target: slowStepLabel }
|
|
1576
|
+
});
|
|
1577
|
+
|
|
1578
|
+
// Lower Decision DAG nodes -> kernel basic blocks!
|
|
1579
|
+
const emittedDNodes = new Map(); // dnode.id -> blockLabel
|
|
1580
|
+
const exitBlocks = []; // tracked for table synthesis metadata!
|
|
1581
|
+
|
|
1582
|
+
function lowerDNode(dnode, preferredLabel = null) {
|
|
1583
|
+
if (dnode.kind === "fail") return "err";
|
|
1584
|
+
if (!preferredLabel && emittedDNodes.has(dnode.id)) return emittedDNodes.get(dnode.id);
|
|
1585
|
+
|
|
1586
|
+
const lbl = preferredLabel || freshLbl(`d${dnode.id}`);
|
|
1587
|
+
emittedDNodes.set(dnode.id, lbl);
|
|
1588
|
+
|
|
1589
|
+
if (dnode.kind === "peek") {
|
|
1590
|
+
// Case 1: Promoted finite-enum register!
|
|
1591
|
+
if (regPorts.has(dnode.p)) {
|
|
1592
|
+
const rName = regNameOfPort.get(dnode.p);
|
|
1593
|
+
const cases = Object.values(dnode.cases).map((c) => ({
|
|
1594
|
+
value: c.ord,
|
|
1595
|
+
target: lowerDNode(c.node)
|
|
1596
|
+
}));
|
|
1597
|
+
blocks.push({
|
|
1598
|
+
label: lbl,
|
|
1599
|
+
stmts: [],
|
|
1600
|
+
term: { op: "switch_reg", reg: rName, cases }
|
|
1601
|
+
});
|
|
1602
|
+
return lbl;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
// Case 2: Promoted virtual LIFO bit-stack!
|
|
1606
|
+
if (stackPorts.has(dnode.p)) {
|
|
1607
|
+
const spMeta = stackPorts.get(dnode.p);
|
|
1608
|
+
const sInfo = spMeta.stackInfo;
|
|
1609
|
+
const sName = stackNameOfPort.get(dnode.p);
|
|
1610
|
+
const emptyCase = dnode.cases[sInfo.termTag];
|
|
1611
|
+
const emptyTarget = emptyCase ? lowerDNode(emptyCase.node) : "err";
|
|
1612
|
+
const tmp = `%sp_${dnode.id}`;
|
|
1613
|
+
const recCases = sInfo.recTags.map((rt, bitIdx) => ({
|
|
1614
|
+
bits: toBitsLit(bitIdx, sInfo.stackBitWidth),
|
|
1615
|
+
target: dnode.cases[rt.tag] ? lowerDNode(dnode.cases[rt.tag].node) : "err"
|
|
1616
|
+
}));
|
|
1617
|
+
// Pop top bit (on empty -> branch to `termTag` case!).
|
|
1618
|
+
// If a child path does NOT consume the stack (identity), we re-push it there!
|
|
1619
|
+
// Wait: let's track `poppedStackTag` cleanly — even simpler: in every loop/emit
|
|
1620
|
+
// leaf, `dnode.cases[rt]` already has `st.peeks[sp] = [rt.tag]` (`consumeCount = 1`)!
|
|
1621
|
+
// If a leaf has `ne.consumeCount === 0` on `sp` (meaning it only peeked without popping!),
|
|
1622
|
+
// that leaf simply re-pushes `rt.tag`! That way `stack_pop` works in 1 op!
|
|
1623
|
+
blocks.push({
|
|
1624
|
+
label: lbl,
|
|
1625
|
+
stmts: [
|
|
1626
|
+
{ op: "stack_pop", dst: tmp, stack: sName, width: sInfo.stackBitWidth, onEmpty: emptyTarget }
|
|
1627
|
+
],
|
|
1628
|
+
term: { op: "switch_bits", src: tmp, cases: recCases, defaultTarget: "err" }
|
|
1629
|
+
});
|
|
1630
|
+
return lbl;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// Case 3: Normal stream input `peek_bits`!
|
|
1634
|
+
const tmp = `%t_${dnode.id}`;
|
|
1635
|
+
const cases = Object.values(dnode.cases).map((c) => ({
|
|
1636
|
+
bits: c.bits,
|
|
1637
|
+
target: lowerDNode(c.node)
|
|
1638
|
+
}));
|
|
1639
|
+
blocks.push({
|
|
1640
|
+
label: lbl,
|
|
1641
|
+
stmts: [
|
|
1642
|
+
{
|
|
1643
|
+
op: "peek_bits",
|
|
1644
|
+
dst: tmp,
|
|
1645
|
+
src: kInNames[dnode.p],
|
|
1646
|
+
offset: dnode.offsetBits,
|
|
1647
|
+
width: dnode.width,
|
|
1648
|
+
onEof: "err"
|
|
1649
|
+
}
|
|
1650
|
+
],
|
|
1651
|
+
term: { op: "switch_bits", src: tmp, cases, defaultTarget: "err" }
|
|
1652
|
+
});
|
|
1653
|
+
return lbl;
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
if (dnode.kind === "loop") {
|
|
1657
|
+
const stmts = [];
|
|
1658
|
+
// 1. Shift consumed input tags on stream ports
|
|
1659
|
+
for (let p = 0; p < P; p++) {
|
|
1660
|
+
if (regPorts.has(p) || unshiftAccPorts.has(p) || stackPorts.has(p)) continue;
|
|
1661
|
+
for (const st of dnode.shiftTokens[p]) {
|
|
1662
|
+
stmts.push({
|
|
1663
|
+
op: "shift_tag",
|
|
1664
|
+
src: kInNames[p],
|
|
1665
|
+
width: st.width,
|
|
1666
|
+
nextSchema: internSchemaExpr(st.nextPlist, `st${p}`)
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
// 2. Push TMC forward output bits
|
|
1671
|
+
for (let q = 0; q < Q; q++) {
|
|
1672
|
+
for (const tok of dnode.outEmitPrefixes[q] || []) {
|
|
1673
|
+
if (tok.width > 0) {
|
|
1674
|
+
stmts.push({
|
|
1675
|
+
op: "push_bits",
|
|
1676
|
+
dst: kOutNames[q],
|
|
1677
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1678
|
+
width: tok.width
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
// 2b. Unshift write-only prepend accumulator tags directly onto output `q`!
|
|
1684
|
+
for (const [p, uMeta] of unshiftAccPorts.entries()) {
|
|
1685
|
+
const ne = dnode.nextExprs[p];
|
|
1686
|
+
if (ne.kind === "splice" && ne.prefix.length > 0) {
|
|
1687
|
+
for (let i = ne.prefix.length - 1; i >= 0; i--) {
|
|
1688
|
+
const tok = ne.prefix[i];
|
|
1689
|
+
if (tok.width > 0) {
|
|
1690
|
+
stmts.push({
|
|
1691
|
+
op: "unshift_bits",
|
|
1692
|
+
dst: kOutNames[uMeta.outIdx],
|
|
1693
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1694
|
+
width: tok.width
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
// 3. Update promoted registers
|
|
1701
|
+
for (const [p, info] of regPorts.entries()) {
|
|
1702
|
+
const ne = dnode.nextExprs[p];
|
|
1703
|
+
if (ne.kind === "const" && ne.tokens.length === 1) {
|
|
1704
|
+
stmts.push({ op: "set_reg", reg: regNameOfPort.get(p), value: ne.tokens[0].ord });
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
// 4. Update promoted virtual stack (push / clear)
|
|
1708
|
+
for (const [p, spMeta] of stackPorts.entries()) {
|
|
1709
|
+
const sInfo = spMeta.stackInfo;
|
|
1710
|
+
const sName = stackNameOfPort.get(p);
|
|
1711
|
+
const ne = dnode.nextExprs[p];
|
|
1712
|
+
if (ne.kind === "const") {
|
|
1713
|
+
stmts.push({ op: "stack_clear", stack: sName });
|
|
1714
|
+
} else if (ne.kind === "splice" && ne.prefix.length > 0) {
|
|
1715
|
+
// Push in reverse so first tag in `prefix` ends up on TOP of LIFO stack!
|
|
1716
|
+
for (let i = ne.prefix.length - 1; i >= 0; i--) {
|
|
1717
|
+
const bit = sInfo.recTagToBit.get(ne.prefix[i].tag);
|
|
1718
|
+
stmts.push({
|
|
1719
|
+
op: "stack_push",
|
|
1720
|
+
stack: sName,
|
|
1721
|
+
bits: toBitsLit(bit, sInfo.stackBitWidth),
|
|
1722
|
+
width: sInfo.stackBitWidth
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
blocks.push({
|
|
1728
|
+
label: lbl,
|
|
1729
|
+
stmts,
|
|
1730
|
+
term: { op: "goto", target: loopHeaderLabel }
|
|
1731
|
+
});
|
|
1732
|
+
return lbl;
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
if (dnode.kind === "emit") {
|
|
1736
|
+
// Split emit into: (a) shift block (runs on `slow_step`), jumping to
|
|
1737
|
+
// (b) clean exit handler block `exit_N` (which BOTH `slow_step` AND `table_step`
|
|
1738
|
+
// can jump to — running `drain_guard`s, final emits, `splice`/`close`, `retire`!)
|
|
1739
|
+
const exitLbl = freshLbl("exit");
|
|
1740
|
+
exitBlocks.push({ label: exitLbl, dnode });
|
|
1741
|
+
|
|
1742
|
+
const shiftStmts = [];
|
|
1743
|
+
for (let p = 0; p < P; p++) {
|
|
1744
|
+
if (regPorts.has(p) || unshiftAccPorts.has(p) || stackPorts.has(p)) continue;
|
|
1745
|
+
for (const st of dnode.shiftTokens[p]) {
|
|
1746
|
+
shiftStmts.push({
|
|
1747
|
+
op: "shift_tag",
|
|
1748
|
+
src: kInNames[p],
|
|
1749
|
+
width: st.width,
|
|
1750
|
+
nextSchema: internSchemaExpr(st.nextPlist, `st${p}`)
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
blocks.push({
|
|
1755
|
+
label: lbl,
|
|
1756
|
+
stmts: shiftStmts,
|
|
1757
|
+
term: { op: "goto", target: exitLbl }
|
|
1758
|
+
});
|
|
1759
|
+
|
|
1760
|
+
// Build the exit handler block `exitLbl`
|
|
1761
|
+
const exitStmts = [];
|
|
1762
|
+
// Re-align `consSchema` on any spliced stream port whose post-shift schema differs from its
|
|
1763
|
+
// entry schema (so `table_step`/`fsm_table_step` raw `shiftBits` transitions align cleanly!).
|
|
1764
|
+
for (let p = 0; p < P; p++) {
|
|
1765
|
+
if (regPorts.has(p) || unshiftAccPorts.has(p) || stackPorts.has(p)) continue;
|
|
1766
|
+
const toks = dnode.shiftTokens[p];
|
|
1767
|
+
if (toks.length > 0 && dnode.outExprs.some((e) => e.kind === "splice" && e.p === p)) {
|
|
1768
|
+
const remPl = toks[toks.length - 1].nextPlist;
|
|
1769
|
+
if (!schemasEquivalent(remPl, 0, inLeaves[p].plist, 0)) {
|
|
1770
|
+
exitStmts.push({
|
|
1771
|
+
op: "shift_tag",
|
|
1772
|
+
src: kInNames[p],
|
|
1773
|
+
width: 0,
|
|
1774
|
+
nextSchema: internSchemaExpr(remPl, `re${p}`)
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
for (let p = 0; p < P; p++) {
|
|
1780
|
+
if (regPorts.has(p) || unshiftAccPorts.has(p)) continue;
|
|
1781
|
+
if (stackPorts.has(p)) {
|
|
1782
|
+
const spMeta = stackPorts.get(p);
|
|
1783
|
+
if (spMeta.exitMode === "clear") {
|
|
1784
|
+
exitStmts.push({ op: "stack_clear", stack: stackNameOfPort.get(p) });
|
|
1785
|
+
}
|
|
1786
|
+
continue;
|
|
1787
|
+
}
|
|
1788
|
+
if (dnode.drainGuards[p]) {
|
|
1789
|
+
exitStmts.push({
|
|
1790
|
+
op: "drain_guard",
|
|
1791
|
+
src: kInNames[p],
|
|
1792
|
+
schema: internSchemaExpr(dnode.drainGuards[p], `dg${p}`)
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
// Helper to emit a single standard or unshift-acc output `q` (returns true if emitted inline,
|
|
1798
|
+
// or false if `e` splices a promoted `reg` port that must be emitted via `switch_reg`!)
|
|
1799
|
+
const regOutList = [];
|
|
1800
|
+
const emitOutputToStmts = (q, targetStmts) => {
|
|
1801
|
+
const e = dnode.outExprs[q];
|
|
1802
|
+
if (e.kind === "splice" && regPorts.has(e.p)) {
|
|
1803
|
+
regOutList.push({ q, e });
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
if (unshiftOutToPort.has(q)) {
|
|
1807
|
+
// `unshift` output: prepend any exit prefix in reverse order, then `splice %acc -> %out`!
|
|
1808
|
+
const pref = e.prefix || [];
|
|
1809
|
+
for (let i = pref.length - 1; i >= 0; i--) {
|
|
1810
|
+
const tok = pref[i];
|
|
1811
|
+
if (tok.width > 0) {
|
|
1812
|
+
targetStmts.push({
|
|
1813
|
+
op: "unshift_bits",
|
|
1814
|
+
dst: kOutNames[q],
|
|
1815
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1816
|
+
width: tok.width
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
targetStmts.push({ op: "splice", src: kInNames[e.p], dst: kOutNames[q] });
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
if (e.kind === "const") {
|
|
1824
|
+
for (const tok of e.tokens) {
|
|
1825
|
+
if (tok.width > 0) {
|
|
1826
|
+
targetStmts.push({
|
|
1827
|
+
op: "push_bits",
|
|
1828
|
+
dst: kOutNames[q],
|
|
1829
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1830
|
+
width: tok.width
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
targetStmts.push({ op: "close", dst: kOutNames[q] });
|
|
1835
|
+
} else if (e.kind === "splice") {
|
|
1836
|
+
for (const tok of e.prefix) {
|
|
1837
|
+
if (tok.width > 0) {
|
|
1838
|
+
targetStmts.push({
|
|
1839
|
+
op: "push_bits",
|
|
1840
|
+
dst: kOutNames[q],
|
|
1841
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1842
|
+
width: tok.width
|
|
1843
|
+
});
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
targetStmts.push({ op: "splice", src: kInNames[e.p], dst: kOutNames[q] });
|
|
1847
|
+
}
|
|
1848
|
+
};
|
|
1849
|
+
|
|
1850
|
+
// Chain `switch_reg` blocks to emit any promoted register outputs before jumping to `finalTerm`
|
|
1851
|
+
const chainRegOutputs = (startLbl, startStmts, finalTerm) => {
|
|
1852
|
+
if (regOutList.length === 0) {
|
|
1853
|
+
blocks.push({ label: startLbl, stmts: startStmts, term: finalTerm });
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
let curLbl = startLbl;
|
|
1857
|
+
let curStmts = startStmts;
|
|
1858
|
+
for (let ri = 0; ri < regOutList.length; ri++) {
|
|
1859
|
+
const { q, e } = regOutList[ri];
|
|
1860
|
+
const info = regPorts.get(e.p);
|
|
1861
|
+
const rName = regNameOfPort.get(e.p);
|
|
1862
|
+
const isLast = ri === regOutList.length - 1;
|
|
1863
|
+
const nextLbl = isLast ? null : freshLbl("reg_out_next");
|
|
1864
|
+
const cases = [];
|
|
1865
|
+
for (let ord = 0; ord < info.states; ord++) {
|
|
1866
|
+
const cLbl = freshLbl(`emit_r${e.p}_${ord}`);
|
|
1867
|
+
const cStmts = [];
|
|
1868
|
+
for (const tok of e.prefix || []) {
|
|
1869
|
+
if (tok.width > 0) {
|
|
1870
|
+
cStmts.push({
|
|
1871
|
+
op: "push_bits",
|
|
1872
|
+
dst: kOutNames[q],
|
|
1873
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1874
|
+
width: tok.width
|
|
1875
|
+
});
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
if (info.width > 0) {
|
|
1879
|
+
cStmts.push({
|
|
1880
|
+
op: "push_bits",
|
|
1881
|
+
dst: kOutNames[q],
|
|
1882
|
+
bits: toBitsLit(ord, info.width),
|
|
1883
|
+
width: info.width
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
cStmts.push({ op: "close", dst: kOutNames[q] });
|
|
1887
|
+
blocks.push({
|
|
1888
|
+
label: cLbl,
|
|
1889
|
+
stmts: cStmts,
|
|
1890
|
+
term: isLast ? finalTerm : { op: "goto", target: nextLbl }
|
|
1891
|
+
});
|
|
1892
|
+
cases.push({ value: ord, target: cLbl });
|
|
1893
|
+
}
|
|
1894
|
+
blocks.push({
|
|
1895
|
+
label: curLbl,
|
|
1896
|
+
stmts: curStmts,
|
|
1897
|
+
term: { op: "switch_reg", reg: rName, cases }
|
|
1898
|
+
});
|
|
1899
|
+
curLbl = nextLbl;
|
|
1900
|
+
curStmts = [];
|
|
1901
|
+
}
|
|
1902
|
+
};
|
|
1903
|
+
|
|
1904
|
+
// Check if any read/write stack port flushes to an output on exit!
|
|
1905
|
+
let flushStackPort = null;
|
|
1906
|
+
for (const [p, spMeta] of stackPorts.entries()) {
|
|
1907
|
+
if (spMeta.exitMode === "flush_to_out") {
|
|
1908
|
+
flushStackPort = { p, spMeta };
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
if (flushStackPort) {
|
|
1913
|
+
const { p, spMeta } = flushStackPort;
|
|
1914
|
+
const sInfo = spMeta.stackInfo;
|
|
1915
|
+
const sName = stackNameOfPort.get(p);
|
|
1916
|
+
const flushQ = spMeta.outIdx;
|
|
1917
|
+
// Emit ALL OTHER outputs `q2 !== flushQ` first so no output is ever left open!
|
|
1918
|
+
for (let q2 = 0; q2 < Q; q2++) {
|
|
1919
|
+
if (q2 !== flushQ) emitOutputToStmts(q2, exitStmts);
|
|
1920
|
+
}
|
|
1921
|
+
const expr = dnode.outExprs[flushQ];
|
|
1922
|
+
for (const tok of expr.prefix || []) {
|
|
1923
|
+
if (tok.width > 0) {
|
|
1924
|
+
exitStmts.push({
|
|
1925
|
+
op: "push_bits",
|
|
1926
|
+
dst: kOutNames[flushQ],
|
|
1927
|
+
bits: toBitsLit(tok.ord, tok.width),
|
|
1928
|
+
width: tok.width
|
|
1929
|
+
});
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
const flushLoopLbl = freshLbl("flush_stack");
|
|
1933
|
+
const flushDoneLbl = freshLbl("flush_done");
|
|
1934
|
+
chainRegOutputs(exitLbl, exitStmts, { op: "goto", target: flushLoopLbl });
|
|
1935
|
+
|
|
1936
|
+
const tmp = `%fl_${blkSeq++}`;
|
|
1937
|
+
const recCases = sInfo.recTags.map((rt, bitIdx) => {
|
|
1938
|
+
const emitBitLbl = freshLbl(`emit_s${bitIdx}`);
|
|
1939
|
+
blocks.push({
|
|
1940
|
+
label: emitBitLbl,
|
|
1941
|
+
stmts: [{ op: "push_bits", dst: kOutNames[flushQ], bits: toBitsLit(rt.ord, sInfo.tagWidth), width: sInfo.tagWidth }],
|
|
1942
|
+
term: { op: "goto", target: flushLoopLbl }
|
|
1943
|
+
});
|
|
1944
|
+
return { bits: toBitsLit(bitIdx, sInfo.stackBitWidth), target: emitBitLbl };
|
|
1945
|
+
});
|
|
1946
|
+
blocks.push({
|
|
1947
|
+
label: flushLoopLbl,
|
|
1948
|
+
stmts: [{ op: "stack_pop", dst: tmp, stack: sName, width: sInfo.stackBitWidth, onEmpty: flushDoneLbl }],
|
|
1949
|
+
term: { op: "switch_bits", src: tmp, cases: recCases, defaultTarget: "err" }
|
|
1950
|
+
});
|
|
1951
|
+
blocks.push({
|
|
1952
|
+
label: flushDoneLbl,
|
|
1953
|
+
stmts: [{ op: "splice", src: kInNames[p], dst: kOutNames[flushQ] }],
|
|
1954
|
+
term: { op: "retire" }
|
|
1955
|
+
});
|
|
1956
|
+
return lbl;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
// Standard exit: emit every output cleanly!
|
|
1960
|
+
for (let q = 0; q < Q; q++) {
|
|
1961
|
+
emitOutputToStmts(q, exitStmts);
|
|
1962
|
+
}
|
|
1963
|
+
chainRegOutputs(exitLbl, exitStmts, { op: "retire" });
|
|
1964
|
+
return lbl;
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
return "err";
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
lowerDNode(root, slowStepLabel);
|
|
1971
|
+
|
|
1972
|
+
blocks.push({ label: "err", stmts: [], term: { op: "fail" } });
|
|
1973
|
+
|
|
1974
|
+
const attrs = [];
|
|
1975
|
+
if (!c.hasFail) attrs.push("total");
|
|
1976
|
+
if (isLoop && hasTmcEmit) attrs.push("tmc");
|
|
1977
|
+
|
|
1978
|
+
const outputModes = outLeaves.map((_, q) => (unshiftOutToPort.has(q) ? "unshift" : "push"));
|
|
1979
|
+
|
|
1980
|
+
const kernel = {
|
|
1981
|
+
name: kName,
|
|
1982
|
+
inputs: kInputs,
|
|
1983
|
+
outputs: kOutputs,
|
|
1984
|
+
attrs,
|
|
1985
|
+
regs,
|
|
1986
|
+
stacks,
|
|
1987
|
+
blocks,
|
|
1988
|
+
// Internal metadata consumed by `synthesize-tables.mjs` (stripped before JSON/DSL export)
|
|
1989
|
+
_optMeta: {
|
|
1990
|
+
isLoop,
|
|
1991
|
+
hasTmcEmit,
|
|
1992
|
+
loopHeaderLabel,
|
|
1993
|
+
slowStepLabel,
|
|
1994
|
+
exitBlocks: exitBlocks.map((e) => e.label),
|
|
1995
|
+
streamPortIndices: inLeaves.map((_, i) => i).filter((i) => !regPorts.has(i) && !unshiftAccPorts.has(i) && !stackPorts.has(i)),
|
|
1996
|
+
regPortIndices: [...regPorts.keys()],
|
|
1997
|
+
unshiftAccPortIndices: [...unshiftAccPorts.keys()],
|
|
1998
|
+
stackPortIndices: [...stackPorts.keys()],
|
|
1999
|
+
outputModes,
|
|
2000
|
+
inLeaves,
|
|
2001
|
+
outLeaves
|
|
2002
|
+
}
|
|
2003
|
+
};
|
|
2004
|
+
|
|
2005
|
+
// Build wrapper proc: `demux` product inputs -> `exec @kernel` -> `mux` product outputs
|
|
2006
|
+
const wrapBody = [];
|
|
2007
|
+
let wv = 0;
|
|
2008
|
+
const wvar = (p) => `%w_${p}_${wv++}`;
|
|
2009
|
+
|
|
2010
|
+
const emitDemuxLeaves = (srcVar, plist, nodeId, outVars) => {
|
|
2011
|
+
const [kind, edges] = plist[nodeId];
|
|
2012
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
2013
|
+
const subPl = subPlist(plist, nodeId);
|
|
2014
|
+
const dFields = [];
|
|
2015
|
+
const pairs = [];
|
|
2016
|
+
for (const [lbl, t] of edges) {
|
|
2017
|
+
const tPl = subPlist(plist, t);
|
|
2018
|
+
const v = wvar(lbl);
|
|
2019
|
+
wrapBody.push({ op: "chan", name: v, schema: internSchemaExpr(tPl, lbl) });
|
|
2020
|
+
dFields.push({ label: lbl, name: v });
|
|
2021
|
+
pairs.push({ v, t });
|
|
2022
|
+
}
|
|
2023
|
+
wrapBody.push({ op: "demux", src: srcVar, schema: internSchemaExpr(subPl, "wd"), fields: dFields });
|
|
2024
|
+
for (const pair of pairs) emitDemuxLeaves(pair.v, plist, pair.t, outVars);
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
outVars.push(srcVar);
|
|
2028
|
+
};
|
|
2029
|
+
|
|
2030
|
+
const emitMuxLeaves = (plist, nodeId, leafVars, idxBox, targetVar = null) => {
|
|
2031
|
+
const [kind, edges] = plist[nodeId];
|
|
2032
|
+
if (kind === "closed-product" && edges.length > 0) {
|
|
2033
|
+
const subPl = subPlist(plist, nodeId);
|
|
2034
|
+
const mFields = edges.map(([lbl, t]) => ({
|
|
2035
|
+
label: lbl,
|
|
2036
|
+
name: emitMuxLeaves(plist, t, leafVars, idxBox, null)
|
|
2037
|
+
}));
|
|
2038
|
+
const dst = targetVar || wvar("mux");
|
|
2039
|
+
if (!targetVar) wrapBody.push({ op: "chan", name: dst, schema: internSchemaExpr(subPl, "wm") });
|
|
2040
|
+
wrapBody.push({ op: "mux", fields: mFields, dst, schema: internSchemaExpr(subPl, "wm") });
|
|
2041
|
+
return dst;
|
|
2042
|
+
}
|
|
2043
|
+
const v = leafVars[idxBox.i++];
|
|
2044
|
+
if (targetVar && v !== targetVar) {
|
|
2045
|
+
wrapBody.push({ op: "splice", src: v, dst: targetVar });
|
|
2046
|
+
return targetVar;
|
|
2047
|
+
}
|
|
2048
|
+
return v;
|
|
2049
|
+
};
|
|
2050
|
+
|
|
2051
|
+
const flatInVars = [];
|
|
2052
|
+
for (let i = 0; i < proc.inputs.length; i++) {
|
|
2053
|
+
emitDemuxLeaves(proc.inputs[i].name, c.inPortPlists[i], 0, flatInVars);
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
const flatOutVars = [];
|
|
2057
|
+
const directOut = proc.outputs.length === 1 && Q === 1;
|
|
2058
|
+
if (directOut) {
|
|
2059
|
+
flatOutVars.push(proc.outputs[0].name);
|
|
2060
|
+
} else {
|
|
2061
|
+
for (let q = 0; q < Q; q++) {
|
|
2062
|
+
const v = wvar(`o${q}`);
|
|
2063
|
+
wrapBody.push({ op: "chan", name: v, schema: internSchemaExpr(outLeaves[q].plist, `wo${q}`) });
|
|
2064
|
+
flatOutVars.push(v);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
wrapBody.push({
|
|
2069
|
+
op: "exec",
|
|
2070
|
+
target: kName,
|
|
2071
|
+
inputs: flatInVars,
|
|
2072
|
+
outputs: flatOutVars
|
|
2073
|
+
});
|
|
2074
|
+
|
|
2075
|
+
if (!directOut) {
|
|
2076
|
+
const box = { i: 0 };
|
|
2077
|
+
for (let i = 0; i < proc.outputs.length; i++) {
|
|
2078
|
+
emitMuxLeaves(c.outPortPlists[i], 0, flatOutVars, box, proc.outputs[i].name);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
const wrapperProc = {
|
|
2083
|
+
name: proc.name,
|
|
2084
|
+
params: [],
|
|
2085
|
+
inputs: cloneAst(proc.inputs),
|
|
2086
|
+
outputs: cloneAst(proc.outputs),
|
|
2087
|
+
attrs: [...(proc.attrs || [])],
|
|
2088
|
+
body: wrapBody
|
|
2089
|
+
};
|
|
2090
|
+
|
|
2091
|
+
return {
|
|
2092
|
+
kernel,
|
|
2093
|
+
wrapperProc,
|
|
2094
|
+
fallbackProc,
|
|
2095
|
+
promotedRegCount: regPorts.size,
|
|
2096
|
+
hasVirtualStack: stackPorts.size > 0
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
const outMod = createModule({
|
|
2101
|
+
version: mod.version || "0.1",
|
|
2102
|
+
layer: "mono",
|
|
2103
|
+
entry: mod.entry,
|
|
2104
|
+
schemas: emittedSchemas,
|
|
2105
|
+
procs: [...newProcs, ...helperProcs],
|
|
2106
|
+
kernels: emittedKernels,
|
|
2107
|
+
tables: cloneAst(mod.tables || [])
|
|
2108
|
+
});
|
|
2109
|
+
|
|
2110
|
+
return { module: outMod, stats };
|
|
2111
|
+
}
|