ab_riscv_interpreter/lib.rs
1//! Composable and generic RISC-V interpreter.
2//!
3//! This interpreter is designed to work with abstractions from [`ab-riscv-primitives`] crate and is
4//! similarly composable with a powerful macro system and trait abstractions over handling of
5//! memory, syscalls, etc.
6//!
7//! [`ab-riscv-primitives`]: ab_riscv_primitives
8//!
9//! The immediate needs dictate the current set of available instructions and extensions. Consider
10//! contributing if you need something not yet available.
11//!
12//! `ab-riscv-act4-runner` crate in the repository contains a complementary RISC-V Architectural
13//! Certification Tests runner for <https://github.com/riscv-non-isa/riscv-arch-test> that ensures
14//! correct implementation.
15//!
16//! Does not require a standard library (`no_std`) or an allocator, never panics, almost 100% of the
17//! API abstractions are usable in const, including several extensions beyond base ISA.
18//!
19//! ## Examples
20//!
21//! `examples` directory contains runnable examples, in increasing order of complexity. Each of them
22//! executes a small program written in ordinary safe Rust and compiled for a bare-metal RISC-V
23//! target, see `examples/guests/README.md`:
24//! * `hello` is the smallest configuration that runs a real program: RV32I with no extensions and
25//! no `unsafe` anywhere
26//! * `checksum` composes RV64IMAC with the `#[instruction]` macro, together with an execution
27//! environment that provides what those extensions ask for, including handling of the guest's
28//! syscalls
29//! * `vector-sum` runs a vectorized guest and shows the vector CSRs and register file an execution
30//! environment has to provide for it
31//! * `dot-product` (needs the `alloc` feature and a 64-bit host) is the same thing built for speed:
32//! an environment that keeps those CSRs decoded, eagerly decoded instructions and threaded
33//! dispatch
34//!
35//! For example, `cargo run --release --example dot-product --features alloc`.
36//!
37//! ## Supported ISA variants and extensions
38//!
39//! ISA variants:
40//! * RV32I (version 2.1)
41//! * RV32E (version 2.0)
42//! * RV64I (version 2.1)
43//! * RV64E (version 2.0)
44//!
45//! Extensions:
46//! * A (version 2.1)
47//! * M (version 2.0)
48//! * B (version 1.0.0)
49//! * Zaamo (version 1.0.0)
50//! * Zabha (version 1.0.0)
51//! * Zacas (version 1.0.0)
52//! * (experimental) Zalasr (version 1.0.0)
53//! * Zalrsc (version 1.0.0)
54//! * Zawrs (version 1.0.0)
55//! * Zba (version 1.0.0)
56//! * Zbb (version 1.0.0)
57//! * Zbc (version 1.0.0)
58//! * Zbkb (version 1.0.1)
59//! * Zbkc (version 1.0.1)
60//! * Zbkx (version 1.0.1)
61//! * Zbs (version 1.0.0)
62//! * Zca (version 1.0.0)
63//! * Zcb (version 1.0.0)
64//! * (experimental) Zcmp (version 1.0.0)
65//! * Zicond (version 1.0.0)
66//! * Zicsr (version 2.0)
67//! * Zifencei (version 2.0)
68//! * Zkn (version 1.0.1)
69//! * Zknd (version 1.0.1)
70//! * Zkne (version 1.0.1)
71//! * Zknh (version 1.0.1)
72//! * Zkr (version 1.0.1)
73//! * Zvbb (version 1.0.0)
74//! * Zvbc (version 1.0.0)
75//! * ZveXx (version 1.0.0), where `X` is anything allowed by the specification like Zve32x or
76//! Zve64x
77//! * Zvkb (version 1.0.0)
78//! * Zvl*b (version 1.0.0), where `*` is anything allowed by the specification like Zvl128b or
79//! Zvl512b
80//! * Ssstrict
81//!
82//! All extensions except experimental pass all relevant RISC-V Architectural Certification Tests
83//! (ACTs) using the ACT4 framework.
84//!
85//! Any permutation of compatible extensions is supported.
86//!
87//! Experimental extensions may not have ACT4 tests yet and are not guaranteed to work correctly.
88//!
89//! ## Design choices
90//!
91//! This crate was designed with a blockchain use case in mind, though it is in no way tied to any
92//! particular blockchain and is completely general purpose. As a result, the implementation is
93//! designed to be precise and non-ambiguous.
94//!
95//! A few key points:
96//! * anything "reserved" in the specification is considered to be illegal
97//! * anything "optional" in the specification is considered to be illegal
98//! * anything "implementation-defined" in the specification is selected to be the most natural and
99//! deterministic
100//! * type system is used to make the majority of invalid invariants impossible to represent in code
101//! and/or decode
102//!
103//! Examples:
104//! * `vma`/`vta` are always undisturbed in vector extensions
105//! * Zve64x extension instructions are purposefully restricted to what it is required to be capable
106//! of, although it would be cheaper to support the fuller feature set only required by V
107//! extension
108//! * vector instructions other than loads, stores and `vset{i}vl{i}` only accept a zero `vstart`
109//! and raise an illegal instruction exception otherwise, since they never trap partway through,
110//! so a non-zero `vstart` is a value this implementation never produces for them
111//!
112//! ### Instruction implementations are assembled, not compiled in place
113//!
114//! Instruction implementations are not compiled where they are written. `build.rs` calls
115//! `ab_riscv_macros::process_instruction_macros()`, which parses the sources marked with the
116//! `#[instruction]` and `#[instruction_execution]` attribute macros and writes a generated
117//! execution implementation per instruction set into `OUT_DIR`.
118//!
119//! Macros have documentation about how they work, but the important thing is that `match`
120//! expressions are parsed and re-assembled as needed instead of being compiled in place.
121//!
122//! Two things follow from this, and both constrain how instruction implementations must be written:
123//! * the same arm is expanded into more than one crate, so a `crate::`-relative path inside an arm
124//! resolves against whichever crate it landed in and is avoided. Shared code is reached through
125//! helper modules re-exported from [`prelude`] - like `rv64_zbb_helpers` and similar - so that an
126//! arm can name them unqualified wherever it ends up
127//! * because each arm is kept separately and names exactly the operands its instruction uses, the
128//! same arms can be emitted as something other than one large `match`. Emitting them as
129//! standalone per-instruction functions, dispatched by tail call, is what allows an interpreter
130//! to avoid decoding operands that the instruction about to run does not use, and to stop paying
131//! for extensions that are compiled in but never executed
132
133#![expect(incomplete_features, reason = "generic_const_*, explicit_tail_calls")]
134#![feature(
135 adt_const_params,
136 const_block_items,
137 const_closures,
138 const_cmp,
139 const_convert,
140 const_default,
141 const_destruct,
142 const_index,
143 const_iter,
144 const_ops,
145 const_option_ops,
146 const_result_trait_fn,
147 const_trait_impl,
148 const_try,
149 derive_const,
150 explicit_tail_calls,
151 fn_align,
152 gca_const_items,
153 gca_macroless_args,
154 gca_min_const_items,
155 generic_const_items,
156 impl_restriction,
157 inherent_associated_types,
158 integer_widen_truncate,
159 portable_simd,
160 signed_bigint_helpers,
161 try_trait_v2,
162 widening_mul
163)]
164#![cfg_attr(test, feature(try_blocks))]
165// Needed by the instruction set composed in tests of the eager instruction fetcher
166#![cfg_attr(
167 all(test, feature = "alloc", target_pointer_width = "64"),
168 feature(const_try_residual)
169)]
170#![cfg_attr(
171 any(
172 all(
173 target_arch = "riscv32",
174 any(
175 target_feature = "zbb",
176 target_feature = "zbc",
177 target_feature = "zbkb",
178 target_feature = "zbkx",
179 target_feature = "zknd",
180 target_feature = "zkne",
181 target_feature = "zknh"
182 ),
183 not(miri)
184 ),
185 all(
186 target_arch = "riscv64",
187 any(
188 target_feature = "zbb",
189 target_feature = "zbc",
190 target_feature = "zbkx",
191 target_feature = "zknd",
192 target_feature = "zkne",
193 target_feature = "zknh"
194 ),
195 not(miri)
196 )
197 ),
198 feature(riscv_ext_intrinsics)
199)]
200#![cfg_attr(
201 test,
202 expect(
203 clippy::rest_pattern_accessible_field,
204 reason = "Too verbose for tests"
205 )
206)]
207#![no_std]
208
209pub mod basic;
210mod const_utils;
211pub mod prelude;
212pub mod rv32;
213pub mod rv64;
214#[cfg(test)]
215mod tests;
216pub mod v;
217pub mod zawrs;
218pub mod zicond;
219pub mod zicsr;
220pub mod zifencei;
221pub mod zkr;
222pub mod zvbb;
223pub mod zvbc;
224
225#[cfg(feature = "alloc")]
226extern crate alloc;
227
228use ab_riscv_primitives::prelude::*;
229#[cfg(feature = "alloc")]
230use alloc::boxed::Box;
231use core::fmt;
232use core::hint::{cold_path, unreachable_unchecked};
233use core::marker::{Destruct, PhantomData};
234use core::ops::{ControlFlow, FromResidual, Sub};
235
236type InstructionReg<I> = <<I as Instruction>::Hart as HartConfig>::Reg;
237type RegisterType<I> = <InstructionReg<I> as Register>::Type;
238type Address<I> = RegisterType<I>;
239
240/// A GPR (General Purpose Register) file abstraction
241pub const trait RegisterFile<Reg>
242where
243 Reg: [const] Register,
244{
245 /// Read register value
246 fn read(&self, reg: Reg) -> Reg::Type;
247
248 /// Write register value
249 fn write(&mut self, reg: Reg, value: Reg::Type);
250}
251
252/// Errors for [`VirtualMemory`]
253#[derive(Debug, thiserror::Error)]
254pub enum VirtualMemoryError {
255 /// Out-of-bounds read
256 #[error("Out-of-bounds read at address {address}")]
257 OutOfBoundsRead {
258 /// Address of the out-of-bounds read
259 address: u64,
260 },
261 /// Out-of-bounds write
262 #[error("Out-of-bounds write at address {address}")]
263 OutOfBoundsWrite {
264 /// Address of the out-of-bounds write
265 address: u64,
266 },
267}
268
269/// Basic integer types that can be read and written to/from memory freely
270pub impl(self) trait BasicInt: Sized + Copy + 'static {}
271
272impl BasicInt for u8 {}
273impl BasicInt for u16 {}
274impl BasicInt for u32 {}
275impl BasicInt for u64 {}
276impl BasicInt for i8 {}
277impl BasicInt for i16 {}
278impl BasicInt for i32 {}
279impl BasicInt for i64 {}
280
281/// Virtual memory interface
282pub const trait VirtualMemory {
283 /// Read a value from memory at the specified address
284 fn read<T>(&self, address: u64) -> Result<T, VirtualMemoryError>
285 where
286 T: BasicInt;
287
288 /// Unchecked read a value from memory at the specified address.
289 ///
290 /// # Safety
291 /// The address and value must be in-bounds.
292 unsafe fn read_unchecked<T>(&self, address: u64) -> T
293 where
294 T: BasicInt;
295
296 /// Read a contiguous byte slice from memory
297 fn read_slice(&self, address: u64, len: u32) -> Result<&[u8], VirtualMemoryError>;
298
299 /// Read as many contiguous bytes as possible starting at `address`, up to `len` bytes total.
300 ///
301 /// Can return an empty slice in cases like when the address is out of bounds.
302 fn read_slice_up_to(&self, address: u64, len: u32) -> &[u8];
303
304 /// Write a value to memory at the specified address
305 fn write<T>(&mut self, address: u64, value: T) -> Result<(), VirtualMemoryError>
306 where
307 T: BasicInt;
308
309 /// Write a contiguous byte slice to memory
310 fn write_slice(&mut self, address: u64, data: &[u8]) -> Result<(), VirtualMemoryError>;
311}
312
313#[cfg(feature = "alloc")]
314impl<M> VirtualMemory for Box<M>
315where
316 M: VirtualMemory,
317{
318 #[inline(always)]
319 fn read<T>(&self, address: u64) -> Result<T, VirtualMemoryError>
320 where
321 T: BasicInt,
322 {
323 self.as_ref().read(address)
324 }
325
326 #[inline(always)]
327 unsafe fn read_unchecked<T>(&self, address: u64) -> T
328 where
329 T: BasicInt,
330 {
331 // SAFETY: Guaranteed by the caller
332 unsafe { self.as_ref().read_unchecked(address) }
333 }
334
335 #[inline(always)]
336 fn read_slice(&self, address: u64, len: u32) -> Result<&[u8], VirtualMemoryError> {
337 self.as_ref().read_slice(address, len)
338 }
339
340 #[inline(always)]
341 fn read_slice_up_to(&self, address: u64, len: u32) -> &[u8] {
342 self.as_ref().read_slice_up_to(address, len)
343 }
344
345 #[inline(always)]
346 fn write<T>(&mut self, address: u64, value: T) -> Result<(), VirtualMemoryError>
347 where
348 T: BasicInt,
349 {
350 self.as_mut().write(address, value)
351 }
352
353 #[inline(always)]
354 fn write_slice(&mut self, address: u64, data: &[u8]) -> Result<(), VirtualMemoryError> {
355 self.as_mut().write_slice(address, data)
356 }
357}
358
359/// Generic program counter
360pub const trait ProgramCounter<Address, Memory>
361where
362 Address: Copy,
363{
364 /// Get the current value of the program counter
365 fn get_pc(&self) -> Address;
366
367 /// Get the previous value of the program counter before executing an `instruction`.
368 ///
369 /// This is usually called from under instruction execution when the program counter is already
370 /// advanced during instruction fetching. As such, `pc - instruction_size` is expected to never
371 /// underflow.
372 #[inline(always)]
373 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic(const))]
374 fn old_pc(&self, instruction_size: u8) -> Address
375 where
376 Address: [const] From<u8> + [const] Sub<Output = Address>,
377 {
378 // TODO: Wrapping subtraction would be nice, but causes a lot of additional generic bounds
379 // that are bad for ergonomics
380 self.get_pc() - Address::from(instruction_size)
381 }
382
383 /// Apply [`ExecutionResult::Branch`], continuing `offset` bytes from the instruction being
384 /// executed.
385 ///
386 /// This is [`Self::try_set_pc_relative()`] followed, if it refused the target, by
387 /// [`Self::failed_branch()`], and exists for callers that have nothing better to do with a
388 /// refused target than ask what was wrong with it right there.
389 #[inline(always)]
390 fn set_pc_relative(
391 &mut self,
392 memory: &Memory,
393 instruction_size: u8,
394 offset: i32,
395 ) -> Result<ControlFlow<()>, ExecutionError<Address>>
396 where
397 Self: [const] ProgramCounter<Address, Memory>,
398 {
399 // SAFETY: A refused target is handed straight to `failed_branch()` below, before anything
400 // else can observe the program counter
401 if unsafe { self.try_set_pc_relative(instruction_size, offset) } {
402 return Ok(ControlFlow::Continue(()));
403 }
404
405 cold_path();
406
407 // SAFETY: `try_set_pc_relative()` has just refused the target
408 unsafe { self.failed_branch(memory) }
409 }
410
411 /// Move `offset` bytes from the instruction being executed for targets this can resolve.
412 ///
413 /// A simple implementation can resolve the offset against the program counter and validate it
414 /// the way [`Self::set_pc()`] does. Implementation that keeps the program counter as a position
415 /// in an already decoded instruction stream can move within that stream directly, which avoids
416 /// converting an address back into a position.
417 ///
418 /// Returns `true` when the program counter now points at the target, and `false` when the
419 /// target is not somewhere it may point at.
420 ///
421 /// Separate from [`Self::failed_branch()`] for the sake of threaded dispatch, where working out
422 /// what exactly is wrong with a target is code that no branch or jump ever runs, and inlining
423 /// it into the handler of every one of them puts it between the parts of the interpreter that
424 /// do run frequently. Split this way, a handler can hand a refused target to a cold
425 /// continuation with a tail call, which is the one call that costs it nothing, since nothing it
426 /// holds has to survive one.
427 ///
428 /// # Safety
429 /// When this returns `false`, the program counter is left holding the refused target, which is
430 /// not a position to fetch from - it is what [`Self::failed_branch()`] reads to say what was
431 /// wrong with it. That call must come next before anything else observes the program counter.
432 unsafe fn try_set_pc_relative(&mut self, instruction_size: u8, offset: i32) -> bool;
433
434 /// Say what is wrong with the target [`Self::try_set_pc_relative()`] refused.
435 ///
436 /// Implementations are expected to be `#[cold]` and `#[inline(never)]`: this is the half of
437 /// [`Self::set_pc_relative()`] that a program only reaches on its way out.
438 ///
439 /// # Safety
440 /// Must be called right after [`Self::try_set_pc_relative()`] returned `false`, with nothing in
441 /// between having observed the program counter.
442 unsafe fn failed_branch(
443 &mut self,
444 memory: &Memory,
445 ) -> Result<ControlFlow<()>, ExecutionError<Address>>;
446
447 /// Set the current value of the program counter
448 fn set_pc(
449 &mut self,
450 memory: &Memory,
451 pc: Address,
452 ) -> Result<ControlFlow<()>, ExecutionError<Address>>;
453}
454
455/// Address wrapper for [`ExecutionError`] with an alignment of 4 rather than its natural one.
456///
457/// This is needed for [`ExecutionResult`] that contains [`ExecutionError`] to fit within 16 bytes
458/// or two native registers on 64-bit platforms.
459#[derive(Copy, Clone, Eq, PartialEq)]
460#[repr(C, packed(4))]
461pub struct PackedAddress<Address>(Address);
462
463impl<Address> PackedAddress<Address>
464where
465 Address: Copy,
466{
467 /// Create a new instance
468 #[inline(always)]
469 pub const fn new(address: Address) -> Self {
470 Self(address)
471 }
472
473 /// Read the address back
474 #[inline(always)]
475 pub const fn get(self) -> Address {
476 self.0
477 }
478}
479
480const impl<Address> From<Address> for PackedAddress<Address>
481where
482 Address: Copy + [const] Destruct,
483{
484 #[inline(always)]
485 fn from(address: Address) -> Self {
486 Self(address)
487 }
488}
489
490impl<Address> fmt::Debug for PackedAddress<Address>
491where
492 Address: fmt::Debug + Copy,
493{
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 let address = self.0;
496 fmt::Debug::fmt(&address, f)
497 }
498}
499
500impl<Address> fmt::Display for PackedAddress<Address>
501where
502 Address: fmt::Display + Copy,
503{
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 let address = self.0;
506 fmt::Display::fmt(&address, f)
507 }
508}
509
510impl<Address> fmt::LowerHex for PackedAddress<Address>
511where
512 Address: fmt::LowerHex + Copy,
513{
514 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
515 let address = self.0;
516 fmt::LowerHex::fmt(&address, f)
517 }
518}
519
520/// Execution errors.
521///
522/// The variants of [`VirtualMemoryError`] and [`CsrError`] are inlined
523/// here rather than nested. Nesting cost an extra discriminant per level, which made this type 24
524/// bytes; flattened it is 16, which is what lets `Result<_, ExecutionError>` be returned in
525/// registers instead of through a hidden out-pointer. `From` implementations for all three are
526/// provided, so `?` on them keeps working unchanged.
527#[derive(Debug, thiserror::Error)]
528pub enum ExecutionError<Address>
529where
530 Address: Copy,
531{
532 /// Unaligned instruction
533 #[error("Unaligned instruction at address {address}")]
534 UnalignedInstruction {
535 /// Address of the unaligned instruction fetch
536 address: PackedAddress<Address>,
537 },
538 /// Out-of-bounds read
539 #[error("Out-of-bounds read at address {address}")]
540 OutOfBoundsRead {
541 /// Address of the out-of-bounds read
542 address: PackedAddress<u64>,
543 },
544 /// Out-of-bounds write
545 #[error("Out-of-bounds write at address {address}")]
546 OutOfBoundsWrite {
547 /// Address of the out-of-bounds write
548 address: PackedAddress<u64>,
549 },
550 /// Misaligned read from an instruction that requires natural alignment (e.g. `lr`), unlike
551 /// ordinary loads
552 #[error("Misaligned read at address {address}")]
553 MisalignedRead {
554 /// Address of the misaligned read
555 address: PackedAddress<u64>,
556 },
557 /// Misaligned write from an instruction that requires natural alignment (e.g. `sc`), unlike
558 /// ordinary stores
559 #[error("Misaligned write at address {address}")]
560 MisalignedWrite {
561 /// Address of the misaligned write
562 address: PackedAddress<u64>,
563 },
564 /// Misaligned atomic access (e.g. AMO) whose accessed bytes are not all within the same
565 /// misaligned atomicity granule, unlike an ordinary misaligned read or write
566 #[error("Misaligned atomic access at address {address}")]
567 MisalignedAtomic {
568 /// Address of the misaligned atomic access
569 address: PackedAddress<u64>,
570 },
571 /// Unsupported `ecall` instruction
572 #[error("Unsupported `ecall` instruction at address {address:#x}")]
573 EcallUnsupported {
574 /// Address of the unsupported instruction
575 address: PackedAddress<Address>,
576 },
577 /// Unimplemented/illegal instruction
578 #[error("Unimplemented/illegal instruction at address {address:#x}")]
579 IllegalInstruction {
580 /// Address of the `unimp` instruction
581 address: PackedAddress<Address>,
582 },
583 /// Read only CSR
584 #[error("Read only CSR {csr_index:#x}")]
585 CsrReadOnly {
586 /// Index of CSR where write was attempted
587 csr_index: u16,
588 },
589 /// Illegal read access
590 #[error("Illegal read access to CSR {csr_index:#x}")]
591 CsrIllegalRead {
592 /// Index of the accessed CSR
593 csr_index: u16,
594 },
595 /// Illegal write access
596 #[error("Illegal write access to CSR {csr_index:#x}")]
597 CsrIllegalWrite {
598 /// Index of the accessed CSR
599 csr_index: u16,
600 },
601 /// Unknown CSR
602 #[error("Unknown CSR {csr_index:#x}")]
603 CsrUnknown {
604 /// Index of the accessed CSR
605 csr_index: u16,
606 },
607 /// Insufficient privilege level
608 #[error(
609 "Insufficient privilege level for CSR {csr_index:#x}: required {required:?}, \
610 current {current:?}"
611 )]
612 CsrInsufficientPrivilege {
613 /// Index of the accessed CSR
614 csr_index: u16,
615 /// Required privilege level
616 required: PrivilegeLevel,
617 /// Current privilege level
618 current: PrivilegeLevel,
619 },
620 /// Threaded execution is not supported on this platform.
621 ///
622 /// See [`OpaqueThreadedExecutionResult::platform_supported()`] for what makes a platform
623 /// unsupported and why the answer is a run-time one.
624 #[error("Threaded execution is not supported on this platform")]
625 UnsupportedPlatform,
626 /// Custom error
627 #[error("Custom error: {0:?}")]
628 Custom([u8; 8]),
629}
630
631/// Where execution continues after an instruction, or why it could not.
632///
633/// Instructions describe control flow rather than performing it: they say where execution goes next
634/// instead of moving the program counter themselves. This keeps instruction bodies independent of
635/// how the program counter is represented, which is what allows the same bodies to drive both an
636/// interpreter loop that owns a program counter and one that carries it in a register.
637#[derive(Debug)]
638pub enum ExecutionResult<Reg>
639where
640 Reg: Register,
641{
642 /// Write the register and continue with the instruction that follows this one
643 Continue {
644 /// Register to write
645 rd: Reg,
646 /// Value to write into it
647 value: Reg::Type,
648 },
649 /// Continue with the instruction that follows this one without writing to `rd` register
650 ContinueNoWrite,
651 /// Continue `offset` bytes away from the address of *this* instruction.
652 ///
653 /// Keeping it relative rather than resolving it against the program counter here means a
654 /// pre-decoded interpreter can reach the target by moving within the decoded stream instead of
655 /// converting an address back into a position.
656 Branch {
657 /// Signed byte offset from this instruction
658 offset: i32,
659 },
660 /// Continue at an absolute guest address, as `jalr`-style jumps produce
661 Jump {
662 /// Address to continue at
663 target: Reg::Type,
664 },
665 /// Stop execution
666 Break,
667 /// Execution failed
668 Err(ExecutionError<Reg::Type>),
669}
670
671const {
672 // Ensure result type retains its size
673 assert!(size_of::<ExecutionResult<Reg<u64>>>() <= 16);
674 assert!(size_of::<ExecutionResult<Reg<u32>>>() <= 16);
675}
676
677const impl<Reg> From<ExecutionError<Reg::Type>> for ExecutionResult<Reg>
678where
679 Reg: Register,
680{
681 #[inline(always)]
682 fn from(error: ExecutionError<Reg::Type>) -> Self {
683 cold_path();
684 Self::Err(error)
685 }
686}
687
688const impl<Reg, E> FromResidual<Result<!, E>> for ExecutionResult<Reg>
689where
690 Reg: Register,
691 E: [const] Into<ExecutionError<Reg::Type>> + [const] Destruct,
692{
693 #[inline(always)]
694 fn from_residual(residual: Result<!, E>) -> Self {
695 match residual {
696 Ok(never) => match never {},
697 Err(error) => {
698 cold_path();
699 Self::Err(error.into())
700 }
701 }
702 }
703}
704
705const impl<Address> From<VirtualMemoryError> for ExecutionError<Address>
706where
707 Address: Copy,
708{
709 #[inline(always)]
710 fn from(value: VirtualMemoryError) -> Self {
711 match value {
712 VirtualMemoryError::OutOfBoundsRead { address } => Self::OutOfBoundsRead {
713 address: PackedAddress::new(address),
714 },
715 VirtualMemoryError::OutOfBoundsWrite { address } => Self::OutOfBoundsWrite {
716 address: PackedAddress::new(address),
717 },
718 }
719 }
720}
721
722const impl<Address> From<CsrError> for ExecutionError<Address>
723where
724 Address: Copy,
725{
726 #[inline(always)]
727 fn from(value: CsrError) -> Self {
728 match value {
729 CsrError::ReadOnly { csr_index } => Self::CsrReadOnly { csr_index },
730 CsrError::IllegalRead { csr_index } => Self::CsrIllegalRead { csr_index },
731 CsrError::IllegalWrite { csr_index } => Self::CsrIllegalWrite { csr_index },
732 CsrError::Unknown { csr_index } => Self::CsrUnknown { csr_index },
733 CsrError::InsufficientPrivilege {
734 csr_index,
735 required,
736 current,
737 } => Self::CsrInsufficientPrivilege {
738 csr_index,
739 required,
740 current,
741 },
742 CsrError::Custom(error) => Self::Custom(error),
743 }
744 }
745}
746
747/// Result of [`InstructionFetcher::fetch_instruction()`] and
748/// [`InstructionFetcher::peek_instruction()`] calls.
749///
750/// `Peeked` is the instruction itself when fetching, and whatever
751/// [`InstructionFetcher::Peeked`] is when peeking.
752#[derive(Debug)]
753pub enum FetchInstructionResult<I, Peeked = I>
754where
755 I: Instruction,
756{
757 /// Instruction to execute
758 Instruction(Peeked),
759 /// Nothing to execute here, carry on from wherever the program counter now points
760 Continue,
761 /// Stop execution
762 Break,
763 /// Fetching failed
764 Err(ExecutionError<Address<I>>),
765}
766
767/// Generic instruction fetcher.
768///
769/// # Performance considerations
770/// In threaded dispatch, the instruction fetcher is moved through the handler chain by value, so it
771/// should have 16 bytes size (next instruction pointer + pointer to extra state) and no drop glue.
772/// A fetcher that owns something is dropped by whichever handler ends execution. Every handler that
773/// can fail is a candidate for that, which forces a stack frame, callee-saved register spills, and
774/// a reload into the hot path of every load, store, branch and jump. A fetcher that only borrows
775/// what it walks (`Copy`, or at least `!needs_drop`) keeps them all frameless and fast.
776///
777/// # Fetching
778/// The methods that read an instruction are `unsafe`. Implementations may assume that the program
779/// counter is at an instruction, so they don't have to check it on every fetch. Fetching is
780/// allowed when the fetcher was just created by its constructor, or when the last call that moved
781/// the program counter was one of these:
782/// * [`ProgramCounter::set_pc()`], [`ProgramCounter::set_pc_relative()`] or
783/// [`ProgramCounter::failed_branch()`] returning `Ok(ControlFlow::Continue(()))`
784/// * [`ProgramCounter::try_set_pc_relative()`] returning `true`
785/// * [`Self::advance()`] or [`Self::fetch_instruction()`] moving past an instruction whose
786/// execution continued with the next one
787/// * [`Self::peek_instruction()`] or [`Self::fetch_instruction()`] returning
788/// [`FetchInstructionResult::Continue`]
789///
790/// A copy or a clone of a fetcher doesn't count as just created. It starts in the state the
791/// original was in, and the rules above apply to it from there.
792///
793/// Anything else may leave the program counter where there is nothing to fetch, for example a
794/// branch that [`ProgramCounter::set_pc_relative()`] refused. `set_pc(get_pc())` is the cheap way
795/// back: at an instruction it does nothing, and otherwise it returns what stopped execution there.
796///
797/// # Safety
798/// Execution relies on the following for soundness, and every implementation promises it:
799/// * Fetching is sound whenever it is allowed, see above.
800/// * Nothing done through a shared reference to the fetcher moves the program counter. That
801/// includes [`ProgramCounter::get_pc()`] and [`Self::peeked_instruction()`]. Instructions get the
802/// fetcher by shared reference while they execute, and the next instruction is fetched after that
803/// without checking the program counter again.
804/// * [`Self::peeked_instruction()`] returns the instruction that [`Self::peek_instruction()`] read
805/// when it returned `peeked`. It keeps returning that same instruction until the program counter
806/// moves, even after the fetcher or `peeked` is moved to another place in memory. Threaded
807/// dispatch picks the handler by the variant of this instruction. The handler then reads the
808/// instruction again and takes that variant for granted.
809pub const unsafe trait InstructionFetcher<I, Memory>
810where
811 Self: ProgramCounter<Address<I>, Memory>,
812 I: Instruction,
813{
814 /// What [`Self::peek_instruction()`] returns an instruction as, which is whatever
815 /// [`Self::peeked_instruction()`] needs besides the fetcher to get back to the instruction.
816 ///
817 /// A fetcher that decodes on the fly has nothing but the instruction itself to hand over,
818 /// while one that walks a decoded stream still has the instruction where it was decoded, so it
819 /// hands over nothing at all. The difference matters to threaded dispatch, which passes this
820 /// to the handler by value: an instruction takes a register, and each operand then costs a
821 /// shift and a mask to extract from it, while `()` takes no register at all, and the handler
822 /// loads each operand it uses from the decoded stream at a constant offset, one instruction
823 /// each.
824 type Peeked;
825
826 /// Read the instruction at the current position, leaving the program counter on it.
827 ///
828 /// [`Self::advance()`] is what moves past it, and the two are separate because of what deriving
829 /// the size from the instruction is costly for threaded dispatch: it makes the address of the
830 /// *next* instruction depend on decoding the current one. In threaded dispatch caller already
831 /// knows which variant it is holding and advances by a constant instead, allowing the next load
832 /// to be issued immediately.
833 ///
834 /// # Safety
835 /// Fetching must be allowed, see [`InstructionFetcher`].
836 unsafe fn peek_instruction(
837 &mut self,
838 memory: &Memory,
839 ) -> FetchInstructionResult<I, Self::Peeked>;
840
841 /// The instruction that [`Self::peek_instruction()`] returned `peeked` for.
842 ///
843 /// Only meaningful until the program counter moves, since `peeked` may be nothing more than a
844 /// promise that the instruction is still at the current position.
845 ///
846 /// A reference rather than a copy on purpose, even though callers destructure it right away:
847 /// destructuring through a reference into a decoded stream loads each field on its own, while
848 /// a copy is loaded whole and its fields are then extracted from a register with a shift and a
849 /// mask each.
850 ///
851 /// # Safety
852 /// `peeked` must come from [`Self::peek_instruction()`] on this fetcher, and the program
853 /// counter must not have moved since.
854 unsafe fn peeked_instruction<'a>(&'a self, peeked: &'a Self::Peeked) -> &'a I;
855
856 /// Move the program counter past an instruction of `instruction_size` bytes that
857 /// [`Self::peek_instruction()`] has just returned.
858 ///
859 /// # Safety
860 /// Must be called exactly once after a successful [`Self::peek_instruction()`], with what
861 /// [`Instruction::size()`] returns for the instruction that call returned. Implementations are
862 /// free to rely on that and skip checks accordingly: one over a pre-decoded stream that is
863 /// followed by an instruction that never continues, for instance, treats the resulting
864 /// position as valid without bounds-checking it.
865 ///
866 /// [`Instruction`] is a safe trait, so nothing stops `size()` from returning a different value
867 /// for the same instruction later. An implementation that needs the size to match what it
868 /// checked earlier has to require that itself, the way `BasicEagerInstructions::decode()` does.
869 unsafe fn advance(&mut self, instruction_size: u8);
870
871 /// Fetch a single instruction at a specified address and advance the program counter on
872 /// successful fetch.
873 ///
874 /// This is effectively [`Self::peek_instruction()`] followed by [`Self::peeked_instruction()`]
875 /// and [`Self::advance()`]. It exists for callers that do not know what they are about to
876 /// fetch, which is every caller that dispatches through a `match` rather than through
877 /// per-variant handlers.
878 ///
879 /// # Safety
880 /// Fetching must be allowed, see [`InstructionFetcher`].
881 unsafe fn fetch_instruction(&mut self, memory: &Memory) -> FetchInstructionResult<I>;
882}
883
884/// CSR error
885#[derive(Debug, thiserror::Error)]
886pub enum CsrError {
887 /// Read only CSR
888 #[error("Read only CSR {csr_index:#x}")]
889 ReadOnly {
890 /// Index of CSR where write was attempted
891 csr_index: u16,
892 },
893 /// Illegal read access
894 #[error("Illegal read access to CSR {csr_index:#x}")]
895 IllegalRead {
896 /// Index of the accessed CSR
897 csr_index: u16,
898 },
899 /// Illegal write access
900 #[error("Illegal write access to CSR {csr_index:#x}")]
901 IllegalWrite {
902 /// Index of the accessed CSR
903 csr_index: u16,
904 },
905 /// Unknown CSR
906 #[error("Unknown CSR {csr_index:#x}")]
907 Unknown {
908 /// Index of the accessed CSR
909 csr_index: u16,
910 },
911 /// Insufficient privilege level
912 #[error(
913 "Insufficient privilege level for CSR {csr_index:#x}: required {required:?}, \
914 current {current:?}"
915 )]
916 InsufficientPrivilege {
917 /// Index of the accessed CSR
918 csr_index: u16,
919 /// Required privilege level
920 required: PrivilegeLevel,
921 /// Current privilege level
922 current: PrivilegeLevel,
923 },
924 /// Custom error
925 #[error("Custom error: {0:?}")]
926 Custom([u8; 8]),
927}
928
929/// CSRs (Control and Status Registers)
930pub const trait Csrs<Reg>
931where
932 Reg: [const] Register,
933{
934 /// Current privilege level
935 #[inline(always)]
936 fn privilege_level(&self) -> PrivilegeLevel {
937 PrivilegeLevel::Machine
938 }
939
940 /// Reads register value
941 fn read_csr(&self, csr_index: u16) -> Result<Reg::Type, CsrError>;
942
943 /// Writes register value
944 fn write_csr(&mut self, csr_index: u16, value: Reg::Type) -> Result<(), CsrError>;
945}
946
947// Convenience for threaded execution
948const impl<Reg, T> Csrs<Reg> for &mut T
949where
950 Reg: [const] Register,
951 T: [const] Csrs<Reg>,
952{
953 #[inline(always)]
954 fn privilege_level(&self) -> PrivilegeLevel {
955 T::privilege_level(self)
956 }
957
958 #[inline(always)]
959 fn read_csr(&self, csr_index: u16) -> Result<Reg::Type, CsrError> {
960 T::read_csr(self, csr_index)
961 }
962
963 #[inline(always)]
964 fn write_csr(&mut self, csr_index: u16, value: Reg::Type) -> Result<(), CsrError> {
965 T::write_csr(self, csr_index, value)
966 }
967}
968
969/// Custom handler for system instructions `ecall` and `ebreak`
970pub const trait SystemInstructionHandler<Reg, Regs, Memory, PC>
971where
972 Reg: Register,
973{
974 // TODO: Figure out the correct API for this method
975 /// Handle a `fence` instruction
976 #[inline(always)]
977 fn handle_fence(&mut self, pred: u8, succ: u8) {
978 let _: u8 = pred;
979 let _: u8 = succ;
980 // NOP by default
981 }
982
983 // TODO: Figure out the correct API for this method
984 /// Handle a `fence.tso` instruction
985 #[inline(always)]
986 fn handle_fence_tso(&mut self) {
987 // NOP by default
988 }
989
990 /// Handle an `ecall` instruction
991 fn handle_ecall(
992 &mut self,
993 regs: &mut Regs,
994 memory: &mut Memory,
995 program_counter: &PC,
996 ) -> ExecutionResult<Reg>;
997
998 /// Handle an `ebreak` (or compressed `c.ebreak`) instruction
999 #[inline(always)]
1000 fn handle_ebreak(
1001 &mut self,
1002 regs: &mut Regs,
1003 memory: &mut Memory,
1004 program_counter: &PC,
1005 instruction_size: u8,
1006 ) -> ExecutionResult<Reg> {
1007 // These are for cleaner trait API without leading `_` on arguments
1008 let _: &Regs = regs;
1009 let _: &mut Memory = memory;
1010 let _: &PC = program_counter;
1011 let _: u8 = instruction_size;
1012 // NOP by default
1013 ExecutionResult::ContinueNoWrite
1014 }
1015}
1016
1017// Convenience for threaded execution
1018const impl<Reg, Regs, Memory, PC, T> SystemInstructionHandler<Reg, Regs, Memory, PC> for &mut T
1019where
1020 Reg: [const] Register,
1021 T: [const] SystemInstructionHandler<Reg, Regs, Memory, PC>,
1022{
1023 #[inline(always)]
1024 fn handle_fence(&mut self, pred: u8, succ: u8) {
1025 T::handle_fence(self, pred, succ);
1026 }
1027
1028 #[inline(always)]
1029 fn handle_fence_tso(&mut self) {
1030 T::handle_fence_tso(self);
1031 }
1032
1033 #[inline(always)]
1034 fn handle_ecall(
1035 &mut self,
1036 regs: &mut Regs,
1037 memory: &mut Memory,
1038 program_counter: &PC,
1039 ) -> ExecutionResult<Reg> {
1040 T::handle_ecall(self, regs, memory, program_counter)
1041 }
1042
1043 #[inline(always)]
1044 fn handle_ebreak(
1045 &mut self,
1046 regs: &mut Regs,
1047 memory: &mut Memory,
1048 program_counter: &PC,
1049 instruction_size: u8,
1050 ) -> ExecutionResult<Reg> {
1051 T::handle_ebreak(self, regs, memory, program_counter, instruction_size)
1052 }
1053}
1054
1055/// `rs1`/`rs2` instruction operands
1056#[derive(Debug, Default, Copy, Clone)]
1057pub struct Rs1Rs2Operands<Reg> {
1058 /// `rs1` operand.
1059 ///
1060 /// Zero register if `rs1` was missing in the original instruction definition.
1061 pub rs1: Reg,
1062 /// `rs2` operand.
1063 ///
1064 /// Zero register if `rs2` was missing in the original instruction definition.
1065 pub rs2: Reg,
1066}
1067
1068/// `rs1`/`rs2` instruction operands
1069#[derive(Debug, Default, Copy, Clone)]
1070pub struct Rs1Rs2OperandValues<RegType> {
1071 /// `rs1` operand value.
1072 ///
1073 /// Zero if `rs1` was missing in the original instruction definition.
1074 pub rs1_value: RegType,
1075 /// `rs2` operand value.
1076 ///
1077 /// Zero if `rs2` was missing in the original instruction definition.
1078 pub rs2_value: RegType,
1079}
1080
1081/// `rs1`/`rs2` instruction operands
1082pub const trait ExecutableInstructionOperands
1083where
1084 Self: Instruction,
1085{
1086 /// `rs1`/`rs2` instruction operands.
1087 ///
1088 /// Returns zero register for `rs1`/`rs2` that were missing in the original instruction
1089 /// definition.
1090 ///
1091 /// Takes `&self` so that an instruction read through a reference into memory has the two
1092 /// registers loaded from there, a byte each, rather than copied out whole and extracted with
1093 /// a shift and a mask each, see [`InstructionFetcher::peeked_instruction()`].
1094 fn get_rs1_rs2_operands(&self) -> Rs1Rs2Operands<<Self::Hart as HartConfig>::Reg>;
1095}
1096
1097pub const trait ExecutableInstructionCsr<Env>
1098where
1099 Self: Instruction,
1100{
1101 /// Prepare CSR read.
1102 ///
1103 /// This method is called on each extension one by one with the `raw_value` (contents of the
1104 /// corresponding CSR register) and initially zero-initialized `output_value`. In return value
1105 /// every extension can accept (`Ok(true)`), ignore (`Ok(false)`) or reject (`Err(CsrError)`)
1106 /// read request. For accepted reads the extension must update `output_value` accordingly, which
1107 /// will be the value used by the `Zicsr` extension handler.
1108 ///
1109 /// Some extensions will just copy `raw_value` to output value, others will copy only some bits
1110 /// or zero some bits of the `raw_value`, as required by the specification.
1111 ///
1112 /// `will_write` indicates whether the CSR instruction performing this read will also perform a
1113 /// write immediately afterward (as part of the same instruction). It is always `true` for
1114 /// `csrrw{,i}`, and `true` for `csrrs{,i}`/`csrrc{,i}` unless their `rs1`/`zimm` operand is
1115 /// zero (in which case they are a pure read with no write). Some CSRs (e.g. `Zkr`'s `seed`)
1116 /// are only legal to access through a genuine read-write instruction and must reject the read
1117 /// when `will_write` is `false`.
1118 ///
1119 /// If no extension returns `Ok(true)`, the read operation is implicitly rejected as illegal
1120 /// access.
1121 #[inline(always)]
1122 fn prepare_csr_read(
1123 env: &Env,
1124 csr_index: u16,
1125 will_write: bool,
1126 raw_value: RegisterType<Self>,
1127 output_value: &mut RegisterType<Self>,
1128 ) -> Result<bool, CsrError> {
1129 // These are for cleaner trait API without leading `_` on arguments
1130 let _: &Env = env;
1131 let _: u16 = csr_index;
1132 let _: bool = will_write;
1133 let _: RegisterType<Self> = raw_value;
1134 let _: &mut RegisterType<Self> = output_value;
1135 // The default implementation is to not allow anything
1136 Ok(false)
1137 }
1138
1139 /// Prepare CSR write.
1140 ///
1141 /// This method is called on each extension one by one with `write_value` being prepared by the
1142 /// `Zicsr` extension handler. In return value every extension can accept (`Ok(true)`), ignore
1143 /// (`Ok(false)`) or reject (`Err(CsrError)`) write request. For accepted writes the extension
1144 /// must update `output_value` accordingly, which will be written to the corresponding CSR
1145 /// register.
1146 ///
1147 /// Some extensions will just copy `write_value` to output value, others will copy some bits or
1148 /// zero some bits of the `write_value`, as required by the specification.
1149 ///
1150 /// If no extension returns `Ok(true)`, the write operation is implicitly rejected as illegal
1151 /// access.
1152 #[inline(always)]
1153 fn prepare_csr_write(
1154 env: &mut Env,
1155 csr_index: u16,
1156 write_value: RegisterType<Self>,
1157 output_value: &mut RegisterType<Self>,
1158 ) -> Result<bool, CsrError> {
1159 // These are for cleaner trait API without leading `_` on arguments
1160 let _: &mut Env = env;
1161 let _: u16 = csr_index;
1162 let _: RegisterType<Self> = write_value;
1163 let _: &mut RegisterType<Self> = output_value;
1164 // The default implementation is to not allow anything
1165 Ok(false)
1166 }
1167}
1168
1169/// Trait for executable instructions
1170pub const trait ExecutableInstruction<Regs, Env, Memory, PC>
1171where
1172 Self: ExecutableInstructionOperands + ExecutableInstructionCsr<Env>,
1173{
1174 /// Execute instruction.
1175 ///
1176 /// Instructions might place additional constraints on `Env` to require additional registers,
1177 /// handlers (like [`SystemInstructionHandler`]) or other resources. If no such constraint is
1178 /// used, `()` can be used as a placeholder.
1179 ///
1180 /// On success `ExecutionResult::Continue { rd: rd, value: rd_value }` is returned, which will
1181 /// be written into the register file. In most cases this is the only register that needs to
1182 /// be written. If no value needs to be written, `ExecutionResult::ContinueNoWrite` should be
1183 /// returned, which skips the register file write entirely.
1184 ///
1185 /// `program_counter` is read-only. Instructions say where execution goes next with
1186 /// [`ExecutionResult::Branch`] or [`ExecutionResult::Jump`].
1187 fn execute(
1188 self,
1189 rs1rs2_values: Rs1Rs2OperandValues<<<Self::Hart as HartConfig>::Reg as Register>::Type>,
1190 regs: &mut Regs,
1191 env: &mut Env,
1192 memory: &mut Memory,
1193 program_counter: &PC,
1194 ) -> ExecutionResult<<Self::Hart as HartConfig>::Reg>;
1195}
1196
1197/// Outcome of [`ThreadedExecutableInstruction::execute_threaded()`].
1198///
1199/// Unlike [`ExecutionResult`], this is produced exactly once, by the handler that stops the chain
1200/// and is not on the per-instruction path.
1201///
1202/// For performance reasons everything inside has to fit into what the platform returns in
1203/// registers, in the shape of [`OpaqueThreadedExecutionResult`]. A caller that needs its fetcher
1204/// after execution keeps its own copy and sets the program counter to the correct value after
1205/// execution manually.
1206#[derive(Debug)]
1207pub struct ThreadedExecutionResult<I>
1208where
1209 I: Instruction,
1210{
1211 /// Program counter as of the moment execution stopped
1212 pub program_counter: Address<I>,
1213 /// Why execution stopped
1214 pub outcome: Result<(), ExecutionError<Address<I>>>,
1215}
1216
1217impl<I> ThreadedExecutionResult<I>
1218where
1219 I: Instruction,
1220{
1221 /// Execution stopped gracefully
1222 #[inline(always)]
1223 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1224 pub const fn stopped(program_counter: Address<I>) -> Self {
1225 Self {
1226 program_counter,
1227 outcome: Ok(()),
1228 }
1229 }
1230
1231 /// Execution failed
1232 #[inline(always)]
1233 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1234 pub const fn failed(program_counter: Address<I>, error: ExecutionError<Address<I>>) -> Self {
1235 cold_path();
1236 Self {
1237 program_counter,
1238 outcome: Err(error),
1239 }
1240 }
1241}
1242
1243cfg_select! {
1244 all(target_arch = "x86_64", any(not(miri), target_feature = "avx")) => {
1245 /// x86-64 System V only returns an aggregate larger than two eightbytes in registers when
1246 /// it is a single vector, hence a 256-bit one (a pair of 128-bit vectors classifies as
1247 /// memory). Moving one of those needs AVX, which is what makes this the only shape here
1248 /// with a run-time platform requirement.
1249 type OpaqueLanes = core::arch::x86_64::__m256i;
1250 }
1251 _ => {
1252 type OpaqueLanes = [u64; 3];
1253 }
1254}
1255
1256/// [`ThreadedExecutionResult`] in the shape tail-called handlers return it in.
1257///
1258/// Threaded handler internally returns this rather than [`ThreadedExecutionResult`] so that the
1259/// outcome travels in registers instead of through a hidden out-pointer where possible for
1260/// performance reasons (primarily on x86-64 due to a limited number of usable GPRs in the ABI).
1261///
1262/// On x86-64 the lanes are a 256-bit vector, so returning one of these in a register, which is what
1263/// handlers do, requires AVX - see [`Self::platform_supported()`].
1264#[derive(Debug, Copy, Clone)]
1265#[repr(transparent)]
1266pub struct OpaqueThreadedExecutionResult<I> {
1267 lanes: OpaqueLanes,
1268 phantom: PhantomData<I>,
1269}
1270
1271impl<I> OpaqueThreadedExecutionResult<I>
1272where
1273 I: Instruction,
1274{
1275 const TAG_STOPPED: u64 = 0;
1276 const TAG_UNALIGNED_INSTRUCTION: u64 = 1;
1277 const TAG_OUT_OF_BOUNDS_READ: u64 = 2;
1278 const TAG_OUT_OF_BOUNDS_WRITE: u64 = 3;
1279 const TAG_MISALIGNED_READ: u64 = 4;
1280 const TAG_MISALIGNED_WRITE: u64 = 5;
1281 const TAG_MISALIGNED_ATOMIC: u64 = 6;
1282 const TAG_ECALL_UNSUPPORTED: u64 = 7;
1283 const TAG_ILLEGAL_INSTRUCTION: u64 = 8;
1284 const TAG_CSR_READ_ONLY: u64 = 9;
1285 const TAG_CSR_ILLEGAL_READ: u64 = 10;
1286 const TAG_CSR_ILLEGAL_WRITE: u64 = 11;
1287 const TAG_CSR_UNKNOWN: u64 = 12;
1288 const TAG_CSR_INSUFFICIENT_PRIVILEGE: u64 = 13;
1289 const TAG_UNSUPPORTED_PLATFORM: u64 = 14;
1290 const TAG_CUSTOM: u64 = 15;
1291
1292 /// Whether this platform can carry an outcome the way [`Self::new()`] does.
1293 ///
1294 /// It cannot on an x86-64 CPU without AVX, where the lanes are a 256-bit vector: Rust targets
1295 /// x86-64-v1 by default, so a runtime check is necessary.
1296 ///
1297 /// This is called once within [`ThreadedExecutableInstruction::execute_threaded()`].
1298 #[inline(always)]
1299 #[must_use = "Check if platform is supported"]
1300 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1301 pub fn platform_supported() -> bool {
1302 cfg_select! {
1303 all(target_arch = "x86_64", not(target_feature = "avx")) => {
1304 cpufeatures::new!(cpuid_avx, "avx");
1305
1306 cpuid_avx::get()
1307 }
1308 _ => true,
1309 }
1310 }
1311
1312 /// Serialize an outcome into the shape handlers return
1313 #[inline(always)]
1314 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1315 pub fn new(result: ThreadedExecutionResult<I>) -> Self {
1316 let program_counter = result.program_counter.as_u64();
1317
1318 let (tag, payload) = match result.outcome {
1319 Ok(()) => (Self::TAG_STOPPED, 0),
1320 Err(error) => match error {
1321 ExecutionError::UnalignedInstruction { address } => {
1322 (Self::TAG_UNALIGNED_INSTRUCTION, address.get().as_u64())
1323 }
1324 ExecutionError::OutOfBoundsRead { address } => {
1325 (Self::TAG_OUT_OF_BOUNDS_READ, address.get())
1326 }
1327 ExecutionError::OutOfBoundsWrite { address } => {
1328 (Self::TAG_OUT_OF_BOUNDS_WRITE, address.get())
1329 }
1330 ExecutionError::MisalignedRead { address } => {
1331 (Self::TAG_MISALIGNED_READ, address.get())
1332 }
1333 ExecutionError::MisalignedWrite { address } => {
1334 (Self::TAG_MISALIGNED_WRITE, address.get())
1335 }
1336 ExecutionError::MisalignedAtomic { address } => {
1337 (Self::TAG_MISALIGNED_ATOMIC, address.get())
1338 }
1339 ExecutionError::EcallUnsupported { address } => {
1340 (Self::TAG_ECALL_UNSUPPORTED, address.get().as_u64())
1341 }
1342 ExecutionError::IllegalInstruction { address } => {
1343 (Self::TAG_ILLEGAL_INSTRUCTION, address.get().as_u64())
1344 }
1345 ExecutionError::CsrReadOnly { csr_index } => {
1346 (Self::TAG_CSR_READ_ONLY, u64::from(csr_index))
1347 }
1348 ExecutionError::CsrIllegalRead { csr_index } => {
1349 (Self::TAG_CSR_ILLEGAL_READ, u64::from(csr_index))
1350 }
1351 ExecutionError::CsrIllegalWrite { csr_index } => {
1352 (Self::TAG_CSR_ILLEGAL_WRITE, u64::from(csr_index))
1353 }
1354 ExecutionError::CsrUnknown { csr_index } => {
1355 (Self::TAG_CSR_UNKNOWN, u64::from(csr_index))
1356 }
1357 ExecutionError::CsrInsufficientPrivilege {
1358 csr_index,
1359 required,
1360 current,
1361 } => (
1362 Self::TAG_CSR_INSUFFICIENT_PRIVILEGE,
1363 u64::from(csr_index)
1364 | (u64::from(required.to_bits()) << 16)
1365 | (u64::from(current.to_bits()) << 24),
1366 ),
1367 ExecutionError::Custom(error) => (Self::TAG_CUSTOM, u64::from_le_bytes(error)),
1368 ExecutionError::UnsupportedPlatform => (Self::TAG_UNSUPPORTED_PLATFORM, 0),
1369 },
1370 };
1371
1372 Self {
1373 lanes: cfg_select! {
1374 all(target_arch = "x86_64", any(not(miri), target_feature = "avx")) => {
1375 core::simd::u64x4::from_array([program_counter, tag, payload, 0]).into()
1376 }
1377 _ => [program_counter, tag, payload],
1378 },
1379 phantom: PhantomData,
1380 }
1381 }
1382
1383 /// Deserialize what [`Self::new()`] produced.
1384 ///
1385 /// The lanes only ever come from there, in this very crate, which is what makes the
1386 /// unknown-tag arm unreachable.
1387 #[inline(always)]
1388 #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
1389 pub fn into_result(self) -> ThreadedExecutionResult<I> {
1390 let [program_counter, tag, payload] = cfg_select! {
1391 all(target_arch = "x86_64", any(not(miri), target_feature = "avx")) => {
1392 // TODO: `match` is used because rustfmt removes nested block braces, which
1393 // breaks compilation: https://github.com/rust-lang/rustfmt/issues/7045
1394 match core::simd::u64x4::from(self.lanes).to_array() {
1395 [program_counter, tag, payload, _] => [program_counter, tag, payload],
1396 }
1397 }
1398 _ => self.lanes,
1399 };
1400
1401 let program_counter = Address::<I>::truncate_from_u64(program_counter);
1402 let csr_index = payload as u16;
1403
1404 let error = match tag {
1405 // TODO: Associated constant doesn't compile right now:
1406 // https://github.com/rust-lang/rust/issues/162679
1407 // Self::TAG_STOPPED
1408 0 => {
1409 return ThreadedExecutionResult::stopped(program_counter);
1410 }
1411 // TODO: Associated constant doesn't compile right now:
1412 // https://github.com/rust-lang/rust/issues/162679
1413 // Self::TAG_UNALIGNED_INSTRUCTION
1414 1 => ExecutionError::UnalignedInstruction {
1415 address: PackedAddress::new(Address::<I>::truncate_from_u64(payload)),
1416 },
1417 // TODO: Associated constant doesn't compile right now:
1418 // https://github.com/rust-lang/rust/issues/162679
1419 // Self::TAG_OUT_OF_BOUNDS_READ
1420 2 => ExecutionError::OutOfBoundsRead {
1421 address: PackedAddress::new(payload),
1422 },
1423 // TODO: Associated constant doesn't compile right now:
1424 // https://github.com/rust-lang/rust/issues/162679
1425 // Self::TAG_OUT_OF_BOUNDS_WRITE
1426 3 => ExecutionError::OutOfBoundsWrite {
1427 address: PackedAddress::new(payload),
1428 },
1429 // TODO: Associated constant doesn't compile right now:
1430 // https://github.com/rust-lang/rust/issues/162679
1431 // Self::TAG_MISALIGNED_READ
1432 4 => ExecutionError::MisalignedRead {
1433 address: PackedAddress::new(payload),
1434 },
1435 // TODO: Associated constant doesn't compile right now:
1436 // https://github.com/rust-lang/rust/issues/162679
1437 // Self::TAG_MISALIGNED_WRITE
1438 5 => ExecutionError::MisalignedWrite {
1439 address: PackedAddress::new(payload),
1440 },
1441 // TODO: Associated constant doesn't compile right now:
1442 // https://github.com/rust-lang/rust/issues/162679
1443 // Self::TAG_MISALIGNED_ATOMIC
1444 6 => ExecutionError::MisalignedAtomic {
1445 address: PackedAddress::new(payload),
1446 },
1447 // TODO: Associated constant doesn't compile right now:
1448 // https://github.com/rust-lang/rust/issues/162679
1449 // Self::TAG_ECALL_UNSUPPORTED
1450 7 => ExecutionError::EcallUnsupported {
1451 address: PackedAddress::new(Address::<I>::truncate_from_u64(payload)),
1452 },
1453 // TODO: Associated constant doesn't compile right now:
1454 // https://github.com/rust-lang/rust/issues/162679
1455 // Self::TAG_ILLEGAL_INSTRUCTION
1456 8 => ExecutionError::IllegalInstruction {
1457 address: PackedAddress::new(Address::<I>::truncate_from_u64(payload)),
1458 },
1459 // TODO: Associated constant doesn't compile right now:
1460 // https://github.com/rust-lang/rust/issues/162679
1461 // Self::TAG_CSR_READ_ONLY
1462 9 => ExecutionError::CsrReadOnly { csr_index },
1463 // TODO: Associated constant doesn't compile right now:
1464 // https://github.com/rust-lang/rust/issues/162679
1465 // Self::TAG_CSR_ILLEGAL_READ
1466 10 => ExecutionError::CsrIllegalRead { csr_index },
1467 // TODO: Associated constant doesn't compile right now:
1468 // https://github.com/rust-lang/rust/issues/162679
1469 // Self::TAG_CSR_ILLEGAL_WRITE
1470 11 => ExecutionError::CsrIllegalWrite { csr_index },
1471 // TODO: Associated constant doesn't compile right now:
1472 // https://github.com/rust-lang/rust/issues/162679
1473 // Self::TAG_CSR_UNKNOWN
1474 12 => ExecutionError::CsrUnknown { csr_index },
1475 // TODO: Associated constant doesn't compile right now:
1476 // https://github.com/rust-lang/rust/issues/162679
1477 // Self::TAG_CSR_INSUFFICIENT_PRIVILEGE
1478 13 => {
1479 // SAFETY: `::new()` constructor created this value with `to_bits()`
1480 let required =
1481 unsafe { PrivilegeLevel::from_bits((payload >> 16) as u8).unwrap_unchecked() };
1482 // SAFETY: `::new()` constructor created this value with `to_bits()`
1483 let current =
1484 unsafe { PrivilegeLevel::from_bits((payload >> 24) as u8).unwrap_unchecked() };
1485
1486 ExecutionError::CsrInsufficientPrivilege {
1487 csr_index,
1488 required,
1489 current,
1490 }
1491 }
1492 // TODO: Associated constant doesn't compile right now:
1493 // https://github.com/rust-lang/rust/issues/162679
1494 // Self::TAG_UNSUPPORTED_PLATFORM
1495 14 => ExecutionError::UnsupportedPlatform,
1496 // TODO: Associated constant doesn't compile right now:
1497 // https://github.com/rust-lang/rust/issues/162679
1498 // Self::TAG_CUSTOM
1499 15 => ExecutionError::Custom(payload.to_le_bytes()),
1500 _ => {
1501 // SAFETY: Lanes are private and only ever produced by `new()`, which uses one of
1502 // the tags above
1503 unsafe { unreachable_unchecked() }
1504 }
1505 };
1506
1507 ThreadedExecutionResult::failed(program_counter, error)
1508 }
1509}
1510
1511/// Tail-call-threaded counterpart of [`ExecutableInstruction`].
1512///
1513/// [`ExecutableInstruction::execute()`] describes what a single instruction does and leaves both
1514/// fetching and control flow to a driver loop. This trait instead runs the whole program: it is
1515/// generated as one handler function per instruction variant, each of which executes its own
1516/// instruction and then tail-calls (`become`) the handler of the next one, so there is no loop and
1517/// no return until execution stops. Each handler touches only the operands its own instruction
1518/// names, which is what the shared loop cannot do.
1519///
1520/// Instruction implementations are unaffected: the handlers are assembled from the very same
1521/// `match` arms that [`ExecutableInstruction::execute()`] are assembled from, so both paths execute
1522/// identical logic and a caller picks between them purely on the trade between code size
1523/// (`execute`) and throughput (`execute_threaded`).
1524///
1525/// This trait is deliberately not `const`, unlike [`ExecutableInstruction`]: dispatch goes through
1526/// a table of function pointers, and calls through a function pointer are not allowed in
1527/// `const fn`.
1528pub trait ThreadedExecutableInstruction<Regs, Env, Memory, PC>
1529where
1530 Self: ExecutableInstruction<Regs, Env, Memory, PC>,
1531 PC: InstructionFetcher<Self, Memory>,
1532{
1533 /// Execute instructions starting at the instruction fetcher's current position and continue
1534 /// until execution stops or fails.
1535 ///
1536 /// The instruction fetcher is taken by value rather than behind a reference so that it stays in
1537 /// registers across the whole handler chain.
1538 ///
1539 /// `env` is taken by value for the same reason and one more: an owned value can be a zero-sized
1540 /// type, which occupies no argument register at all, whereas a `&mut` occupies one whether
1541 /// there is anything behind it or not. Most configurations have a stateless environment, which
1542 /// thus vanishes, allowing more registers for other arguments. A configuration that does have a
1543 /// state passes a `&mut` to it (which is an owned value too and for which there are blanket
1544 /// implementations for convenience).
1545 ///
1546 /// When execution fails, the program counter stays where the failure left it:
1547 /// * after a branch whose target was refused, at that target, so calling this again fails the
1548 /// same way
1549 /// * after an instruction that failed, or a jump whose target [`ProgramCounter::set_pc()`]
1550 /// refused, right after that instruction, so calling this again continues with the next one
1551 /// * after a failed fetch, wherever the instruction fetcher left it, which for
1552 /// [`BasicInstructionFetcher`] is the address it couldn't fetch from
1553 ///
1554 /// [`BasicInstructionFetcher`]: basic::BasicInstructionFetcher
1555 fn execute_threaded(
1556 instruction_fetcher: PC,
1557 regs: &mut Regs,
1558 env: Env,
1559 memory: &mut Memory,
1560 ) -> ThreadedExecutionResult<Self>;
1561}