@gmitch215/folio 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +541 -2
  3. package/dist/bake.d.ts +179 -0
  4. package/dist/bake.js +704 -0
  5. package/dist/browser-worker.d.ts +9 -0
  6. package/dist/browser-worker.js +37 -0
  7. package/dist/browser.d.ts +68 -0
  8. package/dist/browser.js +274 -0
  9. package/dist/compiler.d.ts +79 -0
  10. package/dist/compiler.js +620 -0
  11. package/dist/context.d.ts +33 -0
  12. package/dist/context.js +93 -0
  13. package/dist/coordinator.d.ts +27 -0
  14. package/dist/coordinator.js +191 -0
  15. package/dist/extract.d.ts +165 -0
  16. package/dist/extract.js +1817 -0
  17. package/dist/frames.d.ts +33 -0
  18. package/dist/frames.js +159 -0
  19. package/dist/guards.d.ts +12 -0
  20. package/dist/guards.js +202 -0
  21. package/dist/host.d.ts +60 -0
  22. package/dist/host.js +374 -0
  23. package/dist/import-order.d.ts +2 -0
  24. package/dist/import-order.js +114 -0
  25. package/dist/index.d.ts +4 -0
  26. package/dist/index.js +2 -0
  27. package/dist/inline.d.ts +68 -0
  28. package/dist/inline.js +503 -0
  29. package/dist/iteration-admission.d.ts +76 -0
  30. package/dist/iteration-admission.js +72 -0
  31. package/dist/iteration-layout.d.ts +75 -0
  32. package/dist/iteration-layout.js +118 -0
  33. package/dist/iteration-owner.d.ts +32 -0
  34. package/dist/iteration-owner.js +223 -0
  35. package/dist/iteration-worker.d.ts +1 -0
  36. package/dist/iteration-worker.js +150 -0
  37. package/dist/iteration.d.ts +163 -0
  38. package/dist/iteration.js +435 -0
  39. package/dist/managed.d.ts +92 -0
  40. package/dist/managed.js +421 -0
  41. package/dist/memory.d.ts +10 -0
  42. package/dist/memory.js +89 -0
  43. package/dist/node.d.ts +138 -0
  44. package/dist/node.js +1153 -0
  45. package/dist/pages.d.ts +109 -0
  46. package/dist/pages.js +339 -0
  47. package/dist/remote.d.ts +86 -0
  48. package/dist/remote.js +255 -0
  49. package/dist/tasks.d.ts +107 -0
  50. package/dist/tasks.js +330 -0
  51. package/dist/transaction.d.ts +23 -0
  52. package/dist/transaction.js +93 -0
  53. package/dist/values.d.ts +3 -0
  54. package/dist/values.js +25 -0
  55. package/dist/worker.d.ts +1 -0
  56. package/dist/worker.js +86 -0
  57. package/package.json +130 -5
@@ -0,0 +1,1817 @@
1
+ import binaryen from 'binaryen';
2
+ import { restoreImportOrder } from "./import-order.js";
3
+ /** Calibrated on Apple M2 Pro; see `results/execution/admission/admission-calibration.summary.json`. */
4
+ export const DEFAULT_MINIMUM_REGION_WORK = 200_000;
5
+ export const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
6
+ // a tracked load or store costs about this many plain instructions in a speculative lane
7
+ const ACCESS_COST = 3600;
8
+ const CALL_COST = 2;
9
+ const SCALE_LIMIT = 2 ** 50;
10
+ const supported = new Set([
11
+ binaryen.BlockId,
12
+ binaryen.IfId,
13
+ binaryen.LoopId,
14
+ binaryen.BreakId,
15
+ binaryen.SwitchId,
16
+ binaryen.CallId,
17
+ binaryen.CallIndirectId,
18
+ binaryen.LocalGetId,
19
+ binaryen.LocalSetId,
20
+ binaryen.GlobalGetId,
21
+ binaryen.GlobalSetId,
22
+ binaryen.LoadId,
23
+ binaryen.StoreId,
24
+ binaryen.MemoryCopyId,
25
+ binaryen.MemoryFillId,
26
+ binaryen.MemoryInitId,
27
+ binaryen.DataDropId,
28
+ binaryen.MemorySizeId,
29
+ binaryen.MemoryGrowId,
30
+ binaryen.TableSizeId,
31
+ binaryen.ConstId,
32
+ binaryen.UnaryId,
33
+ binaryen.BinaryId,
34
+ binaryen.SelectId,
35
+ binaryen.DropId,
36
+ binaryen.ReturnId,
37
+ binaryen.NopId,
38
+ binaryen.UnreachableId
39
+ ]);
40
+ const pureNodes = new Set([
41
+ binaryen.BlockId,
42
+ binaryen.IfId,
43
+ binaryen.LoopId,
44
+ binaryen.BreakId,
45
+ binaryen.SwitchId,
46
+ binaryen.CallId,
47
+ binaryen.LocalGetId,
48
+ binaryen.LocalSetId,
49
+ binaryen.LoadId,
50
+ binaryen.StoreId,
51
+ binaryen.MemoryCopyId,
52
+ binaryen.MemoryFillId,
53
+ binaryen.ConstId,
54
+ binaryen.UnaryId,
55
+ binaryen.BinaryId,
56
+ binaryen.SelectId,
57
+ binaryen.DropId,
58
+ binaryen.ReturnId,
59
+ binaryen.NopId,
60
+ binaryen.UnreachableId
61
+ ]);
62
+ const raw = binaryen;
63
+ const numeric = new Set([binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64]);
64
+ function info(expression) {
65
+ const id = binaryen.getExpressionId(expression);
66
+ if (id === binaryen.NopId || id === binaryen.UnreachableId)
67
+ return { id, type: binaryen.getExpressionType(expression) };
68
+ return binaryen.getExpressionInfo(expression);
69
+ }
70
+ function children(v) {
71
+ switch (v.id) {
72
+ case binaryen.BlockId:
73
+ return v.children;
74
+ case binaryen.IfId:
75
+ return [v.condition, v.ifTrue, v.ifFalse].filter(Boolean);
76
+ case binaryen.LoopId:
77
+ return [v.body];
78
+ case binaryen.BreakId:
79
+ case binaryen.SwitchId:
80
+ return [v.value, v.condition].filter(Boolean);
81
+ case binaryen.CallId:
82
+ return v.operands;
83
+ case binaryen.CallIndirectId:
84
+ return [...v.operands, v.target];
85
+ case binaryen.LocalSetId:
86
+ case binaryen.GlobalSetId:
87
+ case binaryen.UnaryId:
88
+ case binaryen.DropId:
89
+ return [v.value];
90
+ case binaryen.LoadId:
91
+ return [v.ptr];
92
+ case binaryen.StoreId:
93
+ return [v.ptr, v.value];
94
+ case binaryen.BinaryId:
95
+ return [v.left, v.right];
96
+ case binaryen.SelectId:
97
+ return [v.ifTrue, v.ifFalse, v.condition];
98
+ case binaryen.ReturnId:
99
+ return v.value ? [v.value] : [];
100
+ case binaryen.MemoryGrowId:
101
+ return [v.delta];
102
+ case binaryen.MemoryCopyId:
103
+ return [v.dest, v.source, v.size];
104
+ case binaryen.MemoryFillId:
105
+ return [v.dest, v.value, v.size];
106
+ case binaryen.MemoryInitId:
107
+ return [v.dest, v.offset, v.size];
108
+ default:
109
+ return [];
110
+ }
111
+ }
112
+ function memoryCount(bytes) {
113
+ let cursor = 8;
114
+ const uint = () => {
115
+ let result = 0, shift = 0, byte;
116
+ do {
117
+ byte = bytes[cursor++];
118
+ result += (byte & 127) * 2 ** shift;
119
+ shift += 7;
120
+ } while (byte & 128);
121
+ return result;
122
+ };
123
+ let defined = 0;
124
+ while (cursor < bytes.length) {
125
+ const section = bytes[cursor++];
126
+ const length = uint();
127
+ const end = cursor + length;
128
+ if (section === 5)
129
+ defined = uint();
130
+ cursor = end;
131
+ }
132
+ return (defined +
133
+ WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(bytes))).filter((value) => value.kind === 'memory').length);
134
+ }
135
+ function memoryName(module) {
136
+ for (let i = 0; i < module.getNumExports(); i++) {
137
+ const exported = binaryen.getExportInfo(module.getExportByIndex(i));
138
+ if (exported.kind === binaryen.ExternalMemory)
139
+ return exported.value;
140
+ }
141
+ const token = /\(memory\s+(\$(?:"(?:\\.|[^"\\])*"|[^\s()]+))/.exec(module.emitText())?.[1];
142
+ if (!token)
143
+ throw new Error('missing memory name');
144
+ if (token[1] !== '"')
145
+ return token.slice(1);
146
+ const bytes = [];
147
+ const content = token.slice(2, -1);
148
+ for (let i = 0; i < content.length;) {
149
+ if (content[i] === '\\') {
150
+ bytes.push(Number.parseInt(content.slice(i + 1, i + 3), 16));
151
+ i += 3;
152
+ }
153
+ else {
154
+ const point = content.codePointAt(i);
155
+ bytes.push(...new TextEncoder().encode(String.fromCodePoint(point)));
156
+ i += point > 65535 ? 2 : 1;
157
+ }
158
+ }
159
+ return new TextDecoder().decode(new Uint8Array(bytes));
160
+ }
161
+ const comparisons = new Set([
162
+ binaryen.LtUInt32,
163
+ binaryen.LtSInt32,
164
+ binaryen.LeUInt32,
165
+ binaryen.LeSInt32,
166
+ binaryen.GtUInt32,
167
+ binaryen.GtSInt32,
168
+ binaryen.GeUInt32,
169
+ binaryen.GeSInt32,
170
+ binaryen.NeInt32
171
+ ]);
172
+ // a counted loop ends on a comparison of a counter local against a constant or an untouched input
173
+ function loopBound(loop, inputs) {
174
+ const body = info(loop.body);
175
+ const tail = body.id === binaryen.BlockId ? body.children.at(-1) : loop.body;
176
+ if (tail === undefined)
177
+ return;
178
+ const branch = info(tail);
179
+ if (branch.id !== binaryen.BreakId || branch.name !== loop.name || !branch.condition)
180
+ return;
181
+ const test = info(branch.condition);
182
+ if (test.id !== binaryen.BinaryId || !comparisons.has(test.op))
183
+ return;
184
+ const sides = [info(test.left), info(test.right)];
185
+ for (const [index, bound] of sides.entries()) {
186
+ if (bound.id === binaryen.ConstId && typeof bound.value === 'number' && bound.value >= 1)
187
+ return { constant: bound.value };
188
+ const counter = sides[1 - index];
189
+ if (inputs &&
190
+ bound.id === binaryen.LocalGetId &&
191
+ inputs.input(bound.index) &&
192
+ counter.id === binaryen.LocalGetId &&
193
+ inputs.counter(counter.index))
194
+ return { parameter: bound.index };
195
+ }
196
+ }
197
+ // a countdown loop ends on `local.tee $c (c - 1)`, so it runs for the value $c held on entry
198
+ function countdownLocal(loop) {
199
+ const body = info(loop.body);
200
+ const tail = body.id === binaryen.BlockId ? body.children.at(-1) : loop.body;
201
+ if (tail === undefined)
202
+ return;
203
+ const branch = info(tail);
204
+ if (branch.id !== binaryen.BreakId || branch.name !== loop.name || !branch.condition)
205
+ return;
206
+ const step = info(branch.condition);
207
+ if (step.id !== binaryen.LocalSetId || !step.isTee)
208
+ return;
209
+ const next = info(step.value);
210
+ if (next.id !== binaryen.BinaryId)
211
+ return;
212
+ const [from, by] = [info(next.left), info(next.right)];
213
+ if (from.id !== binaryen.LocalGetId || from.index !== step.index || by.id !== binaryen.ConstId)
214
+ return;
215
+ const down = (next.op === binaryen.AddInt32 && by.value === -1) ||
216
+ (next.op === binaryen.SubInt32 && by.value === 1);
217
+ return down ? step.index : undefined;
218
+ }
219
+ /**
220
+ * Trip-weighted instruction and tracked-access counts of one body, calls included. A loop bounded
221
+ * by an untouched input makes a term in that local; other unknown bounds use `assumedTrips`.
222
+ */
223
+ export function estimateTerms(body, callee, assumedTrips, inputs) {
224
+ const terms = new Map();
225
+ const add = (factor, params, compute, accesses) => {
226
+ const key = params.join(',');
227
+ const term = terms.get(key) ?? { params, compute: 0, accesses: 0 };
228
+ term.compute = Math.min(term.compute + factor * compute, SCALE_LIMIT);
229
+ term.accesses = Math.min(term.accesses + factor * accesses, SCALE_LIMIT);
230
+ terms.set(key, term);
231
+ };
232
+ // what a local was last set to in program order: an untouched input or a constant
233
+ const initial = new Map();
234
+ const visit = (expression, factor, params) => {
235
+ const v = info(expression);
236
+ let inner = factor;
237
+ let innerParams = params;
238
+ let countdown;
239
+ switch (v.id) {
240
+ case binaryen.LocalSetId: {
241
+ const value = info(v.value);
242
+ if (value.id === binaryen.LocalGetId && inputs?.input(value.index))
243
+ initial.set(v.index, { parameter: value.index });
244
+ else if (value.id === binaryen.ConstId &&
245
+ typeof value.value === 'number' &&
246
+ value.value >= 1)
247
+ initial.set(v.index, { constant: value.value });
248
+ else
249
+ initial.delete(v.index);
250
+ add(factor, params, 1, 0);
251
+ break;
252
+ }
253
+ case binaryen.LoopId: {
254
+ countdown = countdownLocal(v);
255
+ const bound = (countdown === undefined ? undefined : initial.get(countdown)) ??
256
+ loopBound(v, inputs);
257
+ if (bound && 'parameter' in bound)
258
+ innerParams = [...params, bound.parameter].sort((a, b) => a - b);
259
+ else
260
+ inner = Math.min(factor * (bound && 'constant' in bound ? bound.constant : assumedTrips), SCALE_LIMIT);
261
+ break;
262
+ }
263
+ case binaryen.CallId: {
264
+ const known = callee(v.target);
265
+ add(factor, params, CALL_COST + (known?.compute ?? 0), known?.accesses ?? 0);
266
+ break;
267
+ }
268
+ case binaryen.LoadId:
269
+ case binaryen.StoreId:
270
+ add(factor, params, 1, 1);
271
+ break;
272
+ case binaryen.MemoryCopyId:
273
+ case binaryen.MemoryFillId: {
274
+ const size = info(v.size);
275
+ add(factor, params, 1, size.id === binaryen.ConstId ? Number(size.value) >>> 0 : assumedTrips);
276
+ break;
277
+ }
278
+ case binaryen.BlockId:
279
+ case binaryen.ConstId:
280
+ case binaryen.LocalGetId:
281
+ case binaryen.NopId:
282
+ case binaryen.DropId:
283
+ break;
284
+ default:
285
+ add(factor, params, 1, 0);
286
+ }
287
+ for (const child of children(v))
288
+ visit(child, inner, innerParams);
289
+ if (countdown !== undefined)
290
+ initial.delete(countdown);
291
+ };
292
+ visit(body, 1, []);
293
+ return [...terms.values()];
294
+ }
295
+ function mergeTerms(lists) {
296
+ const merged = new Map();
297
+ for (const term of lists.flat()) {
298
+ const key = term.params.join(',');
299
+ const known = merged.get(key) ?? { params: term.params, compute: 0, accesses: 0 };
300
+ known.compute += term.compute;
301
+ known.accesses += term.accesses;
302
+ merged.set(key, known);
303
+ }
304
+ return [...merged.values()];
305
+ }
306
+ /** Numeric work with every parameter-bounded loop assumed to run `assumedTrips` times. */
307
+ export function settleWork(terms, assumedTrips) {
308
+ const total = { compute: 0, accesses: 0 };
309
+ for (const term of terms) {
310
+ const factor = Math.min(assumedTrips ** term.params.length, SCALE_LIMIT);
311
+ total.compute = Math.min(total.compute + factor * term.compute, SCALE_LIMIT);
312
+ total.accesses = Math.min(total.accesses + factor * term.accesses, SCALE_LIMIT);
313
+ }
314
+ return total;
315
+ }
316
+ export function estimateWork(body, callee, assumedTrips) {
317
+ return settleWork(estimateTerms(body, callee, assumedTrips), assumedTrips);
318
+ }
319
+ export const netWork = (work) => work.compute - ACCESS_COST * work.accesses;
320
+ /**
321
+ * `static` regions always run as regions, `dynamic` ones when their parameters make the estimate
322
+ * reach the threshold at the call, and the rest never. A threshold of zero admits every region.
323
+ */
324
+ function classify(terms, minimum) {
325
+ if (minimum === 0)
326
+ return 'static';
327
+ const fixed = terms.filter((term) => !term.params.length);
328
+ if (fixed.reduce((sum, term) => sum + netWork(term), 0) >= minimum)
329
+ return 'static';
330
+ return terms.some((term) => term.params.length && netWork(term) > 0) ? 'dynamic' : 'refused';
331
+ }
332
+ /** Resolves defaults and rejects values the estimate cannot use. */
333
+ export function admission(options) {
334
+ const minimumWork = options.minimumRegionWork ?? DEFAULT_MINIMUM_REGION_WORK;
335
+ const assumedTrips = options.assumedTripCount ?? DEFAULT_ASSUMED_TRIP_COUNT;
336
+ if (!Number.isFinite(minimumWork) || minimumWork < 0)
337
+ throw new RangeError('invalid minimumRegionWork');
338
+ if (!Number.isInteger(assumedTrips) || assumedTrips < 1)
339
+ throw new RangeError('invalid assumedTripCount');
340
+ return { minimumWork, assumedTrips };
341
+ }
342
+ // every function on a call cycle, in discovery order
343
+ function recursiveFunctions(calls) {
344
+ const indexes = new Map();
345
+ const lowlinks = new Map();
346
+ const stack = [];
347
+ const active = new Set();
348
+ const recursive = new Set();
349
+ const components = (name) => {
350
+ indexes.set(name, indexes.size);
351
+ lowlinks.set(name, indexes.get(name));
352
+ stack.push(name);
353
+ active.add(name);
354
+ for (const target of calls.get(name) ?? []) {
355
+ if (!calls.has(target))
356
+ continue;
357
+ if (!indexes.has(target)) {
358
+ components(target);
359
+ lowlinks.set(name, Math.min(lowlinks.get(name), lowlinks.get(target)));
360
+ }
361
+ else if (active.has(target))
362
+ lowlinks.set(name, Math.min(lowlinks.get(name), indexes.get(target)));
363
+ }
364
+ if (lowlinks.get(name) !== indexes.get(name))
365
+ return;
366
+ const component = [];
367
+ let member;
368
+ do {
369
+ member = stack.pop();
370
+ active.delete(member);
371
+ component.push(member);
372
+ } while (member !== name);
373
+ if (component.length > 1 || calls.get(name)?.has(name))
374
+ for (const member of component)
375
+ recursive.add(member);
376
+ };
377
+ for (const name of calls.keys())
378
+ if (!indexes.has(name))
379
+ components(name);
380
+ return recursive;
381
+ }
382
+ // memoized per-function work; a call cycle is cut at its back edge, so the estimate of a recursive
383
+ // function counts one level of its own calls and always terminates
384
+ function workModel(functions, included, assumedTrips) {
385
+ const known = new Map();
386
+ const termsOf = (name) => {
387
+ let terms = known.get(name);
388
+ if (!terms) {
389
+ known.set(name, []);
390
+ const f = functions.get(name);
391
+ const written = new Set();
392
+ const scan = (e) => {
393
+ const v = info(e);
394
+ if (v.id === binaryen.LocalSetId)
395
+ written.add(v.index);
396
+ for (const child of children(v))
397
+ scan(child);
398
+ };
399
+ scan(f.body);
400
+ const count = binaryen.expandType(f.params).length;
401
+ terms = estimateTerms(f.body, workOf, assumedTrips, {
402
+ input: (index) => index < count && !written.has(index),
403
+ counter: (index) => written.has(index)
404
+ });
405
+ known.set(name, terms);
406
+ }
407
+ return terms;
408
+ };
409
+ const workOf = (name) => included(name) ? settleWork(termsOf(name), assumedTrips) : undefined;
410
+ return { termsOf, workOf };
411
+ }
412
+ // a span with every reason it cannot move into another function; none means it can
413
+ function summarizeSpan(expression, allow = {}) {
414
+ const span = {
415
+ expression,
416
+ reads: new Map(),
417
+ writes: new Set(),
418
+ locals: new Set(),
419
+ memoryWrite: false,
420
+ compute: false
421
+ };
422
+ const refusals = new Set();
423
+ const labels = new Set();
424
+ const targets = [];
425
+ if (info(expression).type !== binaryen.none)
426
+ refusals.add('statement has a value');
427
+ const visit = (e) => {
428
+ const v = info(e);
429
+ if (v.id === binaryen.CallId) {
430
+ if (!allow.call?.(v.target))
431
+ refusals.add('call outside the worker set');
432
+ }
433
+ else if (v.id === binaryen.GlobalGetId) {
434
+ if (!allow.global?.(v.name))
435
+ refusals.add('global access');
436
+ }
437
+ else if (v.id === binaryen.CallIndirectId)
438
+ refusals.add('indirect call');
439
+ else if (v.id === binaryen.ReturnId)
440
+ refusals.add('return in the body');
441
+ else if (!pureNodes.has(v.id))
442
+ refusals.add('impure expression');
443
+ if (v.isAtomic)
444
+ refusals.add('atomic access');
445
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) && !numeric.has(v.type))
446
+ refusals.add('non-numeric value');
447
+ if ((v.id === binaryen.BlockId || v.id === binaryen.LoopId) && v.name)
448
+ labels.add(v.name);
449
+ if (v.id === binaryen.BreakId)
450
+ targets.push(v.name);
451
+ if (v.id === binaryen.SwitchId)
452
+ targets.push(...v.names, v.defaultName);
453
+ if (v.id === binaryen.LocalGetId) {
454
+ span.locals.add(v.index);
455
+ span.reads.set(v.index, (span.reads.get(v.index) ?? 0) + 1);
456
+ }
457
+ if (v.id === binaryen.LocalSetId) {
458
+ span.locals.add(v.index);
459
+ span.writes.add(v.index);
460
+ }
461
+ if ([binaryen.StoreId, binaryen.MemoryCopyId, binaryen.MemoryFillId].includes(v.id))
462
+ span.memoryWrite = true;
463
+ if ([binaryen.LoopId, binaryen.IfId, binaryen.BinaryId, binaryen.UnaryId].includes(v.id))
464
+ span.compute = true;
465
+ for (const child of children(v))
466
+ visit(child);
467
+ };
468
+ visit(expression);
469
+ if (!targets.every((target) => labels.has(target)))
470
+ refusals.add('branch escapes the body');
471
+ return { span, refusals };
472
+ }
473
+ // locals the spans write that something else reads, or that they read before assigning
474
+ function carriedLocals(spans, totalReads) {
475
+ const reads = new Map();
476
+ const writes = new Set();
477
+ for (const span of spans) {
478
+ for (const [index, amount] of span.reads)
479
+ reads.set(index, (reads.get(index) ?? 0) + amount);
480
+ for (const index of span.writes)
481
+ writes.add(index);
482
+ }
483
+ const carried = new Set([...writes].filter((index) => (totalReads.get(index) ?? 0) !== (reads.get(index) ?? 0)));
484
+ const exits = new Map();
485
+ const intersect = (paths) => paths.length
486
+ ? new Set([...paths[0]].filter((index) => paths.every((path) => path.has(index))))
487
+ : undefined;
488
+ const flow = (expression, incoming) => {
489
+ const v = info(expression);
490
+ let assigned = new Set(incoming);
491
+ if (v.id === binaryen.LocalGetId && writes.has(v.index) && !assigned.has(v.index))
492
+ carried.add(v.index);
493
+ if (v.id === binaryen.IfId) {
494
+ assigned = flow(v.condition, assigned);
495
+ if (!assigned)
496
+ return;
497
+ return intersect([flow(v.ifTrue, assigned), v.ifFalse ? flow(v.ifFalse, assigned) : assigned].filter((path) => path !== undefined));
498
+ }
499
+ if (v.id === binaryen.BlockId || v.id === binaryen.LoopId) {
500
+ if (v.name)
501
+ exits.set(v.name, []);
502
+ for (const child of children(v)) {
503
+ if (!assigned)
504
+ break;
505
+ assigned = flow(child, assigned);
506
+ }
507
+ const branches = v.name ? exits.get(v.name) : [];
508
+ if (v.name)
509
+ exits.delete(v.name);
510
+ return intersect([
511
+ ...(assigned ? [assigned] : []),
512
+ ...(v.id === binaryen.BlockId ? branches : [])
513
+ ]);
514
+ }
515
+ for (const child of children(v)) {
516
+ if (!assigned)
517
+ return;
518
+ assigned = flow(child, assigned);
519
+ }
520
+ if (!assigned)
521
+ return;
522
+ if (v.id === binaryen.LocalSetId)
523
+ assigned.add(v.index);
524
+ if (v.id === binaryen.BreakId || v.id === binaryen.SwitchId) {
525
+ const targets = v.id === binaryen.SwitchId ? [...v.names, v.defaultName] : [v.name];
526
+ for (const target of targets)
527
+ exits.get(target)?.push(new Set(assigned));
528
+ if (v.id === binaryen.SwitchId || !v.condition)
529
+ return;
530
+ }
531
+ return v.id === binaryen.UnreachableId ? undefined : assigned;
532
+ };
533
+ let assigned = new Set();
534
+ for (const span of spans) {
535
+ if (!assigned)
536
+ break;
537
+ assigned = flow(span.expression, assigned);
538
+ }
539
+ return carried;
540
+ }
541
+ // renumbers the locals of an expression in place
542
+ function remapLocals(expression, positions) {
543
+ const v = info(expression);
544
+ if (v.id === binaryen.LocalGetId)
545
+ raw._BinaryenLocalGetSetIndex(expression, positions.get(v.index));
546
+ if (v.id === binaryen.LocalSetId)
547
+ raw._BinaryenLocalSetSetIndex(expression, positions.get(v.index));
548
+ for (const child of children(v))
549
+ remapLocals(child, positions);
550
+ }
551
+ export function extract(original, prepareTracked, options = {}) {
552
+ const { minimumWork, assumedTrips } = admission(options);
553
+ let module;
554
+ let worker;
555
+ try {
556
+ if (memoryCount(original) !== 1)
557
+ return;
558
+ module = binaryen.readBinary(original);
559
+ const memory = module.getMemoryInfo();
560
+ if (memory.is64)
561
+ return;
562
+ const m = module;
563
+ const compactImports = binaryen.Features
564
+ .CompactImports;
565
+ m.setFeatures(binaryen.Features.All & ~compactImports);
566
+ const internalMemory = memoryName(m);
567
+ const functions = new Map();
568
+ let outlineIndex = 0;
569
+ const originals = Array.from({ length: m.getNumFunctions() }, (_, index) => binaryen.getFunctionInfo(m.getFunctionByIndex(index)));
570
+ const originalBodies = new Map(originals.filter((f) => f.body).map((f) => [f.name, m.copyExpression(f.body)]));
571
+ for (const f of originals) {
572
+ if (!f.body)
573
+ continue;
574
+ const localTypes = [...binaryen.expandType(f.params), ...f.vars];
575
+ if (!localTypes.every((type) => numeric.has(type)))
576
+ continue;
577
+ const totalReads = new Map();
578
+ let traversable = true;
579
+ const count = (expression) => {
580
+ const v = info(expression);
581
+ if (!supported.has(v.id))
582
+ traversable = false;
583
+ if (v.id === binaryen.LocalGetId)
584
+ totalReads.set(v.index, (totalReads.get(v.index) ?? 0) + 1);
585
+ for (const child of children(v))
586
+ count(child);
587
+ };
588
+ try {
589
+ count(f.body);
590
+ }
591
+ catch {
592
+ traversable = false;
593
+ }
594
+ if (!traversable)
595
+ continue;
596
+ const summarize = (expression) => {
597
+ const summary = summarizeSpan(expression);
598
+ return summary.refusals.size ? undefined : summary.span;
599
+ };
600
+ const outline = (spans) => {
601
+ const carried = carriedLocals(spans, totalReads);
602
+ if (carried.size) {
603
+ const result = [];
604
+ let pending = [];
605
+ for (const span of spans) {
606
+ if ([...span.writes].some((index) => carried.has(index))) {
607
+ if (pending.length)
608
+ result.push(...outline(pending));
609
+ pending = [];
610
+ result.push(span.expression);
611
+ }
612
+ else
613
+ pending.push(span);
614
+ }
615
+ if (pending.length)
616
+ result.push(...outline(pending));
617
+ return result;
618
+ }
619
+ if (!spans.some((span) => span.memoryWrite) || !spans.some((span) => span.compute))
620
+ return spans.map((span) => span.expression);
621
+ const written = new Set(spans.flatMap((span) => [...span.writes]));
622
+ const spanned = mergeTerms(spans.map((span) => estimateTerms(span.expression, () => undefined, assumedTrips, {
623
+ input: (index) => !written.has(index),
624
+ counter: (index) => written.has(index)
625
+ })));
626
+ const verdict = classify(spanned, minimumWork);
627
+ if (options.observed) {
628
+ const work = settleWork(spanned, assumedTrips);
629
+ options.observed({ name: `span in ${f.name}`, kind: verdict, ...work });
630
+ }
631
+ if (verdict === 'refused')
632
+ return spans.map((span) => span.expression);
633
+ const captured = [...new Set(spans.flatMap((span) => [...span.locals]))].sort((a, b) => a - b);
634
+ const positions = new Map(captured.map((index, position) => [index, position]));
635
+ const body = m.block(null, spans.map((span) => m.copyExpression(span.expression)));
636
+ remapLocals(body, positions);
637
+ let name;
638
+ do {
639
+ name = `__folio_inline_${outlineIndex++}`;
640
+ } while (m.getFunction(name));
641
+ m.addFunction(name, binaryen.createType(captured.map((index) => localTypes[index])), binaryen.none, [], body);
642
+ return [
643
+ m.call(name, captured.map((index) => m.local.get(index, localTypes[index])), binaryen.none)
644
+ ];
645
+ };
646
+ const rewrite = (expression) => {
647
+ const v = info(expression);
648
+ for (const child of children(v))
649
+ rewrite(child);
650
+ if (v.id !== binaryen.BlockId)
651
+ return;
652
+ const current = info(expression).children;
653
+ const rewritten = [];
654
+ let pending = [];
655
+ for (const child of current) {
656
+ const span = summarize(child);
657
+ if (span)
658
+ pending.push(span);
659
+ else {
660
+ if (pending.length)
661
+ rewritten.push(...outline(pending));
662
+ pending = [];
663
+ rewritten.push(child);
664
+ }
665
+ }
666
+ if (pending.length)
667
+ rewritten.push(...outline(pending));
668
+ for (let i = current.length - 1; i >= 0; i--)
669
+ raw._BinaryenBlockRemoveChildAt(expression, i);
670
+ for (const child of rewritten)
671
+ raw._BinaryenBlockAppendChild(expression, child);
672
+ };
673
+ rewrite(f.body);
674
+ }
675
+ for (let i = 0; i < m.getNumFunctions(); i++) {
676
+ const f = binaryen.getFunctionInfo(m.getFunctionByIndex(i));
677
+ functions.set(f.name, f);
678
+ }
679
+ const controllers = new Set();
680
+ const pure = new Set();
681
+ const calls = new Map();
682
+ const diagnostics = [];
683
+ for (const f of functions.values()) {
684
+ if (!f.body)
685
+ continue;
686
+ let control = [...binaryen.expandType(f.params), ...f.vars].every((t) => numeric.has(t)) &&
687
+ (f.results === binaryen.none || numeric.has(f.results));
688
+ let candidate = control;
689
+ const targets = new Set();
690
+ const visit = (expression) => {
691
+ const v = info(expression);
692
+ if (!supported.has(v.id))
693
+ control = false;
694
+ if (!pureNodes.has(v.id) || v.isAtomic)
695
+ candidate = false;
696
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) &&
697
+ !numeric.has(v.type)) {
698
+ control = false;
699
+ candidate = false;
700
+ }
701
+ if (v.id === binaryen.CallId) {
702
+ targets.add(v.target);
703
+ if (v.operands.some((e) => !numeric.has(info(e).type)))
704
+ control = false;
705
+ }
706
+ if (v.id === binaryen.CallIndirectId &&
707
+ children(v).some((e) => !numeric.has(info(e).type)))
708
+ control = false;
709
+ for (const child of children(v))
710
+ visit(child);
711
+ };
712
+ try {
713
+ visit(f.body);
714
+ }
715
+ catch {
716
+ control = candidate = false;
717
+ }
718
+ calls.set(f.name, targets);
719
+ if (control)
720
+ controllers.add(f.name);
721
+ else
722
+ diagnostics.push(`ordered native function: ${f.name}`);
723
+ if (candidate && control)
724
+ pure.add(f.name);
725
+ }
726
+ for (const name of recursiveFunctions(calls)) {
727
+ controllers.delete(name);
728
+ pure.delete(name);
729
+ diagnostics.push(`ordered native recursion: ${name}`);
730
+ }
731
+ for (let changed = true; changed;) {
732
+ changed = false;
733
+ for (const name of pure) {
734
+ if ([...calls.get(name)].some((target) => !pure.has(target))) {
735
+ pure.delete(name);
736
+ changed = true;
737
+ }
738
+ }
739
+ }
740
+ if (!pure.size) {
741
+ options.refused?.('no pure function to run as a region');
742
+ return;
743
+ }
744
+ const { termsOf } = workModel(functions, (name) => pure.has(name), assumedTrips);
745
+ const admitted = new Set();
746
+ const guarded = new Map();
747
+ for (const name of pure) {
748
+ const kind = classify(termsOf(name), minimumWork);
749
+ options.observed?.({
750
+ name,
751
+ kind,
752
+ ...settleWork(termsOf(name), assumedTrips)
753
+ });
754
+ if (kind !== 'refused')
755
+ admitted.add(name);
756
+ if (kind === 'dynamic')
757
+ guarded.set(name, termsOf(name));
758
+ }
759
+ const enqueued = new Set();
760
+ const queued = new Set();
761
+ const enqueues = (v) => {
762
+ const call = v.id === binaryen.DropId ? info(v.value) : v;
763
+ const direct = v.id === binaryen.CallId && v.type === binaryen.none;
764
+ if (call.id === binaryen.CallId &&
765
+ !call.isReturn &&
766
+ (direct || v.id === binaryen.DropId) &&
767
+ admitted.has(call.target))
768
+ return call.target;
769
+ };
770
+ for (const name of controllers) {
771
+ const visit = (e) => {
772
+ const v = info(e);
773
+ const target = enqueues(v);
774
+ if (target) {
775
+ enqueued.add(target);
776
+ queued.add(name);
777
+ }
778
+ for (const child of children(v))
779
+ visit(child);
780
+ };
781
+ visit(functions.get(name).body);
782
+ }
783
+ if (!enqueued.size) {
784
+ options.refused?.(admitted.size
785
+ ? `no admitted region has a call site (${pure.size} pure functions, ${admitted.size} admitted)`
786
+ : `no region reached ${minimumWork} net work (${pure.size} pure functions, none admitted)`);
787
+ return;
788
+ }
789
+ for (let changed = true; changed;) {
790
+ changed = false;
791
+ for (const name of controllers) {
792
+ if (!queued.has(name) &&
793
+ [...calls.get(name)].some((target) => controllers.has(target) && queued.has(target))) {
794
+ queued.add(name);
795
+ changed = true;
796
+ }
797
+ }
798
+ }
799
+ // a function that never reaches a region keeps its original body and runs natively
800
+ for (const name of [...controllers])
801
+ if (!queued.has(name))
802
+ controllers.delete(name);
803
+ for (const f of originals) {
804
+ if (f.body && !controllers.has(f.name))
805
+ raw._BinaryenFunctionSetBody(m.getFunction(f.name), originalBodies.get(f.name));
806
+ }
807
+ diagnostics.push(`region admission: ${enqueued.size} regions from ${admitted.size} of ${pure.size} pure functions at ${minimumWork} net work; ${queued.size} instrumented`);
808
+ let namespace = '__folio_control';
809
+ const imported = WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original)));
810
+ while (imported.some((item) => item.module === namespace))
811
+ namespace += '_';
812
+ let serial = '__folio_control_serial';
813
+ while (m.getGlobal(serial))
814
+ serial += '_';
815
+ let pending = '__folio_control_pending';
816
+ while (m.getGlobal(pending))
817
+ pending += '_';
818
+ let memoryExport = '__folio_control_memory';
819
+ while (m.getExport(memoryExport))
820
+ memoryExport += '_';
821
+ const unique = (stem) => {
822
+ let name = stem;
823
+ while (m.getFunction(name) || m.getExport(name))
824
+ name += '_';
825
+ return name;
826
+ };
827
+ const barrier = unique('__folio_control_barrier');
828
+ m.addFunctionImport(barrier, namespace, 'barrier', binaryen.none, binaryen.none);
829
+ const poll = unique('__folio_control_poll');
830
+ m.addFunctionImport(poll, namespace, 'poll', binaryen.none, binaryen.none);
831
+ m.addGlobalImport(serial, namespace, 'serial', binaryen.i32, true);
832
+ m.addGlobalImport(pending, namespace, 'pending', binaryen.i32, true);
833
+ m.addMemoryExport(internalMemory, memoryExport);
834
+ worker = new binaryen.Module();
835
+ const w = worker;
836
+ const maximum = memory.max ?? 65536;
837
+ w.setFeatures(m.getFeatures() | binaryen.Features.Atomics);
838
+ w.setMemory(memory.initial, maximum, null, [], true, false, internalMemory);
839
+ w.addMemoryImport(internalMemory, 'env', 'memory', true);
840
+ for (const name of pure) {
841
+ const f = functions.get(name);
842
+ w.addFunction(name, f.params, f.results, f.vars, w.copyExpression(f.body));
843
+ }
844
+ for (let i = 0; i < m.getNumExports(); i++) {
845
+ const exported = binaryen.getExportInfo(m.getExportByIndex(i));
846
+ if (exported.kind === binaryen.ExternalFunction && pure.has(exported.value))
847
+ w.addFunctionExport(exported.value, exported.name);
848
+ }
849
+ const regions = [];
850
+ const enqueueFor = new Map();
851
+ for (const name of enqueued) {
852
+ const f = functions.get(name);
853
+ const params = binaryen.expandType(f.params);
854
+ const encoded = params.map((t) => t === binaryen.i64 || t === binaryen.f64 ? binaryen.i64 : binaryen.i32);
855
+ const exportName = unique(`__folio_region_${regions.length}`);
856
+ const importName = `region_${regions.length}`;
857
+ const descriptor = {
858
+ importName,
859
+ exportName,
860
+ parameters: encoded.map((t) => t === binaryen.i64 ? 'i64' : 'i32')
861
+ };
862
+ regions.push(descriptor);
863
+ const wrapper = (target) => {
864
+ const args = params.map((t, i) => {
865
+ const value = target.local.get(i, encoded[i]);
866
+ return t === binaryen.f32
867
+ ? target.f32.reinterpret(value)
868
+ : t === binaryen.f64
869
+ ? target.f64.reinterpret(value)
870
+ : value;
871
+ });
872
+ const call = target.call(name, args, f.results);
873
+ target.addFunction(exportName, binaryen.createType(encoded), binaryen.none, [], f.results === binaryen.none ? call : target.drop(call));
874
+ target.addFunctionExport(exportName, exportName);
875
+ };
876
+ wrapper(m);
877
+ wrapper(w);
878
+ const enqueue = unique(`__folio_enqueue_${regions.length - 1}`);
879
+ enqueueFor.set(name, enqueue);
880
+ m.addFunctionImport(enqueue, namespace, importName, binaryen.createType(encoded), binaryen.none);
881
+ }
882
+ const labels = new Map();
883
+ for (const name of controllers) {
884
+ const map = new Map();
885
+ const existing = new Set();
886
+ const visit = (e) => {
887
+ const v = info(e);
888
+ if ((v.id === binaryen.BlockId || v.id === binaryen.LoopId) && v.name)
889
+ existing.add(v.name);
890
+ for (const child of children(v))
891
+ visit(child);
892
+ };
893
+ visit(functions.get(name).body);
894
+ for (const label of existing) {
895
+ let replacement = `${label}__folio`;
896
+ while (existing.has(replacement) || [...map.values()].includes(replacement))
897
+ replacement += '_';
898
+ map.set(label, replacement);
899
+ }
900
+ labels.set(name, map);
901
+ }
902
+ let helperIndex = 0;
903
+ const memoryHelpers = new Map();
904
+ const trappedUnary = new Set([
905
+ binaryen.TruncSFloat32ToInt32,
906
+ binaryen.TruncUFloat32ToInt32,
907
+ binaryen.TruncSFloat64ToInt32,
908
+ binaryen.TruncUFloat64ToInt32,
909
+ binaryen.TruncSFloat32ToInt64,
910
+ binaryen.TruncUFloat32ToInt64,
911
+ binaryen.TruncSFloat64ToInt64,
912
+ binaryen.TruncUFloat64ToInt64
913
+ ]);
914
+ const trappedBinary = new Set([
915
+ binaryen.DivSInt32,
916
+ binaryen.DivUInt32,
917
+ binaryen.RemSInt32,
918
+ binaryen.RemUInt32,
919
+ binaryen.DivSInt64,
920
+ binaryen.DivUInt64,
921
+ binaryen.RemSInt64,
922
+ binaryen.RemUInt64
923
+ ]);
924
+ // the host raises `pending` while regions are queued; an empty queue never crosses into JSPI
925
+ const whenPending = (target) => m.if(m.global.get(pending, binaryen.i32), m.call(target, [], binaryen.none));
926
+ const drain = () => whenPending(barrier);
927
+ const joinPoll = () => whenPending(poll);
928
+ // a call the owner makes natively: queued regions join first, and callees see serial set
929
+ const hostCalls = new Map();
930
+ const hostCall = (target) => {
931
+ const known = hostCalls.get(target);
932
+ if (known)
933
+ return known;
934
+ const callee = functions.get(target);
935
+ const types = binaryen.expandType(callee.params);
936
+ const result = callee.results;
937
+ const name = unique(`__folio_control_host_${helperIndex++}`);
938
+ const native = m.call(target, types.map((t, i) => m.local.get(i, t)), result);
939
+ const prefix = [drain(), m.global.set(serial, m.i32.const(1))];
940
+ const vars = result === binaryen.none ? [] : [result];
941
+ const code = vars.length
942
+ ? m.block(null, [
943
+ ...prefix,
944
+ m.local.set(types.length, native),
945
+ m.global.set(serial, m.i32.const(0)),
946
+ m.local.get(types.length, result)
947
+ ], result)
948
+ : m.block(null, [...prefix, native, m.global.set(serial, m.i32.const(0))], result);
949
+ m.addFunction(name, binaryen.createType(types), result, vars, code);
950
+ hostCalls.set(target, name);
951
+ return name;
952
+ };
953
+ // a region with a parameter-bounded loop compares its estimate with the threshold per call
954
+ const routes = new Map();
955
+ for (const name of enqueued) {
956
+ const entry = enqueueFor.get(name);
957
+ const terms = guarded.get(name);
958
+ if (!terms) {
959
+ routes.set(name, { callee: entry, encoded: true });
960
+ continue;
961
+ }
962
+ const f = functions.get(name);
963
+ const params = binaryen.expandType(f.params);
964
+ const local = (i) => m.local.get(i, params[i]);
965
+ let work = m.f64.const(0);
966
+ for (const term of terms) {
967
+ if (!netWork(term))
968
+ continue;
969
+ let product = m.f64.const(netWork(term));
970
+ for (const parameter of term.params)
971
+ product = m.f64.mul(product, m.f64.convert_u.i32(local(parameter)));
972
+ work = m.f64.add(work, product);
973
+ }
974
+ const queue = m.call(entry, params.map((t, i) => t === binaryen.f32
975
+ ? m.i32.reinterpret(local(i))
976
+ : t === binaryen.f64
977
+ ? m.i64.reinterpret(local(i))
978
+ : local(i)), binaryen.none);
979
+ const native = m.call(hostCall(name), params.map((_, i) => local(i)), f.results);
980
+ const dispatch = unique(`__folio_dispatch_${routes.size}`);
981
+ m.addFunction(dispatch, binaryen.createType(params), binaryen.none, [], m.if(m.f64.ge(work, m.f64.const(minimumWork)), queue, f.results === binaryen.none ? native : m.drop(native)));
982
+ routes.set(name, { callee: dispatch, encoded: false });
983
+ }
984
+ const helper = (expression, operands, setters, opaque = false) => {
985
+ const v = info(expression);
986
+ const resultType = v.id === binaryen.CallIndirectId ? v.results : v.type;
987
+ const types = operands.map((e) => info(e).type);
988
+ if (types.some((type) => !numeric.has(type)))
989
+ throw new Error('non-scalar helper operand');
990
+ // One memory is admitted. Retain every opcode attribute; only operands become parameters.
991
+ const memoryKey = v.id === binaryen.LoadId || v.id === binaryen.StoreId
992
+ ? JSON.stringify([
993
+ types,
994
+ Object.entries(v).filter(([key]) => key !== 'ptr' && key !== 'value')
995
+ ])
996
+ : undefined;
997
+ if (memoryKey !== undefined) {
998
+ const existing = memoryHelpers.get(memoryKey);
999
+ if (existing)
1000
+ return existing;
1001
+ }
1002
+ const body = v.id === binaryen.CallIndirectId && v.isReturn
1003
+ ? m.call_indirect(v.table, v.target, v.operands, v.params, v.results)
1004
+ : m.copyExpression(expression);
1005
+ for (let i = 0; i < setters.length; i++) {
1006
+ if (setters[i].startsWith('operand:')) {
1007
+ const index = Number(setters[i].slice(8));
1008
+ raw._BinaryenCallIndirectSetOperandAt(body, index, m.local.get(i, types[i]));
1009
+ }
1010
+ else
1011
+ raw[setters[i]](body, m.local.get(i, types[i]));
1012
+ }
1013
+ const name = unique(`__folio_control_helper_${helperIndex++}`);
1014
+ let code;
1015
+ const vars = [];
1016
+ if (!opaque)
1017
+ code = m.block(null, [drain(), body], resultType);
1018
+ else {
1019
+ const prefix = [drain(), m.global.set(serial, m.i32.const(1))];
1020
+ if (resultType === binaryen.none || resultType === binaryen.unreachable)
1021
+ code = m.block(null, [...prefix, body, m.global.set(serial, m.i32.const(0))], resultType);
1022
+ else {
1023
+ vars.push(resultType);
1024
+ code = m.block(null, [
1025
+ ...prefix,
1026
+ m.local.set(types.length, body),
1027
+ m.global.set(serial, m.i32.const(0)),
1028
+ m.local.get(types.length, resultType)
1029
+ ], resultType);
1030
+ }
1031
+ }
1032
+ const result = resultType === binaryen.unreachable ? binaryen.none : resultType;
1033
+ m.addFunction(name, binaryen.createType(types), result, vars, code);
1034
+ const reference = { name, result };
1035
+ if (memoryKey !== undefined)
1036
+ memoryHelpers.set(memoryKey, reference);
1037
+ return reference;
1038
+ };
1039
+ const lower = (expression, owner) => {
1040
+ const v = info(expression);
1041
+ const label = (name) => labels.get(owner).get(name) ?? name;
1042
+ const callHelper = (operands, setters, opaque = false) => {
1043
+ const h = helper(expression, operands, setters, opaque);
1044
+ const values = operands.map((e) => lower(e, owner));
1045
+ return v.id === binaryen.CallIndirectId && v.isReturn
1046
+ ? m.return_call(h.name, values, h.result)
1047
+ : m.call(h.name, values, h.result);
1048
+ };
1049
+ const enqueue = (call) => {
1050
+ const route = routes.get(call.target);
1051
+ const values = call.operands.map((e) => {
1052
+ const value = lower(e, owner);
1053
+ const type = info(e).type;
1054
+ return !route.encoded
1055
+ ? value
1056
+ : type === binaryen.f32
1057
+ ? m.i32.reinterpret(value)
1058
+ : type === binaryen.f64
1059
+ ? m.i64.reinterpret(value)
1060
+ : value;
1061
+ });
1062
+ return m.call(route.callee, values, binaryen.none);
1063
+ };
1064
+ switch (v.id) {
1065
+ case binaryen.BlockId:
1066
+ return m.block(label(v.name), v.children.map((e) => lower(e, owner)), v.type);
1067
+ case binaryen.IfId:
1068
+ return m.if(lower(v.condition, owner), lower(v.ifTrue, owner), v.ifFalse ? lower(v.ifFalse, owner) : undefined);
1069
+ case binaryen.LoopId:
1070
+ return m.loop(label(v.name), m.block(null, [joinPoll(), lower(v.body, owner)], info(v.body).type));
1071
+ case binaryen.BreakId:
1072
+ return m.br(label(v.name), v.condition ? lower(v.condition, owner) : undefined, v.value ? lower(v.value, owner) : undefined);
1073
+ case binaryen.SwitchId:
1074
+ return m.switch(v.names.map(label), label(v.defaultName), lower(v.condition, owner), v.value ? lower(v.value, owner) : undefined);
1075
+ case binaryen.CallId: {
1076
+ if (!v.isReturn && v.type === binaryen.none && enqueueFor.has(v.target))
1077
+ return enqueue(v);
1078
+ const result = functions.get(v.target).results;
1079
+ const args = v.operands.map((e) => lower(e, owner));
1080
+ if (controllers.has(v.target))
1081
+ return v.isReturn
1082
+ ? m.return_call(v.target, args, result)
1083
+ : m.call(v.target, args, result);
1084
+ const target = hostCall(v.target);
1085
+ return v.isReturn
1086
+ ? m.return_call(target, args, result)
1087
+ : m.call(target, args, result);
1088
+ }
1089
+ case binaryen.CallIndirectId:
1090
+ return callHelper([...v.operands, v.target], [
1091
+ ...v.operands.map((_, i) => `operand:${i}`),
1092
+ '_BinaryenCallIndirectSetTarget'
1093
+ ], true);
1094
+ case binaryen.LocalSetId:
1095
+ return v.isTee
1096
+ ? m.local.tee(v.index, lower(v.value, owner), v.type)
1097
+ : m.local.set(v.index, lower(v.value, owner));
1098
+ case binaryen.LoadId:
1099
+ return callHelper([v.ptr], ['_BinaryenLoadSetPtr']);
1100
+ case binaryen.StoreId:
1101
+ return callHelper([v.ptr, v.value], ['_BinaryenStoreSetPtr', '_BinaryenStoreSetValue']);
1102
+ case binaryen.GlobalGetId:
1103
+ case binaryen.MemorySizeId:
1104
+ case binaryen.TableSizeId:
1105
+ case binaryen.DataDropId:
1106
+ return callHelper([], []);
1107
+ case binaryen.GlobalSetId:
1108
+ return callHelper([v.value], ['_BinaryenGlobalSetSetValue']);
1109
+ case binaryen.MemoryGrowId:
1110
+ return callHelper([v.delta], ['_BinaryenMemoryGrowSetDelta']);
1111
+ case binaryen.MemoryCopyId:
1112
+ return callHelper([v.dest, v.source, v.size], [
1113
+ '_BinaryenMemoryCopySetDest',
1114
+ '_BinaryenMemoryCopySetSource',
1115
+ '_BinaryenMemoryCopySetSize'
1116
+ ]);
1117
+ case binaryen.MemoryFillId:
1118
+ return callHelper([v.dest, v.value, v.size], [
1119
+ '_BinaryenMemoryFillSetDest',
1120
+ '_BinaryenMemoryFillSetValue',
1121
+ '_BinaryenMemoryFillSetSize'
1122
+ ]);
1123
+ case binaryen.MemoryInitId:
1124
+ return callHelper([v.dest, v.offset, v.size], [
1125
+ '_BinaryenMemoryInitSetDest',
1126
+ '_BinaryenMemoryInitSetOffset',
1127
+ '_BinaryenMemoryInitSetSize'
1128
+ ]);
1129
+ case binaryen.UnaryId:
1130
+ return trappedUnary.has(v.op)
1131
+ ? callHelper([v.value], ['_BinaryenUnarySetValue'])
1132
+ : raw._BinaryenUnary(m.ptr, v.op, lower(v.value, owner));
1133
+ case binaryen.BinaryId:
1134
+ return trappedBinary.has(v.op)
1135
+ ? callHelper([v.left, v.right], ['_BinaryenBinarySetLeft', '_BinaryenBinarySetRight'])
1136
+ : raw._BinaryenBinary(m.ptr, v.op, lower(v.left, owner), lower(v.right, owner));
1137
+ case binaryen.SelectId:
1138
+ return m.select(lower(v.condition, owner), lower(v.ifTrue, owner), lower(v.ifFalse, owner));
1139
+ case binaryen.DropId: {
1140
+ const child = info(v.value);
1141
+ return child.id === binaryen.CallId &&
1142
+ !child.isReturn &&
1143
+ enqueueFor.has(child.target)
1144
+ ? enqueue(child)
1145
+ : m.drop(lower(v.value, owner));
1146
+ }
1147
+ case binaryen.ReturnId:
1148
+ return m.return(v.value ? lower(v.value, owner) : undefined);
1149
+ case binaryen.UnreachableId:
1150
+ return m.block(null, [drain(), m.unreachable()]);
1151
+ default:
1152
+ return m.copyExpression(expression);
1153
+ }
1154
+ };
1155
+ for (const name of controllers) {
1156
+ const f = functions.get(name);
1157
+ const transformed = m.block(null, [joinPoll(), lower(f.body, name)], f.results);
1158
+ raw._BinaryenFunctionSetBody(m.getFunction(name), m.if(m.global.get(serial, binaryen.i32), m.copyExpression(originalBodies.get(name) ?? f.body), transformed));
1159
+ }
1160
+ const entries = [];
1161
+ for (let i = 0; i < m.getNumExports(); i++) {
1162
+ const exported = binaryen.getExportInfo(m.getExportByIndex(i));
1163
+ if (exported.kind === binaryen.ExternalFunction &&
1164
+ functions.has(exported.value) &&
1165
+ queued.has(exported.value))
1166
+ entries.push(exported.name);
1167
+ }
1168
+ if (!entries.length) {
1169
+ options.refused?.('no exported function reaches an admitted region');
1170
+ return;
1171
+ }
1172
+ if (!m.validate() || !w.validate())
1173
+ throw new Error('invalid control extraction');
1174
+ const coordinator = restoreImportOrder(m.emitBinary(), WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original))));
1175
+ const workerOriginal = w.emitBinary();
1176
+ new WebAssembly.Module(Uint8Array.from(coordinator));
1177
+ new WebAssembly.Module(Uint8Array.from(workerOriginal));
1178
+ const transactional = prepareTracked(workerOriginal).transactional;
1179
+ if (!transactional)
1180
+ throw new Error('control worker transactional lowering unavailable');
1181
+ new WebAssembly.Module(Uint8Array.from(transactional));
1182
+ return {
1183
+ coordinator,
1184
+ workerOriginal,
1185
+ transactional,
1186
+ namespace,
1187
+ serialGlobal: 'serial',
1188
+ pendingGlobal: 'pending',
1189
+ memoryExport,
1190
+ shared: memory.shared,
1191
+ initial: memory.initial,
1192
+ maximum,
1193
+ entries,
1194
+ regions,
1195
+ diagnostics
1196
+ };
1197
+ }
1198
+ finally {
1199
+ worker?.dispose();
1200
+ module?.dispose();
1201
+ }
1202
+ }
1203
+ /** Computes the stack route of a module. A failure is reported in `diagnostics`, never thrown. */
1204
+ export function stackRoute(original, options = {}) {
1205
+ const { assumedTrips } = admission(options);
1206
+ const route = {
1207
+ eligible: false,
1208
+ constants: [],
1209
+ functions: [],
1210
+ recursive: [],
1211
+ work: Object.create(null),
1212
+ diagnostics: []
1213
+ };
1214
+ let module;
1215
+ try {
1216
+ if (memoryCount(original) !== 1) {
1217
+ route.diagnostics.push('exactly one memory required');
1218
+ return route;
1219
+ }
1220
+ module = binaryen.readBinary(original);
1221
+ if (module.getMemoryInfo().is64) {
1222
+ route.diagnostics.push('wasm64 memory');
1223
+ return route;
1224
+ }
1225
+ const compactImports = binaryen.Features
1226
+ .CompactImports;
1227
+ module.setFeatures(binaryen.Features.All & ~compactImports);
1228
+ const globals = new Map();
1229
+ for (let i = 0; i < module.getNumGlobals(); i++) {
1230
+ const g = binaryen.getGlobalInfo(module.getGlobalByIndex(i));
1231
+ const init = g.module ? undefined : info(g.init);
1232
+ const constant = init?.id === binaryen.ConstId;
1233
+ globals.set(g.name, {
1234
+ mutable: g.mutable,
1235
+ constant,
1236
+ initial: constant && g.type === binaryen.i32 ? Number(init.value) : undefined,
1237
+ refusal: g.module
1238
+ ? 'imported global'
1239
+ : !numeric.has(g.type)
1240
+ ? 'reference-typed global'
1241
+ : !constant
1242
+ ? 'initializer is not a constant'
1243
+ : g.mutable && g.type !== binaryen.i32
1244
+ ? 'mutable global is not i32'
1245
+ : undefined
1246
+ });
1247
+ }
1248
+ const bodies = [];
1249
+ for (let i = 0; i < module.getNumFunctions(); i++) {
1250
+ const f = binaryen.getFunctionInfo(module.getFunctionByIndex(i));
1251
+ if (!f.body)
1252
+ continue;
1253
+ const body = { info: f, targets: new Set(), refs: new Set() };
1254
+ if (![...binaryen.expandType(f.params), ...f.vars].every((t) => numeric.has(t)) ||
1255
+ !(f.results === binaryen.none || numeric.has(f.results)))
1256
+ body.cause = 'non-numeric signature';
1257
+ const visit = (expression) => {
1258
+ const v = info(expression);
1259
+ if (!supported.has(v.id))
1260
+ body.cause ??= 'unsupported expression';
1261
+ else if (v.id === binaryen.GlobalGetId || v.id === binaryen.GlobalSetId)
1262
+ body.refs.add(v.name);
1263
+ else if (!pureNodes.has(v.id))
1264
+ body.cause ??= 'impure expression';
1265
+ if (v.isAtomic)
1266
+ body.cause ??= 'atomic access';
1267
+ if (![binaryen.none, binaryen.unreachable].includes(v.type) && !numeric.has(v.type))
1268
+ body.cause ??= 'non-numeric value';
1269
+ if (v.id === binaryen.CallId)
1270
+ body.targets.add(v.target);
1271
+ for (const child of children(v))
1272
+ visit(child);
1273
+ };
1274
+ try {
1275
+ visit(f.body);
1276
+ }
1277
+ catch {
1278
+ body.cause ??= 'unreadable expression';
1279
+ }
1280
+ bodies.push(body);
1281
+ }
1282
+ const referenced = new Set(bodies.flatMap((body) => [...body.refs]));
1283
+ const named = [...globals.keys()].filter((name) => referenced.has(name));
1284
+ const mutable = named.filter((name) => globals.get(name).mutable);
1285
+ if (mutable.length > 1) {
1286
+ for (const name of mutable.slice(1))
1287
+ route.diagnostics.push(`refused global ${name}: second mutable global (stack candidate ${mutable[0]})`);
1288
+ return route;
1289
+ }
1290
+ const refused = new Set();
1291
+ for (const name of named) {
1292
+ const g = globals.get(name);
1293
+ if (g.refusal) {
1294
+ refused.add(name);
1295
+ route.diagnostics.push(`refused global ${name}: ${g.refusal}`);
1296
+ }
1297
+ else if (g.mutable)
1298
+ route.stack = { name, initial: g.initial };
1299
+ else
1300
+ route.constants.push(name);
1301
+ }
1302
+ if (route.stack)
1303
+ route.diagnostics.push(`stack global ${route.stack.name}`);
1304
+ for (const body of bodies)
1305
+ if (!body.cause && [...body.refs].some((name) => refused.has(name)))
1306
+ body.cause = 'refused global';
1307
+ const members = new Set(bodies.filter((body) => !body.cause).map((b) => b.info.name));
1308
+ for (let changed = true; changed;) {
1309
+ changed = false;
1310
+ for (const body of bodies) {
1311
+ if (body.cause || ![...body.targets].some((name) => !members.has(name)))
1312
+ continue;
1313
+ body.cause = 'call outside the set';
1314
+ members.delete(body.info.name);
1315
+ changed = true;
1316
+ }
1317
+ }
1318
+ const inSet = bodies.filter((body) => members.has(body.info.name));
1319
+ route.functions = inSet.map((body) => body.info.name);
1320
+ const cyclic = recursiveFunctions(new Map(inSet.map((b) => [b.info.name, b.targets])));
1321
+ route.recursive = route.functions.filter((name) => cyclic.has(name));
1322
+ const model = workModel(new Map(inSet.map((body) => [body.info.name, body.info])), (name) => members.has(name), assumedTrips);
1323
+ for (const name of route.functions)
1324
+ route.work[name] = model.workOf(name);
1325
+ route.diagnostics.push(`worker set: ${route.functions.length} of ${bodies.length} functions, ${route.recursive.length} recursive`);
1326
+ const causes = new Map();
1327
+ for (const body of bodies)
1328
+ if (body.cause)
1329
+ causes.set(body.cause, (causes.get(body.cause) ?? 0) + 1);
1330
+ if (causes.size)
1331
+ route.diagnostics.push(`excluded: ${[...causes]
1332
+ .sort(([a], [b]) => (a < b ? -1 : 1))
1333
+ .map(([cause, count]) => `${count} ${cause}`)
1334
+ .join(', ')}`);
1335
+ route.eligible = route.functions.length > 0;
1336
+ if (!route.eligible)
1337
+ route.diagnostics.push('no function can run on a worker');
1338
+ return route;
1339
+ }
1340
+ catch (error) {
1341
+ return {
1342
+ eligible: false,
1343
+ constants: [],
1344
+ functions: [],
1345
+ recursive: [],
1346
+ work: Object.create(null),
1347
+ diagnostics: [
1348
+ `stack route unavailable: ${error instanceof Error ? error.message : String(error)}`
1349
+ ]
1350
+ };
1351
+ }
1352
+ finally {
1353
+ module?.dispose();
1354
+ }
1355
+ }
1356
+ const emptyIteration = (diagnostics) => ({
1357
+ eligible: false,
1358
+ locals: [],
1359
+ diagnostics
1360
+ });
1361
+ /**
1362
+ * Finds an owner whose single loop is a countdown over independent calls into the stack route's
1363
+ * worker set and outlines one iteration of it. A refusal is a named diagnostic, never an exception.
1364
+ */
1365
+ export function iterationRoute(original, route) {
1366
+ if (!route.eligible)
1367
+ return emptyIteration([
1368
+ `stack route refused: ${route.diagnostics.join('; ') || 'empty set'}`
1369
+ ]);
1370
+ let module;
1371
+ try {
1372
+ module = binaryen.readBinary(original);
1373
+ const m = module;
1374
+ const compactImports = binaryen.Features
1375
+ .CompactImports;
1376
+ m.setFeatures(binaryen.Features.All & ~compactImports);
1377
+ const members = new Set(route.functions);
1378
+ const stack = route.stack?.name;
1379
+ const constants = new Set(route.constants);
1380
+ const refusals = [];
1381
+ for (let i = 0; i < m.getNumFunctions(); i++) {
1382
+ const f = binaryen.getFunctionInfo(m.getFunctionByIndex(i));
1383
+ if (!f.body || !callsInLoop(f.body, members))
1384
+ continue;
1385
+ const plan = outlineOwner(m, f, { members, stack, constants, route });
1386
+ if (plan.route) {
1387
+ plan.route.diagnostics.unshift(...refusals);
1388
+ return plan.route;
1389
+ }
1390
+ for (const reason of plan.refusals)
1391
+ if (refusals.length < 16)
1392
+ refusals.push(`refused loop in ${f.name}: ${reason}`);
1393
+ }
1394
+ refusals.push('no loop calls into the worker set');
1395
+ return emptyIteration(refusals);
1396
+ }
1397
+ catch (error) {
1398
+ return emptyIteration([
1399
+ `iteration route unavailable: ${error instanceof Error ? error.message : String(error)}`
1400
+ ]);
1401
+ }
1402
+ finally {
1403
+ module?.dispose();
1404
+ }
1405
+ }
1406
+ // does any loop in the body contain a call to a member of the set
1407
+ function callsInLoop(body, members) {
1408
+ const visit = (expression, inLoop) => {
1409
+ const v = info(expression);
1410
+ if (inLoop && v.id === binaryen.CallId && members.has(v.target))
1411
+ return true;
1412
+ return children(v).some((child) => visit(child, inLoop || v.id === binaryen.LoopId));
1413
+ };
1414
+ try {
1415
+ return visit(body, false);
1416
+ }
1417
+ catch {
1418
+ return false;
1419
+ }
1420
+ }
1421
+ // `local = local + c`, `local - c`, `local + other` or `local - other` as a statement
1422
+ function strideUpdate(statement) {
1423
+ const set = info(statement);
1424
+ if (set.id !== binaryen.LocalSetId || set.isTee)
1425
+ return;
1426
+ const next = info(set.value);
1427
+ if (next.id !== binaryen.BinaryId)
1428
+ return;
1429
+ const [left, right] = [info(next.left), info(next.right)];
1430
+ const isSelf = (v) => v.id === binaryen.LocalGetId && v.index === set.index;
1431
+ const constant = (v) => v.id === binaryen.ConstId && typeof v.value === 'number' ? v : undefined;
1432
+ const other = (v) => v.id === binaryen.LocalGetId && v.index !== set.index ? v.index : undefined;
1433
+ if (next.op === binaryen.AddInt32) {
1434
+ if (isSelf(left) && constant(right))
1435
+ return { local: set.index, stride: right.value | 0 };
1436
+ if (isSelf(right) && constant(left))
1437
+ return { local: set.index, stride: left.value | 0 };
1438
+ if (isSelf(left) && other(right) !== undefined)
1439
+ return { local: set.index, stride: 1, strideLocal: other(right) };
1440
+ if (isSelf(right) && other(left) !== undefined)
1441
+ return { local: set.index, stride: 1, strideLocal: other(left) };
1442
+ }
1443
+ if (next.op === binaryen.SubInt32 && isSelf(left)) {
1444
+ if (constant(right))
1445
+ return { local: set.index, stride: -right.value | 0 };
1446
+ if (other(right) !== undefined)
1447
+ return { local: set.index, stride: -1, strideLocal: other(right) };
1448
+ }
1449
+ }
1450
+ function outlineOwner(m, f, context) {
1451
+ const { members, stack, constants } = context;
1452
+ const refuse = new Set();
1453
+ const localTypes = [...binaryen.expandType(f.params), ...f.vars];
1454
+ const parameterCount = binaryen.expandType(f.params).length;
1455
+ if (!localTypes.every((type) => numeric.has(type)))
1456
+ return { refusals: ['non-numeric signature'] };
1457
+ // one pass: loops, write and read counts, the loop's own writes
1458
+ const loops = [];
1459
+ const writes = new Map();
1460
+ const totalReads = new Map();
1461
+ const scan = (expression) => {
1462
+ const v = info(expression);
1463
+ if (v.id === binaryen.LoopId)
1464
+ loops.push(expression);
1465
+ if (v.id === binaryen.LocalSetId)
1466
+ writes.set(v.index, (writes.get(v.index) ?? 0) + 1);
1467
+ if (v.id === binaryen.LocalGetId)
1468
+ totalReads.set(v.index, (totalReads.get(v.index) ?? 0) + 1);
1469
+ for (const child of children(v))
1470
+ scan(child);
1471
+ };
1472
+ scan(f.body);
1473
+ if (loops.length !== 1)
1474
+ return { refusals: [`${loops.length} loops, one required`] };
1475
+ const loopExpression = loops[0];
1476
+ const loop = info(loopExpression);
1477
+ // the blocks that lead to the loop, outermost first
1478
+ const levels = [];
1479
+ const locate = (expression) => {
1480
+ if (expression === loopExpression)
1481
+ return true;
1482
+ const v = info(expression);
1483
+ if (v.id !== binaryen.BlockId)
1484
+ return false;
1485
+ for (let i = 0; i < v.children.length; i++) {
1486
+ if (!locate(v.children[i]))
1487
+ continue;
1488
+ levels.unshift({ children: v.children, index: i });
1489
+ return true;
1490
+ }
1491
+ return false;
1492
+ };
1493
+ if (!locate(f.body))
1494
+ return { refusals: ['the loop is not reached through blocks'] };
1495
+ const before = levels.flatMap((level) => level.children.slice(0, level.index));
1496
+ const after = levels.flatMap((level) => level.children.slice(level.index + 1));
1497
+ // the trip count: a countdown that ends on its own decrement
1498
+ const counter = countdownLocal(loop);
1499
+ if (counter === undefined || localTypes[counter] !== binaryen.i32)
1500
+ return { refusals: ['trip count is not computable before the loop starts'] };
1501
+ const loopWrites = new Map();
1502
+ const countLoopWrites = (expression) => {
1503
+ const v = info(expression);
1504
+ if (v.id === binaryen.LocalSetId)
1505
+ loopWrites.set(v.index, (loopWrites.get(v.index) ?? 0) + 1);
1506
+ for (const child of children(v))
1507
+ countLoopWrites(child);
1508
+ };
1509
+ countLoopWrites(loopExpression);
1510
+ if ((loopWrites.get(counter) ?? 0) !== 1)
1511
+ return { refusals: ['trip count is not computable before the loop starts'] };
1512
+ // the loop body, the trailing stride updates and the back edge; a step is a constant or an i32
1513
+ // local the loop never writes
1514
+ const body = info(loop.body);
1515
+ const statements = body.id === binaryen.BlockId ? body.children : [loop.body];
1516
+ const stepIsInvariant = (update) => update.strideLocal === undefined ||
1517
+ (localTypes[update.strideLocal] === binaryen.i32 && !loopWrites.get(update.strideLocal));
1518
+ const updates = new Map([[counter, { local: counter, stride: -1 }]]);
1519
+ let end = statements.length - 1;
1520
+ while (end > 0) {
1521
+ const update = strideUpdate(statements[end - 1]);
1522
+ if (!update ||
1523
+ updates.has(update.local) ||
1524
+ localTypes[update.local] !== binaryen.i32 ||
1525
+ loopWrites.get(update.local) !== 1 ||
1526
+ !stepIsInvariant(update))
1527
+ break;
1528
+ updates.set(update.local, update);
1529
+ end--;
1530
+ }
1531
+ // top-level updates that stay in the body: iterate runs them, so later statements see the new
1532
+ // value; a stride-shaped statement that cannot stay names why, used if its local is carried
1533
+ const midUpdates = new Map();
1534
+ const shaped = new Map();
1535
+ const scanUpdates = (expression, top, conditional) => {
1536
+ const v = info(expression);
1537
+ const update = v.id === binaryen.LocalSetId ? strideUpdate(expression) : undefined;
1538
+ if (update && update.local !== counter && localTypes[update.local] === binaryen.i32) {
1539
+ if (!top)
1540
+ shaped.set(update.local, conditional
1541
+ ? 'stride update is conditional'
1542
+ : 'stride update is not at the top level of the body');
1543
+ else if (loopWrites.get(update.local) !== 1)
1544
+ shaped.set(update.local, 'stride update of a local the loop also writes elsewhere');
1545
+ else if (!stepIsInvariant(update))
1546
+ shaped.set(update.local, 'stride is written in the loop');
1547
+ else
1548
+ midUpdates.set(update.local, update);
1549
+ }
1550
+ for (const child of children(v))
1551
+ scanUpdates(child, false, conditional || v.id === binaryen.IfId);
1552
+ };
1553
+ for (const statement of statements.slice(0, end))
1554
+ scanUpdates(statement, true, false);
1555
+ for (const [local, update] of midUpdates)
1556
+ updates.set(local, update);
1557
+ const spans = [];
1558
+ for (const statement of statements.slice(0, end)) {
1559
+ const summary = summarizeSpan(statement, {
1560
+ call: (target) => members.has(target),
1561
+ global: (name) => name === stack || constants.has(name)
1562
+ });
1563
+ for (const reason of summary.refusals)
1564
+ refuse.add(reason);
1565
+ spans.push(summary.span);
1566
+ }
1567
+ if (!spans.length)
1568
+ refuse.add('empty loop body');
1569
+ // the frame: `sp = global - size` in the owner's prologue
1570
+ let frame;
1571
+ if (stack) {
1572
+ const frameOf = (expression) => {
1573
+ const sub = info(expression);
1574
+ if (sub.id !== binaryen.BinaryId || sub.op !== binaryen.SubInt32)
1575
+ return;
1576
+ const [from, size] = [info(sub.left), info(sub.right)];
1577
+ if (from.id === binaryen.GlobalGetId &&
1578
+ from.name === stack &&
1579
+ size.id === binaryen.ConstId)
1580
+ return size.value;
1581
+ };
1582
+ const top = levels[0] ? levels[0].children.slice(0, levels[0].index) : [];
1583
+ for (const [i, statement] of top.entries()) {
1584
+ const v = info(statement);
1585
+ if (v.id === binaryen.GlobalSetId && v.name === stack) {
1586
+ const tee = info(v.value);
1587
+ const size = tee.id === binaryen.LocalSetId && tee.isTee ? frameOf(tee.value) : undefined;
1588
+ if (size !== undefined)
1589
+ frame = { global: stack, size, local: tee.index, copy: true };
1590
+ }
1591
+ if (v.id === binaryen.LocalSetId && !v.isTee && frameOf(v.value) !== undefined) {
1592
+ const next = top[i + 1] ? info(top[i + 1]) : undefined;
1593
+ const value = next?.id === binaryen.GlobalSetId ? info(next.value) : undefined;
1594
+ if (next?.name === stack &&
1595
+ value?.id === binaryen.LocalGetId &&
1596
+ value.index === v.index)
1597
+ frame = { global: stack, size: frameOf(v.value), local: v.index, copy: true };
1598
+ }
1599
+ if (frame)
1600
+ break;
1601
+ }
1602
+ if (frame && (writes.get(frame.local) ?? 0) !== 1)
1603
+ frame = undefined;
1604
+ }
1605
+ // locals that hold or derive from a frame address
1606
+ const tainted = new Set(frame ? [frame.local] : []);
1607
+ const derives = (expression) => {
1608
+ const v = info(expression);
1609
+ if (v.id === binaryen.LocalGetId && tainted.has(v.index))
1610
+ return true;
1611
+ if (v.id === binaryen.GlobalGetId && v.name === stack)
1612
+ return true;
1613
+ return children(v).some(derives);
1614
+ };
1615
+ for (let changed = true; changed;) {
1616
+ changed = false;
1617
+ const grow = (expression) => {
1618
+ const v = info(expression);
1619
+ if (v.id === binaryen.LocalSetId && !tainted.has(v.index) && derives(v.value)) {
1620
+ tainted.add(v.index);
1621
+ changed = true;
1622
+ }
1623
+ for (const child of children(v))
1624
+ grow(child);
1625
+ };
1626
+ grow(f.body);
1627
+ }
1628
+ const callsMember = (expression) => {
1629
+ const v = info(expression);
1630
+ return (v.id === binaryen.CallId && members.has(v.target)) || children(v).some(callsMember);
1631
+ };
1632
+ if (spans.length && !spans.some((span) => callsMember(span.expression)))
1633
+ refuse.add('no call into the worker set in the loop body');
1634
+ for (const span of spans) {
1635
+ const check = (expression) => {
1636
+ const v = info(expression);
1637
+ if (v.id === binaryen.StoreId && derives(v.value))
1638
+ refuse.add('frame address stored to memory');
1639
+ if ((v.id === binaryen.CallIndirectId ||
1640
+ (v.id === binaryen.CallId && !members.has(v.target))) &&
1641
+ children(v).some(derives))
1642
+ refuse.add('frame address passed outside the worker set');
1643
+ if (v.id === binaryen.GlobalGetId && v.name === stack && !frame)
1644
+ refuse.add('stack global read in the body without a frame');
1645
+ for (const child of children(v))
1646
+ check(child);
1647
+ };
1648
+ check(span.expression);
1649
+ }
1650
+ // what runs after the loop must not read the frame; the epilogue restore is the one allowed use
1651
+ const afterReads = new Map();
1652
+ const inspect = (expression) => {
1653
+ const v = info(expression);
1654
+ if (frame && v.id === binaryen.GlobalSetId && v.name === stack) {
1655
+ const sum = info(v.value);
1656
+ const [a, b] = sum.id === binaryen.BinaryId ? [info(sum.left), info(sum.right)] : [];
1657
+ if (sum.op === binaryen.AddInt32 &&
1658
+ a?.id === binaryen.LocalGetId &&
1659
+ a.index === frame.local &&
1660
+ b?.id === binaryen.ConstId &&
1661
+ b.value === frame.size)
1662
+ return;
1663
+ }
1664
+ if (v.id === binaryen.LocalGetId) {
1665
+ afterReads.set(v.index, (afterReads.get(v.index) ?? 0) + 1);
1666
+ if (tainted.has(v.index))
1667
+ refuse.add('frame object read after the loop');
1668
+ }
1669
+ for (const child of children(v))
1670
+ inspect(child);
1671
+ };
1672
+ for (const statement of after)
1673
+ inspect(statement);
1674
+ const bodyWrites = new Set(spans.flatMap((span) => [...span.writes]));
1675
+ const carried = carriedLocals(spans, totalReads);
1676
+ for (const local of bodyWrites) {
1677
+ if (midUpdates.has(local))
1678
+ continue;
1679
+ if (afterReads.get(local))
1680
+ refuse.add('loop body writes a local the code after the loop reads');
1681
+ else if (carried.has(local)) {
1682
+ refuse.add('carried local is not a constant stride');
1683
+ const why = shaped.get(local);
1684
+ if (why)
1685
+ refuse.add(why);
1686
+ }
1687
+ }
1688
+ // the owner sets a constant-stride local to its loop-exit value, and has no way to do that for a
1689
+ // step that is held in a local
1690
+ for (const [local, update] of updates)
1691
+ if (update.strideLocal !== undefined && afterReads.get(local))
1692
+ refuse.add('local advanced by a run-time stride is read after the loop');
1693
+ // classify what the body reads
1694
+ const bodyReads = new Set(spans.flatMap((span) => [...span.reads.keys()]));
1695
+ const entry = (local) => {
1696
+ const outside = (writes.get(local) ?? 0) - (loopWrites.get(local) ?? 0);
1697
+ if (local < parameterCount && outside === 0)
1698
+ return { parameter: local };
1699
+ if (outside !== 1)
1700
+ return;
1701
+ for (const statement of [...before].reverse()) {
1702
+ const v = info(statement);
1703
+ if (v.id !== binaryen.LocalSetId || v.isTee || v.index !== local)
1704
+ continue;
1705
+ const value = info(v.value);
1706
+ if (value.id === binaryen.ConstId && typeof value.value === 'number')
1707
+ return { constant: value.value >>> 0 };
1708
+ if (value.id === binaryen.LocalGetId &&
1709
+ value.index < parameterCount &&
1710
+ !writes.get(value.index))
1711
+ return { parameter: value.index };
1712
+ return;
1713
+ }
1714
+ };
1715
+ const strided = [];
1716
+ const invariant = [];
1717
+ for (const [local, update] of [...updates].sort(([a], [b]) => a - b))
1718
+ strided.push({
1719
+ local,
1720
+ kind: local === counter ? 'induction' : 'stride',
1721
+ start: entry(local),
1722
+ stride: update.stride,
1723
+ ...(update.strideLocal === undefined ? {} : { strideLocal: update.strideLocal })
1724
+ });
1725
+ for (const local of [...bodyReads].sort((a, b) => a - b)) {
1726
+ if (bodyWrites.has(local) || updates.has(local) || local === frame?.local)
1727
+ continue;
1728
+ if ((loopWrites.get(local) ?? 0) > 0)
1729
+ refuse.add('carried local is not a constant stride');
1730
+ invariant.push({ local, kind: 'invariant', start: entry(local) });
1731
+ }
1732
+ // a step local the body does not read still needs its loop-entry value, so `iterate` takes it too
1733
+ const steps = new Set([...updates.values()].flatMap((update) => update.strideLocal === undefined ? [] : [update.strideLocal]));
1734
+ for (const local of [...steps].sort((a, b) => a - b))
1735
+ if (!invariant.some((item) => item.local === local))
1736
+ invariant.push({ local, kind: 'invariant', start: entry(local) });
1737
+ invariant.sort((a, b) => a.local - b.local);
1738
+ for (const item of [...strided, ...invariant]) {
1739
+ if (bodyReads.has(item.local) && tainted.has(item.local))
1740
+ refuse.add('frame address held in a local the body reads');
1741
+ if (steps.has(item.local) && tainted.has(item.local))
1742
+ refuse.add('frame address used as a run-time stride');
1743
+ }
1744
+ if (refuse.size)
1745
+ return { refusals: [...refuse] };
1746
+ // `iterate`: strided and invariant locals in order, then the frame base, then the body's temporaries
1747
+ const parameters = [...strided, ...invariant].filter((item) => bodyReads.has(item.local) || steps.has(item.local));
1748
+ const order = [...parameters.map((item) => item.local), ...(frame ? [frame.local] : [])];
1749
+ const temporaries = [...new Set(spans.flatMap((span) => [...span.locals]))]
1750
+ .filter((local) => !order.includes(local))
1751
+ .sort((a, b) => a - b);
1752
+ const positions = new Map([...order, ...temporaries].map((local, index) => [local, index]));
1753
+ parameters.forEach((item, index) => (item.argument = index));
1754
+ const memory = m.getMemoryInfo();
1755
+ const internalMemory = memoryName(m);
1756
+ const w = new binaryen.Module();
1757
+ try {
1758
+ w.setFeatures(m.getFeatures() | binaryen.Features.Atomics);
1759
+ w.setMemory(memory.initial, memory.max ?? 65536, null, [], true, false, internalMemory);
1760
+ w.addMemoryImport(internalMemory, 'env', 'memory', true);
1761
+ if (stack)
1762
+ w.addGlobal(stack, binaryen.i32, true, w.i32.const(context.route.stack.initial));
1763
+ for (const name of constants) {
1764
+ const g = binaryen.getGlobalInfo(m.getGlobal(name));
1765
+ w.addGlobal(name, g.type, false, w.copyExpression(g.init));
1766
+ }
1767
+ for (const name of context.route.functions) {
1768
+ const g = binaryen.getFunctionInfo(m.getFunction(name));
1769
+ w.addFunction(name, g.params, g.results, g.vars, w.copyExpression(g.body));
1770
+ }
1771
+ let iterate = '__folio_iterate';
1772
+ while (w.getFunction(iterate))
1773
+ iterate += '_';
1774
+ const block = w.block(null, spans.map((span) => w.copyExpression(span.expression)));
1775
+ remapLocals(block, positions);
1776
+ w.addFunction(iterate, binaryen.createType(order.map((local) => localTypes[local])), binaryen.none, temporaries.map((local) => localTypes[local]), block);
1777
+ w.addFunctionExport(iterate, iterate);
1778
+ const stackExport = '__folio_stack';
1779
+ if (stack)
1780
+ w.addGlobalExport(stack, stackExport);
1781
+ if (!w.validate())
1782
+ throw new Error('invalid iteration module');
1783
+ const bytes = w.emitBinary();
1784
+ new WebAssembly.Module(Uint8Array.from(bytes));
1785
+ const trip = entry(counter);
1786
+ const locals = [
1787
+ ...strided,
1788
+ ...invariant,
1789
+ ...(frame
1790
+ ? [{ local: frame.local, kind: 'frame', argument: order.length - 1 }]
1791
+ : [])
1792
+ ];
1793
+ const diagnostics = [
1794
+ `owner ${f.name}: countdown loop on local ${counter}, ${spans.length} body statements, ${order.length} arguments`
1795
+ ];
1796
+ if (frame)
1797
+ diagnostics.push(`frame ${frame.global} - ${frame.size} in local ${frame.local}`);
1798
+ return {
1799
+ refusals: [],
1800
+ route: {
1801
+ eligible: true,
1802
+ owner: f.name,
1803
+ loop: loop.name || undefined,
1804
+ trip: { local: counter, ...(trip ?? {}) },
1805
+ locals,
1806
+ frame,
1807
+ iterate,
1808
+ stackExport: stack ? stackExport : undefined,
1809
+ module: bytes,
1810
+ diagnostics
1811
+ }
1812
+ };
1813
+ }
1814
+ finally {
1815
+ w.dispose();
1816
+ }
1817
+ }