@mica-js/simulator 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2001,6 +2001,14 @@ function compileObservation(target, key, path) {
2001
2001
  //#endregion
2002
2002
  //#region src/runtime/execution.ts
2003
2003
  var compiledBodies = /* @__PURE__ */ new WeakMap();
2004
+ /**
2005
+ * Deterministic generic-body diagnostics. Translation no longer compiles a body eagerly, so a
2006
+ * Direct-resident workload must leave `compiled` unchanged.
2007
+ */
2008
+ var genericBodies = {
2009
+ compiled: 0,
2010
+ reused: 0
2011
+ };
2004
2012
  var resumablePrograms = /* @__PURE__ */ new WeakMap();
2005
2013
  var compiledComputations = /* @__PURE__ */ new WeakMap();
2006
2014
  /**
@@ -2020,7 +2028,8 @@ function body(region) {
2020
2028
  if (!result) {
2021
2029
  result = compileBody(region);
2022
2030
  compiledBodies.set(region, result);
2023
- }
2031
+ genericBodies.compiled++;
2032
+ } else genericBodies.reused++;
2024
2033
  return result;
2025
2034
  }
2026
2035
  /**
@@ -2195,6 +2204,19 @@ function isPollingInstruction(body, pc, pcName) {
2195
2204
  //#region src/runtime/jit.ts
2196
2205
  /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2197
2206
  var DIRECT_SHARD_SIZE = 32;
2207
+ /**
2208
+ * Process-wide compiler artifact cache for registrations that opt in with
2209
+ * `shareDirectArtifacts: true`. The default gives every registration its own cache.
2210
+ */
2211
+ var sharedDirectArtifacts = compileDirectJit.createArtifactCache();
2212
+ /** Last artifact counters observed by each JIT from its selected cache. */
2213
+ var directArtifactSnapshots = /* @__PURE__ */ new WeakMap();
2214
+ /** False when a declared quiet guard cannot be resolved; marked routes must not enroll. */
2215
+ var directTimingEligible = /* @__PURE__ */ new WeakMap();
2216
+ /** Resolve one registration's artifact cache; omission keeps the original private default. */
2217
+ function resolveDirectArtifactCache(shareDirectArtifacts) {
2218
+ return shareDirectArtifacts === true ? sharedDirectArtifacts : compileDirectJit.createArtifactCache();
2219
+ }
2198
2220
  function syncJitCall(jit, name) {
2199
2221
  const step = jit.host.call(name, []).next();
2200
2222
  if (!step.done) throw new TypeError("Unexpected suspension in synchronous function");
@@ -2249,7 +2271,18 @@ function directStats(jit) {
2249
2271
  directRoutes: 0,
2250
2272
  directDispatchMisses: 0,
2251
2273
  directGenericInstructions: 0,
2274
+ directPromotionGenericRuns: 0,
2275
+ directPromotions: 0,
2276
+ directTierFallbacks: 0,
2277
+ directPromotedRoutes: 0,
2278
+ directPromotionResets: 0,
2252
2279
  directBodyBytes: 0,
2280
+ directArtifactInstructionHits: 0,
2281
+ directArtifactInstructionMisses: 0,
2282
+ directArtifactShardSourceHits: 0,
2283
+ directArtifactFactoryCompiles: 0,
2284
+ directArtifactFactoryReuses: 0,
2285
+ directArtifactEntries: 0,
2253
2286
  directShardBytes: 0,
2254
2287
  directDispatcherBytes: 0,
2255
2288
  directHelperBytes: 0,
@@ -2279,6 +2312,37 @@ function directStats(jit) {
2279
2312
  crossView: 0,
2280
2313
  service: 0,
2281
2314
  notAdmitted: 0
2315
+ },
2316
+ directSpans: 0,
2317
+ directSpanRuns: 0,
2318
+ directSpanRejected: 0,
2319
+ directLoops: 0,
2320
+ directLoopRounds: 0,
2321
+ directLoopRejected: 0,
2322
+ directSpanCallbacks: 0,
2323
+ directSpanCandidates: 0,
2324
+ directLoopCallbacks: 0,
2325
+ directLoopCandidates: 0,
2326
+ directSpanMarkRejected: {
2327
+ invalid: 0,
2328
+ unknownPc: 0,
2329
+ duplicate: 0,
2330
+ discontinuous: 0,
2331
+ notAdmitted: 0,
2332
+ conflict: 0
2333
+ },
2334
+ directLoopMarkRejected: {
2335
+ invalid: 0,
2336
+ unknownPc: 0,
2337
+ duplicate: 0,
2338
+ notAdmitted: 0,
2339
+ delayConflict: 0,
2340
+ conflict: 0,
2341
+ address: 0
2342
+ },
2343
+ directDependencyMarkRejected: {
2344
+ invalidRange: 0,
2345
+ outsideView: 0
2282
2346
  }
2283
2347
  };
2284
2348
  }
@@ -2300,6 +2364,8 @@ function syncDirectSessionStats(jit, session) {
2300
2364
  stats.directRouteInstalls += next.routeInstalls - (base?.routeInstalls ?? 0);
2301
2365
  stats.directRouteRemovals += next.routeRemovals - (base?.routeRemovals ?? 0);
2302
2366
  stats.directBodyBytes += next.bodyBytes - (base?.bodyBytes ?? 0);
2367
+ stats.directArtifactInstructionHits += next.artifactInstructionHits - (base?.artifactInstructionHits ?? 0);
2368
+ stats.directArtifactInstructionMisses += next.artifactInstructionMisses - (base?.artifactInstructionMisses ?? 0);
2303
2369
  stats.directShardBytes += next.shardBytes - (base?.shardBytes ?? 0);
2304
2370
  stats.directDispatcherBytes += next.dispatcherBytes - (base?.dispatcherBytes ?? 0);
2305
2371
  stats.directHelperBytes += next.helperBytes - (base?.helperBytes ?? 0);
@@ -2316,8 +2382,22 @@ function syncDirectSessionStats(jit, session) {
2316
2382
  stats.directShareRejected.delay += next.shareRejected.delay - (base?.shareRejected.delay ?? 0);
2317
2383
  stats.directShareRejected.isolated += next.shareRejected.isolated - (base?.shareRejected.isolated ?? 0);
2318
2384
  stats.directShareRejected.context += next.shareRejected.context - (base?.shareRejected.context ?? 0);
2385
+ stats.directSpans += next.spansInstalled - (base?.spansInstalled ?? 0);
2386
+ stats.directSpanRejected += next.spansRejected - (base?.spansRejected ?? 0);
2387
+ stats.directLoops += next.loopsInstalled - (base?.loopsInstalled ?? 0);
2388
+ stats.directLoopRejected += next.loopsRejected - (base?.loopsRejected ?? 0);
2389
+ const artifacts = compileDirectJit.artifactCacheStats(jit.artifactCache);
2390
+ const artifactsBase = directArtifactSnapshots.get(jit);
2391
+ stats.directArtifactShardSourceHits += artifacts.reusedShardSources - (artifactsBase?.reusedShardSources ?? 0);
2392
+ stats.directArtifactFactoryCompiles += artifacts.createdFactories - (artifactsBase?.createdFactories ?? 0);
2393
+ stats.directArtifactFactoryReuses += artifacts.reusedFactories - (artifactsBase?.reusedFactories ?? 0);
2394
+ stats.directArtifactEntries = artifacts.instructionEntries + artifacts.shardEntries;
2395
+ directArtifactSnapshots.set(jit, artifacts);
2319
2396
  stats.directShards = next.shards;
2320
2397
  stats.directRoutes = next.routes;
2398
+ let promotedRoutes = 0;
2399
+ for (const [pc, promotion] of jit.promotions) if (promotion.state === "promoted" && session.has(pc)) promotedRoutes++;
2400
+ stats.directPromotedRoutes = promotedRoutes;
2321
2401
  directSessionSnapshots.set(jit, {
2322
2402
  session,
2323
2403
  stats: next
@@ -2337,6 +2417,7 @@ function releaseDirectSession(jit) {
2337
2417
  if (stats !== void 0) {
2338
2418
  stats.directShards = 0;
2339
2419
  stats.directRoutes = 0;
2420
+ stats.directPromotedRoutes = 0;
2340
2421
  stats.directShareGroups = 0;
2341
2422
  stats.directSharedRoutes = 0;
2342
2423
  }
@@ -2369,6 +2450,7 @@ function disposeDirect(jit) {
2369
2450
  jit.directStale = false;
2370
2451
  jit.directSkip = void 0;
2371
2452
  jit.directMemories.clear();
2453
+ clearPromotions(jit, false);
2372
2454
  }
2373
2455
  /** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */
2374
2456
  function codeRegionFor(jit, pc) {
@@ -2383,12 +2465,102 @@ function directCodeInstruction(jit, instruction) {
2383
2465
  function directAdmitted(jit, instruction) {
2384
2466
  return !instruction.polling && !effectivePolling(jit).has(instruction.pc) && directCodeInstruction(jit, instruction);
2385
2467
  }
2468
+ /**
2469
+ * Two-tier admission. Without `directTier` every admitted entry keeps the immediate-Direct
2470
+ * policy; with a tier only a promoted entry whose exact translation identity still matches
2471
+ * may enter a session.
2472
+ */
2473
+ function directTierAdmitted(jit, instruction) {
2474
+ if (jit.options.directTier === void 0) return true;
2475
+ if (instruction === void 0) return false;
2476
+ const promotion = jit.promotions.get(instruction.pc);
2477
+ return promotion !== void 0 && promotion.state === "promoted" && promotion.body === instruction.body && promotion.nextPc === instruction.nextPc && promotion.codeVersion === instruction.codeVersion;
2478
+ }
2479
+ /** Revoke one Direct route after its promotion identity changed; suspended suffixes finish. */
2480
+ function revokeDirectRoute(jit, pc) {
2481
+ const direct = jit.direct;
2482
+ if (direct === void 0 || jit.directStale || direct.frame.resume !== 0) return;
2483
+ if (!direct.session.has(pc)) return;
2484
+ direct.session.remove([pc]);
2485
+ syncDirectSessionStats(jit, direct.session);
2486
+ }
2487
+ /**
2488
+ * Clear every promotion record of this instance. `reset` counts the records as invalidated by
2489
+ * primary code writes or IR replacement; explicit disposal clears them silently.
2490
+ */
2491
+ function clearPromotions(jit, reset = true) {
2492
+ if (jit.promotions.size === 0) return;
2493
+ const stats = directJitStats(jit);
2494
+ if (stats !== void 0) {
2495
+ if (reset) stats.directPromotionResets += jit.promotions.size;
2496
+ stats.directPromotedRoutes = 0;
2497
+ }
2498
+ jit.promotions.clear();
2499
+ }
2500
+ /**
2501
+ * Count one successfully completed generic instruction. Only the shared generic body calls
2502
+ * this, after its final suffix and after re-checking that the executed translation is still
2503
+ * the cached one. Polling, rejected and stale paths never reach the threshold.
2504
+ */
2505
+ function recordDirectPromotion(jit, pc, instruction) {
2506
+ const tier = jit.options.directTier;
2507
+ if (tier === void 0) return;
2508
+ const current = jit.cache.get(pc);
2509
+ if (current === void 0 || current.body !== instruction.body || current.nextPc !== instruction.nextPc || current.codeVersion !== instruction.codeVersion || !directAdmitted(jit, current)) return;
2510
+ let promotion = jit.promotions.get(pc);
2511
+ if (promotion !== void 0 && (promotion.body !== current.body || promotion.nextPc !== current.nextPc || promotion.codeVersion !== current.codeVersion)) {
2512
+ jit.promotions.delete(pc);
2513
+ revokeDirectRoute(jit, pc);
2514
+ promotion = void 0;
2515
+ }
2516
+ const stats = directStats(jit);
2517
+ if (promotion === void 0) {
2518
+ promotion = {
2519
+ count: 0,
2520
+ state: "generic",
2521
+ body: current.body,
2522
+ nextPc: current.nextPc,
2523
+ codeVersion: current.codeVersion
2524
+ };
2525
+ jit.promotions.set(pc, promotion);
2526
+ } else if (promotion.state === "promoted") return;
2527
+ stats.directPromotionGenericRuns++;
2528
+ if (promotion.count < tier.promoteAfter) {
2529
+ promotion.count = Math.min(promotion.count + 1, Number.MAX_SAFE_INTEGER);
2530
+ if (promotion.count >= tier.promoteAfter) {
2531
+ promotion.state = "promoted";
2532
+ stats.directPromotions++;
2533
+ }
2534
+ }
2535
+ }
2536
+ /**
2537
+ * Reconcile promotion state with an overlapping translation. Identical body/nextPc/version
2538
+ * keeps the counter; any other replacement clears that PC and revokes its old route.
2539
+ */
2540
+ function reconcilePromotions(jit, instructions, oldEntries) {
2541
+ if (jit.options.directTier === void 0 || jit.promotions.size === 0) return;
2542
+ const stats = directJitStats(jit);
2543
+ for (const instruction of instructions) {
2544
+ if (!oldEntries.has(instruction.pc)) continue;
2545
+ const promotion = jit.promotions.get(instruction.pc);
2546
+ if (promotion === void 0) continue;
2547
+ if (promotion.body === instruction.body && promotion.nextPc === instruction.nextPc && promotion.codeVersion === instruction.codeVersion) continue;
2548
+ jit.promotions.delete(instruction.pc);
2549
+ if (stats !== void 0) stats.directPromotionResets++;
2550
+ revokeDirectRoute(jit, instruction.pc);
2551
+ }
2552
+ }
2386
2553
  function directInstruction(jit, instruction) {
2554
+ const timingEligible = directTimingEligible.get(jit) !== false;
2387
2555
  return {
2388
2556
  pc: instruction.pc,
2389
2557
  nextPc: instruction.nextPc,
2390
2558
  body: instruction.body,
2391
- ...jit.options.shareDirectBodies === true && instruction.share !== void 0 ? { share: instruction.share } : {}
2559
+ ...jit.options.shareDirectBodies === true && instruction.share !== void 0 ? { share: instruction.share } : {},
2560
+ ...!timingEligible ? {} : {
2561
+ ...instruction.span === void 0 ? {} : { span: instruction.span },
2562
+ ...instruction.loop === void 0 ? {} : { loop: instruction.loop }
2563
+ }
2392
2564
  };
2393
2565
  }
2394
2566
  /**
@@ -2456,6 +2628,232 @@ function applyDirectShareMarks(jit, startRegion, codeLength, instructions, marks
2456
2628
  stats.directShareCandidates++;
2457
2629
  }
2458
2630
  }
2631
+ /**
2632
+ * Copy a loop candidate while the translate callback is on the stack. Later mutation of the
2633
+ * caller's object cannot change what this translation validated.
2634
+ */
2635
+ function captureLoopCandidate(value) {
2636
+ try {
2637
+ dataObject(value);
2638
+ const kind = value.kind;
2639
+ if (kind === "spin") return Object.freeze({ kind: "spin" });
2640
+ if (kind !== "decrement8") return void 0;
2641
+ dataObject(value, [
2642
+ "kind",
2643
+ "memory",
2644
+ "address"
2645
+ ]);
2646
+ const record = value;
2647
+ if (typeof record.memory !== "string" || record.memory.length === 0) return void 0;
2648
+ dataObject(record.address);
2649
+ const address = record.address;
2650
+ if (address.kind === "constant") {
2651
+ dataObject(address, ["kind", "offset"]);
2652
+ const offset = address.offset;
2653
+ if (typeof offset !== "number") return void 0;
2654
+ return Object.freeze({
2655
+ kind: "decrement8",
2656
+ memory: record.memory,
2657
+ address: Object.freeze({
2658
+ kind: "constant",
2659
+ offset
2660
+ })
2661
+ });
2662
+ }
2663
+ if (address.kind !== "maskedByte") return void 0;
2664
+ dataObject(address, [
2665
+ "kind",
2666
+ "memory",
2667
+ "offset",
2668
+ "mask",
2669
+ "bits"
2670
+ ]);
2671
+ const masked = address;
2672
+ if (typeof masked.memory !== "string" || masked.memory.length === 0 || typeof masked.offset !== "number" || typeof masked.mask !== "number" || typeof masked.bits !== "number") return void 0;
2673
+ return Object.freeze({
2674
+ kind: "decrement8",
2675
+ memory: record.memory,
2676
+ address: Object.freeze({
2677
+ kind: "maskedByte",
2678
+ memory: masked.memory,
2679
+ offset: masked.offset,
2680
+ mask: masked.mask,
2681
+ bits: masked.bits
2682
+ })
2683
+ });
2684
+ } catch {
2685
+ return;
2686
+ }
2687
+ }
2688
+ /** Primary memory and the ordinary Direct admission shared by span members. */
2689
+ function directPrimaryAdmitted(jit, instruction) {
2690
+ const region = instruction.codeRegion;
2691
+ return region !== void 0 && region.memory === jit.options.code && directAdmitted(jit, instruction);
2692
+ }
2693
+ /** Validate a decrement8 address against the instance memories; undefined means rejected. */
2694
+ function directLoopCandidate(jit, candidate) {
2695
+ if (candidate.kind === "spin") return Object.freeze({ kind: "spin" });
2696
+ const memory = candidate.memory;
2697
+ if (typeof memory !== "string" || memory.length === 0) return void 0;
2698
+ if (jit.codeRegions.some((region) => region.memory === memory)) return void 0;
2699
+ const counter = jit.instance.memories.get(memory);
2700
+ if (counter === void 0) return void 0;
2701
+ const address = candidate.address;
2702
+ if (address.kind === "constant") {
2703
+ const offset = address.offset;
2704
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= counter.length) return void 0;
2705
+ return Object.freeze({
2706
+ kind: "decrement8",
2707
+ memory,
2708
+ address: Object.freeze({
2709
+ kind: "constant",
2710
+ offset
2711
+ })
2712
+ });
2713
+ }
2714
+ const selectorMemory = address.memory;
2715
+ const offset = address.offset;
2716
+ const mask = address.mask;
2717
+ const bits = address.bits;
2718
+ if (typeof selectorMemory !== "string" || selectorMemory.length === 0) return void 0;
2719
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(mask) || mask < 0 || mask > 255 || !Number.isSafeInteger(bits) || bits < 0 || bits > 255) return void 0;
2720
+ const selector = jit.instance.memories.get(selectorMemory);
2721
+ if (selector === void 0 || offset >= selector.length) return void 0;
2722
+ if (jit.codeRegions.some((region) => region.memory === selectorMemory)) return void 0;
2723
+ if ((mask | bits) >= counter.length) return void 0;
2724
+ for (let value = 0; value < 256; value++) if ((value & mask | bits) >>> 0 >= counter.length) return void 0;
2725
+ return Object.freeze({
2726
+ kind: "decrement8",
2727
+ memory,
2728
+ address: Object.freeze({
2729
+ kind: "maskedByte",
2730
+ memory: selectorMemory,
2731
+ offset,
2732
+ mask,
2733
+ bits
2734
+ })
2735
+ });
2736
+ }
2737
+ /**
2738
+ * Attach validated Direct timing marks to their translated entries. Rejections only drop the
2739
+ * optimization: the block itself is already committed to the ordinary interpreter path.
2740
+ */
2741
+ function applyDirectTimingMarks(jit, instructions, spanMarks, loopMarks) {
2742
+ if (spanMarks.length === 0 && loopMarks.length === 0) return;
2743
+ const stats = directStats(jit);
2744
+ const indexByPc = /* @__PURE__ */ new Map();
2745
+ for (let index = 0; index < instructions.length; index++) {
2746
+ const pc = instructions[index].pc;
2747
+ if (!indexByPc.has(pc)) indexByPc.set(pc, index);
2748
+ }
2749
+ const spanPcs = /* @__PURE__ */ new Set();
2750
+ const loopPcs = /* @__PURE__ */ new Set();
2751
+ for (const mark of spanMarks) if (Number.isSafeInteger(mark.pc) && mark.pc >= 0 && Number.isInteger(mark.instructionCount) && mark.instructionCount >= 2 && mark.instructionCount <= 8) spanPcs.add(mark.pc);
2752
+ for (const mark of loopMarks) if (Number.isSafeInteger(mark.pc) && mark.pc >= 0) loopPcs.add(mark.pc);
2753
+ const spanRejected = stats.directSpanMarkRejected;
2754
+ const seenSpans = /* @__PURE__ */ new Set();
2755
+ for (const mark of spanMarks) {
2756
+ const { pc, instructionCount } = mark;
2757
+ if (!Number.isSafeInteger(pc) || pc < 0 || !Number.isInteger(instructionCount) || instructionCount < 2 || instructionCount > 8) {
2758
+ spanRejected.invalid++;
2759
+ continue;
2760
+ }
2761
+ if (seenSpans.has(pc)) {
2762
+ spanRejected.duplicate++;
2763
+ continue;
2764
+ }
2765
+ seenSpans.add(pc);
2766
+ if (loopPcs.has(pc)) {
2767
+ spanRejected.conflict++;
2768
+ continue;
2769
+ }
2770
+ const index = indexByPc.get(pc);
2771
+ if (index === void 0) {
2772
+ spanRejected.unknownPc++;
2773
+ continue;
2774
+ }
2775
+ if (index + instructionCount > instructions.length) {
2776
+ spanRejected.discontinuous++;
2777
+ continue;
2778
+ }
2779
+ const members = instructions.slice(index, index + instructionCount);
2780
+ const memberPcs = /* @__PURE__ */ new Set();
2781
+ let continuous = true;
2782
+ for (let member = 0; member < members.length; member++) {
2783
+ const current = members[member];
2784
+ if (memberPcs.has(current.pc)) {
2785
+ continuous = false;
2786
+ break;
2787
+ }
2788
+ memberPcs.add(current.pc);
2789
+ const next = members[member + 1];
2790
+ if (next !== void 0 && current.nextPc !== next.pc) {
2791
+ continuous = false;
2792
+ break;
2793
+ }
2794
+ }
2795
+ if (!continuous) {
2796
+ spanRejected.discontinuous++;
2797
+ continue;
2798
+ }
2799
+ if (members.some((member) => !directPrimaryAdmitted(jit, member))) {
2800
+ spanRejected.notAdmitted++;
2801
+ continue;
2802
+ }
2803
+ const pcs = Object.freeze(members.map((member) => member.pc));
2804
+ instructions[index] = {
2805
+ ...instructions[index],
2806
+ span: Object.freeze({ pcs })
2807
+ };
2808
+ stats.directSpanCandidates++;
2809
+ }
2810
+ const loopRejected = stats.directLoopMarkRejected;
2811
+ const seenLoops = /* @__PURE__ */ new Set();
2812
+ for (const mark of loopMarks) {
2813
+ const { pc, candidate } = mark;
2814
+ if (!Number.isSafeInteger(pc) || pc < 0) {
2815
+ loopRejected.invalid++;
2816
+ continue;
2817
+ }
2818
+ if (seenLoops.has(pc)) {
2819
+ loopRejected.duplicate++;
2820
+ continue;
2821
+ }
2822
+ seenLoops.add(pc);
2823
+ if (spanPcs.has(pc)) {
2824
+ loopRejected.conflict++;
2825
+ continue;
2826
+ }
2827
+ const index = indexByPc.get(pc);
2828
+ if (index === void 0) {
2829
+ loopRejected.unknownPc++;
2830
+ continue;
2831
+ }
2832
+ const instruction = instructions[index];
2833
+ if (!directAdmitted(jit, instruction)) {
2834
+ loopRejected.notAdmitted++;
2835
+ continue;
2836
+ }
2837
+ if (effectiveDelays(jit).has(pc)) {
2838
+ loopRejected.delayConflict++;
2839
+ continue;
2840
+ }
2841
+ if (candidate === void 0) {
2842
+ loopRejected.invalid++;
2843
+ continue;
2844
+ }
2845
+ const loop = directLoopCandidate(jit, candidate);
2846
+ if (loop === void 0) {
2847
+ loopRejected.address++;
2848
+ continue;
2849
+ }
2850
+ instructions[index] = {
2851
+ ...instruction,
2852
+ loop
2853
+ };
2854
+ stats.directLoopCandidates++;
2855
+ }
2856
+ }
2459
2857
  function effectivePolling(jit) {
2460
2858
  return jit.metadata?.polling ?? jit.polling;
2461
2859
  }
@@ -2757,6 +3155,38 @@ function directDelayLoops(jit, layout) {
2757
3155
  function directBinding(jit, layout) {
2758
3156
  const { states, memories, pins } = layout;
2759
3157
  const entry = entryBlockedNames(jit);
3158
+ let functions = jit.functions;
3159
+ let directTiming;
3160
+ let timingEligible = true;
3161
+ const option = jit.options.directTiming;
3162
+ if (option !== void 0) {
3163
+ let blocked = option.blocked;
3164
+ if (blocked !== void 0) {
3165
+ const declaration = functions?.get(blocked) ?? jit.instance.declarations.get(blocked);
3166
+ if (declaration?.kind !== "function" || declaration.pure !== true || declaration.params.length !== 0 || declaration.returns?.kind !== "bool") {
3167
+ blocked = void 0;
3168
+ timingEligible = false;
3169
+ } else if (functions?.get(blocked) === void 0) {
3170
+ const extended = new Map(functions ?? []);
3171
+ extended.set(blocked, declaration);
3172
+ functions = extended;
3173
+ }
3174
+ }
3175
+ const service = option.service;
3176
+ if (service !== void 0) {
3177
+ const elapsed = states.get(service.elapsed);
3178
+ const deadline = states.get(service.deadline);
3179
+ if ((option.blocked === void 0 || blocked !== void 0) && elapsed !== void 0 && deadline !== void 0) directTiming = {
3180
+ elapsed,
3181
+ deadline,
3182
+ ...blocked === void 0 ? {} : { blocked }
3183
+ };
3184
+ }
3185
+ }
3186
+ const memoryLengths = /* @__PURE__ */ new Map();
3187
+ for (const name of layout.memoryNames) memoryLengths.set(name, jit.instance.memory(name).length);
3188
+ const codeMemories = new Set(jit.codeRegions.map((region) => region.memory));
3189
+ directTimingEligible.set(jit, timingEligible);
2760
3190
  return {
2761
3191
  states,
2762
3192
  memories,
@@ -2766,14 +3196,17 @@ function directBinding(jit, layout) {
2766
3196
  index: states.get(jit.options.pc)
2767
3197
  },
2768
3198
  host: true,
2769
- ...jit.functions === void 0 ? {} : { functions: jit.functions },
3199
+ ...functions === void 0 ? {} : { functions },
2770
3200
  split: true,
2771
3201
  shardSize: DIRECT_SHARD_SIZE,
2772
3202
  delayLoops: directDelayLoops(jit, layout),
2773
3203
  entryBlockedStates: entry.states,
2774
3204
  entryBlockedMemories: entry.memories,
2775
3205
  blockedStates: jit.directStateGuards,
2776
- blockedMemories: jit.directMemoryGuards
3206
+ blockedMemories: jit.directMemoryGuards,
3207
+ ...directTiming === void 0 ? {} : { directTiming },
3208
+ memoryLengths,
3209
+ codeMemories
2777
3210
  };
2778
3211
  }
2779
3212
  /** Grow the frame's local bank only between runs, never while a suffix is suspended. */
@@ -2792,7 +3225,7 @@ function addDirectInstructions(jit, instructions) {
2792
3225
  const direct = jit.direct;
2793
3226
  if (direct === void 0 || jit.directStale || direct.frame.resume !== 0) return;
2794
3227
  const admitted = [];
2795
- for (const instruction of instructions) if (directAdmitted(jit, instruction)) admitted.push(instruction);
3228
+ for (const instruction of instructions) if (directAdmitted(jit, instruction) && (jit.options.directTier === void 0 || directTierAdmitted(jit, instruction))) admitted.push(instruction);
2796
3229
  direct.session.updateDelays(directDelayLoops(jit, jit.directLayout));
2797
3230
  if (admitted.length) {
2798
3231
  direct.session.add(admitted.map((instruction) => directInstruction(jit, instruction)));
@@ -2820,17 +3253,19 @@ function commitDirectTranslation(jit, instructions, replaced) {
2820
3253
  function ensureDirectSession(board, jit) {
2821
3254
  if (jit.direct !== void 0) return jit.direct;
2822
3255
  if (jit.directStale) jit.directStale = false;
3256
+ const admitted = [];
3257
+ for (const instruction of jit.cache.values()) if (directAdmitted(jit, instruction) && (jit.options.directTier === void 0 || directTierAdmitted(jit, instruction))) admitted.push(instruction);
3258
+ if (jit.options.directTier !== void 0 && admitted.length === 0) return void 0;
2823
3259
  const layout = directLayout(jit);
2824
3260
  if (jit.directCacheInvalid) {
2825
3261
  if (jit.directCache !== void 0) compileDirectJit.clearCache(jit.directCache);
2826
3262
  jit.directCacheInvalid = false;
2827
3263
  }
2828
3264
  const cache = jit.directCache ??= compileDirectJit.createCache();
3265
+ if (!directArtifactSnapshots.has(jit)) directArtifactSnapshots.set(jit, compileDirectJit.artifactCacheStats(jit.artifactCache));
2829
3266
  let session;
2830
- const admitted = [];
2831
3267
  try {
2832
- session = compileDirectJit.createSession(directBinding(jit, layout), cache);
2833
- for (const instruction of jit.cache.values()) if (directAdmitted(jit, instruction)) admitted.push(instruction);
3268
+ session = compileDirectJit.createSession(directBinding(jit, layout), cache, jit.artifactCache);
2834
3269
  if (admitted.length) session.add(admitted.map((instruction) => directInstruction(jit, instruction)));
2835
3270
  session.updateDelays(directDelayLoops(jit, layout));
2836
3271
  } catch (cause) {
@@ -2879,7 +3314,11 @@ function createDirectFrame(board, jit, layout, session, barrier) {
2879
3314
  due: board.time,
2880
3315
  resume: 0,
2881
3316
  stopAfterInstruction: false,
2882
- boundarySettled: false
3317
+ boundarySettled: false,
3318
+ directMetrics: {
3319
+ spanRuns: 0,
3320
+ loopRounds: 0
3321
+ }
2883
3322
  };
2884
3323
  frame.writePinIntent = (pinIndex, value) => {
2885
3324
  if (!Object.hasOwn(instance, "writeIntent")) {
@@ -2959,6 +3398,10 @@ function runDirect(board, jit, hookReads) {
2959
3398
  if (board.execution !== "throughput" || board.jits.length !== 1 || region !== void 0 && region.memory !== jit.options.code || effectivePolling(jit).has(pc) || jit.cache.get(pc)?.polling) return "declined";
2960
3399
  refreshDirectGuards(jit, hookReads);
2961
3400
  if (jit.directSkip === pc) return "declined";
3401
+ if (jit.options.directTier !== void 0 && !directTierAdmitted(jit, jit.cache.get(pc))) {
3402
+ if (jit.cache.has(pc)) directStats(jit).directTierFallbacks++;
3403
+ return "declined";
3404
+ }
2962
3405
  if (jit.direct === void 0 && ensureDirectSession(board, jit) === void 0) return "declined";
2963
3406
  }
2964
3407
  const direct = jit.direct;
@@ -2971,11 +3414,21 @@ function runDirect(board, jit, hookReads) {
2971
3414
  let reason;
2972
3415
  let wrote;
2973
3416
  const stats = directStats(jit);
3417
+ const metrics = frame.directMetrics;
3418
+ const beforeSpanRuns = metrics?.spanRuns ?? 0;
3419
+ const beforeLoopRounds = metrics?.loopRounds ?? 0;
2974
3420
  stats.directCalls++;
2975
3421
  try {
2976
3422
  reason = direct.session.run(frame, Math.min(board.executionEnd, board.events.time));
2977
3423
  } finally {
2978
- wrote = flushDirect(board, instance, layout, frame);
3424
+ try {
3425
+ wrote = flushDirect(board, instance, layout, frame);
3426
+ } finally {
3427
+ if (metrics !== void 0) {
3428
+ stats.directSpanRuns += metrics.spanRuns - beforeSpanRuns;
3429
+ stats.directLoopRounds += metrics.loopRounds - beforeLoopRounds;
3430
+ }
3431
+ }
2979
3432
  }
2980
3433
  const progressed = wrote || board.time !== start;
2981
3434
  if (frame.boundarySettled) frame.boundarySettled = false;
@@ -3054,6 +3507,7 @@ function assembleDirect(board, jit, pc) {
3054
3507
  instruction = jit.cache.get(pc);
3055
3508
  return instruction !== void 0;
3056
3509
  }
3510
+ if (jit.options.directTier !== void 0 && !directTierAdmitted(jit, instruction)) return false;
3057
3511
  if (!direct.session.has(pc)) addDirectInstructions(jit, [instruction]);
3058
3512
  return true;
3059
3513
  }
@@ -3136,6 +3590,7 @@ function jitSignal(board, jit, signal) {
3136
3590
  if (signal.kind === "stop") {
3137
3591
  jit.stopped = true;
3138
3592
  jit.execution = void 0;
3593
+ if (jit.options.directTier !== void 0) jit.genericInstruction = void 0;
3139
3594
  board.boundary("jitSignal");
3140
3595
  return true;
3141
3596
  }
@@ -3144,6 +3599,7 @@ function jitSignal(board, jit, signal) {
3144
3599
  const duration = time(signal.delay);
3145
3600
  jit.instance.host.write(jit.options.pc, signal.pc);
3146
3601
  jit.execution = void 0;
3602
+ if (jit.options.directTier !== void 0) jit.genericInstruction = void 0;
3147
3603
  const polling = jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;
3148
3604
  const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : void 0;
3149
3605
  jit.automaticPolling = false;
@@ -3182,7 +3638,10 @@ function translateBlock(board, jit, pc) {
3182
3638
  if (!valid) throw board.error("OBJECT_DISPOSED", "Translation view expired", jit.instance);
3183
3639
  });
3184
3640
  const shareMarks = jit.options.shareDirectBodies === true ? [] : void 0;
3185
- marking = shareMarks !== void 0;
3641
+ const spanMarks = jit.options.directTiming !== void 0 ? [] : void 0;
3642
+ const loopMarks = jit.options.directTiming !== void 0 ? [] : void 0;
3643
+ const dependencyMarks = jit.options.translationIdentity !== void 0;
3644
+ marking = shareMarks !== void 0 || spanMarks !== void 0 || loopMarks !== void 0 || dependencyMarks;
3186
3645
  const result = jit.options.translate(Object.freeze({
3187
3646
  pc,
3188
3647
  code,
@@ -3195,6 +3654,44 @@ function translateBlock(board, jit, pc) {
3195
3654
  pc: markPc,
3196
3655
  byteLength
3197
3656
  });
3657
+ } },
3658
+ ...spanMarks === void 0 ? {} : { markDirectSpan: (markPc, instructionCount) => {
3659
+ if (!marking) return;
3660
+ directStats(jit).directSpanCallbacks++;
3661
+ spanMarks.push({
3662
+ pc: markPc,
3663
+ instructionCount
3664
+ });
3665
+ } },
3666
+ ...loopMarks === void 0 ? {} : { markDirectLoop: (markPc, candidate) => {
3667
+ if (!marking) return;
3668
+ directStats(jit).directLoopCallbacks++;
3669
+ loopMarks.push({
3670
+ pc: markPc,
3671
+ candidate: captureLoopCandidate(candidate)
3672
+ });
3673
+ } },
3674
+ ...!dependencyMarks ? {} : { markTranslationDependencies: (ranges) => {
3675
+ if (!marking) return;
3676
+ const rejected = directStats(jit).directDependencyMarkRejected;
3677
+ if (!Array.isArray(ranges)) {
3678
+ rejected.invalidRange++;
3679
+ return;
3680
+ }
3681
+ for (const range of ranges) {
3682
+ try {
3683
+ dataObject(range, ["offset", "length"]);
3684
+ } catch {
3685
+ rejected.invalidRange++;
3686
+ continue;
3687
+ }
3688
+ const { offset, length } = range;
3689
+ if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 || typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || !Number.isSafeInteger(offset + length)) {
3690
+ rejected.invalidRange++;
3691
+ continue;
3692
+ }
3693
+ if (offset + length > code.length) rejected.outsideView++;
3694
+ }
3198
3695
  } }
3199
3696
  }), createJitBlockBuilder({ device: jit.model }));
3200
3697
  acceptSync(result);
@@ -3208,18 +3705,24 @@ function translateBlock(board, jit, pc) {
3208
3705
  nextPc: instruction.nextPc,
3209
3706
  body: instruction.body,
3210
3707
  polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),
3211
- execute: body(instruction.body),
3212
3708
  codeRegion: region,
3213
3709
  codeVersion: jit.instance.codeVersion(region?.memory ?? jit.options.code)
3214
3710
  };
3215
3711
  });
3712
+ if (spanMarks !== void 0 || loopMarks !== void 0) applyDirectTimingMarks(jit, instructions, spanMarks ?? [], loopMarks ?? []);
3216
3713
  if (shareMarks !== void 0) applyDirectShareMarks(jit, codeRegion, code.length, instructions, shareMarks);
3217
- const replaced = instructions.some((entry) => jit.cache.has(entry.pc));
3714
+ const oldEntries = /* @__PURE__ */ new Map();
3715
+ for (const entry of instructions) {
3716
+ const previous = jit.cache.get(entry.pc);
3717
+ if (previous !== void 0) oldEntries.set(entry.pc, previous);
3718
+ }
3719
+ const replaced = oldEntries.size !== 0;
3218
3720
  for (let index = instructions.length - 1; index >= 0; index--) {
3219
3721
  const entry = instructions[index];
3220
3722
  jit.cache.set(entry.pc, entry);
3221
3723
  jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);
3222
3724
  }
3725
+ if (jit.options.directTier !== void 0) reconcilePromotions(jit, instructions, oldEntries);
3223
3726
  if (instructions.some((entry) => entry.codeRegion === void 0 || entry.codeRegion.memory === jit.options.code)) jit.revision++;
3224
3727
  jit.directSkip = void 0;
3225
3728
  commitDirectTranslation(jit, instructions, replaced);
@@ -3245,6 +3748,7 @@ function runJit(board, jit) {
3245
3748
  if (!jit.execution) {
3246
3749
  jit.automaticPolling = false;
3247
3750
  jit.pollReads = void 0;
3751
+ if (jit.options.directTier !== void 0) jit.genericInstruction = void 0;
3248
3752
  let hookReads;
3249
3753
  let hookPending = false;
3250
3754
  const hook = jit.options.beforeInstruction;
@@ -3295,8 +3799,15 @@ function runJit(board, jit) {
3295
3799
  if (board.execution === "throughput" && board.jits.length === 1) directStats(jit).directGenericInstructions++;
3296
3800
  jit.automaticPolling = board.execution === "throughput" && board.jits.length === 1 && instruction.polling && !hookPending && (!hook || hookReads !== void 0);
3297
3801
  jit.pollReads = hookReads;
3802
+ let execute;
3803
+ try {
3804
+ execute = instruction.execute ??= body(instruction.body);
3805
+ } catch (cause) {
3806
+ throw board.wrap(cause, "JIT_FAILED", "translate", jit.instance);
3807
+ }
3298
3808
  jit.instance.host.write(jit.options.pc, instruction.nextPc);
3299
- jit.execution = instruction.execute(jit.host);
3809
+ if (jit.options.directTier !== void 0) jit.genericInstruction = instruction;
3810
+ jit.execution = execute(jit.host);
3300
3811
  }
3301
3812
  for (;;) {
3302
3813
  const step = jit.automaticPolling ? (() => {
@@ -3306,6 +3817,11 @@ function runJit(board, jit) {
3306
3817
  })() : jit.execution.next();
3307
3818
  if (step.done) {
3308
3819
  jit.execution = void 0;
3820
+ if (jit.options.directTier !== void 0) {
3821
+ const instruction = jit.genericInstruction;
3822
+ jit.genericInstruction = void 0;
3823
+ if (instruction !== void 0 && !jit.automaticPolling && board.execution === "throughput" && board.jits.length === 1) recordDirectPromotion(jit, instruction.pc, instruction);
3824
+ }
3309
3825
  board.boundary("runJit");
3310
3826
  board.queueJit(jit);
3311
3827
  return;
@@ -3939,6 +4455,7 @@ var Instance = class {
3939
4455
  jit.cache.clear();
3940
4456
  jit.cacheMemories.clear();
3941
4457
  jit.revision++;
4458
+ clearPromotions(jit);
3942
4459
  invalidateDirect(jit, true);
3943
4460
  } else if (jit.cacheMemories.has(name)) {
3944
4461
  for (const [pc, instruction] of jit.cache) if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);
@@ -4247,6 +4764,59 @@ var Instance = class {
4247
4764
  value: captured
4248
4765
  });
4249
4766
  }
4767
+ bindingObject(value, fields, message) {
4768
+ try {
4769
+ dataObject(value, fields);
4770
+ } catch {
4771
+ throw this.board.error("INVALID_BINDING", message, this);
4772
+ }
4773
+ return value;
4774
+ }
4775
+ captureDirectTiming(value, functions) {
4776
+ const input = this.bindingObject(value, ["service", "blocked"], "Invalid directTiming");
4777
+ let service;
4778
+ if (Object.hasOwn(input, "service")) {
4779
+ const raw = this.bindingObject(input.service, ["elapsed", "deadline"], "Invalid directTiming service");
4780
+ if (!Object.hasOwn(raw, "elapsed") || !Object.hasOwn(raw, "deadline")) throw this.board.error("INVALID_BINDING", "directTiming service is incomplete", this);
4781
+ const elapsed = raw.elapsed;
4782
+ const deadline = raw.deadline;
4783
+ if (typeof elapsed !== "string" || elapsed.length === 0 || typeof deadline !== "string" || deadline.length === 0) throw this.board.error("INVALID_BINDING", "Invalid directTiming service states", this);
4784
+ for (const name of [elapsed, deadline]) {
4785
+ const declaration = this.declarations.get(name);
4786
+ if (declaration?.kind !== "state" || declaration.type.kind !== "number") throw this.board.error("INVALID_BINDING", "directTiming service must name number states", this);
4787
+ }
4788
+ service = Object.freeze({
4789
+ elapsed,
4790
+ deadline
4791
+ });
4792
+ }
4793
+ if (Object.hasOwn(input, "blocked") && service === void 0) throw this.board.error("INVALID_BINDING", "directTiming blocked requires service", this);
4794
+ let blocked;
4795
+ if (Object.hasOwn(input, "blocked")) {
4796
+ const name = input.blocked;
4797
+ if (typeof name !== "string" || name.length === 0) throw this.board.error("INVALID_BINDING", "Invalid directTiming blocked function", this);
4798
+ const declaration = functions?.get(name) ?? this.declarations.get(name);
4799
+ if (declaration?.kind !== "function" || declaration.pure !== true || declaration.params.length !== 0 || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid directTiming blocked function", this);
4800
+ blocked = name;
4801
+ }
4802
+ return Object.freeze({
4803
+ ...service === void 0 ? {} : { service },
4804
+ ...blocked === void 0 ? {} : { blocked }
4805
+ });
4806
+ }
4807
+ captureTranslationIdentity(value) {
4808
+ const input = this.bindingObject(value, ["abi", "configuration"], "Invalid translationIdentity");
4809
+ if (!Object.hasOwn(input, "abi") || !Object.hasOwn(input, "configuration") || typeof input.abi !== "string" || input.abi.length === 0 || typeof input.configuration !== "string" || input.configuration.length === 0) throw this.board.error("INVALID_BINDING", "Invalid translationIdentity", this);
4810
+ return Object.freeze({
4811
+ abi: input.abi,
4812
+ configuration: input.configuration
4813
+ });
4814
+ }
4815
+ captureDirectTier(value) {
4816
+ const input = this.bindingObject(value, ["promoteAfter"], "Invalid directTier");
4817
+ if (!Object.hasOwn(input, "promoteAfter") || !Number.isSafeInteger(input.promoteAfter) || input.promoteAfter <= 0) throw this.board.error("INVALID_BINDING", "Invalid directTier promoteAfter", this);
4818
+ return Object.freeze({ promoteAfter: input.promoteAfter });
4819
+ }
4250
4820
  captureCodeRegions(options) {
4251
4821
  const primaryMemory = this.memories.get(options.code);
4252
4822
  const primary = Object.freeze({
@@ -4384,7 +4954,11 @@ var Instance = class {
4384
4954
  "beforeInstruction",
4385
4955
  "polling",
4386
4956
  "delays",
4957
+ "directTiming",
4387
4958
  "shareDirectBodies",
4959
+ "shareDirectArtifacts",
4960
+ "translationIdentity",
4961
+ "directTier",
4388
4962
  "translate"
4389
4963
  ]);
4390
4964
  identity(options.entry);
@@ -4405,6 +4979,7 @@ var Instance = class {
4405
4979
  const polling = Object.hasOwn(options, "polling") ? this.capturePolling(options.polling) : /* @__PURE__ */ new Map();
4406
4980
  if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
4407
4981
  if (Object.hasOwn(options, "shareDirectBodies") && typeof options.shareDirectBodies !== "boolean") throw new TypeError("shareDirectBodies must be a boolean");
4982
+ if (Object.hasOwn(options, "shareDirectArtifacts") && typeof options.shareDirectArtifacts !== "boolean") throw new TypeError("shareDirectArtifacts must be a boolean");
4408
4983
  const metadata = Object.hasOwn(options, "codeMetadata") ? {
4409
4984
  regions: new Map(codeRegions.all.map((region) => [region, {
4410
4985
  region,
@@ -4439,6 +5014,10 @@ var Instance = class {
4439
5014
  }
4440
5015
  };
4441
5016
  }
5017
+ const directTiming = Object.hasOwn(options, "directTiming") ? this.captureDirectTiming(options.directTiming, functions) : void 0;
5018
+ const translationIdentity = Object.hasOwn(options, "translationIdentity") ? this.captureTranslationIdentity(options.translationIdentity) : void 0;
5019
+ const directTier = Object.hasOwn(options, "directTier") ? this.captureDirectTier(options.directTier) : void 0;
5020
+ const artifactCache = resolveDirectArtifactCache(options.shareDirectArtifacts);
4442
5021
  const jit = {
4443
5022
  instance: this,
4444
5023
  model,
@@ -4447,11 +5026,15 @@ var Instance = class {
4447
5026
  options: Object.freeze({
4448
5027
  ...options,
4449
5028
  ...options.codeRegions === void 0 ? {} : { codeRegions: codeRegions.additional },
4450
- ...options.beforeInstruction ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) } : {}
5029
+ ...options.beforeInstruction ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) } : {},
5030
+ ...directTiming === void 0 ? {} : { directTiming },
5031
+ ...translationIdentity === void 0 ? {} : { translationIdentity },
5032
+ ...directTier === void 0 ? {} : { directTier }
4451
5033
  }),
4452
5034
  codeRegions: codeRegions.all,
4453
5035
  cache: /* @__PURE__ */ new Map(),
4454
5036
  cacheMemories: /* @__PURE__ */ new Set(),
5037
+ promotions: /* @__PURE__ */ new Map(),
4455
5038
  metadata,
4456
5039
  polling,
4457
5040
  delays: options.delays ?? /* @__PURE__ */ new Map(),
@@ -4461,6 +5044,7 @@ var Instance = class {
4461
5044
  directMemoryGuards: /* @__PURE__ */ new Set(),
4462
5045
  directHookReads: /* @__PURE__ */ new Set(),
4463
5046
  directMemories: /* @__PURE__ */ new Set(),
5047
+ artifactCache,
4464
5048
  direct: void 0,
4465
5049
  directSkip: void 0,
4466
5050
  directStale: false,
@@ -4477,7 +5061,8 @@ var Instance = class {
4477
5061
  active: true,
4478
5062
  stopped: false,
4479
5063
  queued: false,
4480
- execution: void 0
5064
+ execution: void 0,
5065
+ genericInstruction: void 0
4481
5066
  };
4482
5067
  this.jits.push(jit);
4483
5068
  this.board.jits.push(jit);