shape-jit 0.3.0

Tiered JIT compiler (Cranelift) for the Shape virtual machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! Accessor methods and utility functions
//!
//! This module contains simple accessor methods and helper functions
//! for querying JIT compiler state.

use super::setup::JITCompiler;
use crate::context::JittedStrategyFn;
use shape_vm::bytecode::{BuiltinFunction, BytecodeProgram, Instruction, OpCode, Operand};

impl JITCompiler {
    /// Get the function table for setting up JITContext
    #[inline(always)]
    pub fn get_function_table(&self) -> &[*const u8] {
        &self.function_table
    }

    /// Get a compiled function pointer by function index
    #[inline(always)]
    pub fn get_function_by_index(&self, idx: usize) -> Option<JittedStrategyFn> {
        self.function_table.get(idx).and_then(|&ptr| {
            if ptr.is_null() {
                None
            } else {
                Some(unsafe { std::mem::transmute(ptr) })
            }
        })
    }
}

/// Program-level preflight report for JIT capability checks.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct JitPreflightReport {
    /// Opcodes that require VM execution for correct behavior.
    pub vm_only_opcodes: Vec<OpCode>,
    /// Builtins that are not lowered by the JIT translator.
    pub unsupported_builtins: Vec<BuiltinFunction>,
}

impl JitPreflightReport {
    /// True when the program can run safely in JIT without semantic downgrades.
    pub fn can_jit(&self) -> bool {
        self.vm_only_opcodes.is_empty() && self.unsupported_builtins.is_empty()
    }

    /// Human-readable blocker summary for diagnostics/logging.
    pub fn blockers_summary(&self) -> String {
        let mut parts = Vec::new();

        if !self.vm_only_opcodes.is_empty() {
            let opcodes = self
                .vm_only_opcodes
                .iter()
                .map(|op| format!("{op:?}"))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("opcodes=[{opcodes}]"));
        }

        if !self.unsupported_builtins.is_empty() {
            let builtins = self
                .unsupported_builtins
                .iter()
                .map(|builtin| format!("{builtin:?}"))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("builtins=[{builtins}]"));
        }

        if parts.is_empty() {
            "none".to_string()
        } else {
            parts.join("; ")
        }
    }
}

/// Program-level JIT parity entry (opcode/builtin support row).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JitParityEntry {
    pub target: JitParityTarget,
    pub jit_supported: bool,
    pub reason: &'static str,
}

/// What the parity row describes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JitParityTarget {
    Opcode(OpCode),
    Builtin(BuiltinFunction),
}

fn push_unique_opcode(out: &mut Vec<OpCode>, opcode: OpCode) {
    if !out.contains(&opcode) {
        out.push(opcode);
    }
}

fn push_unique_builtin(out: &mut Vec<BuiltinFunction>, builtin: BuiltinFunction) {
    if !out.contains(&builtin) {
        out.push(builtin);
    }
}

fn sort_opcodes(opcodes: &mut [OpCode]) {
    opcodes.sort_by_key(|op| format!("{op:?}"));
}

fn sort_builtins(builtins: &mut [BuiltinFunction]) {
    builtins.sort_by_key(|builtin| format!("{builtin:?}"));
}

const ALL_OPCODES: &[OpCode] = &[
    OpCode::PushConst,
    OpCode::PushNull,
    OpCode::Pop,
    OpCode::Dup,
    OpCode::Swap,
    OpCode::BitAnd,
    OpCode::BitOr,
    OpCode::BitShl,
    OpCode::BitShr,
    OpCode::BitNot,
    OpCode::BitXor,
    OpCode::GtInt,
    OpCode::GtNumber,
    OpCode::GtDecimal,
    OpCode::LtInt,
    OpCode::LtNumber,
    OpCode::LtDecimal,
    OpCode::GteInt,
    OpCode::GteNumber,
    OpCode::GteDecimal,
    OpCode::LteInt,
    OpCode::EqInt,
    OpCode::EqNumber,
    OpCode::NeqInt,
    OpCode::NeqNumber,
    OpCode::EqString,
    OpCode::GtString,
    OpCode::LtString,
    OpCode::GteString,
    OpCode::LteString,
    OpCode::EqDecimal,
    OpCode::IsNull,
    OpCode::And,
    OpCode::Or,
    OpCode::Not,
    OpCode::AddInt,
    OpCode::AddNumber,
    OpCode::AddDecimal,
    OpCode::SubInt,
    OpCode::SubNumber,
    OpCode::SubDecimal,
    OpCode::MulInt,
    OpCode::MulNumber,
    OpCode::MulDecimal,
    OpCode::DivInt,
    OpCode::DivNumber,
    OpCode::DivDecimal,
    OpCode::ModInt,
    OpCode::NegInt,
    OpCode::NegNumber,
    OpCode::Jump,
    OpCode::JumpIfFalse,
    OpCode::JumpIfFalseTrusted,
    OpCode::JumpIfTrue,
    OpCode::Call,
    OpCode::Return,
    OpCode::ReturnValue,
    OpCode::CallValue,
    OpCode::CallClosure,
    OpCode::CallFunctionIndirect,
    OpCode::LoadLocal,
    OpCode::LoadLocalTrusted,
    OpCode::StoreLocal,
    OpCode::LoadModuleBinding,
    OpCode::StoreModuleBinding,
    OpCode::LoadClosure,
    OpCode::StoreClosure,
    OpCode::MakeClosure,
    OpCode::CloseUpvalue,
    OpCode::MakeRef,
    // γ-CP4 jit-makefieldref: `MakeFieldRef` (`&`/`&mut` into a typed-
    // object field) is JIT-compiled via the field-address path in
    // `mir_compiler::rvalues::Rvalue::Borrow`; `MakeIndexRef` is out of
    // the β1 `RefTarget` scope and clean-deopts to the interpreter. Both
    // produce correct results, so the parity matrix lists them supported.
    OpCode::MakeFieldRef,
    OpCode::MakeIndexRef,
    OpCode::DerefLoad,
    OpCode::DerefStore,
    OpCode::SetIndexRef,
    OpCode::NewArray,
    OpCode::NewTypedArray,
    OpCode::NewObject,
    OpCode::GetProp,
    OpCode::SetProp,
    OpCode::Length,
    OpCode::ArrayPush,
    OpCode::ArrayPop,
    OpCode::MergeObject,
    OpCode::SetLocalIndex,
    OpCode::SetModuleBindingIndex,
    OpCode::ArrayPushLocal,
    OpCode::LoopStart,
    OpCode::LoopEnd,
    OpCode::Break,
    OpCode::Continue,
    OpCode::IterNext,
    OpCode::IterDone,
    OpCode::CallMethod,
    OpCode::PushTimeframe,
    OpCode::PopTimeframe,
    OpCode::BuiltinCall,
    OpCode::TypeCheck,
    OpCode::Convert,
    OpCode::ModNumber,
    OpCode::ModDecimal,
    OpCode::PowInt,
    OpCode::PowNumber,
    OpCode::PowDecimal,
    OpCode::LteNumber,
    OpCode::LteDecimal,
    OpCode::SetupTry,
    OpCode::PopHandler,
    OpCode::Throw,
    OpCode::TryUnwrap,
    OpCode::UnwrapOption,
    OpCode::ErrorContext,
    OpCode::IsOk,
    OpCode::IsErr,
    OpCode::UnwrapOk,
    OpCode::UnwrapErr,
    OpCode::SliceAccess,
    OpCode::NullCoalesce,
    OpCode::MakeRange,
    OpCode::GetDataField,
    OpCode::GetDataRow,
    OpCode::GetFieldTyped,
    OpCode::SetFieldTyped,
    OpCode::NewTypedObject,
    OpCode::TypedMergeObject,
    OpCode::WrapTypeAnnotation,
    OpCode::Yield,
    OpCode::Suspend,
    OpCode::Resume,
    OpCode::Poll,
    OpCode::AwaitBar,
    OpCode::AwaitTick,
    OpCode::Await,
    OpCode::SpawnTask,
    OpCode::EmitAlert,
    OpCode::EmitEvent,
    OpCode::JoinInit,
    OpCode::JoinAwait,
    OpCode::CancelTask,
    OpCode::AsyncScopeEnter,
    OpCode::AsyncScopeExit,
    OpCode::LoadColF64,
    OpCode::LoadColI64,
    OpCode::LoadColBool,
    OpCode::LoadColStr,
    OpCode::BindSchema,
    OpCode::BoxTraitObject,
    OpCode::DynMethodCall,
    OpCode::Nop,
    OpCode::Halt,
    OpCode::IntToNumber,
    OpCode::NumberToInt,
    OpCode::CallForeign,
    OpCode::AddTyped,
    OpCode::SubTyped,
    OpCode::MulTyped,
    OpCode::DivTyped,
    OpCode::ModTyped,
    OpCode::CmpTyped,
    OpCode::StoreLocalTyped,
    OpCode::StoreModuleBindingTyped,
    OpCode::CastWidth,
    // v2 typed array opcodes
    OpCode::NewTypedArrayF64,
    OpCode::NewTypedArrayI64,
    OpCode::NewTypedArrayI32,
    OpCode::NewTypedArrayBool,
    OpCode::TypedArrayGetF64,
    OpCode::TypedArrayGetI64,
    OpCode::TypedArrayGetI32,
    OpCode::TypedArrayGetBool,
    OpCode::TypedArraySetF64,
    OpCode::TypedArraySetI64,
    OpCode::TypedArraySetI32,
    OpCode::TypedArraySetBool,
    OpCode::TypedArrayPushF64,
    OpCode::TypedArrayPushI64,
    OpCode::TypedArrayPushI32,
    OpCode::TypedArrayPushBool,
    OpCode::TypedArrayLen,
    // W12 S1 (2026-05-13) — sized-integer typed array opcodes (I8/U8/I16/U16/U32/U64).
    // The opcodes themselves are VM-dispatched today (`exec_v2_typed_array`);
    // the JIT registers them here to mark the parity matrix as supported
    // and to keep `build_full_opcode_parity_matrix` exhaustive.
    OpCode::NewTypedArrayI8,
    OpCode::TypedArrayGetI8,
    OpCode::TypedArrayPushI8,
    OpCode::TypedArraySetI8,
    OpCode::NewTypedArrayU8,
    OpCode::TypedArrayGetU8,
    OpCode::TypedArrayPushU8,
    OpCode::TypedArraySetU8,
    OpCode::NewTypedArrayI16,
    OpCode::TypedArrayGetI16,
    OpCode::TypedArrayPushI16,
    OpCode::TypedArraySetI16,
    OpCode::NewTypedArrayU16,
    OpCode::TypedArrayGetU16,
    OpCode::TypedArrayPushU16,
    OpCode::TypedArraySetU16,
    OpCode::NewTypedArrayU32,
    OpCode::TypedArrayGetU32,
    OpCode::TypedArrayPushU32,
    OpCode::TypedArraySetU32,
    // U64 typed-array opcodes intentionally NOT minted — deferred to
    // S1.5 per supervisor's S1 reopen (2026-05-13). See
    // crates/shape-vm/src/bytecode/opcode_defs.rs comment block.
    // Wave 2 Agent A1 (2026-05-14) — F32 + Char monomorphizations.
    // VM-dispatched today via `exec_v2_typed_array`; JIT registers them
    // in the parity matrix to keep `build_full_opcode_parity_matrix`
    // exhaustive. The JIT v2_array_new_func / v2_array_push_elem_size
    // helpers return None for these element kinds, so the JIT codegen
    // falls back to the legacy NaN-boxed path or the VM dispatcher.
    OpCode::NewTypedArrayF32,
    OpCode::TypedArrayGetF32,
    OpCode::TypedArrayPushF32,
    OpCode::TypedArraySetF32,
    OpCode::NewTypedArrayChar,
    OpCode::TypedArrayGetChar,
    OpCode::TypedArrayPushChar,
    OpCode::TypedArraySetChar,
];

const ALL_BUILTINS: &[BuiltinFunction] = &[
    // Math (18)
    BuiltinFunction::Abs,
    BuiltinFunction::Sqrt,
    BuiltinFunction::Ln,
    BuiltinFunction::Pow,
    BuiltinFunction::Exp,
    BuiltinFunction::Log,
    BuiltinFunction::Min,
    BuiltinFunction::Max,
    BuiltinFunction::Floor,
    BuiltinFunction::Ceil,
    BuiltinFunction::Round,
    BuiltinFunction::Sin,
    BuiltinFunction::Cos,
    BuiltinFunction::Tan,
    BuiltinFunction::Asin,
    BuiltinFunction::Acos,
    BuiltinFunction::Atan,
    BuiltinFunction::StdDev,
    // Array (8)
    BuiltinFunction::Range,
    BuiltinFunction::Slice,
    BuiltinFunction::Push,
    BuiltinFunction::Pop,
    BuiltinFunction::First,
    BuiltinFunction::Last,
    BuiltinFunction::Zip,
    BuiltinFunction::Filled,
    // HOF (8)
    BuiltinFunction::Map,
    BuiltinFunction::Filter,
    BuiltinFunction::Reduce,
    BuiltinFunction::ForEach,
    BuiltinFunction::Find,
    BuiltinFunction::FindIndex,
    BuiltinFunction::Some,
    BuiltinFunction::Every,
    // Utility (4)
    BuiltinFunction::Print,
    BuiltinFunction::Format,
    BuiltinFunction::Snapshot,
    BuiltinFunction::Exit,
    // Object (1)
    BuiltinFunction::ObjectRest,
    // Control (1)
    BuiltinFunction::ControlFold,
    // Type (7)
    BuiltinFunction::TypeOf,
    BuiltinFunction::IsNumber,
    BuiltinFunction::IsString,
    BuiltinFunction::IsBool,
    BuiltinFunction::IsArray,
    BuiltinFunction::IsObject,
    BuiltinFunction::IsDataRow,
    // Conversion (3)
    BuiltinFunction::ToString,
    BuiltinFunction::ToNumber,
    BuiltinFunction::ToBool,
    // Native ptr (8)
    BuiltinFunction::NativePtrSize,
    BuiltinFunction::NativePtrNewCell,
    BuiltinFunction::NativePtrFreeCell,
    BuiltinFunction::NativePtrReadPtr,
    BuiltinFunction::NativePtrWritePtr,
    BuiltinFunction::NativeTableFromArrowC,
    BuiltinFunction::NativeTableFromArrowCTyped,
    BuiltinFunction::NativeTableBindType,
    // Format (2)
    BuiltinFunction::FormatValueWithMeta,
    BuiltinFunction::FormatValueWithSpec,
    // R8 W4 W18.4 (supervisor 2026-05-24 D1 + (a-modified)
    // REVIVE-WITH-SHARED-MODULE): f-string content-lowering (3).
    // VM-dispatched today; registered here to keep
    // `build_full_opcode_parity_matrix` exhaustive.
    BuiltinFunction::FStringContentText,
    BuiltinFunction::FStringContentStyledText,
    BuiltinFunction::FStringContentFragment,
    // Math intrinsics (5)
    // W12-stdlib-intrinsic-collapse (Wave-2-Agent-G, 2026-05-14):
    // `IntrinsicSum` deleted — PHF `.sum()` is canonical (ADR-005 §1).
    BuiltinFunction::IntrinsicMean,
    BuiltinFunction::IntrinsicMin,
    BuiltinFunction::IntrinsicMax,
    BuiltinFunction::IntrinsicStd,
    BuiltinFunction::IntrinsicVariance,
    // Random (5)
    BuiltinFunction::IntrinsicRandom,
    BuiltinFunction::IntrinsicRandomInt,
    BuiltinFunction::IntrinsicRandomSeed,
    BuiltinFunction::IntrinsicRandomNormal,
    BuiltinFunction::IntrinsicRandomArray,
    // Distribution (5)
    BuiltinFunction::IntrinsicDistUniform,
    BuiltinFunction::IntrinsicDistLognormal,
    BuiltinFunction::IntrinsicDistExponential,
    BuiltinFunction::IntrinsicDistPoisson,
    BuiltinFunction::IntrinsicDistSampleN,
    // Stochastic (4)
    BuiltinFunction::IntrinsicBrownianMotion,
    BuiltinFunction::IntrinsicGbm,
    BuiltinFunction::IntrinsicOuProcess,
    BuiltinFunction::IntrinsicRandomWalk,
    // Rolling window (7)
    BuiltinFunction::IntrinsicRollingSum,
    BuiltinFunction::IntrinsicRollingMean,
    BuiltinFunction::IntrinsicRollingStd,
    BuiltinFunction::IntrinsicRollingMin,
    BuiltinFunction::IntrinsicRollingMax,
    BuiltinFunction::IntrinsicEma,
    BuiltinFunction::IntrinsicLinearRecurrence,
    // Series transform (7)
    BuiltinFunction::IntrinsicShift,
    BuiltinFunction::IntrinsicDiff,
    BuiltinFunction::IntrinsicPctChange,
    BuiltinFunction::IntrinsicFillna,
    BuiltinFunction::IntrinsicCumsum,
    BuiltinFunction::IntrinsicCumprod,
    BuiltinFunction::IntrinsicClip,
    // Statistics (4)
    BuiltinFunction::IntrinsicCorrelation,
    BuiltinFunction::IntrinsicCovariance,
    BuiltinFunction::IntrinsicPercentile,
    BuiltinFunction::IntrinsicMedian,
    // Trigonometric (4)
    BuiltinFunction::IntrinsicAtan2,
    BuiltinFunction::IntrinsicSinh,
    BuiltinFunction::IntrinsicCosh,
    BuiltinFunction::IntrinsicTanh,
    // Char codes (2)
    BuiltinFunction::IntrinsicCharCode,
    BuiltinFunction::IntrinsicFromCharCode,
    // Series (1)
    BuiltinFunction::IntrinsicSeries,
    // Vector intrinsics (12 — includes R5.4D IntrinsicVecAddI64)
    BuiltinFunction::IntrinsicVecAbs,
    BuiltinFunction::IntrinsicVecSqrt,
    BuiltinFunction::IntrinsicVecLn,
    BuiltinFunction::IntrinsicVecExp,
    BuiltinFunction::IntrinsicVecAdd,
    BuiltinFunction::IntrinsicVecSub,
    BuiltinFunction::IntrinsicVecMul,
    BuiltinFunction::IntrinsicVecDiv,
    BuiltinFunction::IntrinsicVecMax,
    BuiltinFunction::IntrinsicVecMin,
    BuiltinFunction::IntrinsicVecSelect,
    BuiltinFunction::IntrinsicVecAddI64,
    // Matrix (4 — includes R5.4D IntrinsicMatAdd / IntrinsicMatSub)
    BuiltinFunction::IntrinsicMatMulVec,
    BuiltinFunction::IntrinsicMatMulMat,
    BuiltinFunction::IntrinsicMatAdd,
    BuiltinFunction::IntrinsicMatSub,
    // Eval helpers (6)
    BuiltinFunction::EvalTimeRef,
    BuiltinFunction::EvalDateTimeExpr,
    BuiltinFunction::EvalDataDateTimeRef,
    BuiltinFunction::EvalDataSet,
    BuiltinFunction::EvalDataRelative,
    BuiltinFunction::EvalDataRelativeRange,
    // Option/Result ctors (3)
    BuiltinFunction::SomeCtor,
    BuiltinFunction::OkCtor,
    BuiltinFunction::ErrCtor,
    // Collection ctors (4)
    BuiltinFunction::HashMapCtor,
    BuiltinFunction::SetCtor,
    BuiltinFunction::DequeCtor,
    BuiltinFunction::PriorityQueueCtor,
    // JSON (5)
    BuiltinFunction::JsonObjectGet,
    BuiltinFunction::JsonArrayAt,
    BuiltinFunction::JsonObjectKeys,
    BuiltinFunction::JsonArrayLen,
    BuiltinFunction::JsonObjectLen,
    // Window functions (14)
    BuiltinFunction::WindowRowNumber,
    BuiltinFunction::WindowRank,
    BuiltinFunction::WindowDenseRank,
    BuiltinFunction::WindowNtile,
    BuiltinFunction::WindowLag,
    BuiltinFunction::WindowLead,
    BuiltinFunction::WindowFirstValue,
    BuiltinFunction::WindowLastValue,
    BuiltinFunction::WindowNthValue,
    BuiltinFunction::WindowSum,
    BuiltinFunction::WindowAvg,
    BuiltinFunction::WindowMin,
    BuiltinFunction::WindowMax,
    BuiltinFunction::WindowCount,
    // Join (1)
    BuiltinFunction::JoinExecute,
    // Reflection (1)
    BuiltinFunction::Reflect,
    // Content (6 constructors)
    BuiltinFunction::ContentChart,
    BuiltinFunction::ContentTextCtor,
    BuiltinFunction::ContentTableCtor,
    BuiltinFunction::ContentCodeCtor,
    BuiltinFunction::ContentKvCtor,
    BuiltinFunction::ContentFragmentCtor,
    // DateTime (6)
    BuiltinFunction::DateTimeNow,
    BuiltinFunction::DateTimeUtc,
    BuiltinFunction::DateTimeParse,
    BuiltinFunction::DateTimeFromEpoch,
    BuiltinFunction::DateTimeFromParts,
    BuiltinFunction::DateTimeFromUnixSecs,
    // Concurrency (4)
    BuiltinFunction::MutexCtor,
    BuiltinFunction::AtomicCtor,
    BuiltinFunction::LazyCtor,
    BuiltinFunction::ChannelCtor,
    // Math extras (7)
    BuiltinFunction::Sign,
    BuiltinFunction::Gcd,
    BuiltinFunction::Lcm,
    BuiltinFunction::Hypot,
    BuiltinFunction::Clamp,
    BuiltinFunction::IsNaN,
    BuiltinFunction::IsFinite,
    // Table construction
    BuiltinFunction::MakeTableFromRows,
    // W18.5 content builder ctors (3) — supervisor D4 (R8 W3, 2026-05-24).
    // VM-dispatched via builtins.rs; listed here to keep
    // `build_full_opcode_parity_matrix` exhaustive (the JIT trampoline
    // routes BuiltinCall instructions to the VM dispatch for these
    // identifiers).
    BuiltinFunction::TableBuilderNew,
    BuiltinFunction::CodeBuilderNew,
    BuiltinFunction::KeyValueBuilderNew,
];

fn vm_only_opcode_reason(opcode: OpCode) -> Option<&'static str> {
    // All opcodes are now compiled by the JIT translator — either natively
    // or via FFI trampoline calls to the VM runtime.  No interpreter
    // fallback is required.
    //
    // Track A.1D.2: `LoadOwnedMutableCapture` / `StoreOwnedMutableCapture`
    // are now compiled by MirToIR via the A.1D.2 side-table (see
    // `MirToIR::owned_mutable_capture_slots` and `register_owned_mutable_capture_slots`).
    // The MIR's plain `LoadLocal` / `StoreLocal` on capture param slots
    // are dispatched to pointer-deref `load.i64` / `store.i64` through
    // the `*mut ValueWord` cell bits stored in the slot. These opcodes
    // no longer force interpreter fallback.
    //
    // Track A.1E: `LoadSharedCapture` / `StoreSharedCapture` are now
    // compiled by MirToIR via the Shared-capture side-table (see
    // `MirToIR::shared_capture_slots`). The MIR's plain `LoadLocal` /
    // `StoreLocal` on capture param slots are dispatched to lock-gated
    // pointer-deref `load.i64` / `store.i64` through the
    // `*const SharedCell` pointer bits stored in the slot. The lock
    // fast path is a single CAS on the state byte at offset 0; slow
    // paths call `jit_shared_lock_contended` /
    // `jit_shared_unlock_contended`.
    //
    // Session 1 Commit 3: MirToIR now carries the infrastructure to
    // lower the outer-scope `var` lifecycle opcodes
    // (`AllocSharedLocal` / `LoadSharedLocal` / `StoreSharedLocal` /
    // `DropSharedLocal`) — see the `MirToIR::shared_local_slots`
    // side-table populated from `StoragePlan::slot_classes`, the
    // `initialize_shared_local_slots` helper that eagerly allocates
    // one `Arc<SharedCell>` per SharedCow slot at function entry,
    // the lock-gated `read_place` / `write_place` branches that
    // mirror the interpreter's `op_load_shared_local` /
    // `op_store_shared_local`, and the `emit_drop` branch that calls
    // `jit_arc_shared_release` on the slot's share.
    //
    // The full end-to-end lift of the preflight gate still exhibits
    // a cell-identity mismatch under the current JIT closure
    // dispatch pipeline — see `project_jit_closure_fix.md`'s
    // follow-up note. To keep the a1e gated e2e tests green (which
    // rely on the outer frame staying interpreted while the closure
    // body JIT-runs against the interpreter-allocated cell) the gate
    // remains in place for the four local opcodes.
    //
    // The infrastructure is wired and tested at the FFI + preflight
    // level so a follow-up commit can flip this match arm to `None`
    // once the outer-frame cell-identity handshake is resolved.
    //
    // The module-binding variants remain gated for the same reason
    // plus the per-module side-table requirement — their storage
    // lives outside the MIR slot space.
    //
    // WS-12 as-cast (v0.3 round-6, 2026-05-22): the `ConvertTo*` /
    // `TryConvertTo*` opcode family (`expr as int/number/string/bool/
    // decimal/char`) is NOT lowered by the JIT translator. The opcode-
    // FFI trampoline (`ffi/generic_builtin.rs::dispatch_opcode`) is a
    // deliberate pass-through stub — it returns the operand bits
    // unchanged, so a JIT'd `x as int` silently yields the unconverted
    // value (`true` instead of `1`, or a raw `Ptr(Option)` pointer
    // printed as garbage). That is a real VM≠JIT correctness divergence.
    // Until the per-kind typed convert opcode bodies land on the JIT
    // side, these opcodes are VM-only: the preflight gate routes any
    // program containing them to the bytecode interpreter via the
    // documented `[jit-fallback]` path (NOT silent-wrong-output). This
    // is surface-and-stop, not a dynamic-fallback shim — the JIT simply
    // does not implement these opcodes yet.
    match opcode {
        OpCode::AllocSharedModuleBinding
        | OpCode::LoadSharedModuleBinding
        | OpCode::StoreSharedModuleBinding => Some(
            "A.1C.3 outer-scope Shared module-binding opcode; Cranelift lowering pending",
        ),
        OpCode::ConvertToInt
        | OpCode::ConvertToNumber
        | OpCode::ConvertToString
        | OpCode::ConvertToBool
        | OpCode::ConvertToDecimal
        | OpCode::ConvertToChar
        | OpCode::TryConvertToInt
        | OpCode::TryConvertToNumber
        | OpCode::TryConvertToString
        | OpCode::TryConvertToBool
        | OpCode::TryConvertToDecimal
        | OpCode::TryConvertToChar => Some(
            "WS-12: ConvertTo*/TryConvertTo* (`as` cast) not lowered by the \
             JIT translator; VM-only until per-kind typed convert bodies land",
        ),
        _ => None,
    }
}

fn is_supported_builtin(_builtin: BuiltinFunction) -> bool {
    // All builtins are now supported — either via dedicated JIT lowering
    // or via the generic builtin FFI trampoline.
    true
}

/// Run JIT compatibility preflight on a raw instruction slice.
///
/// This is the shared core used by both `preflight_blob_jit_compatibility`
/// and `preflight_jit_compatibility`. It enables per-function JIT/interpreter
/// decisions in the mixed function table.
pub fn preflight_instructions(instructions: &[Instruction]) -> JitPreflightReport {
    let mut report = JitPreflightReport::default();

    for instr in instructions {
        if vm_only_opcode_reason(instr.opcode).is_some() {
            push_unique_opcode(&mut report.vm_only_opcodes, instr.opcode);
        }

        if instr.opcode == OpCode::BuiltinCall {
            if let Some(Operand::Builtin(builtin)) = instr.operand {
                if !is_supported_builtin(builtin) {
                    push_unique_builtin(&mut report.unsupported_builtins, builtin);
                }
            }
        }
    }

    sort_opcodes(&mut report.vm_only_opcodes);
    sort_builtins(&mut report.unsupported_builtins);
    report
}

/// Run JIT compatibility preflight on a single function blob.
///
/// Same logic as the whole-program preflight but operating on a single
/// `FunctionBlob`'s instruction stream. This enables per-function
/// JIT/interpreter decisions in the mixed function table.
pub fn preflight_blob_jit_compatibility(
    blob: &shape_vm::bytecode::FunctionBlob,
) -> JitPreflightReport {
    preflight_instructions(&blob.instructions)
}

/// Run JIT preflight and collect all constructs that require VM fallback.
pub fn preflight_jit_compatibility(program: &BytecodeProgram) -> JitPreflightReport {
    let mut report = JitPreflightReport::default();

    for instr in &program.instructions {
        if vm_only_opcode_reason(instr.opcode).is_some() {
            push_unique_opcode(&mut report.vm_only_opcodes, instr.opcode);
        }

        if instr.opcode == OpCode::BuiltinCall {
            if let Some(Operand::Builtin(builtin)) = instr.operand {
                if !is_supported_builtin(builtin) {
                    push_unique_builtin(&mut report.unsupported_builtins, builtin);
                }
            }
        }
    }

    sort_opcodes(&mut report.vm_only_opcodes);
    sort_builtins(&mut report.unsupported_builtins);
    report
}

/// Build a program-specific JIT parity matrix.
///
/// This is intended for diagnostics/CI tooling that wants an automatic
/// per-program support report.
pub fn build_program_parity_matrix(program: &BytecodeProgram) -> Vec<JitParityEntry> {
    let mut opcodes = Vec::new();
    let mut builtins = Vec::new();

    for instr in &program.instructions {
        push_unique_opcode(&mut opcodes, instr.opcode);
        if instr.opcode == OpCode::BuiltinCall {
            if let Some(Operand::Builtin(builtin)) = instr.operand {
                push_unique_builtin(&mut builtins, builtin);
            }
        }
    }

    sort_opcodes(&mut opcodes);
    sort_builtins(&mut builtins);

    let mut matrix = Vec::with_capacity(opcodes.len() + builtins.len());

    for opcode in opcodes {
        if let Some(reason) = vm_only_opcode_reason(opcode) {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Opcode(opcode),
                jit_supported: false,
                reason,
            });
        } else {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Opcode(opcode),
                jit_supported: true,
                reason: "Opcode is lowered by the JIT translator.",
            });
        }
    }

    for builtin in builtins {
        if is_supported_builtin(builtin) {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Builtin(builtin),
                jit_supported: true,
                reason: "Builtin is lowered by JIT builtin handlers.",
            });
        } else {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Builtin(builtin),
                jit_supported: false,
                reason: "Builtin is not lowered by JIT and must run on VM.",
            });
        }
    }

    matrix.sort_by_key(|entry| format!("{:?}", entry.target));
    matrix
}

/// Build a full opcode parity matrix across the entire VM opcode surface.
pub fn build_full_opcode_parity_matrix() -> Vec<JitParityEntry> {
    let mut matrix = Vec::with_capacity(ALL_OPCODES.len());
    for &opcode in ALL_OPCODES {
        if let Some(reason) = vm_only_opcode_reason(opcode) {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Opcode(opcode),
                jit_supported: false,
                reason,
            });
        } else {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Opcode(opcode),
                jit_supported: true,
                reason: "Opcode is lowered by the JIT translator.",
            });
        }
    }
    matrix.sort_by_key(|entry| format!("{:?}", entry.target));
    matrix
}

/// Build a full builtin parity matrix across the entire BuiltinFunction surface.
pub fn build_full_builtin_parity_matrix() -> Vec<JitParityEntry> {
    let mut matrix = Vec::with_capacity(ALL_BUILTINS.len());
    for &builtin in ALL_BUILTINS {
        if is_supported_builtin(builtin) {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Builtin(builtin),
                jit_supported: true,
                reason: "Builtin is lowered by JIT builtin handlers.",
            });
        } else {
            matrix.push(JitParityEntry {
                target: JitParityTarget::Builtin(builtin),
                jit_supported: false,
                reason: "Builtin is not lowered by JIT and must run on VM.",
            });
        }
    }
    matrix.sort_by_key(|entry| format!("{:?}", entry.target));
    matrix
}

/// Check if a bytecode program can be fully JIT-compiled
#[inline(always)]
pub fn can_jit_compile(program: &BytecodeProgram) -> bool {
    preflight_jit_compatibility(program).can_jit()
}

/// Get a list of unsupported opcodes in a program (for debugging)
#[inline(always)]
pub fn get_unsupported_opcodes(program: &BytecodeProgram) -> Vec<OpCode> {
    let report = preflight_jit_compatibility(program);
    let mut unsupported = report.vm_only_opcodes;

    if !report.unsupported_builtins.is_empty() && !unsupported.contains(&OpCode::BuiltinCall) {
        unsupported.push(OpCode::BuiltinCall);
    }

    sort_opcodes(&mut unsupported);
    unsupported
}

/// Get a list of opcodes that have placeholder (incomplete) implementations
pub fn get_incomplete_opcodes(_program: &BytecodeProgram) -> Vec<OpCode> {
    // All opcodes now have full implementations (native or FFI).
    Vec::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use shape_vm::bytecode::{Instruction, Operand};

    #[test]
    fn preflight_accepts_all_opcodes() {
        // All opcodes are now supported — no VM-only gates remain.
        let program = BytecodeProgram {
            instructions: vec![Instruction::simple(OpCode::Await)],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(report.can_jit());
    }

    #[test]
    fn preflight_accepts_all_builtins() {
        // All builtins are now supported — dedicated or generic trampoline.
        let program = BytecodeProgram {
            instructions: vec![Instruction::new(
                OpCode::BuiltinCall,
                Some(Operand::Builtin(BuiltinFunction::Snapshot)),
            )],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(report.can_jit());
    }

    #[test]
    fn parity_matrix_marks_all_builtins_supported() {
        let program = BytecodeProgram {
            instructions: vec![Instruction::new(
                OpCode::BuiltinCall,
                Some(Operand::Builtin(BuiltinFunction::Snapshot)),
            )],
            ..Default::default()
        };
        let matrix = build_program_parity_matrix(&program);
        assert!(matrix.iter().all(|row| row.jit_supported));
    }

    #[test]
    fn preflight_instructions_compatible_slice() {
        let instructions = vec![
            Instruction::simple(OpCode::PushConst),
            Instruction::simple(OpCode::AddInt),
            Instruction::simple(OpCode::ReturnValue),
        ];
        let report = preflight_instructions(&instructions);
        assert!(report.can_jit());
    }

    #[test]
    fn preflight_instructions_all_opcodes_pass() {
        // Even async opcodes now pass preflight.
        let instructions = vec![
            Instruction::simple(OpCode::PushConst),
            Instruction::simple(OpCode::Await),
            Instruction::simple(OpCode::ReturnValue),
        ];
        let report = preflight_instructions(&instructions);
        assert!(report.can_jit());
    }

    #[test]
    fn preflight_blob_passes_with_spawn_task() {
        use shape_vm::bytecode::FunctionBlob;

        let blob = FunctionBlob {
            content_hash: shape_vm::bytecode::FunctionHash::ZERO,
            name: "test_fn".to_string(),
            arity: 0,
            param_names: vec![],
            locals_count: 0,
            is_closure: false,
            captures_count: 0,
            is_async: false,
            ref_params: vec![],
            ref_mutates: vec![],
            mutable_captures: vec![],
            instructions: vec![
                Instruction::simple(OpCode::PushConst),
                Instruction::simple(OpCode::SpawnTask),
                Instruction::simple(OpCode::ReturnValue),
            ],
            constants: vec![],
            strings: vec![],
            required_permissions: Default::default(),
            dependencies: vec![],
            callee_names: vec![],
            type_schemas: vec![],
            source_map: vec![],
            foreign_dependencies: vec![],
            frame_descriptor: None,
        };

        let report = preflight_blob_jit_compatibility(&blob);
        assert!(report.can_jit());
    }

    #[test]
    fn all_opcodes_pass_preflight() {
        // Exhaustive check: every opcode in ALL_OPCODES must pass preflight.
        for &opcode in ALL_OPCODES {
            assert!(
                vm_only_opcode_reason(opcode).is_none(),
                "Opcode {:?} should pass preflight",
                opcode
            );
        }
    }

    #[test]
    fn all_builtins_pass_preflight() {
        // Exhaustive check: every builtin in ALL_BUILTINS must be supported.
        for &builtin in ALL_BUILTINS {
            assert!(
                is_supported_builtin(builtin),
                "Builtin {:?} should be supported",
                builtin
            );
        }
    }

    // Track A.1D.2 — OwnedMutable opcodes are now JIT-compiled via the
    // MIR-side `owned_mutable_capture_slots` side-table (see
    // `MirToIR::register_owned_mutable_capture_slots` +
    // `read_place`/`write_place` pointer-deref lowering). These tests
    // pin that the preflight gate accepts OwnedMutable opcodes while
    // keeping Shared opcodes gated.
    //
    // Previously (A.1C / A.1D partial) these tests asserted rejection of
    // LoadOwnedMutableCapture / StoreOwnedMutableCapture; A.1D.2 flips
    // them to assert acceptance, matching the lifted `vm_only_opcode_reason`
    // entry.

    #[test]
    fn a1d2_preflight_accepts_load_owned_mutable_capture() {
        let program = BytecodeProgram {
            instructions: vec![
                Instruction::new(OpCode::LoadOwnedMutableCapture, Some(Operand::Local(0))),
                Instruction::simple(OpCode::ReturnValue),
            ],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(
            report.can_jit(),
            "A.1D.2: LoadOwnedMutableCapture is now lowered by MirToIR; \
             preflight must accept it"
        );
        assert!(
            !report
                .vm_only_opcodes
                .contains(&OpCode::LoadOwnedMutableCapture),
            "A.1D.2 removes LoadOwnedMutableCapture from vm_only_opcode_reason"
        );
    }

    #[test]
    fn a1d2_preflight_accepts_store_owned_mutable_capture() {
        let program = BytecodeProgram {
            instructions: vec![
                Instruction::new(OpCode::StoreOwnedMutableCapture, Some(Operand::Local(0))),
                Instruction::simple(OpCode::ReturnValue),
            ],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(
            report.can_jit(),
            "A.1D.2: StoreOwnedMutableCapture is now lowered by MirToIR; \
             preflight must accept it"
        );
        assert!(
            !report
                .vm_only_opcodes
                .contains(&OpCode::StoreOwnedMutableCapture),
            "A.1D.2 removes StoreOwnedMutableCapture from vm_only_opcode_reason"
        );
    }

    // Track A.1E replaces the A.1C rejection tests for
    // `LoadSharedCapture` / `StoreSharedCapture` with acceptance
    // assertions on the lifted gate. The Cranelift inline parking_lot
    // fast path is now live — see `MirToIR::shared_capture_slots` and
    // the lock-gated pointer-deref in `read_place` / `write_place`.

    #[test]
    fn a1e_preflight_accepts_load_shared_capture() {
        let program = BytecodeProgram {
            instructions: vec![
                Instruction::new(OpCode::LoadSharedCapture, Some(Operand::Local(0))),
                Instruction::simple(OpCode::ReturnValue),
            ],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(
            report.can_jit(),
            "A.1E: LoadSharedCapture is now lowered by MirToIR; \
             preflight must accept it"
        );
        assert!(
            !report.vm_only_opcodes.contains(&OpCode::LoadSharedCapture),
            "A.1E removes LoadSharedCapture from vm_only_opcode_reason"
        );
    }

    #[test]
    fn a1e_preflight_accepts_store_shared_capture() {
        let program = BytecodeProgram {
            instructions: vec![
                Instruction::new(OpCode::StoreSharedCapture, Some(Operand::Local(0))),
                Instruction::simple(OpCode::ReturnValue),
            ],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(
            report.can_jit(),
            "A.1E: StoreSharedCapture is now lowered by MirToIR; \
             preflight must accept it"
        );
        assert!(
            !report.vm_only_opcodes.contains(&OpCode::StoreSharedCapture),
            "A.1E removes StoreSharedCapture from vm_only_opcode_reason"
        );
    }

    #[test]
    fn a1c_preflight_immutable_closure_body_still_jits() {
        // Closure bodies that DON'T contain the A.1B mutable-cell opcodes
        // should still JIT-compile — the A.1C gate is narrow.
        let program = BytecodeProgram {
            instructions: vec![
                Instruction::simple(OpCode::PushConst),
                Instruction::simple(OpCode::AddInt),
                Instruction::simple(OpCode::ReturnValue),
            ],
            ..Default::default()
        };
        let report = preflight_jit_compatibility(&program);
        assert!(report.can_jit());
    }

    // Track A.1E — A.1E lifts the capture-side Shared opcodes
    // (`Load/StoreSharedCapture`). The outer-scope `var`-lifecycle
    // opcodes remain gated pending follow-up work. This guard pins
    // exactly which opcodes are still interpreter-only after A.1E.

    #[test]
    fn cell_identity_preflight_accepts_outer_shared_local_opcodes() {
        // cell-identity #3: after the JIT/VM cell-identity handshake
        // fix, the outer-scope `var` lifecycle opcodes pass preflight.
        // MirToIR lowers them via `shared_local_slots` +
        // `initialize_shared_local_slots` + lock-gated
        // `read_place` / `write_place` / `emit_drop` (see
        // `mir_compiler/mod.rs`, `blocks.rs`, `places.rs`,
        // `ownership.rs`). The trampoline boundary preserves cell
        // identity by sharing the trampoline VM's stack slot through
        // `jit_shared_local_install` — see
        // `crates/shape-jit/src/ffi/object/closure.rs`.
        for op in [
            OpCode::AllocSharedLocal,
            OpCode::LoadSharedLocal,
            OpCode::StoreSharedLocal,
            OpCode::DropSharedLocal,
        ] {
            let program = BytecodeProgram {
                instructions: vec![
                    Instruction::new(op, Some(Operand::Local(0))),
                    Instruction::simple(OpCode::ReturnValue),
                ],
                ..Default::default()
            };
            let report = preflight_jit_compatibility(&program);
            assert!(
                report.can_jit(),
                "cell-identity: outer-scope Shared local opcode {:?} \
                 must pass preflight after the handshake fix",
                op
            );
            assert!(
                !report.vm_only_opcodes.contains(&op),
                "cell-identity: {:?} must be removed from vm_only_opcode_reason",
                op
            );
        }
    }

    #[test]
    fn session1_preflight_still_rejects_outer_shared_module_binding_opcodes() {
        // The module-binding counterparts remain gated — their
        // storage lives on a per-module side-table, not on a MIR slot,
        // and needs its own lowering (A.1C.3 follow-up). This guard
        // pins the exact set still rejected after Session 1 Commit 3.
        for op in [
            OpCode::AllocSharedModuleBinding,
            OpCode::LoadSharedModuleBinding,
            OpCode::StoreSharedModuleBinding,
        ] {
            let program = BytecodeProgram {
                instructions: vec![
                    Instruction::new(op, Some(Operand::Local(0))),
                    Instruction::simple(OpCode::ReturnValue),
                ],
                ..Default::default()
            };
            let report = preflight_jit_compatibility(&program);
            assert!(
                !report.can_jit(),
                "Outer-scope Shared module-binding opcode {:?} must \
                 remain preflight-rejected pending A.1C.3 JIT lowering",
                op
            );
        }
    }

    #[test]
    fn a1e_preflight_accepts_capture_side_shared_opcodes() {
        // Symmetric to the outer-scope rejection: the capture-side
        // opcodes `Load/StoreSharedCapture` DO pass preflight after
        // A.1E.
        for op in [OpCode::LoadSharedCapture, OpCode::StoreSharedCapture] {
            let program = BytecodeProgram {
                instructions: vec![
                    Instruction::new(op, Some(Operand::Local(0))),
                    Instruction::simple(OpCode::ReturnValue),
                ],
                ..Default::default()
            };
            let report = preflight_jit_compatibility(&program);
            assert!(
                report.can_jit(),
                "Capture-side Shared opcode {:?} must pass preflight after A.1E",
                op
            );
        }
    }

    #[test]
    fn ws12_preflight_rejects_convert_cast_opcodes() {
        // WS-12: the `ConvertTo*` / `TryConvertTo*` (`as` cast) opcode
        // family is not lowered by the JIT translator — the opcode-FFI
        // trampoline `dispatch_opcode` is a pass-through stub that
        // returns the operand unchanged, silently yielding the
        // unconverted value (`true` instead of `1`, a raw Ptr printed
        // as garbage). Preflight must reject any program containing one
        // so `--mode jit` cleanly falls back to the bytecode
        // interpreter rather than producing wrong output. This guard
        // pins the exact gated set.
        for op in [
            OpCode::ConvertToInt,
            OpCode::ConvertToNumber,
            OpCode::ConvertToString,
            OpCode::ConvertToBool,
            OpCode::ConvertToDecimal,
            OpCode::ConvertToChar,
            OpCode::TryConvertToInt,
            OpCode::TryConvertToNumber,
            OpCode::TryConvertToString,
            OpCode::TryConvertToBool,
            OpCode::TryConvertToDecimal,
            OpCode::TryConvertToChar,
        ] {
            let program = BytecodeProgram {
                instructions: vec![
                    Instruction::simple(op),
                    Instruction::simple(OpCode::ReturnValue),
                ],
                ..Default::default()
            };
            let report = preflight_jit_compatibility(&program);
            assert!(
                !report.can_jit(),
                "WS-12: cast opcode {:?} must be preflight-rejected \
                 (JIT translator does not lower it)",
                op
            );
            assert!(
                report.vm_only_opcodes.contains(&op),
                "WS-12: {:?} must appear in vm_only_opcodes",
                op
            );
        }
    }
}