@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
package/dist/inline.js ADDED
@@ -0,0 +1,503 @@
1
+ import binaryen from 'binaryen';
2
+ import { stackRoute } from "./extract.js";
3
+ const info = (expression) => {
4
+ const id = binaryen.getExpressionId(expression);
5
+ if (id === binaryen.UnreachableId || id === binaryen.NopId) {
6
+ return { id, type: binaryen.getExpressionType(expression) };
7
+ }
8
+ return binaryen.getExpressionInfo(expression);
9
+ };
10
+ // #region inline tracking lowering
11
+ const capi = binaryen;
12
+ /** Names of the exported mutable i32 globals the inline lowering adds, plus the stack export. */
13
+ export const inlineGlobals = {
14
+ readBitmap: '__folio_rb',
15
+ writeBitmap: '__folio_wb',
16
+ logPointer: '__folio_lp',
17
+ logLimit: '__folio_ll',
18
+ stampAddress: '__folio_sa',
19
+ stackPointer: '__folio_sp',
20
+ frameLow: '__folio_fl',
21
+ frameSize: '__folio_fn',
22
+ frameShadow: '__folio_fs'
23
+ };
24
+ /** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
25
+ export const inlineEntryBytes = (writeGranule = 32) => 8 + writeGranule;
26
+ const inlineHelpers = [
27
+ '__folio_r_mark',
28
+ '__folio_w_mark',
29
+ '__folio_w_set',
30
+ '__folio_undo',
31
+ '__folio_r_range',
32
+ '__folio_w_range',
33
+ '__folio_f_r',
34
+ '__folio_f_w',
35
+ '__folio_f_rr',
36
+ '__folio_f_rw'
37
+ ];
38
+ const inlineLeaves = new Set([
39
+ binaryen.ConstId,
40
+ binaryen.LocalGetId,
41
+ binaryen.GlobalGetId,
42
+ binaryen.NopId,
43
+ binaryen.UnreachableId,
44
+ binaryen.MemorySizeId,
45
+ binaryen.DataDropId,
46
+ binaryen.AtomicFenceId
47
+ ]);
48
+ const simdLoadBytes = new Map([
49
+ [binaryen.Operations.Load8SplatVec128, 1],
50
+ [binaryen.Operations.Load16SplatVec128, 2],
51
+ [binaryen.Operations.Load32SplatVec128, 4],
52
+ [binaryen.Operations.Load64SplatVec128, 8],
53
+ [binaryen.Operations.Load8x8SVec128, 8],
54
+ [binaryen.Operations.Load8x8UVec128, 8],
55
+ [binaryen.Operations.Load16x4SVec128, 8],
56
+ [binaryen.Operations.Load16x4UVec128, 8],
57
+ [binaryen.Operations.Load32x2SVec128, 8],
58
+ [binaryen.Operations.Load32x2UVec128, 8],
59
+ [binaryen.Operations.Load32ZeroVec128, 4],
60
+ [binaryen.Operations.Load64ZeroVec128, 8]
61
+ ]);
62
+ const simdLaneBytes = new Map([
63
+ [binaryen.Operations.Load8LaneVec128, 1],
64
+ [binaryen.Operations.Load16LaneVec128, 2],
65
+ [binaryen.Operations.Load32LaneVec128, 4],
66
+ [binaryen.Operations.Load64LaneVec128, 8],
67
+ [binaryen.Operations.Store8LaneVec128, 1],
68
+ [binaryen.Operations.Store16LaneVec128, 2],
69
+ [binaryen.Operations.Store32LaneVec128, 4],
70
+ [binaryen.Operations.Store64LaneVec128, 8]
71
+ ]);
72
+ // operand expressions of every node the lowering may meet; anything else is refused by name
73
+ function inlineChildren(v) {
74
+ switch (v.id) {
75
+ case binaryen.BlockId:
76
+ return v.children;
77
+ case binaryen.IfId:
78
+ return [v.condition, v.ifTrue, v.ifFalse].filter(Boolean);
79
+ case binaryen.LoopId:
80
+ return [v.body];
81
+ case binaryen.BreakId:
82
+ case binaryen.SwitchId:
83
+ return [v.value, v.condition].filter(Boolean);
84
+ case binaryen.CallId:
85
+ return v.operands;
86
+ case binaryen.CallIndirectId:
87
+ return [...v.operands, v.target];
88
+ case binaryen.LocalSetId:
89
+ case binaryen.GlobalSetId:
90
+ case binaryen.UnaryId:
91
+ case binaryen.DropId:
92
+ return [v.value];
93
+ case binaryen.ReturnId:
94
+ return v.value ? [v.value] : [];
95
+ case binaryen.LoadId:
96
+ case binaryen.SIMDLoadId:
97
+ return [v.ptr];
98
+ case binaryen.StoreId:
99
+ case binaryen.AtomicRMWId:
100
+ return [v.ptr, v.value];
101
+ case binaryen.BinaryId:
102
+ case binaryen.SIMDShuffleId:
103
+ return [v.left, v.right];
104
+ case binaryen.SelectId:
105
+ return [v.ifTrue, v.ifFalse, v.condition];
106
+ case binaryen.MemoryGrowId:
107
+ return [v.delta];
108
+ case binaryen.MemoryCopyId:
109
+ return [v.dest, v.source, v.size];
110
+ case binaryen.MemoryFillId:
111
+ return [v.dest, v.value, v.size];
112
+ case binaryen.MemoryInitId:
113
+ return [v.dest, v.offset, v.size];
114
+ case binaryen.AtomicCmpxchgId:
115
+ return [v.ptr, v.expected, v.replacement];
116
+ case binaryen.AtomicWaitId:
117
+ return [v.ptr, v.expected, v.timeout];
118
+ case binaryen.AtomicNotifyId:
119
+ return [v.ptr, v.notifyCount];
120
+ case binaryen.SIMDExtractId:
121
+ return [v.vec];
122
+ case binaryen.SIMDReplaceId:
123
+ return [v.vec, v.value];
124
+ case binaryen.SIMDTernaryId:
125
+ return [v.a, v.b, v.c];
126
+ case binaryen.SIMDShiftId:
127
+ return [v.vec, v.shift];
128
+ case binaryen.SIMDLoadStoreLaneId:
129
+ return [v.ptr, v.vec];
130
+ default:
131
+ if (inlineLeaves.has(v.id))
132
+ return [];
133
+ throw new Error(`unsupported expression ${v.id}`);
134
+ }
135
+ }
136
+ function granuleShift(value, fallback, low, high) {
137
+ const size = value ?? fallback;
138
+ if (!Number.isInteger(size) || size < low || size > high || size & (size - 1))
139
+ throw new RangeError(`granule must be a power of two from ${low} to ${high}`);
140
+ return Math.log2(size);
141
+ }
142
+ function memoryCount(bytes, native) {
143
+ let cursor = 8, defined = 0;
144
+ const unsigned = () => {
145
+ let value = 0, shift = 0, byte;
146
+ do {
147
+ byte = bytes[cursor++];
148
+ value += (byte & 127) * 2 ** shift;
149
+ shift += 7;
150
+ } while (byte & 128);
151
+ return value;
152
+ };
153
+ while (cursor < bytes.length) {
154
+ const section = bytes[cursor++];
155
+ const end = unsigned() + cursor;
156
+ if (section === 5)
157
+ defined = unsigned();
158
+ cursor = end;
159
+ }
160
+ return defined + WebAssembly.Module.imports(native).filter((i) => i.kind === 'memory').length;
161
+ }
162
+ /**
163
+ * A second lowering, next to the host-call one in `prepare`: it marks memory accesses inline, with
164
+ * no host call and no added import, so a region can be validated after it ran. Nothing in
165
+ * `prepare` calls it yet and its output is not a `PreparedProgram` field.
166
+ *
167
+ * State lives in mutable i32 globals the owner exports and sets before each region; all start at
168
+ * 0, which traps on the first access. `__folio_rb` and `__folio_wb` are the bases of the read and
169
+ * write bitmaps, `__folio_lp` and `__folio_ll` the undo log pointer and limit, `__folio_sa` the
170
+ * address of a shared i32 stamp counter (4-byte aligned). The stack pointer global is exported as
171
+ * `__folio_sp` when the module has one. A bitmap has one bit per granule: granule `g`, with
172
+ * `g = address >> log2(granule)`, is bit `g & 7` of byte `base + (g >> 3)`. The bitmaps are
173
+ * private to a region and the owner clears them between regions.
174
+ *
175
+ * Every load, store, atomic access and SIMD load marks its read granule, and an access that
176
+ * crosses a boundary marks both. A store, a SIMD lane store and the destination of `memory.copy`,
177
+ * `memory.fill` and `memory.init` mark write granules; atomic accesses mark both sets; the source
178
+ * of `memory.copy` marks read granules. The first write to a write granule appends an undo entry
179
+ * at `__folio_lp`: the granule address (u32), a stamp from an atomic add on `__folio_sa` taken
180
+ * after the prior bytes were copied and before the write, then the prior bytes of the granule.
181
+ * `__folio_lp` then advances by `inlineEntryBytes(writeGranule)`; an entry that would pass
182
+ * `__folio_ll` traps with `unreachable`. The start function is not lowered.
183
+ *
184
+ * With `frame: true` the module also tracks one frame region, for a stack frame whose bytes an
185
+ * iteration may read after an earlier iteration wrote them. The owner sets `__folio_fl` (low
186
+ * address), `__folio_fn` (size in bytes) and `__folio_fs` (shadow base) before a region; with
187
+ * `__folio_fn` at 0 nothing is tracked. An access that overlaps the region is checked against a
188
+ * shadow of one written bit per frame byte, `4 * ceil(size / 32)` bytes with the bits of frame
189
+ * granule `g` (32 bytes) in the i32 at `__folio_fs + 4 * g`, then 4 pad bytes, then the exposed
190
+ * bits laid out the same way, then 4 more pad bytes. A store sets written bits after its value is
191
+ * computed; a load sets the exposed bit of each byte it reads whose written bit is clear, so a
192
+ * region reports exactly the frame bytes it read before it wrote them.
193
+ * `memory.copy`, `memory.fill` and `memory.init` set or check the exact byte range, an atomic
194
+ * read-modify-write checks then sets, and any other atomic access or SIMD load checks. The owner
195
+ * zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
196
+ * the region is not tracked.
197
+ *
198
+ * Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
199
+ * `requireShared` is set, a start function that calls, a reserved name or an expression it does
200
+ * not know. An imported host function that touches memory is not seen.
201
+ */
202
+ export function lowerInline(bytes, options = {}) {
203
+ const rg = granuleShift(options.readGranule, 64, 16, 4096);
204
+ const wg = granuleShift(options.writeGranule, 32, 16, 256);
205
+ const entry = inlineEntryBytes(1 << wg);
206
+ const original = Uint8Array.from(bytes);
207
+ const native = new WebAssembly.Module(original);
208
+ if (memoryCount(original, native) !== 1)
209
+ throw new Error('exactly one memory required');
210
+ const stack = options.stack ?? stackRoute(original).stack?.name;
211
+ const m = binaryen.readBinary(original);
212
+ try {
213
+ const compactImports = binaryen.Features
214
+ .CompactImports;
215
+ m.setFeatures(binaryen.Features.All & ~compactImports);
216
+ const memory = m.getMemoryInfo();
217
+ if (memory.is64)
218
+ throw new Error('memory64 is not supported');
219
+ if ((options.requireShared ?? true) && !memory.shared)
220
+ throw new Error('shared memory required; pass requireShared: false for one thread');
221
+ const reserved = [...Object.values(inlineGlobals), ...inlineHelpers];
222
+ if (reserved.some((name) => m.getGlobal(name) || m.getFunction(name) || m.getExport(name)))
223
+ throw new Error('reserved function name');
224
+ if (stack !== undefined) {
225
+ const global = m.getGlobal(stack);
226
+ const shape = global ? binaryen.getGlobalInfo(global) : undefined;
227
+ if (!shape || !shape.mutable || shape.type !== binaryen.i32 || shape.module)
228
+ throw new Error(`stack global ${stack} is not a defined mutable i32`);
229
+ }
230
+ const frame = Boolean(options.frame);
231
+ const rb = inlineGlobals.readBitmap, wb = inlineGlobals.writeBitmap, lp = inlineGlobals.logPointer, ll = inlineGlobals.logLimit, sa = inlineGlobals.stampAddress, fl = inlineGlobals.frameLow, fn = inlineGlobals.frameSize, fs = inlineGlobals.frameShadow;
232
+ const i32 = binaryen.i32, none = binaryen.none;
233
+ const c = (value) => m.i32.const(value | 0);
234
+ const g = (name) => m.global.get(name, i32);
235
+ const l = (index) => m.local.get(index, i32);
236
+ const call = (name, ...args) => m.call(name, args, none);
237
+ const bitOf = (address, shift) => m.i32.shl(c(1), m.i32.and(m.i32.shr_u(address(), c(shift)), c(7)));
238
+ const byteOf = (base, address, shift) => m.i32.add(g(base), m.i32.shr_u(address(), c(shift + 3)));
239
+ const setBit = (base, address, shift) => m.i32.store8(0, 1, byteOf(base, address, shift), m.i32.or(m.i32.load8_u(0, 1, byteOf(base, address, shift)), bitOf(address, shift)));
240
+ const unmarked = (address) => m.i32.eqz(m.i32.and(m.i32.load8_u(0, 1, byteOf(wb, address, wg)), bitOf(address, wg)));
241
+ // does an access of `width` bytes at the address overlap the frame region
242
+ const inFrame = (address, width) => width === 1
243
+ ? m.i32.lt_u(m.i32.sub(address(), g(fl)), g(fn))
244
+ : m.i32.lt_u(m.i32.add(m.i32.sub(address(), g(fl)), c(width - 1)), m.i32.add(g(fn), c(width - 1)));
245
+ const frameCall = (name, address, width) => m.if(inFrame(address, width), call(name, address(), c(width)));
246
+ const hold = (local, value) => m.block(null, [m.local.set(local, value), l(local)], i32);
247
+ const startRef = m.getStart();
248
+ const start = startRef ? binaryen.getFunctionInfo(startRef).name : undefined;
249
+ const callsOut = (expression) => {
250
+ const v = info(expression);
251
+ return v.id === binaryen.CallId || inlineChildren(v).some(callsOut);
252
+ };
253
+ for (let index = 0, count = m.getNumFunctions(); index < count; index++) {
254
+ const f = m.getFunctionByIndex(index);
255
+ const { name, body } = binaryen.getFunctionInfo(f);
256
+ if (!body)
257
+ continue;
258
+ if (name === start) {
259
+ if (callsOut(body))
260
+ throw new Error('start function calls another function');
261
+ continue;
262
+ }
263
+ const vars = (n) => Array.from({ length: n }, () => capi._BinaryenFunctionAddVar(f, i32));
264
+ let pointer = -1, effective = -1;
265
+ const temps = new Map();
266
+ // a frame store marks its written bits after its value is computed, from a saved address
267
+ const afterValue = (value, saved, width, reads) => {
268
+ const type = binaryen.getExpressionType(value);
269
+ if (type === binaryen.unreachable)
270
+ return value;
271
+ if (!temps.has(type))
272
+ temps.set(type, capi._BinaryenFunctionAddVar(f, type));
273
+ const t = temps.get(type);
274
+ return m.block(null, [
275
+ m.local.set(t, value),
276
+ ...(reads ? [frameCall('__folio_f_r', () => l(saved), width)] : []),
277
+ frameCall('__folio_f_w', () => l(saved), width),
278
+ m.local.get(t, type)
279
+ ], type);
280
+ };
281
+ const saver = () => (frame ? vars(1)[0] : undefined);
282
+ // the pointer operand becomes a block that marks the granules and yields the pointer
283
+ const access = (ptr, offset, width, read, write, checks = false, saved) => {
284
+ if (pointer < 0)
285
+ [pointer, effective] = vars(2);
286
+ const t = pointer, u = effective;
287
+ const steps = [
288
+ m.local.set(t, ptr),
289
+ m.local.set(u, offset ? m.i32.add(l(t), c(offset)) : l(t))
290
+ ];
291
+ const crosses = (shift, mark) => m.if(m.i32.gt_u(m.i32.and(l(u), c((1 << shift) - 1)), c((1 << shift) - width)), call(mark, m.i32.add(l(u), c(width - 1))));
292
+ if (read) {
293
+ steps.push(setBit(rb, () => l(u), rg));
294
+ if (width > 1)
295
+ steps.push(crosses(rg, '__folio_r_mark'));
296
+ }
297
+ if (write) {
298
+ steps.push(m.if(unmarked(() => l(u)), call('__folio_w_set', l(u))));
299
+ if (width > 1)
300
+ steps.push(crosses(wg, '__folio_w_mark'));
301
+ }
302
+ if (frame && checks)
303
+ steps.push(frameCall('__folio_f_r', () => l(u), width));
304
+ if (saved !== undefined)
305
+ steps.push(m.local.set(saved, l(u)));
306
+ steps.push(l(t));
307
+ return m.block(null, steps, i32);
308
+ };
309
+ const visit = (e) => {
310
+ const v = info(e);
311
+ for (const child of inlineChildren(v))
312
+ visit(child);
313
+ switch (v.id) {
314
+ case binaryen.LoadId:
315
+ capi._BinaryenLoadSetPtr(e, access(v.ptr, v.offset, v.bytes, true, Boolean(v.isAtomic), true));
316
+ break;
317
+ case binaryen.StoreId: {
318
+ const saved = saver();
319
+ capi._BinaryenStoreSetPtr(e, access(v.ptr, v.offset, v.bytes, Boolean(v.isAtomic), true, false, saved));
320
+ if (saved !== undefined)
321
+ capi._BinaryenStoreSetValue(e, afterValue(v.value, saved, v.bytes, false));
322
+ break;
323
+ }
324
+ case binaryen.AtomicRMWId: {
325
+ const saved = saver();
326
+ capi._BinaryenAtomicRMWSetPtr(e, access(v.ptr, v.offset, v.bytes, true, true, false, saved));
327
+ if (saved !== undefined)
328
+ capi._BinaryenAtomicRMWSetValue(e, afterValue(v.value, saved, v.bytes, true));
329
+ break;
330
+ }
331
+ case binaryen.AtomicCmpxchgId: {
332
+ const saved = saver();
333
+ capi._BinaryenAtomicCmpxchgSetPtr(e, access(v.ptr, v.offset, v.bytes, true, true, false, saved));
334
+ if (saved !== undefined)
335
+ capi._BinaryenAtomicCmpxchgSetReplacement(e, afterValue(v.replacement, saved, v.bytes, true));
336
+ break;
337
+ }
338
+ case binaryen.AtomicWaitId:
339
+ capi._BinaryenAtomicWaitSetPtr(e, access(v.ptr, 0, v.expectedType === binaryen.i64 ? 8 : 4, true, true, true));
340
+ break;
341
+ case binaryen.AtomicNotifyId:
342
+ capi._BinaryenAtomicNotifySetPtr(e, access(v.ptr, 0, 4, true, true, true));
343
+ break;
344
+ case binaryen.SIMDLoadId:
345
+ capi._BinaryenSIMDLoadSetPtr(e, access(v.ptr, v.offset, simdLoadBytes.get(v.op), true, false, true));
346
+ break;
347
+ case binaryen.SIMDLoadStoreLaneId: {
348
+ const bytes = simdLaneBytes.get(v.op);
349
+ const saved = v.isStore ? saver() : undefined;
350
+ capi._BinaryenSIMDLoadStoreLaneSetPtr(e, access(v.ptr, v.offset, bytes, !v.isStore, Boolean(v.isStore), !v.isStore, saved));
351
+ if (saved !== undefined)
352
+ capi._BinaryenSIMDLoadStoreLaneSetVec(e, afterValue(v.vec, saved, bytes, false));
353
+ break;
354
+ }
355
+ case binaryen.MemoryCopyId: {
356
+ const [td, ts, tn] = vars(3);
357
+ capi._BinaryenMemoryCopySetDest(e, hold(td, v.dest));
358
+ capi._BinaryenMemoryCopySetSource(e, hold(ts, v.source));
359
+ capi._BinaryenMemoryCopySetSize(e, m.block(null, [
360
+ m.local.set(tn, v.size),
361
+ call('__folio_r_range', l(ts), l(tn)),
362
+ call('__folio_w_range', l(td), l(tn)),
363
+ ...(frame
364
+ ? [
365
+ call('__folio_f_rr', l(ts), l(tn)),
366
+ call('__folio_f_rw', l(td), l(tn))
367
+ ]
368
+ : []),
369
+ l(tn)
370
+ ], i32));
371
+ break;
372
+ }
373
+ case binaryen.MemoryFillId:
374
+ case binaryen.MemoryInitId: {
375
+ const [td, tn] = vars(2);
376
+ const fill = v.id === binaryen.MemoryFillId;
377
+ capi[fill ? '_BinaryenMemoryFillSetDest' : '_BinaryenMemoryInitSetDest'](e, hold(td, v.dest));
378
+ capi[fill ? '_BinaryenMemoryFillSetSize' : '_BinaryenMemoryInitSetSize'](e, m.block(null, [
379
+ m.local.set(tn, v.size),
380
+ call('__folio_w_range', l(td), l(tn)),
381
+ ...(frame ? [call('__folio_f_rw', l(td), l(tn))] : []),
382
+ l(tn)
383
+ ], i32));
384
+ break;
385
+ }
386
+ }
387
+ };
388
+ visit(body);
389
+ }
390
+ for (const name of [rb, wb, lp, ll, sa]) {
391
+ m.addGlobal(name, i32, true, c(0));
392
+ m.addGlobalExport(name, name);
393
+ }
394
+ if (frame)
395
+ for (const name of [fl, fn, fs]) {
396
+ m.addGlobal(name, i32, true, c(0));
397
+ m.addGlobalExport(name, name);
398
+ }
399
+ if (stack !== undefined)
400
+ m.addGlobalExport(stack, inlineGlobals.stackPointer);
401
+ const pair = binaryen.createType([i32, i32]);
402
+ const addFrameHelpers = () => {
403
+ const v = l;
404
+ const max = (a, b) => m.select(m.i32.gt_u(a(), b()), a(), b());
405
+ const exposedBase = () => m.i32.add(g(fs), m.i32.add(m.i32.shl(m.i32.shr_u(m.i32.add(g(fn), c(31)), c(5)), c(2)), c(4)));
406
+ // scalar access: params a, w; vars 2 lo, 3 hi, 4 end, 5 i, 6 n, 7 p, 8 miss, 9 q
407
+ const scalar = (name, read) => {
408
+ const mask = () => m.i32.shl(m.i32.sub(m.i32.shl(c(1), v(6)), c(1)), m.i32.and(v(5), c(7)));
409
+ const body = [
410
+ m.local.set(2, max(() => v(0), () => g(fl))),
411
+ m.local.set(3, m.i32.add(v(0), v(1))),
412
+ m.local.set(4, m.i32.add(g(fl), g(fn))),
413
+ m.if(m.i32.gt_u(v(3), v(4)), m.local.set(3, v(4))),
414
+ m.if(m.i32.le_u(v(3), v(2)), m.return()),
415
+ m.local.set(5, m.i32.sub(v(2), g(fl))),
416
+ m.local.set(6, m.i32.sub(v(3), v(2))),
417
+ m.local.set(7, m.i32.add(g(fs), m.i32.shr_u(v(5), c(3)))),
418
+ ...(read
419
+ ? [
420
+ m.local.set(8, m.i32.and(mask(), m.i32.xor(m.i32.load(0, 1, v(7)), c(-1)))),
421
+ m.if(v(8), m.block(null, [
422
+ m.local.set(9, m.i32.add(exposedBase(), m.i32.shr_u(v(5), c(3)))),
423
+ m.i32.store(0, 1, v(9), m.i32.or(m.i32.load(0, 1, v(9)), v(8)))
424
+ ], none))
425
+ ]
426
+ : [m.i32.store(0, 1, v(7), m.i32.or(m.i32.load(0, 1, v(7)), mask()))])
427
+ ];
428
+ m.addFunction(name, pair, none, Array(8).fill(i32), m.block(null, body, none));
429
+ };
430
+ scalar('__folio_f_r', true);
431
+ scalar('__folio_f_w', false);
432
+ // range access: params a, n; vars 2 lo, 3 hi, 4 end, 5 i, 6 j, 7 g, 8 last, 9 ms, 10 len,
433
+ // 11 mask, 12 p, 13 miss
434
+ const bulk = (name, read) => {
435
+ const body = [
436
+ m.if(m.i32.eqz(v(1)), m.return()),
437
+ m.local.set(2, max(() => v(0), () => g(fl))),
438
+ m.local.set(3, m.i32.add(v(0), v(1))),
439
+ m.if(m.i32.lt_u(v(3), v(0)), m.local.set(3, c(-1))),
440
+ m.local.set(4, m.i32.add(g(fl), g(fn))),
441
+ m.if(m.i32.gt_u(v(3), v(4)), m.local.set(3, v(4))),
442
+ m.if(m.i32.le_u(v(3), v(2)), m.return()),
443
+ m.local.set(5, m.i32.sub(v(2), g(fl))),
444
+ m.local.set(6, m.i32.sub(v(3), g(fl))),
445
+ m.local.set(7, m.i32.shr_u(v(5), c(5))),
446
+ m.local.set(8, m.i32.shr_u(m.i32.sub(v(6), c(1)), c(5))),
447
+ m.loop('again', m.block(null, [
448
+ // ms: first byte of the range inside granule g; len: bytes of it inside
449
+ m.local.set(9, m.i32.sub(max(() => v(5), () => m.i32.shl(v(7), c(5))), m.i32.shl(v(7), c(5)))),
450
+ m.local.set(10, m.i32.sub(m.select(m.i32.lt_u(v(6), m.i32.add(m.i32.shl(v(7), c(5)), c(32))), v(6), m.i32.add(m.i32.shl(v(7), c(5)), c(32))), m.i32.add(m.i32.shl(v(7), c(5)), v(9)))),
451
+ m.local.set(11, m.select(m.i32.eq(v(10), c(32)), c(-1), m.i32.shl(m.i32.sub(m.i32.shl(c(1), v(10)), c(1)), v(9)))),
452
+ m.local.set(12, m.i32.add(g(fs), m.i32.shl(v(7), c(2)))),
453
+ ...(read
454
+ ? [
455
+ m.local.set(13, m.i32.and(v(11), m.i32.xor(m.i32.load(0, 4, v(12)), c(-1)))),
456
+ m.if(v(13), m.i32.store(0, 4, m.i32.add(v(12), m.i32.sub(exposedBase(), g(fs))), m.i32.or(m.i32.load(0, 4, m.i32.add(v(12), m.i32.sub(exposedBase(), g(fs)))), v(13))))
457
+ ]
458
+ : [
459
+ m.i32.store(0, 4, v(12), m.i32.or(m.i32.load(0, 4, v(12)), v(11)))
460
+ ]),
461
+ m.local.set(7, m.i32.add(v(7), c(1))),
462
+ m.br('again', m.i32.le_u(v(7), v(8)))
463
+ ], none))
464
+ ];
465
+ m.addFunction(name, pair, none, Array(12).fill(i32), m.block(null, body, none));
466
+ };
467
+ bulk('__folio_f_rr', true);
468
+ bulk('__folio_f_rw', false);
469
+ };
470
+ m.addFunction('__folio_r_mark', i32, none, [], setBit(rb, () => l(0), rg));
471
+ m.addFunction('__folio_undo', i32, none, [i32], m.block(null, [
472
+ m.if(m.i32.gt_u(m.i32.add(g(lp), c(entry)), g(ll)), m.unreachable()),
473
+ m.local.set(1, g(lp)),
474
+ m.i32.store(0, 4, l(1), l(0)),
475
+ ...Array.from({ length: (1 << wg) / 8 }, (_, k) => m.i64.store(8 + 8 * k, 8, l(1), m.i64.load(8 * k, 8, l(0)))),
476
+ m.i32.store(4, 4, l(1), m.i32.atomic.rmw.add(0, g(sa), c(1))),
477
+ m.global.set(lp, m.i32.add(l(1), c(entry)))
478
+ ], none));
479
+ m.addFunction('__folio_w_set', i32, none, [], m.block(null, [setBit(wb, () => l(0), wg), call('__folio_undo', m.i32.and(l(0), c(-(1 << wg))))], none));
480
+ m.addFunction('__folio_w_mark', i32, none, [], m.if(unmarked(() => l(0)), call('__folio_w_set', l(0))));
481
+ // every granule from a to a + n - 1
482
+ const range = (name, shift, mark) => m.addFunction(name, pair, none, [i32, i32], m.if(l(1), m.block(null, [
483
+ m.local.set(2, m.i32.shr_u(l(0), c(shift))),
484
+ m.local.set(3, m.i32.shr_u(m.i32.add(l(0), m.i32.sub(l(1), c(1))), c(shift))),
485
+ m.loop('again', m.block(null, [
486
+ call(mark, m.i32.shl(l(2), c(shift))),
487
+ m.local.set(2, m.i32.add(l(2), c(1))),
488
+ m.br('again', m.i32.le_u(l(2), l(3)))
489
+ ], none))
490
+ ], none)));
491
+ range('__folio_r_range', rg, '__folio_r_mark');
492
+ range('__folio_w_range', wg, '__folio_w_mark');
493
+ if (frame)
494
+ addFrameHelpers();
495
+ if (!m.validate())
496
+ throw new Error('invalid inline lowering');
497
+ return m.emitBinary();
498
+ }
499
+ finally {
500
+ m.dispose();
501
+ }
502
+ }
503
+ // #endregion
@@ -0,0 +1,76 @@
1
+ /** Why the rest of a loop ran serially after the pooled path was tried or refused. */
2
+ export type IterationStop = 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'dependency';
3
+ /** What the admission decision saw and chose for one owner call's loop. */
4
+ export interface IterationAdmission {
5
+ /** Time of iteration 0 on the owner thread, on a plain instance and the real frame. */
6
+ plainIterationMs: number;
7
+ /** Serial time of the iterations after iteration 0, from `plainIterationMs`. */
8
+ remainingSerialMs: number;
9
+ /** The least remaining serial time worth dispatching: `fixedMs * margin`. */
10
+ floorMs: number;
11
+ /** The decision before the first dispatch. A later stop is `IterationReport.stopped`. */
12
+ admitted: boolean;
13
+ /** Wall of the last batch, dispatch to the end of its replays. */
14
+ batchWallMs?: number;
15
+ /** The same iterations at `plainIterationMs` each. */
16
+ batchSerialMs?: number;
17
+ }
18
+ /** The constants of the decision. A re-calibration changes these and nothing else. */
19
+ export interface IterationAdmissionConstants {
20
+ /** Wall of the pooled path that does not shrink with the loop: dispatch, join, validation. */
21
+ fixedMs: number;
22
+ /** The pooled path has to beat the serial one by this factor, before and after each batch. */
23
+ margin: number;
24
+ }
25
+ /**
26
+ * Fitted on a Mac sweep of `scripts/research/iteration-admission.ts` and checked on the rig at widths
27
+ * 8 and 4; a re-calibration updates only these two numbers.
28
+ *
29
+ * `fixedMs` 2 is the smallest value at which no cell of the Mac sweep (18 cells, 4 KiB to 4 MiB
30
+ * by 8 to 128 iterations, width 8) dispatched and lost. The pooled wall minus the batch time
31
+ * measured 0.1 to 2.9 ms there with the input copy left out of the timing; the prototype's rows
32
+ * bracket 3 to 8 ms but include that copy. The loop is not worth dispatching when the serial time
33
+ * of its remaining iterations is below `fixedMs * margin`.
34
+ *
35
+ * `margin` 1.25 is the speedup a batch has to show over the serial time of its iterations for
36
+ * the loop to keep dispatching. A batch that misses it twice in a row ends the dispatch, and so
37
+ * does one batch whose wall passes `batchCollapse` times that serial time.
38
+ */
39
+ export declare const iterationAdmissionConstants: IterationAdmissionConstants;
40
+ export interface AdmitInput {
41
+ plainIterationMs: number;
42
+ trip: number;
43
+ width: number;
44
+ constants?: IterationAdmissionConstants;
45
+ }
46
+ /**
47
+ * Decides before the first dispatch from the measured serial time of iteration 0, which has
48
+ * already run. Admits when at least two iterations are left for at least two workers and their
49
+ * serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
50
+ */
51
+ export declare function admitIteration({ plainIterationMs: t0, trip, width, constants }: AdmitInput): IterationAdmission;
52
+ /** True when a batch did not beat the serial time of its iterations by the margin. */
53
+ export declare function batchLoses(batchWallMs: number, batchSerialMs: number, constants?: IterationAdmissionConstants): boolean;
54
+ /** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
55
+ export declare const batchCollapse = 1.5;
56
+ /** True when a batch took clearly longer than the serial time of its iterations. */
57
+ export declare function batchCollapses(batchWallMs: number, batchSerialMs: number): boolean;
58
+ /**
59
+ * Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
60
+ * iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
61
+ * rule; `force` admits any loop with an iteration left after iteration 0 and never stops on the
62
+ * batch rule. The structural stops (`log-exhausted`, `frame-carried dependence`, `dependency`)
63
+ * are not affected.
64
+ * @internal
65
+ */
66
+ export declare const admissionSeam: {
67
+ scale: number;
68
+ batchScale: number;
69
+ force: boolean;
70
+ };
71
+ /** `admitIteration` through the seam; what the host function calls. */
72
+ export declare function decideAdmission(plainIterationMs: number, trip: number, width: number): IterationAdmission;
73
+ /** `batchLoses` through the seam; what the host function passes the pool. */
74
+ export declare function decideBatch(batchWallMs: number, batchSerialMs: number): boolean;
75
+ /** `batchCollapses` through the seam; what the host function passes the pool. */
76
+ export declare function decideCollapse(batchWallMs: number, batchSerialMs: number): boolean;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Fitted on a Mac sweep of `scripts/research/iteration-admission.ts` and checked on the rig at widths
3
+ * 8 and 4; a re-calibration updates only these two numbers.
4
+ *
5
+ * `fixedMs` 2 is the smallest value at which no cell of the Mac sweep (18 cells, 4 KiB to 4 MiB
6
+ * by 8 to 128 iterations, width 8) dispatched and lost. The pooled wall minus the batch time
7
+ * measured 0.1 to 2.9 ms there with the input copy left out of the timing; the prototype's rows
8
+ * bracket 3 to 8 ms but include that copy. The loop is not worth dispatching when the serial time
9
+ * of its remaining iterations is below `fixedMs * margin`.
10
+ *
11
+ * `margin` 1.25 is the speedup a batch has to show over the serial time of its iterations for
12
+ * the loop to keep dispatching. A batch that misses it twice in a row ends the dispatch, and so
13
+ * does one batch whose wall passes `batchCollapse` times that serial time.
14
+ */
15
+ export const iterationAdmissionConstants = {
16
+ fixedMs: 2,
17
+ margin: 1.25
18
+ };
19
+ /**
20
+ * Decides before the first dispatch from the measured serial time of iteration 0, which has
21
+ * already run. Admits when at least two iterations are left for at least two workers and their
22
+ * serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
23
+ */
24
+ export function admitIteration({ plainIterationMs: t0, trip, width, constants = iterationAdmissionConstants }) {
25
+ const remaining = trip - 1;
26
+ const remainingSerialMs = remaining * t0;
27
+ const floorMs = constants.fixedMs * constants.margin;
28
+ const admitted = Number.isFinite(t0) && remaining >= 2 && width >= 2 && remainingSerialMs > floorMs;
29
+ return { plainIterationMs: t0, remainingSerialMs, floorMs, admitted };
30
+ }
31
+ /** True when a batch did not beat the serial time of its iterations by the margin. */
32
+ export function batchLoses(batchWallMs, batchSerialMs, constants = iterationAdmissionConstants) {
33
+ return batchWallMs * constants.margin > batchSerialMs;
34
+ }
35
+ /** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
36
+ export const batchCollapse = 1.5;
37
+ /** True when a batch took clearly longer than the serial time of its iterations. */
38
+ export function batchCollapses(batchWallMs, batchSerialMs) {
39
+ return batchWallMs > batchSerialMs * batchCollapse;
40
+ }
41
+ /**
42
+ * Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
43
+ * iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
44
+ * rule; `force` admits any loop with an iteration left after iteration 0 and never stops on the
45
+ * batch rule. The structural stops (`log-exhausted`, `frame-carried dependence`, `dependency`)
46
+ * are not affected.
47
+ * @internal
48
+ */
49
+ export const admissionSeam = { scale: 1, batchScale: 1, force: false };
50
+ /** `admitIteration` through the seam; what the host function calls. */
51
+ export function decideAdmission(plainIterationMs, trip, width) {
52
+ const decision = admitIteration({
53
+ plainIterationMs: plainIterationMs * admissionSeam.scale,
54
+ trip,
55
+ width
56
+ });
57
+ if (admissionSeam.force && trip >= 2 && width >= 2)
58
+ decision.admitted = true;
59
+ return decision;
60
+ }
61
+ /** `batchLoses` through the seam; what the host function passes the pool. */
62
+ export function decideBatch(batchWallMs, batchSerialMs) {
63
+ if (admissionSeam.force)
64
+ return false;
65
+ return batchLoses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
66
+ }
67
+ /** `batchCollapses` through the seam; what the host function passes the pool. */
68
+ export function decideCollapse(batchWallMs, batchSerialMs) {
69
+ if (admissionSeam.force)
70
+ return false;
71
+ return batchCollapses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
72
+ }