Skip to main content

polkavm_common/
program.rs

1use crate::abi::{VM_CODE_ADDRESS_ALIGNMENT, VM_MAXIMUM_CODE_SIZE, VM_MAXIMUM_IMPORT_COUNT, VM_MAXIMUM_JUMP_TABLE_ENTRIES};
2use crate::cast::cast;
3use crate::utils::ArcBytes;
4use crate::varint::{read_simple_varint, read_varint, simple_varint_length, write_simple_varint_with_length, MAX_VARINT_LENGTH};
5use core::fmt::Write;
6use core::ops::Range;
7
8#[derive(Copy, Clone)]
9#[repr(transparent)]
10pub struct RawReg(u32);
11
12#[cfg(feature = "alloc")]
13use crate::abi::MemoryMapBuilder;
14
15impl Eq for RawReg {}
16impl PartialEq for RawReg {
17    fn eq(&self, rhs: &Self) -> bool {
18        self.get() == rhs.get()
19    }
20}
21
22#[cfg(feature = "arbitrary")]
23impl arbitrary::Arbitrary<'_> for RawReg {
24    fn arbitrary(unstructured: &mut arbitrary::Unstructured) -> Result<Self, arbitrary::Error> {
25        Reg::arbitrary(unstructured).map(|reg| reg.into())
26    }
27}
28
29impl RawReg {
30    #[inline]
31    pub const fn get(self) -> Reg {
32        let mut value = self.0 & 0b1111;
33        if value > 12 {
34            value = 12;
35        }
36
37        let Some(reg) = Reg::from_raw(value) else { unreachable!() };
38        reg
39    }
40
41    #[inline]
42    pub const fn raw_unparsed(self) -> u32 {
43        self.0
44    }
45}
46
47impl From<Reg> for RawReg {
48    fn from(reg: Reg) -> Self {
49        Self(reg as u32)
50    }
51}
52
53impl From<RawReg> for Reg {
54    fn from(reg: RawReg) -> Self {
55        reg.get()
56    }
57}
58
59impl core::fmt::Debug for RawReg {
60    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
61        write!(fmt, "{} (0x{:x})", self.get(), self.0)
62    }
63}
64
65impl core::fmt::Display for RawReg {
66    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
67        self.get().fmt(fmt)
68    }
69}
70
71#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
72#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
73#[repr(u32)]
74pub enum Reg {
75    RA = 0,
76    SP = 1,
77    T0 = 2,
78    T1 = 3,
79    T2 = 4,
80    S0 = 5,
81    S1 = 6,
82    A0 = 7,
83    A1 = 8,
84    A2 = 9,
85    A3 = 10,
86    A4 = 11,
87    A5 = 12,
88}
89
90impl Reg {
91    #[inline]
92    pub const fn to_usize(self) -> usize {
93        self as usize
94    }
95
96    #[inline]
97    pub const fn to_u32(self) -> u32 {
98        self as u32
99    }
100
101    #[inline]
102    pub const fn raw(self) -> RawReg {
103        RawReg(self as u32)
104    }
105
106    #[inline]
107    pub const fn from_raw(value: u32) -> Option<Reg> {
108        Some(match value {
109            0 => Reg::RA,
110            1 => Reg::SP,
111            2 => Reg::T0,
112            3 => Reg::T1,
113            4 => Reg::T2,
114            5 => Reg::S0,
115            6 => Reg::S1,
116            7 => Reg::A0,
117            8 => Reg::A1,
118            9 => Reg::A2,
119            10 => Reg::A3,
120            11 => Reg::A4,
121            12 => Reg::A5,
122            _ => return None,
123        })
124    }
125
126    pub const fn name(self) -> &'static str {
127        use Reg::*;
128        match self {
129            RA => "ra",
130            SP => "sp",
131            T0 => "t0",
132            T1 => "t1",
133            T2 => "t2",
134            S0 => "s0",
135            S1 => "s1",
136            A0 => "a0",
137            A1 => "a1",
138            A2 => "a2",
139            A3 => "a3",
140            A4 => "a4",
141            A5 => "a5",
142        }
143    }
144
145    pub const fn name_non_abi(self) -> &'static str {
146        use Reg::*;
147        match self {
148            RA => "r0",
149            SP => "r1",
150            T0 => "r2",
151            T1 => "r3",
152            T2 => "r4",
153            S0 => "r5",
154            S1 => "r6",
155            A0 => "r7",
156            A1 => "r8",
157            A2 => "r9",
158            A3 => "r10",
159            A4 => "r11",
160            A5 => "r12",
161        }
162    }
163
164    /// List of all of the VM's registers.
165    pub const ALL: [Reg; 13] = {
166        use Reg::*;
167        [RA, SP, T0, T1, T2, S0, S1, A0, A1, A2, A3, A4, A5]
168    };
169
170    /// List of all input/output argument registers.
171    pub const ARG_REGS: [Reg; 9] = [Reg::A0, Reg::A1, Reg::A2, Reg::A3, Reg::A4, Reg::A5, Reg::T0, Reg::T1, Reg::T2];
172
173    pub const MAXIMUM_INPUT_REGS: usize = 9;
174    pub const MAXIMUM_OUTPUT_REGS: usize = 2;
175}
176
177impl core::fmt::Display for Reg {
178    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
179        fmt.write_str(self.name())
180    }
181}
182
183#[inline(never)]
184#[cold]
185fn find_next_offset_legacy_unbounded(bitmask: &[u8], code_len: u32, mut offset: u32) -> u32 {
186    while let Some(&byte) = bitmask.get(offset as usize >> 3) {
187        let shift = offset & 7;
188        let mask = byte >> shift;
189        if mask == 0 {
190            offset += 8 - shift;
191        } else {
192            offset += mask.trailing_zeros();
193            break;
194        }
195    }
196
197    core::cmp::min(code_len, offset)
198}
199
200#[inline(never)]
201fn visitor_step_slow_legacy<T>(
202    state: &mut <T as OpcodeVisitor>::State,
203    code: &[u8],
204    bitmask: &[u8],
205    offset: u32,
206    opcode_visitor: T,
207) -> (u32, <T as OpcodeVisitor>::ReturnTy, bool)
208where
209    T: OpcodeVisitor,
210{
211    if offset as usize >= code.len() {
212        return (offset + 1, visitor_step_invalid_instruction(state, offset, 1, opcode_visitor), true);
213    }
214
215    debug_assert!(code.len() <= u32::MAX as usize);
216    debug_assert_eq!(bitmask.len(), code.len().div_ceil(8));
217    debug_assert!(offset as usize <= code.len());
218    debug_assert!(get_bit_for_offset(bitmask, code.len(), offset), "bit at {offset} is zero");
219
220    let (skip, mut is_next_instruction_invalid) = parse_bitmask_slow(bitmask, code.len(), offset);
221    let chunk = load_chunk(code, offset as usize);
222    let opcode = chunk as u8;
223
224    if is_next_instruction_invalid && offset as usize + skip as usize + 1 >= code.len() {
225        // This is the last instruction.
226        if !opcode_visitor
227            .instruction_set()
228            .opcode_from_raw(u32::from(opcode))
229            .unwrap_or(Opcode::trap)
230            .can_fallthrough()
231        {
232            // We can't fallthrough, so there's no need to inject a trap after this instruction.
233            is_next_instruction_invalid = false;
234        }
235    }
236
237    (
238        offset + skip + 1,
239        opcode_visitor.dispatch(state, usize::from(opcode), chunk, offset, skip + 1),
240        is_next_instruction_invalid,
241    )
242}
243
244#[cfg_attr(not(debug_assertions), inline(always))]
245fn visitor_step_fast_legacy<T>(
246    state: &mut <T as OpcodeVisitor>::State,
247    code: &[u8],
248    bitmask: &[u8],
249    offset: u32,
250    opcode_visitor: T,
251) -> (u32, <T as OpcodeVisitor>::ReturnTy, bool)
252where
253    T: OpcodeVisitor,
254{
255    debug_assert!(code.len() <= u32::MAX as usize);
256    debug_assert_eq!(bitmask.len(), code.len().div_ceil(8));
257    debug_assert!(offset as usize <= code.len());
258    debug_assert!(get_bit_for_offset(bitmask, code.len(), offset), "bit at {offset} is zero");
259    debug_assert!(offset as usize + 32 <= code.len());
260
261    let Some(skip) = parse_bitmask_fast(bitmask, offset) else {
262        unreachable!()
263    };
264
265    let chunk = load_chunk(code, offset as usize);
266    let opcode = usize::from(chunk as u8);
267
268    debug_assert!(skip <= BITMASK_MAX);
269    let result = opcode_visitor.dispatch(state, opcode, chunk, offset, skip + 1);
270
271    let next_offset = offset + skip + 1;
272    let is_next_instruction_invalid = skip == 24 && !get_bit_for_offset(bitmask, code.len(), next_offset);
273    (next_offset, result, is_next_instruction_invalid)
274}
275
276#[cfg_attr(not(debug_assertions), inline(always))]
277#[cold]
278fn visitor_step_invalid_instruction<T>(state: &mut <T as OpcodeVisitor>::State, offset: u32, length: u32, opcode_visitor: T) -> T::ReturnTy
279where
280    T: OpcodeVisitor,
281{
282    opcode_visitor.dispatch(state, LEGACY_INVALID_RAW_OPCODE as usize, 0, offset, length)
283}
284
285#[cfg_attr(not(debug_assertions), inline(always))]
286fn visitor_step_runner_legacy<T, const FAST_PATH: bool>(
287    state: &mut <T as OpcodeVisitor>::State,
288    code: &[u8],
289    bitmask: &[u8],
290    mut offset: u32,
291    opcode_visitor: T,
292) -> u32
293where
294    T: OpcodeVisitor<ReturnTy = ()>,
295{
296    let (next_offset, (), is_next_instruction_invalid) = if FAST_PATH {
297        visitor_step_fast_legacy(state, code, bitmask, offset, opcode_visitor)
298    } else {
299        visitor_step_slow_legacy(state, code, bitmask, offset, opcode_visitor)
300    };
301
302    offset = next_offset;
303    if is_next_instruction_invalid {
304        // The invalid instruction covers everything up until the next real instruction.
305        let next_offset = if (offset as usize) < code.len() {
306            let next_offset = find_next_offset_legacy_unbounded(bitmask, code.len() as u32, offset);
307            debug_assert!(next_offset > offset);
308            next_offset
309        } else {
310            offset
311        };
312
313        visitor_step_invalid_instruction(state, offset, next_offset - offset, opcode_visitor);
314        offset = next_offset;
315    }
316
317    offset
318}
319
320#[cfg_attr(not(debug_assertions), inline(always))]
321fn visitor_run<T>(state: &mut <T as OpcodeVisitor>::State, blob: &ProgramBlob, opcode_visitor: T)
322where
323    T: OpcodeVisitor<ReturnTy = ()>,
324{
325    if opcode_visitor.instruction_set().is_legacy() {
326        visitor_run_legacy(state, blob.code(), blob.bitmask(), opcode_visitor)
327    } else {
328        visitor_run_extended(state, blob.code(), opcode_visitor)
329    }
330}
331
332// Having this be never inlined makes it easier to analyze the resulting assembly/machine code,
333// and it also seems to make the code mariginally faster for some reason.
334#[inline(never)]
335fn visitor_run_legacy<T>(state: &mut <T as OpcodeVisitor>::State, code: &[u8], bitmask: &[u8], opcode_visitor: T)
336where
337    T: OpcodeVisitor<ReturnTy = ()>,
338{
339    let mut offset = 0;
340    if !get_bit_for_offset(bitmask, code.len(), 0) {
341        offset = find_next_offset_legacy_unbounded(bitmask, code.len() as u32, 0);
342        visitor_step_invalid_instruction(state, 0, offset, opcode_visitor);
343    }
344
345    while cast(offset).to_usize() + 32 <= code.len() {
346        offset = visitor_step_runner_legacy::<T, true>(state, code, bitmask, offset, opcode_visitor);
347    }
348
349    while cast(offset).to_usize() < code.len() {
350        offset = visitor_step_runner_legacy::<T, false>(state, code, bitmask, offset, opcode_visitor);
351    }
352}
353
354#[inline(never)]
355fn visitor_run_extended<T>(state: &mut <T as OpcodeVisitor>::State, code: &[u8], opcode_visitor: T)
356where
357    T: OpcodeVisitor<ReturnTy = ()>,
358{
359    let table = opcode_visitor.instruction_set().raw_opcode_table();
360    let mut offset: usize = 0;
361
362    if code.len() >= CODE_BLOCK_SIZE {
363        offset = visitor_run_extended_full_blocks::<T>(state, code, opcode_visitor, table);
364    }
365
366    if offset < code.len() {
367        offset = visitor_run_extended_last_block::<T>(state, code, opcode_visitor, table, offset);
368    }
369
370    debug_assert_eq!(offset, code.len());
371}
372
373#[must_use]
374#[inline(never)]
375fn visitor_run_extended_full_blocks<T>(
376    state: &mut <T as OpcodeVisitor>::State,
377    code: &[u8],
378    opcode_visitor: T,
379    table: &'static RawOpcodeTable,
380) -> usize
381where
382    T: OpcodeVisitor<ReturnTy = ()>,
383{
384    let loop_boundary = (code.len() / CODE_BLOCK_SIZE) * CODE_BLOCK_SIZE;
385    let mut offset = 0;
386    while offset < loop_boundary {
387        debug_assert!(is_on_a_block_boundary(offset));
388
389        let block_boundary = offset + CODE_BLOCK_SIZE;
390        while offset < block_boundary {
391            offset = visitor_step_extended::<T>(state, code, offset, block_boundary, opcode_visitor, table);
392        }
393
394        debug_assert_eq!(offset, block_boundary);
395    }
396
397    offset
398}
399
400#[must_use]
401#[inline(never)]
402fn visitor_run_extended_last_block<T>(
403    state: &mut <T as OpcodeVisitor>::State,
404    code: &[u8],
405    opcode_visitor: T,
406    table: &'static RawOpcodeTable,
407    mut offset: usize,
408) -> usize
409where
410    T: OpcodeVisitor<ReturnTy = ()>,
411{
412    debug_assert!(is_on_a_block_boundary(offset));
413    debug_assert!(code.len() - offset < CODE_BLOCK_SIZE);
414
415    let block_boundary = code.len();
416    let bulk_boundary = (code.len() / 16) * 16;
417    while offset < bulk_boundary {
418        // Fast path.
419        offset = visitor_step_extended::<T>(state, code, offset, block_boundary, opcode_visitor, table);
420    }
421
422    while offset < code.len() {
423        // Slow path.
424        offset = visitor_step_extended::<T>(state, code, offset, block_boundary, opcode_visitor, table);
425    }
426
427    offset
428}
429
430#[cfg_attr(not(debug_assertions), inline(always))]
431fn load_chunk(code: &[u8], offset: usize) -> u128 {
432    let chunk = code.get(offset..offset + 16);
433    if let Some(chunk) = chunk {
434        // NOTE: This should produce the same assembly as the unsafe `read_unaligned`.
435        u128::from_le_bytes([
436            chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7], chunk[8], chunk[9], chunk[10], chunk[11],
437            chunk[12], chunk[13], chunk[14], chunk[15],
438        ])
439    } else {
440        let code = &code[core::cmp::min(offset, code.len())..];
441        let mut t: [u8; 16] = [0; 16];
442        t[..code.len()].copy_from_slice(code);
443        u128::from_le_bytes([
444            t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15],
445        ])
446    }
447}
448
449#[cfg_attr(not(debug_assertions), inline(always))]
450fn extract_opcode(chunk: u32) -> u32 {
451    let raw_opcode = chunk & 0xffff;
452    let mut opcode = raw_opcode & 0xff;
453    if opcode == u32::from(EXTENDED_OPCODE_PREFIX) {
454        opcode += raw_opcode >> 8;
455    }
456
457    opcode
458}
459
460#[cfg_attr(not(debug_assertions), inline(always))]
461fn visitor_step_extended<T>(
462    state: &mut <T as OpcodeVisitor>::State,
463    code: &[u8],
464    offset: usize,
465    block_boundary: usize,
466    opcode_visitor: T,
467    table: &'static RawOpcodeTable,
468) -> usize
469where
470    T: OpcodeVisitor<ReturnTy = ()>,
471{
472    let ((), next_offset) = parse_raw_extended(code, offset, block_boundary, table, move |raw_opcode, chunk, offset, length| {
473        debug_assert!(offset + cast(length).to_usize() <= block_boundary);
474        opcode_visitor.dispatch(
475            state,
476            cast(raw_opcode).to_usize(),
477            chunk,
478            cast(offset).to_u32_or_debug_panic(),
479            length,
480        );
481    });
482
483    next_offset
484}
485
486#[cfg_attr(not(debug_assertions), inline(always))]
487fn parse_raw_extended<F, R>(code: &[u8], offset: usize, block_boundary: usize, table: &'static RawOpcodeTable, callback: F) -> (R, usize)
488where
489    F: FnOnce(u32, u128, usize, u32) -> R,
490{
491    debug_assert!(code.len() <= u32::MAX as usize);
492    debug_assert!(offset <= code.len());
493
494    let chunk: u128 = load_chunk(code, offset);
495    let mut raw_opcode = extract_opcode(chunk as u32);
496    let Some(length) = table.length_table.get(cast(raw_opcode).to_usize()) else {
497        unreachable!();
498    };
499
500    let mut length = length.get();
501    let mut next_offset = offset + cast(length).to_usize();
502    if next_offset >= block_boundary {
503        // The last instruction of a macro block has to fit in it and has to end a basic block, otherwise it becomes a trap.
504        if next_offset > block_boundary || !table.ends_basic_block(cast(raw_opcode).to_usize()) {
505            raw_opcode = cast(EXTENDED_INVALID_RAW_OPCODE).to_u32_or_debug_panic();
506        }
507
508        length = cast(block_boundary - offset).to_u32_or_debug_panic();
509        next_offset = block_boundary;
510    }
511
512    let result = callback(raw_opcode, chunk, offset, length);
513    debug_assert!(next_offset > offset);
514    (result, next_offset)
515}
516
517#[derive(Copy, Clone, Debug)]
518struct ExtendedStep {
519    raw_opcode: usize,
520    next_offset: usize,
521    #[allow(dead_code)]
522    length: u32,
523}
524
525#[cfg_attr(not(debug_assertions), inline(always))]
526fn parse_simple_extended<I>(instruction_set: I, code: &[u8], offset: usize) -> ExtendedStep
527where
528    I: InstructionSet,
529{
530    let ((raw_opcode, length), next_offset) = parse_raw_extended(
531        code,
532        offset,
533        end_of_macro_block(offset, code.len()),
534        instruction_set.raw_opcode_table(),
535        |raw_opcode, _, _, length| (raw_opcode, length),
536    );
537
538    ExtendedStep {
539        raw_opcode: cast(raw_opcode).to_usize(),
540        next_offset,
541        length,
542    }
543}
544
545#[inline(always)]
546fn sign_extend_at(value: u32, bits_to_cut: u32) -> u32 {
547    (((u64::from(value) << bits_to_cut) as u32 as i32).wrapping_shr(bits_to_cut)) as u32
548}
549
550type LookupEntry = u32;
551const EMPTY_LOOKUP_ENTRY: LookupEntry = 0;
552
553#[repr(transparent)]
554struct LookupTable([LookupEntry; 256]);
555
556impl LookupTable {
557    const fn pack(imm1_bits: u32, imm1_skip: u32, imm2_bits: u32) -> LookupEntry {
558        assert!(imm1_bits <= 0b111111);
559        assert!(imm2_bits <= 0b111111);
560        assert!(imm1_skip <= 0b111111);
561        (imm1_bits) | ((imm1_skip) << 6) | ((imm2_bits) << 12)
562    }
563
564    #[inline(always)]
565    fn unpack(entry: LookupEntry) -> (u32, u32, u32) {
566        (entry & 0b111111, (entry >> 6) & 0b111111, (entry >> 12) & 0b111111)
567    }
568
569    const fn build(offset: i32) -> Self {
570        const fn min_u32(a: u32, b: u32) -> u32 {
571            if a < b {
572                a
573            } else {
574                b
575            }
576        }
577
578        const fn clamp_i32(range: core::ops::RangeInclusive<i32>, value: i32) -> i32 {
579            if value < *range.start() {
580                *range.start()
581            } else if value > *range.end() {
582                *range.end()
583            } else {
584                value
585            }
586        }
587
588        const fn sign_extend_cutoff_for_length(length: u32) -> u32 {
589            match length {
590                0 => 32,
591                1 => 24,
592                2 => 16,
593                3 => 8,
594                4 => 0,
595                _ => unreachable!(),
596            }
597        }
598
599        let mut output = [EMPTY_LOOKUP_ENTRY; 256];
600        let mut skip = 0;
601        while skip <= 0b11111 {
602            let mut aux = 0;
603            while aux <= 0b111 {
604                let imm1_length = min_u32(4, aux);
605                let imm2_length = clamp_i32(0..=4, skip as i32 - imm1_length as i32 - offset) as u32;
606                let imm1_bits = sign_extend_cutoff_for_length(imm1_length);
607                let imm2_bits = sign_extend_cutoff_for_length(imm2_length);
608                let imm1_skip = imm1_length * 8;
609
610                let index = Self::get_lookup_index(skip, aux);
611                output[index as usize] = Self::pack(imm1_bits, imm1_skip, imm2_bits);
612                aux += 1;
613            }
614            skip += 1;
615        }
616
617        LookupTable(output)
618    }
619
620    #[inline(always)]
621    const fn get_lookup_index(skip: u32, aux: u32) -> u32 {
622        debug_assert!(skip <= 0b11111);
623        let skip = skip & 0b11111;
624        let index = skip | ((aux & 0b111) << 5);
625        debug_assert!(index <= 0xff);
626        index
627    }
628
629    #[inline(always)]
630    fn get(&self, skip: u32, aux: u32) -> (u32, u32, u32) {
631        let index = Self::get_lookup_index(skip, aux);
632        debug_assert!((index as usize) < self.0.len());
633
634        #[allow(unsafe_code)]
635        // SAFETY: `index` is composed of a 5-bit `skip` and 3-bit `aux`,
636        // which gives us 8 bits in total, and the table's length is 256,
637        // so out of bounds access in impossible.
638        Self::unpack(*unsafe { self.0.get_unchecked(index as usize) })
639    }
640}
641
642/// The size in bytes of an interpreter cache entry for the cache size limit, the same on every target.
643pub const INTERPRETER_CACHE_ENTRY_SIZE: u32 = 24;
644
645pub const INTERPRETER_FLATMAP_ENTRY_SIZE: u32 = 4;
646
647pub fn interpreter_calculate_cache_size(count: usize) -> usize {
648    count * INTERPRETER_CACHE_ENTRY_SIZE as usize
649}
650
651pub fn interpreter_calculate_cache_num_entries(bytes: usize) -> usize {
652    bytes / INTERPRETER_CACHE_ENTRY_SIZE as usize
653}
654
655static TABLE_2: LookupTable = LookupTable::build(2);
656static TABLE_3: LookupTable = LookupTable::build(3);
657static TABLE_4: LookupTable = LookupTable::build(4);
658
659#[inline(always)]
660fn fixup_length<const EXT: bool>(length: u32) -> u32 {
661    if EXT {
662        length - 2
663    } else {
664        length - 1
665    }
666}
667
668#[inline(always)]
669const fn fixup_shift<const EXT: bool>() -> u32 {
670    if EXT {
671        16
672    } else {
673        8
674    }
675}
676
677#[inline(always)]
678fn chunk_into_u64<const EXT: bool, const EXTRA_SHIFT: u32>(chunk: u128) -> u64 {
679    let shift = const { fixup_shift::<EXT>() + EXTRA_SHIFT };
680    (chunk >> shift) as u64
681}
682
683#[inline(always)]
684fn chunk_into_u32<const EXT: bool, const EXTRA_SHIFT: u32>(chunk: u128) -> u32 {
685    let shift = const {
686        let shift = fixup_shift::<EXT>() + EXTRA_SHIFT;
687        assert!(shift <= 32);
688        shift
689    };
690    ((chunk as u64) >> shift) as u32
691}
692
693#[inline(always)]
694fn fixup_chunk64<const EXT: bool>(chunk: u128) -> u64 {
695    (chunk as u64) >> fixup_shift::<EXT>()
696}
697
698#[inline(always)]
699const fn fixup_table_1<const EXT: bool>() -> &'static LookupTable {
700    if EXT {
701        &TABLE_3
702    } else {
703        &TABLE_2
704    }
705}
706
707#[inline(always)]
708const fn fixup_table_2<const EXT: bool>() -> &'static LookupTable {
709    if EXT {
710        &TABLE_4
711    } else {
712        &TABLE_3
713    }
714}
715
716#[doc(hidden)]
717#[inline(always)]
718pub fn read_args_imm<const EXT: bool>(chunk: u128, length: u32) -> i32 {
719    let length = fixup_length::<EXT>(length);
720    let chunk = chunk_into_u32::<EXT, 0>(chunk);
721    cast(read_simple_varint(chunk, length)).bitwise_as_i32()
722}
723
724#[doc(hidden)]
725#[inline(always)]
726pub fn read_args_offset<const EXT: bool>(chunk: u128, instruction_offset: u32, length: u32) -> u32 {
727    instruction_offset.wrapping_add(cast(read_args_imm::<EXT>(chunk, length)).bitwise_as_u32())
728}
729
730#[doc(hidden)]
731#[inline(always)]
732pub fn read_args_imm2<const EXT: bool>(chunk: u128, length: u32) -> (i32, i32) {
733    let (imm1_bits, imm1_skip, imm2_bits) = fixup_table_1::<EXT>().get(length, chunk_into_u32::<EXT, 0>(chunk));
734    let chunk = chunk_into_u64::<EXT, 8>(chunk);
735    let imm1 = sign_extend_at(chunk as u32, imm1_bits);
736    let chunk = chunk >> imm1_skip;
737    let imm2 = sign_extend_at(chunk as u32, imm2_bits);
738    (cast(imm1).bitwise_as_i32(), cast(imm2).bitwise_as_i32())
739}
740
741#[doc(hidden)]
742#[inline(always)]
743pub fn read_args_reg_imm<const EXT: bool>(chunk: u128, length: u32) -> (RawReg, i32) {
744    let chunk = fixup_chunk64::<EXT>(chunk);
745    let reg = RawReg(chunk as u32);
746    let chunk = chunk >> 8;
747    let (_, _, imm_bits) = fixup_table_1::<EXT>().get(length, 0);
748    let imm = sign_extend_at(chunk as u32, imm_bits);
749    (reg, cast(imm).bitwise_as_i32())
750}
751
752#[doc(hidden)]
753#[inline(always)]
754pub fn read_args_reg_imm2<const EXT: bool>(chunk: u128, length: u32) -> (RawReg, i32, i32) {
755    let reg = RawReg(chunk_into_u32::<EXT, 0>(chunk));
756    let (imm1_bits, imm1_skip, imm2_bits) = fixup_table_1::<EXT>().get(length, chunk_into_u32::<EXT, 4>(chunk));
757    let chunk = chunk_into_u64::<EXT, 8>(chunk);
758    let imm1 = sign_extend_at(chunk as u32, imm1_bits);
759    let chunk = chunk >> imm1_skip;
760    let imm2 = sign_extend_at(chunk as u32, imm2_bits);
761    (reg, cast(imm1).bitwise_as_i32(), cast(imm2).bitwise_as_i32())
762}
763
764#[doc(hidden)]
765#[inline(always)]
766pub fn read_args_reg_imm_offset<const EXT: bool>(chunk: u128, instruction_offset: u32, length: u32) -> (RawReg, i32, u32) {
767    let (reg, imm1, imm2) = read_args_reg_imm2::<EXT>(chunk, length);
768    let imm2 = instruction_offset.wrapping_add(cast(imm2).bitwise_as_u32());
769    (reg, imm1, imm2)
770}
771
772#[doc(hidden)]
773#[inline(always)]
774pub fn read_args_regs2_imm2<const EXT: bool>(chunk: u128, length: u32) -> (RawReg, RawReg, i32, i32) {
775    let (reg1, reg2, imm1_aux) = {
776        let value = chunk_into_u32::<EXT, 0>(chunk);
777        (RawReg(value), RawReg(value >> 4), value >> 8)
778    };
779
780    let (imm1_bits, imm1_skip, imm2_bits) = fixup_table_2::<EXT>().get(length, imm1_aux);
781    let chunk = chunk_into_u64::<EXT, 16>(chunk);
782    let imm1 = sign_extend_at(chunk as u32, imm1_bits);
783    let chunk = chunk >> imm1_skip;
784    let imm2 = sign_extend_at(chunk as u32, imm2_bits);
785    (reg1, reg2, cast(imm1).bitwise_as_i32(), cast(imm2).bitwise_as_i32())
786}
787
788#[doc(hidden)]
789#[inline(always)]
790pub fn read_args_reg_imm64<const EXT: bool>(chunk: u128) -> (RawReg, u64) {
791    let reg = RawReg(chunk_into_u32::<EXT, 0>(chunk));
792    let imm = chunk_into_u64::<EXT, 8>(chunk);
793    (reg, imm)
794}
795
796#[doc(hidden)]
797#[inline(always)]
798pub fn read_args_regs2_imm<const EXT: bool>(chunk: u128, length: u32) -> (RawReg, RawReg, i32) {
799    let chunk = fixup_chunk64::<EXT>(chunk);
800    let (reg1, reg2) = {
801        let value = chunk as u32;
802        (RawReg(value), RawReg(value >> 4))
803    };
804    let chunk = chunk >> 8;
805    let (_, _, imm_bits) = fixup_table_1::<EXT>().get(length, 0);
806    let imm = sign_extend_at(chunk as u32, imm_bits);
807    (reg1, reg2, cast(imm).bitwise_as_i32())
808}
809
810#[doc(hidden)]
811#[inline(always)]
812pub fn read_args_regs2_offset<const EXT: bool>(chunk: u128, instruction_offset: u32, length: u32) -> (RawReg, RawReg, u32) {
813    let (reg1, reg2, imm) = read_args_regs2_imm::<EXT>(chunk, length);
814    let imm = instruction_offset.wrapping_add(cast(imm).bitwise_as_u32());
815    (reg1, reg2, imm)
816}
817
818#[doc(hidden)]
819#[inline(always)]
820pub fn read_args_regs3<const EXT: bool>(chunk: u128) -> (RawReg, RawReg, RawReg) {
821    let chunk = chunk_into_u32::<EXT, 0>(chunk);
822    let (reg2, reg3, reg1) = (RawReg(chunk), RawReg(chunk >> 4), RawReg(chunk >> 8));
823    (reg1, reg2, reg3)
824}
825
826#[doc(hidden)]
827#[inline(always)]
828pub fn read_args_regs2<const EXT: bool>(chunk: u128) -> (RawReg, RawReg) {
829    let chunk = chunk_into_u32::<EXT, 0>(chunk);
830    let (reg1, reg2) = (RawReg(chunk), RawReg(chunk >> 4));
831    (reg1, reg2)
832}
833
834#[cfg(kani)]
835mod kani {
836    use crate::cast::cast;
837    use core::cmp::min;
838
839    fn clamp<T>(range: core::ops::RangeInclusive<T>, value: T) -> T
840    where
841        T: PartialOrd + Copy,
842    {
843        if value < *range.start() {
844            *range.start()
845        } else if value > *range.end() {
846            *range.end()
847        } else {
848            value
849        }
850    }
851
852    fn read<O, L>(slice: &[u8], offset: O, length: L) -> u32
853    where
854        O: TryInto<usize>,
855        L: TryInto<usize>,
856    {
857        let offset = offset.try_into().unwrap_or_else(|_| unreachable!());
858        let length = length.try_into().unwrap_or_else(|_| unreachable!());
859        let slice = &slice[offset..offset + length];
860        match length {
861            0 => 0,
862            1 => slice[0] as u32,
863            2 => u16::from_le_bytes([slice[0], slice[1]]) as u32,
864            3 => u32::from_le_bytes([slice[0], slice[1], slice[2], 0]),
865            4 => u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]),
866            _ => unreachable!(),
867        }
868    }
869
870    fn sext<L>(value: u32, length: L) -> u32
871    where
872        L: Into<i64>,
873    {
874        match length.into() {
875            0 => 0,
876            1 => value as u8 as i8 as i32 as u32,
877            2 => value as u16 as i16 as i32 as u32,
878            3 => (((value << 8) as i32) >> 8) as u32,
879            4 => value,
880            _ => unreachable!(),
881        }
882    }
883
884    macro_rules! args {
885        ($opcode_bytes:expr) => {{
886            let code: [u8; 16] = kani::any();
887            let chunk = u128::from_le_bytes(code);
888            let length: u32 = kani::any_where(|x| *x >= $opcode_bytes && *x - $opcode_bytes <= super::BITMASK_MAX);
889
890            (code, chunk, length)
891        }};
892    }
893
894    macro_rules! for_both_ext {
895        (|$code:ident, $chunk:ident, $length:ident, $args:ident, $read_args:ident| $body:expr) => {{
896            {
897                let (code, $chunk, $length) = args!(1);
898                let $code = &code[1..];
899                let $args = $length - 1;
900                let $read_args = super::$read_args::<false>;
901                $body
902            }
903            {
904                let (code, $chunk, $length) = args!(2);
905                let $code = &code[2..];
906                let $args = $length - 2;
907                let $read_args = super::$read_args::<true>;
908                $body
909            }
910        }};
911    }
912
913    #[kani::proof]
914    fn verify_read_args_imm() {
915        fn simple_read_args_imm(code: &[u8], args_length: u32) -> i32 {
916            let imm_length = min(4, args_length);
917            cast(sext(read(code, 0, imm_length), imm_length)).bitwise_as_i32()
918        }
919
920        for_both_ext!(|code, chunk, length, args_length, read_args_imm| {
921            assert_eq!(read_args_imm(chunk, length), simple_read_args_imm(code, args_length));
922        });
923    }
924
925    #[kani::proof]
926    fn verify_read_args_imm2() {
927        fn simple_read_args_imm2(code: &[u8], args_length: i32) -> (i32, i32) {
928            let imm1_length = min(4, i32::from(code[0]) & 0b111);
929            let imm2_length = clamp(0..=4, args_length - imm1_length - 1);
930            let imm1 = sext(read(code, 1, imm1_length), imm1_length);
931            let imm2 = sext(read(code, 1 + imm1_length, imm2_length), imm2_length);
932            let imm1 = cast(imm1).bitwise_as_i32();
933            let imm2 = cast(imm2).bitwise_as_i32();
934            (imm1, imm2)
935        }
936
937        for_both_ext!(|code, chunk, length, args_length, read_args_imm2| {
938            assert_eq!(read_args_imm2(chunk, length), simple_read_args_imm2(code, args_length as i32));
939        });
940    }
941
942    #[kani::proof]
943    fn verify_read_args_reg_imm() {
944        fn simple_read_args_reg_imm(code: &[u8], args_length: i32) -> (u8, i32) {
945            let reg = min(12, code[0] & 0b1111);
946            let imm_length = clamp(0..=4, args_length - 1);
947            let imm = sext(read(code, 1, imm_length), imm_length);
948            let imm = cast(imm).bitwise_as_i32();
949            (reg, imm)
950        }
951
952        for_both_ext!(|code, chunk, length, args_length, read_args_reg_imm| {
953            let (reg, imm) = read_args_reg_imm(chunk, length);
954            let reg = reg.get() as u8;
955            assert_eq!((reg, imm), simple_read_args_reg_imm(code, args_length as i32));
956        });
957    }
958
959    #[kani::proof]
960    fn verify_read_args_reg_imm2() {
961        fn simple_read_args_reg_imm2(code: &[u8], args_length: i32) -> (u8, i32, i32) {
962            let reg = min(12, code[0] & 0b1111);
963            let imm1_length = min(4, i32::from(code[0] >> 4) & 0b111);
964            let imm2_length = clamp(0..=4, args_length - imm1_length - 1);
965            let imm1 = sext(read(code, 1, imm1_length), imm1_length);
966            let imm2 = sext(read(code, 1 + imm1_length, imm2_length), imm2_length);
967            let imm1 = cast(imm1).bitwise_as_i32();
968            let imm2 = cast(imm2).bitwise_as_i32();
969            (reg, imm1, imm2)
970        }
971
972        for_both_ext!(|code, chunk, length, args_length, read_args_reg_imm2| {
973            let (reg, imm1, imm2) = read_args_reg_imm2(chunk, length);
974            let reg = reg.get() as u8;
975            assert_eq!((reg, imm1, imm2), simple_read_args_reg_imm2(code, args_length as i32));
976        });
977    }
978
979    #[kani::proof]
980    fn verify_read_args_regs2_imm2() {
981        fn simple_read_args_regs2_imm2(code: &[u8], args_length: i32) -> (u8, u8, i32, i32) {
982            let reg1 = min(12, code[0] & 0b1111);
983            let reg2 = min(12, code[0] >> 4);
984            let imm1_length = min(4, i32::from(code[1]) & 0b111);
985            let imm2_length = clamp(0..=4, args_length - imm1_length - 2);
986            let imm1 = sext(read(code, 2, imm1_length), imm1_length);
987            let imm2 = sext(read(code, 2 + imm1_length, imm2_length), imm2_length);
988            let imm1 = cast(imm1).bitwise_as_i32();
989            let imm2 = cast(imm2).bitwise_as_i32();
990            (reg1, reg2, imm1, imm2)
991        }
992
993        for_both_ext!(|code, chunk, length, args_length, read_args_regs2_imm2| {
994            let (reg1, reg2, imm1, imm2) = read_args_regs2_imm2(chunk, length);
995            let reg1 = reg1.get() as u8;
996            let reg2 = reg2.get() as u8;
997            assert_eq!((reg1, reg2, imm1, imm2), simple_read_args_regs2_imm2(code, args_length as i32));
998        });
999    }
1000
1001    #[kani::proof]
1002    fn verify_read_args_regs2_imm() {
1003        fn simple_read_args_regs2_imm(code: &[u8], args_length: u32) -> (u8, u8, i32) {
1004            let reg1 = min(12, code[0] & 0b1111);
1005            let reg2 = min(12, code[0] >> 4);
1006            let imm_length = clamp(0..=4, args_length as i32 - 1);
1007            let imm = sext(read(code, 1, imm_length), imm_length);
1008            let imm = cast(imm).bitwise_as_i32();
1009            (reg1, reg2, imm)
1010        }
1011
1012        for_both_ext!(|code, chunk, length, args_length, read_args_regs2_imm| {
1013            let (reg1, reg2, imm) = read_args_regs2_imm(chunk, length);
1014            let reg1 = reg1.get() as u8;
1015            let reg2 = reg2.get() as u8;
1016            assert_eq!((reg1, reg2, imm), simple_read_args_regs2_imm(code, args_length));
1017        });
1018    }
1019
1020    #[kani::proof]
1021    fn verify_read_args_regs3() {
1022        fn simple_read_args_regs3(code: &[u8]) -> (u8, u8, u8) {
1023            let reg2 = min(12, code[0] & 0b1111);
1024            let reg3 = min(12, code[0] >> 4);
1025            let reg1 = min(12, code[1] & 0b1111);
1026            (reg1, reg2, reg3)
1027        }
1028
1029        {
1030            let (code, chunk, _) = args!(1);
1031            let (reg1, reg2, reg3) = super::read_args_regs3::<false>(chunk);
1032            assert_eq!(
1033                (reg1.get() as u8, reg2.get() as u8, reg3.get() as u8),
1034                simple_read_args_regs3(&code[1..])
1035            );
1036        }
1037        {
1038            let (code, chunk, _) = args!(2);
1039            let (reg1, reg2, reg3) = super::read_args_regs3::<true>(chunk);
1040            assert_eq!(
1041                (reg1.get() as u8, reg2.get() as u8, reg3.get() as u8),
1042                simple_read_args_regs3(&code[2..])
1043            );
1044        }
1045    }
1046
1047    #[kani::proof]
1048    fn verify_read_args_regs2() {
1049        fn simple_read_args_regs2(code: &[u8]) -> (u8, u8) {
1050            let reg1 = min(12, code[0] & 0b1111);
1051            let reg2 = min(12, code[0] >> 4);
1052            (reg1, reg2)
1053        }
1054
1055        {
1056            let (code, chunk, _) = args!(1);
1057            let (reg1, reg2) = super::read_args_regs2::<false>(chunk);
1058            assert_eq!((reg1.get() as u8, reg2.get() as u8), simple_read_args_regs2(&code[1..]));
1059        }
1060        {
1061            let (code, chunk, _) = args!(2);
1062            let (reg1, reg2) = super::read_args_regs2::<true>(chunk);
1063            assert_eq!((reg1.get() as u8, reg2.get() as u8), simple_read_args_regs2(&code[2..]));
1064        }
1065    }
1066
1067    #[kani::proof]
1068    fn verify_interpreter_cache_size() {
1069        let x: usize = kani::any_where(|x| *x <= super::cast(u32::MAX).to_usize());
1070        let bytes: usize = super::interpreter_calculate_cache_size(x);
1071        let calculate_count = super::interpreter_calculate_cache_num_entries(bytes);
1072        assert_eq!(calculate_count, x);
1073
1074        let count = super::interpreter_calculate_cache_num_entries(x);
1075        let calculated_bytes = super::interpreter_calculate_cache_size(count);
1076        assert!(calculated_bytes <= x);
1077        assert!(x - calculated_bytes <= super::interpreter_calculate_cache_size(1));
1078    }
1079
1080    #[kani::proof]
1081    fn verify_extended_parse_simple() {
1082        let isa = super::ISA_Latest64;
1083        let mut code = [0_u8; super::CODE_BLOCK_SIZE + 6];
1084        let offset: usize = kani::any_where(|x| *x < super::CODE_BLOCK_SIZE + 6);
1085        code[offset] = kani::any();
1086        if offset + 1 < code.len() {
1087            code[offset + 1] = kani::any();
1088        }
1089
1090        let block_end = super::end_of_macro_block(offset, code.len());
1091        let step = super::parse_simple_extended(isa, &code, offset);
1092        assert!(step.next_offset > offset);
1093        assert!(step.next_offset <= block_end);
1094        assert!(offset + step.length as usize == step.next_offset);
1095
1096        if step.raw_opcode != super::EXTENDED_INVALID_RAW_OPCODE {
1097            let length = super::InstructionSet::raw_opcode_table(isa).length_table[step.raw_opcode].get();
1098            assert!(step.next_offset == min(offset + length as usize, block_end));
1099
1100            // The last instruction of a macro block always ends a basic block.
1101            assert!(step.next_offset < block_end || super::ends_basic_block_extended(isa, step.raw_opcode));
1102        }
1103    }
1104
1105    #[kani::proof]
1106    fn verify_extended_parse_instruction() {
1107        let isa = super::ISA_Latest64;
1108        let raw_opcode: usize = kani::any_where(|x| *x <= super::EXTENDED_INVALID_RAW_OPCODE);
1109        let chunk: u128 = kani::any();
1110        let offset: u32 = kani::any();
1111        let length = if raw_opcode == super::EXTENDED_INVALID_RAW_OPCODE {
1112            // A truncated instruction is decoded as `invalid` with the length it covers.
1113            kani::any()
1114        } else {
1115            super::InstructionSet::raw_opcode_table(isa).length_table[raw_opcode].get()
1116        };
1117
1118        let _ = super::InstructionSet::parse_instruction(isa, raw_opcode, chunk, offset, length);
1119    }
1120}
1121
1122/// The lowest level visitor; dispatches directly on opcode numbers.
1123pub trait OpcodeVisitor: Copy {
1124    type State;
1125    type ReturnTy;
1126    type InstructionSet: InstructionSet;
1127
1128    fn instruction_set(self) -> Self::InstructionSet;
1129    fn dispatch(self, state: &mut Self::State, opcode: usize, chunk: u128, offset: u32, length: u32) -> Self::ReturnTy;
1130}
1131
1132macro_rules! define_all_instructions {
1133    (@impl_shared $($name:ident,)+) => {
1134        #[allow(non_camel_case_types)]
1135        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
1136        #[repr(u8)]
1137        pub enum Opcode {
1138            $(
1139                $name,
1140            )+
1141
1142            // This is here to prevent `as` casts.
1143            #[doc(hidden)]
1144            _NonExhaustive(()),
1145        }
1146
1147        impl Opcode {
1148            pub const ALL: &[Opcode] = &[
1149                $(Opcode::$name,)+
1150            ];
1151
1152            pub fn name(self) -> &'static str {
1153                match self {
1154                    $(
1155                        Opcode::$name => stringify!($name),
1156                    )+
1157
1158                    Opcode::_NonExhaustive(()) => {
1159                        #[cfg(debug_assertions)]
1160                        unreachable!();
1161
1162                        #[cfg(not(debug_assertions))]
1163                        ""
1164                    },
1165                }
1166            }
1167
1168            #[inline]
1169            const fn discriminant(&self) -> u8 {
1170                #[allow(unsafe_code)]
1171                // SAFETY: Reading a discriminant into a primitive when we have a #[repr] on the enum is safe,
1172                //         since Rust guarantees it has a union-like layout.
1173                unsafe {
1174                    *(self as *const Opcode).cast::<u8>()
1175                }
1176            }
1177        }
1178
1179        impl core::fmt::Display for Opcode {
1180            fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
1181                fmt.write_str(self.name())
1182            }
1183        }
1184
1185        impl core::str::FromStr for Opcode {
1186            type Err = &'static str;
1187            fn from_str(s: &str) -> Result<Self, Self::Err> {
1188                Ok(match s {
1189                    $(
1190                        stringify!($name) => Opcode::$name,
1191                    )+
1192                    _ => return Err("unknown opcode")
1193                })
1194            }
1195        }
1196    };
1197
1198    (
1199        [$($name_argless:ident,)+]
1200        [$($name_reg_imm:ident,)+]
1201        [$($name_reg_imm_offset:ident,)+]
1202        [$($name_reg_imm_imm:ident,)+]
1203        [$($name_reg_reg_imm:ident,)+]
1204        [$($name_reg_reg_offset:ident,)+]
1205        [$($name_reg_reg_reg:ident,)+]
1206        [$($name_offset:ident,)+]
1207        [$($name_imm:ident,)+]
1208        [$($name_imm_imm:ident,)+]
1209        [$($name_reg_reg:ident,)+]
1210        [$($name_reg_reg_imm_imm:ident,)+]
1211        [$($name_reg_imm64:ident,)+]
1212    ) => {
1213        define_all_instructions!(
1214            @impl_shared
1215            $($name_argless,)+
1216            $($name_reg_imm,)+
1217            $($name_reg_imm_offset,)+
1218            $($name_reg_imm_imm,)+
1219            $($name_reg_reg_imm,)+
1220            $($name_reg_reg_offset,)+
1221            $($name_reg_reg_reg,)+
1222            $($name_offset,)+
1223            $($name_imm,)+
1224            $($name_imm_imm,)+
1225            $($name_reg_reg,)+
1226            $($name_reg_reg_imm_imm,)+
1227            $($name_reg_imm64,)+
1228        );
1229
1230        #[macro_export]
1231        macro_rules! impl_parsing_visitor_for_instruction_visitor {
1232            ($visitor_ty:ident) => {
1233                impl ParsingVisitor for $visitor_ty {
1234                    type ReturnTy = <$visitor_ty as $crate::program::InstructionVisitor>::ReturnTy;
1235
1236                    $(fn $name_argless(&mut self, _offset: u32, _length: u32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_argless(self) })+
1237                    $(fn $name_reg_imm(&mut self, _offset: u32, _length: u32, reg: RawReg, imm: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_imm(self, reg, imm) })+
1238                    $(fn $name_reg_imm_offset(&mut self, _offset: u32, _length: u32, reg: RawReg, imm1: i32, imm2: u32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_imm_offset(self, reg, imm1, imm2) })+
1239                    $(fn $name_reg_imm_imm(&mut self, _offset: u32, _length: u32, reg: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_imm_imm(self, reg, imm1, imm2) })+
1240                    $(fn $name_reg_reg_imm(&mut self, _offset: u32, _length: u32, reg1: RawReg, reg2: RawReg, imm: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_reg_imm(self, reg1, reg2, imm) })+
1241                    $(fn $name_reg_reg_offset(&mut self, _offset: u32, _length: u32, reg1: RawReg, reg2: RawReg, imm: u32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_reg_offset(self, reg1, reg2, imm) })+
1242                    $(fn $name_reg_reg_reg(&mut self, _offset: u32, _length: u32, reg1: RawReg, reg2: RawReg, reg3: RawReg) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_reg_reg(self, reg1, reg2, reg3) })+
1243                    $(fn $name_offset(&mut self, _offset: u32, _length: u32, imm: u32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_offset(self, imm) })+
1244                    $(fn $name_imm(&mut self, _offset: u32, _length: u32, imm: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_imm(self, imm) })+
1245                    $(fn $name_imm_imm(&mut self, _offset: u32, _length: u32, imm1: i32, imm2: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_imm_imm(self, imm1, imm2) })+
1246                    $(fn $name_reg_reg(&mut self, _offset: u32, _length: u32, reg1: RawReg, reg2: RawReg) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_reg(self, reg1, reg2) })+
1247                    $(fn $name_reg_reg_imm_imm(&mut self, _offset: u32, _length: u32, reg1: RawReg, reg2: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_reg_imm_imm(self, reg1, reg2, imm1, imm2) })+
1248                    $(fn $name_reg_imm64(&mut self, _offset: u32, _length: u32, reg: RawReg, imm: u64) -> Self::ReturnTy { $crate::program::InstructionVisitor::$name_reg_imm64(self, reg, imm) })+
1249
1250                    fn invalid(&mut self, _offset: u32, _length: u32) -> Self::ReturnTy { $crate::program::InstructionVisitor::invalid(self) }
1251                }
1252            };
1253        }
1254
1255        pub trait ParsingVisitor {
1256            type ReturnTy;
1257
1258            $(fn $name_argless(&mut self, offset: u32, length: u32) -> Self::ReturnTy;)+
1259            $(fn $name_reg_imm(&mut self, offset: u32, length: u32, reg: RawReg, imm: i32) -> Self::ReturnTy;)+
1260            $(fn $name_reg_imm_offset(&mut self, offset: u32, length: u32, reg: RawReg, imm1: i32, imm2: u32) -> Self::ReturnTy;)+
1261            $(fn $name_reg_imm_imm(&mut self, offset: u32, length: u32, reg: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1262            $(fn $name_reg_reg_imm(&mut self, offset: u32, length: u32, reg1: RawReg, reg2: RawReg, imm: i32) -> Self::ReturnTy;)+
1263            $(fn $name_reg_reg_offset(&mut self, offset: u32, length: u32, reg1: RawReg, reg2: RawReg, imm: u32) -> Self::ReturnTy;)+
1264            $(fn $name_reg_reg_reg(&mut self, offset: u32, length: u32, reg1: RawReg, reg2: RawReg, reg3: RawReg) -> Self::ReturnTy;)+
1265            $(fn $name_offset(&mut self, offset: u32, length: u32, imm: u32) -> Self::ReturnTy;)+
1266            $(fn $name_imm(&mut self, offset: u32, length: u32, imm: i32) -> Self::ReturnTy;)+
1267            $(fn $name_imm_imm(&mut self, offset: u32, length: u32, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1268            $(fn $name_reg_reg(&mut self, offset: u32, length: u32, reg1: RawReg, reg2: RawReg) -> Self::ReturnTy;)+
1269            $(fn $name_reg_reg_imm_imm(&mut self, offset: u32, length: u32, reg1: RawReg, reg2: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1270            $(fn $name_reg_imm64(&mut self, offset: u32, length: u32, reg: RawReg, imm: u64) -> Self::ReturnTy;)+
1271
1272            fn invalid(&mut self, offset: u32, length: u32) -> Self::ReturnTy;
1273        }
1274
1275        pub trait InstructionVisitor {
1276            type ReturnTy;
1277
1278            $(fn $name_argless(&mut self) -> Self::ReturnTy;)+
1279            $(fn $name_reg_imm(&mut self, reg: RawReg, imm: i32) -> Self::ReturnTy;)+
1280            $(fn $name_reg_imm_offset(&mut self, reg: RawReg, imm1: i32, imm2: u32) -> Self::ReturnTy;)+
1281            $(fn $name_reg_imm_imm(&mut self, reg: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1282            $(fn $name_reg_reg_imm(&mut self, reg1: RawReg, reg2: RawReg, imm: i32) -> Self::ReturnTy;)+
1283            $(fn $name_reg_reg_offset(&mut self, reg1: RawReg, reg2: RawReg, imm: u32) -> Self::ReturnTy;)+
1284            $(fn $name_reg_reg_reg(&mut self, reg1: RawReg, reg2: RawReg, reg3: RawReg) -> Self::ReturnTy;)+
1285            $(fn $name_offset(&mut self, imm: u32) -> Self::ReturnTy;)+
1286            $(fn $name_imm(&mut self, imm: i32) -> Self::ReturnTy;)+
1287            $(fn $name_imm_imm(&mut self, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1288            $(fn $name_reg_reg(&mut self, reg1: RawReg, reg2: RawReg) -> Self::ReturnTy;)+
1289            $(fn $name_reg_reg_imm_imm(&mut self, reg1: RawReg, reg2: RawReg, imm1: i32, imm2: i32) -> Self::ReturnTy;)+
1290            $(fn $name_reg_imm64(&mut self, reg: RawReg, imm: u64) -> Self::ReturnTy;)+
1291
1292            fn invalid(&mut self) -> Self::ReturnTy;
1293        }
1294
1295        #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1296        #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
1297        #[allow(non_camel_case_types)]
1298        #[repr(u32)]
1299        pub enum Instruction {
1300            $($name_argless,)+
1301            $($name_reg_imm(RawReg, i32),)+
1302            $($name_reg_imm_offset(RawReg, i32, u32),)+
1303            $($name_reg_imm_imm(RawReg, i32, i32),)+
1304            $($name_reg_reg_imm(RawReg, RawReg, i32),)+
1305            $($name_reg_reg_offset(RawReg, RawReg, u32),)+
1306            $($name_reg_reg_reg(RawReg, RawReg, RawReg),)+
1307            $($name_offset(u32),)+
1308            $($name_imm(i32),)+
1309            $($name_imm_imm(i32, i32),)+
1310            $($name_reg_reg(RawReg, RawReg),)+
1311            $($name_reg_reg_imm_imm(RawReg, RawReg, i32, i32),)+
1312            $($name_reg_imm64(RawReg, u64),)+
1313            invalid = LEGACY_INVALID_RAW_OPCODE as u32,
1314        }
1315
1316        impl Instruction {
1317            pub fn visit<T>(self, visitor: &mut T) -> T::ReturnTy where T: InstructionVisitor {
1318                match self {
1319                    $(Self::$name_argless => visitor.$name_argless(),)+
1320                    $(Self::$name_reg_imm(reg, imm) => visitor.$name_reg_imm(reg, imm),)+
1321                    $(Self::$name_reg_imm_offset(reg, imm1, imm2) => visitor.$name_reg_imm_offset(reg, imm1, imm2),)+
1322                    $(Self::$name_reg_imm_imm(reg, imm1, imm2) => visitor.$name_reg_imm_imm(reg, imm1, imm2),)+
1323                    $(Self::$name_reg_reg_imm(reg1, reg2, imm) => visitor.$name_reg_reg_imm(reg1, reg2, imm),)+
1324                    $(Self::$name_reg_reg_offset(reg1, reg2, imm) => visitor.$name_reg_reg_offset(reg1, reg2, imm),)+
1325                    $(Self::$name_reg_reg_reg(reg1, reg2, reg3) => visitor.$name_reg_reg_reg(reg1, reg2, reg3),)+
1326                    $(Self::$name_offset(imm) => visitor.$name_offset(imm),)+
1327                    $(Self::$name_imm(imm) => visitor.$name_imm(imm),)+
1328                    $(Self::$name_imm_imm(imm1, imm2) => visitor.$name_imm_imm(imm1, imm2),)+
1329                    $(Self::$name_reg_reg(reg1, reg2) => visitor.$name_reg_reg(reg1, reg2),)+
1330                    $(Self::$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2) => visitor.$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2),)+
1331                    $(Self::$name_reg_imm64(reg, imm) => visitor.$name_reg_imm64(reg, imm),)+
1332                    Self::invalid => visitor.invalid(),
1333                }
1334            }
1335
1336            pub fn visit_parsing<T>(self, offset: u32, length: u32, visitor: &mut T) -> T::ReturnTy where T: ParsingVisitor {
1337                match self {
1338                    $(Self::$name_argless => visitor.$name_argless(offset, length),)+
1339                    $(Self::$name_reg_imm(reg, imm) => visitor.$name_reg_imm(offset, length, reg, imm),)+
1340                    $(Self::$name_reg_imm_offset(reg, imm1, imm2) => visitor.$name_reg_imm_offset(offset, length, reg, imm1, imm2),)+
1341                    $(Self::$name_reg_imm_imm(reg, imm1, imm2) => visitor.$name_reg_imm_imm(offset, length, reg, imm1, imm2),)+
1342                    $(Self::$name_reg_reg_imm(reg1, reg2, imm) => visitor.$name_reg_reg_imm(offset, length, reg1, reg2, imm),)+
1343                    $(Self::$name_reg_reg_offset(reg1, reg2, imm) => visitor.$name_reg_reg_offset(offset, length, reg1, reg2, imm),)+
1344                    $(Self::$name_reg_reg_reg(reg1, reg2, reg3) => visitor.$name_reg_reg_reg(offset, length, reg1, reg2, reg3),)+
1345                    $(Self::$name_offset(imm) => visitor.$name_offset(offset, length, imm),)+
1346                    $(Self::$name_imm(imm) => visitor.$name_imm(offset, length, imm),)+
1347                    $(Self::$name_imm_imm(imm1, imm2) => visitor.$name_imm_imm(offset, length, imm1, imm2),)+
1348                    $(Self::$name_reg_reg(reg1, reg2) => visitor.$name_reg_reg(offset, length, reg1, reg2),)+
1349                    $(Self::$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2) => visitor.$name_reg_reg_imm_imm(offset, length, reg1, reg2, imm1, imm2),)+
1350                    $(Self::$name_reg_imm64(reg, imm) => visitor.$name_reg_imm64(offset, length, reg, imm),)+
1351                    Self::invalid => visitor.invalid(offset, length),
1352                }
1353            }
1354
1355            pub fn serialize_into<I>(self, isa: I, position: u32, buffer: &mut [u8]) -> usize where I: InstructionSet {
1356                match self {
1357                    $(Self::$name_argless => Self::serialize_argless(isa, buffer, Opcode::$name_argless),)+
1358                    $(Self::$name_reg_imm(reg, imm) => Self::serialize_reg_imm(isa, buffer, Opcode::$name_reg_imm, reg, imm),)+
1359                    $(Self::$name_reg_imm_offset(reg, imm1, imm2) => Self::serialize_reg_imm_offset(isa, buffer, position, Opcode::$name_reg_imm_offset, reg, imm1, imm2),)+
1360                    $(Self::$name_reg_imm_imm(reg, imm1, imm2) => Self::serialize_reg_imm_imm(isa, buffer, Opcode::$name_reg_imm_imm, reg, imm1, imm2),)+
1361                    $(Self::$name_reg_reg_imm(reg1, reg2, imm) => Self::serialize_reg_reg_imm(isa, buffer, Opcode::$name_reg_reg_imm, reg1, reg2, imm),)+
1362                    $(Self::$name_reg_reg_offset(reg1, reg2, imm) => Self::serialize_reg_reg_offset(isa, buffer, position, Opcode::$name_reg_reg_offset, reg1, reg2, imm),)+
1363                    $(Self::$name_reg_reg_reg(reg1, reg2, reg3) => Self::serialize_reg_reg_reg(isa, buffer, Opcode::$name_reg_reg_reg, reg1, reg2, reg3),)+
1364                    $(Self::$name_offset(imm) => Self::serialize_offset(isa, buffer, position, Opcode::$name_offset, imm),)+
1365                    $(Self::$name_imm(imm) => Self::serialize_imm(isa, buffer, Opcode::$name_imm, imm),)+
1366                    $(Self::$name_imm_imm(imm1, imm2) => Self::serialize_imm_imm(isa, buffer, Opcode::$name_imm_imm, imm1, imm2),)+
1367                    $(Self::$name_reg_reg(reg1, reg2) => Self::serialize_reg_reg(isa, buffer, Opcode::$name_reg_reg, reg1, reg2),)+
1368                    $(Self::$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2) => Self::serialize_reg_reg_imm_imm(isa, buffer, Opcode::$name_reg_reg_imm_imm, reg1, reg2, imm1, imm2),)+
1369                    $(Self::$name_reg_imm64(reg, imm) => Self::serialize_reg_imm64(isa, buffer, Opcode::$name_reg_imm64, reg, imm),)+
1370                    Self::invalid => Self::serialize_argless(isa, buffer, Opcode::trap),
1371                }
1372            }
1373
1374            pub fn opcode(self) -> Opcode {
1375                match self {
1376                    $(Self::$name_argless => Opcode::$name_argless,)+
1377                    $(Self::$name_reg_imm(..) => Opcode::$name_reg_imm,)+
1378                    $(Self::$name_reg_imm_offset(..) => Opcode::$name_reg_imm_offset,)+
1379                    $(Self::$name_reg_imm_imm(..) => Opcode::$name_reg_imm_imm,)+
1380                    $(Self::$name_reg_reg_imm(..) => Opcode::$name_reg_reg_imm,)+
1381                    $(Self::$name_reg_reg_offset(..) => Opcode::$name_reg_reg_offset,)+
1382                    $(Self::$name_reg_reg_reg(..) => Opcode::$name_reg_reg_reg,)+
1383                    $(Self::$name_offset(..) => Opcode::$name_offset,)+
1384                    $(Self::$name_imm(..) => Opcode::$name_imm,)+
1385                    $(Self::$name_imm_imm(..) => Opcode::$name_imm_imm,)+
1386                    $(Self::$name_reg_reg(..) => Opcode::$name_reg_reg,)+
1387                    $(Self::$name_reg_reg_imm_imm(..) => Opcode::$name_reg_reg_imm_imm,)+
1388                    $(Self::$name_reg_imm64(..) => Opcode::$name_reg_imm64,)+
1389                    Self::invalid => Opcode::trap,
1390                }
1391            }
1392        }
1393
1394        pub mod asm {
1395            use super::{Instruction, Reg};
1396
1397            $(
1398                pub fn $name_argless() -> Instruction {
1399                    Instruction::$name_argless
1400                }
1401            )+
1402
1403            $(
1404                pub fn $name_reg_imm(reg: Reg, imm: i32) -> Instruction {
1405                    Instruction::$name_reg_imm(reg.into(), imm)
1406                }
1407            )+
1408
1409            $(
1410                pub fn $name_reg_imm_offset(reg: Reg, imm1: i32, imm2: u32) -> Instruction {
1411                    Instruction::$name_reg_imm_offset(reg.into(), imm1, imm2)
1412                }
1413            )+
1414
1415            $(
1416                pub fn $name_reg_imm_imm(reg: Reg, imm1: i32, imm2: i32) -> Instruction {
1417                    Instruction::$name_reg_imm_imm(reg.into(), imm1, imm2)
1418                }
1419            )+
1420
1421            $(
1422                pub fn $name_reg_reg_imm(reg1: Reg, reg2: Reg, imm: i32) -> Instruction {
1423                    Instruction::$name_reg_reg_imm(reg1.into(), reg2.into(), imm)
1424                }
1425            )+
1426
1427            $(
1428                pub fn $name_reg_reg_offset(reg1: Reg, reg2: Reg, imm: u32) -> Instruction {
1429                    Instruction::$name_reg_reg_offset(reg1.into(), reg2.into(), imm)
1430                }
1431            )+
1432
1433            $(
1434                pub fn $name_reg_reg_reg(reg1: Reg, reg2: Reg, reg3: Reg) -> Instruction {
1435                    Instruction::$name_reg_reg_reg(reg1.into(), reg2.into(), reg3.into())
1436                }
1437            )+
1438
1439            $(
1440                pub fn $name_offset(imm: u32) -> Instruction {
1441                    Instruction::$name_offset(imm)
1442                }
1443            )+
1444
1445            $(
1446                pub fn $name_imm(imm: i32) -> Instruction {
1447                    Instruction::$name_imm(imm)
1448                }
1449            )+
1450
1451            $(
1452                pub fn $name_imm_imm(imm1: i32, imm2: i32) -> Instruction {
1453                    Instruction::$name_imm_imm(imm1, imm2)
1454                }
1455            )+
1456
1457            $(
1458                pub fn $name_reg_reg(reg1: Reg, reg2: Reg) -> Instruction {
1459                    Instruction::$name_reg_reg(reg1.into(), reg2.into())
1460                }
1461            )+
1462
1463            $(
1464                pub fn $name_reg_reg_imm_imm(reg1: Reg, reg2: Reg, imm1: i32, imm2: i32) -> Instruction {
1465                    Instruction::$name_reg_reg_imm_imm(reg1.into(), reg2.into(), imm1, imm2)
1466                }
1467            )+
1468
1469            $(
1470                pub fn $name_reg_imm64(reg: Reg, imm: u64) -> Instruction {
1471                    Instruction::$name_reg_imm64(reg.into(), imm)
1472                }
1473            )+
1474
1475            pub fn ret() -> Instruction {
1476                jump_indirect(Reg::RA, 0)
1477            }
1478        }
1479
1480        #[derive(Copy, Clone)]
1481        struct EnumVisitor<I> {
1482            instruction_set: I
1483        }
1484
1485        impl<'a, I> OpcodeVisitor for EnumVisitor<I> where I: InstructionSet {
1486            type State = ();
1487            type ReturnTy = Instruction;
1488            type InstructionSet = I;
1489
1490            fn instruction_set(self) -> Self::InstructionSet {
1491                self.instruction_set
1492            }
1493
1494            fn dispatch(self, _state: &mut (), opcode: usize, chunk: u128, offset: u32, length: u32) -> Instruction {
1495                self.instruction_set().parse_instruction(opcode, chunk, offset, length)
1496            }
1497        }
1498    };
1499}
1500
1501const UNUSED_RAW_OPCODE: u32 = 254;
1502
1503macro_rules! define_legacy_instruction_set {
1504    (@impl_shared $isa_name:ident, $($name:ident = $value:expr,)+) => {
1505        #[allow(non_camel_case_types)]
1506        #[derive(Copy, Clone, Debug, Default)]
1507        pub struct $isa_name;
1508
1509        impl $isa_name {
1510            #[doc(hidden)]
1511            pub const RAW_OPCODE_TO_ENUM_CONST: [Option<Opcode>; 256] = {
1512                let mut map = [None; 256];
1513                $(
1514                    map[$value] = Some(Opcode::$name);
1515                )+
1516                map
1517            };
1518
1519            pub const OPCODE_DISCRIMINANT_TO_RAW_OPCODE_CONST: [u8; 256] = {
1520                let mut map = [UNUSED_RAW_OPCODE as u8; 256];
1521                assert!($isa_name::RAW_OPCODE_TO_ENUM_CONST[UNUSED_RAW_OPCODE as usize].is_none());
1522
1523                $({
1524                    let discriminant = Opcode::$name.discriminant() as usize;
1525                    assert!(map[discriminant] as u32 == UNUSED_RAW_OPCODE);
1526                    map[discriminant] = $value;
1527                })+
1528
1529                map
1530            };
1531        }
1532    };
1533
1534    (
1535        ($d:tt)
1536        $isa_name:ident,
1537        $build_static_dispatch_table:ident,
1538        [$($name_argless:ident = $value_argless:expr,)+]
1539        [$($name_reg_imm:ident = $value_reg_imm:expr,)+]
1540        [$($name_reg_imm_offset:ident = $value_reg_imm_offset:expr,)+]
1541        [$($name_reg_imm_imm:ident = $value_reg_imm_imm:expr,)+]
1542        [$($name_reg_reg_imm:ident = $value_reg_reg_imm:expr,)+]
1543        [$($name_reg_reg_offset:ident = $value_reg_reg_offset:expr,)+]
1544        [$($name_reg_reg_reg:ident = $value_reg_reg_reg:expr,)+]
1545        [$($name_offset:ident = $value_offset:expr,)+]
1546        [$($name_imm:ident = $value_imm:expr,)+]
1547        [$($name_imm_imm:ident = $value_imm_imm:expr,)+]
1548        [$($name_reg_reg:ident = $value_reg_reg:expr,)+]
1549        [$($name_reg_reg_imm_imm:ident = $value_reg_reg_imm_imm:expr,)+]
1550        [$($name_reg_imm64:ident = $value_reg_imm64:expr,)*]
1551    ) => {
1552        define_legacy_instruction_set!(
1553            @impl_shared
1554            $isa_name,
1555            $($name_argless = $value_argless,)+
1556            $($name_reg_imm = $value_reg_imm,)+
1557            $($name_reg_imm_offset = $value_reg_imm_offset,)+
1558            $($name_reg_imm_imm = $value_reg_imm_imm,)+
1559            $($name_reg_reg_imm = $value_reg_reg_imm,)+
1560            $($name_reg_reg_offset = $value_reg_reg_offset,)+
1561            $($name_reg_reg_reg = $value_reg_reg_reg,)+
1562            $($name_offset = $value_offset,)+
1563            $($name_imm = $value_imm,)+
1564            $($name_imm_imm = $value_imm_imm,)+
1565            $($name_reg_reg = $value_reg_reg,)+
1566            $($name_reg_reg_imm_imm = $value_reg_reg_imm_imm,)+
1567            $($name_reg_imm64 = $value_reg_imm64,)*
1568        );
1569
1570        impl InstructionSet for $isa_name {
1571            #[inline]
1572            fn is_legacy(self) -> bool {
1573                true
1574            }
1575
1576            #[cfg_attr(feature = "alloc", inline)]
1577            fn opcode_from_raw(self, raw_opcode: u32) -> Option<Opcode> {
1578                static RAW_OPCODE_TO_ENUM: [Option<Opcode>; 256] = $isa_name::RAW_OPCODE_TO_ENUM_CONST;
1579                *RAW_OPCODE_TO_ENUM.get(raw_opcode as usize)?
1580            }
1581
1582            #[cfg_attr(feature = "alloc", inline)]
1583            fn opcode_to_raw(self, opcode: Opcode, args_length: u32) -> Option<(u32, u32)> {
1584                static OPCODE_DISCRIMINANT_TO_RAW_OPCODE: [u8; 256] = $isa_name::OPCODE_DISCRIMINANT_TO_RAW_OPCODE_CONST;
1585                let raw_opcode = OPCODE_DISCRIMINANT_TO_RAW_OPCODE[opcode.discriminant() as usize];
1586                if u32::from(raw_opcode) == UNUSED_RAW_OPCODE {
1587                    None
1588                } else {
1589                    Some((u32::from(raw_opcode), args_length))
1590                }
1591            }
1592
1593            fn supports_opcode(self, opcode: Opcode) -> bool {
1594                match opcode {
1595                    $(Opcode::$name_argless => true,)+
1596                    $(Opcode::$name_reg_imm => true,)+
1597                    $(Opcode::$name_reg_imm_offset => true,)+
1598                    $(Opcode::$name_reg_imm_imm => true,)+
1599                    $(Opcode::$name_reg_reg_imm => true,)+
1600                    $(Opcode::$name_reg_reg_offset => true,)+
1601                    $(Opcode::$name_reg_reg_reg => true,)+
1602                    $(Opcode::$name_offset => true,)+
1603                    $(Opcode::$name_imm => true,)+
1604                    $(Opcode::$name_imm_imm => true,)+
1605                    $(Opcode::$name_reg_reg => true,)+
1606                    $(Opcode::$name_reg_reg_imm_imm => true,)+
1607                    $(Opcode::$name_reg_imm64 => true,)*
1608                    #[allow(unreachable_patterns)]
1609                    _ => false,
1610                }
1611            }
1612
1613            fn parse_instruction(self, raw_opcode: usize, chunk: u128, offset: u32, length: u32) -> Instruction {
1614                match raw_opcode {
1615                    $(
1616                        $value_argless => Instruction::$name_argless,
1617                    )+
1618                    $(
1619                        $value_reg_imm => {
1620                            let (reg, imm) = $crate::program::read_args_reg_imm::<false>(chunk, length);
1621                            Instruction::$name_reg_imm(reg, imm)
1622                        },
1623                    )+
1624                    $(
1625                        $value_reg_imm_offset => {
1626                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm_offset::<false>(chunk, offset, length);
1627                            Instruction::$name_reg_imm_offset(reg, imm1, imm2)
1628                        },
1629                    )+
1630                    $(
1631                        $value_reg_imm_imm => {
1632                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm2::<false>(chunk, length);
1633                            Instruction::$name_reg_imm_imm(reg, imm1, imm2)
1634                        },
1635                    )+
1636                    $(
1637                        $value_reg_reg_imm => {
1638                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_imm::<false>(chunk, length);
1639                            Instruction::$name_reg_reg_imm(reg1, reg2, imm)
1640                        }
1641                    )+
1642                    $(
1643                        $value_reg_reg_offset => {
1644                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_offset::<false>(chunk, offset, length);
1645                            Instruction::$name_reg_reg_offset(reg1, reg2, imm)
1646                        }
1647                    )+
1648                    $(
1649                        $value_reg_reg_reg => {
1650                            let (reg1, reg2, reg3) = $crate::program::read_args_regs3::<false>(chunk);
1651                            Instruction::$name_reg_reg_reg(reg1, reg2, reg3)
1652                        }
1653                    )+
1654                    $(
1655                        $value_offset => {
1656                            let imm = $crate::program::read_args_offset::<false>(chunk, offset, length);
1657                            Instruction::$name_offset(imm)
1658                        }
1659                    )+
1660                    $(
1661                        $value_imm => {
1662                            let imm = $crate::program::read_args_imm::<false>(chunk, length);
1663                            Instruction::$name_imm(imm)
1664                        }
1665                    )+
1666                    $(
1667                        $value_imm_imm => {
1668                            let (imm1, imm2) = $crate::program::read_args_imm2::<false>(chunk, length);
1669                            Instruction::$name_imm_imm(imm1, imm2)
1670                        }
1671                    )+
1672                    $(
1673                        $value_reg_reg => {
1674                            let (reg1, reg2) = $crate::program::read_args_regs2::<false>(chunk);
1675                            Instruction::$name_reg_reg(reg1, reg2)
1676                        }
1677                    )+
1678                    $(
1679                        $value_reg_reg_imm_imm => {
1680                            let (reg1, reg2, imm1, imm2) = $crate::program::read_args_regs2_imm2::<false>(chunk, length);
1681                            Instruction::$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2)
1682                        }
1683                    )+
1684                    $(
1685                        $value_reg_imm64 => {
1686                            let (reg, imm) = $crate::program::read_args_reg_imm64::<false>(chunk);
1687                            Instruction::$name_reg_imm64(reg, imm)
1688                        }
1689                    )*
1690                    _ => Instruction::invalid,
1691                }
1692            }
1693        }
1694
1695        #[macro_export]
1696        macro_rules! $build_static_dispatch_table {
1697            ($table_name:ident, $visitor_ty:ident<$d($visitor_ty_params:tt),*>) => {{
1698                use $crate::program::{
1699                    LEGACY_RAW_OPCODE_COUNT,
1700                    ParsingVisitor
1701                };
1702
1703                type ReturnTy<$d($visitor_ty_params),*> = <$visitor_ty<$d($visitor_ty_params),*> as ParsingVisitor>::ReturnTy;
1704                type VisitFn<$d($visitor_ty_params),*> = fn(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32);
1705
1706                #[derive(Copy, Clone)]
1707                struct DispatchTable<'a>(&'a [VisitFn<'a>; LEGACY_RAW_OPCODE_COUNT]);
1708
1709                impl<'a> $crate::program::OpcodeVisitor for DispatchTable<'a> {
1710                    type State = $visitor_ty<'a>;
1711                    type ReturnTy = ();
1712                    type InstructionSet = $crate::program::$isa_name;
1713
1714                    #[inline]
1715                    fn instruction_set(self) -> Self::InstructionSet {
1716                        $crate::program::$isa_name
1717                    }
1718
1719                    #[inline]
1720                    fn dispatch(self, state: &mut $visitor_ty<'a>, opcode: usize, chunk: u128, offset: u32, length: u32) {
1721                        self.0[opcode](state, chunk, offset, length)
1722                    }
1723                }
1724
1725                static $table_name: [VisitFn; LEGACY_RAW_OPCODE_COUNT] = {
1726                    let mut table = [invalid_instruction as VisitFn; LEGACY_RAW_OPCODE_COUNT];
1727
1728                    $({
1729                        // Putting all of the handlers in a single link section can make a big difference
1730                        // when it comes to performance, even up to 10% in some cases. This will force the
1731                        // compiler and the linker to put all of this code near each other, minimizing
1732                        // instruction cache misses.
1733                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1734                        fn $name_argless<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, _chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1735                            state.$name_argless(offset, length)
1736                        }
1737
1738                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_argless].is_some() {
1739                            table[$value_argless] = $name_argless;
1740                        }
1741                    })*
1742
1743                    $({
1744                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1745                        fn $name_reg_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1746                            let (reg, imm) = $crate::program::read_args_reg_imm::<false>(chunk, length);
1747                            state.$name_reg_imm(offset, length, reg, imm)
1748                        }
1749
1750                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_imm].is_some() {
1751                            table[$value_reg_imm] = $name_reg_imm;
1752                        }
1753                    })*
1754
1755                    $({
1756                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1757                        fn $name_reg_imm_offset<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1758                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm_offset::<false>(chunk, offset, length);
1759                            state.$name_reg_imm_offset(offset, length, reg, imm1, imm2)
1760                        }
1761
1762                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_imm_offset].is_some() {
1763                            table[$value_reg_imm_offset] = $name_reg_imm_offset;
1764                        }
1765                    })*
1766
1767                    $({
1768                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1769                        fn $name_reg_imm_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1770                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm2::<false>(chunk, length);
1771                            state.$name_reg_imm_imm(offset, length, reg, imm1, imm2)
1772                        }
1773
1774                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_imm_imm].is_some() {
1775                            table[$value_reg_imm_imm] = $name_reg_imm_imm;
1776                        }
1777                    })*
1778
1779                    $({
1780                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1781                        fn $name_reg_reg_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1782                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_imm::<false>(chunk, length);
1783                            state.$name_reg_reg_imm(offset, length, reg1, reg2, imm)
1784                        }
1785
1786                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_reg_imm].is_some() {
1787                            table[$value_reg_reg_imm] = $name_reg_reg_imm;
1788                        }
1789                    })*
1790
1791                    $({
1792                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1793                        fn $name_reg_reg_offset<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1794                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_offset::<false>(chunk, offset, length);
1795                            state.$name_reg_reg_offset(offset, length, reg1, reg2, imm)
1796                        }
1797
1798                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_reg_offset].is_some() {
1799                            table[$value_reg_reg_offset] = $name_reg_reg_offset;
1800                        }
1801                    })*
1802
1803                    $({
1804                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1805                        fn $name_reg_reg_reg<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1806                            let (reg1, reg2, reg3) = $crate::program::read_args_regs3::<false>(chunk);
1807                            state.$name_reg_reg_reg(offset, length, reg1, reg2, reg3)
1808                        }
1809
1810                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_reg_reg].is_some() {
1811                            table[$value_reg_reg_reg] = $name_reg_reg_reg;
1812                        }
1813                    })*
1814
1815                    $({
1816                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1817                        fn $name_offset<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1818                            let imm = $crate::program::read_args_offset::<false>(chunk, offset, length);
1819                            state.$name_offset(offset, length, imm)
1820                        }
1821
1822                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_offset].is_some() {
1823                            table[$value_offset] = $name_offset;
1824                        }
1825                    })*
1826
1827                    $({
1828                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1829                        fn $name_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1830                            let imm = $crate::program::read_args_imm::<false>(chunk, length);
1831                            state.$name_imm(offset, length, imm)
1832                        }
1833
1834                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_imm].is_some() {
1835                            table[$value_imm] = $name_imm;
1836                        }
1837                    })*
1838
1839                    $({
1840                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1841                        fn $name_imm_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1842                            let (imm1, imm2) = $crate::program::read_args_imm2::<false>(chunk, length);
1843                            state.$name_imm_imm(offset, length, imm1, imm2)
1844                        }
1845
1846                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_imm_imm].is_some() {
1847                            table[$value_imm_imm] = $name_imm_imm;
1848                        }
1849                    })*
1850
1851                    $({
1852                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1853                        fn $name_reg_reg<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1854                            let (reg1, reg2) = $crate::program::read_args_regs2::<false>(chunk);
1855                            state.$name_reg_reg(offset, length, reg1, reg2)
1856                        }
1857
1858                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_reg].is_some() {
1859                            table[$value_reg_reg] = $name_reg_reg;
1860                        }
1861                    })*
1862
1863                    $({
1864                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1865                        fn $name_reg_reg_imm_imm<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1866                            let (reg1, reg2, imm1, imm2) = $crate::program::read_args_regs2_imm2::<false>(chunk, length);
1867                            state.$name_reg_reg_imm_imm(offset, length, reg1, reg2, imm1, imm2)
1868                        }
1869
1870                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_reg_imm_imm].is_some() {
1871                            table[$value_reg_reg_imm_imm] = $name_reg_reg_imm_imm;
1872                        }
1873                    })*
1874
1875                    $({
1876                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1877                        fn $name_reg_imm64<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1878                            let (reg, imm) = $crate::program::read_args_reg_imm64::<false>(chunk);
1879                            state.$name_reg_imm64(offset, length, reg, imm)
1880                        }
1881
1882                        if $crate::program::$isa_name::RAW_OPCODE_TO_ENUM_CONST[$value_reg_imm64].is_some() {
1883                            table[$value_reg_imm64] = $name_reg_imm64;
1884                        }
1885                    })*
1886
1887                    #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
1888                    #[cold]
1889                    fn invalid_instruction<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, _chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
1890                        state.invalid(offset, length)
1891                    }
1892
1893                    table
1894                };
1895
1896                #[inline]
1897                #[allow(unsafe_code)]
1898                // SAFETY: Here we transmute the lifetimes which were unnecessarily extended to be 'static due to the table here being a `static`.
1899                fn transmute_lifetime<'a>(table: DispatchTable<'static>) -> DispatchTable<'a> {
1900                    unsafe { core::mem::transmute(&$table_name) }
1901                }
1902
1903                transmute_lifetime(DispatchTable(&$table_name))
1904            }};
1905        }
1906
1907        pub use $build_static_dispatch_table;
1908    };
1909}
1910
1911macro_rules! define_extended_instruction_set {
1912    (
1913        ($d:tt)
1914        $isa_name:ident,
1915        $build_static_dispatch_table:ident,
1916
1917        [$($name_argless:ident = [$($length_argless:literal: $value_argless:expr),+],)+]
1918        [$($name_reg_imm:ident = [$($length_reg_imm:literal: $value_reg_imm:expr),+],)+]
1919        [$($name_reg_imm_offset:ident = [$($length_reg_imm_offset:literal: $value_reg_imm_offset:expr),+],)+]
1920        [$($name_reg_imm_imm:ident = [$($length_reg_imm_imm:literal: $value_reg_imm_imm:expr),+],)+]
1921        [$($name_reg_reg_imm:ident = [$($length_reg_reg_imm:literal: $value_reg_reg_imm:expr),+],)+]
1922        [$($name_reg_reg_offset:ident = [$($length_reg_reg_offset:literal: $value_reg_reg_offset:expr),+],)+]
1923        [$($name_reg_reg_reg:ident = [$($length_reg_reg_reg:literal: $value_reg_reg_reg:expr),+],)+]
1924        [$($name_offset:ident = [$($length_offset:literal: $value_offset:expr),+],)+]
1925        [$($name_imm:ident = [$($length_imm:literal: $value_imm:expr),+],)+]
1926        [$($name_imm_imm:ident = [$($length_imm_imm:literal: $value_imm_imm:expr),+],)+]
1927        [$($name_reg_reg:ident = [$($length_reg_reg:literal: $value_reg_reg:expr),+],)+]
1928        [$($name_reg_reg_imm_imm:ident = [$($length_reg_reg_imm_imm:literal: $value_reg_reg_imm_imm:expr),+],)+]
1929        [$($name_reg_imm64:ident = [$($length_reg_imm64:literal: $value_reg_imm64:expr),*],)*]
1930    ) => {
1931        #[allow(non_camel_case_types)]
1932        #[derive(Copy, Clone, Debug, Default)]
1933        pub struct $isa_name;
1934
1935        macro_rules! extended_for_each_entry {
1936            ($d callback:ident) => {
1937                $($( $d callback!($name_argless, $value_argless, $length_argless); )+)+
1938                $($( $d callback!($name_reg_imm, $value_reg_imm, $length_reg_imm); )+)+
1939                $($( $d callback!($name_reg_imm_offset, $value_reg_imm_offset, $length_reg_imm_offset); )+)+
1940                $($( $d callback!($name_reg_imm_imm, $value_reg_imm_imm, $length_reg_imm_imm); )+)+
1941                $($( $d callback!($name_reg_reg_imm, $value_reg_reg_imm, $length_reg_reg_imm); )+)+
1942                $($( $d callback!($name_reg_reg_offset, $value_reg_reg_offset, $length_reg_reg_offset); )+)+
1943                $($( $d callback!($name_reg_reg_reg, $value_reg_reg_reg, $length_reg_reg_reg); )+)+
1944                $($( $d callback!($name_offset, $value_offset, $length_offset); )+)+
1945                $($( $d callback!($name_imm, $value_imm, $length_imm); )+)+
1946                $($( $d callback!($name_imm_imm, $value_imm_imm, $length_imm_imm); )+)+
1947                $($( $d callback!($name_reg_reg, $value_reg_reg, $length_reg_reg); )+)+
1948                $($( $d callback!($name_reg_reg_imm_imm, $value_reg_reg_imm_imm, $length_reg_reg_imm_imm); )+)+
1949                $($( $d callback!($name_reg_imm64, $value_reg_imm64, $length_reg_imm64); )*)*
1950            }
1951        }
1952
1953        impl $isa_name {
1954            #[doc(hidden)]
1955            pub const RAW_OPCODE_TO_ENUM_CONST: [Option<Opcode>; EXTENDED_RAW_OPCODE_COUNT] = {
1956                let mut map = [None; EXTENDED_RAW_OPCODE_COUNT];
1957                macro_rules! set {
1958                    ($entry_name:ident, $value:expr, $args_length:expr) => {
1959                        assert!($value < EXTENDED_INVALID_RAW_OPCODE);
1960                        #[allow(unused_comparisons)]
1961                        {
1962                            assert!($args_length <= EXTENDED_MAX_ARGS_LENGTH);
1963                        }
1964                        assert!(map[$value].is_none(), "duplicate opcode byte value");
1965                        map[$value] = Some(Opcode::$entry_name);
1966                    };
1967                }
1968                extended_for_each_entry!(set);
1969                map
1970            };
1971
1972            #[doc(hidden)]
1973            pub const RAW_OPCODE_STARTS_NEW_BASIC_BLOCK_CONST: [bool; EXTENDED_RAW_OPCODE_COUNT] = {
1974                let mut map = [true; EXTENDED_RAW_OPCODE_COUNT];
1975                macro_rules! set {
1976                    ($entry_name:ident, $value:expr, $args_length:expr) => {
1977                        map[$value] = Opcode::$entry_name.starts_new_basic_block();
1978                    };
1979                }
1980                extended_for_each_entry!(set);
1981                map
1982            };
1983
1984            #[doc(hidden)]
1985            pub const RAW_OPCODE_TO_LENGTH_CONST: [RawOpcodeLength; EXTENDED_RAW_OPCODE_COUNT] = {
1986                let mut map = [RawOpcodeLength(0_u8); EXTENDED_RAW_OPCODE_COUNT];
1987                let mut index = 0;
1988                while index < map.len() {
1989                    map[index].0 = 1;
1990                    if index >= 255 {
1991                        map[index].0 += 1;
1992                    }
1993                    index += 1;
1994                }
1995
1996                macro_rules! set {
1997                    ($entry_name:ident, $raw_opcode:expr, $args_length:expr) => {
1998                        let mut length = $args_length as u8 + 1;
1999                        if $raw_opcode >= 255 {
2000                            length += 1;
2001                        }
2002                        map[$raw_opcode].0 = length;
2003                    };
2004                }
2005                extended_for_each_entry!(set);
2006                map
2007            };
2008
2009            #[doc(hidden)]
2010            pub const OPCODE_AND_LENGTH_TO_RAW_OPCODE_CONST: [[RawOpcodeEntry; EXTENDED_MAX_ARGS_LENGTH + 1]; 256] = {
2011                let mut map = [[RawOpcodeEntry::empty(); EXTENDED_MAX_ARGS_LENGTH + 1]; 256];
2012                macro_rules! set {
2013                    ($entry_name:ident, $raw_opcode:expr, $args_length:expr) => {
2014                        let args_length: u16 = $args_length;
2015                        let discriminant = Opcode::$entry_name.discriminant() as usize;
2016                        let entry = &mut map[discriminant];
2017                        entry[args_length as usize] = RawOpcodeEntry::new($raw_opcode as u16, args_length);
2018
2019                        let mut args_length_subset = 0;
2020                        while args_length_subset < args_length {
2021                            if entry[args_length_subset as usize].is_empty() {
2022                                entry[args_length_subset as usize] = RawOpcodeEntry::new($raw_opcode as u16, args_length);
2023                            }
2024                            args_length_subset += 1;
2025                        }
2026                    };
2027                }
2028                extended_for_each_entry!(set);
2029                map
2030            };
2031
2032            #[doc(hidden)]
2033            pub const OPCODE_IS_SUPPORTED_CONST: [bool; 256] = {
2034                let mut map = [false; 256];
2035                macro_rules! set {
2036                    ($entry_name:ident, $raw_opcode:expr, $args_length:expr) => {
2037                        map[Opcode::$entry_name.discriminant() as usize] = true;
2038                    };
2039                }
2040                extended_for_each_entry!(set);
2041                map
2042            };
2043        }
2044
2045        impl InstructionSet for $isa_name {
2046            #[inline]
2047            fn is_legacy(self) -> bool {
2048                false
2049            }
2050
2051            #[cfg_attr(feature = "alloc", inline)]
2052            fn opcode_from_raw(self, raw_opcode: u32) -> Option<Opcode> {
2053                static RAW_OPCODE_TO_ENUM: [Option<Opcode>; EXTENDED_RAW_OPCODE_COUNT] = $isa_name::RAW_OPCODE_TO_ENUM_CONST;
2054                *RAW_OPCODE_TO_ENUM.get(raw_opcode as usize)?
2055            }
2056
2057            #[cfg_attr(feature = "alloc", inline)]
2058            fn opcode_to_raw(self, opcode: Opcode, args_length: u32) -> Option<(u32, u32)> {
2059                static OPCODE_AND_LENGTH_TO_RAW_OPCODE: [[RawOpcodeEntry; EXTENDED_MAX_ARGS_LENGTH + 1]; 256] = $isa_name::OPCODE_AND_LENGTH_TO_RAW_OPCODE_CONST;
2060                let entry = *OPCODE_AND_LENGTH_TO_RAW_OPCODE[opcode.discriminant() as usize].get(args_length as usize)?;
2061                if entry.is_empty() {
2062                    None
2063                } else {
2064                    Some((u32::from(entry.raw_opcode()), u32::from(entry.args_length())))
2065                }
2066            }
2067
2068            #[cfg_attr(feature = "alloc", inline)]
2069            fn supports_opcode(self, opcode: Opcode) -> bool {
2070                static OPCODE_IS_SUPPORTED: [bool; 256] = $isa_name::OPCODE_IS_SUPPORTED_CONST;
2071                OPCODE_IS_SUPPORTED[opcode.discriminant() as usize]
2072            }
2073
2074            #[cfg_attr(feature = "alloc", inline)]
2075            fn raw_opcode_table(self) -> &'static RawOpcodeTable {
2076                static RAW_OPCODE_TABLE: RawOpcodeTable = RawOpcodeTable {
2077                    length_table: $isa_name::RAW_OPCODE_TO_LENGTH_CONST,
2078                    starts_new_basic_block_table: $isa_name::RAW_OPCODE_STARTS_NEW_BASIC_BLOCK_CONST,
2079                };
2080
2081                &RAW_OPCODE_TABLE
2082            }
2083
2084            fn parse_instruction(self, raw_opcode: usize, chunk: u128, offset: u32, length: u32) -> Instruction {
2085                macro_rules! args {
2086                    ($name:ident($d($arg:ident),+)) => {
2087                        if raw_opcode >= 255 {
2088                            $crate::program::$name::<true>($d($arg),+)
2089                        } else {
2090                            $crate::program::$name::<false>($d($arg),+)
2091                        }
2092                    }
2093                }
2094
2095                match raw_opcode {
2096                    $(
2097                        $($value_argless)|+ => Instruction::$name_argless,
2098                    )+
2099                    $(
2100                        $($value_reg_imm)|+ => {
2101                            let (reg, imm) = args!(read_args_reg_imm(chunk, length));
2102                            Instruction::$name_reg_imm(reg, imm)
2103                        },
2104                    )+
2105                    $(
2106                        $($value_reg_imm_offset)|+ => {
2107                            let (reg, imm1, imm2) = args!(read_args_reg_imm_offset(chunk, offset, length));
2108                            Instruction::$name_reg_imm_offset(reg, imm1, imm2)
2109                        },
2110                    )+
2111                    $(
2112                        $($value_reg_imm_imm)|+ => {
2113                            let (reg, imm1, imm2) = args!(read_args_reg_imm2(chunk, length));
2114                            Instruction::$name_reg_imm_imm(reg, imm1, imm2)
2115                        },
2116                    )+
2117                    $(
2118                        $($value_reg_reg_imm)|+ => {
2119                            let (reg1, reg2, imm) = args!(read_args_regs2_imm(chunk, length));
2120                            Instruction::$name_reg_reg_imm(reg1, reg2, imm)
2121                        }
2122                    )+
2123                    $(
2124                        $($value_reg_reg_offset)|+ => {
2125                            let (reg1, reg2, imm) = args!(read_args_regs2_offset(chunk, offset, length));
2126                            Instruction::$name_reg_reg_offset(reg1, reg2, imm)
2127                        }
2128                    )+
2129                    $(
2130                        $($value_reg_reg_reg)|+ => {
2131                            let (reg1, reg2, reg3) = args!(read_args_regs3(chunk));
2132                            Instruction::$name_reg_reg_reg(reg1, reg2, reg3)
2133                        }
2134                    )+
2135                    $(
2136                        $($value_offset)|+ => {
2137                            let imm = args!(read_args_offset(chunk, offset, length));
2138                            Instruction::$name_offset(imm)
2139                        }
2140                    )+
2141                    $(
2142                        $($value_imm)|+ => {
2143                            let imm = args!(read_args_imm(chunk, length));
2144                            Instruction::$name_imm(imm)
2145                        }
2146                    )+
2147                    $(
2148                        $($value_imm_imm)|+ => {
2149                            let (imm1, imm2) = args!(read_args_imm2(chunk, length));
2150                            Instruction::$name_imm_imm(imm1, imm2)
2151                        }
2152                    )+
2153                    $(
2154                        $($value_reg_reg)|+ => {
2155                            let (reg1, reg2) = args!(read_args_regs2(chunk));
2156                            Instruction::$name_reg_reg(reg1, reg2)
2157                        }
2158                    )+
2159                    $(
2160                        $($value_reg_reg_imm_imm)|+ => {
2161                            let (reg1, reg2, imm1, imm2) = args!(read_args_regs2_imm2(chunk, length));
2162                            Instruction::$name_reg_reg_imm_imm(reg1, reg2, imm1, imm2)
2163                        }
2164                    )+
2165                    $(
2166                        $($value_reg_imm64)|+ => {
2167                            let (reg, imm) = args!(read_args_reg_imm64(chunk));
2168                            Instruction::$name_reg_imm64(reg, imm)
2169                        }
2170                    )*
2171                    _ => Instruction::invalid,
2172                }
2173            }
2174        }
2175
2176        #[macro_export]
2177        macro_rules! $build_static_dispatch_table {
2178            ($table_name:ident, $visitor_ty:ident<$d($visitor_ty_params:tt),*>) => {{
2179                use $crate::program::{
2180                    EXTENDED_RAW_OPCODE_COUNT,
2181                    ParsingVisitor
2182                };
2183
2184                type ReturnTy<$d($visitor_ty_params),*> = <$visitor_ty<$d($visitor_ty_params),*> as ParsingVisitor>::ReturnTy;
2185                type VisitFn<$d($visitor_ty_params),*> = fn(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32);
2186
2187                #[derive(Copy, Clone)]
2188                struct DispatchTable<'a>(&'a [VisitFn<'a>; EXTENDED_RAW_OPCODE_COUNT]);
2189
2190                impl<'a> $crate::program::OpcodeVisitor for DispatchTable<'a> {
2191                    type State = $visitor_ty<'a>;
2192                    type ReturnTy = ();
2193                    type InstructionSet = $crate::program::$isa_name;
2194
2195                    #[inline]
2196                    fn instruction_set(self) -> Self::InstructionSet {
2197                        $crate::program::$isa_name
2198                    }
2199
2200                    #[inline]
2201                    fn dispatch(self, state: &mut $visitor_ty<'a>, opcode: usize, chunk: u128, offset: u32, length: u32) {
2202                        self.0[opcode](state, chunk, offset, length)
2203                    }
2204                }
2205
2206                static $table_name: [VisitFn; EXTENDED_RAW_OPCODE_COUNT] = {
2207                    let mut table = [invalid_instruction as VisitFn; EXTENDED_RAW_OPCODE_COUNT];
2208
2209                    $({
2210                        // Putting all of the handlers in a single link section can make a big difference
2211                        // when it comes to performance, even up to 10% in some cases. This will force the
2212                        // compiler and the linker to put all of this code near each other, minimizing
2213                        // instruction cache misses.
2214                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2215                        fn $name_argless<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, _chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2216                            state.$name_argless(offset, length)
2217                        }
2218
2219                        $(table[$value_argless] = $name_argless;)+
2220                    })*
2221
2222                    $({
2223                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2224                        fn $name_reg_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2225                            let (reg, imm) = $crate::program::read_args_reg_imm::<EXT>(chunk, length);
2226                            state.$name_reg_imm(offset, length, reg, imm)
2227                        }
2228
2229                        $(table[$value_reg_imm] = $name_reg_imm::<{ ($value_reg_imm) >= 255 }>;)+
2230                    })*
2231
2232
2233                    $({
2234                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2235                        fn $name_reg_imm_offset<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2236                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm_offset::<EXT>(chunk, offset, length);
2237                            state.$name_reg_imm_offset(offset, length, reg, imm1, imm2)
2238                        }
2239
2240                        $(table[$value_reg_imm_offset] = $name_reg_imm_offset::<{ ($value_reg_imm_offset) >= 255 }>;)+
2241                    })*
2242
2243
2244                    $({
2245                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2246                        fn $name_reg_imm_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2247                            let (reg, imm1, imm2) = $crate::program::read_args_reg_imm2::<EXT>(chunk, length);
2248                            state.$name_reg_imm_imm(offset, length, reg, imm1, imm2)
2249                        }
2250
2251                        $(table[$value_reg_imm_imm] = $name_reg_imm_imm::<{ ($value_reg_imm_imm) >= 255 }>;)+
2252                    })*
2253
2254
2255                    $({
2256                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2257                        fn $name_reg_reg_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2258                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_imm::<EXT>(chunk, length);
2259                            state.$name_reg_reg_imm(offset, length, reg1, reg2, imm)
2260                        }
2261
2262                        $(table[$value_reg_reg_imm] = $name_reg_reg_imm::<{ ($value_reg_reg_imm) >= 255 }>;)+
2263                    })*
2264
2265
2266                    $({
2267                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2268                        fn $name_reg_reg_offset<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2269                            let (reg1, reg2, imm) = $crate::program::read_args_regs2_offset::<EXT>(chunk, offset, length);
2270                            state.$name_reg_reg_offset(offset, length, reg1, reg2, imm)
2271                        }
2272
2273                        $(table[$value_reg_reg_offset] = $name_reg_reg_offset::<{ ($value_reg_reg_offset) >= 255 }>;)+
2274                    })*
2275
2276
2277                    $({
2278                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2279                        fn $name_reg_reg_reg<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2280                            let (reg1, reg2, reg3) = $crate::program::read_args_regs3::<EXT>(chunk);
2281                            state.$name_reg_reg_reg(offset, length, reg1, reg2, reg3)
2282                        }
2283
2284                        $(table[$value_reg_reg_reg] = $name_reg_reg_reg::<{ ($value_reg_reg_reg) >= 255 }>;)+
2285                    })*
2286
2287
2288                    $({
2289                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2290                        fn $name_offset<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2291                            let imm = $crate::program::read_args_offset::<EXT>(chunk, offset, length);
2292                            state.$name_offset(offset, length, imm)
2293                        }
2294
2295                        $(table[$value_offset] = $name_offset::<{ ($value_offset) >= 255 }>;)+
2296                    })*
2297
2298
2299                    $({
2300                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2301                        fn $name_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2302                            let imm = $crate::program::read_args_imm::<EXT>(chunk, length);
2303                            state.$name_imm(offset, length, imm)
2304                        }
2305
2306                        $(table[$value_imm] = $name_imm::<{ ($value_imm) >= 255 }>;)+
2307                    })*
2308
2309
2310                    $({
2311                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2312                        fn $name_imm_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2313                            let (imm1, imm2) = $crate::program::read_args_imm2::<EXT>(chunk, length);
2314                            state.$name_imm_imm(offset, length, imm1, imm2)
2315                        }
2316
2317                        $(table[$value_imm_imm] = $name_imm_imm::<{ ($value_imm_imm) >= 255 }>;)+
2318                    })*
2319
2320
2321                    $({
2322                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2323                        fn $name_reg_reg<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2324                            let (reg1, reg2) = $crate::program::read_args_regs2::<EXT>(chunk);
2325                            state.$name_reg_reg(offset, length, reg1, reg2)
2326                        }
2327
2328                        $(table[$value_reg_reg] = $name_reg_reg::<{ ($value_reg_reg) >= 255 }>;)+
2329                    })*
2330
2331
2332                    $({
2333                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2334                        fn $name_reg_reg_imm_imm<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2335                            let (reg1, reg2, imm1, imm2) = $crate::program::read_args_regs2_imm2::<EXT>(chunk, length);
2336                            state.$name_reg_reg_imm_imm(offset, length, reg1, reg2, imm1, imm2)
2337                        }
2338
2339                        $(table[$value_reg_reg_imm_imm] = $name_reg_reg_imm_imm::<{ ($value_reg_reg_imm_imm) >= 255 }>;)+
2340                    })*
2341
2342
2343                    $({
2344                        #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2345                        fn $name_reg_imm64<$d($visitor_ty_params),*, const EXT: bool>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2346                            let (reg, imm) = $crate::program::read_args_reg_imm64::<EXT>(chunk);
2347                            state.$name_reg_imm64(offset, length, reg, imm)
2348                        }
2349
2350                        $(table[$value_reg_imm64] = $name_reg_imm64::<{ ($value_reg_imm64) >= 255 }>;)*
2351                    })*
2352
2353
2354                    #[cfg_attr(target_os = "linux", link_section = concat!(".text.", stringify!($table_name)))]
2355                    #[cold]
2356                    fn invalid_instruction<$d($visitor_ty_params),*>(state: &mut $visitor_ty<$d($visitor_ty_params),*>, _chunk: u128, offset: u32, length: u32) -> ReturnTy<$d($visitor_ty_params),*>{
2357                        state.invalid(offset, length)
2358                    }
2359
2360                    table
2361                };
2362
2363                #[inline]
2364                #[allow(unsafe_code)]
2365                // SAFETY: Here we transmute the lifetimes which were unnecessarily extended to be 'static due to the table here being a `static`.
2366                fn transmute_lifetime<'a>(table: DispatchTable<'static>) -> DispatchTable<'a> {
2367                    unsafe { core::mem::transmute(&$table_name) }
2368                }
2369
2370                transmute_lifetime(DispatchTable(&$table_name))
2371            }};
2372        }
2373
2374        pub use $build_static_dispatch_table;
2375    };
2376}
2377
2378#[inline]
2379fn parse_instruction_legacy<I>(instruction_set: I, code: &[u8], bitmask: &[u8], offset: u32) -> (u32, Instruction, bool)
2380where
2381    I: InstructionSet,
2382{
2383    let visitor = EnumVisitor { instruction_set };
2384    if offset as usize + 32 <= code.len() {
2385        visitor_step_fast_legacy(&mut (), code, bitmask, offset, visitor)
2386    } else {
2387        visitor_step_slow_legacy(&mut (), code, bitmask, offset, visitor)
2388    }
2389}
2390
2391const LEGACY_INVALID_RAW_OPCODE: u32 = 256;
2392
2393#[doc(hidden)]
2394pub const LEGACY_RAW_OPCODE_COUNT: usize = 257;
2395
2396define_all_instructions! {
2397    // Instructions with args: none
2398    [
2399        trap,
2400        fallthrough,
2401        memset,
2402        unlikely,
2403    ]
2404
2405    // Instructions with args: reg, imm
2406    [
2407        jump_indirect,
2408        load_imm,
2409        load_u8,
2410        load_i8,
2411        load_u16,
2412        load_i16,
2413        load_i32,
2414        load_u32,
2415        load_u64,
2416        store_u8,
2417        store_u16,
2418        store_u32,
2419        store_u64,
2420    ]
2421
2422    // Instructions with args: reg, imm, offset
2423    [
2424        load_imm_and_jump,
2425        branch_eq_imm,
2426        branch_not_eq_imm,
2427        branch_less_unsigned_imm,
2428        branch_less_signed_imm,
2429        branch_greater_or_equal_unsigned_imm,
2430        branch_greater_or_equal_signed_imm,
2431        branch_less_or_equal_signed_imm,
2432        branch_less_or_equal_unsigned_imm,
2433        branch_greater_signed_imm,
2434        branch_greater_unsigned_imm,
2435    ]
2436
2437    // Instructions with args: reg, imm, imm
2438    [
2439        store_imm_indirect_u8,
2440        store_imm_indirect_u16,
2441        store_imm_indirect_u32,
2442        store_imm_indirect_u64,
2443    ]
2444
2445    // Instructions with args: reg, reg, imm
2446    [
2447        store_indirect_u8,
2448        store_indirect_u16,
2449        store_indirect_u32,
2450        store_indirect_u64,
2451        load_indirect_u8,
2452        load_indirect_i8,
2453        load_indirect_u16,
2454        load_indirect_i16,
2455        load_indirect_i32,
2456        load_indirect_u32,
2457        load_indirect_u64,
2458        add_imm_32,
2459        add_imm_64,
2460        and_imm,
2461        xor_imm,
2462        or_imm,
2463        mul_imm_32,
2464        mul_imm_64,
2465        set_less_than_unsigned_imm,
2466        set_less_than_signed_imm,
2467        shift_logical_left_imm_32,
2468        shift_logical_left_imm_64,
2469        shift_logical_right_imm_32,
2470        shift_logical_right_imm_64,
2471        shift_arithmetic_right_imm_32,
2472        shift_arithmetic_right_imm_64,
2473        negate_and_add_imm_32,
2474        negate_and_add_imm_64,
2475        set_greater_than_unsigned_imm,
2476        set_greater_than_signed_imm,
2477        shift_logical_right_imm_alt_32,
2478        shift_logical_right_imm_alt_64,
2479        shift_arithmetic_right_imm_alt_32,
2480        shift_arithmetic_right_imm_alt_64,
2481        shift_logical_left_imm_alt_32,
2482        shift_logical_left_imm_alt_64,
2483
2484        cmov_if_zero_imm,
2485        cmov_if_not_zero_imm,
2486
2487        rotate_right_imm_32,
2488        rotate_right_imm_alt_32,
2489        rotate_right_imm_64,
2490        rotate_right_imm_alt_64,
2491    ]
2492
2493    // Instructions with args: reg, reg, offset
2494    [
2495        branch_eq,
2496        branch_not_eq,
2497        branch_less_unsigned,
2498        branch_less_signed,
2499        branch_greater_or_equal_unsigned,
2500        branch_greater_or_equal_signed,
2501    ]
2502
2503    // Instructions with args: reg, reg, reg
2504    [
2505        add_32,
2506        add_64,
2507        sub_32,
2508        sub_64,
2509        and,
2510        xor,
2511        or,
2512        mul_32,
2513        mul_64,
2514        mul_upper_signed_signed,
2515        mul_upper_unsigned_unsigned,
2516        mul_upper_signed_unsigned,
2517        set_less_than_unsigned,
2518        set_less_than_signed,
2519        shift_logical_left_32,
2520        shift_logical_left_64,
2521        shift_logical_right_32,
2522        shift_logical_right_64,
2523        shift_arithmetic_right_32,
2524        shift_arithmetic_right_64,
2525        div_unsigned_32,
2526        div_unsigned_64,
2527        div_signed_32,
2528        div_signed_64,
2529        rem_unsigned_32,
2530        rem_unsigned_64,
2531        rem_signed_32,
2532        rem_signed_64,
2533
2534        cmov_if_zero,
2535        cmov_if_not_zero,
2536
2537        and_inverted,
2538        or_inverted,
2539        xnor,
2540        maximum,
2541        maximum_unsigned,
2542        minimum,
2543        minimum_unsigned,
2544        rotate_left_32,
2545        rotate_left_64,
2546        rotate_right_32,
2547        rotate_right_64,
2548    ]
2549
2550    // Instructions with args: offset
2551    [
2552        jump,
2553    ]
2554
2555    // Instructions with args: imm
2556    [
2557        ecalli,
2558    ]
2559
2560    // Instructions with args: imm, imm
2561    [
2562        store_imm_u8,
2563        store_imm_u16,
2564        store_imm_u32,
2565        store_imm_u64,
2566    ]
2567
2568    // Instructions with args: reg, reg
2569    [
2570        move_reg,
2571        sbrk,
2572        count_leading_zero_bits_32,
2573        count_leading_zero_bits_64,
2574        count_trailing_zero_bits_32,
2575        count_trailing_zero_bits_64,
2576        count_set_bits_32,
2577        count_set_bits_64,
2578        sign_extend_8,
2579        sign_extend_16,
2580        zero_extend_16,
2581        reverse_byte,
2582    ]
2583
2584    // Instructions with args: reg, reg, imm, imm
2585    [
2586        load_imm_and_jump_indirect,
2587    ]
2588
2589    // Instruction with args: reg, imm64
2590    [
2591        load_imm64,
2592    ]
2593}
2594
2595define_legacy_instruction_set! {
2596    ($)
2597
2598    ISA_ReviveV1,
2599    build_static_dispatch_table_revive_v1,
2600
2601    [
2602        trap                                     = 0,
2603        fallthrough                              = 1,
2604        // MISSING: memset
2605        // MISSING: unlikely
2606    ]
2607    [
2608        jump_indirect                            = 50,
2609        load_imm                                 = 51,
2610        load_u8                                  = 52,
2611        load_i8                                  = 53,
2612        load_u16                                 = 54,
2613        load_i16                                 = 55,
2614        load_i32                                 = 57,
2615        load_u32                                 = 56,
2616        load_u64                                 = 58,
2617        store_u8                                 = 59,
2618        store_u16                                = 60,
2619        store_u32                                = 61,
2620        store_u64                                = 62,
2621    ]
2622    [
2623        load_imm_and_jump                        = 80,
2624        branch_eq_imm                            = 81,
2625        branch_not_eq_imm                        = 82,
2626        branch_less_unsigned_imm                 = 83,
2627        branch_less_signed_imm                   = 87,
2628        branch_greater_or_equal_unsigned_imm     = 85,
2629        branch_greater_or_equal_signed_imm       = 89,
2630        branch_less_or_equal_signed_imm          = 88,
2631        branch_less_or_equal_unsigned_imm        = 84,
2632        branch_greater_signed_imm                = 90,
2633        branch_greater_unsigned_imm              = 86,
2634    ]
2635    [
2636        store_imm_indirect_u8                    = 70,
2637        store_imm_indirect_u16                   = 71,
2638        store_imm_indirect_u32                   = 72,
2639        store_imm_indirect_u64                   = 73,
2640    ]
2641    [
2642        store_indirect_u8                        = 120,
2643        store_indirect_u16                       = 121,
2644        store_indirect_u32                       = 122,
2645        store_indirect_u64                       = 123,
2646        load_indirect_u8                         = 124,
2647        load_indirect_i8                         = 125,
2648        load_indirect_u16                        = 126,
2649        load_indirect_i16                        = 127,
2650        load_indirect_i32                        = 129,
2651        load_indirect_u32                        = 128,
2652        load_indirect_u64                        = 130,
2653        add_imm_32                               = 131,
2654        add_imm_64                               = 149,
2655        and_imm                                  = 132,
2656        xor_imm                                  = 133,
2657        or_imm                                   = 134,
2658        mul_imm_32                               = 135,
2659        mul_imm_64                               = 150,
2660        set_less_than_unsigned_imm               = 136,
2661        set_less_than_signed_imm                 = 137,
2662        shift_logical_left_imm_32                = 138,
2663        shift_logical_left_imm_64                = 151,
2664        shift_logical_right_imm_32               = 139,
2665        shift_logical_right_imm_64               = 152,
2666        shift_arithmetic_right_imm_32            = 140,
2667        shift_arithmetic_right_imm_64            = 153,
2668        negate_and_add_imm_32                    = 141,
2669        negate_and_add_imm_64                    = 154,
2670        set_greater_than_unsigned_imm            = 142,
2671        set_greater_than_signed_imm              = 143,
2672        shift_logical_right_imm_alt_32           = 145,
2673        shift_logical_right_imm_alt_64           = 156,
2674        shift_arithmetic_right_imm_alt_32        = 146,
2675        shift_arithmetic_right_imm_alt_64        = 157,
2676        shift_logical_left_imm_alt_32            = 144,
2677        shift_logical_left_imm_alt_64            = 155,
2678        cmov_if_zero_imm                         = 147,
2679        cmov_if_not_zero_imm                     = 148,
2680        rotate_right_imm_32                      = 160,
2681        rotate_right_imm_alt_32                  = 161,
2682        rotate_right_imm_64                      = 158,
2683        rotate_right_imm_alt_64                  = 159,
2684    ]
2685    [
2686        branch_eq                                = 170,
2687        branch_not_eq                            = 171,
2688        branch_less_unsigned                     = 172,
2689        branch_less_signed                       = 173,
2690        branch_greater_or_equal_unsigned         = 174,
2691        branch_greater_or_equal_signed           = 175,
2692    ]
2693    [
2694        add_32                                   = 190,
2695        add_64                                   = 200,
2696        sub_32                                   = 191,
2697        sub_64                                   = 201,
2698        and                                      = 210,
2699        xor                                      = 211,
2700        or                                       = 212,
2701        mul_32                                   = 192,
2702        mul_64                                   = 202,
2703        mul_upper_signed_signed                  = 213,
2704        mul_upper_unsigned_unsigned              = 214,
2705        mul_upper_signed_unsigned                = 215,
2706        set_less_than_unsigned                   = 216,
2707        set_less_than_signed                     = 217,
2708        shift_logical_left_32                    = 197,
2709        shift_logical_left_64                    = 207,
2710        shift_logical_right_32                   = 198,
2711        shift_logical_right_64                   = 208,
2712        shift_arithmetic_right_32                = 199,
2713        shift_arithmetic_right_64                = 209,
2714        div_unsigned_32                          = 193,
2715        div_unsigned_64                          = 203,
2716        div_signed_32                            = 194,
2717        div_signed_64                            = 204,
2718        rem_unsigned_32                          = 195,
2719        rem_unsigned_64                          = 205,
2720        rem_signed_32                            = 196,
2721        rem_signed_64                            = 206,
2722        cmov_if_zero                             = 218,
2723        cmov_if_not_zero                         = 219,
2724        and_inverted                             = 224,
2725        or_inverted                              = 225,
2726        xnor                                     = 226,
2727        maximum                                  = 227,
2728        maximum_unsigned                         = 228,
2729        minimum                                  = 229,
2730        minimum_unsigned                         = 230,
2731        rotate_left_32                           = 221,
2732        rotate_left_64                           = 220,
2733        rotate_right_32                          = 223,
2734        rotate_right_64                          = 222,
2735    ]
2736    [
2737        jump                                     = 40,
2738    ]
2739    [
2740        ecalli                                   = 10,
2741    ]
2742    [
2743        store_imm_u8                             = 30,
2744        store_imm_u16                            = 31,
2745        store_imm_u32                            = 32,
2746        store_imm_u64                            = 33,
2747    ]
2748    [
2749        move_reg                                 = 100,
2750        count_leading_zero_bits_32               = 105,
2751        count_leading_zero_bits_64               = 104,
2752        count_trailing_zero_bits_32              = 107,
2753        count_trailing_zero_bits_64              = 106,
2754        count_set_bits_32                        = 103,
2755        count_set_bits_64                        = 102,
2756        sign_extend_8                            = 108,
2757        sign_extend_16                           = 109,
2758        zero_extend_16                           = 110,
2759        reverse_byte                             = 111,
2760    ]
2761    [
2762        load_imm_and_jump_indirect               = 180,
2763    ]
2764    [
2765        load_imm64                               = 20,
2766    ]
2767}
2768
2769define_legacy_instruction_set! {
2770    ($)
2771
2772    ISA_Latest32,
2773    build_static_dispatch_table_latest32,
2774
2775    [
2776        trap                                     = 0,
2777        fallthrough                              = 1,
2778        memset                                   = 2,
2779        unlikely                                 = 3,
2780    ]
2781    [
2782        jump_indirect                            = 50,
2783        load_imm                                 = 51,
2784        load_u8                                  = 52,
2785        load_i8                                  = 53,
2786        load_u16                                 = 54,
2787        load_i16                                 = 55,
2788        load_i32                                 = 57,
2789        store_u8                                 = 59,
2790        store_u16                                = 60,
2791        store_u32                                = 61,
2792    ]
2793    [
2794        load_imm_and_jump                        = 80,
2795        branch_eq_imm                            = 81,
2796        branch_not_eq_imm                        = 82,
2797        branch_less_unsigned_imm                 = 83,
2798        branch_less_signed_imm                   = 87,
2799        branch_greater_or_equal_unsigned_imm     = 85,
2800        branch_greater_or_equal_signed_imm       = 89,
2801        branch_less_or_equal_signed_imm          = 88,
2802        branch_less_or_equal_unsigned_imm        = 84,
2803        branch_greater_signed_imm                = 90,
2804        branch_greater_unsigned_imm              = 86,
2805    ]
2806    [
2807        store_imm_indirect_u8                    = 70,
2808        store_imm_indirect_u16                   = 71,
2809        store_imm_indirect_u32                   = 72,
2810    ]
2811    [
2812        store_indirect_u8                        = 120,
2813        store_indirect_u16                       = 121,
2814        store_indirect_u32                       = 122,
2815        load_indirect_u8                         = 124,
2816        load_indirect_i8                         = 125,
2817        load_indirect_u16                        = 126,
2818        load_indirect_i16                        = 127,
2819        load_indirect_i32                        = 129,
2820        add_imm_32                               = 131,
2821        and_imm                                  = 132,
2822        xor_imm                                  = 133,
2823        or_imm                                   = 134,
2824        mul_imm_32                               = 135,
2825        set_less_than_unsigned_imm               = 136,
2826        set_less_than_signed_imm                 = 137,
2827        shift_logical_left_imm_32                = 138,
2828        shift_logical_right_imm_32               = 139,
2829        shift_arithmetic_right_imm_32            = 140,
2830        negate_and_add_imm_32                    = 141,
2831        set_greater_than_unsigned_imm            = 142,
2832        set_greater_than_signed_imm              = 143,
2833        shift_logical_right_imm_alt_32           = 145,
2834        shift_arithmetic_right_imm_alt_32        = 146,
2835        shift_logical_left_imm_alt_32            = 144,
2836        cmov_if_zero_imm                         = 147,
2837        cmov_if_not_zero_imm                     = 148,
2838        rotate_right_imm_32                      = 160,
2839        rotate_right_imm_alt_32                  = 161,
2840    ]
2841    [
2842        branch_eq                                = 170,
2843        branch_not_eq                            = 171,
2844        branch_less_unsigned                     = 172,
2845        branch_less_signed                       = 173,
2846        branch_greater_or_equal_unsigned         = 174,
2847        branch_greater_or_equal_signed           = 175,
2848    ]
2849    [
2850        add_32                                   = 190,
2851        sub_32                                   = 191,
2852        and                                      = 210,
2853        xor                                      = 211,
2854        or                                       = 212,
2855        mul_32                                   = 192,
2856        mul_upper_signed_signed                  = 213,
2857        mul_upper_unsigned_unsigned              = 214,
2858        mul_upper_signed_unsigned                = 215,
2859        set_less_than_unsigned                   = 216,
2860        set_less_than_signed                     = 217,
2861        shift_logical_left_32                    = 197,
2862        shift_logical_right_32                   = 198,
2863        shift_arithmetic_right_32                = 199,
2864        div_unsigned_32                          = 193,
2865        div_signed_32                            = 194,
2866        rem_unsigned_32                          = 195,
2867        rem_signed_32                            = 196,
2868        cmov_if_zero                             = 218,
2869        cmov_if_not_zero                         = 219,
2870        and_inverted                             = 224,
2871        or_inverted                              = 225,
2872        xnor                                     = 226,
2873        maximum                                  = 227,
2874        maximum_unsigned                         = 228,
2875        minimum                                  = 229,
2876        minimum_unsigned                         = 230,
2877        rotate_left_32                           = 221,
2878        rotate_right_32                          = 223,
2879    ]
2880    [
2881        jump                                     = 40,
2882    ]
2883    [
2884        ecalli                                   = 10,
2885    ]
2886    [
2887        store_imm_u8                             = 30,
2888        store_imm_u16                            = 31,
2889        store_imm_u32                            = 32,
2890    ]
2891    [
2892        move_reg                                 = 100,
2893        sbrk                                     = 101,
2894        count_leading_zero_bits_32               = 105,
2895        count_trailing_zero_bits_32              = 107,
2896        count_set_bits_32                        = 103,
2897        sign_extend_8                            = 108,
2898        sign_extend_16                           = 109,
2899        zero_extend_16                           = 110,
2900        reverse_byte                             = 111,
2901    ]
2902    [
2903        load_imm_and_jump_indirect               = 180,
2904    ]
2905    [
2906    ]
2907}
2908
2909define_extended_instruction_set! {
2910    ($)
2911
2912    ISA_Latest64,
2913    build_static_dispatch_table_latest64,
2914
2915    // argless
2916    [
2917        trap                                     = [0: 0],
2918        fallthrough                              = [0: 1],
2919        memset                                   = [0: 510],
2920        unlikely                                 = [0: 2],
2921    ]
2922    // reg_imm
2923    [
2924        jump_indirect                            = [1: 3, 5: 255],
2925        load_imm                                 = [1: 4, 2: 5, 3: 6, 4: 7, 5: 8],
2926        load_u8                                  = [5: 9],
2927        load_i8                                  = [4: 10, 5: 256],
2928        load_u16                                 = [5: 11],
2929        load_i16                                 = [5: 12],
2930        load_i32                                 = [4: 13, 5: 14],
2931        load_u32                                 = [5: 15],
2932        load_u64                                 = [4: 16, 5: 17],
2933        store_u8                                 = [5: 18],
2934        store_u16                                = [5: 19],
2935        store_u32                                = [5: 20],
2936        store_u64                                = [4: 21, 5: 22],
2937    ]
2938    // reg_imm_offset
2939    [
2940        load_imm_and_jump                        = [4: 23, 5: 24, 6: 25, 7: 26, 8: 27, 9: 257],
2941        branch_eq_imm                            = [2: 28, 3: 29, 4: 30, 5: 31, 6: 32, 9: 33],
2942        branch_not_eq_imm                        = [2: 34, 3: 35, 4: 36, 6: 37, 9: 258],
2943        branch_less_unsigned_imm                 = [3: 38, 4: 39, 5: 40, 9: 41],
2944        branch_less_signed_imm                   = [2: 42, 3: 43, 4: 44, 9: 45],
2945        branch_greater_or_equal_unsigned_imm     = [3: 46, 4: 47, 5: 48, 9: 259],
2946        branch_greater_or_equal_signed_imm       = [2: 49, 3: 50, 9: 51],
2947        branch_less_or_equal_signed_imm          = [2: 52, 3: 53, 6: 54, 9: 260],
2948        branch_less_or_equal_unsigned_imm        = [3: 55, 4: 56, 6: 57, 9: 261],
2949        branch_greater_signed_imm                = [3: 58, 4: 59, 5: 60, 9: 61],
2950        branch_greater_unsigned_imm              = [3: 62, 4: 63, 5: 64, 9: 65],
2951    ]
2952    // reg_imm_imm
2953    [
2954        store_imm_indirect_u8                    = [1: 66, 2: 67, 3: 68, 4: 69, 5: 70, 9: 262],
2955        store_imm_indirect_u16                   = [2: 71, 3: 72, 4: 73, 5: 74, 9: 263],
2956        store_imm_indirect_u32                   = [1: 75, 2: 76, 3: 77, 4: 78, 6: 79, 9: 80],
2957        store_imm_indirect_u64                   = [1: 81, 2: 82, 3: 83, 4: 84, 5: 85, 6: 86, 7: 87, 9: 264],
2958    ]
2959    // reg_reg_imm
2960    [
2961        store_indirect_u8                        = [1: 88, 2: 89, 3: 90, 5: 265],
2962        store_indirect_u16                       = [1: 91, 2: 92, 3: 93, 5: 266],
2963        store_indirect_u32                       = [1: 94, 2: 95, 3: 96, 5: 267],
2964        store_indirect_u64                       = [1: 97, 2: 98, 3: 99, 5: 268],
2965        load_indirect_u8                         = [1: 100, 2: 101, 3: 102, 5: 269],
2966        load_indirect_i8                         = [1: 103, 2: 104, 3: 105, 5: 270],
2967        load_indirect_u16                        = [1: 106, 2: 107, 3: 108, 5: 271],
2968        load_indirect_i16                        = [1: 109, 2: 110, 3: 111, 5: 272],
2969        load_indirect_i32                        = [1: 112, 2: 113, 3: 114, 5: 273],
2970        load_indirect_u32                        = [1: 115, 2: 116, 3: 117, 5: 274],
2971        load_indirect_u64                        = [1: 118, 2: 119, 3: 120, 5: 275],
2972        add_imm_32                               = [1: 121, 2: 122, 3: 123, 5: 124],
2973        add_imm_64                               = [2: 125, 3: 126, 4: 127, 5: 128],
2974        and_imm                                  = [2: 129, 3: 130, 5: 131],
2975        xor_imm                                  = [2: 132, 3: 133, 5: 134],
2976        or_imm                                   = [2: 135, 3: 136, 5: 137],
2977        mul_imm_32                               = [5: 138],
2978        mul_imm_64                               = [2: 139, 3: 140, 5: 141],
2979        set_less_than_unsigned_imm               = [2: 142, 3: 143, 5: 144],
2980        set_less_than_signed_imm                 = [1: 145, 2: 146, 5: 276],
2981        shift_logical_left_imm_32                = [2: 147, 5: 277],
2982        shift_logical_left_imm_64                = [2: 148, 5: 278],
2983        shift_logical_right_imm_32               = [2: 149, 5: 279],
2984        shift_logical_right_imm_64               = [2: 150, 5: 280],
2985        shift_arithmetic_right_imm_32            = [2: 151, 5: 281],
2986        shift_arithmetic_right_imm_64            = [2: 152, 5: 282],
2987        negate_and_add_imm_32                    = [1: 153, 3: 154, 5: 283],
2988        negate_and_add_imm_64                    = [1: 155, 2: 156, 5: 157],
2989        set_greater_than_unsigned_imm            = [1: 158, 5: 159],
2990        set_greater_than_signed_imm              = [1: 160, 5: 284],
2991        shift_logical_right_imm_alt_32           = [5: 285],
2992        shift_logical_right_imm_alt_64           = [2: 161, 5: 162],
2993        shift_arithmetic_right_imm_alt_32        = [5: 286],
2994        shift_arithmetic_right_imm_alt_64        = [5: 287],
2995        shift_logical_left_imm_alt_32            = [5: 163],
2996        shift_logical_left_imm_alt_64            = [2: 164, 5: 288],
2997        cmov_if_zero_imm                         = [1: 165, 2: 166, 5: 167],
2998        cmov_if_not_zero_imm                     = [1: 168, 2: 169, 5: 170],
2999        rotate_right_imm_32                      = [2: 171, 5: 289],
3000        rotate_right_imm_alt_32                  = [5: 290],
3001        rotate_right_imm_64                      = [2: 172, 5: 291],
3002        rotate_right_imm_alt_64                  = [5: 292],
3003    ]
3004    // reg_reg_offset
3005    [
3006        branch_eq                                = [2: 173, 3: 174, 5: 175],
3007        branch_not_eq                            = [2: 176, 3: 177, 5: 178],
3008        branch_less_unsigned                     = [2: 179, 3: 180, 5: 293],
3009        branch_less_signed                       = [2: 181, 3: 182, 5: 294],
3010        branch_greater_or_equal_unsigned         = [2: 183, 3: 184, 5: 295],
3011        branch_greater_or_equal_signed           = [2: 185, 3: 186, 5: 296],
3012    ]
3013    // reg_reg_reg
3014    [
3015        add_32                                   = [2: 187],
3016        add_64                                   = [2: 188],
3017        sub_32                                   = [2: 189],
3018        sub_64                                   = [2: 190],
3019        and                                      = [2: 191],
3020        xor                                      = [2: 192],
3021        or                                       = [2: 193],
3022        mul_32                                   = [2: 194],
3023        mul_64                                   = [2: 195],
3024        mul_upper_signed_signed                  = [2: 297],
3025        mul_upper_unsigned_unsigned              = [2: 196],
3026        mul_upper_signed_unsigned                = [2: 298],
3027        set_less_than_unsigned                   = [2: 197],
3028        set_less_than_signed                     = [2: 198],
3029        shift_logical_left_32                    = [2: 199],
3030        shift_logical_left_64                    = [2: 200],
3031        shift_logical_right_32                   = [2: 201],
3032        shift_logical_right_64                   = [2: 202],
3033        shift_arithmetic_right_32                = [2: 299],
3034        shift_arithmetic_right_64                = [2: 300],
3035        div_unsigned_32                          = [2: 203],
3036        div_unsigned_64                          = [2: 204],
3037        div_signed_32                            = [2: 205],
3038        div_signed_64                            = [2: 301],
3039        rem_unsigned_32                          = [2: 206],
3040        rem_unsigned_64                          = [2: 207],
3041        rem_signed_32                            = [2: 208],
3042        rem_signed_64                            = [2: 302],
3043        cmov_if_zero                             = [2: 209],
3044        cmov_if_not_zero                         = [2: 210],
3045        and_inverted                             = [2: 211],
3046        or_inverted                              = [2: 212],
3047        xnor                                     = [2: 213],
3048        maximum                                  = [2: 303],
3049        maximum_unsigned                         = [2: 214],
3050        minimum                                  = [2: 304],
3051        minimum_unsigned                         = [2: 215],
3052        rotate_left_32                           = [2: 305],
3053        rotate_left_64                           = [2: 216],
3054        rotate_right_32                          = [2: 306],
3055        rotate_right_64                          = [2: 307],
3056    ]
3057    // offset
3058    [
3059        jump                                     = [1: 217, 2: 218, 3: 219, 4: 220],
3060    ]
3061    // imm
3062    [
3063        ecalli                                   = [1: 221, 4: 308],
3064    ]
3065    // imm_imm
3066    [
3067        store_imm_u8                             = [6: 222, 9: 309],
3068        store_imm_u16                            = [9: 310],
3069        store_imm_u32                            = [5: 223, 6: 224, 9: 225],
3070        store_imm_u64                            = [5: 226, 9: 311],
3071    ]
3072    // reg_reg
3073    [
3074        move_reg                                 = [1: 227],
3075        sbrk                                     = [1: 509],
3076        count_leading_zero_bits_32               = [1: 228],
3077        count_leading_zero_bits_64               = [1: 229],
3078        count_trailing_zero_bits_32              = [1: 312],
3079        count_trailing_zero_bits_64              = [1: 230],
3080        count_set_bits_32                        = [1: 231],
3081        count_set_bits_64                        = [1: 232],
3082        sign_extend_8                            = [1: 233],
3083        sign_extend_16                           = [1: 234],
3084        zero_extend_16                           = [1: 235],
3085        reverse_byte                             = [1: 236],
3086    ]
3087    // reg_reg_imm_imm
3088    [
3089        load_imm_and_jump_indirect               = [4: 237, 5: 238, 10: 313],
3090    ]
3091    // reg_imm64
3092    [
3093        load_imm64                               = [9: 239],
3094    ]
3095}
3096
3097define_legacy_instruction_set! {
3098    ($)
3099
3100    ISA_JamV1,
3101    build_static_dispatch_table_jam_v1,
3102
3103    [
3104        trap                                     = 0,
3105        fallthrough                              = 1,
3106        unlikely                                 = 2,
3107    ]
3108    [
3109        jump_indirect                            = 50,
3110        load_imm                                 = 51,
3111        load_u8                                  = 52,
3112        load_i8                                  = 53,
3113        load_u16                                 = 54,
3114        load_i16                                 = 55,
3115        load_i32                                 = 57,
3116        load_u32                                 = 56,
3117        load_u64                                 = 58,
3118        store_u8                                 = 59,
3119        store_u16                                = 60,
3120        store_u32                                = 61,
3121        store_u64                                = 62,
3122    ]
3123    [
3124        load_imm_and_jump                        = 80,
3125        branch_eq_imm                            = 81,
3126        branch_not_eq_imm                        = 82,
3127        branch_less_unsigned_imm                 = 83,
3128        branch_less_signed_imm                   = 87,
3129        branch_greater_or_equal_unsigned_imm     = 85,
3130        branch_greater_or_equal_signed_imm       = 89,
3131        branch_less_or_equal_signed_imm          = 88,
3132        branch_less_or_equal_unsigned_imm        = 84,
3133        branch_greater_signed_imm                = 90,
3134        branch_greater_unsigned_imm              = 86,
3135    ]
3136    [
3137        store_imm_indirect_u8                    = 70,
3138        store_imm_indirect_u16                   = 71,
3139        store_imm_indirect_u32                   = 72,
3140        store_imm_indirect_u64                   = 73,
3141    ]
3142    [
3143        store_indirect_u8                        = 120,
3144        store_indirect_u16                       = 121,
3145        store_indirect_u32                       = 122,
3146        store_indirect_u64                       = 123,
3147        load_indirect_u8                         = 124,
3148        load_indirect_i8                         = 125,
3149        load_indirect_u16                        = 126,
3150        load_indirect_i16                        = 127,
3151        load_indirect_i32                        = 129,
3152        load_indirect_u32                        = 128,
3153        load_indirect_u64                        = 130,
3154        add_imm_32                               = 131,
3155        add_imm_64                               = 149,
3156        and_imm                                  = 132,
3157        xor_imm                                  = 133,
3158        or_imm                                   = 134,
3159        mul_imm_32                               = 135,
3160        mul_imm_64                               = 150,
3161        set_less_than_unsigned_imm               = 136,
3162        set_less_than_signed_imm                 = 137,
3163        shift_logical_left_imm_32                = 138,
3164        shift_logical_left_imm_64                = 151,
3165        shift_logical_right_imm_32               = 139,
3166        shift_logical_right_imm_64               = 152,
3167        shift_arithmetic_right_imm_32            = 140,
3168        shift_arithmetic_right_imm_64            = 153,
3169        negate_and_add_imm_32                    = 141,
3170        negate_and_add_imm_64                    = 154,
3171        set_greater_than_unsigned_imm            = 142,
3172        set_greater_than_signed_imm              = 143,
3173        shift_logical_right_imm_alt_32           = 145,
3174        shift_logical_right_imm_alt_64           = 156,
3175        shift_arithmetic_right_imm_alt_32        = 146,
3176        shift_arithmetic_right_imm_alt_64        = 157,
3177        shift_logical_left_imm_alt_32            = 144,
3178        shift_logical_left_imm_alt_64            = 155,
3179        cmov_if_zero_imm                         = 147,
3180        cmov_if_not_zero_imm                     = 148,
3181        rotate_right_imm_32                      = 160,
3182        rotate_right_imm_alt_32                  = 161,
3183        rotate_right_imm_64                      = 158,
3184        rotate_right_imm_alt_64                  = 159,
3185    ]
3186    [
3187        branch_eq                                = 170,
3188        branch_not_eq                            = 171,
3189        branch_less_unsigned                     = 172,
3190        branch_less_signed                       = 173,
3191        branch_greater_or_equal_unsigned         = 174,
3192        branch_greater_or_equal_signed           = 175,
3193    ]
3194    [
3195        add_32                                   = 190,
3196        add_64                                   = 200,
3197        sub_32                                   = 191,
3198        sub_64                                   = 201,
3199        and                                      = 210,
3200        xor                                      = 211,
3201        or                                       = 212,
3202        mul_32                                   = 192,
3203        mul_64                                   = 202,
3204        mul_upper_signed_signed                  = 213,
3205        mul_upper_unsigned_unsigned              = 214,
3206        mul_upper_signed_unsigned                = 215,
3207        set_less_than_unsigned                   = 216,
3208        set_less_than_signed                     = 217,
3209        shift_logical_left_32                    = 197,
3210        shift_logical_left_64                    = 207,
3211        shift_logical_right_32                   = 198,
3212        shift_logical_right_64                   = 208,
3213        shift_arithmetic_right_32                = 199,
3214        shift_arithmetic_right_64                = 209,
3215        div_unsigned_32                          = 193,
3216        div_unsigned_64                          = 203,
3217        div_signed_32                            = 194,
3218        div_signed_64                            = 204,
3219        rem_unsigned_32                          = 195,
3220        rem_unsigned_64                          = 205,
3221        rem_signed_32                            = 196,
3222        rem_signed_64                            = 206,
3223        cmov_if_zero                             = 218,
3224        cmov_if_not_zero                         = 219,
3225        and_inverted                             = 224,
3226        or_inverted                              = 225,
3227        xnor                                     = 226,
3228        maximum                                  = 227,
3229        maximum_unsigned                         = 228,
3230        minimum                                  = 229,
3231        minimum_unsigned                         = 230,
3232        rotate_left_32                           = 221,
3233        rotate_left_64                           = 220,
3234        rotate_right_32                          = 223,
3235        rotate_right_64                          = 222,
3236    ]
3237    [
3238        jump                                     = 40,
3239    ]
3240    [
3241        ecalli                                   = 10,
3242    ]
3243    [
3244        store_imm_u8                             = 30,
3245        store_imm_u16                            = 31,
3246        store_imm_u32                            = 32,
3247        store_imm_u64                            = 33,
3248    ]
3249    [
3250        move_reg                                 = 100,
3251        count_leading_zero_bits_32               = 104,
3252        count_leading_zero_bits_64               = 103,
3253        count_trailing_zero_bits_32              = 106,
3254        count_trailing_zero_bits_64              = 105,
3255        count_set_bits_32                        = 102,
3256        count_set_bits_64                        = 101,
3257        sign_extend_8                            = 107,
3258        sign_extend_16                           = 108,
3259        zero_extend_16                           = 109,
3260        reverse_byte                             = 110,
3261    ]
3262    [
3263        load_imm_and_jump_indirect               = 180,
3264    ]
3265    [
3266        load_imm64                               = 20,
3267    ]
3268}
3269
3270#[test]
3271fn test_opcode_from_raw() {
3272    assert_eq!(ISA_Latest64.opcode_from_raw(0), Some(Opcode::trap));
3273    assert_eq!(ISA_Latest64.opcode_from_raw(1), Some(Opcode::fallthrough));
3274    assert_eq!(
3275        ISA_Latest64.opcode_from_raw(u32::from(EXTENDED_OPCODE_PREFIX)),
3276        Some(Opcode::jump_indirect)
3277    );
3278    assert_eq!(ISA_Latest64.opcode_from_raw(EXTENDED_INVALID_RAW_OPCODE as u32), None);
3279    assert_eq!(ISA_ReviveV1.opcode_from_raw(LEGACY_INVALID_RAW_OPCODE), None);
3280    assert_eq!(ISA_ReviveV1.opcode_from_raw(3), None);
3281}
3282
3283#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
3284pub enum InstructionSetKind {
3285    ReviveV1,
3286    JamV1,
3287    Latest32,
3288    Latest64,
3289}
3290
3291impl InstructionSetKind {
3292    pub fn name(self) -> &'static str {
3293        match self {
3294            Self::ReviveV1 => "revive_v1",
3295            Self::JamV1 => "jam_v1",
3296            Self::Latest32 => "latest32",
3297            Self::Latest64 => "latest64",
3298        }
3299    }
3300
3301    #[cfg(feature = "alloc")]
3302    pub(crate) fn blob_version(self) -> u8 {
3303        match self {
3304            Self::ReviveV1 => 0,
3305            Self::Latest32 => 1,
3306            Self::Latest64 => 2,
3307            Self::JamV1 => 3,
3308        }
3309    }
3310
3311    pub(crate) fn from_blob_version(version: u8) -> Option<Self> {
3312        match version {
3313            0 => Some(Self::ReviveV1),
3314            1 => Some(Self::Latest32),
3315            2 => Some(Self::Latest64),
3316            3 => Some(Self::JamV1),
3317            _ => None,
3318        }
3319    }
3320
3321    /// Returns whether the ISA is 64-bit.
3322    pub fn is_64_bit(&self) -> bool {
3323        match self {
3324            InstructionSetKind::Latest32 => false,
3325            InstructionSetKind::ReviveV1 | InstructionSetKind::JamV1 | InstructionSetKind::Latest64 => true,
3326        }
3327    }
3328}
3329
3330macro_rules! dispatch_isa {
3331    ($self:ident, $isa:ident => $e:expr) => {
3332        match $self {
3333            Self::ReviveV1 => {
3334                let $isa = ISA_ReviveV1;
3335                $e
3336            }
3337            Self::Latest32 => {
3338                let $isa = ISA_Latest32;
3339                $e
3340            }
3341            Self::Latest64 => {
3342                let $isa = ISA_Latest64;
3343                $e
3344            }
3345            Self::JamV1 => {
3346                let $isa = ISA_JamV1;
3347                $e
3348            }
3349        }
3350    };
3351}
3352
3353impl InstructionSet for InstructionSetKind {
3354    fn opcode_from_raw(self, raw_opcode: u32) -> Option<Opcode> {
3355        dispatch_isa!(self, isa => isa.opcode_from_raw(raw_opcode))
3356    }
3357
3358    fn opcode_to_raw(self, opcode: Opcode, args_length: u32) -> Option<(u32, u32)> {
3359        dispatch_isa!(self, isa => isa.opcode_to_raw(opcode, args_length))
3360    }
3361
3362    fn supports_opcode(self, opcode: Opcode) -> bool {
3363        dispatch_isa!(self, isa => isa.supports_opcode(opcode))
3364    }
3365
3366    fn parse_instruction(self, raw_opcode: usize, chunk: u128, offset: u32, length: u32) -> Instruction {
3367        dispatch_isa!(self, isa => isa.parse_instruction(raw_opcode, chunk, offset, length))
3368    }
3369
3370    #[inline]
3371    fn is_legacy(self) -> bool {
3372        dispatch_isa!(self, isa => isa.is_legacy())
3373    }
3374
3375    #[inline]
3376    fn raw_opcode_table(self) -> &'static RawOpcodeTable {
3377        dispatch_isa!(self, isa => isa.raw_opcode_table())
3378    }
3379}
3380
3381impl Opcode {
3382    pub fn can_fallthrough(self) -> bool {
3383        !matches!(
3384            self,
3385            Self::trap | Self::jump | Self::jump_indirect | Self::load_imm_and_jump | Self::load_imm_and_jump_indirect
3386        )
3387    }
3388
3389    pub const fn starts_new_basic_block(self) -> bool {
3390        matches!(
3391            self,
3392            Self::trap
3393                | Self::fallthrough
3394                | Self::jump
3395                | Self::jump_indirect
3396                | Self::load_imm_and_jump
3397                | Self::load_imm_and_jump_indirect
3398                | Self::branch_eq
3399                | Self::branch_eq_imm
3400                | Self::branch_greater_or_equal_signed
3401                | Self::branch_greater_or_equal_signed_imm
3402                | Self::branch_greater_or_equal_unsigned
3403                | Self::branch_greater_or_equal_unsigned_imm
3404                | Self::branch_greater_signed_imm
3405                | Self::branch_greater_unsigned_imm
3406                | Self::branch_less_or_equal_signed_imm
3407                | Self::branch_less_or_equal_unsigned_imm
3408                | Self::branch_less_signed
3409                | Self::branch_less_signed_imm
3410                | Self::branch_less_unsigned
3411                | Self::branch_less_unsigned_imm
3412                | Self::branch_not_eq
3413                | Self::branch_not_eq_imm
3414        )
3415    }
3416}
3417
3418impl core::fmt::Display for Instruction {
3419    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
3420        self.visit(&mut InstructionFormatter {
3421            format: &Default::default(),
3422            fmt,
3423        })
3424    }
3425}
3426
3427impl Instruction {
3428    pub fn display<'a>(self, format: &'a InstructionFormat<'a>) -> impl core::fmt::Display + 'a {
3429        struct Inner<'a, 'b> {
3430            instruction: Instruction,
3431            format: &'a InstructionFormat<'b>,
3432        }
3433
3434        impl<'a, 'b> core::fmt::Display for Inner<'a, 'b> {
3435            fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
3436                self.instruction.visit(&mut InstructionFormatter { format: self.format, fmt })
3437            }
3438        }
3439
3440        Inner { instruction: self, format }
3441    }
3442
3443    pub fn starts_new_basic_block(self) -> bool {
3444        self.opcode().starts_new_basic_block()
3445    }
3446
3447    #[must_use]
3448    fn serialize_opcode(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, args_length: u32) -> (usize, u32) {
3449        if let Some((raw_opcode, actual_args_length)) = isa.opcode_to_raw(opcode, args_length) {
3450            let length = if raw_opcode < u32::from(EXTENDED_OPCODE_PREFIX) {
3451                buffer[0] = raw_opcode as u8;
3452                1
3453            } else {
3454                buffer[0] = EXTENDED_OPCODE_PREFIX;
3455                buffer[1] = (raw_opcode - u32::from(EXTENDED_OPCODE_PREFIX)) as u8;
3456                2
3457            };
3458
3459            (length, actual_args_length - args_length)
3460        } else {
3461            buffer[0] = UNUSED_RAW_OPCODE as u8;
3462            (1, 0)
3463        }
3464    }
3465
3466    fn adjust_length(imm_length: u32, length_delta: u32) -> u32 {
3467        debug_assert!(imm_length <= 4);
3468        let imm_length_ext = imm_length + length_delta;
3469        debug_assert!(imm_length_ext <= 4);
3470        imm_length_ext
3471    }
3472
3473    fn adjust_length2(imm1_length: u32, imm2_length: u32, length_delta: u32) -> (u32, u32) {
3474        debug_assert!(imm1_length <= 4);
3475        debug_assert!(imm2_length <= 4);
3476
3477        let imm1_length_ext = (imm1_length + length_delta).min(4);
3478        let length_delta = length_delta - (imm1_length_ext - imm1_length);
3479        let imm2_length_ext = imm2_length + length_delta;
3480
3481        debug_assert!(imm1_length_ext <= 4);
3482        debug_assert!(imm2_length_ext <= 4);
3483
3484        (imm1_length_ext, imm2_length_ext)
3485    }
3486
3487    fn serialize_argless(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode) -> usize {
3488        Self::serialize_opcode(isa, buffer, opcode, 0).0
3489    }
3490
3491    fn serialize_reg_imm_offset(
3492        isa: impl InstructionSet,
3493        buffer: &mut [u8],
3494        position: u32,
3495        opcode: Opcode,
3496        reg: RawReg,
3497        imm1: i32,
3498        imm2: u32,
3499    ) -> usize {
3500        let imm1 = cast(imm1).bitwise_as_u32();
3501        let imm2 = imm2.wrapping_sub(position);
3502        let imm1_length = simple_varint_length(imm1);
3503        let imm2_length = simple_varint_length(imm2);
3504        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm1_length + imm2_length);
3505        let (imm1_length, imm2_length) = Self::adjust_length2(imm1_length, imm2_length, length_delta);
3506        buffer[position] = reg.0 as u8 | (imm1_length << 4) as u8;
3507        position += 1;
3508        position += write_simple_varint_with_length(imm1, imm1_length, &mut buffer[position..]);
3509        position += write_simple_varint_with_length(imm2, imm2_length, &mut buffer[position..]);
3510        position
3511    }
3512
3513    fn serialize_reg_imm_imm(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, reg: RawReg, imm1: i32, imm2: i32) -> usize {
3514        let imm1 = cast(imm1).bitwise_as_u32();
3515        let imm2 = cast(imm2).bitwise_as_u32();
3516        let imm1_length = simple_varint_length(imm1);
3517        let imm2_length = simple_varint_length(imm2);
3518        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm1_length + imm2_length);
3519        let (imm1_length, imm2_length) = Self::adjust_length2(imm1_length, imm2_length, length_delta);
3520        buffer[position] = reg.0 as u8 | (imm1_length << 4) as u8;
3521        position += 1;
3522        position += write_simple_varint_with_length(imm1, imm1_length, &mut buffer[position..]);
3523        position += write_simple_varint_with_length(imm2, imm2_length, &mut buffer[position..]);
3524        position
3525    }
3526    fn serialize_reg_reg_imm_imm(
3527        isa: impl InstructionSet,
3528        buffer: &mut [u8],
3529        opcode: Opcode,
3530        reg1: RawReg,
3531        reg2: RawReg,
3532        imm1: i32,
3533        imm2: i32,
3534    ) -> usize {
3535        let imm1 = cast(imm1).bitwise_as_u32();
3536        let imm2 = cast(imm2).bitwise_as_u32();
3537        let imm1_length = simple_varint_length(imm1);
3538        let imm2_length = simple_varint_length(imm2);
3539        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 2 + imm1_length + imm2_length);
3540        let (imm1_length, imm2_length) = Self::adjust_length2(imm1_length, imm2_length, length_delta);
3541        buffer[position] = reg1.0 as u8 | (reg2.0 as u8) << 4;
3542        position += 1;
3543        buffer[position] = imm1_length as u8;
3544        position += 1;
3545        position += write_simple_varint_with_length(imm1, imm1_length, &mut buffer[position..]);
3546        position + write_simple_varint_with_length(imm2, imm2_length, &mut buffer[position..])
3547    }
3548
3549    fn serialize_reg_imm64(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, reg: RawReg, imm: u64) -> usize {
3550        let (mut position, _) = Self::serialize_opcode(isa, buffer, opcode, 9);
3551        buffer[position] = reg.0 as u8;
3552        position += 1;
3553        buffer[position..position + 8].copy_from_slice(&imm.to_le_bytes());
3554        position + 8
3555    }
3556
3557    fn serialize_reg_reg_reg(
3558        isa: impl InstructionSet,
3559        buffer: &mut [u8],
3560        opcode: Opcode,
3561        reg1: RawReg,
3562        reg2: RawReg,
3563        reg3: RawReg,
3564    ) -> usize {
3565        let (mut position, _) = Self::serialize_opcode(isa, buffer, opcode, 2);
3566        buffer[position] = reg2.0 as u8 | (reg3.0 as u8) << 4;
3567        position += 1;
3568        buffer[position] = reg1.0 as u8;
3569        position + 1
3570    }
3571
3572    fn serialize_reg_reg_imm(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, reg1: RawReg, reg2: RawReg, imm: i32) -> usize {
3573        let imm = cast(imm).bitwise_as_u32();
3574        let imm_length = simple_varint_length(imm);
3575        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm_length);
3576        let imm_length = Self::adjust_length(imm_length, length_delta);
3577        buffer[position] = reg1.0 as u8 | (reg2.0 as u8) << 4;
3578        position += 1;
3579        position + write_simple_varint_with_length(imm, imm_length, &mut buffer[position..])
3580    }
3581
3582    fn serialize_reg_reg_offset(
3583        isa: impl InstructionSet,
3584        buffer: &mut [u8],
3585        position: u32,
3586        opcode: Opcode,
3587        reg1: RawReg,
3588        reg2: RawReg,
3589        imm: u32,
3590    ) -> usize {
3591        let imm = imm.wrapping_sub(position);
3592        let imm_length = simple_varint_length(imm);
3593        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm_length);
3594        let imm_length = Self::adjust_length(imm_length, length_delta);
3595        buffer[position] = reg1.0 as u8 | (reg2.0 as u8) << 4;
3596        position += 1;
3597        position + write_simple_varint_with_length(imm, imm_length, &mut buffer[position..])
3598    }
3599
3600    fn serialize_reg_imm(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, reg: RawReg, imm: i32) -> usize {
3601        let imm = cast(imm).bitwise_as_u32();
3602        let imm_length = simple_varint_length(imm);
3603        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm_length);
3604        let imm_length = Self::adjust_length(imm_length, length_delta);
3605        buffer[position] = reg.0 as u8;
3606        position += 1;
3607        position + write_simple_varint_with_length(imm, imm_length, &mut buffer[position..])
3608    }
3609
3610    fn serialize_offset(isa: impl InstructionSet, buffer: &mut [u8], position: u32, opcode: Opcode, imm: u32) -> usize {
3611        Self::serialize_offset_with_minimum_imm_length(isa, buffer, position, opcode, imm, 0)
3612    }
3613
3614    pub(crate) fn serialize_offset_with_minimum_imm_length(
3615        isa: impl InstructionSet,
3616        buffer: &mut [u8],
3617        position: u32,
3618        opcode: Opcode,
3619        imm: u32,
3620        minimum_imm_length: u32,
3621    ) -> usize {
3622        let imm = imm.wrapping_sub(position);
3623        let imm_length = simple_varint_length(imm).max(minimum_imm_length);
3624        let (position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, imm_length);
3625        let imm_length = Self::adjust_length(imm_length, length_delta);
3626        position + write_simple_varint_with_length(imm, imm_length, &mut buffer[position..])
3627    }
3628
3629    fn serialize_imm(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, imm: i32) -> usize {
3630        let imm = cast(imm).bitwise_as_u32();
3631        let imm_length = simple_varint_length(imm);
3632        let (position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, imm_length);
3633        let imm_length = Self::adjust_length(imm_length, length_delta);
3634        position + write_simple_varint_with_length(imm, imm_length, &mut buffer[position..])
3635    }
3636
3637    fn serialize_imm_imm(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, imm1: i32, imm2: i32) -> usize {
3638        let imm1 = cast(imm1).bitwise_as_u32();
3639        let imm2 = cast(imm2).bitwise_as_u32();
3640        let imm1_length = simple_varint_length(imm1);
3641        let imm2_length = simple_varint_length(imm2);
3642        let (mut position, length_delta) = Self::serialize_opcode(isa, buffer, opcode, 1 + imm1_length + imm2_length);
3643        let (imm1_length, imm2_length) = Self::adjust_length2(imm1_length, imm2_length, length_delta);
3644        buffer[position] = imm1_length as u8;
3645        position += 1;
3646        position += write_simple_varint_with_length(imm1, imm1_length, &mut buffer[position..]);
3647        position + write_simple_varint_with_length(imm2, imm2_length, &mut buffer[position..])
3648    }
3649
3650    fn serialize_reg_reg(isa: impl InstructionSet, buffer: &mut [u8], opcode: Opcode, reg1: RawReg, reg2: RawReg) -> usize {
3651        let (position, _) = Self::serialize_opcode(isa, buffer, opcode, 1);
3652        buffer[position] = reg1.0 as u8 | (reg2.0 as u8) << 4;
3653        position + 1
3654    }
3655}
3656
3657pub const MAX_INSTRUCTION_LENGTH: usize = 2 + MAX_VARINT_LENGTH * 2;
3658
3659#[derive(Clone)]
3660#[non_exhaustive]
3661pub struct InstructionFormat<'a> {
3662    pub prefer_non_abi_reg_names: bool,
3663    pub prefer_unaliased: bool,
3664    pub jump_target_formatter: Option<&'a dyn Fn(u32, &mut core::fmt::Formatter) -> core::fmt::Result>,
3665    pub is_64_bit: bool,
3666}
3667
3668impl<'a> Default for InstructionFormat<'a> {
3669    fn default() -> Self {
3670        InstructionFormat {
3671            prefer_non_abi_reg_names: false,
3672            prefer_unaliased: false,
3673            jump_target_formatter: None,
3674            is_64_bit: true,
3675        }
3676    }
3677}
3678
3679struct InstructionFormatter<'a, 'b, 'c> {
3680    format: &'a InstructionFormat<'c>,
3681    fmt: &'a mut core::fmt::Formatter<'b>,
3682}
3683
3684impl<'a, 'b, 'c> InstructionFormatter<'a, 'b, 'c> {
3685    fn format_reg(&self, reg: RawReg) -> &'static str {
3686        if self.format.prefer_non_abi_reg_names {
3687            reg.get().name_non_abi()
3688        } else {
3689            reg.get().name()
3690        }
3691    }
3692
3693    fn format_jump(&self, imm: u32) -> impl core::fmt::Display + 'a {
3694        struct Formatter<'a>(Option<&'a dyn Fn(u32, &mut core::fmt::Formatter) -> core::fmt::Result>, u32);
3695        impl<'a> core::fmt::Display for Formatter<'a> {
3696            fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
3697                if let Some(f) = self.0 {
3698                    f(self.1, fmt)
3699                } else {
3700                    write!(fmt, "{}", self.1)
3701                }
3702            }
3703        }
3704
3705        Formatter(self.format.jump_target_formatter, imm)
3706    }
3707
3708    fn format_imm(&self, imm: i32) -> impl core::fmt::Display {
3709        struct Formatter {
3710            imm: i32,
3711            is_64_bit: bool,
3712        }
3713
3714        impl core::fmt::Display for Formatter {
3715            fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
3716                if self.imm == 0 {
3717                    write!(fmt, "{}", self.imm)
3718                } else if !self.is_64_bit {
3719                    write!(fmt, "0x{:x}", self.imm)
3720                } else {
3721                    let imm: i64 = cast(self.imm).to_i64_sign_extend();
3722                    write!(fmt, "0x{:x}", imm)
3723                }
3724            }
3725        }
3726
3727        Formatter {
3728            imm,
3729            is_64_bit: self.format.is_64_bit,
3730        }
3731    }
3732
3733    fn format_offset(&self, offset: i32) -> impl core::fmt::Display {
3734        struct Formatter {
3735            offset: i32,
3736            prefer_unaliased: bool,
3737        }
3738
3739        impl core::fmt::Display for Formatter {
3740            fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
3741                if self.offset == 0 && !self.prefer_unaliased {
3742                    Ok(())
3743                } else if self.offset < 0 {
3744                    write!(fmt, " - {}", cast(self.offset).to_i64_sign_extend() * -1)
3745                } else {
3746                    write!(fmt, " + {}", self.offset)
3747                }
3748            }
3749        }
3750
3751        Formatter {
3752            offset,
3753            prefer_unaliased: self.format.prefer_unaliased,
3754        }
3755    }
3756}
3757
3758impl<'a, 'b, 'c> core::fmt::Write for InstructionFormatter<'a, 'b, 'c> {
3759    fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> {
3760        self.fmt.write_str(s)
3761    }
3762}
3763
3764impl<'a, 'b, 'c> InstructionVisitor for InstructionFormatter<'a, 'b, 'c> {
3765    type ReturnTy = core::fmt::Result;
3766
3767    fn trap(&mut self) -> Self::ReturnTy {
3768        write!(self, "trap")
3769    }
3770
3771    fn fallthrough(&mut self) -> Self::ReturnTy {
3772        write!(self, "fallthrough")
3773    }
3774
3775    fn unlikely(&mut self) -> Self::ReturnTy {
3776        write!(self, "unlikely")
3777    }
3778
3779    fn sbrk(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
3780        let d = self.format_reg(d);
3781        let s = self.format_reg(s);
3782        write!(self, "{d} = sbrk {s}")
3783    }
3784
3785    fn memset(&mut self) -> Self::ReturnTy {
3786        write!(self, "[a0..a0 + a2] = u8 a1")
3787    }
3788
3789    fn ecalli(&mut self, nth_import: i32) -> Self::ReturnTy {
3790        write!(self, "ecalli {}", cast(nth_import).bitwise_as_u32())
3791    }
3792
3793    fn set_less_than_unsigned(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3794        let d = self.format_reg(d);
3795        let s1 = self.format_reg(s1);
3796        let s2 = self.format_reg(s2);
3797        write!(self, "{d} = {s1} <u {s2}")
3798    }
3799
3800    fn set_less_than_signed(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3801        let d = self.format_reg(d);
3802        let s1 = self.format_reg(s1);
3803        let s2 = self.format_reg(s2);
3804        write!(self, "{d} = {s1} <s {s2}")
3805    }
3806
3807    fn shift_logical_right_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3808        let d = self.format_reg(d);
3809        let s1 = self.format_reg(s1);
3810        let s2 = self.format_reg(s2);
3811        write!(self, "{d} = {s1} >> {s2}")
3812    }
3813
3814    fn shift_arithmetic_right_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3815        let d = self.format_reg(d);
3816        let s1 = self.format_reg(s1);
3817        let s2 = self.format_reg(s2);
3818        write!(self, "{d} = {s1} >>a {s2}")
3819    }
3820
3821    fn shift_logical_left_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3822        let d = self.format_reg(d);
3823        let s1 = self.format_reg(s1);
3824        let s2 = self.format_reg(s2);
3825        write!(self, "{d} = {s1} << {s2}")
3826    }
3827
3828    fn shift_logical_right_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3829        let d = self.format_reg(d);
3830        let s1 = self.format_reg(s1);
3831        let s2 = self.format_reg(s2);
3832        if self.format.is_64_bit {
3833            write!(self, "i32 {d} = {s1} >> {s2}")
3834        } else {
3835            write!(self, "{d} = {s1} >> {s2}")
3836        }
3837    }
3838
3839    fn shift_arithmetic_right_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3840        let d = self.format_reg(d);
3841        let s1 = self.format_reg(s1);
3842        let s2 = self.format_reg(s2);
3843        if self.format.is_64_bit {
3844            write!(self, "i32 {d} = {s1} >>a {s2}")
3845        } else {
3846            write!(self, "{d} = {s1} >>a {s2}")
3847        }
3848    }
3849
3850    fn shift_logical_left_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3851        let d = self.format_reg(d);
3852        let s1 = self.format_reg(s1);
3853        let s2 = self.format_reg(s2);
3854        if self.format.is_64_bit {
3855            write!(self, "i32 {d} = {s1} << {s2}")
3856        } else {
3857            write!(self, "{d} = {s1} << {s2}")
3858        }
3859    }
3860
3861    fn xor(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3862        let d = self.format_reg(d);
3863        let s1 = self.format_reg(s1);
3864        let s2 = self.format_reg(s2);
3865        write!(self, "{d} = {s1} ^ {s2}")
3866    }
3867
3868    fn and(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3869        let d = self.format_reg(d);
3870        let s1 = self.format_reg(s1);
3871        let s2 = self.format_reg(s2);
3872        write!(self, "{d} = {s1} & {s2}")
3873    }
3874
3875    fn or(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3876        let d = self.format_reg(d);
3877        let s1 = self.format_reg(s1);
3878        let s2 = self.format_reg(s2);
3879        write!(self, "{d} = {s1} | {s2}")
3880    }
3881
3882    fn add_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3883        let d = self.format_reg(d);
3884        let s1 = self.format_reg(s1);
3885        let s2 = self.format_reg(s2);
3886        if self.format.is_64_bit {
3887            write!(self, "i32 {d} = {s1} + {s2}")
3888        } else {
3889            write!(self, "{d} = {s1} + {s2}")
3890        }
3891    }
3892
3893    fn add_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3894        let d = self.format_reg(d);
3895        let s1 = self.format_reg(s1);
3896        let s2 = self.format_reg(s2);
3897        write!(self, "{d} = {s1} + {s2}")
3898    }
3899
3900    fn sub_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3901        let d = self.format_reg(d);
3902        let s1 = self.format_reg(s1);
3903        let s2 = self.format_reg(s2);
3904        if self.format.is_64_bit {
3905            write!(self, "i32 {d} = {s1} - {s2}")
3906        } else {
3907            write!(self, "{d} = {s1} - {s2}")
3908        }
3909    }
3910
3911    fn sub_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3912        let d = self.format_reg(d);
3913        let s1 = self.format_reg(s1);
3914        let s2 = self.format_reg(s2);
3915        write!(self, "{d} = {s1} - {s2}")
3916    }
3917
3918    fn mul_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3919        let d = self.format_reg(d);
3920        let s1 = self.format_reg(s1);
3921        let s2 = self.format_reg(s2);
3922        if self.format.is_64_bit {
3923            write!(self, "i32 {d} = {s1} * {s2}")
3924        } else {
3925            write!(self, "{d} = {s1} * {s2}")
3926        }
3927    }
3928
3929    fn mul_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3930        let d = self.format_reg(d);
3931        let s1 = self.format_reg(s1);
3932        let s2 = self.format_reg(s2);
3933        write!(self, "{d} = {s1} * {s2}")
3934    }
3935
3936    fn mul_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
3937        let d = self.format_reg(d);
3938        let s1 = self.format_reg(s1);
3939        let s2 = self.format_imm(s2);
3940        if self.format.is_64_bit {
3941            write!(self, "i32 {d} = {s1} * {s2}")
3942        } else {
3943            write!(self, "{d} = {s1} * {s2}")
3944        }
3945    }
3946
3947    fn mul_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
3948        let d = self.format_reg(d);
3949        let s1 = self.format_reg(s1);
3950        let s2 = self.format_imm(s2);
3951        write!(self, "{d} = {s1} * {s2}")
3952    }
3953
3954    fn mul_upper_signed_signed(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3955        let d = self.format_reg(d);
3956        let s1 = self.format_reg(s1);
3957        let s2 = self.format_reg(s2);
3958        write!(self, "{d} = {s1} mulh {s2}")
3959    }
3960
3961    fn mul_upper_unsigned_unsigned(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3962        let d = self.format_reg(d);
3963        let s1 = self.format_reg(s1);
3964        let s2 = self.format_reg(s2);
3965        write!(self, "{d} = {s1} mulhu {s2}")
3966    }
3967
3968    fn mul_upper_signed_unsigned(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3969        let d = self.format_reg(d);
3970        let s1 = self.format_reg(s1);
3971        let s2 = self.format_reg(s2);
3972        write!(self, "{d} = {s1} mulhsu {s2}")
3973    }
3974
3975    fn div_unsigned_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3976        let d = self.format_reg(d);
3977        let s1 = self.format_reg(s1);
3978        let s2 = self.format_reg(s2);
3979        if self.format.is_64_bit {
3980            write!(self, "i32 {d} = {s1} /u {s2}")
3981        } else {
3982            write!(self, "{d} = {s1} /u {s2}")
3983        }
3984    }
3985
3986    fn div_signed_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3987        let d = self.format_reg(d);
3988        let s1 = self.format_reg(s1);
3989        let s2 = self.format_reg(s2);
3990        if self.format.is_64_bit {
3991            write!(self, "i32 {d} = {s1} /s {s2}")
3992        } else {
3993            write!(self, "{d} = {s1} /s {s2}")
3994        }
3995    }
3996
3997    fn rem_unsigned_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
3998        let d = self.format_reg(d);
3999        let s1 = self.format_reg(s1);
4000        let s2 = self.format_reg(s2);
4001        if self.format.is_64_bit {
4002            write!(self, "i32 {d} = {s1} %u {s2}")
4003        } else {
4004            write!(self, "{d} = {s1} %u {s2}")
4005        }
4006    }
4007
4008    fn rem_signed_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4009        let d = self.format_reg(d);
4010        let s1 = self.format_reg(s1);
4011        let s2 = self.format_reg(s2);
4012        if self.format.is_64_bit {
4013            write!(self, "i32 {d} = {s1} %s {s2}")
4014        } else {
4015            write!(self, "{d} = {s1} %s {s2}")
4016        }
4017    }
4018
4019    fn div_unsigned_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4020        let d = self.format_reg(d);
4021        let s1 = self.format_reg(s1);
4022        let s2 = self.format_reg(s2);
4023        write!(self, "{d} = {s1} /u {s2}")
4024    }
4025
4026    fn div_signed_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4027        let d = self.format_reg(d);
4028        let s1 = self.format_reg(s1);
4029        let s2 = self.format_reg(s2);
4030        write!(self, "{d} = {s1} /s {s2}")
4031    }
4032
4033    fn rem_unsigned_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4034        let d = self.format_reg(d);
4035        let s1 = self.format_reg(s1);
4036        let s2 = self.format_reg(s2);
4037        write!(self, "{d} = {s1} %u {s2}")
4038    }
4039
4040    fn rem_signed_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4041        let d = self.format_reg(d);
4042        let s1 = self.format_reg(s1);
4043        let s2 = self.format_reg(s2);
4044        write!(self, "{d} = {s1} %s {s2}")
4045    }
4046
4047    fn and_inverted(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4048        let d = self.format_reg(d);
4049        let s1 = self.format_reg(s1);
4050        let s2 = self.format_reg(s2);
4051        write!(self, "{d} = {s1} & ~{s2}")
4052    }
4053
4054    fn or_inverted(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4055        let d = self.format_reg(d);
4056        let s1 = self.format_reg(s1);
4057        let s2 = self.format_reg(s2);
4058        write!(self, "{d} = {s1} | ~{s2}")
4059    }
4060
4061    fn xnor(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4062        let d = self.format_reg(d);
4063        let s1 = self.format_reg(s1);
4064        let s2 = self.format_reg(s2);
4065        write!(self, "{d} = ~({s1} ^ {s2})")
4066    }
4067
4068    fn maximum(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4069        let d = self.format_reg(d);
4070        let s1 = self.format_reg(s1);
4071        let s2 = self.format_reg(s2);
4072        write!(self, "{d} = maxs({s1}, {s2})")
4073    }
4074
4075    fn maximum_unsigned(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4076        let d = self.format_reg(d);
4077        let s1 = self.format_reg(s1);
4078        let s2 = self.format_reg(s2);
4079        write!(self, "{d} = maxu({s1}, {s2})")
4080    }
4081
4082    fn minimum(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4083        let d = self.format_reg(d);
4084        let s1 = self.format_reg(s1);
4085        let s2 = self.format_reg(s2);
4086        write!(self, "{d} = mins({s1}, {s2})")
4087    }
4088
4089    fn minimum_unsigned(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4090        let d = self.format_reg(d);
4091        let s1 = self.format_reg(s1);
4092        let s2 = self.format_reg(s2);
4093        write!(self, "{d} = minu({s1}, {s2})")
4094    }
4095
4096    fn rotate_left_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4097        let d = self.format_reg(d);
4098        let s1 = self.format_reg(s1);
4099        let s2 = self.format_reg(s2);
4100        if self.format.is_64_bit {
4101            write!(self, "i32 {d} = {s1} <<r {s2}")
4102        } else {
4103            write!(self, "{d} = {s1} <<r {s2}")
4104        }
4105    }
4106
4107    fn rotate_left_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4108        let d = self.format_reg(d);
4109        let s1 = self.format_reg(s1);
4110        let s2 = self.format_reg(s2);
4111        write!(self, "{d} = {s1} <<r {s2}")
4112    }
4113
4114    fn rotate_right_32(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4115        let d = self.format_reg(d);
4116        let s1 = self.format_reg(s1);
4117        let s2 = self.format_reg(s2);
4118        if self.format.is_64_bit {
4119            write!(self, "i32 {d} = {s1} >>r {s2}")
4120        } else {
4121            write!(self, "{d} = {s1} >>r {s2}")
4122        }
4123    }
4124
4125    fn rotate_right_64(&mut self, d: RawReg, s1: RawReg, s2: RawReg) -> Self::ReturnTy {
4126        let d = self.format_reg(d);
4127        let s1 = self.format_reg(s1);
4128        let s2 = self.format_reg(s2);
4129        write!(self, "{d} = {s1} >>r {s2}")
4130    }
4131
4132    fn set_less_than_unsigned_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4133        let d = self.format_reg(d);
4134        let s1 = self.format_reg(s1);
4135        let s2 = self.format_imm(s2);
4136        write!(self, "{d} = {s1} <u {s2}")
4137    }
4138
4139    fn set_greater_than_unsigned_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4140        let d = self.format_reg(d);
4141        let s1 = self.format_reg(s1);
4142        let s2 = self.format_imm(s2);
4143        write!(self, "{d} = {s1} >u {s2}")
4144    }
4145
4146    fn set_less_than_signed_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4147        let d = self.format_reg(d);
4148        let s1 = self.format_reg(s1);
4149        let s2 = self.format_imm(s2);
4150        write!(self, "{d} = {s1} <s {s2}")
4151    }
4152
4153    fn set_greater_than_signed_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4154        let d = self.format_reg(d);
4155        let s1 = self.format_reg(s1);
4156        let s2 = self.format_imm(s2);
4157        write!(self, "{d} = {s1} >s {s2}")
4158    }
4159
4160    fn shift_logical_right_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4161        let d = self.format_reg(d);
4162        let s1 = self.format_reg(s1);
4163        let s2 = self.format_imm(s2);
4164        if self.format.is_64_bit {
4165            write!(self, "i32 {d} = {s1} >> {s2}")
4166        } else {
4167            write!(self, "{d} = {s1} >> {s2}")
4168        }
4169    }
4170
4171    fn shift_logical_right_imm_alt_32(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4172        let d = self.format_reg(d);
4173        let s1 = self.format_imm(s1);
4174        let s2 = self.format_reg(s2);
4175        if self.format.is_64_bit {
4176            write!(self, "i32 {d} = {s1} >> {s2}")
4177        } else {
4178            write!(self, "{d} = {s1} >> {s2}")
4179        }
4180    }
4181
4182    fn shift_arithmetic_right_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4183        let d = self.format_reg(d);
4184        let s1 = self.format_reg(s1);
4185        let s2 = self.format_imm(s2);
4186        if self.format.is_64_bit {
4187            write!(self, "i32 {d} = {s1} >>a {s2}")
4188        } else {
4189            write!(self, "{d} = {s1} >>a {s2}")
4190        }
4191    }
4192
4193    fn shift_logical_right_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4194        let d = self.format_reg(d);
4195        let s1 = self.format_reg(s1);
4196        let s2 = self.format_imm(s2);
4197        write!(self, "{d} = {s1} >> {s2}")
4198    }
4199
4200    fn shift_logical_right_imm_alt_64(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4201        let d = self.format_reg(d);
4202        let s1 = self.format_imm(s1);
4203        let s2 = self.format_reg(s2);
4204        write!(self, "{d} = {s1} >> {s2}")
4205    }
4206
4207    fn shift_arithmetic_right_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4208        let d = self.format_reg(d);
4209        let s1 = self.format_reg(s1);
4210        let s2 = self.format_imm(s2);
4211        write!(self, "{d} = {s1} >>a {s2}")
4212    }
4213
4214    fn shift_arithmetic_right_imm_alt_32(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4215        let d = self.format_reg(d);
4216        let s1 = self.format_imm(s1);
4217        let s2 = self.format_reg(s2);
4218        if self.format.is_64_bit {
4219            write!(self, "i32 {d} = {s1} >>a {s2}")
4220        } else {
4221            write!(self, "{d} = {s1} >>a {s2}")
4222        }
4223    }
4224
4225    fn shift_logical_left_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4226        let d = self.format_reg(d);
4227        let s1 = self.format_reg(s1);
4228        let s2 = self.format_imm(s2);
4229        if self.format.is_64_bit {
4230            write!(self, "i32 {d} = {s1} << {s2}")
4231        } else {
4232            write!(self, "{d} = {s1} << {s2}")
4233        }
4234    }
4235
4236    fn shift_logical_left_imm_alt_32(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4237        let d = self.format_reg(d);
4238        let s1 = self.format_imm(s1);
4239        let s2 = self.format_reg(s2);
4240        if self.format.is_64_bit {
4241            write!(self, "i32 {d} = {s1} << {s2}")
4242        } else {
4243            write!(self, "{d} = {s1} << {s2}")
4244        }
4245    }
4246
4247    fn shift_arithmetic_right_imm_alt_64(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4248        let d = self.format_reg(d);
4249        let s1 = self.format_imm(s1);
4250        let s2 = self.format_reg(s2);
4251        write!(self, "{d} = {s1} >>a {s2}")
4252    }
4253
4254    fn shift_logical_left_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4255        let d = self.format_reg(d);
4256        let s1 = self.format_reg(s1);
4257        let s2 = self.format_imm(s2);
4258        write!(self, "{d} = {s1} << {s2}")
4259    }
4260
4261    fn shift_logical_left_imm_alt_64(&mut self, d: RawReg, s2: RawReg, s1: i32) -> Self::ReturnTy {
4262        let d = self.format_reg(d);
4263        let s1 = self.format_imm(s1);
4264        let s2 = self.format_reg(s2);
4265        write!(self, "{d} = {s1} << {s2}")
4266    }
4267
4268    fn or_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4269        let d = self.format_reg(d);
4270        let s1 = self.format_reg(s1);
4271        let s2 = self.format_imm(s2);
4272        write!(self, "{d} = {s1} | {s2}")
4273    }
4274
4275    fn and_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4276        let d = self.format_reg(d);
4277        let s1 = self.format_reg(s1);
4278        let s2 = self.format_imm(s2);
4279        write!(self, "{d} = {s1} & {s2}")
4280    }
4281
4282    fn xor_imm(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4283        let d = self.format_reg(d);
4284        let s1 = self.format_reg(s1);
4285        let s2 = self.format_imm(s2);
4286        write!(self, "{d} = {s1} ^ {s2}")
4287    }
4288
4289    fn load_imm(&mut self, d: RawReg, a: i32) -> Self::ReturnTy {
4290        let d = self.format_reg(d);
4291        let a = self.format_imm(a);
4292        write!(self, "{d} = {a}")
4293    }
4294
4295    fn load_imm64(&mut self, d: RawReg, a: u64) -> Self::ReturnTy {
4296        let d = self.format_reg(d);
4297        write!(self, "{d} = 0x{a:x}")
4298    }
4299
4300    fn move_reg(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4301        let d = self.format_reg(d);
4302        let s = self.format_reg(s);
4303        write!(self, "{d} = {s}")
4304    }
4305
4306    fn count_leading_zero_bits_32(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4307        let d = self.format_reg(d);
4308        let s = self.format_reg(s);
4309        if self.format.is_64_bit {
4310            write!(self, "i32 {d} = clz {s}")
4311        } else {
4312            write!(self, "{d} = clz {s}")
4313        }
4314    }
4315
4316    fn count_leading_zero_bits_64(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4317        let d = self.format_reg(d);
4318        let s = self.format_reg(s);
4319        write!(self, "{d} = clz {s}")
4320    }
4321
4322    fn count_trailing_zero_bits_32(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4323        let d = self.format_reg(d);
4324        let s = self.format_reg(s);
4325        if self.format.is_64_bit {
4326            write!(self, "i32 {d} = ctz {s}")
4327        } else {
4328            write!(self, "{d} = ctz {s}")
4329        }
4330    }
4331
4332    fn count_trailing_zero_bits_64(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4333        let d = self.format_reg(d);
4334        let s = self.format_reg(s);
4335        write!(self, "{d} = ctz {s}")
4336    }
4337
4338    fn count_set_bits_32(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4339        let d = self.format_reg(d);
4340        let s = self.format_reg(s);
4341        if self.format.is_64_bit {
4342            write!(self, "i32 {d} = cpop {s}")
4343        } else {
4344            write!(self, "{d} = cpop {s}")
4345        }
4346    }
4347
4348    fn count_set_bits_64(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4349        let d = self.format_reg(d);
4350        let s = self.format_reg(s);
4351        write!(self, "{d} = cpop {s}")
4352    }
4353
4354    fn sign_extend_8(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4355        let d = self.format_reg(d);
4356        let s = self.format_reg(s);
4357        write!(self, "{d} = sext8 {s}")
4358    }
4359
4360    fn sign_extend_16(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4361        let d = self.format_reg(d);
4362        let s = self.format_reg(s);
4363        write!(self, "{d} = sext16 {s}")
4364    }
4365
4366    fn zero_extend_16(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4367        let d = self.format_reg(d);
4368        let s = self.format_reg(s);
4369        write!(self, "{d} = zext16 {s}")
4370    }
4371
4372    fn reverse_byte(&mut self, d: RawReg, s: RawReg) -> Self::ReturnTy {
4373        let d = self.format_reg(d);
4374        let s = self.format_reg(s);
4375        write!(self, "{d} = reverse {s}")
4376    }
4377
4378    fn cmov_if_zero(&mut self, d: RawReg, s: RawReg, c: RawReg) -> Self::ReturnTy {
4379        let d = self.format_reg(d);
4380        let s = self.format_reg(s);
4381        let c = self.format_reg(c);
4382        write!(self, "{d} = {s} if {c} == 0")
4383    }
4384
4385    fn cmov_if_not_zero(&mut self, d: RawReg, s: RawReg, c: RawReg) -> Self::ReturnTy {
4386        let d = self.format_reg(d);
4387        let s = self.format_reg(s);
4388        let c = self.format_reg(c);
4389        write!(self, "{d} = {s} if {c} != 0")
4390    }
4391
4392    fn cmov_if_zero_imm(&mut self, d: RawReg, c: RawReg, s: i32) -> Self::ReturnTy {
4393        let d = self.format_reg(d);
4394        let c = self.format_reg(c);
4395        let s = self.format_imm(s);
4396        write!(self, "{d} = {s} if {c} == 0")
4397    }
4398
4399    fn cmov_if_not_zero_imm(&mut self, d: RawReg, c: RawReg, s: i32) -> Self::ReturnTy {
4400        let d = self.format_reg(d);
4401        let c = self.format_reg(c);
4402        let s = self.format_imm(s);
4403        write!(self, "{d} = {s} if {c} != 0")
4404    }
4405
4406    fn rotate_right_imm_32(&mut self, d: RawReg, s: RawReg, c: i32) -> Self::ReturnTy {
4407        let d = self.format_reg(d);
4408        let s = self.format_reg(s);
4409        let c = self.format_imm(c);
4410        if self.format.is_64_bit {
4411            write!(self, "i32 {d} = {s} >>r {c}")
4412        } else {
4413            write!(self, "{d} = {s} >> {c}")
4414        }
4415    }
4416
4417    fn rotate_right_imm_alt_32(&mut self, d: RawReg, c: RawReg, s: i32) -> Self::ReturnTy {
4418        let d = self.format_reg(d);
4419        let c = self.format_reg(c);
4420        let s = self.format_imm(s);
4421        if self.format.is_64_bit {
4422            write!(self, "i32 {d} = {s} >>r {c}")
4423        } else {
4424            write!(self, "{d} = {s} >> {c}")
4425        }
4426    }
4427
4428    fn rotate_right_imm_64(&mut self, d: RawReg, s: RawReg, c: i32) -> Self::ReturnTy {
4429        let d = self.format_reg(d);
4430        let s = self.format_reg(s);
4431        let c = self.format_imm(c);
4432        write!(self, "{d} = {s} >>r {c}")
4433    }
4434
4435    fn rotate_right_imm_alt_64(&mut self, d: RawReg, c: RawReg, s: i32) -> Self::ReturnTy {
4436        let d = self.format_reg(d);
4437        let c = self.format_reg(c);
4438        let s = self.format_imm(s);
4439        write!(self, "{d} = {s} >>r {c}")
4440    }
4441
4442    fn add_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4443        let d = self.format_reg(d);
4444        let s1 = self.format_reg(s1);
4445        if !self.format.prefer_unaliased && i64::from(s2) < 0 && i64::from(s2) > -4096 {
4446            write!(self, "{d} = {s1} - {s2}", s2 = -i64::from(s2))
4447        } else {
4448            let s2 = self.format_imm(s2);
4449            write!(self, "{d} = {s1} + {s2}")
4450        }
4451    }
4452
4453    fn add_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4454        let d = self.format_reg(d);
4455        let s1 = self.format_reg(s1);
4456        let prefix = if self.format.is_64_bit { "i32 " } else { "" };
4457        if !self.format.prefer_unaliased && i64::from(s2) < 0 && i64::from(s2) > -4096 {
4458            write!(self, "{prefix}{d} = {s1} - {s2}", s2 = -i64::from(s2))
4459        } else {
4460            let s2 = self.format_imm(s2);
4461            write!(self, "{prefix}{d} = {s1} + {s2}")
4462        }
4463    }
4464
4465    fn negate_and_add_imm_32(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4466        let d = self.format_reg(d);
4467        let s1 = self.format_reg(s1);
4468        let prefix = if self.format.is_64_bit { "i32 " } else { "" };
4469        if !self.format.prefer_unaliased && s2 == 0 {
4470            write!(self, "{prefix}{d} = -{s1}")
4471        } else {
4472            let s2 = self.format_imm(s2);
4473            write!(self, "{prefix}{d} = {s2} - {s1}")
4474        }
4475    }
4476
4477    fn negate_and_add_imm_64(&mut self, d: RawReg, s1: RawReg, s2: i32) -> Self::ReturnTy {
4478        let d = self.format_reg(d);
4479        let s1 = self.format_reg(s1);
4480        if !self.format.prefer_unaliased && s2 == 0 {
4481            write!(self, "{d} = -{s1}")
4482        } else {
4483            let s2 = self.format_imm(s2);
4484            write!(self, "{d} = {s2} - {s1}")
4485        }
4486    }
4487
4488    fn store_imm_indirect_u8(&mut self, base: RawReg, offset: i32, value: i32) -> Self::ReturnTy {
4489        let base = self.format_reg(base);
4490        let value = self.format_imm(value);
4491        let offset = self.format_offset(offset);
4492        write!(self, "u8 [{base}{offset}] = {value}")
4493    }
4494
4495    fn store_imm_indirect_u16(&mut self, base: RawReg, offset: i32, value: i32) -> Self::ReturnTy {
4496        let base = self.format_reg(base);
4497        let value = self.format_imm(value);
4498        let offset = self.format_offset(offset);
4499        write!(self, "u16 [{base}{offset}] = {value}")
4500    }
4501
4502    fn store_imm_indirect_u32(&mut self, base: RawReg, offset: i32, value: i32) -> Self::ReturnTy {
4503        let base = self.format_reg(base);
4504        let value = self.format_imm(value);
4505        let offset = self.format_offset(offset);
4506        write!(self, "u32 [{base}{offset}] = {value}")
4507    }
4508
4509    fn store_imm_indirect_u64(&mut self, base: RawReg, offset: i32, value: i32) -> Self::ReturnTy {
4510        let base = self.format_reg(base);
4511        let value = self.format_imm(value);
4512        let offset = self.format_offset(offset);
4513        write!(self, "u64 [{base}{offset}] = {value}")
4514    }
4515
4516    fn store_indirect_u8(&mut self, src: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4517        let base = self.format_reg(base);
4518        let offset = self.format_offset(offset);
4519        write!(self, "u8 [{base}{offset}] = {src}")
4520    }
4521
4522    fn store_indirect_u16(&mut self, src: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4523        let src = self.format_reg(src);
4524        let base = self.format_reg(base);
4525        let offset = self.format_offset(offset);
4526        write!(self, "u16 [{base}{offset}] = {src}")
4527    }
4528
4529    fn store_indirect_u32(&mut self, src: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4530        let src = self.format_reg(src);
4531        let base = self.format_reg(base);
4532        let offset = self.format_offset(offset);
4533        write!(self, "u32 [{base}{offset}] = {src}")
4534    }
4535
4536    fn store_indirect_u64(&mut self, src: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4537        let src = self.format_reg(src);
4538        let base = self.format_reg(base);
4539        let offset = self.format_offset(offset);
4540        write!(self, "u64 [{base}{offset}] = {src}")
4541    }
4542
4543    fn store_imm_u8(&mut self, offset: i32, value: i32) -> Self::ReturnTy {
4544        let offset = self.format_imm(offset);
4545        let value = self.format_imm(value);
4546        write!(self, "u8 [{offset}] = {value}")
4547    }
4548
4549    fn store_imm_u16(&mut self, offset: i32, value: i32) -> Self::ReturnTy {
4550        let offset = self.format_imm(offset);
4551        let value = self.format_imm(value);
4552        write!(self, "u16 [{offset}] = {value}")
4553    }
4554
4555    fn store_imm_u32(&mut self, offset: i32, value: i32) -> Self::ReturnTy {
4556        let offset = self.format_imm(offset);
4557        let value = self.format_imm(value);
4558        write!(self, "u32 [{offset}] = {value}")
4559    }
4560
4561    fn store_imm_u64(&mut self, offset: i32, value: i32) -> Self::ReturnTy {
4562        let offset = self.format_imm(offset);
4563        let value = self.format_imm(value);
4564        write!(self, "u64 [{offset}] = {value}")
4565    }
4566
4567    fn store_u8(&mut self, src: RawReg, offset: i32) -> Self::ReturnTy {
4568        let src = self.format_reg(src);
4569        let offset = self.format_imm(offset);
4570        write!(self, "u8 [{offset}] = {src}")
4571    }
4572
4573    fn store_u16(&mut self, src: RawReg, offset: i32) -> Self::ReturnTy {
4574        let src = self.format_reg(src);
4575        let offset = self.format_imm(offset);
4576        write!(self, "u16 [{offset}] = {src}")
4577    }
4578
4579    fn store_u32(&mut self, src: RawReg, offset: i32) -> Self::ReturnTy {
4580        let src = self.format_reg(src);
4581        let offset = self.format_imm(offset);
4582        write!(self, "u32 [{offset}] = {src}")
4583    }
4584
4585    fn store_u64(&mut self, src: RawReg, offset: i32) -> Self::ReturnTy {
4586        let src = self.format_reg(src);
4587        let offset = self.format_imm(offset);
4588        write!(self, "u64 [{offset}] = {src}")
4589    }
4590
4591    fn load_indirect_u8(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4592        let dst = self.format_reg(dst);
4593        let base = self.format_reg(base);
4594        let offset = self.format_offset(offset);
4595        write!(self, "{} = u8 [{}{}]", dst, base, offset)
4596    }
4597
4598    fn load_indirect_i8(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4599        let dst = self.format_reg(dst);
4600        let base = self.format_reg(base);
4601        let offset = self.format_offset(offset);
4602        write!(self, "{} = i8 [{}{}]", dst, base, offset)
4603    }
4604
4605    fn load_indirect_u16(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4606        let dst = self.format_reg(dst);
4607        let base = self.format_reg(base);
4608        let offset = self.format_offset(offset);
4609        write!(self, "{} = u16 [{}{}]", dst, base, offset)
4610    }
4611
4612    fn load_indirect_i16(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4613        let dst = self.format_reg(dst);
4614        let base = self.format_reg(base);
4615        let offset = self.format_offset(offset);
4616        write!(self, "{} = i16 [{}{}]", dst, base, offset)
4617    }
4618
4619    fn load_indirect_u32(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4620        let dst = self.format_reg(dst);
4621        let base = self.format_reg(base);
4622        let offset = self.format_offset(offset);
4623        write!(self, "{} = u32 [{}{}]", dst, base, offset)
4624    }
4625
4626    fn load_indirect_i32(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4627        let dst = self.format_reg(dst);
4628        let base = self.format_reg(base);
4629        let offset = self.format_offset(offset);
4630        write!(self, "{} = i32 [{}{}]", dst, base, offset)
4631    }
4632
4633    fn load_indirect_u64(&mut self, dst: RawReg, base: RawReg, offset: i32) -> Self::ReturnTy {
4634        let dst = self.format_reg(dst);
4635        let base = self.format_reg(base);
4636        let offset = self.format_offset(offset);
4637        write!(self, "{} = u64 [{}{}]", dst, base, offset)
4638    }
4639
4640    fn load_u8(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4641        let dst = self.format_reg(dst);
4642        let offset = self.format_imm(offset);
4643        write!(self, "{} = u8 [{}]", dst, offset)
4644    }
4645
4646    fn load_i8(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4647        let dst = self.format_reg(dst);
4648        let offset = self.format_imm(offset);
4649        write!(self, "{} = i8 [{}]", dst, offset)
4650    }
4651
4652    fn load_u16(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4653        let dst = self.format_reg(dst);
4654        let offset = self.format_imm(offset);
4655        write!(self, "{} = u16 [{}]", dst, offset)
4656    }
4657
4658    fn load_i16(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4659        let dst = self.format_reg(dst);
4660        let offset = self.format_imm(offset);
4661        write!(self, "{} = i16 [{}]", dst, offset)
4662    }
4663
4664    fn load_i32(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4665        let dst = self.format_reg(dst);
4666        let offset = self.format_imm(offset);
4667        write!(self, "{} = i32 [{}]", dst, offset)
4668    }
4669
4670    fn load_u32(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4671        let dst = self.format_reg(dst);
4672        let offset = self.format_imm(offset);
4673        write!(self, "{} = u32 [{}]", dst, offset)
4674    }
4675
4676    fn load_u64(&mut self, dst: RawReg, offset: i32) -> Self::ReturnTy {
4677        let dst = self.format_reg(dst);
4678        let offset = self.format_imm(offset);
4679        write!(self, "{} = u64 [{}]", dst, offset)
4680    }
4681
4682    fn branch_less_unsigned(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4683        let s1 = self.format_reg(s1);
4684        let s2 = self.format_reg(s2);
4685        let imm = self.format_jump(imm);
4686        write!(self, "jump {} if {} <u {}", imm, s1, s2)
4687    }
4688
4689    fn branch_less_signed(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4690        let s1 = self.format_reg(s1);
4691        let s2 = self.format_reg(s2);
4692        let imm = self.format_jump(imm);
4693        write!(self, "jump {} if {} <s {}", imm, s1, s2)
4694    }
4695
4696    fn branch_less_unsigned_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4697        let s1 = self.format_reg(s1);
4698        let imm = self.format_jump(imm);
4699        write!(self, "jump {} if {} <u {}", imm, s1, s2)
4700    }
4701
4702    fn branch_less_signed_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4703        let s1 = self.format_reg(s1);
4704        let imm = self.format_jump(imm);
4705        write!(self, "jump {} if {} <s {}", imm, s1, s2)
4706    }
4707
4708    fn branch_greater_or_equal_unsigned(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4709        let s1 = self.format_reg(s1);
4710        let s2 = self.format_reg(s2);
4711        let imm = self.format_jump(imm);
4712        write!(self, "jump {} if {} >=u {}", imm, s1, s2)
4713    }
4714
4715    fn branch_greater_or_equal_signed(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4716        let s1 = self.format_reg(s1);
4717        let s2 = self.format_reg(s2);
4718        let imm = self.format_jump(imm);
4719        write!(self, "jump {} if {} >=s {}", imm, s1, s2)
4720    }
4721
4722    fn branch_greater_or_equal_unsigned_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4723        let s1 = self.format_reg(s1);
4724        let imm = self.format_jump(imm);
4725        write!(self, "jump {} if {} >=u {}", imm, s1, s2)
4726    }
4727
4728    fn branch_greater_or_equal_signed_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4729        let s1 = self.format_reg(s1);
4730        let imm = self.format_jump(imm);
4731        write!(self, "jump {} if {} >=s {}", imm, s1, s2)
4732    }
4733
4734    fn branch_eq(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4735        let s1 = self.format_reg(s1);
4736        let s2 = self.format_reg(s2);
4737        let imm = self.format_jump(imm);
4738        write!(self, "jump {} if {} == {}", imm, s1, s2)
4739    }
4740
4741    fn branch_not_eq(&mut self, s1: RawReg, s2: RawReg, imm: u32) -> Self::ReturnTy {
4742        let s1 = self.format_reg(s1);
4743        let s2 = self.format_reg(s2);
4744        let imm = self.format_jump(imm);
4745        write!(self, "jump {} if {} != {}", imm, s1, s2)
4746    }
4747
4748    fn branch_eq_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4749        let s1 = self.format_reg(s1);
4750        let imm = self.format_jump(imm);
4751        write!(self, "jump {} if {} == {}", imm, s1, s2)
4752    }
4753
4754    fn branch_not_eq_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4755        let s1 = self.format_reg(s1);
4756        let imm = self.format_jump(imm);
4757        write!(self, "jump {} if {} != {}", imm, s1, s2)
4758    }
4759
4760    fn branch_less_or_equal_unsigned_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4761        let s1 = self.format_reg(s1);
4762        let imm = self.format_jump(imm);
4763        write!(self, "jump {} if {} <=u {}", imm, s1, s2)
4764    }
4765
4766    fn branch_less_or_equal_signed_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4767        let s1 = self.format_reg(s1);
4768        let imm = self.format_jump(imm);
4769        write!(self, "jump {} if {} <=s {}", imm, s1, s2)
4770    }
4771
4772    fn branch_greater_unsigned_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4773        let s1 = self.format_reg(s1);
4774        let imm = self.format_jump(imm);
4775        write!(self, "jump {} if {} >u {}", imm, s1, s2)
4776    }
4777
4778    fn branch_greater_signed_imm(&mut self, s1: RawReg, s2: i32, imm: u32) -> Self::ReturnTy {
4779        let s1 = self.format_reg(s1);
4780        let imm = self.format_jump(imm);
4781        write!(self, "jump {} if {} >s {}", imm, s1, s2)
4782    }
4783
4784    fn jump(&mut self, target: u32) -> Self::ReturnTy {
4785        let target = self.format_jump(target);
4786        write!(self, "jump {}", target)
4787    }
4788
4789    fn load_imm_and_jump(&mut self, ra: RawReg, value: i32, target: u32) -> Self::ReturnTy {
4790        let ra = self.format_reg(ra);
4791        let target = self.format_jump(target);
4792        write!(self, "{ra} = {value}, jump {target}")
4793    }
4794
4795    fn jump_indirect(&mut self, base: RawReg, offset: i32) -> Self::ReturnTy {
4796        if !self.format.prefer_unaliased {
4797            match (base, offset) {
4798                (_, 0) if base == Reg::RA.into() => return write!(self, "ret"),
4799                (_, 0) => return write!(self, "jump [{}]", self.format_reg(base)),
4800                (_, _) => {}
4801            }
4802        }
4803
4804        let offset = self.format_offset(offset);
4805        write!(self, "jump [{}{}]", self.format_reg(base), offset)
4806    }
4807
4808    fn load_imm_and_jump_indirect(&mut self, ra: RawReg, base: RawReg, value: i32, offset: i32) -> Self::ReturnTy {
4809        let ra = self.format_reg(ra);
4810        let base = self.format_reg(base);
4811        if ra != base {
4812            if !self.format.prefer_unaliased && offset == 0 {
4813                write!(self, "{ra} = {value}, jump [{base}]")
4814            } else {
4815                let offset = self.format_offset(offset);
4816                write!(self, "{ra} = {value}, jump [{base}{offset}]")
4817            }
4818        } else if !self.format.prefer_unaliased && offset == 0 {
4819            write!(self, "tmp = {base}, {ra} = {value}, jump [tmp]")
4820        } else {
4821            let offset = self.format_offset(offset);
4822            write!(self, "tmp = {base}, {ra} = {value}, jump [tmp{offset}]")
4823        }
4824    }
4825
4826    fn invalid(&mut self) -> Self::ReturnTy {
4827        write!(self, "invalid")
4828    }
4829}
4830
4831#[derive(Debug)]
4832pub struct ProgramParseError(ProgramParseErrorKind);
4833
4834#[derive(Debug)]
4835enum ProgramParseErrorKind {
4836    FailedToReadVarint {
4837        offset: usize,
4838    },
4839    FailedToReadStringNonUtf {
4840        offset: usize,
4841    },
4842    UnexpectedSection {
4843        offset: usize,
4844        section: u8,
4845    },
4846    UnexpectedEnd {
4847        offset: usize,
4848        expected_count: usize,
4849        actual_count: usize,
4850    },
4851    UnsupportedVersion {
4852        version: u8,
4853    },
4854    Other(&'static str),
4855}
4856
4857impl ProgramParseError {
4858    #[cold]
4859    #[inline]
4860    fn failed_to_read_varint(offset: usize) -> ProgramParseError {
4861        ProgramParseError(ProgramParseErrorKind::FailedToReadVarint { offset })
4862    }
4863
4864    #[cold]
4865    #[inline]
4866    fn unexpected_end_of_file(offset: usize, expected_count: usize, actual_count: usize) -> ProgramParseError {
4867        ProgramParseError(ProgramParseErrorKind::UnexpectedEnd {
4868            offset,
4869            expected_count,
4870            actual_count,
4871        })
4872    }
4873}
4874
4875impl core::fmt::Display for ProgramParseError {
4876    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
4877        match self.0 {
4878            ProgramParseErrorKind::FailedToReadVarint { offset } => {
4879                write!(
4880                    fmt,
4881                    "failed to parse program blob: failed to parse a varint at offset 0x{:x}",
4882                    offset
4883                )
4884            }
4885            ProgramParseErrorKind::FailedToReadStringNonUtf { offset } => {
4886                write!(
4887                    fmt,
4888                    "failed to parse program blob: failed to parse a string at offset 0x{:x} (not valid UTF-8)",
4889                    offset
4890                )
4891            }
4892            ProgramParseErrorKind::UnexpectedSection { offset, section } => {
4893                write!(
4894                    fmt,
4895                    "failed to parse program blob: found unexpected section as offset 0x{:x}: 0x{:x}",
4896                    offset, section
4897                )
4898            }
4899            ProgramParseErrorKind::UnexpectedEnd {
4900                offset,
4901                expected_count,
4902                actual_count,
4903            } => {
4904                write!(fmt, "failed to parse program blob: unexpected end of file at offset 0x{:x}: expected to be able to read at least {} bytes, found {} bytes", offset, expected_count, actual_count)
4905            }
4906            ProgramParseErrorKind::UnsupportedVersion { version } => {
4907                write!(fmt, "failed to parse program blob: unsupported version: {}", version)
4908            }
4909            ProgramParseErrorKind::Other(error) => {
4910                write!(fmt, "failed to parse program blob: {}", error)
4911            }
4912        }
4913    }
4914}
4915
4916#[cfg(feature = "alloc")]
4917impl From<ProgramParseError> for alloc::string::String {
4918    fn from(error: ProgramParseError) -> alloc::string::String {
4919        use alloc::string::ToString;
4920        error.to_string()
4921    }
4922}
4923
4924impl core::error::Error for ProgramParseError {}
4925
4926#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
4927#[repr(transparent)]
4928pub struct ProgramCounter(pub u32);
4929
4930impl core::fmt::Display for ProgramCounter {
4931    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
4932        self.0.fmt(fmt)
4933    }
4934}
4935
4936#[derive(Clone, PartialEq, Eq, Debug)]
4937pub struct ProgramExport<T> {
4938    program_counter: ProgramCounter,
4939    symbol: ProgramSymbol<T>,
4940}
4941
4942impl<T> ProgramExport<T>
4943where
4944    T: AsRef<[u8]>,
4945{
4946    pub fn new(program_counter: ProgramCounter, symbol: ProgramSymbol<T>) -> Self {
4947        Self { program_counter, symbol }
4948    }
4949
4950    pub fn program_counter(&self) -> ProgramCounter {
4951        self.program_counter
4952    }
4953
4954    pub fn symbol(&self) -> &ProgramSymbol<T> {
4955        &self.symbol
4956    }
4957}
4958
4959impl<T> PartialEq<str> for ProgramExport<T>
4960where
4961    T: AsRef<[u8]>,
4962{
4963    fn eq(&self, rhs: &str) -> bool {
4964        self.symbol.as_bytes() == rhs.as_bytes()
4965    }
4966}
4967
4968#[derive(Clone, PartialEq, Eq, Debug)]
4969pub struct ProgramSymbol<T>(T);
4970
4971impl<T> ProgramSymbol<T>
4972where
4973    T: AsRef<[u8]>,
4974{
4975    pub fn new(bytes: T) -> Self {
4976        Self(bytes)
4977    }
4978
4979    pub fn into_inner(self) -> T {
4980        self.0
4981    }
4982
4983    pub fn as_bytes(&self) -> &[u8] {
4984        self.0.as_ref()
4985    }
4986}
4987
4988impl<T> PartialEq<str> for ProgramSymbol<T>
4989where
4990    T: AsRef<[u8]>,
4991{
4992    fn eq(&self, rhs: &str) -> bool {
4993        self.as_bytes() == rhs.as_bytes()
4994    }
4995}
4996
4997impl<'a, T> PartialEq<&'a str> for ProgramSymbol<T>
4998where
4999    T: AsRef<[u8]>,
5000{
5001    fn eq(&self, rhs: &&'a str) -> bool {
5002        self.as_bytes() == rhs.as_bytes()
5003    }
5004}
5005
5006impl<T> core::fmt::Display for ProgramSymbol<T>
5007where
5008    T: AsRef<[u8]>,
5009{
5010    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
5011        let bytes = self.0.as_ref();
5012        if let Ok(ident) = core::str::from_utf8(bytes) {
5013            fmt.write_str("'")?;
5014            fmt.write_str(ident)?;
5015            fmt.write_str("'")?;
5016        } else {
5017            fmt.write_str("0x")?;
5018            for &byte in bytes.iter() {
5019                core::write!(fmt, "{:02x}", byte)?;
5020            }
5021        }
5022
5023        Ok(())
5024    }
5025}
5026
5027/// A partially deserialized PolkaVM program.
5028#[derive(Clone)]
5029pub struct ProgramBlob {
5030    #[cfg(feature = "unique-id")]
5031    unique_id: u64,
5032
5033    isa: InstructionSetKind,
5034
5035    ro_data_size: u32,
5036    rw_data_size: u32,
5037    stack_size: u32,
5038
5039    ro_data: ArcBytes,
5040    rw_data: ArcBytes,
5041    code: ArcBytes,
5042    jump_table: ArcBytes,
5043    jump_table_entry_size: u8,
5044    bitmask: ArcBytes,
5045    import_offsets: ArcBytes,
5046    import_symbols: ArcBytes,
5047    exports: ArcBytes,
5048
5049    debug_strings: ArcBytes,
5050    debug_line_program_ranges: ArcBytes,
5051    debug_line_programs: ArcBytes,
5052
5053    metadata_hash: ArcBytes,
5054}
5055
5056struct Reader<'a, T>
5057where
5058    T: ?Sized,
5059{
5060    blob: &'a T,
5061    position: usize,
5062}
5063
5064impl<'a, T> Clone for Reader<'a, T>
5065where
5066    T: ?Sized,
5067{
5068    fn clone(&self) -> Self {
5069        Reader {
5070            blob: self.blob,
5071            position: self.position,
5072        }
5073    }
5074}
5075
5076impl<'a, T> From<&'a T> for Reader<'a, T> {
5077    fn from(blob: &'a T) -> Self {
5078        Self { blob, position: 0 }
5079    }
5080}
5081
5082impl<'a, T> Reader<'a, T>
5083where
5084    T: ?Sized + AsRef<[u8]>,
5085{
5086    fn skip(&mut self, count: usize) -> Result<(), ProgramParseError> {
5087        self.read_slice_as_range(count).map(|_| ())
5088    }
5089
5090    #[inline(always)]
5091    fn read_byte(&mut self) -> Result<u8, ProgramParseError> {
5092        Ok(self.read_slice(1)?[0])
5093    }
5094
5095    #[inline(always)]
5096    fn read_slice(&mut self, length: usize) -> Result<&'a [u8], ProgramParseError> {
5097        let blob = &self.blob.as_ref()[self.position..];
5098        let Some(slice) = blob.get(..length) else {
5099            return Err(ProgramParseError::unexpected_end_of_file(self.position, length, blob.len()));
5100        };
5101
5102        self.position += length;
5103        Ok(slice)
5104    }
5105
5106    #[inline(always)]
5107    fn read_varint(&mut self) -> Result<u32, ProgramParseError> {
5108        let first_byte = self.read_byte()?;
5109        let Some((length, value)) = read_varint(&self.blob.as_ref()[self.position..], first_byte) else {
5110            return Err(ProgramParseError::failed_to_read_varint(self.position - 1));
5111        };
5112
5113        self.position += length;
5114        Ok(value)
5115    }
5116
5117    fn read_bytes_with_length(&mut self) -> Result<&'a [u8], ProgramParseError> {
5118        let length = self.read_varint()? as usize;
5119        self.read_slice(length)
5120    }
5121
5122    fn read_string_with_length(&mut self) -> Result<&'a str, ProgramParseError> {
5123        let offset = self.position;
5124        let slice = self.read_bytes_with_length()?;
5125
5126        core::str::from_utf8(slice)
5127            .ok()
5128            .ok_or(ProgramParseError(ProgramParseErrorKind::FailedToReadStringNonUtf { offset }))
5129    }
5130
5131    fn read_slice_as_range(&mut self, count: usize) -> Result<Range<usize>, ProgramParseError> {
5132        let blob = &self.blob.as_ref()[self.position..];
5133        if blob.len() < count {
5134            return Err(ProgramParseError::unexpected_end_of_file(self.position, count, blob.len()));
5135        };
5136
5137        let range = self.position..self.position + count;
5138        self.position += count;
5139        Ok(range)
5140    }
5141}
5142
5143impl<'a> Reader<'a, ArcBytes> {
5144    fn read_slice_as_bytes(&mut self, length: usize) -> Result<ArcBytes, ProgramParseError> {
5145        let range = self.read_slice_as_range(length)?;
5146        Ok(self.blob.subslice(range))
5147    }
5148
5149    fn read_section_as_bytes(&mut self, out_section: &mut u8, expected_section: u8) -> Result<ArcBytes, ProgramParseError> {
5150        if *out_section != expected_section {
5151            return Ok(ArcBytes::default());
5152        }
5153
5154        let section_length = self.read_varint()? as usize;
5155        let range = self.read_slice_as_range(section_length)?;
5156        *out_section = self.read_byte()?;
5157
5158        Ok(self.blob.subslice(range))
5159    }
5160}
5161
5162#[derive(Copy, Clone)]
5163pub struct Imports<'a> {
5164    offsets: &'a [u8],
5165    symbols: &'a [u8],
5166}
5167
5168impl<'a> Imports<'a> {
5169    pub fn is_empty(&self) -> bool {
5170        self.len() == 0
5171    }
5172
5173    pub fn len(&self) -> u32 {
5174        (self.offsets.len() / 4) as u32
5175    }
5176
5177    pub fn get(&self, index: u32) -> Option<ProgramSymbol<&'a [u8]>> {
5178        let offset_start = index.checked_mul(4)?;
5179        let offset_end = offset_start.checked_add(4)?;
5180        let xs = self.offsets.get(offset_start as usize..offset_end as usize)?;
5181        let offset = u32::from_le_bytes([xs[0], xs[1], xs[2], xs[3]]) as usize;
5182        let next_offset = offset_end
5183            .checked_add(4)
5184            .and_then(|next_offset_end| self.offsets.get(offset_end as usize..next_offset_end as usize))
5185            .map_or(self.symbols.len(), |xs| u32::from_le_bytes([xs[0], xs[1], xs[2], xs[3]]) as usize);
5186
5187        let symbol = self.symbols.get(offset..next_offset)?;
5188        Some(ProgramSymbol::new(symbol))
5189    }
5190
5191    pub fn iter(&self) -> ImportsIter<'a> {
5192        ImportsIter { imports: *self, index: 0 }
5193    }
5194}
5195
5196impl<'a> IntoIterator for Imports<'a> {
5197    type Item = Option<ProgramSymbol<&'a [u8]>>;
5198    type IntoIter = ImportsIter<'a>;
5199
5200    fn into_iter(self) -> Self::IntoIter {
5201        self.iter()
5202    }
5203}
5204
5205impl<'a> IntoIterator for &'a Imports<'a> {
5206    type Item = Option<ProgramSymbol<&'a [u8]>>;
5207    type IntoIter = ImportsIter<'a>;
5208
5209    fn into_iter(self) -> Self::IntoIter {
5210        self.iter()
5211    }
5212}
5213
5214pub struct ImportsIter<'a> {
5215    imports: Imports<'a>,
5216    index: u32,
5217}
5218
5219impl<'a> Iterator for ImportsIter<'a> {
5220    type Item = Option<ProgramSymbol<&'a [u8]>>;
5221    fn next(&mut self) -> Option<Self::Item> {
5222        if self.index >= self.imports.len() {
5223            None
5224        } else {
5225            let value = self.imports.get(self.index);
5226            self.index += 1;
5227            Some(value)
5228        }
5229    }
5230}
5231
5232#[derive(Copy, Clone)]
5233pub struct JumpTable<'a> {
5234    blob: &'a [u8],
5235    entry_size: u32,
5236}
5237
5238impl<'a> JumpTable<'a> {
5239    pub fn is_empty(&self) -> bool {
5240        self.len() == 0
5241    }
5242
5243    pub fn len(&self) -> u32 {
5244        if self.entry_size == 0 {
5245            0
5246        } else {
5247            self.blob.len() as u32 / self.entry_size
5248        }
5249    }
5250
5251    pub fn get_by_address(&self, address: u32) -> Option<ProgramCounter> {
5252        if address & (VM_CODE_ADDRESS_ALIGNMENT - 1) != 0 || address == 0 {
5253            return None;
5254        }
5255
5256        self.get_by_index((address - VM_CODE_ADDRESS_ALIGNMENT) / VM_CODE_ADDRESS_ALIGNMENT)
5257    }
5258
5259    pub fn get_by_index(&self, index: u32) -> Option<ProgramCounter> {
5260        if self.entry_size == 0 {
5261            return None;
5262        }
5263
5264        let start = index.checked_mul(self.entry_size)?;
5265        let end = start.checked_add(self.entry_size)?;
5266        self.blob
5267            .get(start as usize..end as usize)
5268            .map(|xs| match xs.len() {
5269                1 => u32::from(xs[0]),
5270                2 => u32::from(u16::from_le_bytes([xs[0], xs[1]])),
5271                3 => u32::from_le_bytes([xs[0], xs[1], xs[2], 0]),
5272                4 => u32::from_le_bytes([xs[0], xs[1], xs[2], xs[3]]),
5273                _ => unreachable!(),
5274            })
5275            .map(ProgramCounter)
5276    }
5277
5278    pub fn iter(&self) -> JumpTableIter<'a> {
5279        JumpTableIter {
5280            jump_table: *self,
5281            index: 0,
5282        }
5283    }
5284}
5285
5286impl<'a> IntoIterator for JumpTable<'a> {
5287    type Item = ProgramCounter;
5288    type IntoIter = JumpTableIter<'a>;
5289
5290    fn into_iter(self) -> Self::IntoIter {
5291        self.iter()
5292    }
5293}
5294
5295impl<'a> IntoIterator for &'a JumpTable<'a> {
5296    type Item = ProgramCounter;
5297    type IntoIter = JumpTableIter<'a>;
5298
5299    fn into_iter(self) -> Self::IntoIter {
5300        self.iter()
5301    }
5302}
5303
5304pub struct JumpTableIter<'a> {
5305    jump_table: JumpTable<'a>,
5306    index: u32,
5307}
5308
5309impl<'a> Iterator for JumpTableIter<'a> {
5310    type Item = ProgramCounter;
5311    fn next(&mut self) -> Option<Self::Item> {
5312        let value = self.jump_table.get_by_index(self.index)?;
5313        self.index += 1;
5314        Some(value)
5315    }
5316}
5317
5318pub const BITMASK_MAX: u32 = 24;
5319
5320fn get_bit_for_offset(bitmask: &[u8], code_len: usize, offset: u32) -> bool {
5321    let Some(byte) = bitmask.get(offset as usize >> 3) else {
5322        return false;
5323    };
5324
5325    if offset as usize > code_len {
5326        return false;
5327    }
5328
5329    let shift = offset & 7;
5330    ((byte >> shift) & 1) == 1
5331}
5332
5333fn get_previous_instruction_skip(bitmask: &[u8], offset: u32) -> Option<u32> {
5334    let shift = offset & 7;
5335    let mut mask = u64::from(bitmask[offset as usize >> 3]) << 56;
5336    if offset >= 8 {
5337        mask |= u64::from(bitmask[(offset as usize >> 3) - 1]) << 48;
5338    }
5339    if offset >= 16 {
5340        mask |= u64::from(bitmask[(offset as usize >> 3) - 2]) << 40;
5341    }
5342    if offset >= 24 {
5343        mask |= u64::from(bitmask[(offset as usize >> 3) - 3]) << 32;
5344    }
5345    if offset >= 32 {
5346        mask |= u64::from(bitmask[(offset as usize >> 3) - 4]) << 24;
5347    }
5348
5349    mask <<= 8 - shift;
5350    mask >>= 1;
5351    let skip = mask.leading_zeros() - 1;
5352    if skip > BITMASK_MAX {
5353        None
5354    } else {
5355        Some(skip)
5356    }
5357}
5358
5359#[test]
5360fn test_get_previous_instruction_skip() {
5361    assert_eq!(get_previous_instruction_skip(&[0b00000001], 0), None);
5362    assert_eq!(get_previous_instruction_skip(&[0b00000011], 0), None);
5363    assert_eq!(get_previous_instruction_skip(&[0b00000010], 1), None);
5364    assert_eq!(get_previous_instruction_skip(&[0b00000011], 1), Some(0));
5365    assert_eq!(get_previous_instruction_skip(&[0b00000001], 1), Some(0));
5366    assert_eq!(get_previous_instruction_skip(&[0b00000001, 0b00000001], 8), Some(7));
5367    assert_eq!(get_previous_instruction_skip(&[0b00000001, 0b00000000], 8), Some(7));
5368}
5369
5370#[test]
5371fn test_get_previous_instruction_skip_max_length() {
5372    for previous in 0_u32..64 {
5373        let mut bitmask = [0_u8; 16];
5374        bitmask[cast(previous).to_usize() >> 3] |= 1 << (previous & 7);
5375
5376        let offset = previous + BITMASK_MAX + 1;
5377        assert_eq!(
5378            get_previous_instruction_skip(&bitmask, offset),
5379            Some(BITMASK_MAX),
5380            "the instruction at {previous} is out of reach from {offset}"
5381        );
5382
5383        assert_eq!(get_previous_instruction_skip(&bitmask, offset + 1), None);
5384    }
5385}
5386
5387#[repr(transparent)]
5388#[derive(Copy, Clone)]
5389pub struct RawOpcodeLength(u8);
5390
5391impl RawOpcodeLength {
5392    #[inline]
5393    pub fn get(self) -> u32 {
5394        u32::from(self.0)
5395    }
5396}
5397
5398#[repr(transparent)]
5399#[derive(Copy, Clone, PartialEq, Eq)]
5400pub struct RawOpcodeEntry(u16);
5401
5402impl RawOpcodeEntry {
5403    pub const fn empty() -> Self {
5404        Self::new(EXTENDED_INVALID_RAW_OPCODE as u16, 0)
5405    }
5406
5407    pub const fn is_empty(self) -> bool {
5408        self.raw_opcode() == EXTENDED_INVALID_RAW_OPCODE as u16
5409    }
5410
5411    pub const fn new(raw_opcode: u16, args_length: u16) -> Self {
5412        assert!(args_length < 2_u16.pow(4));
5413        assert!(raw_opcode < 2_u16.pow(12));
5414        Self(raw_opcode | (args_length << 12))
5415    }
5416
5417    pub const fn raw_opcode(self) -> u16 {
5418        self.0 & 0x0fff
5419    }
5420
5421    pub const fn args_length(self) -> u16 {
5422        self.0 >> 12
5423    }
5424}
5425
5426pub struct RawOpcodeTable {
5427    length_table: [RawOpcodeLength; EXTENDED_RAW_OPCODE_COUNT],
5428    starts_new_basic_block_table: [bool; EXTENDED_RAW_OPCODE_COUNT],
5429}
5430
5431impl RawOpcodeTable {
5432    #[inline(always)]
5433    fn ends_basic_block(&self, raw_opcode: usize) -> bool {
5434        let Some(&ends_basic_block) = self.starts_new_basic_block_table.get(raw_opcode) else {
5435            unreachable!();
5436        };
5437
5438        ends_basic_block
5439    }
5440}
5441
5442pub trait InstructionSet: Copy {
5443    fn opcode_from_raw(self, raw_opcode: u32) -> Option<Opcode>;
5444    fn opcode_to_raw(self, opcode: Opcode, args_length: u32) -> Option<(u32, u32)>;
5445    fn parse_instruction(self, raw_opcode: usize, chunk: u128, offset: u32, length: u32) -> Instruction;
5446    fn supports_opcode(self, opcode: Opcode) -> bool;
5447    fn is_legacy(self) -> bool;
5448
5449    fn raw_opcode_table(self) -> &'static RawOpcodeTable {
5450        unimplemented!();
5451    }
5452}
5453
5454pub const CODE_BLOCK_SIZE: usize = 1024;
5455const _: () = assert!(CODE_BLOCK_SIZE.is_power_of_two());
5456
5457#[inline(always)]
5458fn start_of_block_boundary(offset: usize) -> usize {
5459    offset & !(CODE_BLOCK_SIZE - 1)
5460}
5461
5462#[inline(always)]
5463fn is_on_a_block_boundary(offset: usize) -> bool {
5464    offset % CODE_BLOCK_SIZE == 0
5465}
5466
5467#[inline(always)]
5468pub(crate) fn next_block_boundary(offset: usize) -> usize {
5469    start_of_block_boundary(offset) + CODE_BLOCK_SIZE
5470}
5471
5472#[inline(always)]
5473fn end_of_macro_block(offset: usize, code_len: usize) -> usize {
5474    next_block_boundary(offset).min(code_len)
5475}
5476
5477const EXTENDED_OPCODE_PREFIX: u8 = 255;
5478const EXTENDED_INVALID_RAW_OPCODE: usize = 512;
5479
5480#[doc(hidden)]
5481pub const EXTENDED_RAW_OPCODE_COUNT: usize = 513;
5482const EXTENDED_MAX_ARGS_LENGTH: usize = 10;
5483
5484fn extended_scan_is_instruction_boundary<I>(instruction_set: I, code: &[u8], offset: u32) -> bool
5485where
5486    I: InstructionSet,
5487{
5488    debug_assert!(!instruction_set.is_legacy());
5489
5490    let offset = cast(offset).to_usize();
5491    if offset >= code.len() {
5492        return false;
5493    }
5494
5495    let mut position = start_of_block_boundary(offset);
5496    while position < offset {
5497        position = parse_simple_extended(instruction_set, code, position).next_offset;
5498    }
5499
5500    position == offset
5501}
5502
5503fn extended_scan_find_next_offset<I>(instruction_set: I, code: &[u8], offset: u32) -> u32
5504where
5505    I: InstructionSet,
5506{
5507    let offset = cast(offset).to_usize();
5508    if offset >= code.len() {
5509        return code.len() as u32;
5510    }
5511
5512    let mut position = start_of_block_boundary(offset);
5513    while position <= offset {
5514        debug_assert!(position < code.len());
5515        position = parse_simple_extended(instruction_set, code, position).next_offset;
5516    }
5517
5518    core::cmp::min(position, code.len()) as u32
5519}
5520
5521#[cfg(feature = "alloc")]
5522pub fn extended_assert_decode_is_deterministic<I>(instruction_set: I, code: &[u8])
5523where
5524    I: InstructionSet,
5525{
5526    use alloc::vec::Vec;
5527
5528    assert!(!instruction_set.is_legacy());
5529    assert!(code.len() <= u32::MAX as usize);
5530
5531    let mut linear: Vec<usize> = Vec::new();
5532    let mut offset = 0;
5533    while offset < code.len() {
5534        linear.push(offset);
5535        let next_offset = parse_simple_extended(instruction_set, code, offset).next_offset;
5536        assert!(next_offset > offset);
5537        offset = next_offset;
5538    }
5539
5540    let mut linear_iter = linear.iter().copied().peekable();
5541    let mut block_start = 0;
5542    while block_start < code.len() {
5543        assert_eq!(linear_iter.peek(), Some(&block_start));
5544
5545        let block_end = core::cmp::min(code.len(), block_start + CODE_BLOCK_SIZE);
5546        let mut offset = block_start;
5547        let mut last_raw_opcode = EXTENDED_INVALID_RAW_OPCODE;
5548        while offset < block_end {
5549            assert_eq!(linear_iter.next(), Some(offset));
5550
5551            let step = parse_simple_extended(instruction_set, code, offset);
5552            assert_eq!(offset + step.length as usize, step.next_offset, "mismatch at offset {offset}");
5553            offset = step.next_offset;
5554            last_raw_opcode = step.raw_opcode;
5555        }
5556
5557        assert_eq!(offset, block_end);
5558        assert!(
5559            ends_basic_block_extended(instruction_set, last_raw_opcode),
5560            "the macro block at offset {block_start} doesn't end a basic block"
5561        );
5562
5563        block_start += CODE_BLOCK_SIZE;
5564    }
5565
5566    assert_eq!(linear_iter.next(), None);
5567
5568    for offset in 0..=code.len() {
5569        assert_eq!(
5570            extended_scan_is_instruction_boundary(instruction_set, code, offset as u32),
5571            linear.binary_search(&offset).is_ok(),
5572            "mismatch at offset {offset}"
5573        );
5574    }
5575
5576    for &offset in &linear {
5577        let step = parse_simple_extended(instruction_set, code, offset);
5578        if ends_basic_block_extended(instruction_set, step.raw_opcode) && step.next_offset < code.len() {
5579            assert!(
5580                scan_is_jump_target_valid_extended(instruction_set, code, step.next_offset as u32),
5581                "the instruction after the one at offset {offset} is not a valid jump target"
5582            );
5583        }
5584    }
5585
5586    let mut block_start = 0;
5587    while block_start < code.len() {
5588        let mut bitmap = CodeBlockBitmap::new();
5589        bitmap.build(instruction_set, code, block_start as u32);
5590
5591        for bit in 0..CODE_BLOCK_SIZE {
5592            let offset = block_start + bit;
5593            let is_valid = scan_is_jump_target_valid_extended(instruction_set, code, offset as u32);
5594            assert_eq!(bitmap.get_local_raw(bit), is_valid, "mismatch at offset {offset}");
5595
5596            if cfg!(test) || block_start <= 2 * CODE_BLOCK_SIZE {
5597                // Don't slow down the fuzz test unnecessarily.
5598                assert_eq!(
5599                    is_valid,
5600                    scan_find_start_of_basic_block_extended(instruction_set, code, offset as u32) == Some(offset as u32),
5601                    "mismatch at offset {offset}"
5602                );
5603            }
5604
5605            if is_valid {
5606                assert!(linear.binary_search(&offset).is_ok());
5607            }
5608        }
5609
5610        let block_end = core::cmp::min(code.len(), block_start + CODE_BLOCK_SIZE);
5611        let mut offset = block_start;
5612        while offset < block_end {
5613            let step = parse_simple_extended(instruction_set, code, offset);
5614            if ends_basic_block_extended(instruction_set, step.raw_opcode) && step.next_offset < block_end {
5615                assert!(
5616                    bitmap.get_local_raw(step.next_offset - block_start),
5617                    "the instruction after the one at offset {offset} is not a valid jump target"
5618                );
5619            }
5620
5621            offset = step.next_offset;
5622        }
5623
5624        block_start += CODE_BLOCK_SIZE;
5625    }
5626}
5627
5628#[cfg(feature = "alloc")]
5629#[test]
5630fn test_extended_decode_is_deterministic() {
5631    let mut state: u64 = 0x853c49e6748fea9b;
5632    let mut rng = move || {
5633        state ^= state << 13;
5634        state ^= state >> 7;
5635        state ^= state << 17;
5636        state
5637    };
5638
5639    for _ in 0..50 {
5640        let length = (rng() % (CODE_BLOCK_SIZE as u64 * 5 / 2)) as usize;
5641        let mut code = alloc::vec![0; length];
5642        for byte in code.iter_mut() {
5643            *byte = match rng() % 4 {
5644                0 => EXTENDED_OPCODE_PREFIX,
5645                _ => (rng() & 0xff) as u8,
5646            };
5647        }
5648
5649        extended_assert_decode_is_deterministic(ISA_Latest64, &code);
5650    }
5651}
5652
5653#[cfg(feature = "alloc")]
5654#[test]
5655fn test_extended_serialization_round_trip() {
5656    let r1 = Reg::A1;
5657    let r2 = Reg::A5;
5658    let r3 = Reg::SP;
5659
5660    let mut instructions = alloc::vec::Vec::new();
5661    for imm in [
5662        0_i32,
5663        1,
5664        -1,
5665        63,
5666        64,
5667        127,
5668        128,
5669        -128,
5670        255,
5671        256,
5672        -257,
5673        0x7fff,
5674        -0x8000,
5675        0x10000,
5676        i32::MAX,
5677        i32::MIN,
5678    ] {
5679        instructions.extend([
5680            asm::load_imm(r1, imm),
5681            asm::add_imm_64(r1, r2, imm),
5682            asm::add_imm_32(r1, r2, imm),
5683            asm::store_imm_indirect_u32(r1, imm, imm.wrapping_mul(3)),
5684            asm::store_imm_u64(imm, imm.wrapping_add(7)),
5685            asm::cmov_if_zero_imm(r1, r2, imm),
5686            asm::jump_indirect(r2, imm),
5687            asm::load_u16(r1, imm),
5688            asm::store_u8(r2, imm),
5689        ]);
5690    }
5691
5692    instructions.extend([
5693        asm::trap(),
5694        asm::fallthrough(),
5695        asm::memset(),
5696        asm::unlikely(),
5697        asm::sbrk(r1, r2),
5698        asm::move_reg(r1, r2),
5699        asm::add_64(r1, r2, r3),
5700        asm::mul_upper_signed_signed(r1, r2, r3),
5701        asm::load_imm64(r1, 0x1234_5678_9abc_def0),
5702        asm::load_imm64(r2, u64::MAX),
5703        asm::ecalli(0),
5704        asm::ecalli(100_000),
5705    ]);
5706
5707    for target in [0_u32, 60, 300, 70_000] {
5708        instructions.extend([
5709            asm::jump(target),
5710            asm::load_imm_and_jump(r1, -5, target),
5711            asm::branch_eq(r1, r2, target),
5712            asm::branch_less_signed_imm(r1, -100, target),
5713        ]);
5714    }
5715
5716    let mut position: u32 = 12345;
5717    for instruction in instructions {
5718        let mut buffer = [0; MAX_INSTRUCTION_LENGTH];
5719        let length = instruction.serialize_into(ISA_Latest64, position, &mut buffer) as u32;
5720        assert!(length > 0 && length <= MAX_INSTRUCTION_LENGTH as u32);
5721
5722        let chunk = load_chunk(&buffer, 0);
5723        let step = parse_simple_extended(ISA_Latest64, &buffer, 0);
5724        assert_eq!(step.length, length, "length mismatch for {instruction:?}");
5725
5726        let parsed = ISA_Latest64.parse_instruction(step.raw_opcode, chunk, position, step.length);
5727        assert_eq!(parsed, instruction, "round trip failed at length {length}");
5728        position += length;
5729    }
5730}
5731
5732#[test]
5733fn test_extended_jumping_after_an_invalid_instruction_is_allowed() {
5734    let invalid_opcode = (0..EXTENDED_OPCODE_PREFIX)
5735        .find(|&raw_opcode| ISA_Latest64.opcode_from_raw(u32::from(raw_opcode)).is_none())
5736        .expect("no unused opcode found to test with");
5737
5738    let mut buffer = [0; MAX_INSTRUCTION_LENGTH];
5739    let filler = asm::add_imm_64(Reg::A0, Reg::A0, 1);
5740    let filler_length = filler.serialize_into(ISA_Latest64, 0, &mut buffer);
5741
5742    let mut code = [0; CODE_BLOCK_SIZE];
5743    code[..filler_length].copy_from_slice(&buffer[..filler_length]);
5744    code[filler_length] = invalid_opcode;
5745
5746    let step = parse_simple_extended(ISA_Latest64, &code, filler_length);
5747    assert_eq!(step.raw_opcode, usize::from(invalid_opcode));
5748    let after_invalid = step.next_offset;
5749
5750    let mut bitmap = CodeBlockBitmap::new();
5751    bitmap.build(ISA_Latest64, &code, 0);
5752
5753    assert!(!scan_is_jump_target_valid_extended(ISA_Latest64, &code, filler_length as u32));
5754    assert!(!bitmap.get_local_raw(filler_length));
5755    assert_eq!(
5756        scan_find_start_of_basic_block_extended(ISA_Latest64, &code, filler_length as u32),
5757        Some(0)
5758    );
5759
5760    assert!(scan_is_jump_target_valid_extended(ISA_Latest64, &code, after_invalid as u32));
5761    assert!(bitmap.get_local_raw(after_invalid));
5762    assert_eq!(
5763        scan_find_start_of_basic_block_extended(ISA_Latest64, &code, after_invalid as u32),
5764        Some(after_invalid as u32)
5765    );
5766}
5767
5768#[test]
5769fn test_extended_instruction_overhanging_a_block_boundary_is_a_trap() {
5770    let mut buffer = [0; MAX_INSTRUCTION_LENGTH];
5771    let instruction = asm::load_imm64(Reg::A0, u64::MAX);
5772    let length = instruction.serialize_into(ISA_Latest64, 0, &mut buffer);
5773    assert_eq!(length, 10);
5774
5775    let mut code = [0; 2048];
5776    let offset = CODE_BLOCK_SIZE - 1;
5777    code[offset..offset + length].copy_from_slice(&buffer[..length]);
5778
5779    let step = parse_simple_extended(ISA_Latest64, &code, offset);
5780    assert_eq!(step.raw_opcode, EXTENDED_INVALID_RAW_OPCODE);
5781    assert_eq!(step.length as usize, CODE_BLOCK_SIZE - offset);
5782    assert_eq!(step.next_offset, CODE_BLOCK_SIZE);
5783
5784    let chunk = load_chunk(&code, offset);
5785    assert_eq!(
5786        ISA_Latest64.parse_instruction(step.raw_opcode, chunk, offset as u32, step.length),
5787        Instruction::invalid
5788    );
5789
5790    // The very same instruction is decoded normally when it fits.
5791    code[CODE_BLOCK_SIZE..CODE_BLOCK_SIZE + length].copy_from_slice(&buffer[..length]);
5792    let step = parse_simple_extended(ISA_Latest64, &code, CODE_BLOCK_SIZE);
5793    assert_eq!(step.next_offset, CODE_BLOCK_SIZE + length);
5794    let chunk = load_chunk(&code, CODE_BLOCK_SIZE);
5795    assert_eq!(
5796        ISA_Latest64.parse_instruction(step.raw_opcode, chunk, CODE_BLOCK_SIZE as u32, step.length),
5797        instruction
5798    );
5799}
5800
5801/// Returns whether a jump to a given `offset` is allowed.
5802#[inline]
5803pub fn scan_is_jump_target_valid<I>(instruction_set: I, code: &[u8], bitmask: &[u8], offset: u32) -> bool
5804where
5805    I: InstructionSet,
5806{
5807    if instruction_set.is_legacy() {
5808        is_jump_target_valid_legacy(instruction_set, code, bitmask, offset)
5809    } else {
5810        scan_is_jump_target_valid_extended(instruction_set, code, offset)
5811    }
5812}
5813
5814fn is_instruction_start_legacy(bitmask: &[u8], code_len: usize, offset: u32) -> bool {
5815    if cast(offset).to_usize() >= code_len {
5816        return false;
5817    }
5818
5819    offset == 0 || get_bit_for_offset(bitmask, code_len, offset) || get_previous_instruction_skip(bitmask, offset) == Some(BITMASK_MAX)
5820}
5821
5822#[inline(never)]
5823fn is_jump_target_valid_legacy<I>(instruction_set: I, code: &[u8], bitmask: &[u8], offset: u32) -> bool
5824where
5825    I: InstructionSet,
5826{
5827    debug_assert!(instruction_set.is_legacy());
5828
5829    if !is_instruction_start_legacy(bitmask, code.len(), offset) {
5830        // We can't jump if there's no instruction here.
5831        return false;
5832    }
5833
5834    previous_instruction_legacy(instruction_set, code, bitmask, offset).is_none_or(|(_, opcode)| opcode.starts_new_basic_block())
5835}
5836
5837#[inline]
5838fn previous_instruction_legacy<I>(instruction_set: I, code: &[u8], bitmask: &[u8], offset: u32) -> Option<(u32, Opcode)>
5839where
5840    I: InstructionSet,
5841{
5842    let skip = get_previous_instruction_skip(bitmask, offset)?;
5843    let previous_offset = offset - skip - 1;
5844    let opcode = instruction_set
5845        .opcode_from_raw(u32::from(code[cast(previous_offset).to_usize()]))
5846        .unwrap_or(Opcode::trap);
5847
5848    Some((previous_offset, opcode))
5849}
5850
5851#[inline(never)]
5852fn scan_is_jump_target_valid_extended<I>(instruction_set: I, code: &[u8], offset: u32) -> bool
5853where
5854    I: InstructionSet,
5855{
5856    debug_assert!(!instruction_set.is_legacy());
5857
5858    let offset = cast(offset).to_usize();
5859    if offset >= code.len() {
5860        return false;
5861    }
5862
5863    let start_of_block = start_of_block_boundary(offset);
5864    if offset == start_of_block {
5865        // A macro block boundary always starts a new basic block, so we can always jump here.
5866        return true;
5867    }
5868
5869    let mut position = start_of_block;
5870    while position < offset {
5871        let step = parse_simple_extended(instruction_set, code, position);
5872        if step.next_offset == offset {
5873            return ends_basic_block_extended(instruction_set, step.raw_opcode);
5874        }
5875
5876        position = step.next_offset;
5877    }
5878
5879    // There's no instruction boundary at `offset`, so we can't jump here.
5880    false
5881}
5882
5883#[inline]
5884fn ends_basic_block_extended<I>(instruction_set: I, raw_opcode: usize) -> bool
5885where
5886    I: InstructionSet,
5887{
5888    debug_assert!(!instruction_set.is_legacy());
5889    instruction_set.raw_opcode_table().ends_basic_block(raw_opcode)
5890}
5891
5892#[inline]
5893pub fn scan_find_start_of_basic_block<I>(instruction_set: I, code: &[u8], bitmask: &[u8], offset: u32) -> Option<u32>
5894where
5895    I: InstructionSet,
5896{
5897    if instruction_set.is_legacy() {
5898        find_start_of_basic_block_legacy(instruction_set, code, bitmask, offset)
5899    } else {
5900        scan_find_start_of_basic_block_extended(instruction_set, code, offset)
5901    }
5902}
5903
5904fn find_start_of_basic_block_legacy<I>(instruction_set: I, code: &[u8], bitmask: &[u8], mut offset: u32) -> Option<u32>
5905where
5906    I: InstructionSet,
5907{
5908    if !is_instruction_start_legacy(bitmask, code.len(), offset) {
5909        // We can't jump if there's no instruction here.
5910        return None;
5911    }
5912
5913    while let Some((previous_offset, opcode)) = previous_instruction_legacy(instruction_set, code, bitmask, offset) {
5914        if opcode.starts_new_basic_block() {
5915            break;
5916        }
5917
5918        offset = previous_offset;
5919    }
5920
5921    Some(offset)
5922}
5923
5924fn scan_find_start_of_basic_block_extended<I>(instruction_set: I, code: &[u8], offset: u32) -> Option<u32>
5925where
5926    I: InstructionSet,
5927{
5928    let offset = cast(offset).to_usize();
5929    if offset >= code.len() {
5930        // We can't jump if there's no instruction here.
5931        return None;
5932    }
5933
5934    let start_of_block = start_of_block_boundary(offset);
5935    let mut block_start = start_of_block;
5936    let mut position = start_of_block;
5937    while position < offset {
5938        let step = parse_simple_extended(instruction_set, code, position);
5939        if ends_basic_block_extended(instruction_set, step.raw_opcode) {
5940            block_start = step.next_offset;
5941        }
5942
5943        position = step.next_offset;
5944    }
5945
5946    if position != offset {
5947        // There's no instruction boundary at `offset`, so we can't jump here.
5948        return None;
5949    }
5950
5951    Some(block_start as u32)
5952}
5953
5954const CODE_BLOCK_BITMAP_ELEMENTS: usize = CODE_BLOCK_SIZE / 64;
5955
5956#[derive(Copy, Clone)]
5957pub struct CodeBlockBitmap {
5958    /// Address of the macro block; `u32::MAX` when none.
5959    block_start: u32,
5960    bits: [u64; CODE_BLOCK_BITMAP_ELEMENTS],
5961}
5962
5963#[cfg(feature = "alloc")]
5964pub type CodeBlockBitmapBox = alloc::boxed::Box<CodeBlockBitmap>;
5965
5966impl Default for CodeBlockBitmap {
5967    fn default() -> Self {
5968        Self::new()
5969    }
5970}
5971
5972impl CodeBlockBitmap {
5973    pub fn new() -> Self {
5974        Self {
5975            block_start: u32::MAX,
5976            bits: [0_u64; CODE_BLOCK_BITMAP_ELEMENTS],
5977        }
5978    }
5979
5980    #[cfg(feature = "alloc")]
5981    pub fn new_boxed() -> CodeBlockBitmapBox {
5982        alloc::boxed::Box::new(Self::new())
5983    }
5984
5985    pub fn get(&self, pc: ProgramCounter) -> bool {
5986        self.is_for_the_block_containing(pc) && self.get_local_raw(cast(pc.0).to_usize() % CODE_BLOCK_SIZE)
5987    }
5988
5989    fn is_for_the_block_containing(&self, pc: ProgramCounter) -> bool {
5990        cast(start_of_block_boundary(cast(pc.0).to_usize())).to_u32_or_debug_panic() == self.block_start
5991    }
5992
5993    pub fn get_local_raw(&self, bit: usize) -> bool {
5994        self.bits[bit / 64] & (1 << (bit % 64)) != 0
5995    }
5996
5997    pub fn set_local_raw(&mut self, bit: usize) {
5998        self.bits[bit / 64] |= 1 << (bit % 64);
5999    }
6000
6001    pub fn clear(&mut self) {
6002        self.block_start = u32::MAX;
6003        self.bits.fill(0);
6004    }
6005
6006    /// Computes the valid jump target bitmap for the whole macro block containing `offset` in a single scan.
6007    pub fn build<I>(&mut self, instruction_set: I, code: &[u8], offset: u32)
6008    where
6009        I: InstructionSet,
6010    {
6011        assert!(!instruction_set.is_legacy());
6012        self.clear();
6013
6014        let block_start = start_of_block_boundary(cast(offset).to_usize());
6015        self.block_start = cast(block_start).to_u32_or_debug_panic();
6016        if block_start >= code.len() {
6017            return;
6018        }
6019
6020        // A macro block boundary always starts a new basic block.
6021        self.set_local_raw(0);
6022
6023        let block_end = core::cmp::min(code.len(), block_start + CODE_BLOCK_SIZE);
6024        let mut position = block_start;
6025        while position < block_end {
6026            let step = parse_simple_extended(instruction_set, code, position);
6027            if ends_basic_block_extended(instruction_set, step.raw_opcode) && step.next_offset < block_end {
6028                self.set_local_raw(step.next_offset - block_start);
6029            }
6030
6031            position = step.next_offset;
6032        }
6033    }
6034
6035    /// Returns the index of the closest set bit at or before `bit`.
6036    fn find_previous_set_bit(&self, bit: usize) -> Option<usize> {
6037        let mut index = bit / 64;
6038        let mut word = self.bits[index] & (u64::MAX >> (63 - bit % 64));
6039        while word == 0 {
6040            index = index.checked_sub(1)?;
6041            word = self.bits[index];
6042        }
6043
6044        Some(index * 64 + cast(u64::BITS - 1 - word.leading_zeros()).to_usize())
6045    }
6046
6047    pub fn find_start_of_basic_block(&self, program_counter: ProgramCounter) -> Option<ProgramCounter> {
6048        if !self.is_for_the_block_containing(program_counter) {
6049            return None;
6050        }
6051
6052        let offset = cast(program_counter.0).to_usize();
6053        let bit = offset % CODE_BLOCK_SIZE;
6054        let block_start = offset - bit;
6055
6056        Some(ProgramCounter(
6057            cast(block_start + self.find_previous_set_bit(bit)?).to_u32_or_debug_panic(),
6058        ))
6059    }
6060}
6061
6062#[test]
6063fn test_find_previous_set_bit_matches_a_linear_search() {
6064    let mut state: u64 = 0x243f6a8885a308d3;
6065    let mut rng = move || {
6066        state ^= state << 13;
6067        state ^= state >> 7;
6068        state ^= state << 17;
6069        state
6070    };
6071
6072    for iteration in 0..100 {
6073        let mut bitmap = CodeBlockBitmap::new();
6074        for word in bitmap.bits.iter_mut() {
6075            *word = match iteration % 4 {
6076                0 => 0,
6077                1 => rng(),
6078                2 => rng() & rng() & rng(),
6079                _ => u64::MAX,
6080            };
6081        }
6082
6083        for bit in 0..CODE_BLOCK_SIZE {
6084            let expected = (0..=bit).rev().find(|&bit| bitmap.get_local_raw(bit));
6085            assert_eq!(bitmap.find_previous_set_bit(bit), expected, "mismatch at bit {bit}");
6086        }
6087    }
6088}
6089
6090#[test]
6091fn test_code_block_bitmap_only_answers_queries_about_its_own_block() {
6092    let opcode_unlikely = ISA_Latest64.opcode_to_raw(Opcode::unlikely, 0).unwrap().0 as u8;
6093    let opcode_fallthrough = ISA_Latest64.opcode_to_raw(Opcode::fallthrough, 0).unwrap().0 as u8;
6094
6095    // Nothing in the first macro block ends a basic block, while everything does in the second one.
6096    let mut code = [opcode_unlikely; CODE_BLOCK_SIZE * 2];
6097    code[CODE_BLOCK_SIZE..].fill(opcode_fallthrough);
6098
6099    let mut bitmap = CodeBlockBitmap::new();
6100    bitmap.build(ISA_Latest64, &code, CODE_BLOCK_SIZE as u32);
6101
6102    let inside = ProgramCounter(CODE_BLOCK_SIZE as u32 + 5);
6103    assert!(bitmap.get(inside));
6104    assert_eq!(bitmap.find_start_of_basic_block(inside), Some(inside));
6105
6106    let outside = ProgramCounter(5);
6107    assert!(!scan_is_jump_target_valid_extended(ISA_Latest64, &code, outside.0));
6108    assert!(!bitmap.get(outside));
6109    assert_eq!(bitmap.find_start_of_basic_block(outside), None);
6110}
6111
6112#[test]
6113fn test_is_jump_target_valid() {
6114    fn assert_get_previous_instruction_skip_matches_instruction_parser(code: &[u8], bitmask: &[u8]) {
6115        for instruction in Instructions::new(ISA_Latest32, code, bitmask, 0, false) {
6116            match instruction.kind {
6117                Instruction::trap => {
6118                    let skip = get_previous_instruction_skip(bitmask, instruction.offset.0);
6119                    if let Some(skip) = skip {
6120                        let previous_offset = instruction.offset.0 - skip - 1;
6121                        assert_eq!(
6122                            Instructions::new(ISA_Latest32, code, bitmask, previous_offset, true)
6123                                .next()
6124                                .unwrap(),
6125                            ParsedInstruction {
6126                                kind: Instruction::trap,
6127                                offset: ProgramCounter(previous_offset),
6128                                next_offset: instruction.offset,
6129                            }
6130                        );
6131                    } else {
6132                        for skip in 0..=24 {
6133                            let Some(previous_offset) = instruction.offset.0.checked_sub(skip + 1) else {
6134                                continue;
6135                            };
6136                            assert_eq!(
6137                                Instructions::new(ISA_Latest32, code, bitmask, previous_offset, true)
6138                                    .next()
6139                                    .unwrap()
6140                                    .kind,
6141                                Instruction::invalid,
6142                            );
6143                        }
6144                    }
6145                }
6146                Instruction::invalid => {}
6147                _ => unreachable!(),
6148            }
6149        }
6150    }
6151
6152    let opcode_trap = ISA_Latest64.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6153
6154    macro_rules! g {
6155        ($code_length:expr, $bits:expr) => {{
6156            let mut bitmask = [0; {
6157                let value: usize = $code_length;
6158                value.div_ceil(8)
6159            }];
6160            for bit in $bits {
6161                let bit: usize = bit;
6162                assert!(bit < $code_length);
6163                bitmask[bit / 8] |= (1 << (bit % 8));
6164            }
6165
6166            let code = [opcode_trap; $code_length];
6167            assert_get_previous_instruction_skip_matches_instruction_parser(&code, &bitmask);
6168            (code, bitmask)
6169        }};
6170    }
6171
6172    // Make sure the helper macro works correctly.
6173    assert_eq!(g!(1, [0]).1, [0b00000001]);
6174    assert_eq!(g!(2, [1]).1, [0b00000010]);
6175    assert_eq!(g!(8, [7]).1, [0b10000000]);
6176    assert_eq!(g!(9, [8]).1, [0b00000000, 0b00000001]);
6177    assert_eq!(g!(10, [9]).1, [0b00000000, 0b00000010]);
6178    assert_eq!(g!(10, [2, 9]).1, [0b00000100, 0b00000010]);
6179
6180    macro_rules! assert_valid {
6181        ($code_length:expr, $bits:expr, $offset:expr) => {{
6182            let (code, bitmask) = g!($code_length, $bits);
6183            assert!(is_jump_target_valid_legacy(ISA_Latest32, &code, &bitmask, $offset));
6184        }};
6185    }
6186
6187    macro_rules! assert_invalid {
6188        ($code_length:expr, $bits:expr, $offset:expr) => {{
6189            let (code, bitmask) = g!($code_length, $bits);
6190            assert!(!is_jump_target_valid_legacy(ISA_Latest32, &code, &bitmask, $offset));
6191        }};
6192    }
6193
6194    assert_valid!(1, [0], 0);
6195    assert_valid!(2, [0, 1], 1);
6196    assert_valid!(8, [0, 7], 7);
6197    assert_valid!(9, [0, 8], 8);
6198    assert_valid!(25, [0, 24], 24);
6199    assert_valid!(26, [0, 25], 25);
6200
6201    assert_invalid!(3, [0, 2], 1);
6202    assert_invalid!(27, [0], 24);
6203
6204    assert_valid!(1, [], 0);
6205    assert_valid!(2, [1], 1);
6206    assert_valid!(27, [0], 25);
6207    assert_valid!(27, [0, 26], 26);
6208
6209    let opcode_load_imm = ISA_Latest32.opcode_to_raw(Opcode::load_imm, 1).unwrap().0 as u8;
6210    assert!(is_jump_target_valid_legacy(ISA_Latest32, &[opcode_load_imm], &[0b00000001], 0));
6211
6212    assert!(!is_jump_target_valid_legacy(
6213        ISA_Latest32,
6214        &[opcode_load_imm, opcode_load_imm],
6215        &[0b00000011],
6216        1
6217    ));
6218
6219    assert!(is_jump_target_valid_legacy(
6220        ISA_Latest32,
6221        &[opcode_trap, opcode_load_imm],
6222        &[0b00000011],
6223        1
6224    ));
6225
6226    // An unassigned opcode is an invalid instruction, which is a trap, so it also ends a basic block.
6227    let opcode_unassigned = (0..=u8::MAX)
6228        .find(|&raw_opcode| ISA_Latest32.opcode_from_raw(u32::from(raw_opcode)).is_none())
6229        .unwrap();
6230
6231    assert!(is_jump_target_valid_legacy(
6232        ISA_Latest32,
6233        &[opcode_unassigned, opcode_load_imm],
6234        &[0b00000011],
6235        1
6236    ));
6237}
6238
6239#[test]
6240fn test_legacy_runner_and_free_functions_match() {
6241    #[derive(Copy, Clone)]
6242    struct CollectInstructionStarts<I>(I);
6243
6244    impl<I> OpcodeVisitor for CollectInstructionStarts<I>
6245    where
6246        I: InstructionSet,
6247    {
6248        type State = [bool; 256];
6249        type ReturnTy = ();
6250        type InstructionSet = I;
6251
6252        fn instruction_set(self) -> I {
6253            self.0
6254        }
6255
6256        fn dispatch(self, state: &mut Self::State, _opcode: usize, _chunk: u128, offset: u32, _length: u32) {
6257            if let Some(is_start) = state.get_mut(cast(offset).to_usize()) {
6258                *is_start = true;
6259            }
6260        }
6261    }
6262
6263    let mut state: u64 = 0x243f6a8885a308d3;
6264    let mut rng = move || {
6265        state ^= state << 13;
6266        state ^= state >> 7;
6267        state ^= state << 17;
6268        state as u8
6269    };
6270
6271    let instruction_set = ISA_Latest32;
6272    let mut injected_instructions = 0;
6273    for iteration in 0..100 {
6274        let mut code = [0_u8; 256];
6275        code.fill_with(&mut rng);
6276
6277        let mut bitmask = [0_u8; 256 / 8];
6278        bitmask.fill_with(|| match iteration % 4 {
6279            0 => 0,
6280            1 => rng(),
6281            2 => rng() & rng() & rng(),
6282            _ => u8::MAX,
6283        });
6284
6285        let mut decoded_starts = [false; 256];
6286        visitor_run_legacy(&mut decoded_starts, &code, &bitmask, CollectInstructionStarts(instruction_set));
6287
6288        for offset in 0..cast(code.len()).to_u32_or_debug_panic() {
6289            let is_instruction_start = is_instruction_start_legacy(&bitmask, code.len(), offset);
6290            assert_eq!(
6291                is_instruction_start,
6292                decoded_starts[cast(offset).to_usize()],
6293                "mismatch at offset {offset} of iteration {iteration}"
6294            );
6295
6296            assert_eq!(
6297                is_jump_target_valid_legacy(instruction_set, &code, &bitmask, offset),
6298                find_start_of_basic_block_legacy(instruction_set, &code, &bitmask, offset) == Some(offset),
6299                "jump target and start of basic block mismatch at offset {offset} of iteration {iteration}"
6300            );
6301
6302            if is_instruction_start && offset != 0 && !get_bit_for_offset(&bitmask, code.len(), offset) {
6303                injected_instructions += 1;
6304            }
6305        }
6306    }
6307
6308    assert!(injected_instructions > 0);
6309}
6310
6311#[cfg_attr(not(debug_assertions), inline(always))]
6312fn parse_bitmask_slow(bitmask: &[u8], code_length: usize, offset: u32) -> (u32, bool) {
6313    let mut offset = offset as usize + 1;
6314    let mut is_next_instruction_invalid = true;
6315    let origin = offset;
6316    while let Some(&byte) = bitmask.get(offset >> 3) {
6317        let shift = offset & 7;
6318        let mask = byte >> shift;
6319        if mask == 0 {
6320            offset += 8 - shift;
6321            if (offset - origin) < BITMASK_MAX as usize {
6322                continue;
6323            }
6324        } else {
6325            offset += mask.trailing_zeros() as usize;
6326            is_next_instruction_invalid = offset >= code_length || (offset - origin) > BITMASK_MAX as usize;
6327        }
6328        break;
6329    }
6330
6331    use core::cmp::min;
6332    let offset = min(offset, code_length);
6333    let skip = min((offset - origin) as u32, BITMASK_MAX);
6334    (skip, is_next_instruction_invalid)
6335}
6336
6337#[cfg_attr(not(debug_assertions), inline(always))]
6338pub(crate) fn parse_bitmask_fast(bitmask: &[u8], mut offset: u32) -> Option<u32> {
6339    debug_assert!(offset < u32::MAX);
6340    debug_assert!(get_bit_for_offset(bitmask, offset as usize + 1, offset));
6341    offset += 1;
6342
6343    let bitmask = bitmask.get(offset as usize >> 3..(offset as usize >> 3) + 4)?;
6344    let shift = offset & 7;
6345    let mask: u32 = (u32::from_le_bytes([bitmask[0], bitmask[1], bitmask[2], bitmask[3]]) >> shift) | (1 << BITMASK_MAX);
6346    Some(mask.trailing_zeros())
6347}
6348
6349#[test]
6350fn test_parse_bitmask() {
6351    #[track_caller]
6352    fn parse_both(bitmask: &[u8], offset: u32) -> u32 {
6353        let result_fast = parse_bitmask_fast(bitmask, offset).unwrap();
6354        let result_slow = parse_bitmask_slow(bitmask, bitmask.len() * 8, offset).0;
6355        assert_eq!(result_fast, result_slow);
6356
6357        result_fast
6358    }
6359
6360    assert_eq!(parse_both(&[0b00000011, 0, 0, 0], 0), 0);
6361    assert_eq!(parse_both(&[0b00000101, 0, 0, 0], 0), 1);
6362    assert_eq!(parse_both(&[0b10000001, 0, 0, 0], 0), 6);
6363    assert_eq!(parse_both(&[0b00000001, 1, 0, 0], 0), 7);
6364    assert_eq!(parse_both(&[0b00000001, 1 << 7, 0, 0], 0), 14);
6365    assert_eq!(parse_both(&[0b00000001, 0, 1, 0], 0), 15);
6366    assert_eq!(parse_both(&[0b00000001, 0, 1 << 7, 0], 0), 22);
6367    assert_eq!(parse_both(&[0b00000001, 0, 0, 1], 0), 23);
6368
6369    assert_eq!(parse_both(&[0b11000000, 0, 0, 0, 0], 6), 0);
6370    assert_eq!(parse_both(&[0b01000000, 1, 0, 0, 0], 6), 1);
6371
6372    assert_eq!(parse_both(&[0b10000000, 1, 0, 0, 0], 7), 0);
6373    assert_eq!(parse_both(&[0b10000000, 1 << 1, 0, 0, 0], 7), 1);
6374}
6375
6376#[derive(Clone)]
6377pub struct Instructions<'a, I> {
6378    code: &'a [u8],
6379    bitmask: &'a [u8],
6380    offset: u32,
6381    invalid_offset: Option<u32>,
6382    is_bounded: bool,
6383    is_done: bool,
6384    instruction_set: I,
6385}
6386
6387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
6388pub struct ParsedInstruction {
6389    pub kind: Instruction,
6390    pub offset: ProgramCounter,
6391    pub next_offset: ProgramCounter,
6392}
6393
6394impl ParsedInstruction {
6395    #[inline]
6396    pub fn visit_parsing<T>(&self, visitor: &mut T) -> <T as ParsingVisitor>::ReturnTy
6397    where
6398        T: ParsingVisitor,
6399    {
6400        self.kind
6401            .visit_parsing(self.offset.0, self.next_offset.0.saturating_sub(self.offset.0), visitor)
6402    }
6403}
6404
6405impl core::ops::Deref for ParsedInstruction {
6406    type Target = Instruction;
6407
6408    #[inline]
6409    fn deref(&self) -> &Self::Target {
6410        &self.kind
6411    }
6412}
6413
6414impl core::fmt::Display for ParsedInstruction {
6415    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
6416        write!(fmt, "{:>7}: {}", self.offset, self.kind)
6417    }
6418}
6419
6420impl<'a, I> Instructions<'a, I>
6421where
6422    I: InstructionSet,
6423{
6424    #[inline]
6425    pub fn new_bounded(instruction_set: I, code: &'a [u8], bitmask: &'a [u8], offset: u32) -> Self {
6426        Self::new(instruction_set, code, bitmask, offset, true)
6427    }
6428
6429    #[inline]
6430    pub fn new_bounded_known_boundary(instruction_set: I, code: &'a [u8], bitmask: &'a [u8], offset: u32) -> Self {
6431        Self::new_impl(instruction_set, code, bitmask, offset, true, true)
6432    }
6433
6434    #[inline]
6435    pub fn new_unbounded(instruction_set: I, code: &'a [u8], bitmask: &'a [u8], offset: u32) -> Self {
6436        Self::new(instruction_set, code, bitmask, offset, false)
6437    }
6438
6439    #[inline]
6440    fn new(instruction_set: I, code: &'a [u8], bitmask: &'a [u8], offset: u32, is_bounded: bool) -> Self {
6441        Self::new_impl(instruction_set, code, bitmask, offset, is_bounded, false)
6442    }
6443
6444    #[inline]
6445    fn new_impl(instruction_set: I, code: &'a [u8], bitmask: &'a [u8], offset: u32, is_bounded: bool, is_known_boundary: bool) -> Self {
6446        assert!(code.len() <= u32::MAX as usize);
6447        let is_legacy = instruction_set.is_legacy();
6448        if is_legacy {
6449            assert_eq!(bitmask.len(), code.len().div_ceil(8));
6450        }
6451
6452        let is_valid = if is_legacy {
6453            debug_assert!(
6454                !is_known_boundary || cast(offset).to_usize() >= code.len() || is_instruction_start_legacy(bitmask, code.len(), offset)
6455            );
6456            get_bit_for_offset(bitmask, code.len(), offset)
6457        } else if is_known_boundary && (offset as usize) < code.len() {
6458            debug_assert!(extended_scan_is_instruction_boundary(instruction_set, code, offset));
6459            true
6460        } else {
6461            extended_scan_is_instruction_boundary(instruction_set, code, offset)
6462        };
6463
6464        let mut is_done = false;
6465        let (offset, invalid_offset) = if is_valid {
6466            (offset, None)
6467        } else if is_bounded {
6468            is_done = true;
6469            if offset == u32::MAX {
6470                (u32::MAX, None)
6471            } else {
6472                (core::cmp::min(offset + 1, code.len() as u32), Some(offset))
6473            }
6474        } else {
6475            let next_offset = if is_legacy {
6476                find_next_offset_legacy_unbounded(bitmask, code.len() as u32, offset)
6477            } else {
6478                extended_scan_find_next_offset(instruction_set, code, offset)
6479            };
6480            debug_assert!(
6481                next_offset as usize == code.len() || !is_legacy || get_bit_for_offset(bitmask, code.len(), next_offset),
6482                "bit at {offset} is zero"
6483            );
6484            (next_offset, Some(offset))
6485        };
6486
6487        Self {
6488            code,
6489            bitmask,
6490            offset,
6491            invalid_offset,
6492            is_bounded,
6493            is_done,
6494            instruction_set,
6495        }
6496    }
6497
6498    #[inline]
6499    pub fn offset(&self) -> u32 {
6500        self.invalid_offset.unwrap_or(self.offset)
6501    }
6502
6503    #[inline]
6504    pub fn visit<T>(&mut self, visitor: &mut T) -> Option<<T as InstructionVisitor>::ReturnTy>
6505    where
6506        T: InstructionVisitor,
6507    {
6508        // TODO: Make this directly dispatched?
6509        Some(self.next()?.visit(visitor))
6510    }
6511
6512    #[inline]
6513    pub fn visit_parsing<T>(&mut self, visitor: &mut T) -> Option<<T as ParsingVisitor>::ReturnTy>
6514    where
6515        T: ParsingVisitor,
6516    {
6517        Some(self.next()?.visit_parsing(visitor))
6518    }
6519}
6520
6521impl<'a, I> Iterator for Instructions<'a, I>
6522where
6523    I: InstructionSet,
6524{
6525    type Item = ParsedInstruction;
6526
6527    #[inline(always)]
6528    fn next(&mut self) -> Option<Self::Item> {
6529        if let Some(offset) = self.invalid_offset.take() {
6530            return Some(ParsedInstruction {
6531                kind: Instruction::invalid,
6532                offset: ProgramCounter(offset),
6533                next_offset: ProgramCounter(self.offset),
6534            });
6535        }
6536
6537        if self.is_done || self.offset as usize >= self.code.len() {
6538            return None;
6539        }
6540
6541        if !self.instruction_set.is_legacy() {
6542            self.next_extended()
6543        } else {
6544            self.next_legacy()
6545        }
6546    }
6547
6548    fn size_hint(&self) -> (usize, Option<usize>) {
6549        (0, Some(self.code.len() - core::cmp::min(self.offset() as usize, self.code.len())))
6550    }
6551}
6552
6553impl<'a, I> Instructions<'a, I>
6554where
6555    I: InstructionSet,
6556{
6557    fn next_legacy(&mut self) -> Option<ParsedInstruction> {
6558        let offset = self.offset;
6559        debug_assert!(get_bit_for_offset(self.bitmask, self.code.len(), offset), "bit at {offset} is zero");
6560
6561        let (next_offset, instruction, is_next_instruction_invalid) =
6562            parse_instruction_legacy(self.instruction_set, self.code, self.bitmask, self.offset);
6563
6564        debug_assert!(next_offset > self.offset);
6565
6566        if !is_next_instruction_invalid {
6567            self.offset = next_offset;
6568            debug_assert!(
6569                self.offset as usize == self.code.len() || get_bit_for_offset(self.bitmask, self.code.len(), self.offset),
6570                "bit at {} is zero",
6571                self.offset
6572            );
6573        } else {
6574            if next_offset as usize == self.code.len() {
6575                self.offset = self.code.len() as u32 + 1;
6576            } else if self.is_bounded {
6577                self.is_done = true;
6578                self.offset = self.code.len() as u32;
6579            } else {
6580                self.offset = find_next_offset_legacy_unbounded(self.bitmask, self.code.len() as u32, next_offset);
6581                debug_assert!(
6582                    self.offset as usize == self.code.len() || get_bit_for_offset(self.bitmask, self.code.len(), self.offset),
6583                    "bit at {} is zero",
6584                    self.offset
6585                );
6586            }
6587
6588            self.invalid_offset = Some(next_offset);
6589        }
6590
6591        Some(ParsedInstruction {
6592            kind: instruction,
6593            offset: ProgramCounter(offset),
6594            next_offset: ProgramCounter(next_offset),
6595        })
6596    }
6597
6598    fn next_extended(&mut self) -> Option<ParsedInstruction> {
6599        let offset = self.offset;
6600        let (instruction, next_offset) = parse_raw_extended(
6601            self.code,
6602            cast(offset).to_usize(),
6603            end_of_macro_block(cast(offset).to_usize(), self.code.len()),
6604            self.instruction_set.raw_opcode_table(),
6605            |raw_opcode, chunk, offset, length| {
6606                self.instruction_set
6607                    .parse_instruction(cast(raw_opcode).to_usize(), chunk, cast(offset).to_u32_or_debug_panic(), length)
6608            },
6609        );
6610
6611        let next_offset = cast(next_offset).to_u32_or_debug_panic();
6612        self.offset = next_offset;
6613
6614        Some(ParsedInstruction {
6615            kind: instruction,
6616            offset: ProgramCounter(offset),
6617            next_offset: ProgramCounter(next_offset),
6618        })
6619    }
6620}
6621
6622#[test]
6623fn test_instructions_iterator_with_implicit_trap() {
6624    let opcode_fallthrough = ISA_Latest32.opcode_to_raw(Opcode::fallthrough, 0).unwrap().0 as u8;
6625    let code = [opcode_fallthrough];
6626    for is_bounded in [false, true] {
6627        let mut i = Instructions::new(ISA_Latest32, &code, &[0b00000001], 0, is_bounded);
6628        assert_eq!(
6629            i.next(),
6630            Some(ParsedInstruction {
6631                kind: Instruction::fallthrough,
6632                offset: ProgramCounter(0),
6633                next_offset: ProgramCounter(1),
6634            })
6635        );
6636
6637        assert_eq!(
6638            i.next(),
6639            Some(ParsedInstruction {
6640                kind: Instruction::invalid,
6641                offset: ProgramCounter(1),
6642                next_offset: ProgramCounter(2),
6643            })
6644        );
6645
6646        assert_eq!(i.next(), None);
6647    }
6648}
6649
6650#[test]
6651fn test_instructions_iterator_without_implicit_trap() {
6652    let opcode_trap = ISA_Latest32.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6653    let code = [opcode_trap];
6654    for is_bounded in [false, true] {
6655        let mut i = Instructions::new(ISA_Latest32, &code, &[0b00000001], 0, is_bounded);
6656        assert_eq!(
6657            i.next(),
6658            Some(ParsedInstruction {
6659                kind: Instruction::trap,
6660                offset: ProgramCounter(0),
6661                next_offset: ProgramCounter(1),
6662            })
6663        );
6664
6665        assert_eq!(i.next(), None);
6666    }
6667}
6668
6669#[test]
6670fn test_instructions_iterator_very_long_bitmask_bounded() {
6671    let mut code = [0_u8; 64];
6672    code[0] = ISA_Latest32.opcode_to_raw(Opcode::fallthrough, 0).unwrap().0 as u8;
6673    let mut bitmask = [0_u8; 8];
6674    bitmask[0] = 0b00000001;
6675    bitmask[7] = 0b10000000;
6676
6677    let mut i = Instructions::new(ISA_Latest32, &code, &bitmask, 0, true);
6678    assert_eq!(
6679        i.next(),
6680        Some(ParsedInstruction {
6681            kind: Instruction::fallthrough,
6682            offset: ProgramCounter(0),
6683            next_offset: ProgramCounter(25),
6684        })
6685    );
6686
6687    assert_eq!(
6688        i.next(),
6689        Some(ParsedInstruction {
6690            kind: Instruction::invalid,
6691            offset: ProgramCounter(25),
6692            next_offset: ProgramCounter(64),
6693        })
6694    );
6695
6696    assert_eq!(i.next(), None);
6697}
6698
6699#[test]
6700fn test_instructions_iterator_very_long_bitmask_unbounded() {
6701    let mut code = [0_u8; 64];
6702    code[0] = ISA_Latest32.opcode_to_raw(Opcode::fallthrough, 0).unwrap().0 as u8;
6703    let mut bitmask = [0_u8; 8];
6704    bitmask[0] = 0b00000001;
6705    bitmask[7] = 0b10000000;
6706
6707    let mut i = Instructions::new(ISA_Latest32, &code, &bitmask, 0, false);
6708    assert_eq!(
6709        i.next(),
6710        Some(ParsedInstruction {
6711            kind: Instruction::fallthrough,
6712            offset: ProgramCounter(0),
6713            next_offset: ProgramCounter(25),
6714        })
6715    );
6716
6717    assert_eq!(
6718        i.next(),
6719        Some(ParsedInstruction {
6720            kind: Instruction::invalid,
6721            offset: ProgramCounter(25),
6722            next_offset: ProgramCounter(63),
6723        })
6724    );
6725
6726    assert_eq!(
6727        i.next(),
6728        Some(ParsedInstruction {
6729            kind: Instruction::trap,
6730            offset: ProgramCounter(63),
6731            next_offset: ProgramCounter(64),
6732        })
6733    );
6734
6735    assert_eq!(i.next(), None);
6736}
6737
6738#[test]
6739fn test_instructions_iterator_start_at_invalid_offset_bounded() {
6740    let opcode_trap = ISA_Latest32.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6741    let code = [opcode_trap; 8];
6742    let mut i = Instructions::new(ISA_Latest32, &code, &[0b10000001], 1, true);
6743    assert_eq!(
6744        i.next(),
6745        Some(ParsedInstruction {
6746            kind: Instruction::invalid,
6747            offset: ProgramCounter(1),
6748            // Since a bounded iterator doesn't scan forward it just assumes the next offset.
6749            next_offset: ProgramCounter(2),
6750        })
6751    );
6752
6753    assert_eq!(i.next(), None);
6754}
6755
6756#[test]
6757fn test_instructions_iterator_start_at_invalid_offset_unbounded() {
6758    let opcode_trap = ISA_Latest32.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6759    let code = [opcode_trap; 8];
6760    let mut i = Instructions::new(ISA_Latest32, &code, &[0b10000001], 1, false);
6761    assert_eq!(
6762        i.next(),
6763        Some(ParsedInstruction {
6764            kind: Instruction::invalid,
6765            offset: ProgramCounter(1),
6766            next_offset: ProgramCounter(7),
6767        })
6768    );
6769
6770    assert_eq!(
6771        i.next(),
6772        Some(ParsedInstruction {
6773            kind: Instruction::trap,
6774            offset: ProgramCounter(7),
6775            next_offset: ProgramCounter(8),
6776        })
6777    );
6778
6779    assert_eq!(i.next(), None);
6780}
6781
6782#[test]
6783fn test_instructions_iterator_emits_an_injected_invalid_instruction_if_bounded_and_ends_with_a_trap() {
6784    let opcode_trap = ISA_Latest32.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6785    let code = [opcode_trap; 32];
6786    let bitmask = [0b00000001, 0b00000000, 0b00000000, 0b00000100];
6787    let mut i = Instructions::new(ISA_Latest32, &code, &bitmask, 0, true);
6788    assert_eq!(i.offset(), 0);
6789    assert_eq!(
6790        i.next(),
6791        Some(ParsedInstruction {
6792            kind: Instruction::trap,
6793            offset: ProgramCounter(0),
6794            next_offset: ProgramCounter(25)
6795        })
6796    );
6797    assert_eq!(i.offset(), 25);
6798    assert_eq!(
6799        i.next(),
6800        Some(ParsedInstruction {
6801            kind: Instruction::invalid,
6802            offset: ProgramCounter(25),
6803            next_offset: ProgramCounter(32)
6804        })
6805    );
6806    assert_eq!(i.next(), None);
6807}
6808
6809#[test]
6810fn test_instructions_iterator_emits_an_injected_invalid_instruction_if_unbounded_and_ends_with_a_trap() {
6811    let opcode_trap = ISA_Latest32.opcode_to_raw(Opcode::trap, 0).unwrap().0 as u8;
6812    let code = [opcode_trap; 32];
6813    let bitmask = [0b00000001, 0b00000000, 0b00000000, 0b00000100];
6814    let mut i = Instructions::new(ISA_Latest32, &code, &bitmask, 0, false);
6815    assert_eq!(i.offset(), 0);
6816    assert_eq!(
6817        i.next(),
6818        Some(ParsedInstruction {
6819            kind: Instruction::trap,
6820            offset: ProgramCounter(0),
6821            next_offset: ProgramCounter(25)
6822        })
6823    );
6824    assert_eq!(i.offset(), 25);
6825    assert_eq!(
6826        i.next(),
6827        Some(ParsedInstruction {
6828            kind: Instruction::invalid,
6829            offset: ProgramCounter(25),
6830            next_offset: ProgramCounter(26)
6831        })
6832    );
6833    assert_eq!(
6834        i.next(),
6835        Some(ParsedInstruction {
6836            kind: Instruction::trap,
6837            offset: ProgramCounter(26),
6838            next_offset: ProgramCounter(32)
6839        })
6840    );
6841    assert_eq!(i.next(), None);
6842}
6843
6844#[derive(Copy, Clone, PartialEq, Eq, Debug)]
6845pub enum EstimateInterpreterMemoryUsageArgs {
6846    UnboundedCache {
6847        instruction_count: u32,
6848        basic_block_count: u32,
6849        page_size: u32,
6850    },
6851    BoundedCache {
6852        instruction_count: u32,
6853        basic_block_count: u32,
6854        max_cache_size_bytes: u32,
6855        max_block_size: u32,
6856        page_size: u32,
6857    },
6858}
6859
6860#[derive(Copy, Clone, PartialEq, Eq, Debug)]
6861pub struct ProgramMemoryInfo {
6862    pub baseline_ram_consumption: u32,
6863    pub purgeable_ram_consumption: u32,
6864}
6865
6866#[derive(Clone)]
6867#[non_exhaustive]
6868pub struct ProgramParts {
6869    pub isa: InstructionSetKind,
6870    pub ro_data_size: u32,
6871    pub rw_data_size: u32,
6872    pub stack_size: u32,
6873
6874    pub ro_data: ArcBytes,
6875    pub rw_data: ArcBytes,
6876    pub code_and_jump_table: ArcBytes,
6877    pub import_offsets: ArcBytes,
6878    pub import_symbols: ArcBytes,
6879    pub exports: ArcBytes,
6880
6881    pub debug_strings: ArcBytes,
6882    pub debug_line_program_ranges: ArcBytes,
6883    pub debug_line_programs: ArcBytes,
6884
6885    pub metadata_hash: ArcBytes,
6886}
6887
6888impl ProgramParts {
6889    pub fn empty(isa: InstructionSetKind) -> Self {
6890        Self {
6891            isa,
6892            ro_data_size: 0,
6893            rw_data_size: 0,
6894            stack_size: 0,
6895
6896            ro_data: Default::default(),
6897            rw_data: Default::default(),
6898            code_and_jump_table: Default::default(),
6899            import_offsets: Default::default(),
6900            import_symbols: Default::default(),
6901            exports: Default::default(),
6902
6903            debug_strings: Default::default(),
6904            debug_line_program_ranges: Default::default(),
6905            debug_line_programs: Default::default(),
6906
6907            metadata_hash: Default::default(),
6908        }
6909    }
6910
6911    pub fn from_bytes(blob: ArcBytes) -> Result<Self, ProgramParseError> {
6912        if !blob.starts_with(&BLOB_MAGIC) {
6913            return Err(ProgramParseError(ProgramParseErrorKind::Other(
6914                "blob doesn't start with the expected magic bytes",
6915            )));
6916        }
6917
6918        let mut reader = Reader {
6919            blob: &blob,
6920            position: BLOB_MAGIC.len(),
6921        };
6922
6923        let blob_version = reader.read_byte()?;
6924        let Some(isa) = InstructionSetKind::from_blob_version(blob_version) else {
6925            return Err(ProgramParseError(ProgramParseErrorKind::UnsupportedVersion {
6926                version: blob_version,
6927            }));
6928        };
6929
6930        let blob_len = BlobLen::from_le_bytes(reader.read_slice(BLOB_LEN_SIZE)?.try_into().unwrap());
6931        if blob_len != blob.len() as u64 {
6932            return Err(ProgramParseError(ProgramParseErrorKind::Other(
6933                "blob size doesn't match the blob length metadata",
6934            )));
6935        }
6936
6937        let mut parts = ProgramParts::empty(isa);
6938        let mut section = reader.read_byte()?;
6939        if section == SECTION_MEMORY_CONFIG {
6940            let section_length = reader.read_varint()?;
6941            let position = reader.position;
6942            parts.ro_data_size = reader.read_varint()?;
6943            parts.rw_data_size = reader.read_varint()?;
6944            parts.stack_size = reader.read_varint()?;
6945            if position + section_length as usize != reader.position {
6946                return Err(ProgramParseError(ProgramParseErrorKind::Other(
6947                    "the memory config section contains more data than expected",
6948                )));
6949            }
6950            section = reader.read_byte()?;
6951        }
6952
6953        parts.ro_data = reader.read_section_as_bytes(&mut section, SECTION_RO_DATA)?;
6954        parts.rw_data = reader.read_section_as_bytes(&mut section, SECTION_RW_DATA)?;
6955
6956        if section == SECTION_IMPORTS {
6957            let section_length = reader.read_varint()? as usize;
6958            let section_start = reader.position;
6959            let import_count = reader.read_varint()?;
6960            if import_count > VM_MAXIMUM_IMPORT_COUNT {
6961                return Err(ProgramParseError(ProgramParseErrorKind::Other("too many imports")));
6962            }
6963
6964            let Some(import_offsets_size) = import_count.checked_mul(4) else {
6965                return Err(ProgramParseError(ProgramParseErrorKind::Other("the imports section is invalid")));
6966            };
6967
6968            parts.import_offsets = reader.read_slice_as_bytes(import_offsets_size as usize)?;
6969            let Some(import_symbols_size) = section_length.checked_sub(reader.position - section_start) else {
6970                return Err(ProgramParseError(ProgramParseErrorKind::Other("the imports section is invalid")));
6971            };
6972
6973            parts.import_symbols = reader.read_slice_as_bytes(import_symbols_size)?;
6974            section = reader.read_byte()?;
6975        }
6976
6977        parts.exports = reader.read_section_as_bytes(&mut section, SECTION_EXPORTS)?;
6978        parts.code_and_jump_table = reader.read_section_as_bytes(&mut section, SECTION_CODE_AND_JUMP_TABLE)?;
6979        parts.debug_strings = reader.read_section_as_bytes(&mut section, SECTION_OPT_DEBUG_STRINGS)?;
6980        parts.debug_line_programs = reader.read_section_as_bytes(&mut section, SECTION_OPT_DEBUG_LINE_PROGRAMS)?;
6981        parts.debug_line_program_ranges = reader.read_section_as_bytes(&mut section, SECTION_OPT_DEBUG_LINE_PROGRAM_RANGES)?;
6982        parts.metadata_hash = reader.read_section_as_bytes(&mut section, SECTION_OPT_METADATA_HASH)?;
6983
6984        while (section & 0b10000000) != 0 {
6985            // We don't know this section, but it's optional, so just skip it.
6986            #[cfg(feature = "logging")]
6987            log::debug!("Skipping unsupported optional section: {}", section);
6988            let section_length = reader.read_varint()?;
6989            reader.skip(section_length as usize)?;
6990            section = reader.read_byte()?;
6991        }
6992
6993        if section != SECTION_END_OF_FILE {
6994            return Err(ProgramParseError(ProgramParseErrorKind::UnexpectedSection {
6995                offset: reader.position - 1,
6996                section,
6997            }));
6998        }
6999
7000        Ok(parts)
7001    }
7002}
7003
7004impl ProgramBlob {
7005    /// Parses the blob length information from the given `raw_blob` bytes.
7006    ///
7007    /// Returns `None` if `raw_blob` doesn't contain enough bytes to read the length.
7008    pub fn blob_length(raw_blob: &[u8]) -> Option<BlobLen> {
7009        let end = BLOB_LEN_OFFSET + BLOB_LEN_SIZE;
7010        if raw_blob.len() < end {
7011            return None;
7012        }
7013        Some(BlobLen::from_le_bytes(raw_blob[BLOB_LEN_OFFSET..end].try_into().unwrap()))
7014    }
7015
7016    /// Parses the given bytes into a program blob.
7017    pub fn parse(bytes: ArcBytes) -> Result<Self, ProgramParseError> {
7018        let parts = ProgramParts::from_bytes(bytes)?;
7019        Self::from_parts(parts)
7020    }
7021
7022    /// Creates a program blob from parts.
7023    pub fn from_parts(parts: ProgramParts) -> Result<Self, ProgramParseError> {
7024        let mut blob = ProgramBlob {
7025            #[cfg(feature = "unique-id")]
7026            unique_id: 0,
7027
7028            isa: parts.isa,
7029
7030            ro_data_size: parts.ro_data_size,
7031            rw_data_size: parts.rw_data_size,
7032            stack_size: parts.stack_size,
7033
7034            ro_data: parts.ro_data,
7035            rw_data: parts.rw_data,
7036            exports: parts.exports,
7037            import_symbols: parts.import_symbols,
7038            import_offsets: parts.import_offsets,
7039            code: Default::default(),
7040            jump_table: Default::default(),
7041            jump_table_entry_size: Default::default(),
7042            bitmask: Default::default(),
7043
7044            debug_strings: parts.debug_strings,
7045            debug_line_program_ranges: parts.debug_line_program_ranges,
7046            debug_line_programs: parts.debug_line_programs,
7047
7048            metadata_hash: parts.metadata_hash,
7049        };
7050
7051        if blob.ro_data.len() > blob.ro_data_size as usize {
7052            return Err(ProgramParseError(ProgramParseErrorKind::Other(
7053                "size of the read-only data payload exceeds the declared size of the section",
7054            )));
7055        }
7056
7057        if blob.rw_data.len() > blob.rw_data_size as usize {
7058            return Err(ProgramParseError(ProgramParseErrorKind::Other(
7059                "size of the read-write data payload exceeds the declared size of the section",
7060            )));
7061        }
7062
7063        if parts.code_and_jump_table.is_empty() {
7064            return Err(ProgramParseError(ProgramParseErrorKind::Other("no code found")));
7065        }
7066
7067        {
7068            let mut reader = Reader {
7069                blob: &parts.code_and_jump_table,
7070                position: 0,
7071            };
7072
7073            let initial_position = reader.position;
7074            let jump_table_entry_count = reader.read_varint()?;
7075            if jump_table_entry_count > VM_MAXIMUM_JUMP_TABLE_ENTRIES {
7076                return Err(ProgramParseError(ProgramParseErrorKind::Other(
7077                    "the jump table section is too long",
7078                )));
7079            }
7080
7081            let jump_table_entry_size = reader.read_byte()?;
7082            let legacy_code_length = if blob.isa.is_legacy() { Some(reader.read_varint()?) } else { None };
7083
7084            if !matches!(jump_table_entry_size, 0..=4) {
7085                return Err(ProgramParseError(ProgramParseErrorKind::Other("invalid jump table entry size")));
7086            }
7087
7088            let Some(jump_table_length) = jump_table_entry_count.checked_mul(u32::from(jump_table_entry_size)) else {
7089                return Err(ProgramParseError(ProgramParseErrorKind::Other("the jump table is too long")));
7090            };
7091
7092            blob.jump_table_entry_size = jump_table_entry_size;
7093            blob.jump_table = reader.read_slice_as_bytes(jump_table_length as usize)?;
7094
7095            let code_length = match legacy_code_length {
7096                Some(code_length) => cast(code_length).to_usize(),
7097                None => parts.code_and_jump_table.len() - (reader.position - initial_position),
7098            };
7099
7100            if code_length > cast(VM_MAXIMUM_CODE_SIZE).to_usize() {
7101                return Err(ProgramParseError(ProgramParseErrorKind::Other("the code section is too long")));
7102            }
7103
7104            blob.code = reader.read_slice_as_bytes(code_length)?;
7105
7106            if blob.code.len() > (i32::MAX as usize) {
7107                return Err(ProgramParseError(ProgramParseErrorKind::Other("the program blob is too large")));
7108            }
7109
7110            if blob.isa.is_legacy() {
7111                let bitmask_length = parts.code_and_jump_table.len() - (reader.position - initial_position);
7112                blob.bitmask = reader.read_slice_as_bytes(bitmask_length)?;
7113
7114                let mut expected_bitmask_length = blob.code.len() / 8;
7115                let is_bitmask_padded = blob.code.len() % 8 != 0;
7116                expected_bitmask_length += usize::from(is_bitmask_padded);
7117
7118                if blob.bitmask.len() != expected_bitmask_length {
7119                    return Err(ProgramParseError(ProgramParseErrorKind::Other(
7120                        "the bitmask length doesn't match the code length",
7121                    )));
7122                }
7123
7124                if is_bitmask_padded {
7125                    let last_byte = *blob.bitmask.last().unwrap();
7126                    let padding_bits = blob.bitmask.len() * 8 - blob.code.len();
7127                    let padding_mask = ((0b10000000_u8 as i8) >> (padding_bits - 1)) as u8;
7128                    if last_byte & padding_mask != 0 {
7129                        return Err(ProgramParseError(ProgramParseErrorKind::Other(
7130                            "the bitmask is padded with non-zero bits",
7131                        )));
7132                    }
7133                }
7134            }
7135        }
7136
7137        #[cfg(feature = "unique-id")]
7138        {
7139            static ID_COUNTER: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
7140            blob.unique_id = ID_COUNTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
7141        }
7142
7143        Ok(blob)
7144    }
7145
7146    #[cfg(feature = "unique-id")]
7147    /// Returns an unique ID of the program blob.
7148    ///
7149    /// This is an automatically incremented counter every time a `ProgramBlob` is created.
7150    pub fn unique_id(&self) -> u64 {
7151        self.unique_id
7152    }
7153
7154    /// Returns the instruction set of this program blob.
7155    pub fn isa(&self) -> InstructionSetKind {
7156        self.isa
7157    }
7158
7159    /// Returns whether the blob contains a 64-bit program.
7160    pub fn is_64_bit(&self) -> bool {
7161        self.isa.is_64_bit()
7162    }
7163
7164    /// Returns the metadata hash embedded in the blob, or an empty slice if none is present.
7165    pub fn metadata_hash(&self) -> &[u8] {
7166        &self.metadata_hash
7167    }
7168
7169    /// Calculates an unique hash of the program blob.
7170    pub fn unique_hash(&self, include_debug: bool) -> crate::hasher::Hash {
7171        let ProgramBlob {
7172            #[cfg(feature = "unique-id")]
7173                unique_id: _,
7174            isa,
7175            ro_data_size,
7176            rw_data_size,
7177            stack_size,
7178            ro_data,
7179            rw_data,
7180            code,
7181            jump_table,
7182            jump_table_entry_size,
7183            bitmask,
7184            import_offsets,
7185            import_symbols,
7186            exports,
7187            debug_strings,
7188            debug_line_program_ranges,
7189            debug_line_programs,
7190            metadata_hash: _,
7191        } = self;
7192
7193        let mut hasher = crate::hasher::Hasher::new();
7194
7195        hasher.update_u32_array([
7196            1_u32, // VERSION
7197            *isa as u32,
7198            *ro_data_size,
7199            *rw_data_size,
7200            *stack_size,
7201            ro_data.len() as u32,
7202            rw_data.len() as u32,
7203            code.len() as u32,
7204            jump_table.len() as u32,
7205            u32::from(*jump_table_entry_size),
7206            bitmask.len() as u32,
7207            import_offsets.len() as u32,
7208            import_symbols.len() as u32,
7209            exports.len() as u32,
7210        ]);
7211
7212        hasher.update(ro_data);
7213        hasher.update(rw_data);
7214        hasher.update(code);
7215        hasher.update(jump_table);
7216        hasher.update(bitmask);
7217        hasher.update(import_offsets);
7218        hasher.update(import_symbols);
7219        hasher.update(exports);
7220
7221        if include_debug {
7222            hasher.update_u32_array([
7223                debug_strings.len() as u32,
7224                debug_line_program_ranges.len() as u32,
7225                debug_line_programs.len() as u32,
7226            ]);
7227
7228            hasher.update(debug_strings);
7229            hasher.update(debug_line_program_ranges);
7230            hasher.update(debug_line_programs);
7231        }
7232
7233        hasher.finalize()
7234    }
7235
7236    /// Returns the contents of the read-only data section.
7237    ///
7238    /// This only covers the initial non-zero portion of the section; use `ro_data_size` to get the full size.
7239    pub fn ro_data(&self) -> &[u8] {
7240        &self.ro_data
7241    }
7242
7243    /// Returns an Arc of the read-only data section.
7244    pub fn ro_data_arc(&self) -> &ArcBytes {
7245        &self.ro_data
7246    }
7247
7248    /// Returns the size of the read-only data section.
7249    ///
7250    /// This can be larger than the length of `ro_data`, in which case the rest of the space is assumed to be filled with zeros.
7251    pub fn ro_data_size(&self) -> u32 {
7252        self.ro_data_size
7253    }
7254
7255    /// Returns the contents of the read-write data section.
7256    ///
7257    /// This only covers the initial non-zero portion of the section; use `rw_data_size` to get the full size.
7258    pub fn rw_data(&self) -> &[u8] {
7259        &self.rw_data
7260    }
7261
7262    /// Returns an Arc of the read-write data section.
7263    pub fn rw_data_arc(&self) -> &ArcBytes {
7264        &self.rw_data
7265    }
7266
7267    /// Returns the size of the read-write data section.
7268    ///
7269    /// This can be larger than the length of `rw_data`, in which case the rest of the space is assumed to be filled with zeros.
7270    pub fn rw_data_size(&self) -> u32 {
7271        self.rw_data_size
7272    }
7273
7274    /// Returns the initial size of the stack.
7275    pub fn stack_size(&self) -> u32 {
7276        self.stack_size
7277    }
7278
7279    /// Returns the program code in its raw form.
7280    pub fn code(&self) -> &[u8] {
7281        &self.code
7282    }
7283
7284    #[cfg(feature = "export-internals-for-testing")]
7285    #[doc(hidden)]
7286    pub fn set_code(&mut self, code: ArcBytes) {
7287        self.code = code;
7288    }
7289
7290    /// Returns the code bitmask in its raw form.
7291    pub fn bitmask(&self) -> &[u8] {
7292        &self.bitmask
7293    }
7294
7295    #[cfg(feature = "export-internals-for-testing")]
7296    #[doc(hidden)]
7297    pub fn set_bitmask(&mut self, bitmask: ArcBytes) {
7298        self.bitmask = bitmask;
7299    }
7300
7301    pub fn imports(&self) -> Imports {
7302        Imports {
7303            offsets: &self.import_offsets,
7304            symbols: &self.import_symbols,
7305        }
7306    }
7307
7308    /// Returns an iterator over program exports.
7309    pub fn exports(&self) -> impl Iterator<Item = ProgramExport<&[u8]>> + Clone {
7310        #[derive(Clone)]
7311        enum State {
7312            Uninitialized,
7313            Pending(u32),
7314            Finished,
7315        }
7316
7317        #[derive(Clone)]
7318        struct ExportIterator<'a> {
7319            state: State,
7320            reader: Reader<'a, [u8]>,
7321        }
7322
7323        impl<'a> Iterator for ExportIterator<'a> {
7324            type Item = ProgramExport<&'a [u8]>;
7325            fn next(&mut self) -> Option<Self::Item> {
7326                let remaining = match core::mem::replace(&mut self.state, State::Finished) {
7327                    State::Uninitialized => self.reader.read_varint().ok()?,
7328                    State::Pending(remaining) => remaining,
7329                    State::Finished => return None,
7330                };
7331
7332                if remaining == 0 {
7333                    return None;
7334                }
7335
7336                let target_code_offset = self.reader.read_varint().ok()?;
7337                let symbol = self.reader.read_bytes_with_length().ok()?;
7338                let export = ProgramExport {
7339                    program_counter: ProgramCounter(target_code_offset),
7340                    symbol: ProgramSymbol::new(symbol),
7341                };
7342
7343                self.state = State::Pending(remaining - 1);
7344                Some(export)
7345            }
7346        }
7347
7348        ExportIterator {
7349            state: if !self.exports.is_empty() {
7350                State::Uninitialized
7351            } else {
7352                State::Finished
7353            },
7354            reader: Reader {
7355                blob: &self.exports,
7356                position: 0,
7357            },
7358        }
7359    }
7360
7361    /// Visits every instruction in the program.
7362    #[cfg_attr(not(debug_assertions), inline(always))]
7363    pub fn visit<T>(&self, dispatch_table: T, visitor: &mut T::State)
7364    where
7365        T: OpcodeVisitor<ReturnTy = ()>,
7366    {
7367        visitor_run(visitor, self, dispatch_table);
7368    }
7369
7370    #[inline]
7371    pub fn instructions(&self) -> Instructions<InstructionSetKind> {
7372        self.instructions_with_isa(self.isa)
7373    }
7374
7375    #[inline]
7376    pub fn instructions_bounded_at(&self, offset: ProgramCounter) -> Instructions<InstructionSetKind> {
7377        self.instructions_bounded_at_with_isa(self.isa, offset)
7378    }
7379
7380    /// Returns an iterator over all of the instructions in the program.
7381    ///
7382    /// WARNING: this is unbounded and has O(n) complexity; just creating this iterator can iterate over the whole program, even if `next` is never called!
7383    #[inline]
7384    pub fn instructions_with_isa<I>(&self, instruction_set: I) -> Instructions<I>
7385    where
7386        I: InstructionSet,
7387    {
7388        Instructions::new_unbounded(instruction_set, self.code(), self.bitmask(), 0)
7389    }
7390
7391    /// Returns an interator over instructions starting at a given offset.
7392    ///
7393    /// This iterator is bounded and has O(1) complexity.
7394    #[inline]
7395    pub fn instructions_bounded_at_with_isa<I>(&self, instruction_set: I, offset: ProgramCounter) -> Instructions<I>
7396    where
7397        I: InstructionSet,
7398    {
7399        Instructions::new_bounded(instruction_set, self.code(), self.bitmask(), offset.0)
7400    }
7401
7402    /// Same as [`Self::instructions_bounded_at`], but assumes `offset` is a known instruction boundary
7403    /// (e.g. it was validated with `is_jump_target_valid`), skipping the boundary check.
7404    ///
7405    /// Calling this with an offset which is *not* an instruction boundary may decode in a way
7406    /// which disagrees with a linear decode of the program.
7407    #[inline]
7408    pub fn instructions_bounded_at_known_boundary(&self, offset: ProgramCounter) -> Instructions<InstructionSetKind> {
7409        Instructions::new_bounded_known_boundary(self.isa, self.code(), self.bitmask(), offset.0)
7410    }
7411
7412    /// Returns whether the code of the module is well formed. Has worst-case O(n) complexity.
7413    pub fn validate_code_with_isa<I>(&self, instruction_set: I) -> Result<(), ProgramCounter>
7414    where
7415        I: InstructionSet,
7416    {
7417        for instruction in self.instructions_bounded_at_with_isa(instruction_set, ProgramCounter(0)) {
7418            if matches!(instruction.kind, Instruction::invalid) {
7419                return Err(instruction.offset);
7420            }
7421        }
7422
7423        Ok(())
7424    }
7425
7426    /// Returns whether the given program counter is a valid target for a jump.
7427    pub fn scan_is_jump_target_valid<I>(&self, instruction_set: I, target: ProgramCounter) -> bool
7428    where
7429        I: InstructionSet,
7430    {
7431        if instruction_set.is_legacy() {
7432            is_jump_target_valid_legacy(instruction_set, self.code(), self.bitmask(), target.0)
7433        } else {
7434            scan_is_jump_target_valid_extended(instruction_set, self.code(), target.0)
7435        }
7436    }
7437
7438    /// Returns a jump table.
7439    pub fn jump_table(&self) -> JumpTable {
7440        JumpTable {
7441            blob: &self.jump_table,
7442            entry_size: u32::from(self.jump_table_entry_size),
7443        }
7444    }
7445
7446    /// Returns the debug string for the given relative offset.
7447    pub fn get_debug_string(&self, offset: u32) -> Result<&str, ProgramParseError> {
7448        let mut reader = Reader {
7449            blob: &self.debug_strings,
7450            position: 0,
7451        };
7452        reader.skip(offset as usize)?;
7453        reader.read_string_with_length()
7454    }
7455
7456    /// Returns the line program for the given instruction.
7457    pub fn get_debug_line_program_at(&self, program_counter: ProgramCounter) -> Result<Option<LineProgram>, ProgramParseError> {
7458        let program_counter = program_counter.0;
7459        if self.debug_line_program_ranges.is_empty() || self.debug_line_programs.is_empty() {
7460            return Ok(None);
7461        }
7462
7463        if self.debug_line_programs[0] != VERSION_DEBUG_LINE_PROGRAM_V1 {
7464            return Err(ProgramParseError(ProgramParseErrorKind::Other(
7465                "the debug line programs section has an unsupported version",
7466            )));
7467        }
7468
7469        const ENTRY_SIZE: usize = 12;
7470
7471        let slice = &self.debug_line_program_ranges;
7472        if slice.len() % ENTRY_SIZE != 0 {
7473            return Err(ProgramParseError(ProgramParseErrorKind::Other(
7474                "the debug function ranges section has an invalid size",
7475            )));
7476        }
7477
7478        let offset = binary_search(slice, ENTRY_SIZE, |xs| {
7479            let begin = u32::from_le_bytes([xs[0], xs[1], xs[2], xs[3]]);
7480            if program_counter < begin {
7481                return core::cmp::Ordering::Greater;
7482            }
7483
7484            let end = u32::from_le_bytes([xs[4], xs[5], xs[6], xs[7]]);
7485            if program_counter >= end {
7486                return core::cmp::Ordering::Less;
7487            }
7488
7489            core::cmp::Ordering::Equal
7490        });
7491
7492        let Ok(offset) = offset else { return Ok(None) };
7493
7494        let xs = &slice[offset..offset + ENTRY_SIZE];
7495        let index_begin = u32::from_le_bytes([xs[0], xs[1], xs[2], xs[3]]);
7496        let index_end = u32::from_le_bytes([xs[4], xs[5], xs[6], xs[7]]);
7497        let info_offset = u32::from_le_bytes([xs[8], xs[9], xs[10], xs[11]]);
7498
7499        if program_counter < index_begin || program_counter >= index_end {
7500            return Err(ProgramParseError(ProgramParseErrorKind::Other(
7501                "binary search for function debug info failed",
7502            )));
7503        }
7504
7505        let mut reader = Reader {
7506            blob: &self.debug_line_programs,
7507            position: 0,
7508        };
7509
7510        reader.skip(info_offset as usize)?;
7511
7512        Ok(Some(LineProgram {
7513            entry_index: offset / ENTRY_SIZE,
7514            region_counter: 0,
7515            blob: self,
7516            reader,
7517            is_finished: false,
7518            program_counter: index_begin,
7519            stack: Default::default(),
7520            stack_depth: 0,
7521            mutation_depth: 0,
7522        }))
7523    }
7524
7525    pub fn get_frame_info_for<'a>(
7526        &'a self,
7527        program_counter: ProgramCounter,
7528        iteration_limit: Option<usize>,
7529    ) -> impl Iterator<Item = FrameInfo<'a>> {
7530        struct FrameInfoIter<'a> {
7531            program_counter: ProgramCounter,
7532            line_program: Option<LineProgram<'a>>,
7533            region_info: Option<RawRegionInfo>,
7534            current_frame: usize,
7535            iteration_limit: usize,
7536        }
7537
7538        impl<'a> Iterator for FrameInfoIter<'a> {
7539            type Item = FrameInfo<'a>;
7540            fn next(&mut self) -> Option<Self::Item> {
7541                self.line_program.as_ref()?;
7542
7543                loop {
7544                    if let Some(ref region_info) = self.region_info {
7545                        let line_program = self.line_program.as_ref()?;
7546                        let region_info = line_program.convert_region_info(region_info.clone());
7547                        if let Some(frame) = region_info.frames.get(self.current_frame) {
7548                            self.current_frame += 1;
7549                            return Some(FrameInfo {
7550                                blob: line_program.blob,
7551                                inner: frame.clone(),
7552                            });
7553                        }
7554                    }
7555
7556                    let line_program = self.line_program.as_mut()?;
7557                    loop {
7558                        if self.iteration_limit == 0 {
7559                            return None;
7560                        }
7561
7562                        self.iteration_limit -= 1;
7563
7564                        let Ok(Some(region_info)) = line_program.raw_run(INSTRUCTION_LIMIT_PER_REGION) else {
7565                            self.iteration_limit = 0;
7566                            return None;
7567                        };
7568
7569                        if !region_info.range.contains(&self.program_counter) {
7570                            continue;
7571                        }
7572
7573                        self.region_info = Some(region_info);
7574                        self.current_frame = 0;
7575                        break;
7576                    }
7577                }
7578            }
7579        }
7580
7581        let line_program = match self.get_debug_line_program_at(program_counter) {
7582            Ok(Some(line_program)) => Some(line_program),
7583            _ => None,
7584        };
7585
7586        FrameInfoIter {
7587            program_counter,
7588            line_program,
7589            region_info: None,
7590            current_frame: 0,
7591            iteration_limit: iteration_limit.unwrap_or(self.debug_line_programs.len()),
7592        }
7593    }
7594
7595    #[cfg(feature = "alloc")]
7596    pub(crate) fn calculate_blob_length(&self) -> u64 {
7597        let ProgramBlob {
7598            #[cfg(feature = "unique-id")]
7599                unique_id: _,
7600            isa: _,
7601            ro_data_size: _,
7602            rw_data_size: _,
7603            stack_size: _,
7604            ro_data,
7605            rw_data,
7606            code,
7607            jump_table,
7608            jump_table_entry_size: _,
7609            bitmask,
7610            import_offsets,
7611            import_symbols,
7612            exports,
7613            debug_strings,
7614            debug_line_program_ranges,
7615            debug_line_programs,
7616            metadata_hash,
7617        } = self;
7618
7619        let mut ranges = [
7620            ro_data.parent_address_range(),
7621            rw_data.parent_address_range(),
7622            code.parent_address_range(),
7623            jump_table.parent_address_range(),
7624            bitmask.parent_address_range(),
7625            import_offsets.parent_address_range(),
7626            import_symbols.parent_address_range(),
7627            exports.parent_address_range(),
7628            debug_strings.parent_address_range(),
7629            debug_line_program_ranges.parent_address_range(),
7630            debug_line_programs.parent_address_range(),
7631            metadata_hash.parent_address_range(),
7632        ];
7633
7634        ranges.sort_unstable_by_key(|r| r.start);
7635
7636        let mut blob_length = 0;
7637        let mut last_range = 0..0;
7638        for range in ranges {
7639            if range == last_range {
7640                continue;
7641            }
7642            blob_length += cast(range.len()).to_u64();
7643            last_range = range;
7644        }
7645        blob_length
7646    }
7647
7648    #[cfg(feature = "alloc")]
7649    pub fn estimate_interpreter_memory_usage(&self, args: EstimateInterpreterMemoryUsageArgs) -> Result<ProgramMemoryInfo, &'static str> {
7650        let (page_size, instruction_count, basic_block_count) = match args {
7651            EstimateInterpreterMemoryUsageArgs::UnboundedCache {
7652                page_size,
7653                instruction_count,
7654                basic_block_count,
7655                ..
7656            } => (page_size, instruction_count, basic_block_count),
7657            EstimateInterpreterMemoryUsageArgs::BoundedCache {
7658                page_size,
7659                instruction_count,
7660                basic_block_count,
7661                ..
7662            } => (page_size, instruction_count, basic_block_count),
7663        };
7664
7665        // The cache grows in powers of two, with room for four more entries before each instruction.
7666        let cache_entry_count_upper_bound =
7667            (cast(instruction_count).to_usize() + cast(basic_block_count).to_usize() + 4).next_power_of_two();
7668        let cache_size_upper_bound = interpreter_calculate_cache_size(cache_entry_count_upper_bound);
7669
7670        let mut purgeable_ram_consumption = match args {
7671            EstimateInterpreterMemoryUsageArgs::UnboundedCache { .. } => cache_size_upper_bound,
7672            EstimateInterpreterMemoryUsageArgs::BoundedCache {
7673                max_cache_size_bytes,
7674                max_block_size,
7675                ..
7676            } => {
7677                let max_cache_size_bytes = cast(max_cache_size_bytes).to_usize();
7678                let cache_entry_count_hard_limit = cast(max_block_size).to_usize();
7679                let cache_bytes_hard_limit = interpreter_calculate_cache_size(cache_entry_count_hard_limit);
7680                if cache_bytes_hard_limit > max_cache_size_bytes {
7681                    return Err("maximum cache size is too small for the given max block size");
7682                }
7683
7684                max_cache_size_bytes.min(cache_size_upper_bound)
7685            }
7686        };
7687
7688        let code_length = self.code.len();
7689        purgeable_ram_consumption = purgeable_ram_consumption.saturating_add((code_length + 1) * INTERPRETER_FLATMAP_ENTRY_SIZE as usize);
7690
7691        if !self.isa.is_legacy() {
7692            let code_block_count = code_length.div_ceil(CODE_BLOCK_SIZE);
7693            purgeable_ram_consumption = purgeable_ram_consumption.saturating_add(
7694                code_block_count * core::mem::size_of::<CodeBlockBitmap>()
7695                    + core::cmp::max(4, code_block_count) * core::mem::size_of::<usize>(),
7696            );
7697        }
7698
7699        let Ok(purgeable_ram_consumption) = u32::try_from(purgeable_ram_consumption) else {
7700            return Err("estimated interpreter cache size is too large");
7701        };
7702
7703        let memory_map = MemoryMapBuilder::new(page_size)
7704            .ro_data_size(self.ro_data_size)
7705            .rw_data_size(self.rw_data_size)
7706            .stack_size(self.stack_size)
7707            .build()?;
7708
7709        let blob_length = self.calculate_blob_length();
7710        let Ok(baseline_ram_consumption) = u32::try_from(
7711            blob_length
7712                .saturating_add(u64::from(memory_map.ro_data_size()))
7713                .saturating_sub(self.ro_data.len() as u64)
7714                .saturating_add(u64::from(memory_map.rw_data_size()))
7715                .saturating_sub(self.rw_data.len() as u64)
7716                .saturating_add(u64::from(memory_map.stack_size())),
7717        ) else {
7718            return Err("calculated baseline RAM consumption is too large");
7719        };
7720
7721        Ok(ProgramMemoryInfo {
7722            baseline_ram_consumption,
7723            purgeable_ram_consumption,
7724        })
7725    }
7726}
7727
7728#[cfg(feature = "alloc")]
7729#[test]
7730fn test_estimate_interpreter_memory_usage_accounts_for_the_jump_target_bitmaps() {
7731    fn estimate(isa: InstructionSetKind) -> (usize, usize) {
7732        let mut code = alloc::vec![asm::add_imm_64(Reg::A0, Reg::A0, 1); 2000];
7733        code.push(asm::trap());
7734
7735        let mut builder = crate::writer::ProgramBlobBuilder::new(isa);
7736        builder.set_code(&code, &[]);
7737        let blob = ProgramBlob::parse(builder.into_vec().unwrap().into()).unwrap();
7738        let info = blob
7739            .estimate_interpreter_memory_usage(EstimateInterpreterMemoryUsageArgs::UnboundedCache {
7740                instruction_count: code.len() as u32,
7741                basic_block_count: 1,
7742                page_size: 0x4000,
7743            })
7744            .unwrap();
7745
7746        let cache = interpreter_calculate_cache_size((code.len() + 1 + 4).next_power_of_two());
7747        let flat_map = (blob.code().len() + 1) * INTERPRETER_FLATMAP_ENTRY_SIZE as usize;
7748        (
7749            blob.code().len(),
7750            cast(info.purgeable_ram_consumption).to_usize() - cache - flat_map,
7751        )
7752    }
7753
7754    assert_eq!(estimate(InstructionSetKind::ReviveV1).1, 0);
7755
7756    let (code_length, extra) = estimate(InstructionSetKind::Latest64);
7757    assert!(code_length > CODE_BLOCK_SIZE);
7758    let code_block_count = code_length.div_ceil(CODE_BLOCK_SIZE);
7759    assert_eq!(
7760        extra,
7761        code_block_count * core::mem::size_of::<CodeBlockBitmap>() + core::cmp::max(4, code_block_count) * 8
7762    );
7763}
7764
7765#[cfg(feature = "alloc")]
7766#[test]
7767fn test_calculate_blob_length() {
7768    let mut builder = crate::writer::ProgramBlobBuilder::new(InstructionSetKind::Latest64);
7769    builder.set_code(&[Instruction::trap], &[]);
7770    let blob = builder.into_vec().unwrap();
7771    let parts = ProgramParts::from_bytes(blob.into()).unwrap();
7772
7773    let big_blob = ArcBytes::from(alloc::vec![0; 1024]);
7774    let small_blob = ArcBytes::from(&parts.code_and_jump_table[..]);
7775    let parts = ProgramParts {
7776        ro_data: big_blob.subslice(10..20),
7777        ro_data_size: 24,
7778        rw_data: big_blob.subslice(24..28),
7779        rw_data_size: 4,
7780        code_and_jump_table: small_blob.clone(),
7781        debug_strings: small_blob.clone(),
7782
7783        isa: InstructionSetKind::Latest64,
7784        stack_size: 0,
7785        import_offsets: Default::default(),
7786        import_symbols: Default::default(),
7787        exports: Default::default(),
7788        debug_line_program_ranges: Default::default(),
7789        debug_line_programs: Default::default(),
7790        metadata_hash: Default::default(),
7791    };
7792
7793    let blob = ProgramBlob::from_parts(parts).unwrap();
7794    assert_eq!(
7795        blob.calculate_blob_length(),
7796        (big_blob.len() + small_blob.len()).try_into().unwrap()
7797    );
7798}
7799
7800#[cfg(feature = "alloc")]
7801#[test]
7802fn test_jump_table_entry_width_with_interior_zero_byte() {
7803    const TARGET_POSITION: u32 = 0x0100FB;
7804
7805    let mut code = alloc::vec![Instruction::trap; TARGET_POSITION as usize];
7806    code.push(Instruction::fallthrough);
7807
7808    let mut builder = crate::writer::ProgramBlobBuilder::new(InstructionSetKind::Latest64);
7809    builder.set_code(&code, &[TARGET_POSITION]);
7810    let blob = ProgramBlob::parse(builder.into_vec().unwrap().into()).unwrap();
7811    assert_eq!(blob.jump_table().get_by_index(0), Some(ProgramCounter(TARGET_POSITION)));
7812}
7813
7814#[cfg(feature = "alloc")]
7815#[test]
7816fn test_from_parts_rejects_non_canonical_varints() {
7817    for code_and_jump_table in [
7818        // |j| = [80, 01]
7819        alloc::vec![0x80, 0x01, 0x01, 0x00, 0x00],
7820        // |j| = [c0, 01, 00]
7821        alloc::vec![0xc0, 0x01, 0x00, 0x01, 0x00, 0x00],
7822        // |j| = [e0, 01, 00, 00]
7823        alloc::vec![0xe0, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00],
7824    ] {
7825        let mut parts = ProgramParts::empty(InstructionSetKind::Latest64);
7826        parts.code_and_jump_table = ArcBytes::from(code_and_jump_table);
7827        assert!(ProgramBlob::from_parts(parts).is_err());
7828    }
7829}
7830
7831#[cfg(feature = "alloc")]
7832#[test]
7833fn test_from_parts_rejects_varints_outside_u32() {
7834    let mut parts = ProgramParts::empty(InstructionSetKind::Latest64);
7835    parts.code_and_jump_table = ArcBytes::from(alloc::vec![0xf1, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
7836    assert!(ProgramBlob::from_parts(parts).is_err());
7837}
7838
7839#[cfg(feature = "alloc")]
7840#[test]
7841fn test_from_parts_accepts_canonical_varints() {
7842    // |j| = 1, z = 1, j = [0], c = [trap]
7843    let mut parts = ProgramParts::empty(InstructionSetKind::Latest64);
7844    parts.code_and_jump_table = ArcBytes::from(alloc::vec![0x01, 0x01, 0x00, 0x00]);
7845    let blob = ProgramBlob::from_parts(parts).unwrap();
7846    assert_eq!(blob.jump_table().len(), 1);
7847    assert_eq!(blob.instructions().count(), 1);
7848}
7849
7850/// The source location.
7851#[derive(Copy, Clone, PartialEq, Eq, Debug)]
7852pub enum SourceLocation<'a> {
7853    Path { path: &'a str },
7854    PathAndLine { path: &'a str, line: u32 },
7855    Full { path: &'a str, line: u32, column: u32 },
7856}
7857
7858impl<'a> SourceLocation<'a> {
7859    /// The path to the original source file.
7860    pub fn path(&self) -> &'a str {
7861        match *self {
7862            Self::Path { path, .. } => path,
7863            Self::PathAndLine { path, .. } => path,
7864            Self::Full { path, .. } => path,
7865        }
7866    }
7867
7868    /// The line in the original source file.
7869    pub fn line(&self) -> Option<u32> {
7870        match *self {
7871            Self::Path { .. } => None,
7872            Self::PathAndLine { line, .. } => Some(line),
7873            Self::Full { line, .. } => Some(line),
7874        }
7875    }
7876
7877    /// The column in the original source file.
7878    pub fn column(&self) -> Option<u32> {
7879        match *self {
7880            Self::Path { .. } => None,
7881            Self::PathAndLine { .. } => None,
7882            Self::Full { column, .. } => Some(column),
7883        }
7884    }
7885}
7886
7887impl<'a> core::fmt::Display for SourceLocation<'a> {
7888    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
7889        match *self {
7890            Self::Path { path } => fmt.write_str(path),
7891            Self::PathAndLine { path, line } => write!(fmt, "{}:{}", path, line),
7892            Self::Full { path, line, column } => write!(fmt, "{}:{}:{}", path, line, column),
7893        }
7894    }
7895}
7896
7897#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
7898pub enum FrameKind {
7899    Enter,
7900    Call,
7901    Line,
7902}
7903
7904pub struct FrameInfo<'a> {
7905    blob: &'a ProgramBlob,
7906    inner: LineProgramFrame,
7907}
7908
7909impl<'a> FrameInfo<'a> {
7910    /// Returns the namespace of this location, if available.
7911    pub fn namespace(&self) -> Result<Option<&str>, ProgramParseError> {
7912        let namespace = self.blob.get_debug_string(self.inner.namespace_offset)?;
7913        if namespace.is_empty() {
7914            Ok(None)
7915        } else {
7916            Ok(Some(namespace))
7917        }
7918    }
7919
7920    /// Returns the function name of location without the namespace, if available.
7921    pub fn function_name_without_namespace(&self) -> Result<Option<&str>, ProgramParseError> {
7922        let function_name = self.blob.get_debug_string(self.inner.function_name_offset)?;
7923        if function_name.is_empty() {
7924            Ok(None)
7925        } else {
7926            Ok(Some(function_name))
7927        }
7928    }
7929
7930    /// Returns the offset into the debug strings section containing the source code path of this location, if available.
7931    pub fn path_debug_string_offset(&self) -> Option<u32> {
7932        if self.inner.path_offset == 0 {
7933            None
7934        } else {
7935            Some(self.inner.path_offset)
7936        }
7937    }
7938
7939    /// Returns the source code path of this location, if available.
7940    pub fn path(&self) -> Result<Option<&str>, ProgramParseError> {
7941        let path = self.blob.get_debug_string(self.inner.path_offset)?;
7942        if path.is_empty() {
7943            Ok(None)
7944        } else {
7945            Ok(Some(path))
7946        }
7947    }
7948
7949    /// Returns the source code line of this location, if available.
7950    pub fn line(&self) -> Option<u32> {
7951        if self.inner.line == 0 {
7952            None
7953        } else {
7954            Some(self.inner.line)
7955        }
7956    }
7957
7958    /// Returns the source code column of this location, if available.
7959    pub fn column(&self) -> Option<u32> {
7960        if self.inner.column == 0 {
7961            None
7962        } else {
7963            Some(self.inner.column)
7964        }
7965    }
7966
7967    pub fn kind(&self) -> FrameKind {
7968        self.inner.kind.unwrap_or(FrameKind::Line)
7969    }
7970
7971    /// Returns the full name of the function.
7972    pub fn full_name(&'_ self) -> Result<impl core::fmt::Display + '_, ProgramParseError> {
7973        Ok(DisplayName {
7974            prefix: self.namespace()?.unwrap_or(""),
7975            suffix: self.function_name_without_namespace()?.unwrap_or(""),
7976        })
7977    }
7978
7979    /// Returns the source location of where this frame comes from.
7980    pub fn location(&self) -> Result<Option<SourceLocation>, ProgramParseError> {
7981        if let Some(path) = self.path()? {
7982            if let Some(line) = self.line() {
7983                if let Some(column) = self.column() {
7984                    Ok(Some(SourceLocation::Full { path, line, column }))
7985                } else {
7986                    Ok(Some(SourceLocation::PathAndLine { path, line }))
7987                }
7988            } else {
7989                Ok(Some(SourceLocation::Path { path }))
7990            }
7991        } else {
7992            Ok(None)
7993        }
7994    }
7995}
7996
7997/// Debug information about a given region of bytecode.
7998pub struct RegionInfo<'a> {
7999    entry_index: usize,
8000    blob: &'a ProgramBlob,
8001    range: Range<ProgramCounter>,
8002    frames: &'a [LineProgramFrame],
8003}
8004
8005#[derive(Clone)]
8006struct RawRegionInfo {
8007    entry_index: usize,
8008    range: Range<ProgramCounter>,
8009    frame_count: usize,
8010}
8011
8012impl<'a> RegionInfo<'a> {
8013    /// Returns the entry index of this region info within the parent line program object.
8014    pub fn entry_index(&self) -> usize {
8015        self.entry_index
8016    }
8017
8018    /// The range of instructions this region covers.
8019    pub fn instruction_range(&self) -> Range<ProgramCounter> {
8020        self.range.clone()
8021    }
8022
8023    /// Returns an iterator over the frames this region covers.
8024    pub fn frames(&self) -> impl ExactSizeIterator<Item = FrameInfo> {
8025        self.frames.iter().map(|inner| FrameInfo {
8026            blob: self.blob,
8027            inner: inner.clone(),
8028        })
8029    }
8030}
8031
8032#[derive(Clone, Default)]
8033struct LineProgramFrame {
8034    kind: Option<FrameKind>,
8035    namespace_offset: u32,
8036    function_name_offset: u32,
8037    path_offset: u32,
8038    line: u32,
8039    column: u32,
8040}
8041
8042/// The default maximum number of line program opcodes parsed for a single region.
8043const INSTRUCTION_LIMIT_PER_REGION: usize = 512;
8044
8045/// A configuration for how a [`LineProgram`] is run.
8046#[derive(Clone, Copy, Debug)]
8047#[non_exhaustive]
8048pub struct LineProgramConfig {
8049    /// The maximum number of line program opcodes parsed for a single region.
8050    ///
8051    /// Parsing fails once a region exceeds this many opcodes, which bounds the work
8052    /// a single region can trigger. Set it to [`usize::MAX`] to disable the limit.
8053    pub instruction_limit_per_region: usize,
8054}
8055
8056impl Default for LineProgramConfig {
8057    fn default() -> Self {
8058        LineProgramConfig {
8059            instruction_limit_per_region: INSTRUCTION_LIMIT_PER_REGION,
8060        }
8061    }
8062}
8063
8064/// A line program state machine.
8065pub struct LineProgram<'a> {
8066    entry_index: usize,
8067    region_counter: usize,
8068    blob: &'a ProgramBlob,
8069    reader: Reader<'a, ArcBytes>,
8070    is_finished: bool,
8071    program_counter: u32,
8072    // Support inline call stacks ~16 frames deep. Picked entirely arbitrarily.
8073    stack: [LineProgramFrame; 16],
8074    stack_depth: u32,
8075    mutation_depth: u32,
8076}
8077
8078impl<'a> LineProgram<'a> {
8079    /// Returns the entry index of this line program object.
8080    pub fn entry_index(&self) -> usize {
8081        self.entry_index
8082    }
8083
8084    /// Runs the line program until the next region becomes available, or until the program ends.
8085    pub fn run(&mut self) -> Result<Option<RegionInfo>, ProgramParseError> {
8086        self.run_with_config(LineProgramConfig::default())
8087    }
8088
8089    /// Runs the line program until the next region becomes available, or until the program ends,
8090    /// using the provided `config` to control how the program is parsed.
8091    pub fn run_with_config(&mut self, config: LineProgramConfig) -> Result<Option<RegionInfo>, ProgramParseError> {
8092        match self.raw_run(config.instruction_limit_per_region) {
8093            Ok(Some(region_info)) => Ok(Some(self.convert_region_info(region_info))),
8094            Ok(None) => Ok(None),
8095            Err(error) => Err(error),
8096        }
8097    }
8098
8099    fn convert_region_info(&self, region_info: RawRegionInfo) -> RegionInfo {
8100        RegionInfo {
8101            entry_index: region_info.entry_index,
8102            blob: self.blob,
8103            range: region_info.range,
8104            frames: &self.stack[..region_info.frame_count],
8105        }
8106    }
8107
8108    fn raw_run(&mut self, instruction_limit_per_region: usize) -> Result<Option<RawRegionInfo>, ProgramParseError> {
8109        struct SetTrueOnDrop<'a>(&'a mut bool);
8110        impl<'a> Drop for SetTrueOnDrop<'a> {
8111            fn drop(&mut self) {
8112                *self.0 = true;
8113            }
8114        }
8115
8116        if self.is_finished {
8117            return Ok(None);
8118        }
8119
8120        let mark_as_finished_on_drop = SetTrueOnDrop(&mut self.is_finished);
8121        for _ in 0..instruction_limit_per_region {
8122            let byte = match self.reader.read_byte() {
8123                Ok(byte) => byte,
8124                Err(error) => {
8125                    return Err(error);
8126                }
8127            };
8128
8129            let Some(opcode) = LineProgramOp::from_u8(byte) else {
8130                return Err(ProgramParseError(ProgramParseErrorKind::Other(
8131                    "found an unrecognized line program opcode",
8132                )));
8133            };
8134
8135            let (count, stack_depth) = match opcode {
8136                LineProgramOp::FinishProgram => {
8137                    return Ok(None);
8138                }
8139                LineProgramOp::SetMutationDepth => {
8140                    self.mutation_depth = self.reader.read_varint()?;
8141                    continue;
8142                }
8143                LineProgramOp::SetKindEnter => {
8144                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8145                        frame.kind = Some(FrameKind::Enter);
8146                    }
8147                    continue;
8148                }
8149                LineProgramOp::SetKindCall => {
8150                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8151                        frame.kind = Some(FrameKind::Call);
8152                    }
8153                    continue;
8154                }
8155                LineProgramOp::SetKindLine => {
8156                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8157                        frame.kind = Some(FrameKind::Line);
8158                    }
8159                    continue;
8160                }
8161                LineProgramOp::SetNamespace => {
8162                    let value = self.reader.read_varint()?;
8163                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8164                        frame.namespace_offset = value;
8165                    }
8166                    continue;
8167                }
8168                LineProgramOp::SetFunctionName => {
8169                    let value = self.reader.read_varint()?;
8170                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8171                        frame.function_name_offset = value;
8172                    }
8173                    continue;
8174                }
8175                LineProgramOp::SetPath => {
8176                    let value = self.reader.read_varint()?;
8177                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8178                        frame.path_offset = value;
8179                    }
8180                    continue;
8181                }
8182                LineProgramOp::SetLine => {
8183                    let value = self.reader.read_varint()?;
8184                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8185                        frame.line = value;
8186                    }
8187                    continue;
8188                }
8189                LineProgramOp::SetColumn => {
8190                    let value = self.reader.read_varint()?;
8191                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8192                        frame.column = value;
8193                    }
8194                    continue;
8195                }
8196                LineProgramOp::SetStackDepth => {
8197                    self.stack_depth = self.reader.read_varint()?;
8198                    continue;
8199                }
8200                LineProgramOp::IncrementLine => {
8201                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8202                        frame.line += 1;
8203                    }
8204                    continue;
8205                }
8206                LineProgramOp::AddLine => {
8207                    let value = self.reader.read_varint()?;
8208                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8209                        frame.line = frame.line.wrapping_add(value);
8210                    }
8211                    continue;
8212                }
8213                LineProgramOp::SubLine => {
8214                    let value = self.reader.read_varint()?;
8215                    if let Some(frame) = self.stack.get_mut(self.mutation_depth as usize) {
8216                        frame.line = frame.line.wrapping_sub(value);
8217                    }
8218                    continue;
8219                }
8220                LineProgramOp::FinishInstruction => (1, self.stack_depth),
8221                LineProgramOp::FinishMultipleInstructions => {
8222                    let count = self.reader.read_varint()?;
8223                    (count, self.stack_depth)
8224                }
8225                LineProgramOp::FinishInstructionAndIncrementStackDepth => {
8226                    let depth = self.stack_depth;
8227                    self.stack_depth = self.stack_depth.saturating_add(1);
8228                    (1, depth)
8229                }
8230                LineProgramOp::FinishMultipleInstructionsAndIncrementStackDepth => {
8231                    let count = self.reader.read_varint()?;
8232                    let depth = self.stack_depth;
8233                    self.stack_depth = self.stack_depth.saturating_add(1);
8234                    (count, depth)
8235                }
8236                LineProgramOp::FinishInstructionAndDecrementStackDepth => {
8237                    let depth = self.stack_depth;
8238                    self.stack_depth = self.stack_depth.saturating_sub(1);
8239                    (1, depth)
8240                }
8241                LineProgramOp::FinishMultipleInstructionsAndDecrementStackDepth => {
8242                    let count = self.reader.read_varint()?;
8243                    let depth = self.stack_depth;
8244                    self.stack_depth = self.stack_depth.saturating_sub(1);
8245                    (count, depth)
8246                }
8247            };
8248
8249            let range = ProgramCounter(self.program_counter)..ProgramCounter(self.program_counter + count);
8250            self.program_counter += count;
8251
8252            core::mem::forget(mark_as_finished_on_drop);
8253
8254            let entry_index = self.region_counter;
8255            self.region_counter += 1;
8256            return Ok(Some(RawRegionInfo {
8257                entry_index,
8258                range,
8259                frame_count: core::cmp::min(stack_depth as usize, self.stack.len()),
8260            }));
8261        }
8262
8263        Err(ProgramParseError(ProgramParseErrorKind::Other(
8264            "found a line program with too many instructions",
8265        )))
8266    }
8267}
8268
8269#[test]
8270fn test_default_line_program_config_uses_the_constant_limit() {
8271    assert_eq!(
8272        LineProgramConfig::default().instruction_limit_per_region,
8273        INSTRUCTION_LIMIT_PER_REGION
8274    );
8275}
8276
8277#[cfg(feature = "alloc")]
8278#[test]
8279fn test_run_with_config_can_raise_the_instruction_limit() {
8280    // One region padded with exactly the default budget of non-finishing opcodes, so its
8281    // finishing opcode falls just past the budget and the default parse should give up.
8282    let mut line_programs = alloc::vec![VERSION_DEBUG_LINE_PROGRAM_V1];
8283    for _ in 0..INSTRUCTION_LIMIT_PER_REGION {
8284        line_programs.push(LineProgramOp::IncrementLine as u8);
8285    }
8286    line_programs.push(LineProgramOp::FinishInstruction as u8);
8287    line_programs.push(LineProgramOp::FinishProgram as u8);
8288
8289    // A single range entry covering program counter 0, whose program starts right after the
8290    // one-byte version marker.
8291    let mut ranges = alloc::vec::Vec::new();
8292    ranges.extend_from_slice(&0_u32.to_le_bytes()); // program_counter_start
8293    ranges.extend_from_slice(&1_u32.to_le_bytes()); // program_counter_end
8294    ranges.extend_from_slice(&1_u32.to_le_bytes()); // info_offset (past the version marker)
8295
8296    let mut builder = crate::writer::ProgramBlobBuilder::new(InstructionSetKind::Latest64);
8297    builder.set_code(&[Instruction::trap], &[]);
8298    builder.add_custom_section(SECTION_OPT_DEBUG_LINE_PROGRAMS, line_programs);
8299    builder.add_custom_section(SECTION_OPT_DEBUG_LINE_PROGRAM_RANGES, ranges);
8300
8301    let blob = ProgramBlob::parse(builder.into_vec().unwrap().into()).unwrap();
8302
8303    // The default limit rejects the over-long region, exactly as a runtime consumer would.
8304    let mut line_program = blob.get_debug_line_program_at(ProgramCounter(0)).unwrap().unwrap();
8305    let Err(error) = line_program.run() else {
8306        panic!("the default limit should reject the over-long region");
8307    };
8308    assert!(
8309        alloc::format!("{error}").contains("too many instructions"),
8310        "unexpected error: {error}"
8311    );
8312
8313    // Raising the limit lets the same region parse: one region, then the program ends.
8314    let config = LineProgramConfig {
8315        instruction_limit_per_region: usize::MAX,
8316    };
8317    let mut line_program = blob.get_debug_line_program_at(ProgramCounter(0)).unwrap().unwrap();
8318    assert!(line_program.run_with_config(config).unwrap().is_some());
8319    assert!(line_program.run_with_config(config).unwrap().is_none());
8320}
8321
8322struct DisplayName<'a> {
8323    prefix: &'a str,
8324    suffix: &'a str,
8325}
8326
8327impl<'a> core::fmt::Display for DisplayName<'a> {
8328    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
8329        fmt.write_str(self.prefix)?;
8330        if !self.prefix.is_empty() {
8331            fmt.write_str("::")?;
8332        }
8333        fmt.write_str(self.suffix)
8334    }
8335}
8336
8337/// A binary search implementation which can work on chunks of items, and guarantees that it
8338/// will always return the first item if there are multiple identical consecutive items.
8339fn binary_search(slice: &[u8], chunk_size: usize, compare: impl Fn(&[u8]) -> core::cmp::Ordering) -> Result<usize, usize> {
8340    let mut size = slice.len() / chunk_size;
8341    if size == 0 {
8342        return Err(0);
8343    }
8344
8345    let mut base = 0_usize;
8346    while size > 1 {
8347        let half = size / 2;
8348        let mid = base + half;
8349        let item = &slice[mid * chunk_size..(mid + 1) * chunk_size];
8350        match compare(item) {
8351            core::cmp::Ordering::Greater => {
8352                // The value we're looking for is to the left of the midpoint.
8353                size -= half;
8354            }
8355            core::cmp::Ordering::Less => {
8356                // The value we're looking for is to the right of the midpoint.
8357                size -= half;
8358                base = mid;
8359            }
8360            core::cmp::Ordering::Equal => {
8361                // We've found the value, but it might not be the first value.
8362                let previous_item = &slice[(mid - 1) * chunk_size..mid * chunk_size];
8363                if compare(previous_item) != core::cmp::Ordering::Equal {
8364                    // It is the first value.
8365                    return Ok(mid * chunk_size);
8366                }
8367
8368                // It's not the first value. Let's continue.
8369                //
8370                // We could do a linear search here which in the average case
8371                // would probably be faster, but keeping it as a binary search
8372                // will avoid a worst-case O(n) scenario.
8373                size -= half;
8374            }
8375        }
8376    }
8377
8378    let item = &slice[base * chunk_size..(base + 1) * chunk_size];
8379    let ord = compare(item);
8380    if ord == core::cmp::Ordering::Equal {
8381        Ok(base * chunk_size)
8382    } else {
8383        Err((base + usize::from(ord == core::cmp::Ordering::Less)) * chunk_size)
8384    }
8385}
8386
8387#[cfg(test)]
8388extern crate std;
8389
8390#[cfg(test)]
8391proptest::proptest! {
8392    #![proptest_config(proptest::prelude::ProptestConfig::with_cases(20000))]
8393    #[allow(clippy::ignored_unit_patterns)]
8394    #[test]
8395    fn test_binary_search(needle: u8, mut xs: std::vec::Vec<u8>) {
8396        xs.sort();
8397        let binary_result = binary_search(&xs, 1, |slice| slice[0].cmp(&needle));
8398        let mut linear_result = Err(0);
8399        for (index, value) in xs.iter().copied().enumerate() {
8400            #[allow(clippy::comparison_chain)]
8401            if value == needle {
8402                linear_result = Ok(index);
8403                break;
8404            } else if value < needle {
8405                linear_result = Err(index + 1);
8406                continue;
8407            } else {
8408                break;
8409            }
8410        }
8411
8412        assert_eq!(binary_result, linear_result, "linear search = {:?}, binary search = {:?}, needle = {}, xs = {:?}", linear_result, binary_result, needle, xs);
8413    }
8414}
8415
8416/// The magic bytes with which every program blob must start with.
8417pub const BLOB_MAGIC: [u8; 4] = [b'P', b'V', b'M', b'\0'];
8418
8419/// The blob length is the length of the blob itself encoded as an 64bit LE integer.
8420/// By embedding this metadata into the header, program blobs stay opaque,
8421/// however this information can still easily be retrieved.
8422/// Found at offset 5 after the magic bytes and version number.
8423pub type BlobLen = u64;
8424pub const BLOB_LEN_SIZE: usize = core::mem::size_of::<BlobLen>();
8425pub const BLOB_LEN_OFFSET: usize = BLOB_MAGIC.len() + 1;
8426
8427pub const SECTION_MEMORY_CONFIG: u8 = 1;
8428pub const SECTION_RO_DATA: u8 = 2;
8429pub const SECTION_RW_DATA: u8 = 3;
8430pub const SECTION_IMPORTS: u8 = 4;
8431pub const SECTION_EXPORTS: u8 = 5;
8432pub const SECTION_CODE_AND_JUMP_TABLE: u8 = 6;
8433pub const SECTION_OPT_DEBUG_STRINGS: u8 = 128;
8434pub const SECTION_OPT_DEBUG_LINE_PROGRAMS: u8 = 129;
8435pub const SECTION_OPT_DEBUG_LINE_PROGRAM_RANGES: u8 = 130;
8436pub const SECTION_OPT_METADATA_HASH: u8 = 131;
8437pub const SECTION_END_OF_FILE: u8 = 0;
8438
8439pub const VERSION_DEBUG_LINE_PROGRAM_V1: u8 = 1;
8440
8441#[derive(Copy, Clone, Debug)]
8442pub enum LineProgramOp {
8443    FinishProgram = 0,
8444    SetMutationDepth = 1,
8445    SetKindEnter = 2,
8446    SetKindCall = 3,
8447    SetKindLine = 4,
8448    SetNamespace = 5,
8449    SetFunctionName = 6,
8450    SetPath = 7,
8451    SetLine = 8,
8452    SetColumn = 9,
8453    SetStackDepth = 10,
8454    IncrementLine = 11,
8455    AddLine = 12,
8456    SubLine = 13,
8457    FinishInstruction = 14,
8458    FinishMultipleInstructions = 15,
8459    FinishInstructionAndIncrementStackDepth = 16,
8460    FinishMultipleInstructionsAndIncrementStackDepth = 17,
8461    FinishInstructionAndDecrementStackDepth = 18,
8462    FinishMultipleInstructionsAndDecrementStackDepth = 19,
8463}
8464
8465impl LineProgramOp {
8466    #[inline]
8467    pub const fn from_u8(value: u8) -> Option<Self> {
8468        match value {
8469            0 => Some(Self::FinishProgram),
8470            1 => Some(Self::SetMutationDepth),
8471            2 => Some(Self::SetKindEnter),
8472            3 => Some(Self::SetKindCall),
8473            4 => Some(Self::SetKindLine),
8474            5 => Some(Self::SetNamespace),
8475            6 => Some(Self::SetFunctionName),
8476            7 => Some(Self::SetPath),
8477            8 => Some(Self::SetLine),
8478            9 => Some(Self::SetColumn),
8479            10 => Some(Self::SetStackDepth),
8480            11 => Some(Self::IncrementLine),
8481            12 => Some(Self::AddLine),
8482            13 => Some(Self::SubLine),
8483            14 => Some(Self::FinishInstruction),
8484            15 => Some(Self::FinishMultipleInstructions),
8485            16 => Some(Self::FinishInstructionAndIncrementStackDepth),
8486            17 => Some(Self::FinishMultipleInstructionsAndIncrementStackDepth),
8487            18 => Some(Self::FinishInstructionAndDecrementStackDepth),
8488            19 => Some(Self::FinishMultipleInstructionsAndDecrementStackDepth),
8489            _ => None,
8490        }
8491    }
8492}
8493
8494#[cfg(feature = "alloc")]
8495#[test]
8496fn test_instruction_formatting() {
8497    use crate::alloc::string::ToString;
8498    assert_eq!(self::asm::store_imm_indirect_u8(Reg::A0, 0, 2).to_string(), "u8 [a0] = 0x2");
8499    assert_eq!(self::asm::store_imm_indirect_u8(Reg::A0, 1, 2).to_string(), "u8 [a0 + 1] = 0x2");
8500    assert_eq!(self::asm::store_imm_indirect_u8(Reg::A0, -1, 2).to_string(), "u8 [a0 - 1] = 0x2");
8501}