Skip to main content

miden_processor/fast/
mod.rs

1use alloc::{
2    boxed::Box,
3    collections::{BTreeMap, BTreeSet},
4    sync::Arc,
5    vec,
6    vec::Vec,
7};
8use core::{cmp::min, ops::ControlFlow};
9
10use miden_air::{Felt, trace::RowIndex};
11use miden_core::{
12    EMPTY_WORD, WORD_SIZE, Word, ZERO,
13    deferred::{DeferredState, Digest, PrecompileWitness, TRUE_DIGEST},
14    mast::{ExecutableMastForest, MastForest},
15    program::{MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
16    utils::range,
17};
18use miden_mast_package::{
19    Package,
20    debug_info::{DebugSourceNodeId, PackageDebugInfo},
21};
22
23use crate::{
24    AdviceInputs, AdviceProvider, ContextId, ExecutionError, ExecutionOptions, LoadedMastForest,
25    ProcessorState,
26    advice::AdviceError,
27    continuation_stack::{Continuation, ContinuationStack},
28    errors::MapExecErrNoCtx,
29    tracer::{OperationHelperRegisters, Tracer},
30};
31
32mod basic_block;
33mod execution_api;
34mod external;
35mod memory;
36mod operation;
37mod step;
38
39pub use basic_block::SystemEventError;
40pub use memory::Memory;
41pub use step::{BreakReason, ResumeContext};
42
43#[cfg(test)]
44mod tests;
45
46// CONSTANTS
47// ================================================================================================
48
49/// The initial size of the stack buffer.
50///
51/// Note: This value is much larger than it needs to be for the majority of programs. However, some
52/// existing programs need it, so we're forced to push it up (though this should be double-checked).
53/// At this high a value, we're starting to see some performance degradation on benchmarks. For
54/// example, the blake3 benchmark went from 285 MHz to 250 MHz (~10% degradation). Perhaps a better
55/// solution would be to make this value much smaller (~1000), and then fallback to a `Vec` if the
56/// stack overflows.
57const INITIAL_STACK_BUFFER_SIZE: usize = 6850;
58
59/// The initial position of the top of the stack in the stack buffer.
60///
61/// We place this value close to 0 because if a program hits the limit, it's much more likely to hit
62/// the upper bound than the lower bound, since hitting the lower bound only occurs when you drop
63/// 0's that were generated automatically to keep the stack depth at 16. In practice, if this
64/// occurs, it is most likely a bug.
65const INITIAL_STACK_TOP_IDX: usize = 250;
66
67/// Default maximum operand stack depth preserving the previous fixed-buffer ceiling.
68const DEFAULT_MAX_STACK_DEPTH: usize =
69    INITIAL_STACK_BUFFER_SIZE - INITIAL_STACK_TOP_IDX - 1 + MIN_STACK_DEPTH;
70
71const _: [(); 1] =
72    [(); (ExecutionOptions::DEFAULT_MAX_STACK_DEPTH == DEFAULT_MAX_STACK_DEPTH) as usize];
73
74/// The stack buffer index where the logical operand stack starts after reset/recenter.
75const STACK_BUFFER_BASE_IDX: usize = INITIAL_STACK_TOP_IDX - MIN_STACK_DEPTH;
76
77// FAST PROCESSOR
78// ================================================================================================
79
80/// A fast processor which doesn't generate any trace.
81///
82/// This processor is designed to be as fast as possible. Hence, it only keeps track of the current
83/// state of the processor (i.e. the stack, current clock cycle, current memory context, and free
84/// memory pointer).
85///
86/// # Stack Management
87/// A few key points about how the stack was designed for maximum performance:
88///
89/// - The stack starts with a fixed buffer size defined by `INITIAL_STACK_BUFFER_SIZE`.
90///     - This was observed to increase performance by at least 2x compared to using a `Vec` with
91///       `push()` & `pop()`.
92///     - We track the stack top and bottom using indices `stack_top_idx` and `stack_bot_idx`,
93///       respectively.
94/// - Since we are using a fixed-size buffer, we need to ensure that stack buffer accesses are not
95///   out of bounds. Naively, we could check for this on every access. However, every operation
96///   alters the stack depth by a predetermined amount, allowing us to precisely determine the
97///   minimum number of operations required to reach a stack buffer boundary, whether at the top or
98///   bottom.
99///     - For example, if the stack top is 10 elements away from the top boundary, and the stack
100///       bottom is 15 elements away from the bottom boundary, then we can safely execute 10
101///       operations that modify the stack depth with no bounds check.
102/// - When switching contexts (e.g., during a call or syscall), all elements past the first 16 are
103///   stored in `stack_overflow_save_stack`, and the stack is truncated to 16 elements. They will be
104///   restored when returning from the call or syscall.
105///
106/// # Clock Cycle Management
107/// - The clock cycle (`clk`) is managed in the same way as in `Process`. That is, it is incremented
108///   by 1 for every row that `Process` adds to the main trace.
109///     - It is important to do so because the clock cycle is used to determine the context ID for
110///       new execution contexts when using `call` or `dyncall`.
111#[derive(Debug)]
112pub struct FastProcessor {
113    /// The stack is stored in reverse order, so that the last element is at the top of the stack.
114    stack: Box<[Felt]>,
115    /// The index of the top of the stack.
116    stack_top_idx: usize,
117    /// The index of the bottom of the stack.
118    stack_bot_idx: usize,
119
120    /// The current clock cycle.
121    clk: RowIndex,
122
123    /// The current context ID.
124    ctx: ContextId,
125
126    /// The hash of the function that called into the current context, or `[ZERO, ZERO, ZERO,
127    /// ZERO]` if we are in the first context (i.e. when `system_call_state_stack` is empty).
128    caller_hash: Word,
129
130    /// The advice provider to be used during execution.
131    advice: AdviceProvider,
132
133    /// MAST forests loaded during this execution, indexed by their local procedure digests.
134    loaded_mast_forests: BTreeMap<Word, LoadedMastForest>,
135
136    /// Commitments of MAST forests whose advice maps have been merged into the advice provider.
137    merged_mast_forests: BTreeSet<Word>,
138
139    /// A map from (context_id, word_address) to the word stored starting at that memory location.
140    memory: Memory,
141
142    /// Stack of saved system state, used when starting a new execution context (from a `call`,
143    /// `syscall` or `dyncall`) to keep track of the previous `(ctx, caller_hash)` upon return.
144    /// Pushed in lockstep with `stack_overflow_save_stack`.
145    system_call_state_stack: Vec<SystemCallState>,
146
147    /// Stack of saved operand-stack overflows, used when starting a new execution context to keep
148    /// the elements that lived past the top 16 of the previous context. Pushed in lockstep with
149    /// `system_call_state_stack`.
150    stack_overflow_save_stack: Vec<Vec<Felt>>,
151
152    /// Running total of the number of field elements currently held across all suspended overflow
153    /// segments in `stack_overflow_save_stack`. Maintained in lockstep with that stack so the
154    /// aggregate operand-stack depth (active context plus all suspended overflow) can be bounded
155    /// by `ExecutionOptions::max_stack_depth()` in O(1) without summing every saved segment on
156    /// each push. See [`Self::ensure_stack_capacity_for_push`].
157    saved_overflow_len: usize,
158
159    /// Options for execution, including cycle limits, stack limits, advice map limits, and the
160    /// size of core trace fragments during execution.
161    options: ExecutionOptions,
162
163    /// Eager deferred evaluation state retained only while execution is running.
164    deferred_state: DeferredState,
165
166    /// Package debug information configured through [`ProgramExecutor`](crate::ProgramExecutor).
167    pub(crate) package_debug_info: Option<PackageDebugInfo>,
168
169    /// Entrypoint source node configured through [`ProgramExecutor`](crate::ProgramExecutor).
170    pub(crate) entrypoint_source_node: Option<DebugSourceNodeId>,
171}
172
173impl FastProcessor {
174    /// Packages the processor state after successful execution into a public result type.
175    #[inline(always)]
176    fn into_execution_output(self, stack: StackOutputs) -> Result<ExecutionOutput, ExecutionError> {
177        let precompile_witness = self
178            .deferred_state
179            .into_witness()
180            .map_err(|_| ExecutionError::Internal("failed to export deferred execution witness"))?;
181        Ok(ExecutionOutput {
182            stack,
183            advice: self.advice,
184            memory: self.memory,
185            precompile_witness,
186        })
187    }
188
189    /// Converts the terminal result of a full execution run into [`ExecutionOutput`].
190    #[inline(always)]
191    fn execution_result_from_flow(
192        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
193        processor: Self,
194    ) -> Result<ExecutionOutput, ExecutionError> {
195        match flow {
196            ControlFlow::Continue(stack_outputs) => processor.into_execution_output(stack_outputs),
197            ControlFlow::Break(break_reason) => match break_reason {
198                BreakReason::Err(err) => Err(err),
199                BreakReason::Stopped(_) => {
200                    unreachable!("Execution never stops prematurely with NeverStopper")
201                },
202            },
203        }
204    }
205
206    /// Converts a testing-only execution result into stack outputs.
207    #[cfg(any(test, feature = "testing"))]
208    #[inline(always)]
209    fn stack_result_from_flow(
210        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
211    ) -> Result<StackOutputs, ExecutionError> {
212        match flow {
213            ControlFlow::Continue(stack_outputs) => Ok(stack_outputs),
214            ControlFlow::Break(break_reason) => match break_reason {
215                BreakReason::Err(err) => Err(err),
216                BreakReason::Stopped(_) => {
217                    unreachable!("Execution never stops prematurely with NeverStopper")
218                },
219            },
220        }
221    }
222
223    // CONSTRUCTORS
224    // ----------------------------------------------------------------------------------------------
225
226    /// Creates a new `FastProcessor` instance with the given stack inputs.
227    ///
228    /// By default, advice inputs are empty and execution options use their defaults.
229    ///
230    /// # Example
231    /// ```ignore
232    /// use miden_processor::FastProcessor;
233    ///
234    /// let processor = FastProcessor::new(stack_inputs)
235    ///     .with_advice(advice_inputs)
236    ///     .expect("advice inputs should fit advice map limits");
237    /// ```
238    ///
239    /// When using non-default advice map limits, prefer [`Self::new_with_options`] so the advice
240    /// inputs are validated against the intended execution options.
241    pub fn new(stack_inputs: StackInputs) -> Self {
242        Self::new_with_options(stack_inputs, AdviceInputs::default(), ExecutionOptions::default())
243            .expect("default processor initialization should fit default execution limits")
244    }
245
246    /// Sets the advice inputs for the processor.
247    ///
248    /// Advice inputs are loaded into the live advice provider immediately and are validated against
249    /// the processor's current [`ExecutionOptions`]. If the advice map needs non-default limits,
250    /// construct the processor with [`Self::new_with_options`] or call [`Self::with_options`]
251    /// before calling this method.
252    pub fn with_advice(mut self, advice_inputs: AdviceInputs) -> Result<Self, AdviceError> {
253        self.advice = AdviceProvider::new(advice_inputs, &self.options)?;
254        Ok(self)
255    }
256
257    /// Sets the execution options for the processor.
258    ///
259    /// Existing advice inputs are revalidated against the new options before they are applied. To
260    /// load advice inputs that require non-default advice map limits, call this before
261    /// [`Self::with_advice`] or use [`Self::new_with_options`]. The installed precompile registry
262    /// and any accumulated deferred state are preserved.
263    pub fn with_options(mut self, options: ExecutionOptions) -> Result<Self, AdviceError> {
264        self.advice.set_options(&options)?;
265        self.memory.set_max_elements(options.max_memory_elements());
266        self.options = options;
267        Ok(self)
268    }
269
270    /// Constructor for creating a `FastProcessor` with all options specified at once.
271    ///
272    /// For a more fluent API, consider using `FastProcessor::new()` with builder methods.
273    pub fn new_with_options(
274        stack_inputs: StackInputs,
275        advice_inputs: AdviceInputs,
276        options: ExecutionOptions,
277    ) -> Result<Self, AdviceError> {
278        let stack_top_idx = INITIAL_STACK_TOP_IDX;
279        let stack = {
280            // Note: we use `Vec::into_boxed_slice()` here, since `Box::new([T; N])` first allocates
281            // the array on the stack, and then moves it to the heap. This might cause a
282            // stack overflow on some systems.
283            let mut stack = vec![ZERO; INITIAL_STACK_BUFFER_SIZE].into_boxed_slice();
284
285            // Copy inputs in reverse order so first element ends up at top of stack
286            for (i, &input) in stack_inputs.iter().enumerate() {
287                stack[stack_top_idx - 1 - i] = input;
288            }
289            stack
290        };
291
292        Ok(Self {
293            advice: AdviceProvider::new(advice_inputs, &options)?,
294            loaded_mast_forests: BTreeMap::new(),
295            merged_mast_forests: BTreeSet::new(),
296            stack,
297            stack_top_idx,
298            stack_bot_idx: stack_top_idx - MIN_STACK_DEPTH,
299            clk: 0_u32.into(),
300            ctx: 0_u32.into(),
301            caller_hash: EMPTY_WORD,
302            memory: Memory::new(options.max_memory_elements()),
303            system_call_state_stack: Vec::new(),
304            stack_overflow_save_stack: Vec::new(),
305            saved_overflow_len: 0,
306            deferred_state: DeferredState::new(Arc::new(miden_precompiles::registry()))
307                .map_err(AdviceError::DeferredStateInitializationFailed)?,
308            package_debug_info: None,
309            entrypoint_source_node: None,
310            options,
311        })
312    }
313
314    /// Returns the resume context to be used with the first call to `step_sync()`.
315    ///
316    /// This function asserts that `package` is of executable type - callers should ensure that it
317    /// is before calling.
318    pub fn get_initial_resume_context_for_package(
319        &mut self,
320        package: Arc<Package>,
321    ) -> Result<ResumeContext, ExecutionError> {
322        let program = package.unwrap_program();
323        let package_debug_info = package.debug_info()?.map(Arc::new);
324        let current_forest = program.mast_forest().clone();
325        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
326
327        let entrypoint_source_node_id = package.entrypoint_source_node();
328        let continuation_stack = if let Some(debug_info) = package_debug_info.as_deref() {
329            Self::source_aware_continuation_stack(&program, debug_info, entrypoint_source_node_id)?
330        } else {
331            ContinuationStack::new(&program)
332        };
333
334        Ok(ResumeContext {
335            current_forest,
336            continuation_stack,
337            kernel: program.kernel().clone(),
338            package_debug_info,
339            inline_call_contexts: Vec::new(),
340        })
341    }
342
343    /// Returns the resume context to be used with the first call to `step_sync()`.
344    pub fn get_initial_resume_context(
345        &mut self,
346        program: &Program,
347    ) -> Result<ResumeContext, ExecutionError> {
348        self.advice
349            .extend_map(program.mast_forest().advice_map())
350            .map_exec_err_no_ctx()?;
351
352        Ok(ResumeContext {
353            current_forest: program.mast_forest().clone(),
354            continuation_stack: ContinuationStack::new(program),
355            kernel: program.kernel().clone(),
356            package_debug_info: None,
357            inline_call_contexts: Vec::new(),
358        })
359    }
360
361    // ACCESSORS
362    // -------------------------------------------------------------------------------------------
363
364    /// Returns the deferred witness accumulated during execution.
365    #[inline(always)]
366    pub fn deferred_state(&self) -> &DeferredState {
367        &self.deferred_state
368    }
369
370    #[inline(always)]
371    pub(super) fn deferred_state_mut(&mut self) -> &mut DeferredState {
372        &mut self.deferred_state
373    }
374
375    /// Returns the size of the stack.
376    #[inline(always)]
377    fn stack_size(&self) -> usize {
378        self.stack_top_idx - self.stack_bot_idx
379    }
380
381    /// Returns the stack, such that the top of the stack is at the last index of the returned
382    /// slice.
383    pub fn stack(&self) -> &[Felt] {
384        &self.stack[self.stack_bot_idx..self.stack_top_idx]
385    }
386
387    /// Returns the top 16 elements of the stack.
388    pub fn stack_top(&self) -> &[Felt] {
389        &self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
390    }
391
392    /// Returns a mutable reference to the top 16 elements of the stack.
393    pub fn stack_top_mut(&mut self) -> &mut [Felt] {
394        &mut self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
395    }
396
397    /// Returns the element on the stack at index `idx`.
398    ///
399    /// This method is only meant to be used to access the stack top by operation handlers, and
400    /// system event handlers.
401    ///
402    /// # Preconditions
403    /// - `idx` must be less than or equal to 15.
404    #[inline(always)]
405    pub fn stack_get(&self, idx: usize) -> Felt {
406        self.stack[self.stack_top_idx - idx - 1]
407    }
408
409    /// Same as [`Self::stack_get()`], but returns [`ZERO`] if `idx` falls below index 0 in the
410    /// stack buffer.
411    ///
412    /// Use this instead of `stack_get()` when `idx` may exceed 15.
413    #[inline(always)]
414    pub fn stack_get_safe(&self, idx: usize) -> Felt {
415        if idx < self.stack_top_idx {
416            self.stack[self.stack_top_idx - idx - 1]
417        } else {
418            ZERO
419        }
420    }
421
422    /// Mutable variant of `stack_get()`.
423    ///
424    /// This method is only meant to be used to access the stack top by operation handlers, and
425    /// system event handlers.
426    ///
427    /// # Preconditions
428    /// - `idx` must be less than or equal to 15.
429    #[inline(always)]
430    pub fn stack_get_mut(&mut self, idx: usize) -> &mut Felt {
431        &mut self.stack[self.stack_top_idx - idx - 1]
432    }
433
434    /// Returns the word on the stack starting at index `start_idx` in "stack order".
435    ///
436    /// For `start_idx=0` the top element of the stack will be at position 0 in the word.
437    ///
438    /// For example, if the stack looks like this:
439    ///
440    /// top                                                       bottom
441    /// v                                                           v
442    /// a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p
443    ///
444    /// Then
445    /// - `stack_get_word(0)` returns `[a, b, c, d]`,
446    /// - `stack_get_word(1)` returns `[b, c, d, e]`,
447    /// - etc.
448    ///
449    /// This method is only meant to be used to access the stack top by operation handlers, and
450    /// system event handlers.
451    ///
452    /// # Preconditions
453    /// - `start_idx` must be less than or equal to 12.
454    #[inline(always)]
455    pub fn stack_get_word(&self, start_idx: usize) -> Word {
456        // Ensure we have enough elements to form a complete word
457        debug_assert!(
458            start_idx + WORD_SIZE <= self.stack_depth() as usize,
459            "Not enough elements on stack to read word starting at index {start_idx}"
460        );
461
462        let word_start_idx = self.stack_top_idx - start_idx - WORD_SIZE;
463        let mut result: [Felt; WORD_SIZE] =
464            self.stack[range(word_start_idx, WORD_SIZE)].try_into().unwrap();
465        // Reverse so top of stack (idx 0) goes to word[0]
466        result.reverse();
467        result.into()
468    }
469
470    /// Same as [`Self::stack_get_word()`], but returns [`ZERO`] for any element that falls below
471    /// index 0 in the stack buffer.
472    ///
473    /// Use this instead of `stack_get_word()` when `start_idx + WORD_SIZE` may exceed
474    /// `stack_top_idx`.
475    #[inline(always)]
476    pub fn stack_get_word_safe(&self, start_idx: usize) -> Word {
477        let buf_end = self.stack_top_idx.saturating_sub(start_idx);
478        let buf_start = self.stack_top_idx.saturating_sub(start_idx.saturating_add(WORD_SIZE));
479        let num_elements_to_read_from_buf = buf_end - buf_start;
480
481        let mut result = [ZERO; WORD_SIZE];
482        if num_elements_to_read_from_buf == WORD_SIZE {
483            result.copy_from_slice(&self.stack[range(buf_start, WORD_SIZE)]);
484        } else if num_elements_to_read_from_buf > 0 {
485            let offset = WORD_SIZE - num_elements_to_read_from_buf;
486            result[offset..]
487                .copy_from_slice(&self.stack[range(buf_start, num_elements_to_read_from_buf)]);
488        }
489        result.reverse();
490
491        result.into()
492    }
493
494    /// Returns the number of elements on the stack in the current context.
495    #[inline(always)]
496    pub fn stack_depth(&self) -> u32 {
497        (self.stack_top_idx - self.stack_bot_idx) as u32
498    }
499
500    /// Returns a reference to the processor's memory.
501    pub fn memory(&self) -> &Memory {
502        &self.memory
503    }
504
505    /// Consumes the processor and returns the advice provider and memory.
506    pub fn into_parts(self) -> (AdviceProvider, Memory) {
507        (self.advice, self.memory)
508    }
509
510    /// Returns a reference to the execution options.
511    pub fn execution_options(&self) -> &ExecutionOptions {
512        &self.options
513    }
514
515    /// Returns a narrowed interface for reading and updating the processor state.
516    #[inline(always)]
517    pub fn state(&self) -> ProcessorState<'_> {
518        ProcessorState { processor: self }
519    }
520
521    // MUTATORS
522    // -------------------------------------------------------------------------------------------
523
524    /// Writes an element to the stack at the given index.
525    #[inline(always)]
526    pub fn stack_write(&mut self, idx: usize, element: Felt) {
527        self.stack[self.stack_top_idx - idx - 1] = element
528    }
529
530    /// Writes a word to the stack starting at the given index.
531    ///
532    /// `word[0]` goes to stack position start_idx (top), `word[1]` to start_idx+1, etc.
533    #[inline(always)]
534    pub fn stack_write_word(&mut self, start_idx: usize, word: &Word) {
535        debug_assert!(start_idx <= MIN_STACK_DEPTH - WORD_SIZE);
536
537        let word_start_idx = self.stack_top_idx - start_idx - 4;
538        let mut source: [Felt; WORD_SIZE] = (*word).into();
539        // Reverse so word[0] ends up at the top of stack (highest internal index)
540        source.reverse();
541        self.stack[range(word_start_idx, WORD_SIZE)].copy_from_slice(&source)
542    }
543
544    /// Swaps the elements at the given indices on the stack.
545    #[inline(always)]
546    pub fn stack_swap(&mut self, idx1: usize, idx2: usize) {
547        let a = self.stack_get(idx1);
548        let b = self.stack_get(idx2);
549        self.stack_write(idx1, b);
550        self.stack_write(idx2, a);
551    }
552
553    /// Increments the stack top pointer by 1.
554    ///
555    /// The bottom of the stack is never affected by this operation.
556    #[inline(always)]
557    fn increment_stack_size(&mut self) {
558        self.stack_top_idx += 1;
559    }
560
561    /// Ensures the internal stack storage can accommodate one additional logical stack element.
562    ///
563    /// The operand stack depth limit is the semantic resource bound; the buffer is only an
564    /// implementation detail. We therefore check the logical depth before allocating so a program
565    /// cannot force memory growth beyond `ExecutionOptions::max_stack_depth()`. When storage does
566    /// need to grow, it grows geometrically and remains heap-allocated as a boxed slice. A
567    /// `SmallVec` would put a useful inline buffer inside `FastProcessor`, and preallocating the
568    /// full limit would penalize ordinary programs. This policy is performance-sensitive and should
569    /// be benchmarked against the fixed-buffer baseline.
570    ///
571    /// The depth that is checked is the *aggregate* operand-stack depth: the active context's depth
572    /// plus every element held in suspended overflow segments (`saved_overflow_len`). A `call`,
573    /// `dyncall`, or `syscall` context switch hides the caller's overflow in
574    /// `stack_overflow_save_stack` rather than freeing it, so checking only the active context
575    /// would let a program nest context switches to accumulate `O(call_depth *
576    /// max_stack_depth)` hidden operand-stack memory while every live frame stayed within the
577    /// limit. Because a context switch merely moves elements between the active stack and the
578    /// saved overflow (it never creates elements), the aggregate is conserved across switches
579    /// and only grows on a push, so enforcing the bound here is sufficient to cap total
580    /// operand-stack memory.
581    #[inline(always)]
582    fn ensure_stack_capacity_for_push(&mut self) -> Result<(), ExecutionError> {
583        let depth = self.stack_size() + self.saved_overflow_len + 1;
584        let max = self.options.max_stack_depth();
585        if depth > max {
586            return Err(ExecutionError::StackDepthLimitExceeded { depth, max });
587        }
588
589        if self.stack_top_idx >= self.stack.len() - 1 {
590            self.grow_stack_buffer(self.stack_top_idx + 2);
591        }
592
593        Ok(())
594    }
595
596    fn ensure_stack_capacity_for_top_idx(&mut self, top_idx: usize) {
597        if top_idx >= self.stack.len() {
598            self.grow_stack_buffer(top_idx + 1);
599        }
600    }
601
602    fn grow_stack_buffer(&mut self, requested_min_len: usize) {
603        // The maximum allocation is tied to the logical operand stack depth, not to the current
604        // buffer position. Using `stack_bot_idx` here would make the allocation ceiling drift when
605        // the live stack has moved away from the initial base.
606        let max_len = STACK_BUFFER_BASE_IDX
607            .saturating_add(self.options.max_stack_depth())
608            .saturating_add(1);
609        let live_len = self.stack_size();
610
611        // Growth also recenters the live stack at the normal base. This keeps future push/drop
612        // behavior close to the fixed-buffer layout and avoids carrying unused prefix cells into
613        // the new allocation. The extra slot is for the next checked push that triggered growth.
614        let recentered_min_len = STACK_BUFFER_BASE_IDX.saturating_add(live_len).saturating_add(2);
615        debug_assert!(recentered_min_len <= max_len);
616
617        // Allocation growth is based on the stack's post-recentered live range, not the previous
618        // buffer length. The `requested_min_len` may be beyond the allocation cap when a shallow
619        // context is still positioned near the end of the old buffer; recentering the live stack is
620        // what makes that valid. The VM-visible requirements are that the live stack is restored at
621        // `STACK_BUFFER_BASE_IDX`, the post-recentered push slot is available, and allocation stays
622        // capped by the configured stack depth. The allocation size can differ from the previous
623        // doubling policy: normal push growth may allocate a couple of extra cells because of the
624        // spare push slot, while restoring a deep caller from a shallow callee may allocate only
625        // the requested restored range instead of doubling the old buffer. That smaller
626        // restore allocation is intentional, but it means future pushes can grow again
627        // sooner and should stay covered by benchmarks.
628        let new_len = recentered_min_len.saturating_mul(2).max(requested_min_len).min(max_len);
629        debug_assert!(new_len <= max_len);
630
631        let mut new_stack = vec![ZERO; new_len].into_boxed_slice();
632        let new_stack_bot_idx = STACK_BUFFER_BASE_IDX;
633        let new_stack_top_idx = new_stack_bot_idx + live_len;
634
635        // Only the active stack range carries VM state. Prefix/suffix cells are scratch storage and
636        // stay zeroed, which keeps growth proportional to the live depth instead of the old buffer
637        // length.
638        new_stack[new_stack_bot_idx..new_stack_top_idx]
639            .copy_from_slice(&self.stack[self.stack_bot_idx..self.stack_top_idx]);
640
641        self.stack = new_stack;
642        self.stack_bot_idx = new_stack_bot_idx;
643        self.stack_top_idx = new_stack_top_idx;
644    }
645
646    /// Decrements the stack top pointer by 1.
647    ///
648    /// The bottom of the stack is only decremented in cases where the stack depth would become less
649    /// than 16.
650    #[inline(always)]
651    fn decrement_stack_size(&mut self) {
652        if self.stack_top_idx == MIN_STACK_DEPTH {
653            // We no longer have any room in the stack buffer to decrement the stack size (which
654            // would cause the `stack_bot_idx` to go below 0). We therefore reset the stack to its
655            // original position.
656            self.reset_stack_in_buffer(INITIAL_STACK_TOP_IDX);
657        }
658
659        self.stack_top_idx -= 1;
660        self.stack_bot_idx = min(self.stack_bot_idx, self.stack_top_idx - MIN_STACK_DEPTH);
661    }
662
663    /// Resets the stack in the buffer to a new position, preserving the top 16 elements of the
664    /// stack.
665    ///
666    /// # Preconditions
667    /// - The stack is expected to have exactly 16 elements.
668    #[inline(always)]
669    fn reset_stack_in_buffer(&mut self, new_stack_top_idx: usize) {
670        debug_assert_eq!(self.stack_depth(), MIN_STACK_DEPTH as u32);
671
672        let new_stack_bot_idx = new_stack_top_idx - MIN_STACK_DEPTH;
673
674        // Copy stack to its new position
675        self.stack
676            .copy_within(self.stack_bot_idx..self.stack_top_idx, new_stack_bot_idx);
677
678        // Zero out stack below the new new_stack_bot_idx, since this is where overflow values
679        // come from, and are guaranteed to be ZERO. We don't need to zero out above
680        // `stack_top_idx`, since values there are never read before being written.
681        self.stack[0..new_stack_bot_idx].fill(ZERO);
682
683        // Update indices.
684        self.stack_bot_idx = new_stack_bot_idx;
685        self.stack_top_idx = new_stack_top_idx;
686    }
687}
688
689// EXECUTION OUTPUT
690// ===============================================================================================
691
692/// The output of a program execution, containing the state of the stack, advice provider, memory,
693/// and optional portable precompile witness at the end of execution.
694#[derive(Debug)]
695pub struct ExecutionOutput {
696    pub stack: StackOutputs,
697    pub advice: AdviceProvider,
698    pub memory: Memory,
699    pub precompile_witness: Option<PrecompileWitness>,
700}
701
702impl ExecutionOutput {
703    /// Returns the carried deferred root, or TRUE when no witness is present.
704    ///
705    /// This does not validate the witness's precompile computations.
706    pub fn precompile_root(&self) -> Digest {
707        self.precompile_witness
708            .as_ref()
709            .map_or(TRUE_DIGEST, PrecompileWitness::root_unchecked)
710    }
711}
712
713// SYSTEM CALL STATE
714// ===============================================================================================
715
716/// The system-state half of a saved execution context.
717///
718/// Used to keep track of the `(ctx, caller_hash)` pair that needs to be restored upon return from a
719/// `call`, `syscall` or `dyncall`.
720#[derive(Debug)]
721pub(super) struct SystemCallState {
722    pub ctx: ContextId,
723    pub caller_hash: Word,
724}
725
726// NOOP TRACER
727// ================================================================================================
728
729/// A [Tracer] that does nothing.
730pub struct NoopTracer;
731
732impl Tracer for NoopTracer {
733    type Processor = FastProcessor;
734    type Forest = Arc<MastForest>;
735
736    #[inline(always)]
737    fn start_clock_cycle(
738        &mut self,
739        _processor: &FastProcessor,
740        _continuation: Continuation<Arc<MastForest>>,
741        _continuation_stack: &ContinuationStack<Arc<MastForest>>,
742        _current_forest: &Arc<MastForest>,
743    ) {
744        // do nothing
745    }
746
747    #[inline(always)]
748    fn finalize_clock_cycle(
749        &mut self,
750        _processor: &FastProcessor,
751        _op_helper_registers: OperationHelperRegisters,
752        _current_forest: &Arc<MastForest>,
753    ) -> Result<(), ExecutionError> {
754        // do nothing
755        Ok(())
756    }
757}